Coverage Report

Created: 2026-11-12 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/pdf/ghostpdf.c
Line
Count
Source
1
/* Copyright (C) 2018-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
/* Top level PDF access routines */
17
#include "ghostpdf.h"
18
#include "pdf_types.h"
19
#include "pdf_dict.h"
20
#include "pdf_array.h"
21
#include "pdf_int.h"
22
#include "pdf_misc.h"
23
#include "pdf_stack.h"
24
#include "pdf_file.h"
25
#include "pdf_loop_detect.h"
26
#include "pdf_trans.h"
27
#include "pdf_font_types.h"
28
#include "pdf_gstate.h"
29
#include "stream.h"
30
#include "strmio.h"
31
#include "assert_.h"
32
#include "pdf_colour.h"
33
#include "pdf_font.h"
34
#include "pdf_text.h"
35
#include "pdf_page.h"
36
#include "pdf_check.h"
37
#include "pdf_optcontent.h"
38
#include "pdf_sec.h"
39
#include "pdf_doc.h"
40
#include "pdf_repair.h"
41
#include "pdf_xref.h"
42
#include "pdf_device.h"
43
#include "pdf_mark.h"
44
#include "pdf_path.h"
45
46
#include "gsstate.h"        /* For gs_gstate */
47
#include "gsicc_manage.h"  /* For gsicc_init_iccmanager() */
48
49
#if PDFI_LEAK_CHECK
50
#include "gsmchunk.h"
51
#endif
52
53
#ifndef USE_PDF_PERMISSIONS
54
#define USE_PDF_PERMISSIONS 0
55
#endif
56
57
extern const char gp_file_name_list_separator;
58
/*
59
 * Convenience routine to check if a given string exists in a dictionary
60
 * verify its contents and print it in a particular fashion to stdout. This
61
 * is used to display information about the PDF in response to -dPDFINFO
62
 */
63
static int dump_info_string(pdf_context *ctx, pdf_dict *source_dict, const char *Key)
64
0
{
65
0
    int code;
66
0
    pdf_string *s = NULL;
67
0
    char *Cstr;
68
69
0
    code = pdfi_dict_knownget_type(ctx, source_dict, Key, PDF_STRING, (pdf_obj **)&s);
70
0
    if (code > 0) {
71
0
        Cstr = (char *)gs_alloc_bytes(ctx->memory, (size_t)s->length + 1, "Working memory for string dumping");
72
0
        if (Cstr) {
73
0
            memcpy(Cstr, s->data, s->length);
74
0
            Cstr[s->length] = 0x00;
75
0
            outprintf(ctx->memory, "%s: %s\n", Key, Cstr);
76
0
            gs_free_object(ctx->memory, Cstr, "Working memory for string dumping");
77
0
        }
78
0
        code = 0;
79
0
    }
80
0
    pdfi_countdown(s);
81
82
0
    return code;
83
0
}
84
85
static int pdfi_output_metadata(pdf_context *ctx)
86
0
{
87
0
    int code = 0;
88
89
0
    if (ctx->filename != NULL)
90
0
        outprintf(ctx->memory, "\n        %s has %"PRIi64" ", ctx->filename, ctx->num_pages);
91
0
    else
92
0
        outprintf(ctx->memory, "\n        File has %"PRIi64" ", ctx->num_pages);
93
94
0
    if (ctx->num_pages > 1)
95
0
        outprintf(ctx->memory, "pages\n\n");
96
0
    else
97
0
        outprintf(ctx->memory, "page.\n\n");
98
99
0
    if (ctx->Info != NULL) {
100
0
        pdf_name *n = NULL;
101
0
        char *Cstr;
102
103
0
        code = dump_info_string(ctx, ctx->Info, "Title");
104
0
        if (code < 0) {
105
0
            if (ctx->args.pdfstoponerror)
106
0
                return code;
107
0
        }
108
109
0
        code = dump_info_string(ctx, ctx->Info, "Author");
110
0
        if (code < 0) {
111
0
            if (ctx->args.pdfstoponerror)
112
0
                return code;
113
0
        }
114
115
0
        code = dump_info_string(ctx, ctx->Info, "Subject");
116
0
        if (code < 0) {
117
0
            if (ctx->args.pdfstoponerror)
118
0
                return code;
119
0
        }
120
121
0
        code = dump_info_string(ctx, ctx->Info, "Keywords");
122
0
        if (code < 0) {
123
0
            if (ctx->args.pdfstoponerror)
124
0
                return code;
125
0
        }
126
127
0
        code = dump_info_string(ctx, ctx->Info, "Creator");
128
0
        if (code < 0) {
129
0
            if (ctx->args.pdfstoponerror)
130
0
                return code;
131
0
        }
132
133
0
        code = dump_info_string(ctx, ctx->Info, "Producer");
134
0
        if (code < 0) {
135
0
            if (ctx->args.pdfstoponerror)
136
0
                return code;
137
0
        }
138
139
0
        code = dump_info_string(ctx, ctx->Info, "CreationDate");
140
0
        if (code < 0) {
141
0
            if (ctx->args.pdfstoponerror)
142
0
                return code;
143
0
        }
144
145
0
        code = dump_info_string(ctx, ctx->Info, "ModDate");
146
0
        if (code < 0) {
147
0
            if (ctx->args.pdfstoponerror)
148
0
                return code;
149
0
        }
150
151
152
0
        code = pdfi_dict_knownget_type(ctx, ctx->Info, "Trapped", PDF_NAME, (pdf_obj **)&n);
153
0
        if (code > 0) {
154
0
            Cstr = (char *)gs_alloc_bytes(ctx->memory, (size_t)n->length + 1, "Working memory for string dumping");
155
0
            if (Cstr) {
156
0
                memcpy(Cstr, n->data, n->length);
157
0
                Cstr[n->length] = 0x00;
158
0
                outprintf(ctx->memory, "Trapped: %s\n\n", Cstr);
159
0
                gs_free_object(ctx->memory, Cstr, "Working memory for string dumping");
160
0
            }
161
0
            code = 0;
162
0
        }
163
0
        pdfi_countdown(n);
164
0
        n = NULL;
165
0
    }
166
0
    outprintf(ctx->memory, "\n");
167
0
    return code;
168
0
}
169
170
/*
171
 * Convenience routine to check if a given *Box exists in a page dictionary
172
 * verify its contents and print it in a particular fashion to stdout. This
173
 * is used to display information about the PDF in response to -dPDFINFO
174
 */
175
static int pdfi_dump_box(pdf_context *ctx, pdf_dict *page_dict, const char *Key)
176
0
{
177
0
    int code, i;
178
0
    pdf_array *a = NULL;
179
0
    double f;
180
181
0
    code = pdfi_dict_knownget_type(ctx, page_dict, Key, PDF_ARRAY, (pdf_obj **)&a);
182
0
    if (code > 0) {
183
0
        if (pdfi_array_size(a) != 4) {
184
0
            outprintf(ctx->memory, "Error - %s does not contain 4 values.\n", Key);
185
0
            code = gs_note_error(gs_error_rangecheck);
186
0
        } else {
187
0
            outprintf(ctx->memory, " %s: [", Key);
188
0
            for (i = 0; i < pdfi_array_size(a); i++) {
189
0
                code = pdfi_array_get_number(ctx, a, (uint64_t)i, &f);
190
0
                if (i != 0)
191
0
                    outprintf(ctx->memory, " ");
192
0
                if (code == 0) {
193
0
                    if (pdfi_type_of(a->values[i]) == PDF_INT)
194
0
                        outprintf(ctx->memory, "%"PRIi64"", ((pdf_num *)a->values[i])->value.i);
195
0
                    else
196
0
                        outprintf(ctx->memory, "%f", ((pdf_num *)a->values[i])->value.d);
197
0
                } else {
198
0
                    outprintf(ctx->memory, "NAN");
199
0
                }
200
0
            }
201
0
            outprintf(ctx->memory, "]");
202
0
        }
203
0
    }
204
0
    pdfi_countdown(a);
205
0
    return code;
206
0
}
207
208
static int dump_font(pdf_context *ctx, pdf_dict *font_dict, bool space_name)
209
0
{
210
0
    pdf_obj *obj = NULL;
211
0
    char *str = NULL;
212
0
    int len = 0, code = 0, i;
213
0
    bool known = false, type0 = false;
214
215
0
    code = pdfi_dict_get_type(ctx, font_dict, "BaseFont", PDF_NAME, &obj);
216
0
    if (code >= 0) {
217
0
        code = pdfi_string_from_name(ctx, (pdf_name *)obj, &str, &len);
218
0
        if (code >= 0) {
219
0
            outprintf(ctx->memory, "%s", str);
220
0
            if (len < 32 && space_name) {
221
0
                for (i = 0; i < 32 - len;i++)
222
0
                    outprintf(ctx->memory, " ");
223
0
            } else
224
0
                outprintf(ctx->memory, "    ");
225
0
            (void)pdfi_free_string_from_name(ctx, str);
226
0
        }
227
0
        pdfi_countdown(obj);
228
0
        obj = NULL;
229
0
    }
230
231
0
    code = pdfi_dict_get_type(ctx, font_dict, "Subtype", PDF_NAME, &obj);
232
0
    if (code >= 0) {
233
0
        code = pdfi_string_from_name(ctx, (pdf_name *)obj, &str, &len);
234
0
        if (code >= 0) {
235
0
            outprintf(ctx->memory, "%s", str);
236
0
            for (i = 0; i < 16 - len;i++)
237
0
                outprintf(ctx->memory, " ");
238
0
            (void)pdfi_free_string_from_name(ctx, str);
239
0
        }
240
0
        if (pdfi_name_is((pdf_name *)obj, "Type0"))
241
0
            type0 = true;
242
0
        pdfi_countdown(obj);
243
0
        obj = NULL;
244
0
    }
245
246
0
    if (!type0) {
247
0
        code = pdfi_dict_get_type(ctx, font_dict, "Embedded", PDF_BOOL, &obj);
248
0
        if (code >= 0) {
249
0
            if (obj == PDF_FALSE_OBJ)
250
0
                outprintf(ctx->memory, "Not embedded    ");
251
0
            else
252
0
                outprintf(ctx->memory, "Embedded        ");
253
0
            pdfi_countdown(obj);
254
0
            obj = NULL;
255
0
        }
256
0
        else
257
0
            outprintf(ctx->memory, "Not embedded    ");
258
0
    } else
259
0
        outprintf(ctx->memory, "                ");
260
261
0
    code = pdfi_dict_get_type(ctx, font_dict, "ToUnicode", PDF_BOOL, &obj);
262
0
    if (code >= 0) {
263
0
        if (obj == PDF_TRUE_OBJ)
264
0
            outprintf(ctx->memory, "Has ToUnicode    ");
265
0
        else
266
0
            outprintf(ctx->memory, "No ToUnicode     ");
267
0
        pdfi_countdown(obj);
268
0
        obj = NULL;
269
0
    }
270
0
    else
271
0
        outprintf(ctx->memory, "No ToUnicode    ");
272
273
0
    code = pdfi_dict_known(ctx, font_dict, "Descendants", &known);
274
0
    if (code >= 0 && known) {
275
0
        code = pdfi_dict_get_type(ctx, font_dict, "Descendants", PDF_ARRAY, &obj);
276
0
        if (code >= 0) {
277
0
            pdf_obj *desc = NULL;
278
279
0
            code = pdfi_array_get_type(ctx, (pdf_array *)obj, 0, PDF_DICT, &desc);
280
0
            if (code >= 0) {
281
0
                outprintf(ctx->memory, "\n            Descendants: [");
282
0
                (void)dump_font(ctx, (pdf_dict *)desc, false);
283
0
                outprintf(ctx->memory, "]");
284
0
            }
285
0
            pdfi_countdown(obj);
286
0
            obj = NULL;
287
0
        }
288
0
    }
289
0
    return 0;
290
0
}
291
292
/*
293
 * This routine along with pdfi_output_metadtaa above, dumps certain kinds
294
 * of metadata from the PDF file, and from each page in the PDF file. It is
295
 * intended to duplicate the pdf_info.ps functionality of the PostScript-based
296
 * PDF interpreter in Ghostscript.
297
 *
298
 * It is not yet complete, we don't allow an option for dumping media sizes
299
 * we always emit them, and the switches -dDumpFontsNeeded, -dDumpXML,
300
 * -dDumpFontsUsed and -dShowEmbeddedFonts are not implemented at all yet.
301
 */
