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