Coverage Report

Created: 2025-06-10 06:58

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