302
int pdfi_output_page_info(pdf_context *ctx, uint64_t page_num)
303
0
{
304
0
    int code;
305
0
    bool known = false;
306
0
    double f;
307
0
    pdf_dict *page_dict = NULL;
308
0
    pdf_array *fonts_array = NULL, *spots_array = NULL;
309
310
0
    code = pdfi_page_get_dict(ctx, page_num, &page_dict);
311
0
    if (code < 0)
312
0
        return code;
313
314
0
    outprintf(ctx->memory, "Page %"PRIi64"", page_num + 1);
315
316
0
    code = pdfi_dict_knownget_number(ctx, page_dict, "UserUnit", &f);
317
0
    if (code > 0)
318
0
        outprintf(ctx->memory, " UserUnit: %f ", f);
319
0
    if (code < 0) {
320
0
        pdfi_countdown(page_dict);
321
0
        return code;
322
0
    }
323
324
0
    code = pdfi_dump_box(ctx, page_dict, "MediaBox");
325
0
    if (code < 0) {
326
0
        if (code != gs_error_undefined && ctx->args.pdfstoponerror) {
327
0
            pdfi_countdown(page_dict);
328
0
            return code;
329
0
        }
330
0
    }
331
332
0
    code = pdfi_dump_box(ctx, page_dict, "CropBox");
333
0
    if (code < 0) {
334
0
        if (code != gs_error_undefined && ctx->args.pdfstoponerror) {
335
0
            pdfi_countdown(page_dict);
336
0
            return code;
337
0
        }
338
0
    }
339
340
0
    code = pdfi_dump_box(ctx, page_dict, "BleedBox");
341
0
    if (code < 0) {
342
0
        if (code != gs_error_undefined && ctx->args.pdfstoponerror) {
343
0
            pdfi_countdown(page_dict);
344
0
            return code;
345
0
        }
346
0
    }
347
348
0
    code = pdfi_dump_box(ctx, page_dict, "TrimBox");
349
0
    if (code < 0) {
350
0
        if (code != gs_error_undefined && ctx->args.pdfstoponerror) {
351
0
            pdfi_countdown(page_dict);
352
0
            return code;
353
0
        }
354
0
    }
355
356
0
    code = pdfi_dump_box(ctx, page_dict, "ArtBox");
357
0
    if (code < 0) {
358
0
        if (code != gs_error_undefined && ctx->args.pdfstoponerror) {
359
0
            pdfi_countdown(page_dict);
360
0
            return code;
361
0
        }
362
0
    }
363
364
0
    code = pdfi_dict_knownget_number(ctx, page_dict, "Rotate", &f);
365
0
    if (code > 0)
366
0
        outprintf(ctx->memory, "    Rotate = %d ", (int)f);
367
0
    if (code < 0) {
368
0
        pdfi_countdown(page_dict);
369
0
        return code;
370
0
    }
371
372
0
    code = pdfi_check_page(ctx, page_dict, &fonts_array, &spots_array, false);
373
0
    if (code < 0) {
374
0
        if (ctx->args.pdfstoponerror)
375
0
            return code;
376
0
    } else {
377
0
        if (ctx->page.has_transparency)
378
0
            outprintf(ctx->memory, "     Page uses transparency features");
379
0
    }
380
381
0
    code = pdfi_dict_known(ctx, page_dict, "Annots", &known);
382
0
    if (code < 0) {
383
0
        if (code != gs_error_undefined && ctx->args.pdfstoponerror)
384
0
            goto error;
385
0
    } else {
386
0
        if (known == true)
387
0
            outprintf(ctx->memory, "     Page contains Annotations");
388
0
        code = 0;
389
0
    }
390
391
0
    if (spots_array != NULL) {
392
0
        uint64_t index = 0;
393
0
        pdf_name *spot = NULL;
394
0
        char *str = NULL;
395
0
        int len;
396
397
0
        outprintf(ctx->memory, "\n    Page Spot colors: \n");
398
0
        for (index = 0;index < pdfi_array_size(spots_array);index++) {
399
0
            code = pdfi_array_get(ctx, spots_array, index, (pdf_obj **)&spot);
400
0
            if (code >= 0) {
401
0
                if (pdfi_type_of(spot) == PDF_NAME) {
402
0
                    code = pdfi_string_from_name(ctx, spot, &str, &len);
403
0
                    if (code >= 0) {
404
0
                        outprintf(ctx->memory, "        '%s'\n", str);
405
0
                        (void)pdfi_free_string_from_name(ctx, str);
406
0
                    }
407
0
                }
408
0
                pdfi_countdown(spot);
409
0
                spot = NULL;
410
0
            }
411
0
        }
412
0
        code = 0;
413
0
    }
414
415
0
    if (fonts_array != NULL && pdfi_array_size(fonts_array) != 0) {
416
0
        uint64_t index = 0;
417
0
        pdf_dict *font_dict = NULL;
418
419
0
        outprintf(ctx->memory, "\n    Fonts used: \n");
420
0
        for (index = 0;index < pdfi_array_size(fonts_array);index++) {
421
0
            code = pdfi_array_get_type(ctx, fonts_array, index, PDF_DICT, (pdf_obj **)&font_dict);
422
0
            if (code >= 0) {
423
0
                outprintf(ctx->memory, "        ");
424
0
                (void)dump_font(ctx, font_dict, true);
425
0
                outprintf(ctx->memory, "\n");
426
0
                pdfi_countdown(font_dict);
427
0
                font_dict = NULL;
428
0
            }
429
0
        }
430
0
        code = 0;
431
0
    }
432
433
0
error:
434
0
    pdfi_countdown(fonts_array);
435
0
    pdfi_countdown(spots_array);
436
0
    outprintf(ctx->memory, "\n\n");
437
0
    pdfi_countdown(page_dict);
438
439
0
    return code;
440
0
}
441
442
/* Error and warning string tables. There should be a string for each error and warning
443
 * defined in the error (pdf_error_e) and warning (pdf_warning_e) enumerators. Having
444
 * more strings is harmless, having too few may cause crashes. These need to be kept in sync.
445
 *
446
 * The Ghostscript graphics library errors should be kept up to date, but this is less critical
447
 * if the error code is greater than the last error we know about we just print a generic
448
 * 'unknown' message.
449
 */
450
const char *pdf_error_strings[] = {
451
#define PARAM(A,B) B
452
#include "pdf_errors.h"
453
    ""                               /* last error, should not be used */
454
};
455
456
const char *pdf_warning_strings[] = {
457
#define PARAM(A,B) B
458
#include "pdf_warnings.h"
459
    ""                               /* Last warning should not be used */
460
};
461
462
const char *gs_error_strings[] = {
463
    "no error",
464
    "unknownerror",
465
    "dictfull",
466
    "dictstackoverflow",
467
    "dictstackunderflow",
468
    "execstackoverflow",
469
    "interrupt",
470
    "invalidaccess",
471
    "invalidexit",
472
    "invalidfileaccess",
473
    "invalidfont",
474
    "invalidrestore",
475
    "ioerror",
476
    "limitcheck",
477
    "nocurrentpoint",
478
    "rangecheck",
479
    "stackoverflow",
480
    "stackunderflow",
481
    "syntaxerror",
482
    "timeout",
483
    "typecheck",
484
    "undefined",
485
    "undefinedfilename",
486
    "undefinedresult",
487
    "unmatchedmark",
488
    "VMerror",
489
    "configurationerror",
490
    "undefinedresource",
491
    "unregistered",
492
    "invalidcontext",
493
    "invalidid",
494
    "pdf_stackoverflow",
495
    "circular reference"
496
};
497
498
const char *gs_internal_error_strings[] = {
499
    "error hit",
500
    "fatal error",
501
    "quit",
502
    "interpreter exit",
503
    "remap color",
504
    "exec stack underflow",
505
    "VMreclaim",
506
    "Need input",
507
    "need file",
508
    "No defined error",
509
    "No defined error (2)",
510
    "error info",
511
    "handled",
512
};
513
0
#define LASTNORMALGSERROR gs_error_circular_reference * -1
514
0
#define FIRSTINTERNALERROR gs_error_hit_detected * -1
515
0
#define LASTGSERROR gs_error_handled * -1
516
517
void pdfi_verbose_error(pdf_context *ctx, int gs_error, const char *gs_lib_function, int pdfi_error, const char *pdfi_function_name, const char *extra_info, const char *file_line)
518
0
{
519
0
    char fallback[] = "unknown graphics library error";
520
521
0
    if (ctx->args.verbose_errors && !ctx->args.QUIET) {
522
0
        if (gs_error != 0) {
523
0
            char *error_string;
524
0
            unsigned int code = gs_error * -1;
525
526
0
            if (code > LASTGSERROR)
527
0
                error_string = fallback;
528
0
            else {
529
0
                if (code > LASTNORMALGSERROR) {
530
0
                    if (code < FIRSTINTERNALERROR)
531
0
                        error_string = fallback;
532
0
                    else
533
0
                        error_string = (char *)gs_internal_error_strings[code - FIRSTINTERNALERROR];
534
0
                } else
535
0
                    error_string = (char *)gs_error_strings[code];
536
0
            }
537
0
            errprintf(ctx->memory, "Graphics library error %d (%s) in function '%s'", gs_error, error_string, pdfi_function_name);
538
0
            if (gs_lib_function != NULL)
539
0
                errprintf(ctx->memory, " from lib routine '%s'", gs_lib_function);
540
541
#if DEBUG_FILE_LINE==1
542
            if (file_line != NULL)
543
                errprintf(ctx->memory, "%s'.\n", file_line);
544
            else
545
                errprintf(ctx->memory, ".\n");
546
#else
547
0
            errprintf(ctx->memory, ".\n");
548
0
#endif
549
550
0
            if (pdfi_error != 0)
551
0
                errprintf(ctx->memory, "\tSetting pdfi error %d - %s.\n", pdfi_error, pdf_error_strings[pdfi_error]);
552
0
            if (extra_info != NULL)
553
0
                errprintf(ctx->memory, "\t%s\n", extra_info);
554
0
        } else {
555
0
            if (pdfi_error != 0) {
556
#if DEBUG_FILE_LINE==1
557
                if (file_line != NULL)
558
                    errprintf(ctx->memory, "Function '%s' %s set pdfi error %d - %s.\n", pdfi_function_name, file_line, pdfi_error, pdf_error_strings[pdfi_error]);
559
                else
560
                    errprintf(ctx->memory, "Function '%s' set pdfi error %d - %s.\n", pdfi_function_name, pdfi_error, pdf_error_strings[pdfi_error]);
561
#else
562
0
                errprintf(ctx->memory, "Function '%s' set pdfi error %d - %s.\n", pdfi_function_name, pdfi_error, pdf_error_strings[pdfi_error]);
563
0
#endif
564
0
                if (extra_info != NULL)
565
0
                    errprintf(ctx->memory, "\t%s\n", extra_info);
566
0
            } else {
567
0
                if (extra_info != NULL)
568
0
                    errprintf(ctx->memory, "%s\n", extra_info);
569
0
            }
570
0
        }
571
0
    }
572
0
}
573
574
void pdfi_verbose_warning(pdf_context *ctx, int gs_error, const char *gs_lib_function, int pdfi_warning, const char *pdfi_function_name, const char *extra_info, const char *file_line)
575
0
{
576
0
    char fallback[] = "unknown graphics library error";
577
578
0
    if (ctx->args.verbose_warnings && !ctx->args.QUIET) {
579
0
        if (gs_error != 0) {
580
0
            char *error_string;
581
0
            unsigned int code = gs_error * -1;
582
583
0
            if (code > LASTGSERROR)
584
0
                error_string = fallback;
585
0
            else {
586
0
                if (code > LASTNORMALGSERROR) {
587
0
                    if (code < FIRSTINTERNALERROR)
588
0
                        error_string = fallback;
589
0
                    else
590
0
                        error_string = (char *)gs_internal_error_strings[code - FIRSTINTERNALERROR];
591
0
                } else
592
0
                    error_string = (char *)gs_error_strings[code];
593
0
            }
594
0
            outprintf(ctx->memory, "Graphics library error %d (%s) in function '%s'", gs_error, error_string, pdfi_function_name);
595
0
            if (gs_lib_function != NULL)
596
0
                outprintf(ctx->memory, " from lib routine '%s'.\n", gs_lib_function);
597
598
#if DEBUG_FILE_LINE==1
599
            if (file_line != NULL)
600
                errprintf(ctx->memory, "%s'.\n", file_line);
601
            else
602
                errprintf(ctx->memory, ".\n");
603
#else
604
0
            errprintf(ctx->memory, ".\n");
605
0
#endif
606
0
            if (pdfi_warning != 0)
607
0
                outprintf(ctx->memory, "\tsetting pdfi warning %d - %s.\n", pdfi_warning, pdf_warning_strings[pdfi_warning]);
608
0
            if (extra_info != NULL)
609
0
                outprintf(ctx->memory, "\t%s\n", extra_info);
610
0
        } else {
611
0
            if (pdfi_warning != 0) {
612
#if DEBUG_FILE_LINE==1
613
                if (file_line != NULL)
614
                    outprintf(ctx->memory, "Function '%s' %s set pdfi warning %d - %s.\n", pdfi_function_name, file_line, pdfi_warning, pdf_warning_strings[pdfi_warning]);
615
                else
616
                    outprintf(ctx->memory, "Function '%s' set pdfi warning %d - %s.\n", pdfi_function_name, pdfi_warning, pdf_warning_strings[pdfi_warning]);
617
#else
618
0
                outprintf(ctx->memory, "Function '%s' set pdfi warning %d - %s.\n", pdfi_function_name, pdfi_warning, pdf_warning_strings[pdfi_warning]);
619
0
#endif
620
0
                if (extra_info != NULL)
621
0
                    errprintf(ctx->memory, "\t%s\n", extra_info);
622
0
            } else {
623
0
                if (extra_info != NULL)
624
0
                    errprintf(ctx->memory, "\t%s\n", extra_info);
625
0
            }
626
0
        }
627
0
    }
628
0
}
629
630
int pdfi_set_error_var(pdf_context *ctx, int gs_error, const char *gs_lib_function, pdf_error pdfi_error, const char *pdfi_function_name, const char *fmt, ...)
631
37.9k
{
632
37.9k
    if (pdfi_error != 0)
633
37.9k
        ctx->pdf_errors[pdfi_error / (sizeof(char) * 8)] |= 1 << pdfi_error % (sizeof(char) * 8);
634
37.9k
    if (ctx->args.verbose_errors) {
635
0
        char extra_info[gp_file_name_sizeof];
636
0
        va_list args;
637
638
0
        va_start(args, fmt);
639
0
        (void)vsnprintf(extra_info, sizeof(extra_info), fmt, args);
640
0
        va_end(args);
641
642
0
        pdfi_verbose_error(ctx, gs_error, gs_lib_function, pdfi_error, pdfi_function_name, extra_info, NULL);
643
0
    }
644
37.9k
    if (ctx->args.pdfstoponerror) {
645
0
        if (gs_error < 0)
646
0
            return gs_error;
647
0
        else
648
0
            return gs_error_unknownerror;
649
0
    }
650
37.9k
    return 0;
651
37.9k
}
652
653
int pdfi_set_warning_var(pdf_context *ctx, int gs_error, const char *gs_lib_function, pdf_warning pdfi_warning, const char *pdfi_function_name, const char *fmt, ...)
654
1.78M
{
655
1.78M
    ctx->pdf_warnings[pdfi_warning / (sizeof(char) * 8)] |= 1 << pdfi_warning % (sizeof(char) * 8);
656
1.78M
    if (ctx->args.verbose_warnings) {
657
0
        char extra_info[gp_file_name_sizeof];
658
0
        va_list args;
659
660
0
        va_start(args, fmt);
661
0
        (void)vsnprintf(extra_info, sizeof(extra_info), fmt, args);
662
0
        va_end(args);
663
664
0
        pdfi_verbose_warning(ctx, gs_error, gs_lib_function, pdfi_warning, pdfi_function_name, extra_info, NULL);
665
0
    }
666
1.78M
    if (ctx->args.pdfstoponwarning) {
667
0
        if (gs_error < 0)
668
0
            return gs_error;
669
0
        else
670
0
            return gs_error_unknownerror;
671
0
    }
672
1.78M
    return 0;
673
1.78M
}
674
675
void
676
pdfi_report_errors(pdf_context *ctx)
677
67.7k
{
678
67.7k
    int code, i, j;
679
67.7k
    bool warnings_exist = false, errors_exist = false;
680
681
67.7k
    if (ctx->args.QUIET)
682
67.7k
        return;
683
684
0
    for (i = 0; i < PDF_ERROR_BYTE_SIZE; i++) {
685
0
        if (ctx->pdf_errors[i] != 0)
686
0
            errors_exist = true;
687
0
    }
688
689
0
    for (i = 0; i < PDF_WARNING_BYTE_SIZE; i++) {
690
0
        if (ctx->pdf_warnings[i] != 0)
691
0
            warnings_exist = true;
692
0
    }
693
694
0
    if (!errors_exist && !warnings_exist)
695
0
        return;
696
697
0
    if (errors_exist)
698
0
    {
699
0
        errprintf(ctx->memory, "\nThe following errors were encountered at least once while processing this file:\n");
700
0
        for (i = 0; i < PDF_ERROR_BYTE_SIZE; i++) {
701
0
            if (ctx->pdf_errors[i] != 0) {
702
0
                for (j=0;j < sizeof(char) * 8; j++) {
703
0
                    if (ctx->pdf_errors[i] & 1 << j) {
704
0
                        int error_num = (i * sizeof(char) * 8) + j;
705
706
                        /* Bits higher than E_PDF_MAX_ERROR - 1 in pdf_errors should never be set, but just in case */
707
0
                        assert(error_num < E_PDF_MAX_ERROR);
708
0
                        if (error_num < E_PDF_MAX_ERROR)
709
0
                            errprintf(ctx->memory, "\t%s\n", pdf_error_strings[error_num]);
710
0
                    }
711
0
                }
712
0
            }
713
0
        }
714
0
    }
715
716
0
    if (warnings_exist)
717
0
    {
718
0
        outprintf(ctx->memory, "\nThe following warnings were encountered at least once while processing this file:\n");
719
0
        for (i = 0; i < PDF_WARNING_BYTE_SIZE; i++) {
720
0
            if (ctx->pdf_warnings[i] != 0) {
721
0
                for (j=0;j < sizeof(char) * 8; j++) {
722
0
                    if (ctx->pdf_warnings[i] & 1 << j) {
723
0
                        int warning_num = (i * sizeof(char) * 8) + j;
724
725
                        /* Bits higher than W_PDF_MAX_WARNING - 1 in pdf_warnings should never be set, but just in case */
726
0
                        assert(warning_num < W_PDF_MAX_WARNING);
727
0
                        if (warning_num < W_PDF_MAX_WARNING)
728
0
                            outprintf(ctx->memory, "\t%s\n", pdf_warning_strings[warning_num]);
729
0
                    }
730
0
                }
731
0
            }
732
0
        }
733
0
    }
734
735
0
    if (errors_exist)
736
0
        errprintf(ctx->memory, "\n   **** This file had errors that were repaired or ignored.\n");
737
0
    else {
738
0
        if (warnings_exist)
739
0
            outprintf(ctx->memory, "\n   **** This file had errors that were repaired or ignored.\n");
740
0
    }
741
0
    if (ctx->Info) {
742
0
        pdf_string *s = NULL;
743
744
0
        code = pdfi_dict_knownget_type(ctx, ctx->Info, "Producer", PDF_STRING, (pdf_obj **)&s);
745
0
        if (code > 0) {
746
0
            char *cs;
747
748
0
            cs = (char *)gs_alloc_bytes(ctx->memory, (size_t)s->length + 1, "temporary string for error report");
749
0
            if (cs == NULL) {
750
0
                errprintf(ctx->memory, "   **** Out of memory while trying to display Producer ****\n");
751
0
            } else {
752
0
                memcpy(cs, s->data, s->length);
753
0
                cs[s->length] = 0x00;
754
0
                if (errors_exist)
755
0
                    errprintf(ctx->memory, "   **** The file was produced by: \n   **** >>>> %s <<<<\n", cs);
756
0
                else {
757
0
                    if (warnings_exist)
758
0
                    outprintf(ctx->memory, "   **** The file was produced by: \n   **** >>>> %s <<<<\n", cs);
759
0
                }
760
0
                gs_free_object(ctx->memory, cs, "temporary string for error report");
761
0
            }
762
0
        }
763
0
        pdfi_countdown(s);
764
0
    }
765
0
    if (errors_exist) {
766
0
        errprintf(ctx->memory, "   **** Please notify the author of the software that produced this\n");
767
0
        errprintf(ctx->memory, "   **** file that it does not conform to Adobe's published PDF\n");
768
0
        errprintf(ctx->memory, "   **** specification.\n\n");
769
0
    } else {
770
0
        outprintf(ctx->memory, "   **** Please notify the author of the software that produced this\n");
771
0
        outprintf(ctx->memory, "   **** file that it does not conform to Adobe's published PDF\n");
772
0
        outprintf(ctx->memory, "   **** specification.\n\n");
773
0
    }
774
0
}
775
776
/* Name table
777
 * I've been trying to avoid this for as long as possible, but it seems it cannot
778
 * be evaded. We need functions to get an index for a given string (which will
779
 * add the string to the table if its not present) and to cleear up the table
780
 * on finishing a PDF file.
781
 */
