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