Coverage Report

Created: 2026-11-12 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/base/gxclfile.c
Line
Count
Source
1
/* Copyright (C) 2001-2026 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
//#define CLIST_WRITE_SQUEEZING
18
#ifdef CLIST_WRITE_SQUEEZING
19
#include <stdlib.h>
20
#include <stdio.h>
21
#endif
22
23
/* File-based command list implementation */
24
#include "assert_.h"
25
#include "stdio_.h"
26
#include "string_.h"
27
#include "unistd_.h"
28
#include "gserrors.h"
29
#include "gsmemory.h"
30
#include "gp.h"
31
#include "gxclio.h"
32
33
#include "valgrind.h"
34
35
36
/* This is an implementation of the command list I/O interface */
37
/* that uses the file system for storage. */
38
39
/* clist cache code so that wrapped files don't incur a performance penalty */
40
13.2k
#define CL_CACHE_NSLOTS (3)
41
13.2k
#define CL_CACHE_SLOT_SIZE_LOG2 (15)
42
4.44M
#define CL_CACHE_SLOT_EMPTY (-1)
43
44
static clist_io_procs_t clist_io_procs_file;
45
46
typedef struct
47
{
48
    int64_t blocknum;
49
    byte *base;
50
} CL_CACHE_SLOT;
51
52
typedef struct
53
{
54
    int block_size;   /* full block size, MUST BE power of 2 */
55
    int nslots;
56
    int64_t filesize;
57
    gs_memory_t *memory;  /* save our allocator */
58
    CL_CACHE_SLOT *slots; /* array of slots */
59
    byte *base;                 /* save base of slot data area */
60
} CL_CACHE;
61
62
/* Forward references */
63
CL_CACHE *cl_cache_alloc(gs_memory_t *mem);
64
void cl_cache_destroy(CL_CACHE *cache);
65
CL_CACHE *cl_cache_read_init(CL_CACHE *cache, int nslots, int64_t block_size, int64_t filesize);
66
int cl_cache_read(byte *data, int len, int64_t pos, CL_CACHE *cache);
67
CL_CACHE_SLOT * cl_cache_get_empty_slot(CL_CACHE *cache, int64_t pos);
68
void cl_cache_load_slot(CL_CACHE *cache, CL_CACHE_SLOT *slot, int64_t pos, byte *data, int len);
69
70
472M
#define CL_CACHE_NEEDS_INIT(cache) (cache != NULL && cache->filesize == 0)
71
72
CL_CACHE *
73
cl_cache_alloc(gs_memory_t *mem)
74
13.2k
{
75
13.2k
    CL_CACHE *cache;
76
77
    /* allocate and initialilze the cache to filesize = 0 to signal read_init needed */
78
13.2k
    cache = (CL_CACHE *)gs_alloc_bytes(mem, sizeof(CL_CACHE), "alloc CL_CACHE");
79
13.2k
    if (cache != NULL) {
80
13.2k
        cache->filesize = 0;
81
13.2k
        cache->nslots = 0;
82
13.2k
        cache->block_size = 0;
83
13.2k
        cache->slots = NULL;
84
13.2k
        cache->base = NULL;
85
13.2k
        cache->memory = mem;
86
13.2k
    }
87
13.2k
    return cache;
88
13.2k
}
89
90
void
91
cl_cache_destroy(CL_CACHE *cache)
92
13.2k
{
93
13.2k
    if (cache == NULL)
94
0
        return;
95
96
13.2k
    if (cache->slots != NULL) {
97
13.2k
        gs_free_object(cache->memory, cache->base, "CL_CACHE SLOT data");
98
13.2k
        gs_free_object(cache->memory, cache->slots, "CL_CACHE slots array");
99
13.2k
    }
100
13.2k
    gs_free_object(cache->memory, cache, "CL_CACHE for IFILE");
101
13.2k
}
102
103
/* Set the cache up for reading. The filesize is used for EOF */
104
CL_CACHE *
105
cl_cache_read_init(CL_CACHE *cache, int nslots, int64_t block_size, int64_t filesize)
106
13.2k
{
107
    /* NB: if fail, and cache is still NULL, proceed without cache, reading will cope */
108
13.2k
    if (cache == NULL || cache->filesize != 0)
109
0
        return cache;   /* once we've done the init, filesize will be set */
110
111
13.2k
    if ((filesize+block_size)/block_size < nslots)
112
11.6k
        nslots = (filesize + block_size)/block_size; /* limit at blocks needed for entire file */
113
13.2k
    cache->slots = (CL_CACHE_SLOT *)gs_alloc_bytes(cache->memory, (size_t)nslots * sizeof(CL_CACHE_SLOT),
114
13.2k
                                                       "CL_CACHE slots array");
115
13.2k
    if (cache->slots == NULL) {
116
0
        gs_free_object(cache->memory, cache, "Free CL_CACHE for IFILE");
117
0
        cache = NULL;     /* cache not possible */
118
13.2k
    } else {
119
13.2k
        cache->slots[0].base = (byte *)gs_alloc_bytes(cache->memory, (size_t)nslots * block_size,
120
13.2k
                                                       "CL_CACHE_SLOT data");
121
13.2k
        if (cache->slots[0].base == NULL) {
122
0
            gs_free_object(cache->memory, cache->slots, "Free CL_CACHE for IFILE");
123
0
            gs_free_object(cache->memory, cache, "Free CL_CACHE for IFILE");
124
0
            cache = NULL;     /* cache not possible */
125
13.2k
        } else {
126
            /* success, initialize the slots */
127
13.2k
            int i;
128
129
30.1k
            for (i=0; i < nslots; i++) {
130
16.8k
                cache->slots[i].blocknum = CL_CACHE_SLOT_EMPTY;
131
16.8k
                cache->slots[i].base = cache->slots[0].base + (i * block_size);
132
16.8k
            }
133
13.2k
            cache->base = cache->slots[0].base;         /* save for the 'destroy' (slots array moves around) */
134
13.2k
            cache->nslots = nslots;
135
13.2k
            cache->block_size = block_size;
136
13.2k
            cache->filesize = filesize;
137
13.2k
        }
138
13.2k
    }
139
13.2k
    return cache; /* May be NULL. If so, no cache used */
140
13.2k
}
141
142
/* Find the cache for the slot containing the 'pos'. */
143
/* return the number of bytes read, up to 'len' bytes */
144
/* returns 0 if 'pos' not in cache, -1 if pos at or past EOF. */
145
int
146
cl_cache_read(byte *data, int len, int64_t pos, CL_CACHE *cache)
147
464M
{
148
464M
    int nread = 0;
149
464M
    int slot;
150
464M
    int offset;
151
464M
    int64_t blocknum = pos / cache->block_size;
152
153
464M
    if (pos >= cache->filesize)
154
0
        return -1;
155
156
    /* find the slot */
157
472M
    for (slot = 0; slot < cache->nslots; slot++) {
158
469M
        if (blocknum == cache->slots[slot].blocknum)
159
462M
            break;
160
469M
    }
161
464M
    if (slot >= cache->nslots)
162
2.22M
        return 0;               /* block not in cache */
163
164
462M
    if (slot != 0) {
165
        /* move the slot we found to the top, moving the rest down */
166
677k
        byte *base = cache->slots[slot].base;
167
677k
        int i;
168
169
1.59M
        for (i = slot; i > 0; i--) {
170
917k
            cache->slots[i].base = cache->slots[i-1].base;
171
917k
            cache->slots[i].blocknum = cache->slots[i-1].blocknum;
172
917k
        }
173
677k
        cache->slots[0].blocknum = blocknum;
174
677k
        cache->slots[0].base = base;
175
677k
    }
176
462M
    offset = pos - cache->slots[0].blocknum * cache->block_size;
177
462M
    nread = min(cache->block_size - offset, len);
178
462M
    if (nread + pos > cache->filesize)
179
0
        nread = cache->filesize - pos; /* limit for EOF */
180
462M
    memcpy(data, cache->slots[0].base + offset, nread);
181
462M
    return nread;
182
464M
}
183
184
/* 'pos' not used yet */
185
/* discard the LRU, move remaining slots down and return the first as new MRU */
186
CL_CACHE_SLOT *
187
cl_cache_get_empty_slot(CL_CACHE *cache, int64_t pos)
188
2.22M
{
189
    /* the LRU is in the last slot, so re-use it */
190
2.22M
    CL_CACHE_SLOT *pslot = &(cache->slots[0]);             /* slot used will always be first, possibly after moving */
191
2.22M
    int64_t slot0_blocknum = pslot->blocknum;
192
193
2.22M
    if (slot0_blocknum == CL_CACHE_SLOT_EMPTY)
194
13.2k
        return pslot;
195
196
    /* if more than on slot in the cache, handle moving slots to bump the LRU (last) */
197
    /* If the block at slot 0 hasn't been flushed at least once before, just use slot 0 */
198
2.20M
    if (cache->nslots > 1) {
199
        /* rotate the cache to re-use the last slot (LRU) and move it to the top, moving the rest down */
200
2.20M
        byte *last_slot_base = cache->slots[cache->nslots - 1].base;    /* save the base for the last slot */
201
2.20M
        int i;
202
203
        /* move the rest down */
204
6.62M
        for (i=cache->nslots - 1; i > 0; i--) {
205
4.41M
            cache->slots[i].blocknum = cache->slots[i-1].blocknum;
206
4.41M
            cache->slots[i].base = cache->slots[i-1].base;
207
4.41M
        }
208
2.20M
        pslot->base = last_slot_base;
209
2.20M
    }
210
2.20M
    pslot->blocknum = CL_CACHE_SLOT_EMPTY;
211
2.20M
    return pslot;
212
2.22M
}
213
214
void
215
cl_cache_load_slot(CL_CACHE *cache, CL_CACHE_SLOT *slot, int64_t pos, byte *data, int len)
216
2.22M
{
217
2.22M
    slot->blocknum = pos / cache->block_size;
218
2.22M
    memmove(slot->base, data, len);
219
2.22M
}
220
221
/* Use our own FILE structure so that, on some platforms, we write and read
222
 * tmp files via a single file descriptor. That allows cleaning of tmp files
223
 * to be addressed via DELETE_ON_CLOSE under Windows, and immediate unlink
224
 * after opening under Linux. When running in this mode, we keep our own
225
 * record of position within the file for the sake of thread safety
226
 */