782
783
int pdfi_get_name_index(pdf_context *ctx, char *name, int len, unsigned int *returned)
784
40.0k
{
785
40.0k
    pdfi_name_entry_t *e = NULL, *last_entry = NULL, *new_entry = NULL;
786
40.0k
    int index = 0;
787
788
40.0k
    if (ctx->name_table == NULL) {
789
1.70k
        e = NULL;
790
38.3k
    } else {
791
38.3k
        e = ctx->name_table;
792
38.3k
    }
793
794
144k
    while(e != NULL) {
795
141k
        if (e->len == len) {
796
80.2k
            if (memcmp(e->name, name, e->len) == 0) {
797
37.2k
                *returned = e->index;
798
37.2k
                return 0;
799
37.2k
            }
800
80.2k
        }
801
104k
        last_entry = e;
802
104k
        index = e->index;
803
104k
        e = e->next;
804
104k
    }
805
806
2.78k
    new_entry = (pdfi_name_entry_t *)gs_alloc_bytes(ctx->memory, sizeof(pdfi_name_entry_t), "Alloc name table entry");
807
2.78k
    if (new_entry == NULL)
808
0
        return_error(gs_error_VMerror);
809
2.78k
    memset(new_entry, 0x00, sizeof(pdfi_name_entry_t));
810
2.78k
    new_entry->name = (char *)gs_alloc_bytes(ctx->memory, (size_t)len+1, "Alloc name table name");
811
2.78k
    if (new_entry->name == NULL) {
812
0
        gs_free_object(ctx->memory, new_entry, "Failed to allocate name entry");
813
0
            return_error(gs_error_VMerror);
814
0
    }
815
2.78k
    memset(new_entry->name, 0x00, len+1);
816
2.78k
    memcpy(new_entry->name, name, len);
817
2.78k
    new_entry->len = len;
818
2.78k
    new_entry->index = ++index;
819
820
2.78k
    if (last_entry)
821
1.08k
        last_entry->next = new_entry;
822
1.70k
    else
823
1.70k
        ctx->name_table = new_entry;
824
825
2.78k
    *returned = new_entry->index;
826
2.78k
    return 0;
827
2.78k
}
828
829
static int pdfi_free_name_table(pdf_context *ctx)
830
104k
{
831
104k
    if (ctx->name_table) {
832
1.70k
        pdfi_name_entry_t *next = NULL, *e = (pdfi_name_entry_t *)ctx->name_table;
833
834
4.48k
        while (e != NULL) {
835
2.78k
            next = (pdfi_name_entry_t *)e->next;
836
2.78k
            gs_free_object(ctx->memory, e->name, "free name table entries");
837
2.78k
            gs_free_object(ctx->memory, e, "free name table entries");
838
2.78k
            e = next;
839
2.78k
        }
840
1.70k
    }
841
104k
    ctx->name_table = NULL;
842
104k
    return 0;
843
104k
}
844
845
int pdfi_name_from_index(pdf_context *ctx, int index, unsigned char **name, unsigned int *len)
846
3.86k
{
847
3.86k
    pdfi_name_entry_t *e = (pdfi_name_entry_t *)ctx->name_table;
848
849
55.3k
    while (e != NULL) {
850
55.3k
        if (e->index == index) {
851
3.86k
            *name = (unsigned char *)e->name;
852
3.86k
            *len = e->len;
853
3.86k
            return 0;
854
3.86k
        }
855
51.4k
        e = e->next;
856
51.4k
    }
857
858
3.86k
    return_error(gs_error_undefined);
859
3.86k
}
860
861
int pdfi_separation_name_from_index(gs_gstate *pgs, gs_separation_name index, unsigned char **name, unsigned int *len)
862
4.17k
{
863
4.17k
    pdfi_int_gstate *igs = (pdfi_int_gstate *)pgs->client_data;
864
4.17k
    pdf_context *ctx = NULL;
865
4.17k
    pdfi_name_entry_t *e = NULL;
866
867
4.17k
    if (igs == NULL)
868
0
        return_error(gs_error_undefined);
869
870
4.17k
    ctx = igs->ctx;
871
4.17k
    if (ctx == NULL)
872
0
        return_error(gs_error_undefined);
873
874
4.17k
    e = (pdfi_name_entry_t *)ctx->name_table;
875
876
4.17k
    while (e != NULL) {
877
4.17k
        if (e->index == index) {
878
4.17k
            *name = (unsigned char *)e->name;
879
4.17k
            *len = e->len;
880
4.17k
            return 0;
881
4.17k
        }
882
0
        e = e->next;
883
0
    }
884
885
4.17k
    return_error(gs_error_undefined);
886
4.17k
}
887
888
int pdfi_finish_pdf_file(pdf_context *ctx)
889
67.2k
{
890
67.2k
    if (ctx->Root) {
891
67.2k
        if (ctx->device_state.writepdfmarks && ctx->device_state.WantsOptionalContent) {
892
3.50k
            pdf_obj *o = NULL;
893
3.50k
            int code = 0;
894
895
3.50k
            code = pdfi_dict_knownget_type(ctx, ctx->Root, "OCProperties", PDF_DICT, &o);
896
3.50k
            if (code > 0) {
897
                /* Build and send the OCProperties structure */
898
106
                code = pdfi_pdfmark_from_objarray(ctx, &o, 1, NULL, "OCProperties");
899
106
                pdfi_countdown(o);
900
106
                if (code < 0)
901
30
                {
902
                    /* Error message ? */
903
30
                }
904
106
            }
905
3.50k
        }
906
67.2k
    }
907
67.2k
    return 0;
908
67.2k
}
909
910
int pdfi_close_pdf_file(pdf_context *ctx)
911
478
{
912
478
    if (ctx->Root) {
913
164
        if (ctx->device_state.writepdfmarks && ctx->device_state.WantsOptionalContent) {
914
0
            pdf_obj *o = NULL;
915
0
            int code = 0;
916
917
0
            code = pdfi_dict_knownget(ctx, ctx->Root, "OCProperties", &o);
918
0
            if (code > 0) {
919
                /* Build and send the OCProperties structure */
920
0
                code = pdfi_pdfmark_from_objarray(ctx, &o, 1, NULL, "OCProperties");
921
0
                pdfi_countdown(o);
922
0
                if (code < 0)
923
0
                {
924
                    /* Error message ? */
925
0
                }
926
0
            }
927
0
        }
928
164
    }
929
930
478
    if (ctx->main_stream) {
931
478
        if (ctx->main_stream->s) {
932
478
            sfclose(ctx->main_stream->s);
933
478
        }
934
478
        gs_free_object(ctx->memory, ctx->main_stream, "Closing main PDF file");
935
478
        ctx->main_stream = NULL;
936
478
    }
937
478
    ctx->main_stream_length = 0;
938
939
478
    if (ctx->filename) {
940
478
        gs_free_object(ctx->memory, ctx->filename, "pdfi_close_pdf_file, free copy of filename");
941
478
        ctx->filename = NULL;
942
478
    }
943
944
478
    pdfi_clear_context(ctx);
945
478
    return 0;
946
478
}
947
948
static int pdfi_process(pdf_context *ctx)
949
164
{
950
164
    int code = 0, i;
951
952
    /* Loop over each page and either render it or output the
953
     * required information.
954
     */
955
379
    for (i=0;i < ctx->num_pages;i++) {
956
215
        if (ctx->args.first_page != 0) {
957
0
            if (i < ctx->args.first_page - 1)
958
0
                continue;
959
0
        }
960
215
        if (ctx->args.last_page != 0) {
961
0
            if (i > ctx->args.last_page - 1)
962
0
                break;
963
0
        }
964
215
        if (ctx->args.pdfinfo)
965
0
            code = pdfi_output_page_info(ctx, i);
966
215
        else
967
215
            code = pdfi_page_render(ctx, i, true);
968
969
215
        if (code < 0)
970
48
            code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_GS_LIB_ERROR, "pdfi_process", NULL);
971
215
    }
972
164
    pdfi_report_errors(ctx);
973
974
164
    return code;
975
164
}
976
977
/* This works by reading each embedded file referenced by the collection. If it
978
 * has a MIME type indicating it's a PDF file, or somewhere in the first 2KB it
979
 * has the PDF header (%PDF-) then we treat it as a PDF file. We read the contents
980
 * of the refrenced stream and write them to disk in a scratch file.
981
 *
982
 * We then process each scratch file in turn. Note that we actually return an
983
 * array of strings; the first string is the temporary filename, the second is
984
 * the entry from the names tree. Since this can be in UTF16-BE format, it can
985
 * contain embedded single byte NULL characters, so we can't use a regular C
986
 * string. Instead we use a triple byte NULL termination.
987
 *
988
 * It ought to be possible to do all the processing without creating scratch files, by saving the
989
 * current file state, and opening a new 'file' on the stream in the original PDF
990
 * file. But I couldn't immediately get that to work.
991
 * So this is a FIXME future enhancement.
992
 */
