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