227
228
670k
#define ENC_FILE_STR ("encoded_file_ptr_%p")
229
664k
#define ENC_FILE_STRX ("encoded_file_ptr_0x%p")
230
231
typedef struct
232
{
233
    gs_memory_t *mem;
234
    gp_file *f;
235
    int64_t pos;
236
    int64_t filesize;   /* filesize maintained by clist_fwrite */
237
    CL_CACHE *cache;
238
} IFILE;
239
240
static void
241
file_to_fake_path(clist_file_ptr file, char fname[gp_file_name_sizeof])
242
6.60k
{
243
6.60k
    gs_snprintf(fname, gp_file_name_sizeof, ENC_FILE_STR, file);
244
6.60k
}
245
246
static clist_file_ptr
247
fake_path_to_file(const char *fname)
248
664k
{
249
664k
    clist_file_ptr i1, i2;
250
251
664k
    int r1 = sscanf(fname, ENC_FILE_STR, &i1);
252
664k
    int r2 = sscanf(fname, ENC_FILE_STRX, &i2);
253
664k
    return r2 == 1 ? i2 : (r1 == 1 ? i1 : NULL);
254
664k
}
255
256
static IFILE *wrap_file(gs_memory_t *mem, gp_file *f, const char *fmode)
257
6.60k
{
258
6.60k
    IFILE *ifile;
259
260
6.60k
    if (!f) return NULL;
261
6.60k
    ifile = (IFILE *)gs_alloc_bytes(mem->non_gc_memory, sizeof(*ifile), "Allocate wrapped IFILE");
262
6.60k
    if (!ifile) {
263
0
        gp_fclose(f);
264
0
        return NULL;
265
0
    }
266
6.60k
    ifile->mem = mem->non_gc_memory;
267
6.60k
    ifile->f = f;
268
6.60k
    ifile->pos = 0;
269
6.60k
    ifile->filesize = 0;
270
6.60k
    ifile->cache = cl_cache_alloc(ifile->mem);
271
6.60k
    return ifile;
272
6.60k
}
273
274
static int clist_close_file(IFILE *ifile)
275
6.60k
{
276
6.60k
    int res = 0;
277
6.60k
    if (ifile) {
278
6.60k
        if (ifile->f != NULL)
279
6.60k
            res = gp_fclose(ifile->f);
280
6.60k
        if (ifile->cache != NULL)
281
6.60k
            cl_cache_destroy(ifile->cache);
282
6.60k
        gs_free_object(ifile->mem, ifile, "Free wrapped IFILE");
283
6.60k
    }
284
6.60k
    return res;
285
6.60k
}
286
287
/* ------ Open/close/unlink ------ */
288
289
static int
290
clist_fopen(char fname[gp_file_name_sizeof], const char *fmode,
291
            clist_file_ptr * pcf, gs_memory_t * mem, gs_memory_t *data_mem,
292
            bool ok_to_compress)