993
int pdfi_prep_collection(pdf_context *ctx, uint64_t *TotalFiles, char ***names_array)
994
0
{
995
0
    int code = 0, i, NumEmbeddedFiles = 0;
996
0
    pdf_obj *Names = NULL, *EmbeddedFiles = NULL;
997
0
    pdf_array *FileNames = NULL;
998
0
    pdf_obj *EF = NULL, *F = NULL;
999
0
    char **working_array = NULL;
1000
1001
0
    if (pdfi_dict_knownget_type(ctx, ctx->Root, "Names", PDF_DICT, &Names) > 0) {
1002
0
        if(pdfi_dict_knownget_type(ctx, (pdf_dict *)Names, "EmbeddedFiles", PDF_DICT, &EmbeddedFiles) > 0) {
1003
0
            if (pdfi_dict_knownget_type(ctx, (pdf_dict *)EmbeddedFiles, "Names", PDF_ARRAY, (pdf_obj **)&FileNames) > 0) {
1004
0
                int ix = 0, index = 0;
1005
0
                gp_file *scratch_file = NULL;
1006
0
                char scratch_name[gp_file_name_sizeof];
1007
1008
0
                NumEmbeddedFiles = pdfi_array_size(FileNames) / 2;
1009
1010
0
                working_array = (char **)gs_alloc_bytes(ctx->memory, (size_t)NumEmbeddedFiles * 2 * sizeof(char *), "Collection file working names array");
1011
0
                if (working_array == NULL) {
1012
0
                    code = gs_note_error(gs_error_VMerror);
1013
0
                    goto exit;
1014
0
                }
1015
0
                memset(working_array, 0x00, NumEmbeddedFiles * 2 * sizeof(char *));
1016
1017
0
                for (ix = 0;ix < NumEmbeddedFiles;ix++) {
1018
0
                    pdf_obj *File = NULL;
1019
0
                    pdf_obj *Subtype = NULL;
1020
1021
0
                    code = pdfi_array_get(ctx, FileNames, (ix * 2) + 1, &File);
1022
0
                    if (code < 0)
1023
0
                        goto exit;
1024
1025
0
                    if (pdfi_type_of(File) == PDF_DICT) {
1026
0
                        if (pdfi_dict_knownget_type(ctx, (pdf_dict *)File, "EF", PDF_DICT, &EF) > 0) {
1027
0
                            if (pdfi_dict_knownget_type(ctx, (pdf_dict *)EF, "F", PDF_STREAM, &F) > 0) {
1028
0
                                pdf_dict *stream_dict = NULL;
1029
0
                                pdf_c_stream *s = NULL;
1030
1031
                                /* pdfi_dict_from_object does not increment the reference count of the stream dictionary
1032
                                 * so we do not need to count it down later.
1033
                                 */
1034
0
                                code = pdfi_dict_from_obj(ctx, F, &stream_dict);
1035
0
                                if (code >= 0) {
1036
0
                                    if (pdfi_dict_knownget_type(ctx, stream_dict, "Subtype", PDF_NAME, &Subtype) <= 0) {
1037
                                        /* No Subtype, (or not a name) we can't check the Mime type, so try to read the first 2Kb
1038
                                         * and look for a %PDF- in that. If not present, assume its not a PDF
1039
                                         */
1040
0
                                        code = pdfi_seek(ctx, ctx->main_stream, pdfi_stream_offset(ctx, (pdf_stream *)F), SEEK_SET);
1041
0
                                        if (code >= 0) {
1042
0
                                            code = pdfi_filter(ctx, (pdf_stream *)F, ctx->main_stream, &s, false);
1043
0
                                            if (code >= 0) {
1044
0
                                                char Buffer[2048];
1045
0
                                                int bytes;
1046
1047
0
                                                bytes = pdfi_read_bytes(ctx, (byte *)Buffer, 1, 2047, s);
1048
0
                                                pdfi_close_file(ctx, s);
1049
0
                                                s = NULL;
1050
                                                /* Assertion; the smallest real PDF file is at least 400 bytes */
1051
0
                                                if (bytes >= 400) {
1052
0
                                                    Buffer[bytes] = 0x00;
1053
0
                                                    if (strstr(Buffer, "%PDF-") == NULL)
1054
0
                                                        code = -1;
1055
0
                                                } else
1056
0
                                                    code = -1;
1057
0
                                            }
1058
0
                                        }
1059
0
                                    } else {
1060
0
                                        if (!pdfi_name_is((const pdf_name *)Subtype, "application/pdf"))
1061
0
                                            code = -1;
1062
0
                                    }
1063
1064
0
                                    if (code >= 0) {
1065
                                        /* Appears to be a PDF file. Create a scratch file to hold it, and then
1066
                                         * read the file from the PDF, and write it to the scratch file. Record
1067
                                         * the scratch filename in the working_array for later processing.
1068
                                         */
1069
0
                                        scratch_file = gp_open_scratch_file(ctx->memory, "gpdf-collection-", scratch_name, "wb");
1070
0
                                        if (scratch_file != NULL) {
1071
0
                                            code = pdfi_seek(ctx, ctx->main_stream, pdfi_stream_offset(ctx, (pdf_stream *)F), SEEK_SET);
1072
0
                                            if (code >= 0) {
1073
0
                                                double L;
1074
0
                                                pdf_c_stream *SubFile_stream = NULL;
1075
1076
                                                /* Start by setting up the file to be read. Apply a SubFileDecode so that, if the input stream
1077
                                                 * is not compressed we will stop reading when we get to the end of the stream.
1078
                                                 */
1079
0
                                                if (pdfi_dict_knownget_number(ctx, stream_dict, "Length", &L) > 0) {
1080
1081
0
                                                    code = pdfi_apply_SubFileDecode_filter(ctx, (int)L, NULL, ctx->main_stream, &SubFile_stream, false);
1082
0
                                                    if (code >= 0)
1083
0
                                                        code = pdfi_filter(ctx, (pdf_stream *)F, SubFile_stream, &s, false);
1084
0
                                                } else
1085
0
                                                    code = pdfi_filter(ctx, (pdf_stream *)F, ctx->main_stream, &s, false);
1086
1087
0
                                                if (code >= 0) {
1088
0
                                                    char Buffer[2048];
1089
0
                                                    int bytes;
1090
0
                                                    pdf_string *Name = NULL;
1091
1092
                                                    /* Read the stream contents and write them to the scratch file */
1093
0
                                                    do {
1094
0
                                                        bytes = pdfi_read_bytes(ctx, (byte *)Buffer, 1, 2048, s);
1095
0
                                                        (void)gp_fwrite(Buffer, 1, bytes, scratch_file);
1096
0
                                                    } while (bytes > 0);
1097
1098
                                                    /* Create an entry for the Description in the names array */
1099
0
                                                    code = pdfi_array_get(ctx, FileNames, ix * 2, (pdf_obj **)&Name);
1100
0
                                                    if (code >= 0) {
1101
0
                                                        if (pdfi_type_of((pdf_obj *)Name) == PDF_STRING) {
1102
0
                                                            working_array[(index * 2) + 1] = (char *)gs_alloc_bytes(ctx->memory, (size_t)Name->length + 3, "Collection file names array entry");
1103
0
                                                            if (working_array[(index * 2) + 1] != NULL) {
1104
0
                                                                memset(working_array[(index * 2) + 1], 0x00, Name->length + 3);
1105
0
                                                                memcpy(working_array[(index * 2) + 1], Name->data, Name->length);
1106
0
                                                            }
1107
0
                                                        }
1108
0
                                                        pdfi_countdown(Name);
1109
0
                                                        Name = NULL;
1110
0
                                                    }
1111
1112
                                                    /* And now the scratch file name */
1113
0
                                                    working_array[index * 2] = (char *)gs_alloc_bytes(ctx->memory, (size_t)strlen(scratch_name) + 3, "Collection file names array entry");
1114
0
                                                    if (working_array[index * 2] != NULL) {
1115
0
                                                        memset(working_array[index * 2], 0x00, strlen(scratch_name) + 3);
1116
0
                                                        strcpy(working_array[index * 2], scratch_name);
1117
0
                                                    }
1118
1119
0
                                                    index++;
1120
0
                                                    (*TotalFiles)++;
1121
0
                                                    pdfi_close_file(ctx, s);
1122
0
                                                    s = NULL;
1123
0
                                                }
1124
0
                                                if (SubFile_stream != NULL)
1125
0
                                                    pdfi_close_file(ctx, SubFile_stream);
1126
0
                                                SubFile_stream = NULL;
1127
0
                                            }
1128
0
                                            gp_fclose(scratch_file);
1129
0
                                        } else
1130
0
                                            errprintf(ctx->memory, "\n   **** Warning: Failed to open a scratch file.\n");
1131
0
                                    }
1132
0
                                }
1133
0
                            }
1134
0
                        }
1135
0
                    }
1136
0
                    pdfi_countdown(Subtype);
1137
0
                    Subtype = NULL;
1138
0
                    pdfi_countdown(F);
1139
0
                    F = NULL;
1140
0
                    pdfi_countdown(EF);
1141
0
                    EF = NULL;
1142
0
                    pdfi_countdown(File);
1143
0
                    File = NULL;
1144
0
                }
1145
0
            } else {
1146
0
                errprintf(ctx->memory, "\n   **** Warning: Failed to read EmbeededFiles Names tree.\n");
1147
0
            }
1148
0
        } else {
1149
0
            errprintf(ctx->memory, "\n   **** Warning: Failed to read EmbeddedFiles.\n");
1150
0
        }
1151
0
    } else {
1152
0
        errprintf(ctx->memory, "\n   **** Warning: Failed to find Names tree.\n");
1153
0
    }
1154
0
    code = 0;
1155
1156
0
exit:
1157
0
    if (code >= 0) {
1158
0
        uint64_t ix = 0;
1159
1160
0
        (*names_array) = (char **)gs_alloc_bytes(ctx->memory, *TotalFiles * (size_t)2 * sizeof(char *), "Collection file namesarray");
1161
0
        if (*names_array == NULL)
1162
0
            code = gs_note_error(gs_error_VMerror);
1163
0
        else {
1164
0
            memset((*names_array), 0x00, *TotalFiles * (size_t)2 * sizeof(char *));
1165
0
            for (i = 0; i < NumEmbeddedFiles;i++) {
1166
0
                if (working_array[i * 2] != NULL && working_array[(i * 2) + 1] != NULL) {
1167
0
                    (*names_array)[ix * 2] = working_array[i * 2];
1168
0
                    working_array[i * 2] = NULL;
1169
0
                    (*names_array)[(ix * 2) + 1] = working_array[(i * 2) + 1];
1170
0
                    working_array[(i * 2) + 1] = NULL;
1171
0
                    ix++;
1172
0
                }
1173
0
            }
1174
0
        }
1175
0
    }
1176
1177
0
    if (working_array != NULL) {
1178
        /* Each embedded file stores an embedded file name, and a scratch file name
1179
         * Hence we need to iterate NumEmbeddedFiles * 2 to free _all_ the strings.
1180
         */
1181
0
        for (i = 0; i < NumEmbeddedFiles * 2;i++)
1182
0
            gs_free_object(ctx->memory, working_array[i], "free collection temporary filenames");
1183
0
        gs_free_object(ctx->memory, working_array, "free collection working array");
1184
0
    }
1185
0
    pdfi_countdown(F);
1186
0
    pdfi_countdown(EF);
1187
0
    pdfi_countdown(FileNames);
1188
0
    pdfi_countdown(EmbeddedFiles);
1189
0
    pdfi_countdown(Names);
1190
0
    return code;
1191
0
}
1192
1193
static int pdfi_process_collection(pdf_context *ctx)
1194
0
{
1195
0
    int code, i;
1196
0
    uint64_t TotalFiles = 0, ix = 0;
1197
0
    char **names_array = NULL;
1198
1199
0
    code = pdfi_prep_collection(ctx, &TotalFiles, &names_array);
1200
0
    if (code >= 0 && TotalFiles > 0)
1201
0
    {
1202
        /* names_array is full of pointers to the scratch file names containing PDF files.
1203
         * Now we need to run each PDF file. First we close down the current file.
1204
         */
1205
0
        (void)pdfi_close_pdf_file(ctx);
1206
1207
0
        for (ix = 0;ix < TotalFiles * 2;ix+=2) {
1208
0
            if (names_array[ix] != NULL) {
1209
0
                (void)pdfi_process_pdf_file(ctx, names_array[ix]);
1210
0
                (void)pdfi_close_pdf_file(ctx);
1211
0
            }
1212
0
        }
1213
0
    } else
1214
        /* We didn't find any PDF files in the Embedded Files. So just run the
1215
         * pages in the container file (the original PDF file)
1216
         */
1217
0
        pdfi_process(ctx);
1218
1219
0
    for (i = 0; i < TotalFiles * 2;i++)
1220
0
        gs_free_object(ctx->memory, names_array[i], "free collection temporary filenames");
1221
0
    gs_free_object(ctx->memory, names_array, "free collection names array");
1222
1223
0
    return 0;
1224
0
}
1225
1226
int pdfi_process_pdf_file(pdf_context *ctx, char *filename)
1227
478
{
1228
478
    int code = 0;
1229
1230
478
    code = pdfi_open_pdf_file(ctx, filename);
1231
478
    if (code < 0) {
1232
314
        pdfi_report_errors(ctx);
1233
314
        return code;
1234
314
    }
1235
1236
    /* Do any custom device configuration */
1237
164
    pdfi_device_misc_config(ctx);
1238
1239
164
    if (ctx->Collection != NULL)
1240
0
        code = pdfi_process_collection(ctx);
1241
164
    else
1242
164
        code = pdfi_process(ctx);
1243
1244
    /* Pdfmark_InitialPage is the offset for Page Dests in
1245
     * /Outlines and Link annotations. It is the count of pages
1246
     * processed so far. Update it by the number of pages in
1247
     * this file.
1248
     */
1249
164
    ctx->Pdfmark_InitialPage += ctx->num_pages;
1250
1251
164
    pdfi_close_pdf_file(ctx);
1252
164
    return code;
1253
478
}
1254
1255
static int pdfi_init_file(pdf_context *ctx)
1256
86.8k
{
1257
86.8k
    int code = 0;
1258
86.8k
    pdf_obj *o = NULL;
1259
1260
86.8k
    code = pdfi_read_xref(ctx);
1261
86.8k
    if (code < 0) {
1262
7.82k
        if (ctx->is_hybrid) {
1263
2
            if ((code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_BADXREFSTREAM, "pdfi_init_file", NULL)) < 0) {
1264
0
                goto exit;
1265
0
            }
1266
            /* If its a hybrid file, and we failed to read the XrefStm, try
1267
             * again, but this time read the xref table instead.
1268
             */
1269
2
            pdfi_countdown(ctx->xref_table);
1270
2
            ctx->xref_table = NULL;
1271
2
            ctx->prefer_xrefstm = false;
1272
2
            code = pdfi_read_xref(ctx);
1273
2
            if (code < 0)
1274
0
                goto exit;
1275
7.82k
        } else {
1276
7.82k
            pdfi_set_error(ctx, code, NULL, E_PDF_BADXREFSTREAM, "pdfi_init_file", NULL);
1277
7.82k
            goto exit;
1278
7.82k
        }
1279
7.82k
    }
