1 /* Copyright (C) 2001-2006 Artifex Software, Inc.
2    All Rights Reserved.
3 
4    This software is provided AS-IS with no warranty, either express or
5    implied.
6 
7    This software is distributed under license and may not be copied, modified
8    or distributed except as expressly authorized under the terms of that
9    license.  Refer to licensing information at http://www.artifex.com/
10    or contact Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134,
11    San Rafael, CA  94903, U.S.A., +1(415)492-9861, for further information.
12 */
13 
14 /* $Id: stream.c 10257 2009-11-02 17:36:56Z alexcher $ */
15 /* Stream package for Ghostscript interpreter */
16 #include "stdio_.h"		/* includes std.h */
17 #include "memory_.h"
18 #include "gdebug.h"
19 #include "gpcheck.h"
20 #include "stream.h"
21 #include "strimpl.h"
22 
23 /* Forward declarations */
24 int s_close_disable(stream *);
25 static int sreadbuf(stream *, stream_cursor_write *);
26 static int swritebuf(stream *, stream_cursor_read *, bool);
27 static void stream_compact(stream *, bool);
28 
29 /* Structure types for allocating streams. */
30 public_st_stream();
31 public_st_stream_state();	/* default */
32 /* GC procedures */
33 static
34 ENUM_PTRS_WITH(stream_enum_ptrs, stream *st) return 0;
35 case 0:
36 if (st->foreign)
37     ENUM_RETURN(NULL);
38 else if (st->cbuf_string.data != 0)
39     ENUM_RETURN_STRING_PTR(stream, cbuf_string);
40 else
41     ENUM_RETURN(st->cbuf);
42 ENUM_PTR3(1, stream, strm, prev, next);
43 ENUM_PTR(4, stream, state);
44 case 5: return ENUM_CONST_STRING(&st->file_name);
45 ENUM_PTRS_END
RELOC_PTRS_WITH(stream_reloc_ptrs,stream * st)46 static RELOC_PTRS_WITH(stream_reloc_ptrs, stream *st)
47 {
48     byte *cbuf_old = st->cbuf;
49 
50     if (cbuf_old != 0 && !st->foreign) {
51 	long reloc;
52 
53 	if (st->cbuf_string.data != 0) {
54 	    RELOC_STRING_VAR(st->cbuf_string);
55 	    st->cbuf = st->cbuf_string.data;
56 	} else
57 	    RELOC_VAR(st->cbuf);
58 	reloc = cbuf_old - st->cbuf;
59 	/* Relocate the other buffer pointers. */
60 	st->srptr -= reloc;
61 	st->srlimit -= reloc;	/* same as swptr */
62 	st->swlimit -= reloc;
63     }
64     RELOC_VAR(st->strm);
65     RELOC_VAR(st->prev);
66     RELOC_VAR(st->next);
67     RELOC_VAR(st->state);
68     RELOC_CONST_STRING_VAR(st->file_name);
69 }
70 RELOC_PTRS_END
71 /* Finalize a stream by closing it. */
72 /* We only do this for file streams, because other kinds of streams */
73 /* may attempt to free storage when closing. */
74 static void
stream_finalize(void * vptr)75 stream_finalize(void *vptr)
76 {
77     stream *const st = vptr;
78 
79     if_debug2('u', "[u]%s 0x%lx\n",
80 	      (!s_is_valid(st) ? "already closed:" :
81 	       st->is_temp ? "is_temp set:" :
82 	       st->file == 0 ? "not file:" :
83 	       "closing file:"), (ulong) st);
84     if (s_is_valid(st) && !st->is_temp && st->file != 0) {
85 	/* Prevent any attempt to free the buffer. */
86 	st->cbuf = 0;
87 	st->cbuf_string.data = 0;
88 	sclose(st);		/* ignore errors */
89     }
90 }
91 
92 /* Dummy template for streams that don't have a separate state. */
93 static const stream_template s_no_template = {
94     &st_stream_state, 0, 0, 1, 1, 0
95 };
96 
97 /* ------ Generic procedures ------ */
98 
99 /* Allocate a stream and initialize it minimally. */
100 void
s_init(stream * s,gs_memory_t * mem)101 s_init(stream *s, gs_memory_t * mem)
102 {
103     s->memory = mem;
104     s->report_error = s_no_report_error;
105     s->min_left = 0;
106     s->error_string[0] = 0;
107     s->prev = s->next = 0;	/* clean for GC */
108     s->file_name.data = 0;	/* ibid. */
109     s->file_name.size = 0;
110     s->close_strm = false;	/* default */
111     s->close_at_eod = true;	/* default */
112 }
113 stream *
s_alloc(gs_memory_t * mem,client_name_t cname)114 s_alloc(gs_memory_t * mem, client_name_t cname)
115 {
116     stream *s = gs_alloc_struct(mem, stream, &st_stream, cname);
117 
118     if_debug2('s', "[s]alloc(%s) = 0x%lx\n",
119 	      client_name_string(cname), (ulong) s);
120     if (s == 0)
121 	return 0;
122     s_init(s, mem);
123     return s;
124 }
125 
126 /* Allocate a stream state and initialize it minimally. */
127 void
s_init_state(stream_state * st,const stream_template * template,gs_memory_t * mem)128 s_init_state(stream_state *st, const stream_template *template,
129 	     gs_memory_t *mem)
130 {
131     st->template = template;
132     st->memory = mem;
133     st->report_error = s_no_report_error;
134     st->min_left = 0;
135     st->error_string[0] = 0;
136 }
137 stream_state *
s_alloc_state(gs_memory_t * mem,gs_memory_type_ptr_t stype,client_name_t cname)138 s_alloc_state(gs_memory_t * mem, gs_memory_type_ptr_t stype,
139 	      client_name_t cname)
140 {
141     stream_state *st = gs_alloc_struct(mem, stream_state, stype, cname);
142 
143     if_debug3('s', "[s]alloc_state %s(%s) = 0x%lx\n",
144 	      client_name_string(cname),
145 	      client_name_string(stype->sname),
146 	      (ulong) st);
147     if (st)
148 	s_init_state(st, NULL, mem);
149     return st;
150 }
151 
152 /* Standard stream initialization */
153 void
s_std_init(register stream * s,byte * ptr,uint len,const stream_procs * pp,int modes)154 s_std_init(register stream * s, byte * ptr, uint len, const stream_procs * pp,
155 	   int modes)
156 {
157     s->template = &s_no_template;
158     s->cbuf = ptr;
159     s->srptr = s->srlimit = s->swptr = ptr - 1;
160     s->swlimit = ptr - 1 + len;
161     s->end_status = 0;
162     s->foreign = 0;
163     s->modes = modes;
164     s->cbuf_string.data = 0;
165     s->position = 0;
166     s->bsize = s->cbsize = len;
167     s->strm = 0;		/* not a filter */
168     s->is_temp = 0;
169     s->procs = *pp;
170     s->state = (stream_state *) s;	/* hack to avoid separate state */
171     s->file = 0;
172     s->file_name.data = 0;	/* in case stream is on stack */
173     s->file_name.size = 0;
174     if_debug4('s', "[s]init 0x%lx, buf=0x%lx, len=%u, modes=%d\n",
175 	      (ulong) s, (ulong) ptr, len, modes);
176 }
177 
178 
179 /* Set the file name of a stream, copying the name. */
180 /* Return <0 if the copy could not be allocated. */
181 int
ssetfilename(stream * s,const byte * data,uint size)182 ssetfilename(stream *s, const byte *data, uint size)
183 {
184     byte *str =
185 	(s->file_name.data == 0 ?
186 	 gs_alloc_string(s->memory, size + 1, "ssetfilename") :
187 	 gs_resize_string(s->memory,
188 			  (byte *)s->file_name.data,	/* break const */
189 			  s->file_name.size,
190 			  size + 1, "ssetfilename"));
191 
192     if (str == 0)
193 	return -1;
194     memcpy(str, data, size);
195     str[size] = 0;
196     s->file_name.data = str;
197     s->file_name.size = size + 1;
198     return 0;
199 }
200 
201 /* Return the file name of a stream, if any. */
202 /* There is a guaranteed 0 byte after the string. */
203 int
sfilename(stream * s,gs_const_string * pfname)204 sfilename(stream *s, gs_const_string *pfname)
205 {
206     pfname->data = s->file_name.data;
207     if (pfname->data == 0) {
208 	pfname->size = 0;
209 	return -1;
210     }
211     pfname->size = s->file_name.size - 1; /* omit terminator */
212     return 0;
213 }
214 
215 /* Implement a stream procedure as a no-op. */
216 int
s_std_null(stream * s)217 s_std_null(stream * s)
218 {
219     return 0;
220 }
221 
222 /* Discard the contents of the buffer when reading. */
223 void
s_std_read_reset(stream * s)224 s_std_read_reset(stream * s)
225 {
226     s->srptr = s->srlimit = s->cbuf - 1;
227 }
228 
229 /* Discard the contents of the buffer when writing. */
230 void
s_std_write_reset(stream * s)231 s_std_write_reset(stream * s)
232 {
233     s->swptr = s->cbuf - 1;
234 }
235 
236 /* Flush data to end-of-file when reading. */
237 int
s_std_read_flush(stream * s)238 s_std_read_flush(stream * s)
239 {
240     while (1) {
241 	s->srptr = s->srlimit = s->cbuf - 1;
242 	if (s->end_status)
243 	    break;
244 	s_process_read_buf(s);
245     }
246     return (s->end_status == EOFC ? 0 : s->end_status);
247 }
248 
249 /* Flush buffered data when writing. */
250 int
s_std_write_flush(stream * s)251 s_std_write_flush(stream * s)
252 {
253     return s_process_write_buf(s, false);
254 }
255 
256 /* Indicate that the number of available input bytes is unknown. */
257 int
s_std_noavailable(stream * s,long * pl)258 s_std_noavailable(stream * s, long *pl)
259 {
260     *pl = -1;
261     return 0;
262 }
263 
264 /* Indicate an error when asked to seek. */
265 int
s_std_noseek(stream * s,long pos)266 s_std_noseek(stream * s, long pos)
267 {
268     return ERRC;
269 }
270 
271 /* Standard stream closing. */
272 int
s_std_close(stream * s)273 s_std_close(stream * s)
274 {
275     return 0;
276 }
277 
278 /* Standard stream mode switching. */
279 int
s_std_switch_mode(stream * s,bool writing)280 s_std_switch_mode(stream * s, bool writing)
281 {
282     return ERRC;
283 }
284 
285 /* Standard stream finalization.  Disable the stream. */
286 void
s_disable(register stream * s)287 s_disable(register stream * s)
288 {
289     s->cbuf = 0;
290     s->bsize = 0;
291     s->end_status = EOFC;
292     s->modes = 0;
293     s->cbuf_string.data = 0;
294     /* The pointers in the next two statements should really be */
295     /* initialized to ([const] byte *)0 - 1, but some very picky */
296     /* compilers complain about this. */
297     s->cursor.r.ptr = s->cursor.r.limit = 0;
298     s->cursor.w.limit = 0;
299     s->procs.close = s_std_null;
300     /* Clear pointers for GC */
301     s->strm = 0;
302     s->state = (stream_state *) s;
303     s->template = &s_no_template;
304     /* Free the file name. */
305     if (s->file_name.data) {
306 	gs_free_const_string(s->memory, s->file_name.data, s->file_name.size,
307 			     "s_disable(file_name)");
308 	s->file_name.data = 0;
309 	s->file_name.size = 0;
310     }
311     /****** SHOULD DO MORE THAN THIS ******/
312     if_debug1('s', "[s]disable 0x%lx\n", (ulong) s);
313 }
314 
315 /* Implement flushing for encoding filters. */
316 int
s_filter_write_flush(register stream * s)317 s_filter_write_flush(register stream * s)
318 {
319     int status = s_process_write_buf(s, false);
320 
321     if (status != 0)
322 	return status;
323     return sflush(s->strm);
324 }
325 
326 /* Close a filter.  If this is an encoding filter, flush it first. */
327 /* If CloseTarget was specified (close_strm), then propagate the sclose */
328 int
s_filter_close(register stream * s)329 s_filter_close(register stream * s)
330 {
331     int status;
332     bool close = s->close_strm;
333     stream *stemp = s->strm;
334 
335     if (s_is_writing(s)) {
336 	int status = s_process_write_buf(s, true);
337 
338 	if (status != 0 && status != EOFC)
339 	    return status;
340         status = sflush(stemp);
341 	if (status != 0 && status != EOFC)
342 	    return status;
343     }
344     status = s_std_close(s);
345     if (status != 0 && status != EOFC)
346 	return status;
347     if (close && stemp != 0)
348 	return sclose(stemp);
349     return status;
350 }
351 
352 /* Disregard a stream error message. */
353 int
s_no_report_error(stream_state * st,const char * str)354 s_no_report_error(stream_state * st, const char *str)
355 {
356     return 0;
357 }
358 
359 /* Generic procedure structures for filters. */
360 
361 const stream_procs s_filter_read_procs = {
362     s_std_noavailable, s_std_noseek, s_std_read_reset,
363     s_std_read_flush, s_filter_close
364 };
365 
366 const stream_procs s_filter_write_procs = {
367     s_std_noavailable, s_std_noseek, s_std_write_reset,
368     s_filter_write_flush, s_filter_close
369 };
370 
371 /* ------ Implementation-independent procedures ------ */
372 
373 /* Store the amount of available data in a(n input) stream. */
374 int
savailable(stream * s,long * pl)375 savailable(stream * s, long *pl)
376 {
377     return (*(s)->procs.available) (s, pl);
378 }
379 
380 /* Return the current position of a stream. */
381 long
stell(stream * s)382 stell(stream * s)
383 {
384     /*
385      * The stream might have been closed, but the position
386      * is still meaningful in this case.
387      */
388     const byte *ptr = (s_is_writing(s) ? s->swptr : s->srptr);
389 
390     return (ptr == 0 ? 0 : ptr + 1 - s->cbuf) + s->position;
391 }
392 
393 /* Set the position of a stream. */
394 int
spseek(stream * s,long pos)395 spseek(stream * s, long pos)
396 {
397     if_debug3('s', "[s]seek 0x%lx to %ld, position was %ld\n",
398 	      (ulong) s, pos, stell(s));
399     return (*(s)->procs.seek) (s, pos);
400 }
401 
402 /* Switch a stream to read or write mode. */
403 /* Return 0 or ERRC. */
404 int
sswitch(register stream * s,bool writing)405 sswitch(register stream * s, bool writing)
406 {
407     if (s->procs.switch_mode == 0)
408 	return ERRC;
409     return (*s->procs.switch_mode) (s, writing);
410 }
411 
412 /* Close a stream, disabling it if successful. */
413 /* (The stream may already be closed.) */
414 int
sclose(register stream * s)415 sclose(register stream * s)
416 {
417     stream_state *st;
418     int status = (*s->procs.close) (s);
419 
420     if (status < 0)
421 	return status;
422     st = s->state;
423     if (st != 0) {
424 	stream_proc_release((*release)) = st->template->release;
425 	if (release != 0)
426 	    (*release) (st);
427 	if (st != (stream_state *) s && st->memory != 0)
428 	    gs_free_object(st->memory, st, "s_std_close");
429 	s->state = (stream_state *) s;
430     }
431     s_disable(s);
432     return status;
433 }
434 
435 /*
436  * Implement sgetc when the buffer may be empty.  If the buffer really is
437  * empty, refill it and then read a byte.  Note that filters must read one
438  * byte ahead, so that they can close immediately after the client reads the
439  * last data byte if the next thing is an EOD.
440  */
441 int
spgetcc(register stream * s,bool close_at_eod)442 spgetcc(register stream * s, bool close_at_eod)
443 {
444     int status, left;
445     int min_left = sbuf_min_left(s);
446 
447     while (status = s->end_status,
448 	   left = s->srlimit - s->srptr,
449 	   left <= min_left && status >= 0
450 	)
451 	s_process_read_buf(s);
452     if (left <= min_left &&
453 	(left == 0 || (status != EOFC && status != ERRC))
454 	) {
455 	/* Compact the stream so stell will return the right result. */
456 	stream_compact(s, true);
457 	if (status == EOFC && close_at_eod && s->close_at_eod) {
458 	    status = sclose(s);
459 	    if (status == 0)
460 		status = EOFC;
461 	    s->end_status = status;
462 	}
463 	return status;
464     }
465     return *++(s->srptr);
466 }
467 
468 /* Implementing sputc when the buffer is full, */
469 /* by flushing the buffer and then writing the byte. */
470 int
spputc(register stream * s,byte b)471 spputc(register stream * s, byte b)
472 {
473     for (;;) {
474 	if (s->end_status)
475 	    return s->end_status;
476 	if (!sendwp(s)) {
477 	    *++(s->swptr) = b;
478 	    return b;
479 	}
480 	s_process_write_buf(s, false);
481     }
482 }
483 
484 /* Push back a character onto a (read) stream. */
485 /* The character must be the same as the last one read. */
486 /* Return 0 on success, ERRC on failure. */
487 int
sungetc(register stream * s,byte c)488 sungetc(register stream * s, byte c)
489 {
490     if (!s_is_reading(s) || s->srptr < s->cbuf || *(s->srptr) != c)
491 	return ERRC;
492     s->srptr--;
493     return 0;
494 }
495 
496 /* Get a string from a stream. */
497 /* Return 0 if the string was filled, or an exception status. */
498 int
sgets(stream * s,byte * buf,uint nmax,uint * pn)499 sgets(stream * s, byte * buf, uint nmax, uint * pn)
500 {
501     stream_cursor_write cw;
502     int status = 0;
503     int min_left = sbuf_min_left(s);
504 
505     cw.ptr = buf - 1;
506     cw.limit = cw.ptr + nmax;
507     while (cw.ptr < cw.limit) {
508 	int left;
509 
510 	if ((left = s->srlimit - s->srptr) > min_left) {
511 	    s->srlimit -= min_left;
512 	    stream_move(&s->cursor.r, &cw);
513 	    s->srlimit += min_left;
514 	} else {
515 	    uint wanted = cw.limit - cw.ptr;
516 	    int c;
517 	    stream_state *st;
518 
519 	    if (wanted >= s->bsize >> 2 &&
520 		(st = s->state) != 0 &&
521 		wanted >= st->template->min_out_size &&
522 		s->end_status == 0 &&
523 		left == 0
524 		) {
525 		byte *wptr = cw.ptr;
526 
527 		cw.limit -= min_left;
528 		status = sreadbuf(s, &cw);
529 		cw.limit += min_left;
530 		/* Compact the stream so stell will return the right result. */
531 		stream_compact(s, true);
532 		/*
533 		 * We know the stream buffer is empty, so it's safe to
534 		 * update position.  However, we need to reset the read
535 		 * cursor to indicate that there is no data in the buffer.
536 		 */
537 		s->srptr = s->srlimit = s->cbuf - 1;
538 		s->position += cw.ptr - wptr;
539 		if (status <= 0 || cw.ptr == cw.limit)
540 		    break;
541 	    }
542 	    c = spgetc(s);
543 	    if (c < 0) {
544 		status = c;
545 		break;
546 	    }
547 	    *++(cw.ptr) = c;
548 	}
549     }
550     *pn = cw.ptr + 1 - buf;
551     return (status >= 0 ? 0 : status);
552 }
553 
554 /* Write a string on a stream. */
555 /* Return 0 if the entire string was written, or an exception status. */
556 int
sputs(register stream * s,const byte * str,uint wlen,uint * pn)557 sputs(register stream * s, const byte * str, uint wlen, uint * pn)
558 {
559     uint len = wlen;
560     int status = s->end_status;
561 
562     if (status >= 0)
563 	while (len > 0) {
564 	    uint count = s->swlimit - s->swptr;
565 
566 	    if (count > 0) {
567 		if (count > len)
568 		    count = len;
569 		memcpy(s->swptr + 1, str, count);
570 		s->swptr += count;
571 		str += count;
572 		len -= count;
573 	    } else {
574 		byte ch = *str++;
575 
576 		status = sputc(s, ch);
577 		if (status < 0)
578 		    break;
579 		len--;
580 	    }
581 	}
582     *pn = wlen - len;
583     return (status >= 0 ? 0 : status);
584 }
585 
586 /* Skip ahead a specified distance in a read stream. */
587 /* Return 0 or an exception status. */
588 /* Store the number of bytes skipped in *pskipped. */
589 int
spskip(register stream * s,long nskip,long * pskipped)590 spskip(register stream * s, long nskip, long *pskipped)
591 {
592     long n = nskip;
593     int min_left;
594 
595     if (nskip < 0 || !s_is_reading(s)) {
596 	*pskipped = 0;
597 	return ERRC;
598     }
599     if (s_can_seek(s)) {
600 	long pos = stell(s);
601 	int status = sseek(s, pos + n);
602 
603 	*pskipped = stell(s) - pos;
604 	return status;
605     }
606     min_left = sbuf_min_left(s);
607     while (sbufavailable(s) < n + min_left) {
608 	int status;
609 
610 	n -= sbufavailable(s);
611 	s->srptr = s->srlimit;
612 	if (s->end_status) {
613 	    *pskipped = nskip - n;
614 	    return s->end_status;
615 	}
616 	status = sgetc(s);
617 	if (status < 0) {
618 	    *pskipped = nskip - n;
619 	    return status;
620 	}
621 	--n;
622     }
623     /* Note that if min_left > 0, n < 0 is possible; this is harmless. */
624     s->srptr += n;
625     *pskipped = nskip;
626     return 0;
627 }
628 
629 /* Read a line from a stream.  See srdline.h for the specification. */
630 int
sreadline(stream * s_in,stream * s_out,void * readline_data,gs_const_string * prompt,gs_string * buf,gs_memory_t * bufmem,uint * pcount,bool * pin_eol,bool (* is_stdin)(const stream *))631 sreadline(stream *s_in, stream *s_out, void *readline_data,
632 	  gs_const_string *prompt, gs_string * buf,
633 	  gs_memory_t * bufmem, uint * pcount, bool *pin_eol,
634 	  bool (*is_stdin)(const stream *))
635 {
636     uint count = *pcount;
637 
638     /* Most systems define \n as 0xa and \r as 0xd; however, */
639     /* OS-9 has \n == \r == 0xd and \l == 0xa.  The following */
640     /* code works properly regardless of environment. */
641 #if '\n' == '\r'
642 #  define LF 0xa
643 #else
644 #  define LF '\n'
645 #endif
646 
647     if (count == 0 && s_out && prompt) {
648 	uint ignore_n;
649 	int ch = sputs(s_out, prompt->data, prompt->size, &ignore_n);
650 
651 	if (ch < 0)
652 	    return ch;
653     }
654 
655 top:
656     if (*pin_eol) {
657 	/*
658 	 * We're in the middle of checking for a two-character
659 	 * end-of-line sequence.  If we get an EOF here, stop, but
660 	 * don't signal EOF now; wait till the next read.
661 	 */
662 	int ch = spgetcc(s_in, false);
663 
664 	if (ch == EOFC) {
665 	    *pin_eol = false;
666 	    return 0;
667 	} else if (ch < 0)
668 	    return ch;
669 	else if (ch != LF)
670 	    sputback(s_in);
671 	*pin_eol = false;
672 	return 0;
673     }
674     for (;;) {
675 	int ch = sgetc(s_in);
676 
677 	if (ch < 0) {		/* EOF or exception */
678 	    *pcount = count;
679 	    return ch;
680 	}
681 	switch (ch) {
682 	    case '\r':
683 		{
684 #if '\n' == '\r'		/* OS-9 or similar */
685 		    if (!is_stdin(s_in))
686 #endif
687 		    {
688 			*pcount = count;
689 			*pin_eol = true;
690 			goto top;
691 		    }
692 		}
693 		/* falls through */
694 	    case LF:
695 #undef LF
696 		*pcount = count;
697 		return 0;
698 	}
699 	if (count >= buf->size) {	/* filled the string */
700 	    if (!bufmem) {
701 		sputback(s_in);
702 		*pcount = count;
703 		return 1;
704 	    }
705 	    {
706 		uint nsize = count + max(count, 20);
707 		byte *ndata = gs_resize_string(bufmem, buf->data, buf->size,
708 					       nsize, "sreadline(buffer)");
709 
710 		if (ndata == 0)
711 		    return ERRC; /* no better choice */
712 		buf->data = ndata;
713 		buf->size = nsize;
714 	    }
715 	}
716 	buf->data[count++] = ch;
717     }
718     /*return 0; *//* not reached */
719 }
720 
721 /* ------ Utilities ------ */
722 
723 /*
724  * Attempt to refill the buffer of a read stream.  Only call this if the
725  * end_status is not EOFC, and if the buffer is (nearly) empty.
726  */
727 int
s_process_read_buf(stream * s)728 s_process_read_buf(stream * s)
729 {
730     int status;
731 
732     stream_compact(s, false);
733     status = sreadbuf(s, &s->cursor.w);
734     s->end_status = (status >= 0 ? 0 : status);
735     return 0;
736 }
737 
738 /*
739  * Attempt to empty the buffer of a write stream.  Only call this if the
740  * end_status is not EOFC.
741  */
742 int
s_process_write_buf(stream * s,bool last)743 s_process_write_buf(stream * s, bool last)
744 {
745     int status = swritebuf(s, &s->cursor.r, last);
746 
747     stream_compact(s, false);
748     return (status >= 0 ? 0 : status);
749 }
750 
751 /* Move forward or backward in a pipeline.  We temporarily reverse */
752 /* the direction of the pointers while doing this. */
753 /* (Cf the Deutsch-Schorr-Waite graph marking algorithm.) */
754 #define MOVE_BACK(curr, prev)\
755   BEGIN\
756     stream *back = prev->strm;\
757     prev->strm = curr; curr = prev; prev = back;\
758   END
759 #define MOVE_AHEAD(curr, prev)\
760   BEGIN\
761     stream *ahead = curr->strm;\
762     curr->strm = prev; prev = curr; curr = ahead;\
763   END
764 
765 /*
766  * Read from a stream pipeline.  Update end_status for all streams that were
767  * actually touched.  Return the status from the outermost stream: this is
768  * normally the same as s->end_status, except that if s->procs.process
769  * returned 1, sreadbuf sets s->end_status to 0, but returns 1.
770  */
771 static int
sreadbuf(stream * s,stream_cursor_write * pbuf)772 sreadbuf(stream * s, stream_cursor_write * pbuf)
773 {
774     stream *prev = 0;
775     stream *curr = s;
776     int status;
777 
778     for (;;) {
779 	stream *strm;
780 	stream_cursor_write *pw;
781 	byte *oldpos;
782 
783 	for (;;) {		/* Descend into the recursion. */
784 	    stream_cursor_read cr;
785 	    stream_cursor_read *pr;
786 	    int left;
787 	    bool eof;
788 
789 	    strm = curr->strm;
790 	    if (strm == 0) {
791 		cr.ptr = 0, cr.limit = 0;
792 		pr = &cr;
793 		left = 0;
794 		eof = false;
795 	    } else {
796 		pr = &strm->cursor.r;
797 		left = sbuf_min_left(strm);
798 		left = min(left, pr->limit - pr->ptr);
799 		pr->limit -= left;
800 		eof = strm->end_status == EOFC;
801 	    }
802 	    pw = (prev == 0 ? pbuf : &curr->cursor.w);
803 	    if_debug4('s', "[s]read process 0x%lx, nr=%u, nw=%u, eof=%d\n",
804 		      (ulong) curr, (uint) (pr->limit - pr->ptr),
805 		      (uint) (pw->limit - pw->ptr), eof);
806 	    oldpos = pw->ptr;
807 	    status = (*curr->procs.process) (curr->state, pr, pw, eof);
808 	    pr->limit += left;
809 	    if_debug5('s', "[s]after read 0x%lx, nr=%u, nw=%u, status=%d, position=%ld\n",
810 		      (ulong) curr, (uint) (pr->limit - pr->ptr),
811 		      (uint) (pw->limit - pw->ptr), status, s->position);
812 	    if (strm == 0 || status != 0)
813 		break;
814 	    if (strm->end_status < 0) {
815 		if (strm->end_status != EOFC || pw->ptr == oldpos)
816 		    status = strm->end_status;
817 		break;
818 	    }
819 	    MOVE_AHEAD(curr, prev);
820 	    stream_compact(curr, false);
821 	}
822 	/* If curr reached EOD and is a filter or file stream, close it
823          * if it is the last filter in the pipeline. Closing the last filter
824          * seems to contradict PLRM3 but matches Adobe interpreters.
825          */
826 	if ((strm != 0 || curr->file) && status == EOFC &&
827 	    curr->cursor.r.ptr >= curr->cursor.r.limit &&
828 	    curr->close_at_eod &&
829             prev == 0
830 	    ) {
831 	    int cstat = sclose(curr);
832 
833 	    if (cstat != 0)
834 		status = cstat;
835 	}
836 	/* Unwind from the recursion. */
837 	curr->end_status = (status >= 0 ? 0 : status);
838 	if (prev == 0)
839 	    return status;
840 	MOVE_BACK(curr, prev);
841     }
842 }
843 
844 /* Write to a pipeline. */
845 static int
swritebuf(stream * s,stream_cursor_read * pbuf,bool last)846 swritebuf(stream * s, stream_cursor_read * pbuf, bool last)
847 {
848     stream *prev = 0;
849     stream *curr = s;
850     int depth = 0;		/* # of non-temp streams before curr */
851     int status;
852 
853     /*
854      * The handling of EOFC is a little tricky.  There are two
855      * invariants that keep it straight:
856      *      - We only pass last = true to a stream if either it is
857      * the first stream in the pipeline, or it is a temporary stream
858      * below the first stream and the stream immediately above it has
859      * end_status = EOFC.
860      */
861     for (;;) {
862 	for (;;) {
863 	    /* Move ahead in the pipeline. */
864 	    stream *strm = curr->strm;
865 	    stream_cursor_write cw;
866 	    stream_cursor_read *pr;
867 	    stream_cursor_write *pw;
868 
869 	    /*
870 	     * We only want to set the last/end flag for
871 	     * the top-level stream and any temporary streams
872 	     * immediately below it.
873 	     */
874 	    bool end = last &&
875 		(prev == 0 ||
876 		 (depth <= 1 && prev->end_status == EOFC));
877 
878 	    if (strm == 0)
879 		cw.ptr = 0, cw.limit = 0, pw = &cw;
880 	    else
881 		pw = &strm->cursor.w;
882 	    if (prev == 0)
883 		pr = pbuf;
884 	    else
885 		pr = &curr->cursor.r;
886 	    if_debug5('s',
887 		      "[s]write process 0x%lx(%s), nr=%u, nw=%u, end=%d\n",
888 		      (ulong)curr,
889 		      gs_struct_type_name(curr->state->template->stype),
890 		      (uint)(pr->limit - pr->ptr),
891 		      (uint)(pw->limit - pw->ptr), end);
892 	    status = curr->end_status;
893 	    if (status >= 0) {
894 		status = (*curr->procs.process)(curr->state, pr, pw, end);
895 		if_debug5('s',
896 			  "[s]after write 0x%lx, nr=%u, nw=%u, end=%d, status=%d\n",
897 			  (ulong) curr, (uint) (pr->limit - pr->ptr),
898 			  (uint) (pw->limit - pw->ptr), end, status);
899 		if (status == 0 && end)
900 		    status = EOFC;
901 		if (status == EOFC || status == ERRC)
902 		    curr->end_status = status;
903 	    }
904 	    if (strm == 0 || (status < 0 && status != EOFC))
905 		break;
906 	    if (status != 1) {
907 		/*
908 		 * Keep going if we are closing a filter with a sub-stream.
909 		 * We know status == 0 or EOFC.
910 		 */
911 		if (!end || !strm->is_temp)
912 		    break;
913 	    }
914 	    status = strm->end_status;
915 	    if (status < 0 && (status != EOFC || !end))
916 		break;
917 	    if (!curr->is_temp)
918 		++depth;
919 	    if_debug1('s', "[s]moving ahead, depth = %d\n", depth);
920 	    MOVE_AHEAD(curr, prev);
921 	    stream_compact(curr, false);
922 	}
923 	/* Move back in the pipeline. */
924 	curr->end_status = (status >= 0 ? 0 : status);
925 	if (status < 0 || prev == 0) {
926 	    /*
927 	     * All streams up to here were called with last = true
928 	     * and returned 0 or EOFC (so their end_status is now EOFC):
929 	     * finish unwinding and then return.  Change the status of
930 	     * the prior streams to ERRC if the new status is ERRC,
931 	     * otherwise leave it alone.
932 	     */
933 	    while (prev) {
934 		if_debug0('s', "[s]unwinding\n");
935 		MOVE_BACK(curr, prev);
936 		if (status >= 0)
937 		    curr->end_status = 0;
938 		else if (status == ERRC)
939 		    curr->end_status = ERRC;
940 	    }
941 	    return status;
942 	}
943 	MOVE_BACK(curr, prev);
944 	if (!curr->is_temp)
945 	    --depth;
946 	if_debug1('s', "[s]moving back, depth = %d\n", depth);
947     }
948 }
949 
950 /* Move as much data as possible from one buffer to another. */
951 /* Return 0 if the input became empty, 1 if the output became full. */
952 int
stream_move(stream_cursor_read * pr,stream_cursor_write * pw)953 stream_move(stream_cursor_read * pr, stream_cursor_write * pw)
954 {
955     uint rcount = pr->limit - pr->ptr;
956     uint wcount = pw->limit - pw->ptr;
957     uint count;
958     int status;
959 
960     if (rcount <= wcount)
961 	count = rcount, status = 0;
962     else
963 	count = wcount, status = 1;
964     memmove(pw->ptr + 1, pr->ptr + 1, count);
965     pr->ptr += count;
966     pw->ptr += count;
967     return status;
968 }
969 
970 /* If possible, compact the information in a stream buffer to the bottom. */
971 static void
stream_compact(stream * s,bool always)972 stream_compact(stream * s, bool always)
973 {
974     if (s->cursor.r.ptr >= s->cbuf && (always || s->end_status >= 0)) {
975 	uint dist = s->cursor.r.ptr + 1 - s->cbuf;
976 
977 	memmove(s->cbuf, s->cursor.r.ptr + 1,
978 		(uint) (s->cursor.r.limit - s->cursor.r.ptr));
979 	s->cursor.r.ptr = s->cbuf - 1;
980 	s->cursor.r.limit -= dist;	/* same as w.ptr */
981 	s->position += dist;
982     }
983 }
984 
985 /* ------ String streams ------ */
986 
987 /* String stream procedures */
988 static int
989     s_string_available(stream *, long *),
990     s_string_read_seek(stream *, long),
991     s_string_write_seek(stream *, long),
992     s_string_read_process(stream_state *, stream_cursor_read *,
993 			  stream_cursor_write *, bool),
994     s_string_write_process(stream_state *, stream_cursor_read *,
995 			   stream_cursor_write *, bool);
996 
997 /* Initialize a stream for reading a string. */
998 void
sread_string(register stream * s,const byte * ptr,uint len)999 sread_string(register stream *s, const byte *ptr, uint len)
1000 {
1001     static const stream_procs p = {
1002 	 s_string_available, s_string_read_seek, s_std_read_reset,
1003 	 s_std_read_flush, s_std_null, s_string_read_process
1004     };
1005 
1006     s_std_init(s, (byte *)ptr, len, &p, s_mode_read + s_mode_seek);
1007     s->cbuf_string.data = (byte *)ptr;
1008     s->cbuf_string.size = len;
1009     s->end_status = EOFC;
1010     s->srlimit = s->swlimit;
1011 }
1012 /* Initialize a reusable stream for reading a string. */
1013 static void
s_string_reusable_reset(stream * s)1014 s_string_reusable_reset(stream *s)
1015 {
1016     s->srptr = s->cbuf - 1;	/* just reset to the beginning */
1017     s->srlimit = s->srptr + s->bsize;  /* might have gotten reset */
1018 }
1019 static int
s_string_reusable_flush(stream * s)1020 s_string_reusable_flush(stream *s)
1021 {
1022     s->srptr = s->srlimit = s->cbuf + s->bsize - 1;  /* just set to the end */
1023     return 0;
1024 }
1025 void
sread_string_reusable(stream * s,const byte * ptr,uint len)1026 sread_string_reusable(stream *s, const byte *ptr, uint len)
1027 {
1028     /*
1029      * Note that s->procs.close is s_close_disable, to parallel
1030      * file_close_disable.
1031      */
1032     static const stream_procs p = {
1033 	 s_string_available, s_string_read_seek, s_string_reusable_reset,
1034 	 s_string_reusable_flush, s_close_disable, s_string_read_process
1035     };
1036 
1037     sread_string(s, ptr, len);
1038     s->procs = p;
1039     s->close_at_eod = false;
1040 }
1041 
1042 /* Return the number of available bytes when reading from a string. */
1043 static int
s_string_available(stream * s,long * pl)1044 s_string_available(stream *s, long *pl)
1045 {
1046     *pl = sbufavailable(s);
1047     if (*pl == 0 && s->close_at_eod)	/* EOF */
1048 	*pl = -1;
1049     return 0;
1050 }
1051 
1052 /* Seek in a string being read.  Return 0 if OK, ERRC if not. */
1053 static int
s_string_read_seek(register stream * s,long pos)1054 s_string_read_seek(register stream * s, long pos)
1055 {
1056     if (pos < 0 || pos > s->bsize)
1057 	return ERRC;
1058     s->srptr = s->cbuf + pos - 1;
1059     /* We might be seeking after a reusable string reached EOF. */
1060     s->srlimit = s->cbuf + s->bsize - 1;
1061     /*
1062      * When the file reaches EOF,
1063      * stream_compact sets s->position to its end.
1064      * Reset it now to allow stell to work properly
1065      * after calls to this function.
1066      * Note that if the riched EOF and this fuction
1067      * was not called, stell still returns a wrong value.
1068      */
1069     s->position = 0;
1070     return 0;
1071 }
1072 
1073 /* Initialize a stream for writing a string. */
1074 void
swrite_string(register stream * s,byte * ptr,uint len)1075 swrite_string(register stream * s, byte * ptr, uint len)
1076 {
1077     static const stream_procs p = {
1078 	s_std_noavailable, s_string_write_seek, s_std_write_reset,
1079 	s_std_null, s_std_null, s_string_write_process
1080     };
1081 
1082     s_std_init(s, ptr, len, &p, s_mode_write + s_mode_seek);
1083     s->cbuf_string.data = ptr;
1084     s->cbuf_string.size = len;
1085 }
1086 
1087 /* Seek in a string being written.  Return 0 if OK, ERRC if not. */
1088 static int
s_string_write_seek(register stream * s,long pos)1089 s_string_write_seek(register stream * s, long pos)
1090 {
1091     if (pos < 0 || pos > s->bsize)
1092 	return ERRC;
1093     s->swptr = s->cbuf + pos - 1;
1094     return 0;
1095 }
1096 
1097 /* Since we initialize the input buffer of a string read stream */
1098 /* to contain all of the data in the string, if we are ever asked */
1099 /* to refill the buffer, we should signal EOF. */
1100 static int
s_string_read_process(stream_state * st,stream_cursor_read * ignore_pr,stream_cursor_write * pw,bool last)1101 s_string_read_process(stream_state * st, stream_cursor_read * ignore_pr,
1102 		      stream_cursor_write * pw, bool last)
1103 {
1104     return EOFC;
1105 }
1106 /* Similarly, if we are ever asked to empty the buffer, it means that */
1107 /* there has been an overrun (unless we are closing the stream). */
1108 static int
s_string_write_process(stream_state * st,stream_cursor_read * pr,stream_cursor_write * ignore_pw,bool last)1109 s_string_write_process(stream_state * st, stream_cursor_read * pr,
1110 		       stream_cursor_write * ignore_pw, bool last)
1111 {
1112     return (last ? EOFC : ERRC);
1113 }
1114 
1115 /* ------ Position-tracking stream ------ */
1116 
1117 static int
1118     s_write_position_process(stream_state *, stream_cursor_read *,
1119 			     stream_cursor_write *, bool);
1120 
1121 /* Set up a write stream that just keeps track of the position. */
1122 void
swrite_position_only(stream * s)1123 swrite_position_only(stream *s)
1124 {
1125     static byte discard_buf[50];	/* size is arbitrary */
1126 
1127     swrite_string(s, discard_buf, sizeof(discard_buf));
1128     s->procs.process = s_write_position_process;
1129 }
1130 
1131 static int
s_write_position_process(stream_state * st,stream_cursor_read * pr,stream_cursor_write * ignore_pw,bool last)1132 s_write_position_process(stream_state * st, stream_cursor_read * pr,
1133 			 stream_cursor_write * ignore_pw, bool last)
1134 {
1135     pr->ptr = pr->limit;	/* discard data */
1136     return 0;
1137 }
1138 
1139 /* ------ Filter pipelines ------ */
1140 
1141 /*
1142  * Add a filter to an output pipeline.  The client must have allocated the
1143  * stream state, if any, using the given allocator.  For s_init_filter, the
1144  * client must have called s_init and s_init_state.
1145  */
1146 int
s_init_filter(stream * fs,stream_state * fss,byte * buf,uint bsize,stream * target)1147 s_init_filter(stream *fs, stream_state *fss, byte *buf, uint bsize,
1148 	      stream *target)
1149 {
1150     const stream_template *template = fss->template;
1151 
1152     if (bsize < template->min_in_size)
1153 	return ERRC;
1154     s_std_init(fs, buf, bsize, &s_filter_write_procs, s_mode_write);
1155     fs->procs.process = template->process;
1156     fs->state = fss;
1157     if (template->init) {
1158 	fs->end_status = (template->init)(fss);
1159 	if (fs->end_status < 0)
1160 	    return fs->end_status;
1161     }
1162     fs->strm = target;
1163     return 0;
1164 }
1165 stream *
s_add_filter(stream ** ps,const stream_template * template,stream_state * ss,gs_memory_t * mem)1166 s_add_filter(stream **ps, const stream_template *template,
1167 	     stream_state *ss, gs_memory_t *mem)
1168 {
1169     stream *es;
1170     stream_state *ess;
1171     uint bsize = max(template->min_in_size, 256);	/* arbitrary */
1172     byte *buf;
1173 
1174     /*
1175      * Ensure enough buffering.  This may require adding an additional
1176      * stream.
1177      */
1178     if (bsize > (*ps)->bsize && template->process != s_NullE_template.process) {
1179 	stream_template null_template;
1180 
1181 	null_template = s_NullE_template;
1182 	null_template.min_in_size = bsize;
1183 	if (s_add_filter(ps, &null_template, NULL, mem) == 0)
1184 	    return 0;
1185     }
1186     es = s_alloc(mem, "s_add_filter(stream)");
1187     buf = gs_alloc_bytes(mem, bsize, "s_add_filter(buf)");
1188     if (es == 0 || buf == 0) {
1189 	gs_free_object(mem, buf, "s_add_filter(buf)");
1190 	gs_free_object(mem, es, "s_add_filter(stream)");
1191 	return 0;
1192     }
1193     ess = (ss == 0 ? (stream_state *)es : ss);
1194     ess->template = template;
1195     ess->memory = mem;
1196     es->memory = mem;
1197     if (s_init_filter(es, ess, buf, bsize, *ps) < 0)
1198 	return 0;
1199     *ps = es;
1200     return es;
1201 }
1202 
1203 /*
1204  * Close the filters in a pipeline, up to a given target stream, freeing
1205  * their buffers and state structures.
1206  */
1207 int
s_close_filters(stream ** ps,stream * target)1208 s_close_filters(stream **ps, stream *target)
1209 {
1210     while (*ps != target) {
1211 	stream *s = *ps;
1212 	gs_memory_t *mem = s->state->memory;
1213 	byte *sbuf = s->cbuf;
1214 	stream *next = s->strm;
1215 	int status = sclose(s);
1216 	stream_state *ss = s->state; /* sclose may set this to s */
1217 
1218 	if (status < 0)
1219 	    return status;
1220 	if (mem) {
1221 	    gs_free_object(mem, sbuf, "s_close_filters(buf)");
1222 	    gs_free_object(mem, s, "s_close_filters(stream)");
1223 	    if (ss != (stream_state *)s)
1224 		gs_free_object(mem, ss, "s_close_filters(state)");
1225 	}
1226 	*ps = next;
1227     }
1228     return 0;
1229 }
1230 
1231 /* ------ Stream closing ------ */
1232 
1233 /*
1234  * Finish closing a file stream.  This used to check whether it was
1235  * currentfile, but we don't have to do this any longer.  This replaces the
1236  * close procedure for the std* streams, which cannot actually be closed.
1237  *
1238  * This is exported for ziodev.c.  */
1239 int
file_close_finish(stream * s)1240 file_close_finish(stream * s)
1241 {
1242     return 0;
1243 }
1244 
1245 /*
1246  * Close a file stream, but don't deallocate the buffer.  This replaces the
1247  * close procedure for %lineedit and %statementedit.  (This is WRONG: these
1248  * streams should allocate a new buffer each time they are opened, but that
1249  * would overstress the allocator right now.)  This is exported for ziodev.c.
1250  * This also replaces the close procedure for the string-reading streams
1251  * created for gs_run_string and for reusable streams.
1252  */
1253 int
s_close_disable(stream * s)1254 s_close_disable(stream *s)
1255 {
1256     /* Increment the IDs to prevent further access. */
1257     s->read_id = s->write_id = (s->read_id | s->write_id) + 1;
1258     return 0;
1259 }
1260 int
file_close_disable(stream * s)1261 file_close_disable(stream * s)
1262 {
1263     int code;
1264 
1265     if ((*s->save_close != NULL) && ((code = (*s->save_close)(s)) != 0))
1266 	return code;
1267     s_close_disable(s);
1268     return file_close_finish(s);
1269 }
1270 
1271 /* ------ NullEncode/Decode ------ */
1272 
1273 /* Process a buffer */
1274 static int
s_Null_process(stream_state * st,stream_cursor_read * pr,stream_cursor_write * pw,bool last)1275 s_Null_process(stream_state * st, stream_cursor_read * pr,
1276 	       stream_cursor_write * pw, bool last)
1277 {
1278     return stream_move(pr, pw);
1279 }
1280 
1281 /* Stream template */
1282 const stream_template s_NullE_template = {
1283     &st_stream_state, NULL, s_Null_process, 1, 1
1284 };
1285 const stream_template s_NullD_template = {
1286     &st_stream_state, NULL, s_Null_process, 1, 1
1287 };
1288