293
6.60k
{
294
6.60k
    if (*fname == 0) {
295
6.60k
        if (fmode[0] == 'r')
296
0
            return_error(gs_error_invalidfileaccess);
297
6.60k
        if (gp_can_share_fdesc()) {
298
6.60k
            *pcf = (clist_file_ptr)wrap_file(mem, gp_open_scratch_file_rm(mem,
299
6.60k
                                                       gp_scratch_file_name_prefix,
300
6.60k
                                                       fname, fmode), fmode);
301
            /* If the platform supports FILE duplication then we overwrite the
302
             * file name with an encoded form of the FILE pointer */
303
6.60k
            if (*pcf != NULL)
304
6.60k
                file_to_fake_path(*pcf, fname);
305
6.60k
        } else {
306
0
            *pcf = (clist_file_ptr)wrap_file(mem, gp_open_scratch_file(mem,
307
0
                                                       gp_scratch_file_name_prefix,
308
0
                                                       fname, fmode), fmode);
309
0
        }
310
6.60k
    } else {
311
0
        clist_file_ptr ocf = fake_path_to_file(fname);
312
0
        if (ocf) {
313
            /*  A special (fake) fname is passed in. If so, clone the FILE handle */
314
0
            *pcf = wrap_file(mem, gp_fdup(((IFILE *)ocf)->f, fmode), fmode);
315
            /* when cloning, copy other parts not done by wrap_file */
316
0
            if (*pcf)
317
0
                ((IFILE *)(*pcf))->filesize = ((IFILE *)ocf)->filesize;
318
0
        } else {
319
0
            *pcf = wrap_file(mem, gp_fopen(mem, fname, fmode), fmode);
320
0
        }
321
0
    }
322
323
6.60k
    if (*pcf == NULL) {
324
0
        emprintf1(mem, "Could not open the scratch file %s.\n", fname);
325
0
        return_error(gs_error_invalidfileaccess);
326
0
    }
327
328
6.60k
    return 0;
329
6.60k
}
330
331
static int
332
clist_unlink(const char *fname)
333
0
{
334
0
    clist_file_ptr ocf = fake_path_to_file(fname);
335
0
    if (ocf) {
336
        /* fname is an encoded file pointer. The file will either have been
337
         * created with the delete-on-close option, or already have been
338
         * unlinked. We need only close the FILE */
339
0
        return clist_close_file((IFILE *)ocf) != 0 ? gs_note_error(gs_error_ioerror) : 0;
340
0
    } else {
341
0
        return (unlink(fname) != 0 ? gs_note_error(gs_error_ioerror) : 0);
342
0
    }
343
0
}
344
345
static int
346
clist_fclose(clist_file_ptr cf, const char *fname, bool delete)
347
6.60k
{
348
6.60k
    clist_file_ptr ocf = fake_path_to_file(fname);
349
6.60k
    if (ocf == cf) {
350
        /* fname is an encoded file pointer, and cf is the FILE used to create it.
351
         * We shouldn't close it unless we have been asked to delete it, in which
352
         * case closing it will delete it */
353
6.60k
        return delete ? (clist_close_file((IFILE *)ocf) ? gs_note_error(gs_error_ioerror) : 0) : 0;
354
6.60k
    } else {
355
0
        return (clist_close_file((IFILE *) cf) != 0 ? gs_note_error(gs_error_ioerror) :
356
0
                delete ? clist_unlink(fname) :
357
0
                0);
358
0
    }
359
6.60k
}
360
361
/* ------ Writing ------ */
362
363
#ifdef CLIST_WRITE_SQUEEZING
364
365
static int cls_inited = 0;
366
#define CLS_UNLIMITED ((size_t)-1)
367
static size_t cls_squeezeat = CLS_UNLIMITED;
368
static size_t cls_total = 0;
369
static int cls_dying = 0;
370
static size_t cls_squeezestep = 0;
371
372
#ifndef _WIN32
373
#define CLIST_HAS_FORK
374
#endif
375
376
#ifdef CLIST_HAS_FORK
377
#include <unistd.h>
378
#include <sys/wait.h>
379
#include <time.h>
380
381
/* FIXME: Find some portable way of getting this */
382
/* MacOSX has 10240, Ubuntu seems to have 256 */
383
#ifndef OPEN_MAX
384
#define OPEN_MAX 10240
385
#endif
386
387
/* stashed_map[j] = i means that file descriptor i-1 was duplicated to j */
388
int stashed_map[OPEN_MAX];
389
390
#include <signal.h>
391
392
static void segv_signal(int sig)
393
{
394
    (void)sig;
395
    fprintf(stderr, "SEGV!\n");
396
    exit(1);
397
}
398
#endif
399
400
#endif
401
402
static int
403
clist_fwrite_chars(const void *data, uint len, clist_file_ptr cf)
404
11.2M
{
405
11.2M
    int res = 0;
406
11.2M
    IFILE *icf = (IFILE *)cf;
407
408
#ifdef CLIST_WRITE_SQUEEZING
409
    uint len2;
410
    if (!cls_inited)
411
    {
412
        const char *env = getenv("CLIST_SQUEEZEAT");
413
        if (env)
414
            cls_squeezeat = (size_t)atoi(env);
415
        cls_inited = 1;
416
417
        env = getenv("CLIST_SQUEEZESTEP");
418
        if (env)
419
            cls_squeezestep = (size_t)atoi(env);
420
        if (cls_squeezestep < 0)
421
            cls_squeezestep = 1;
422
    }
423
 continue_squeezing:
424
425
    if (cls_squeezeat != CLS_UNLIMITED)
426
    {
427
        if (cls_total > cls_squeezeat)
428
            return 0;
429
        if (cls_total + len > cls_squeezeat)
430
        {
431
            len2 = cls_squeezeat - cls_total;
432
            if (len2 > 0)
433
            {
434
                res = clist_fwrite_chars(data, len2, cf);
435
                assert(res == len2);
436
                data = (char *)data + len2;
437
                len -= len2;
438
            }
439
440
            /* Now we need to the squeezing thing. */
441
#ifdef CLIST_HAS_FORK
442
            {
443
                int i, pid;
444
445
                /* If we've forked before and we're now in the process of failing,
446
                 * just exit. */
447
                if (cls_dying)
448
                    return 0;
449
450
                /* When we fork below, the child is going to snaffle all our file pointers
451
                 * and potentially corrupt them. Let's make copies of all of them before
452
                 * we fork, so we can restore them when we restart. */
453
                for (i = 0; i < OPEN_MAX; i++) {
454
                    if (stashed_map[i] == 0) {
455
                        int j = dup(i);
456
                        if (j >= 0) {
457
                            stashed_map[j] = i+1;
458
                        }
459
                    }
460
                }
461
462
                pid = fork();
463
                if (pid == 0) {
464
                    fprintf(stderr, "Clist write squeezing: forking at %d\n", (int)cls_total);
465
                    /* Child */
466
                    cls_dying = 1;
467
                    /* Catch any segv and exit neatly */
468
                    signal(SIGSEGV, segv_signal);
469
                    /* Close the dup-licated fds to avoid them getting corrupted by faulty
470
                     * code. */
471
                    for (i = 0; i < OPEN_MAX; i++) {
472
                        if (stashed_map[i] != 0) {
473
                            /* We close duplicated fds, just in case child has some bad
474
                             * code that modifies/closes random fds. */
475
                            close(i);
476
                        }
477
                    }
478
                    /* In the child, we fail. */
479
                    cls_total += len2;
480
                    return len2;
481
                }
482
483
                 /* When do we want it to fail again? */
484
                 if (cls_squeezestep > 0)
485
                     cls_squeezeat += cls_squeezestep;
486
                 else if (cls_squeezestep == 0)
487
                     cls_squeezeat += len;
488
489
                /* Wait for pid to finish, with a timeout. */
490
                {
491
                    struct timespec tm = { 0, 10 * 1000 * 1000 }; /* 10ms = 100th sec */
492
                    int timeout = 30 * 1000 * 1000; /* time out in microseconds! */
493
                    int status;
494
                    while (waitpid(pid, &status, WNOHANG) == 0) {
495
                        nanosleep(&tm, NULL);
496
                        timeout -= (int)(tm.tv_nsec/1000);
497
                        tm.tv_nsec *= 2;
498
                        if (tm.tv_nsec > 999999999)
499
                            tm.tv_nsec = 999999999;
500
                        if (timeout <= 0) {
501
                           char text[32];
502
                            fprintf(stderr, "Child is taking a long time to die. Killing it.\n");
503
                            snprintf(text, sizeof(text), "kill %d", pid);
504
                            system(text);
505
                            break;
506
                       }
507
                    }
508
509
                    if (status != 0) {
510
                        fprintf(stderr, "Child status=%d\n", status);
511
                    }
512
                }
513
514
                /* Put the files back */
515
                for (i = 0; i < OPEN_MAX; i++) {
516
                    if (stashed_map[i] != 0) {
517
                        dup2(i, stashed_map[i]-1);
518
                        close(i);
519
                        stashed_map[i] = 0;
520
                    }
521
                }
522
                fprintf(stderr, "============================================\n");
523
                goto continue_squeezing;
524
            }
525
#else
526
            fprintf(stderr, "Clist write squeezing at %d\n", (int)cls_total);
527
            {
528
#ifdef _WIN32
529
                fprintf(stderr, "Continue with CLIST_SQUEEZEAT=%d\n", (int)cls_total+1);
530
#else
531
                char val[32];
532
                snprintf(val, sizeof(val), "%d", );
533
                setenv("CLIST_SQUEEZEAT", val, 1);
534
#endif
535
            }
536
            cls_total += len2;
537
            return len2;
538
#endif
539
        }
540
        cls_total += len;
541
    }
542
#endif
543
544
11.2M
    if (gp_can_share_fdesc()) {
545
11.2M
        res = gp_fpwrite((char *)data, len, ((IFILE *)cf)->pos, ((IFILE *)cf)->f);
546
11.2M
    } else {
547
0
        res = gp_fwrite(data, 1, len, ((IFILE *)cf)->f);
548
0
    }
549
11.2M
    if (res >= 0)
550
11.2M
        icf->pos += len;
551
11.2M
    icf->filesize = icf->pos; /* write truncates file */
552
11.2M
    if (!CL_CACHE_NEEDS_INIT(icf->cache)) {
553
        /* writing invalidates the read cache */
554
0
        cl_cache_destroy(icf->cache);
555
0
        icf->cache = NULL;
556
0
    }
557
11.2M
    return res;
558
11.2M
}
559
560
/* ------ Reading ------ */
561
562
static int
563
clist_fread_chars(void *data, uint len, clist_file_ptr cf)
564
461M
{
565
461M
    int nread = 0;
566
567
461M
    if (gp_can_share_fdesc()) {
568
461M
        IFILE *icf = (IFILE *)cf;
569
461M
        byte *dp = data;
570
571
        /* if we have a cache, check if it needs init, and do it */
572
461M
        if (CL_CACHE_NEEDS_INIT(icf->cache)) {
573
13.2k
            icf->cache = cl_cache_read_init(icf->cache, CL_CACHE_NSLOTS, 1<<CL_CACHE_SLOT_SIZE_LOG2, icf->filesize);
574
13.2k
        }
575
        /* cl_cache_read_init may have failed, and set cache to NULL, check before using it */
576
461M
        if (icf->cache != NULL) {
577
464M
            do {
578
464M
                int n;
579
580
464M
                if ((n = cl_cache_read(dp, len-nread, icf->pos+nread, icf->cache)) < 0)
581
0
                    break;
582
464M
                if (n == 0) {
583
                    /* pos was not in cache, get a slot and load it, then loop */
584
2.22M
                    CL_CACHE_SLOT *slot = cl_cache_get_empty_slot(icf->cache, icf->pos+nread);  /* cannot fail */
585
2.22M
                    int64_t block_pos = (icf->pos+nread) & ~(icf->cache->block_size - 1);
586
2.22M
                    int fill_len = gp_fpread((char *)(slot->base), icf->cache->block_size, block_pos, icf->f);
587
588
2.22M
                    cl_cache_load_slot(icf->cache, slot, block_pos, slot->base, fill_len);
589
2.22M
                }
590
464M
                nread += n;
591
464M
                dp += n;
592
464M
            } while (nread < len);
593
461M
        } else {
594
             /* no cache -- just do the read */
595
0
            nread = gp_fpread(data, len, icf->pos, icf->f);
596
0
        }
597
461M
        if (nread >= 0)
598
461M
            icf->pos += nread;
599
461M
    } else {
600
0
        gp_file *f = ((IFILE *)cf)->f;
601
0
        byte *str = data;
602
603
        /* The typical implementation of fread */
604
        /* is extremely inefficient for small counts, */
605
        /* so we just use straight-line code instead. */
606
0
        switch (len) {
607
0
            default:
608
0
                return gp_fread(str, 1, len, f);
609
0
            case 8:
610
0
                *str++ = (byte) gp_fgetc(f);
611
0
            case 7:
612
0
                *str++ = (byte) gp_fgetc(f);
613
0
            case 6:
614
0
                *str++ = (byte) gp_fgetc(f);
615
0
            case 5:
616
0
                *str++ = (byte) gp_fgetc(f);
617
0
            case 4:
618
0
                *str++ = (byte) gp_fgetc(f);
619
0
            case 3:
620
0
                *str++ = (byte) gp_fgetc(f);
621
0
            case 2:
622
0
                *str++ = (byte) gp_fgetc(f);
623
0
            case 1:
624
0
                *str = (byte) gp_fgetc(f);
625
0
        }
626
0
        nread = len;
627
0
    }
628
461M
    return nread;
629
461M
}
630
631
/* ------ Position/status ------ */
632
633
static int
634
clist_set_memory_warning(clist_file_ptr cf, int bytes_left)
635
13.2k
{
636
13.2k
    return 0;     /* no-op */
637
13.2k
}
638
639
static int
640
clist_ferror_code(clist_file_ptr cf)
641
37.6M
{
642
37.6M
    return (gp_ferror(((IFILE *)cf)->f) ? gs_error_ioerror : 0);
643
37.6M
}
644
645
static int64_t
646
clist_ftell(clist_file_ptr cf)
647
3.47M
{
648
3.47M
    IFILE *ifile = (IFILE *)cf;
649
650
3.47M
    return gp_can_share_fdesc() ? ifile->pos : gp_ftell(ifile->f);
651
3.47M
}
652
653
static int
654
clist_rewind(clist_file_ptr cf, bool discard_data, const char *fname)
655
657k
{
656
657k
    gp_file *f = ((IFILE *)cf)->f;
657
657k
    IFILE *ocf = fake_path_to_file(fname);
658
657k
    char fmode[4];
659
660
657k
    snprintf(fmode, sizeof(fmode), "w+%s", gp_fmode_binary_suffix);
661
662
657k
    if (ocf) {
663
657k
        if (discard_data) {
664
            /* fname is an encoded ifile pointer. We can use an entirely
665
             * new scratch file. */
666
6.60k
            char tfname[gp_file_name_sizeof] = {0};
667
6.60k
            const gs_memory_t *mem = ocf->f->memory;
668
6.60k
            gp_fclose(ocf->f);
669
6.60k
            ocf->f = gp_open_scratch_file_rm(mem, gp_scratch_file_name_prefix, tfname, fmode);
670
6.60k
            if (ocf->f == NULL)
671
0
                return_error(gs_error_ioerror);
672
            /* if there was a cache, get rid of it an get a new (empty) one */
673
            /* When we start reading, we will allocate a cache based on the filesize */
674
6.60k
            if (ocf->cache != NULL) {
675
6.60k
                cl_cache_destroy(ocf->cache);
676
6.60k
                ocf->cache = cl_cache_alloc(ocf->mem);
677
6.60k
                if (ocf->cache == NULL)
678
0
                    return_error(gs_error_ioerror);
679
6.60k
            }
680
6.60k
            ((IFILE *)cf)->filesize = 0;
681
6.60k
        }
682
657k
        ((IFILE *)cf)->pos = 0;
683
657k
    } else {
684
0
        if (discard_data) {
685
            /*
686
             * The ANSI C stdio specification provides no operation for
687
             * truncating a file at a given position, or even just for
688
             * deleting its contents; we have to use a bizarre workaround to
689
             * get the same effect.
690
             */
691
692
            /* Opening with "w" mode deletes the contents when closing. */
693
0
            f = gp_freopen(fname, gp_fmode_wb, f);
694
0
            if (f == NULL) return_error(gs_error_ioerror);
695
0
            ((IFILE *)cf)->f = gp_freopen(fname, fmode, f);
696
0
            if (((IFILE *)cf)->f == NULL) return_error(gs_error_ioerror);
697
0
            ((IFILE *)cf)->pos = 0;
698
0
            ((IFILE *)cf)->filesize = 0;
699
0
        } else {
700
0
            gp_rewind(f);
701
0
        }
702
0
    }
703
657k
    return 0;
704
657k
}
705
706
static int
707
clist_fseek(clist_file_ptr cf, int64_t offset, int mode, const char *ignore_fname)
708
25.8M
{
709
25.8M
    IFILE *ifile = (IFILE *)cf;
710
25.8M
    int res = 0;
711
712
25.8M
    if (!gp_can_share_fdesc()) {
713
0
        res = gp_fseek(ifile->f, offset, mode);
714
0
    }
715
    /* NB: if gp_can_share_fdesc, we don't actually seek */
716
    /* The following lgtm tag is required because on some platforms
717
     * !gp_can_share_fdesc() is always true, so the value of res is
718
     * known. On other platforms though, this is NOT true. */
719
25.8M
    if (res >= 0) { /* lgtm [cpp/constant-comparison] */
720
        /* Update the ifile->pos */
721
25.8M
        switch (mode) {
722
25.8M
            case SEEK_SET:
723
25.8M
                ifile->pos = offset;
724
25.8M
                break;
725
0
            case SEEK_CUR:
726
0
                ifile->pos += offset;
727
0
                break;
728
0
            case SEEK_END:
729
0
                ifile->pos = ifile->filesize; /* filesize maintained in clist_fwrite */
730
0
                break;
731
25.8M
        }
732
25.8M
    }
733
25.8M
    return res;
734
25.8M
}
735
736
static clist_io_procs_t clist_io_procs_file = {
737
    clist_fopen,
738
    clist_fclose,
739
    clist_unlink,
740
    clist_fwrite_chars,
741
    clist_fread_chars,
742
    clist_set_memory_warning,
743
    clist_ferror_code,
744
    clist_ftell,
745
    clist_rewind,
746
    clist_fseek,
747
};
748
749
init_proc(gs_gxclfile_init);
750
int
751
gs_gxclfile_init(gs_memory_t *mem)
752
185k
{
753
185k
    gs_lib_ctx_core_t *core = mem->gs_lib_ctx->core;
754
185k
#ifdef PACIFY_VALGRIND
755
185k
    VALGRIND_HG_DISABLE_CHECKING(&core->clist_io_procs_file, sizeof(core->clist_io_procs_file));
756
185k
#endif
757
185k
    core->clist_io_procs_file = &clist_io_procs_file;
758
185k
    return 0;
759
185k
}