1280
1281
79.0k
    pdfi_device_set_flags(ctx);
1282
1283
79.0k
    if (ctx->Trailer) {
1284
        /* See comment in pdfi_read_Root() (pdf_doc.c) for details */
1285
32.5k
        pdf_dict *d = ctx->Trailer;
1286
1287
32.5k
        pdfi_countup(d);
1288
32.5k
        code = pdfi_dict_get(ctx, d, "Encrypt", &o);
1289
32.5k
        pdfi_countdown(d);
1290
32.5k
        if (code < 0 && code != gs_error_undefined)
1291
36
            goto exit;
1292
32.4k
        if (code == 0) {
1293
1.14k
            if (pdfi_type_of(o) == PDF_DICT) {
1294
#if USE_PDF_PERMISSIONS
1295
              double Permissions = 0;
1296
              uint32_t P = 0;
1297
#endif
1298
1299
1.12k
                code = pdfi_initialise_Decryption(ctx);
1300
1.12k
                if (code < 0)
1301
277
                    goto exit;
1302
1303
                /* This section is commetned out but deliberately retained. This code
1304
                 * prevents us from processing any PDF file where the 'print' permission
1305
                 * is not set. Additionally, if the 'print' permission is set, but bit 12
1306
                 * 'faitful digital copy' is not set, *and* we are writing to a high level
1307
                 * device, then we will throw an error..
1308
                 */
1309
#if USE_PDF_PERMISSIONS
1310
                code = pdfi_dict_knownget_number(ctx, (pdf_dict *)o, "P", &Permissions);
1311
                if (code < 0)
1312
                    goto exit;
1313
                if (Permissions > ((unsigned long)1 << 31)) {
1314
                    code = gs_note_error(gs_error_rangecheck);
1315
                    goto exit;
1316
                }
1317
                P = (uint32_t)Permissions;
1318
                if ((P & 0x04) == 0) {
1319
                    errprintf(ctx->memory, "   ****The owner of this file has requested you do not print it.\n");
1320
                    code = gs_note_error(gs_error_invalidfileaccess);
1321
                    goto exit;
1322
                }
1323
                if (ctx->device_state.HighLevelDevice) {
1324
                    if ((P & 0x800) == 0) {
1325
                        errprintf(ctx->memory, "   ****The owner of this file has requested you do not make a digital copy of it.\n");
1326
                        code = gs_note_error(gs_error_invalidfileaccess);
1327
                        goto exit;
1328
                    }
1329
                }
1330
#endif
1331
1.12k
            } else {
1332
22
                if (pdfi_type_of(o) != PDF_NULL)
1333
15
                    if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_typecheck), NULL, E_PDF_BADENCRYPT, "pdfi_init_file", NULL)) < 0)
1334
0
                        goto exit;
1335
22
            }
1336
1.14k
        }
1337
32.4k
    }
1338
1339
78.9k
read_root:
1340
78.9k
    if (ctx->Trailer) {
1341
32.4k
        code = pdfi_read_Root(ctx);
1342
32.4k
        if (code < 0) {
1343
            /* If we couldn#'t find the Root object, and we were using the XrefStm
1344
             * from a hybrid file, then try again, but this time use the xref table
1345
             */
1346
1.03k
            if (code == gs_error_undefined && ctx->is_hybrid && ctx->prefer_xrefstm) {
1347
4
                pdfi_countdown(ctx->xref_table);
1348
4
                ctx->xref_table = NULL;
1349
4
                if ((code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_BADXREFSTREAM, "pdfi_init_file", NULL)) < 0)
1350
0
                    goto exit;
1351
1352
4
                ctx->prefer_xrefstm = false;
1353
4
                code = pdfi_read_xref(ctx);
1354
4
                if (code < 0) {
1355
0
                    pdfi_set_error(ctx, 0, NULL, E_PDF_BADXREF, "pdfi_init_file", NULL);
1356
0
                    goto exit;
1357
0
                }
1358
4
                code = pdfi_read_Root(ctx);
1359
4
                if (code < 0)
1360
4
                    goto exit;
1361
1.02k
            } else {
1362
1.02k
                int code1 = pdfi_repair_file(ctx);
1363
1.02k
                if (code1 < 0)
1364
829
                    goto exit;
1365
200
                goto read_root;
1366
1.02k
            }
1367
1.03k
        }
1368
32.4k
    }
1369
1370
77.9k
    if (ctx->Trailer) {
1371
31.3k
        code = pdfi_read_Info(ctx);
1372
31.3k
        if (code < 0 && code != gs_error_undefined) {
1373
1.02k
            if ((code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_GS_LIB_ERROR, "pdfi_init_file", NULL)) < 0)
1374
0
                goto exit;
1375
1.02k
            pdfi_clearstack(ctx);
1376
1.02k
        }
1377
31.3k
    }
1378
1379
77.9k
    if (!ctx->Root) {
1380
7.56k
        errprintf(ctx->memory, "Catalog dictionary not located in file, unable to proceed\n");
1381
7.56k
        return_error(gs_error_syntaxerror);
1382
7.56k
    }
1383
1384
70.3k
    code = pdfi_read_Pages(ctx);
1385
70.3k
    if (code < 0)
1386
2.62k
        goto exit;
1387
1388
67.7k
    code = pdfi_doc_page_array_init(ctx);
1389
67.7k
    if (code < 0)
1390
1
        goto exit;
1391
1392
67.7k
    if (ctx->num_pages == 0)
1393
183
        errprintf(ctx->memory, "\n   **** Warning: PDF document has no pages.\n");
1394
1395
67.7k
    code = pdfi_doc_trailer(ctx);
1396
67.7k
    if (code < 0)
1397
0
        goto exit;
1398
1399
67.7k
    pdfi_read_OptionalRoot(ctx);
1400
1401
67.7k
    if (ctx->args.pdfinfo) {
1402
0
        code = pdfi_output_metadata(ctx);
1403
0
        if (code < 0 && (code = pdfi_set_error_stop(ctx, code, NULL, E_PDF_GS_LIB_ERROR, "pdfi_init_file", NULL)) < 0)
1404
0
            goto exit;
1405
0
    }
1406
1407
79.3k
exit:
1408
79.3k
    if (code < 0)
1409
11.5k
        pdfi_set_error(ctx, code, NULL, E_PDF_GS_LIB_ERROR, "pdfi_init_file", NULL);
1410
79.3k
    pdfi_countdown(o);
1411
79.3k
    return code;
1412
67.7k
}
1413
1414
int pdfi_set_input_stream(pdf_context *ctx, stream *stm)
1415
86.9k
{
1416
86.9k
    byte *Buffer = NULL;
1417
86.9k
    char *s = NULL, *test = NULL;
1418
86.9k
    float version = 0.0;
1419
86.9k
    gs_offset_t Offset = 0;
1420
86.9k
    int64_t bytes = 0, leftover = 0, bytes_left = 0;
1421
86.9k
    bool found = false;
1422
86.9k
    int code;
1423
1424
    /* In case of broken PDF files, the repair could run off the end of the
1425
     * file, so make sure that doing so does *not* automagically close the file
1426
     */
1427
86.9k
    stm->close_at_eod = false;
1428
1429
86.9k
    ctx->main_stream = (pdf_c_stream *)gs_alloc_bytes(ctx->memory, sizeof(pdf_c_stream), "PDF interpreter allocate main PDF stream");
1430
86.9k
    if (ctx->main_stream == NULL)
1431
0
        return_error(gs_error_VMerror);
1432
86.9k
    memset(ctx->main_stream, 0x00, sizeof(pdf_c_stream));
1433
86.9k
    ctx->main_stream->s = stm;
1434
1435
86.9k
    Buffer = gs_alloc_bytes(ctx->memory, BUF_SIZE, "PDF interpreter - allocate working buffer for file validation");
1436
86.9k
    if (Buffer == NULL) {
1437
0
        code = gs_error_VMerror;
1438
0
        goto error;
1439
0
    }
1440
1441
    /* Determine file size */
1442
86.9k
    pdfi_seek(ctx, ctx->main_stream, 0, SEEK_SET);
1443
86.9k
    pdfi_seek(ctx, ctx->main_stream, 0, SEEK_END);
1444
86.9k
    ctx->main_stream_length = pdfi_tell(ctx->main_stream);
1445
86.9k
    Offset = BUF_SIZE;
1446
86.9k
    bytes = BUF_SIZE;
1447
86.9k
    pdfi_seek(ctx, ctx->main_stream, 0, SEEK_SET);
1448
1449
86.9k
    bytes = Offset = min(BUF_SIZE - 1, ctx->main_stream_length);
1450
1451
86.9k
    if (ctx->args.pdfdebug)
1452
0
        outprintf(ctx->memory, "%% Reading header\n");
1453
1454
86.9k
    bytes = pdfi_read_bytes(ctx, Buffer, 1, Offset, ctx->main_stream);
1455
86.9k
    if (bytes <= 0) {
1456
5
        errprintf(ctx->memory, "Failed to read any bytes from input stream\n");
1457
5
        code = gs_error_ioerror;
1458
5
        goto error;
1459
5
    }
1460
86.9k
    if (bytes < 8) {
1461
50
        errprintf(ctx->memory, "Failed to read enough bytes for a valid PDF header from input stream\n");
1462
50
        code = gs_error_ioerror;
1463
50
        goto error;
1464
50
    }
1465
86.9k
    Buffer[Offset] = 0x00;
1466
1467
    /* First check for existence of header */
1468
86.9k
    test = (char *)Buffer;
1469
86.9k
    bytes_left = bytes;
1470
86.9k
    s = strstr((char *)test, "%PDF-");
1471
86.9k
    if (s == NULL) {
1472
259
        if ((code = pdfi_set_warning_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, W_PDF_GARBAGE_B4HDR, "pdfi_set_input_stream", "")) < 0) {
1473
0
            goto error;
1474
0
        }
1475
259
    }
1476
    /* Garbage before the header can be anything, including binary and NULL (0x00) characters
1477
     * which can defeat using strstr, so if we fail to find a header, try moving on by the length
1478
     * of the C string + 1 and try again.
1479
     */
1480
92.9k
    while (s == NULL) {
1481
6.08k
        bytes_left -= (strlen(test) + 1);
1482
6.08k
        if (bytes_left < 5)
1483
0
            break;
1484
6.08k
        test += strlen(test) + 1;
1485
6.08k
        s = strstr((char *)test, "%PDF-");
1486
6.08k
    };
1487
86.9k
    if (s == NULL) {
1488
0
        char extra_info[gp_file_name_sizeof];
1489
1490
0
        if (ctx->filename)
1491
0
            gs_snprintf(extra_info, sizeof(extra_info), "%% File %s does not appear to be a PDF file (no %%PDF in first 2Kb of file)\n", ctx->filename);
1492
0
        else
1493
0
            gs_snprintf(extra_info, sizeof(extra_info), "%% File does not appear to be a PDF stream (no %%PDF in first 2Kb of stream)\n");
1494
1495
0
        if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, E_PDF_NOHEADER, "pdfi_set_input_stream", extra_info) ) < 0)
1496
0
            goto error;
1497
86.9k
    } else {
1498
        /* Now extract header version (may be overridden later) */
1499
86.9k
        if (sscanf(s + 5, "%f", &version) != 1) {
1500
3.38k
            ctx->HeaderVersion = 0;
1501
3.38k
            if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, E_PDF_NOHEADERVERSION, "pdfi_set_input_stream", (char *)"%% Unable to read PDF version from header\n")) < 0)
1502
0
                goto error;
1503
3.38k
        }
1504
83.5k
        else {
1505
83.5k
            ctx->HeaderVersion = version;
1506
83.5k
            s += 5;
1507
358k
            while (((*s >= '0' && *s <= '9') || *s == '.') && *s != 0x00)
1508
274k
                s++;
1509
87.3k
            while (*s != 0x00) {
1510
86.9k
                if (*s == 0x09 || *s== 0x0c || *s == 0x20) {
1511
3.83k
                    s++;
1512
3.83k
                    continue;
1513
3.83k
                }
1514
83.1k
                if (*s != 0x0A && *s != 0x0D) {
1515
4.20k
                    if ((code = pdfi_set_warning_stop(ctx, 0, NULL, W_PDF_VERSION_NO_EOL, "pdfi_set_input_stream", (char *)"%% PDF version not immediately followed with EOL\n")) < 0)
1516
0
                        goto error;
1517
4.20k
                }
1518
83.1k
                break;
1519
83.1k
            }
1520
83.5k
        }
1521
86.9k
        if (ctx->args.pdfdebug)
1522
0
            outprintf(ctx->memory, "%% Found header, PDF version is %f\n", ctx->HeaderVersion);
1523
86.9k
    }
1524
1525
    /* Jump to EOF and scan backwards looking for startxref */
1526
86.9k
    pdfi_seek(ctx, ctx->main_stream, 0, SEEK_END);
1527
1528
86.9k
    if (ctx->args.pdfdebug)
1529
0
        outprintf(ctx->memory, "%% Searching for 'startxref' keyword\n");
1530
1531
    /* Initially read min(BUF_SIZE, file_length) bytes of data to the buffer */
1532
86.9k
    bytes = Offset;
1533
1534
624k
    do {
1535
624k
        byte *last_lineend = NULL;
1536
624k
        uint32_t read;
1537
1538
624k
        if (pdfi_seek(ctx, ctx->main_stream, ctx->main_stream_length - Offset, SEEK_SET) != 0) {
1539
6
            char msg[128];
1540
6
            gs_snprintf(msg, 128, "%% File is smaller than %"PRIi64" bytes\n", (int64_t)Offset);
1541
6
            code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_ioerror), NULL, E_PDF_GS_LIB_ERROR, "pdfi_set_input_stream", msg);
1542
6
            goto error;
1543
6
        }
1544
624k
        read = pdfi_read_bytes(ctx, Buffer, 1, bytes, ctx->main_stream);
1545
1546
624k
        if (read <= 0) {
1547
0
            char msg[128];
1548
0
            gs_snprintf(msg, 128, "Failed to read %"PRIi64" bytes from file\n", (int64_t)bytes);
1549
0
            code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_ioerror), NULL, E_PDF_GS_LIB_ERROR, "pdfi_set_input_stream", msg);
1550
0
            goto error;
1551
0
        }
1552
1553
        /* When reading backwards, if we ran out of data in the last buffer while looking
1554
         * for a 'startxref, but we had found a linefeed, then we preserved everything
1555
         * from the beginning of the buffer up to that linefeed, by copying it to the end
1556
         * of the buffer and reducing the number of bytes to read so that it should have filled
1557
         * in the gap. If we didn't read enough bytes, then we have a gap between the end of
1558
         * the data we just read and the leftover data from teh last buffer. Move the preserved
1559
         * data down to meet the end of the data we just read.
1560
         */
1561
624k
        if (bytes != read && leftover != 0)
1562
0
            memcpy(Buffer + read, Buffer + bytes, leftover);
1563
1564
        /* As above, if we had any leftover data from the last buffer then increase the
1565
         * number of bytes available by that amount. We increase 'bytes' (the number of bytes
1566
         * to read) to the same value, which should mean we read an entire buffer's worth. Of
1567
         * course if we have any data left out of this buffer we'll reduce bytes again...
1568
         */
1569
624k
        read = bytes = read + leftover;
1570
1571
        /* Now search backwards in the buffer for the startxref token */
1572
1.17G
        while(read) {
1573
1.17G
            if (memcmp(Buffer + read - 9, "startxref", 9) == 0) {
1574
38.6k
                found = true;
1575
38.6k
                break;
1576
1.17G
            } else {
1577
1.17G
                if (Buffer[read - 1] == 0x0a || Buffer[read - 1] == 0x0d)
1578
18.5M
                    last_lineend = Buffer + read;
1579
1.17G
            }
1580
1.17G
            read--;
1581
1.17G
        }
1582
624k
        if (found) {
1583
38.6k
            byte *b = Buffer + read;
1584
1585
            /* Success! stop now */
1586
38.6k
            if(sscanf((char *)b, " %"PRIdOFFSET"", &ctx->startxref) != 1) {
1587
624
                if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_syntaxerror), NULL, E_PDF_BADSTARTXREF, "pdfi_set_input_stream", "Unable to read offset of xref from PDF file\n")) < 0)
1588
0
                    goto error;
1589
624
            }
1590
38.6k
            break;
1591
585k
        } else {
1592
            /* Our file read could conceivably have read back to the point where we read
1593
             * part of the 'startxref' token, but not all of it. So we want to preserve
1594
             * the data in the buffer, but not all of it obviously! The 'startxref' should be followed
1595
             * by a line ending, so above we keep a note of the last line ending. If we found one, then
1596
             * we preserve from the start of the buffer to that point. This could slow us up if the file
1597
             * Is broken, or has a load of junk after the EOF, because we could potentially be saving a
1598
             * lot of data on each pass, but that's only going to happen with bad files.
1599
             * Note we reduce the number of bytes to read so that it just fits into the buffer up to the
1600
             * beginning of the data we preserved.
1601
             */
1602
585k
            if (last_lineend) {
1603
537k
                leftover = last_lineend - Buffer;
1604
                /* Ensure we don't try to copy more than half a buffer, because that will
1605
                 * end up overrunning the buffer end. Since we are only doing this to
1606
                 * ensure we don't drop a partial 'startxref' that's far more than enough.
1607
                 */
1608
537k
                if (leftover < BUF_SIZE / 2) {
1609
526k
                    memmove(Buffer + bytes - leftover, last_lineend, leftover);
1610
526k
                    bytes -= leftover;
1611
526k
                } else
1612
11.3k
                    leftover = 0;
1613
537k
            } else
1614
47.9k
                leftover = 0;
1615
585k
        }
1616
1617
585k
        Offset += bytes;
1618
585k
    } while(Offset < ctx->main_stream_length);
1619
1620
86.8k
    if (!found) {
1621
48.2k
        if ((code = pdfi_set_error_stop(ctx, gs_note_error(gs_error_undefined), NULL, E_PDF_NOSTARTXREF, "pdfi_set_input_stream", NULL)) < 0)
1622
0
            goto error;
1623
48.2k
    }
1624
1625
86.8k
    code = pdfi_init_file(ctx);
1626
1627
86.9k
error:
1628
86.9k
    gs_free_object(ctx->memory, Buffer, "PDF interpreter - allocate working buffer for file validation");
1629
86.9k
    return code;
1630
86.8k
}
1631
1632
int pdfi_open_pdf_file(pdf_context *ctx, char *filename)
1633
478
{
1634
478
    stream *s = NULL;
1635
478
    int code;
1636
1637
478
    if (ctx->args.pdfdebug)
1638
0
        outprintf(ctx->memory, "%% Attempting to open %s as a PDF file\n", filename);
1639
1640
478
    ctx->filename = (char *)gs_alloc_bytes(ctx->memory, (size_t)strlen(filename) + 1, "copy of filename");
1641
478
    if (ctx->filename == NULL)
1642
0
        return_error(gs_error_VMerror);
1643
478
    strcpy(ctx->filename, filename);
1644
1645
478
    s = sfopen(filename, "r", ctx->memory);
1646
478
    if (s == NULL) {
1647
0
        emprintf1(ctx->memory, "Failed to open file %s\n", filename);
1648
0
        return_error(gs_error_ioerror);
1649
0
    }
1650
478
    code = pdfi_set_input_stream(ctx, s);
1651
478
    return code;
1652
478
}
1653
1654
static size_t pdfi_grdir_path_string_match(const byte *str, size_t sl0, byte *pat, size_t pl)
1655
18.4k
{
1656
18.4k
    bool found = false;
1657
18.4k
    size_t sl = sl0;
1658
1659
129k
    while (found == false) {
1660
110k
        if (pl > sl)
1661
0
            break;
1662
110k
        if (*str == *pat && memcmp(str, pat, pl) == 0)
1663
18.4k
            found = true;
1664
92.2k
        else {
1665
92.2k
            str++;
1666
92.2k
            sl--;
1667
92.2k
        }
1668
110k
    }
1669
18.4k
    if (found)
1670
18.4k
        return (sl0 - sl) + pl;
1671
0
    else
1672
0
        return 0;
1673
18.4k
}
1674
1675
int pdfi_add_paths_to_search_paths(pdf_context *ctx, const char *ppath, int l, bool fontpath)
1676
18.4k
{
1677
18.4k
    int i, slen, npaths = (l > 0) ? 1 : 0;
1678
18.4k
    const char *p = ppath;
1679
18.4k
    char *ps;
1680
18.4k
    const char *pe = p + l + 1;
1681
18.4k
    int code = 0;
1682
18.4k
    static const char *resstr = "Resource";
1683
18.4k
    const int restrlen = strlen(resstr);
1684
18.4k
    const char *dirsepstr = gp_file_name_directory_separator();
1685
18.4k
    const int dirsepstrlen = strlen(dirsepstr);
1686
18.4k
    char genresstr[64];
1687
1688
737k
    for (ps = (char *)p; ps < pe; ps++) {
1689
719k
        if (*ps == gp_file_name_list_separator)
1690
18.4k
           npaths++;
1691
719k
    }
1692
1693
18.4k
    if (npaths > 0) {
1694
18.4k
        gs_param_string *pathstrings;
1695
18.4k
        int new_npaths = ctx->search_paths.num_resource_paths + npaths;
1696
1697
18.4k
        if (fontpath != true) {
1698
18.4k
            pathstrings = (gs_param_string *)gs_alloc_bytes(ctx->memory, (size_t)sizeof(gs_param_string) * new_npaths, "array of paths");
1699
18.4k
            if (pathstrings == NULL)
1700
0
                return_error(gs_error_VMerror);
1701
1702
18.4k
            memset(pathstrings, 0x00, sizeof(gs_param_string) * new_npaths);
1703
1704
18.4k
            for (i = 1; i <= ctx->search_paths.num_init_resource_paths; i++) {
1705
0
                pathstrings[new_npaths - i] = ctx->search_paths.resource_paths[ctx->search_paths.num_resource_paths - i];
1706
0
            }
1707
1708
18.4k
            for (i = 0; i < ctx->search_paths.num_resource_paths - ctx->search_paths.num_init_resource_paths; i++) {
1709
0
                pathstrings[i] = ctx->search_paths.resource_paths[i];
1710
0
            }
1711
            /* DO NOT CHANGE "i" BETWEEN HERE....... */
1712
18.4k
            gs_free_object(ctx->memory, ctx->search_paths.resource_paths, "old array of paths");
1713
18.4k
            ctx->search_paths.resource_paths = pathstrings;
1714
18.4k
            ctx->search_paths.num_resource_paths += npaths;
1715
1716
            /* .....AND HERE */
1717
719k
            for (ps = (char *)p; ps < pe; ps++) {
1718
701k
                if (*ps == gp_file_name_list_separator || ps == pe - 1) {
1719
36.8k
                    if (*p == gp_file_name_list_separator) p++; /* move past the separator */
1720
36.8k
                    slen = ps - p;
1721
36.8k
                    pathstrings[i].data = (byte *)gs_alloc_bytes(ctx->memory, slen, "path string body");
1722
1723
36.8k
                    if (pathstrings[i].data == NULL) {
1724
0
                        code = gs_note_error(gs_error_VMerror);
1725
0
                        break;
1726
0
                    }
1727
1728
36.8k
                    memcpy((char *)pathstrings[i].data, p, slen);
1729
36.8k
                    pathstrings[i].size = slen;
1730
36.8k
                    pathstrings[i].persistent = false;
1731
36.8k
                    i++;
1732
36.8k
                    p = ps++;
1733
36.8k
                }
1734
701k
            }
1735
18.4k
            if ((restrlen + 2 * dirsepstrlen) < 64) {
1736
18.4k
                size_t grdlen;
1737
1738
18.4k
                memcpy(genresstr, resstr, restrlen  +1); /* +1 So we get the null terminator */
1739
18.4k
                strncat(genresstr, dirsepstr, dirsepstrlen);
1740
1741
18.4k
                for (i = 0; i < ctx->search_paths.num_resource_paths; i++) {
1742
18.4k
                    if ((grdlen = pdfi_grdir_path_string_match(ctx->search_paths.resource_paths[i].data, ctx->search_paths.resource_paths[i].size, (byte *)genresstr, restrlen + dirsepstrlen)) > 0) {
1743
18.4k
                        ctx->search_paths.genericresourcedir.data = ctx->search_paths.resource_paths[i].data;
1744
18.4k
                        ctx->search_paths.genericresourcedir.size = grdlen;
1745
18.4k
                        ctx->search_paths.genericresourcedir.persistent = true;
1746
18.4k
                        break;
1747
18.4k
                    }
1748
18.4k
                }
1749
18.4k
            }
1750
18.4k
        }
1751
0
        else {
1752
0
            p = ppath;
1753
0
            pathstrings = (gs_param_string *)gs_alloc_bytes(ctx->memory, (size_t)sizeof(gs_param_string) * (npaths + ctx->search_paths.num_font_paths), "array of font paths");
1754
0
            if (pathstrings == NULL)
1755
0
                return_error(gs_error_VMerror);
1756
1757
0
            memset(pathstrings, 0x00, sizeof(gs_param_string) * (npaths + ctx->search_paths.num_font_paths));
1758
1759
0
            for (i = 0; i < ctx->search_paths.num_font_paths; i++) {
1760
0
                pathstrings[npaths + i] = ctx->search_paths.font_paths[i];
1761
0
            }
1762
0
            gs_free_object(ctx->memory, ctx->search_paths.font_paths, "old array of paths");
1763
0
            ctx->search_paths.font_paths = pathstrings;
1764
0
            ctx->search_paths.num_font_paths += npaths;
1765
1766
0
            i = 0;
1767
0
            for (ps = (char *)p; ps < pe; ps++) {
1768
0
                if (*ps == gp_file_name_list_separator || ps == pe - 1) {
1769
0
                    slen = ps - p;
1770
0
                    pathstrings[i].data = (byte *)gs_alloc_bytes(ctx->memory, slen, "path string body");
1771
1772
0
                    if (pathstrings[i].data == NULL) {
1773
0
                        code = gs_note_error(gs_error_VMerror);
1774
0
                        break;
1775
0
                    }
1776
1777
0
                    memcpy((char *)pathstrings[i].data, p, slen);
1778
0
                    pathstrings[i].size = slen;
1779
0
                    pathstrings[i].persistent = false;
1780
0
                    i++;
1781
0
                    p = ps++;
1782
0
                }
1783
0
            }
1784
0
        }
1785
18.4k
    }
1786
1787
18.4k
    return code;
1788
18.4k
}
1789
1790
int pdfi_add_initial_paths_to_search_paths(pdf_context *ctx, const char *ppath, int l)
1791
18.4k
{
1792
18.4k
    int code;
1793
18.4k
    if (ctx->search_paths.num_resource_paths != 0)
1794
0
        return_error(gs_error_invalidaccess);
1795
1796
18.4k
    code = pdfi_add_paths_to_search_paths(ctx, ppath, l, false);
1797
18.4k
    ctx->search_paths.num_init_resource_paths = ctx->search_paths.num_resource_paths;
1798
1799
18.4k
    return code;
1800
18.4k
}
1801
1802
static void pdfi_free_search_paths(pdf_context *ctx)
1803
104k
{
1804
104k
    int i;
1805
1.26M
    for (i = 0; i < ctx->search_paths.num_resource_paths; i++) {
1806
1.16M
        if (ctx->search_paths.resource_paths[i].persistent == false)
1807
1.16M
            gs_free_object(ctx->memory, (byte *)ctx->search_paths.resource_paths[i].data, "path string body");
1808
1.16M
    }
1809
104k
    for (i = 0; i < ctx->search_paths.num_font_paths; i++) {
1810
0
        if (ctx->search_paths.font_paths[i].persistent == false)
1811
0
            gs_free_object(ctx->memory, (byte *)ctx->search_paths.font_paths[i].data, "path string body");
1812
0
    }
1813
104k
    gs_free_object(ctx->memory, (byte *)ctx->search_paths.resource_paths, "array of paths");
1814
104k
    gs_free_object(ctx->memory, (byte *)ctx->search_paths.font_paths, "array of font paths");
1815
1816
104k
    if (ctx->search_paths.genericresourcedir.persistent == false)
1817
86.4k
        gs_free_object(ctx->memory, (byte *)ctx->search_paths.genericresourcedir.data, "generic resource directory");
1818
104k
}
1819
1820
static void pdfi_free_fontmapfiles(pdf_context *ctx)
1821
104k
{
1822
104k
    int i;
1823
104k
    for (i = 0; i < ctx->num_fontmapfiles; i++) {
1824
0
        gs_free_object(ctx->memory, ctx->fontmapfiles[i].data, "fontmapfiles string body");
1825
0
    }
1826
104k
    gs_free_object(ctx->memory, ctx->fontmapfiles, "fontmapfiles array");
1827
104k
}
1828
1829
/* The fontmap file list doesn't extend, later settings in the command line override earlier ones
1830
   (Unlike the "-I" search paths above).
1831
 */
1832
int pdfi_add_fontmapfiles(pdf_context *ctx, const char *ppath, int l)
1833
0
{
1834
0
    int i, nfilenames = (l > 0) ? 1 : 0;
1835
0
    const char *p = ppath;
1836
0
    char *ps;
1837
0
    const char *pe = p + l + 1;
1838
0
    int code = 0;
1839
1840
0
    pdfi_free_fontmapfiles(ctx);
1841
1842
0
    for (ps = (char *)p; ps < pe; ps++) {
1843
0
        if (*ps == gp_file_name_list_separator)
1844
0
           nfilenames++;
1845
0
    }
1846
0
    if (nfilenames > 0) {
1847
0
        ctx->fontmapfiles = (gs_string *)gs_alloc_bytes(ctx->memory, (size_t)sizeof(gs_string) * nfilenames, "array of fontmap files");
1848
0
        if (ctx->fontmapfiles == NULL) {
1849
0
            return_error(gs_error_VMerror);
1850
0
        }
1851
0
        else {
1852
0
           memset(ctx->fontmapfiles, 0x00, sizeof(gs_string) * nfilenames);
1853
0
           ctx->num_fontmapfiles = nfilenames;
1854
1855
0
           for (i = 0; i < nfilenames; i++) {
1856
0
               for (ps = (char *)p; ps < pe; ps++) {
1857
0
                   if (*ps == gp_file_name_list_separator)
1858
0
                       break;
1859
0
               }
1860
0
               ctx->fontmapfiles[i].data = gs_alloc_bytes(ctx->memory, ps - p, "fontmap file name body");
1861
0
               if (ctx->fontmapfiles[i].data == NULL) {
1862
0
                    code = gs_note_error(gs_error_VMerror);
1863
0
                    goto done;
1864
0
               }
1865
0
               memcpy(ctx->fontmapfiles[i].data, p, ps - p);
1866
0
               ctx->fontmapfiles[i].size = ps - p;
1867
0
               p = ps + 1;
1868
0
           }
1869
0
        }
1870
0
    }
1871
0
done:
1872
0
    return code;
1873
0
}
1874
1875
/***********************************************************************************/
1876
/* Highest level functions. The context we create here is returned to the 'PL'     */
1877
/* implementation, in future we plan to return it to PostScript by wrapping a      */
1878
/* gargabe collected object 'ref' around it and returning that to the PostScript   */
1879
/* world. custom PostScript operators will then be able to render pages, annots,   */
1880
/* AcroForms etc by passing the opaque object back to functions here, allowing     */
1881
/* the interpreter access to its context.                                          */
1882
1883
/* We start with routines for creating and destroying the interpreter context */
1884
pdf_context *pdfi_create_context(gs_memory_t *mem)
1885
104k
{
1886
104k
    pdf_context *ctx = NULL;
1887
104k
    gs_gstate *pgs = NULL;
1888
104k
    int code = 0;
1889
104k
    gs_memory_t *pmem = mem->non_gc_memory;
1890
#if PDFI_LEAK_CHECK
1891
    gs_memory_status_t mstat;
1892
    code = gs_memory_chunk_wrap(&pmem, mem->non_gc_memory);
1893
    if (code < 0)
1894
        return NULL;
1895
    gs_memory_status(pmem, &mstat);
1896
#endif
1897
1898
104k
    ctx = (pdf_context *) gs_alloc_bytes(pmem, sizeof(pdf_context), "pdf_create_context");
1899
1900
104k
    pgs = gs_gstate_alloc(pmem);
1901
1902
104k
    if (!ctx || !pgs)
1903
0
    {
1904
0
        if (ctx)
1905
0
            gs_free_object(pmem, ctx, "pdf_create_context");
1906
0
        if (pgs)
1907
0
            gs_gstate_free(pgs);
1908
0
        return NULL;
1909
0
    }
1910
1911
104k
    memset(ctx, 0, sizeof(pdf_context));
1912
104k
    ctx->memory = pmem;
1913
104k
    ctx->type = PDF_CTX;
1914
104k
    ctx->flags = 0;
1915
104k
    ctx->refcnt = 1;
1916
104k
    ctx->ctx = ctx;
1917
1918
#if PDFI_LEAK_CHECK
1919
    ctx->memstat = mstat;
1920
#endif
1921
1922
104k
    ctx->stack_bot = (pdf_obj **)gs_alloc_bytes(ctx->memory, INITIAL_STACK_SIZE * sizeof (pdf_obj *), "pdf_imp_allocate_interp_stack");
1923
104k
    if (ctx->stack_bot == NULL) {
1924
0
        gs_free_object(pmem, ctx, "pdf_create_context");
1925
0
        gs_gstate_free(pgs);
1926
0
        return NULL;
1927
0
    }
1928
104k
    ctx->stack_size = INITIAL_STACK_SIZE;
1929
104k
    ctx->stack_top = ctx->stack_bot - 1;
1930
104k
    code = sizeof(pdf_obj *);
1931
104k
    code *= ctx->stack_size;
1932
104k
    ctx->stack_limit = ctx->stack_bot + ctx->stack_size;
1933
1934
104k
    code = pdfi_init_font_directory(ctx);
1935
104k
    if (code < 0) {
1936
0
        gs_free_object(pmem, ctx->stack_bot, "pdf_create_context");
1937
0
        gs_free_object(pmem, ctx, "pdf_create_context");
1938
0
        gs_gstate_free(pgs);
1939
0
        return NULL;
1940
0
    }
1941
1942
104k
    code = gsicc_init_iccmanager(pgs);
1943
104k
    if (code < 0) {
1944
0
        gs_free_object(ctx->memory, ctx->font_dir, "pdf_create_context");
1945
0
        gs_free_object(pmem, ctx->stack_bot, "pdf_create_context");
1946
0
        gs_free_object(pmem, ctx, "pdf_create_context");
1947
0
        gs_gstate_free(pgs);
1948
0
        return NULL;
1949
0
    }
1950
1951
104k
    ctx->pgs = pgs;
1952
104k
    code = pdfi_gstate_set_client(ctx, pgs);
1953
104k
    if (code < 0) {
1954
0
        gs_free_object(ctx->memory, ctx->font_dir, "pdf_create_context");
1955
0
        gs_free_object(pmem, ctx->stack_bot, "pdf_create_context");
1956
0
        gs_free_object(pmem, ctx, "pdf_create_context");
1957
0
        gs_gstate_free(pgs);
1958
0
        return NULL;
1959
0
    }
1960
1961
    /* Some (but not all) path construction operations can either return
1962
     * an error or clamp values when out of range. In order to match Ghostscript's
1963
     * PDF interpreter written in PostScript, we need to clamp them.
1964
     */
1965
104k
    gs_setlimitclamp(pgs, true);
1966
1967
    /* Declare PDL client support for high level patterns, for the benefit
1968
     * of pdfwrite and other high-level devices
1969
     */
1970
104k
    ctx->pgs->have_pattern_streams = true;
1971
104k
    ctx->device_state.preserve_tr_mode = 0;
1972
104k
    ctx->args.notransparency = false;
1973
1974
104k
    ctx->main_stream = NULL;
1975
1976
    /* Setup some flags that don't default to 'false' */
1977
104k
    ctx->args.showannots = true;
1978
104k
    ctx->args.preserveannots = true;
1979
104k
    ctx->args.preservemarkedcontent = true;
1980
104k
    ctx->args.preserveembeddedfiles = true;
1981
104k
    ctx->args.preservedocview = true;
1982
104k
    ctx->args.PDFCacheSize = MAX_OBJECT_CACHE_SIZE;
1983
    /* NOTE: For testing certain annotations on cluster, might want to set this to false */
1984
104k
    ctx->args.printed = false; /* True if OutputFile is set, false otherwise see pdftop.c, pdf_impl_set_param() */
1985
1986
    /* Initially, prefer the XrefStm in a hybrid file */
1987
104k
    ctx->prefer_xrefstm = true;
1988
1989
    /* We decrypt strings from encrypted files until we start a page */
1990
104k
    ctx->encryption.decrypt_strings = true;
1991
104k
    ctx->get_glyph_name = pdfi_glyph_name;
1992
104k
    ctx->get_glyph_index = pdfi_glyph_index;
1993
1994
104k
    ctx->job_gstate_level = ctx->pgs->level;
1995
    /* Weirdly the graphics library wants us to always have two gstates, the
1996
     * initial state and at least one saved state. if we don't then when we
1997
     * grestore back to the initial state, it immediately saves another one.
1998
     */
1999
104k
    code = gs_gsave(ctx->pgs);
2000
104k
    if (code < 0) {
2001
0
        gs_free_object(ctx->memory, ctx->font_dir, "pdf_create_context");
2002
0
        gs_free_object(pmem, ctx->stack_bot, "pdf_create_context");
2003
0
        gs_gstate_free(ctx->pgs);
2004
0
        gs_free_object(pmem, ctx, "pdf_create_context");
2005
0
        return NULL;
2006
0
    }
2007
#if REFCNT_DEBUG
2008
    ctx->UID = 1;
2009
#endif
2010
#if CACHE_STATISTICS
2011
    ctx->hits = 0;
2012
    ctx->misses = 0;
2013
    ctx->compressed_hits = 0;
2014
    ctx->compressed_misses = 0;
2015
#endif
2016
#ifdef DEBUG
2017
    ctx->args.verbose_errors = ctx->args.verbose_warnings = 1;
2018
#endif
2019
104k
    return ctx;
2020
104k
}
2021
2022
/* Purge all */
2023
static bool
2024
pdfi_fontdir_purge_all(const gs_memory_t * mem, cached_char * cc, void *dummy)
2025
757k
{
2026
757k
    return true;
2027
757k
}
2028
2029
#if DEBUG_CACHE
2030
#if DEBUG_CACHE_FREE
2031
static void
2032
pdfi_print_cache(pdf_context *ctx)
2033
{
2034
    pdf_obj_cache_entry *entry = ctx->cache_LRU, *next;
2035
2036
    outprintf(ctx->memory, "CACHE: #entries=%d\n", ctx->cache_entries);
2037
    while(entry) {
2038
        next = entry->next;
2039
#if REFCNT_DEBUG
2040
        outprintf(ctx->memory, "UID:%ld, Object:%d, refcnt:%d, next=%p, prev=%p\n",
2041
                  entry->o->UID, entry->o->object_num, entry->o->refcnt,
2042
                  entry->next, entry->previous);
2043
#else
2044
        outprintf(ctx->memory, "Object:%d, refcnt:%d, next=%p, prev=%p\n",
2045
                  entry->o->object_num, entry->o->refcnt,
2046
                  entry->next, entry->previous);
2047
#endif
2048
        entry = next;
2049
    }
2050
}
2051
#else
2052
static void
2053
pdfi_print_cache(pdf_context *ctx)
2054
{}
2055
#endif
2056
#endif /* DEBUG */
2057
2058
#if PURGE_CACHE_PER_PAGE
2059
void
2060
pdfi_purge_obj_cache(pdf_context *ctx)
2061
{
2062
    if (ctx->cache_entries != 0) {
2063
        pdf_obj_cache_entry *entry = ctx->cache_LRU, *next;
2064
2065
        while(entry) {
2066
            next = entry->next;
2067
            if (entry->o->object_num != 0) {
2068
                ctx->xref_table->xref[entry->o->object_num].cache = NULL;
2069
            }
2070
            pdfi_countdown(entry->o);
2071
            ctx->cache_entries--;
2072
            gs_free_object(ctx->memory, entry, "pdfi_clear_context, free LRU");
2073
            entry = next;
2074
#if REFCNT_DEBUG
2075
            ctx->cache_LRU = entry;
2076
#endif
2077
        }
2078
        ctx->cache_LRU = ctx->cache_MRU = NULL;
2079
        ctx->cache_entries = 0;
2080
    }
2081
}
2082
#endif
2083
2084
/* pdfi_clear_context frees all the PDF objects associated with interpreting a given
2085
 * PDF file. Once we've called this we can happily run another file. This function is
2086
 * called by pdf_free_context (in case of errors during the file leaving state around)
2087
 * and by pdfi_close_pdf_file.
2088
 */
2089
int pdfi_clear_context(pdf_context *ctx)
2090
105k
{
2091
#if CACHE_STATISTICS
2092
    float compressed_hit_rate = 0.0, hit_rate = 0.0;
2093
2094
    if (ctx->compressed_hits > 0 || ctx->compressed_misses > 0)
2095
        compressed_hit_rate = (float)ctx->compressed_hits / (float)(ctx->compressed_hits + ctx->compressed_misses);
2096
    if (ctx->hits > 0 || ctx->misses > 0)
2097
        hit_rate = (float)ctx->hits / (float)(ctx->hits + ctx->misses);
2098
2099
    outprintf(ctx->memory, "Number of normal object cache hits: %"PRIi64"\n", ctx->hits);
2100
    outprintf(ctx->memory, "Number of normal object cache misses: %"PRIi64"\n", ctx->misses);
2101
    outprintf(ctx->memory, "Number of compressed object cache hits: %"PRIi64"\n", ctx->compressed_hits);
2102
    outprintf(ctx->memory, "Number of compressed object cache misses: %"PRIi64"\n", ctx->compressed_misses);
2103
    outprintf(ctx->memory, "Normal object cache hit rate: %f\n", hit_rate);
2104
    outprintf(ctx->memory, "Compressed object cache hit rate: %f\n", compressed_hit_rate);
2105
#endif
2106
105k
    FreePathRecord(ctx);
2107
2108
105k
    if (ctx->args.PageList) {
2109
0
        gs_free_object(ctx->memory, ctx->args.PageList, "pdfi_clear_context");
2110
0
        ctx->args.PageList = NULL;
2111
0
    }
2112
105k
    if (ctx->Trailer) {
2113
32.5k
        pdfi_countdown(ctx->Trailer);
2114
32.5k
        ctx->Trailer = NULL;
2115
32.5k
    }
2116
2117
105k
    if (ctx->AcroForm) {
2118
5.69k
        pdfi_countdown(ctx->AcroForm);
2119
5.69k
        ctx->AcroForm = NULL;
2120
5.69k
    }
2121
2122
105k
    if(ctx->Root) {
2123
70.6k
        pdfi_countdown(ctx->Root);
2124
70.6k
        ctx->Root = NULL;
2125
70.6k
    }
2126
2127
105k
    if (ctx->Info) {
2128
18.6k
        pdfi_countdown(ctx->Info);
2129
18.6k
        ctx->Info = NULL;
2130
18.6k
    }
2131
2132
105k
    if (ctx->PagesTree) {
2133
67.2k
        pdfi_countdown(ctx->PagesTree);
2134
67.2k
        ctx->PagesTree = NULL;
2135
67.2k
    }
2136
2137
105k
    if (ctx->args.cidfsubstpath.data != NULL) {
2138
0
        gs_free_object(ctx->memory, ctx->args.cidfsubstpath.data, "cidfsubstpath.data");
2139
0
        ctx->args.cidfsubstpath.data = NULL;
2140
0
    }
2141
2142
105k
    if (ctx->args.cidfsubstfont.data != NULL) {
2143
0
        gs_free_object(ctx->memory, ctx->args.cidfsubstfont.data, "cidfsubstfont.data");
2144
0
        ctx->args.cidfsubstfont.data = NULL;
2145
0
    }
2146
2147
105k
    if (ctx->args.defaultfont.data != NULL) {
2148
0
        gs_free_object(ctx->memory, ctx->args.defaultfont.data, "cidfsubstfont.data");
2149
0
        ctx->args.defaultfont.data = NULL;
2150
0
    }
2151
2152
105k
    pdfi_free_cstring_array(ctx, &ctx->args.showannottypes);
2153
105k
    pdfi_free_cstring_array(ctx, &ctx->args.preserveannottypes);
2154
2155
105k
    pdfi_doc_page_array_free(ctx);
2156
2157
105k
    if (ctx->xref_table) {
2158
79.1k
        pdfi_countdown(ctx->xref_table);
2159
79.1k
        ctx->xref_table = NULL;
2160
79.1k
    }
2161
2162
105k
    pdfi_free_OptionalRoot(ctx);
2163
2164
105k
    if (ctx->stack_bot)
2165
105k
        pdfi_clearstack(ctx);
2166
2167
105k
    if (ctx->filename) {
2168
        /* This should already be closed! */
2169
314
        pdfi_close_pdf_file(ctx);
2170
314
        gs_free_object(ctx->memory, ctx->filename, "pdfi_clear_context, free copy of filename");
2171
314
        ctx->filename = NULL;
2172
314
    }
2173
2174
105k
    if (ctx->main_stream) {
2175
86.4k
        gs_free_object(ctx->memory, ctx->main_stream, "pdfi_clear_context, free main PDF stream");
2176
86.4k
        ctx->main_stream = NULL;
2177
86.4k
    }
2178
105k
    ctx->main_stream_length = 0;
2179
2180
105k
    if(ctx->pgs != NULL) {
2181
105k
        gx_pattern_cache_free(ctx->pgs->pattern_cache);
2182
105k
        ctx->pgs->pattern_cache = NULL;
2183
105k
        if (ctx->pgs->font)
2184
0
            pdfi_countdown_current_font(ctx);
2185
2186
        /* We use gs_grestore_only() instead of gs_grestore, because gs_grestore
2187
         * will not restore below two gstates and we want to clear the entire
2188
         * stack of saved states, back to the initial state.
2189
         */
2190
210k
        while (ctx->pgs->level != ctx->job_gstate_level && ctx->pgs->saved)
2191
104k
            gs_grestore_only(ctx->pgs);
2192
105k
    }
2193
2194
105k
    pdfi_free_DefaultQState(ctx);
2195
105k
    pdfi_oc_free(ctx);
2196
2197
105k
    if(ctx->encryption.EKey) {
2198
845
        pdfi_countdown(ctx->encryption.EKey);
2199
845
        ctx->encryption.EKey = NULL;
2200
845
    }
2201
105k
    if (ctx->encryption.Password) {
2202
0
        gs_free_object(ctx->memory, ctx->encryption.Password, "PDF Password from params");
2203
0
        ctx->encryption.Password = NULL;
2204
0
    }
2205
2206
105k
    if (ctx->cache_entries != 0) {
2207
69.0k
        pdf_obj_cache_entry *entry = ctx->cache_LRU, *next;
2208
2209
#if DEBUG_CACHE
2210
        int count;
2211
        bool stop = true;
2212
        pdf_obj_cache_entry *prev;
2213
2214
        do {
2215
            pdfi_print_cache(ctx);
2216
            entry = ctx->cache_LRU;
2217
            stop = true;
2218
            while(entry) {
2219
                pdfi_print_cache(ctx);
2220
                next = entry->next;
2221
                prev = entry->previous;
2222
2223
                /* pass through the cache, count down any objects which are only referenced by the cache (refcnt == 1)
2224
                 * this may cause other objects (referred to by the newly freed object) to decrement their refcnt
2225
                 * until they are also only pointed at by the cache.
2226
                 */
2227
                if (entry->o->refcnt == 1) {
2228
                    stop = false;
2229
                    pdfi_countdown(entry->o);
2230
                    if (prev != NULL)
2231
                        prev->next = next;
2232
                    else
2233
                        ctx->cache_LRU = next;
2234
                    if (next)
2235
                        next->previous = prev;
2236
                    ctx->cache_entries--;
2237
                    gs_free_object(ctx->memory, entry, "pdfi_clear_context, free LRU");
2238
                }
2239
                entry = next;
2240
            }
2241
        } while (stop == false);
2242
2243
        entry = ctx->cache_LRU;
2244
        while(entry) {
2245
            next = entry->next;
2246
            prev = entry->previous;
2247
            count = entry->o->refcnt;
2248
            dbgmprintf1(ctx->memory, "CLEANUP cache entry obj %d", entry->o->object_num);
2249
            dbgmprintf1(ctx->memory, " has refcnt %d\n", count);
2250
            entry = next;
2251
        }
2252
#else
2253
1.51M
        while(entry) {
2254
1.44M
            next = entry->next;
2255
1.44M
            pdfi_countdown(entry->o);
2256
1.44M
            ctx->cache_entries--;
2257
1.44M
            gs_free_object(ctx->memory, entry, "pdfi_clear_context, free LRU");
2258
1.44M
            entry = next;
2259
#if REFCNT_DEBUG
2260
            ctx->cache_LRU = entry;
2261
#endif
2262
1.44M
        }
2263
69.0k
#endif
2264
69.0k
        ctx->cache_LRU = ctx->cache_MRU = NULL;
2265
69.0k
        ctx->cache_entries = 0;
2266
69.0k
    }
2267
2268
    /* We can't free the font directory before the graphics library fonts fonts are freed, as they reference the font_dir.
2269
     * graphics library fonts are refrenced from pdf_font objects, and those may be in the cache, which means they
2270
     * won't be freed until we empty the cache. So we can't free 'font_dir' until after the cache has been cleared.
2271
     */
2272
105k
    if (ctx->font_dir)
2273
105k
        gx_purge_selected_cached_chars(ctx->font_dir, pdfi_fontdir_purge_all, (void *)NULL);
2274
2275
105k
    pdfi_countdown(ctx->pdffontmap);
2276
105k
    ctx->pdffontmap = NULL;
2277
105k
    pdfi_countdown(ctx->pdfnativefontmap);
2278
105k
    ctx->pdfnativefontmap = NULL;
2279
105k
    pdfi_countdown(ctx->pdf_substitute_fonts);
2280
105k
    ctx->pdf_substitute_fonts = NULL;
2281
2282
105k
    return 0;
2283
105k
}
2284
2285
int pdfi_free_context(pdf_context *ctx)
2286
104k
{
2287
#if PDFI_LEAK_CHECK
2288
    gs_memory_status_t mstat, ctxmstat = ctx->memstat;
2289
    gs_memory_t *mem = ctx->memory;
2290
#endif
2291
104k
    pdfi_clear_context(ctx);
2292
2293
104k
    gs_free_object(ctx->memory, ctx->stack_bot, "pdfi_free_context");
2294
2295
104k
    pdfi_free_name_table(ctx);
2296
2297
    /* And here we free the initial graphics state */
2298
104k
    while (ctx->pgs->saved)
2299
0
        gs_grestore_only(ctx->pgs);
2300
2301
104k
    gs_gstate_free(ctx->pgs);
2302
2303
104k
    ctx->pgs = NULL;
2304
2305
104k
    if (ctx->font_dir)
2306
104k
        gs_free_object(ctx->memory, ctx->font_dir, "pdfi_free_context");
2307
2308
    /* Currently this should never happen, but in future it might if we choose
2309
     * not to keep freeing and reallocating the array.
2310
     */
2311
104k
    if (ctx->loop_detection != NULL) {
2312
9
        dbgmprintf(ctx->memory, "Loop detection array exists at EOJ\n");
2313
9
        gs_free_object(ctx->memory, ctx->loop_detection, "pdfi_free_context");
2314
9
    }
2315
2316
104k
    pdfi_free_search_paths(ctx);
2317
104k
    pdfi_free_fontmapfiles(ctx);
2318
2319
104k
    if (ctx->pdfcidfmap != NULL) {
2320
5.36k
        pdfi_countdown(ctx->pdfcidfmap);
2321
5.36k
        ctx->pdfcidfmap = NULL;
2322
5.36k
    }
2323
104k
    if (ctx->pdffontmap != NULL) {
2324
0
        pdfi_countdown(ctx->pdffontmap);
2325
0
        ctx->pdffontmap = NULL;
2326
0
    }
2327
104k
    rc_decrement(ctx->devbbox, "pdfi_free_context");
2328
2329
104k
    gs_free_object(ctx->memory, ctx, "pdfi_free_context");
2330
#if PDFI_LEAK_CHECK
2331
    gs_memory_status(mem, &mstat);
2332
    if (mstat.allocated > ctxmstat.allocated)
2333
        errprintf(mem, "\nMemory Leak Detected: Pre %d, Post %d\n", (int)ctxmstat.allocated, (int)mstat.allocated);
2334
    (void)gs_memory_chunk_unwrap(mem);
2335
#endif
2336
104k
    return 0;
2337
104k
}
2338
2339
/* These routines are used from the PostScript interpreter inteerface. It is important that
2340
 * the 'interpreter part of the graphics state' should be a pdfi interpreter context while pdfi is running
2341
 * but the PostScript itnerpreter context when the PostScript interpreter is running. If we are going
2342
 * to inherit the PostScript graphics state for pdfi, then we need to turn it into a 'pdfi'
2343
 * graphics state for the duration of the interpretation, and back to a PostScript one when
2344
 * we return to the PostScript interpreter.
2345
 *
2346
 * Bizarrely it appears that the interpreter part of the gstate does not obey grestore, instead we copy
2347
 * the 'current' context to the saved context when we do a grestore. This seems wrong to me, but
2348
 * it seems to be what happens, so we can't rely on grestore to put back the interpreter context, but must
2349
 * do so ourselves.
2350
 *
2351
 * Hence the 'from_PS' routine fills in pointers with the current context and procs, with the expectation that
2352
 * these will be saved and used to restore the data in the 'to_PS' routine.
2353
 */
2354
/* NOTE see the comments in zpdfops.c just under the declaration of the pdfi_switch_t strcuture regarding
2355
 * complications with the ICC profile cache.
2356
 */
2357
2358
int pdfi_gstate_from_PS(pdf_context *ctx, gs_gstate *pgs, pdfi_switch_t *i_switch, gsicc_profile_cache_t *profile_cache)
2359
375k
{
2360
375k
    int code;
2361
375k
    i_switch->pgs = ctx->pgs;
2362
375k
    i_switch->procs = pgs->client_procs;
2363
375k
    i_switch->client_data = (void *)pgs->client_data;
2364
375k
    i_switch->profile_cache = pgs->icc_profile_cache;
2365
375k
    code = pdfi_gstate_set_client(ctx, pgs);
2366
375k
    if (code < 0)
2367
0
        return code;
2368
375k
    i_switch->psfont = pgs->font;
2369
375k
    pgs->icc_profile_cache = profile_cache;
2370
375k
    rc_increment(pgs->icc_profile_cache);
2371
375k
    pgs->font = NULL;
2372
375k
    ctx->pgs = pgs;
2373
375k
    return code;
2374
375k
}
2375
2376
void pdfi_gstate_to_PS(pdf_context *ctx, gs_gstate *pgs, pdfi_switch_t *i_switch)
2377
375k
{
2378
375k
    pgs->client_procs.free(pgs->client_data, pgs->memory, pgs);
2379
375k
    pgs->client_data = NULL;
2380
375k
    rc_decrement(pgs->icc_profile_cache, "pdfi_gstate_to_PS");
2381
375k
    pgs->icc_profile_cache = i_switch->profile_cache;
2382
375k
    gs_gstate_set_client(pgs, i_switch->client_data, &i_switch->procs, true);
2383
    ctx->pgs->font = NULL;
2384
375k
    ctx->pgs = i_switch->pgs;
2385
375k
    pgs->font = i_switch->psfont;
2386
375k
}