Coverage Report

Created: 2025-11-16 07:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/devices/vector/gdevpdf.c
Line
Count
Source
1
/* Copyright (C) 2001-2025 Artifex Software, Inc.
2
   All Rights Reserved.
3
4
   This software is provided AS-IS with no warranty, either express or
5
   implied.
6
7
   This software is distributed under license and may not be copied,
8
   modified or distributed except as expressly authorized under the terms
9
   of the license contained in the file LICENSE in this distribution.
10
11
   Refer to licensing information at http://www.artifex.com or contact
12
   Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
13
   CA 94129, USA, for further information.
14
*/
15
16
17
/* PDF-writing driver */
18
#include "fcntl_.h"
19
#include "memory_.h"
20
#include "time_.h"
21
#include "unistd_.h"
22
#include "gx.h"
23
#include "gp.h"     /* for gp_get_realtime */
24
#include "gserrors.h"
25
#include "gxdevice.h"
26
#include "gdevpdfx.h"
27
#include "gdevpdfg.h"   /* only for pdf_reset_graphics */
28
#include "gdevpdfo.h"
29
#include "smd5.h"
30
#include "sarc4.h"
31
#include "sbrotlix.h"
32
#include "gscms.h"
33
#include "gdevpdtf.h"
34
#include "gdevpdtx.h"
35
#include "gdevpdtd.h"
36
#include "gdevpdti.h"
37
#include "gsfcmap.h"        /* For gs_cmap_ToUnicode_free */
38
39
#include "gxfcache.h"
40
#include "gdevpdts.h"       /* for sync_text_state */
41
42
#include "gdevpdfo.h"
43
44
/* Define the default language level and PDF compatibility level. */
45
/* Acrobat 8 (PDF 1.7) is the default. (1.7 for ICC V4.2.0 profile support) */
46
#define PSDF_VERSION_INITIAL psdf_version_ll3
47
#define PDF_COMPATIBILITY_LEVEL_INITIAL 1.7
48
49
/* Define the size of internal stream buffers. */
50
/* (This is not a limitation, it only affects performance.) */
51
126k
#define sbuf_size 512
52
53
/* GC descriptors */
54
private_st_pdf_page();
55
gs_private_st_element(st_pdf_page_element, pdf_page_t, "pdf_page_t[]",
56
                      pdf_page_elt_enum_ptrs, pdf_page_elt_reloc_ptrs,
57
                      st_pdf_page);
58
private_st_pdf_linearisation_record();
59
gs_private_st_element(st_pdf_linearisation_record_element, pdf_linearisation_record_t, "pdf_linearstion_record_t[]",
60
                      pdf_linearisation_record_elt_enum_ptrs, pdf_linearisation_record_elt_reloc_ptrs,
61
                      st_pdf_linearisation_record);
62
private_st_device_pdfwrite();
63
private_st_pdf_substream_save();
64
private_st_pdf_substream_save_element();
65
66
/* GC procedures */
67
static
68
141M
ENUM_PTRS_WITH(device_pdfwrite_enum_ptrs, gx_device_pdf *pdev)
69
120M
{
70
120M
    index -= gx_device_pdf_num_ptrs + gx_device_pdf_num_param_strings;
71
120M
    if (index < NUM_RESOURCE_TYPES * NUM_RESOURCE_CHAINS)
72
110M
        ENUM_RETURN(pdev->resources[index / NUM_RESOURCE_CHAINS].chains[index % NUM_RESOURCE_CHAINS]);
73
9.70M
    index -= NUM_RESOURCE_TYPES * NUM_RESOURCE_CHAINS;
74
9.70M
    if (index <= pdev->outline_depth && pdev->outline_levels)
75
81.6k
        ENUM_RETURN(pdev->outline_levels[index].first.action);
76
9.61M
    index -= pdev->outline_depth + 1;
77
9.61M
    if (index <= pdev->outline_depth && pdev->outline_levels)
78
81.6k
        ENUM_RETURN(pdev->outline_levels[index].last.action);
79
9.53M
    index -= pdev->outline_depth + 1;
80
81
9.53M
    if (index < pdev->PatternDepth) {
82
2
       ENUM_RETURN(pdev->initial_pattern_states[index]);
83
2
    }
84
9.53M
    index -= pdev->PatternDepth;
85
9.53M
    ENUM_PREFIX(st_device_psdf, 0);
86
87
9.53M
}
88
9.53M
 ENUM_PTR(0, gx_device_pdf, asides.strm);
89
9.53M
 ENUM_PTR(1, gx_device_pdf, asides.strm_buf);
90
9.53M
 ENUM_PTR(2, gx_device_pdf, asides.save_strm);
91
9.53M
 ENUM_PTR(3, gx_device_pdf, streams.strm);
92
9.53M
 ENUM_PTR(4, gx_device_pdf, streams.strm_buf);
93
9.53M
 ENUM_PTR(5, gx_device_pdf, ObjStm.strm);
94
9.53M
 ENUM_PTR(6, gx_device_pdf, ObjStm.strm_buf);
95
9.53M
 ENUM_PTR(7, gx_device_pdf, ObjStm.save_strm);
96
9.53M
 ENUM_PTR(8, gx_device_pdf, Catalog);
97
9.53M
 ENUM_PTR(9, gx_device_pdf, Info);
98
9.53M
 ENUM_PTR(10, gx_device_pdf, Pages);
99
9.53M
 ENUM_PTR(11, gx_device_pdf, text);
100
9.53M
 ENUM_PTR(12, gx_device_pdf, pages);
101
9.53M
 ENUM_PTR(13, gx_device_pdf, cs_Patterns[0]);
102
9.53M
 ENUM_PTR(14, gx_device_pdf, cs_Patterns[1]);
103
9.53M
 ENUM_PTR(15, gx_device_pdf, cs_Patterns[3]);
104
9.53M
 ENUM_PTR(16, gx_device_pdf, cs_Patterns[4]);
105
9.53M
 ENUM_PTR(17, gx_device_pdf, last_resource);
106
9.53M
 ENUM_PTR(18, gx_device_pdf, articles);
107
9.53M
 ENUM_PTR(19, gx_device_pdf, Dests);
108
9.53M
 ENUM_PTR(20, gx_device_pdf, global_named_objects);
109
9.53M
 ENUM_PTR(21, gx_device_pdf, local_named_objects);
110
9.53M
 ENUM_PTR(22, gx_device_pdf, NI_stack);
111
9.53M
 ENUM_PTR(23, gx_device_pdf, Namespace_stack);
112
9.53M
 ENUM_PTR(24, gx_device_pdf, font_cache);
113
9.53M
 ENUM_PTR(25, gx_device_pdf, clip_path);
114
9.53M
 ENUM_PTR(26, gx_device_pdf, PageLabels);
115
9.53M
 ENUM_PTR(27, gx_device_pdf, PageLabels_current_label);
116
9.53M
 ENUM_PTR(28, gx_device_pdf, sbstack);
117
9.53M
 ENUM_PTR(29, gx_device_pdf, substream_Resources);
118
9.53M
 ENUM_PTR(30, gx_device_pdf, font3);
119
9.53M
 ENUM_PTR(31, gx_device_pdf, accumulating_substream_resource);
120
9.53M
 ENUM_PTR(32, gx_device_pdf, pres_soft_mask_dict);
121
9.53M
 ENUM_PTR(33, gx_device_pdf, PDFXTrimBoxToMediaBoxOffset.data);
122
9.53M
 ENUM_PTR(34, gx_device_pdf, PDFXBleedBoxToTrimBoxOffset.data);
123
9.53M
 ENUM_PTR(35, gx_device_pdf, Identity_ToUnicode_CMaps[0]);
124
9.53M
 ENUM_PTR(36, gx_device_pdf, Identity_ToUnicode_CMaps[1]);
125
9.53M
 ENUM_PTR(37, gx_device_pdf, vgstack);
126
9.53M
 ENUM_PTR(38, gx_device_pdf, outline_levels);
127
9.53M
 ENUM_PTR(39, gx_device_pdf, EmbeddedFiles);
128
9.53M
 ENUM_PTR(40, gx_device_pdf, AF);
129
9.53M
 ENUM_PTR(41, gx_device_pdf, pdf_font_dir);
130
9.53M
 ENUM_PTR(42, gx_device_pdf, ExtensionMetadata);
131
9.53M
 ENUM_PTR(43, gx_device_pdf, PassThroughWriter);
132
2.16M
#define e1(i,elt) ENUM_PARAM_STRING_PTR(i + gx_device_pdf_num_ptrs, gx_device_pdf, elt);
133
9.53M
gx_device_pdf_do_param_strings(e1)
134
0
#undef e1
135
433k
#define e1(i,elt) ENUM_STRING_PTR(i + gx_device_pdf_num_ptrs + gx_device_pdf_num_param_strings,\
136
433k
                                 gx_device_pdf, elt);
137
141M
gx_device_pdf_do_const_strings(e1)
138
141M
#undef e1
139
141M
ENUM_PTRS_END
140
433k
static RELOC_PTRS_WITH(device_pdfwrite_reloc_ptrs, gx_device_pdf *pdev)
141
433k
{
142
433k
    RELOC_PREFIX(st_device_psdf);
143
433k
 RELOC_PTR(gx_device_pdf, asides.strm);
144
433k
 RELOC_PTR(gx_device_pdf, asides.strm_buf);
145
433k
 RELOC_PTR(gx_device_pdf, asides.save_strm);
146
433k
 RELOC_PTR(gx_device_pdf, streams.strm);
147
433k
 RELOC_PTR(gx_device_pdf, streams.strm_buf);
148
433k
 RELOC_PTR(gx_device_pdf, ObjStm.strm);
149
433k
 RELOC_PTR(gx_device_pdf, ObjStm.strm_buf);
150
433k
 RELOC_PTR(gx_device_pdf, ObjStm.save_strm);
151
433k
 RELOC_PTR(gx_device_pdf, Catalog);
152
433k
 RELOC_PTR(gx_device_pdf, Info);
153
433k
 RELOC_PTR(gx_device_pdf, Pages);
154
433k
 RELOC_PTR(gx_device_pdf, text);
155
433k
 RELOC_PTR(gx_device_pdf, pages);
156
433k
 RELOC_PTR(gx_device_pdf, cs_Patterns[0]);
157
433k
 RELOC_PTR(gx_device_pdf, cs_Patterns[1]);
158
433k
 RELOC_PTR(gx_device_pdf, cs_Patterns[3]);
159
433k
 RELOC_PTR(gx_device_pdf, cs_Patterns[4]);
160
433k
 RELOC_PTR(gx_device_pdf, last_resource);
161
433k
 RELOC_PTR(gx_device_pdf, articles);
162
433k
 RELOC_PTR(gx_device_pdf, Dests);
163
433k
 RELOC_PTR(gx_device_pdf, global_named_objects);
164
433k
 RELOC_PTR(gx_device_pdf, local_named_objects);
165
433k
 RELOC_PTR(gx_device_pdf, NI_stack);
166
433k
 RELOC_PTR(gx_device_pdf, Namespace_stack);
167
433k
 RELOC_PTR(gx_device_pdf, font_cache);
168
433k
 RELOC_PTR(gx_device_pdf, clip_path);
169
433k
 RELOC_PTR(gx_device_pdf, PageLabels);
170
433k
 RELOC_PTR(gx_device_pdf, PageLabels_current_label);
171
433k
 RELOC_PTR(gx_device_pdf, sbstack);
172
433k
 RELOC_PTR(gx_device_pdf, substream_Resources);
173
433k
 RELOC_PTR(gx_device_pdf, font3);
174
433k
 RELOC_PTR(gx_device_pdf, accumulating_substream_resource);
175
433k
 RELOC_PTR(gx_device_pdf, pres_soft_mask_dict);
176
433k
 RELOC_PTR(gx_device_pdf, PDFXTrimBoxToMediaBoxOffset.data);
177
433k
 RELOC_PTR(gx_device_pdf, PDFXBleedBoxToTrimBoxOffset.data);
178
433k
 RELOC_PTR(gx_device_pdf, Identity_ToUnicode_CMaps[0]);
179
433k
 RELOC_PTR(gx_device_pdf, Identity_ToUnicode_CMaps[1]);
180
433k
 RELOC_PTR(gx_device_pdf, vgstack);
181
433k
 RELOC_PTR(gx_device_pdf, EmbeddedFiles);
182
433k
 RELOC_PTR(gx_device_pdf, AF);
183
433k
 RELOC_PTR(gx_device_pdf, pdf_font_dir);
184
433k
 RELOC_PTR(gx_device_pdf, ExtensionMetadata);
185
433k
 RELOC_PTR(gx_device_pdf, PassThroughWriter);
186
2.16M
#define r1(i,elt) RELOC_PARAM_STRING_PTR(gx_device_pdf,elt);
187
2.16M
        gx_device_pdf_do_param_strings(r1)
188
433k
#undef r1
189
433k
#define r1(i,elt) RELOC_CONST_STRING_PTR(gx_device_pdf,elt);
190
433k
        gx_device_pdf_do_const_strings(r1)
191
433k
#undef r1
192
433k
    {
193
433k
        int i, j;
194
195
7.36M
        for (i = 0; i < NUM_RESOURCE_TYPES; ++i)
196
117M
            for (j = 0; j < NUM_RESOURCE_CHAINS; ++j)
197
110M
                RELOC_PTR(gx_device_pdf, resources[i].chains[j]);
198
433k
        if (pdev->outline_levels) {
199
163k
            for (i = 0; i <= pdev->outline_depth; ++i) {
200
81.6k
                RELOC_PTR(gx_device_pdf, outline_levels[i].first.action);
201
81.6k
                RELOC_PTR(gx_device_pdf, outline_levels[i].last.action);
202
81.6k
            }
203
81.6k
        }
204
433k
        for (i = 0; i < pdev->PatternDepth; i++) {
205
2
            RELOC_PTR(gx_device_pdf, initial_pattern_states[i]);
206
2
        }
207
433k
    }
208
433k
 RELOC_PTR(gx_device_pdf, outline_levels);
209
433k
}
210
433k
RELOC_PTRS_END
211
/* Even though device_pdfwrite_finalize is the same as gx_device_finalize, */
212
/* we need to implement it separately because st_composite_final */
213
/* declares all 3 procedures as private. */
214
static void
215
device_pdfwrite_finalize(const gs_memory_t *cmem, void *vpdev)
216
208k
{
217
208k
    gx_device_finalize(cmem, vpdev);
218
208k
}
219
220
/* Driver procedures */
221
static dev_proc_initialize_device(pdfwrite_initialize_device);
222
static dev_proc_open_device(pdf_open);
223
static dev_proc_output_page(pdf_output_page);
224
static dev_proc_close_device(pdf_close);
225
/* Driver procedures defined in other files are declared in gdevpdfx.h. */
226
227
#ifndef X_DPI
228
#  define X_DPI 720
229
#endif
230
#ifndef Y_DPI
231
#  define Y_DPI 720
232
#endif
233
234
/* ---------------- Device prototype ---------------- */
235
236
static void
237
pdfwrite_initialize_device_procs(gx_device *dev)
238
208k
{
239
208k
    set_dev_proc(dev, initialize_device, pdfwrite_initialize_device);
240
208k
    set_dev_proc(dev, open_device, pdf_open);
241
208k
    set_dev_proc(dev, get_initial_matrix, gx_upright_get_initial_matrix);
242
208k
    set_dev_proc(dev, output_page, pdf_output_page);
243
208k
    set_dev_proc(dev, close_device, pdf_close);
244
208k
    set_dev_proc(dev, map_rgb_color, gx_default_rgb_map_rgb_color);
245
208k
    set_dev_proc(dev, map_color_rgb, gx_default_rgb_map_color_rgb);
246
208k
    set_dev_proc(dev, fill_rectangle, gdev_pdf_fill_rectangle);
247
208k
    set_dev_proc(dev, copy_mono, gdev_pdf_copy_mono);
248
208k
    set_dev_proc(dev, copy_color, gdev_pdf_copy_color);
249
208k
    set_dev_proc(dev, get_params, gdev_pdf_get_params);
250
208k
    set_dev_proc(dev, put_params, gdev_pdf_put_params);
251
208k
    set_dev_proc(dev, get_page_device, gx_page_device_get_page_device);
252
208k
    set_dev_proc(dev, fill_path, gdev_pdf_fill_path);
253
208k
    set_dev_proc(dev, stroke_path, gdev_pdf_stroke_path);
254
208k
    set_dev_proc(dev, fill_mask, gdev_pdf_fill_mask);
255
208k
    set_dev_proc(dev, strip_tile_rectangle, gdev_pdf_strip_tile_rectangle);
256
208k
    set_dev_proc(dev, begin_typed_image, gdev_pdf_begin_typed_image);
257
208k
    set_dev_proc(dev, get_bits_rectangle, psdf_get_bits_rectangle);
258
208k
    set_dev_proc(dev, composite, gdev_pdf_composite);
259
208k
    set_dev_proc(dev, text_begin, gdev_pdf_text_begin);
260
208k
    set_dev_proc(dev, begin_transparency_group, gdev_pdf_begin_transparency_group);
261
208k
    set_dev_proc(dev, end_transparency_group, gdev_pdf_end_transparency_group);
262
208k
    set_dev_proc(dev, begin_transparency_mask ,gdev_pdf_begin_transparency_mask);
263
208k
    set_dev_proc(dev, end_transparency_mask, gdev_pdf_end_transparency_mask);
264
208k
    set_dev_proc(dev, fill_rectangle_hl_color, gdev_pdf_fill_rectangle_hl_color);
265
208k
    set_dev_proc(dev, include_color_space, gdev_pdf_include_color_space);
266
208k
    set_dev_proc(dev, fillpage, gdev_pdf_fillpage);
267
208k
    set_dev_proc(dev, dev_spec_op, gdev_pdf_dev_spec_op);
268
208k
    set_dev_proc(dev, fill_stroke_path, gdev_pdf_fill_stroke_path);
269
208k
}
270
271
#define PDF_DEVICE_NAME "pdfwrite"
272
#define PDF_DEVICE_IDENT gs_pdfwrite_device
273
#define PDF_DEVICE_MaxInlineImageSize 4000
274
#define PDF_FOR_OPDFREAD 0
275
#define PDF_FOR_EPS2WRITE 0
276
277
#include "gdevpdfb.h"
278
279
#undef PDF_DEVICE_NAME
280
#undef PDF_DEVICE_IDENT
281
#undef PDF_DEVICE_MaxInlineImageSize
282
#undef PDF_FOR_OPDFREAD
283
284
#define PDF_DEVICE_NAME "ps2write"
285
#define PDF_DEVICE_IDENT gs_ps2write_device
286
#define PDF_DEVICE_MaxInlineImageSize max_long
287
#define PDF_FOR_OPDFREAD 1
288
#define PDF_FOR_EPS2WRITE 0
289
290
#include "gdevpdfb.h"
291
292
#undef PDF_DEVICE_NAME
293
#undef PDF_DEVICE_IDENT
294
#undef PDF_DEVICE_MaxInlineImageSize
295
#undef PDF_FOR_OPDFREAD
296
#undef PDF_FOR_EPS2WRITE
297
298
#define PDF_DEVICE_NAME "eps2write"
299
#define PDF_DEVICE_IDENT gs_eps2write_device
300
#define PDF_DEVICE_MaxInlineImageSize max_long
301
#define PDF_FOR_OPDFREAD 1
302
#define PDF_FOR_EPS2WRITE 1
303
304
#include "gdevpdfb.h"
305
306
#undef PDF_DEVICE_NAME
307
#undef PDF_DEVICE_IDENT
308
#undef PDF_DEVICE_MaxInlineImageSize
309
#undef PDF_FOR_OPDFREAD
310
#undef PDF_FOR_EPS2WRITE
311
/* ---------------- Device open/close ---------------- */
312
313
/* Close and remove temporary files. */
314
int
315
pdf_close_temp_file(gx_device_pdf *pdev, pdf_temp_file_t *ptf, int code)
316
204k
{
317
204k
    int err = 0;
318
204k
    gp_file *file = ptf->file;
319
320
    /*
321
     * ptf->strm == 0 or ptf->file == 0 is only possible if this procedure
322
     * is called to clean up during initialization failure, but ptf->strm
323
     * might not be open if it was finalized before the device was closed.
324
     */
325
204k
    if (ptf->strm) {
326
126k
        if (s_is_valid(ptf->strm)) {
327
126k
            sflush(ptf->strm);
328
            /* Prevent freeing the stream from closing the file. */
329
126k
            ptf->strm->file = 0;
330
126k
        } else
331
0
            ptf->file = file = 0; /* file was closed by finalization */
332
126k
        gs_free_object(pdev->pdf_memory, ptf->strm_buf,
333
126k
                       "pdf_close_temp_file(strm_buf)");
334
126k
        ptf->strm_buf = 0;
335
126k
        gs_free_object(pdev->pdf_memory, ptf->strm,
336
126k
                       "pdf_close_temp_file(strm)");
337
126k
        ptf->strm = 0;
338
126k
    }
339
204k
    if (file) {
340
165k
        err = gp_ferror(file) | gp_fclose(file);
341
165k
        gp_unlink(pdev->memory, ptf->file_name);
342
165k
        ptf->file = 0;
343
165k
    }
344
204k
    ptf->save_strm = 0;
345
204k
    return
346
204k
        (code < 0 ? code : err != 0 ? gs_note_error(gs_error_ioerror) : code);
347
204k
}
348
static int
349
pdf_close_files(gx_device_pdf * pdev, int code)
350
39.3k
{
351
39.3k
    code = pdf_close_temp_file(pdev, &pdev->ObjStm, code);
352
39.3k
    code = pdf_close_temp_file(pdev, &pdev->streams, code);
353
39.3k
    code = pdf_close_temp_file(pdev, &pdev->asides, code);
354
39.3k
    return pdf_close_temp_file(pdev, &pdev->xref, code);
355
39.3k
}
356
357
/* Reset the state of the current page. */
358
static void
359
pdf_reset_page(gx_device_pdf * pdev)
360
90.6k
{
361
90.6k
    pdev->page_dsc_info = gs_pdfwrite_device.page_dsc_info;
362
90.6k
    pdev->contents_id = 0;
363
90.6k
    pdf_reset_graphics(pdev);
364
90.6k
    pdev->procsets = NoMarks;
365
90.6k
    memset(pdev->cs_Patterns, 0, sizeof(pdev->cs_Patterns));  /* simplest to create for each page */
366
90.6k
    pdf_reset_text_page(pdev->text);
367
90.6k
    pdf_remember_clip_path(pdev, 0);
368
90.6k
    pdev->clip_path_id = pdev->no_clip_path_id;
369
90.6k
}
370
371
/* Open a temporary file, with or without a stream. */
372
int
373
pdf_open_temp_file(gx_device_pdf *pdev, pdf_temp_file_t *ptf)
374
165k
{
375
165k
    char fmode[4];
376
377
165k
    if (strlen(gp_fmode_binary_suffix) > 2)
378
0
        return_error(gs_error_invalidfileaccess);
379
380
165k
    strcpy(fmode, "w+");
381
165k
    strcat(fmode, gp_fmode_binary_suffix);
382
165k
    ptf->file = gp_open_scratch_file(pdev->memory,
383
165k
                                     gp_scratch_file_name_prefix,
384
165k
                                     ptf->file_name,
385
165k
                                     fmode);
386
165k
    if (ptf->file == 0)
387
0
        return_error(gs_error_invalidfileaccess);
388
165k
    return 0;
389
165k
}
390
int
391
pdf_open_temp_stream(gx_device_pdf *pdev, pdf_temp_file_t *ptf)
392
126k
{
393
126k
    int code = pdf_open_temp_file(pdev, ptf);
394
395
126k
    if (code < 0)
396
0
        return code;
397
126k
    ptf->strm = s_alloc(pdev->pdf_memory, "pdf_open_temp_stream(strm)");
398
126k
    if (ptf->strm == 0)
399
0
        return_error(gs_error_VMerror);
400
126k
    ptf->strm_buf = gs_alloc_bytes(pdev->pdf_memory, sbuf_size,
401
126k
                                   "pdf_open_temp_stream(strm_buf)");
402
126k
    if (ptf->strm_buf == 0) {
403
0
        gs_free_object(pdev->pdf_memory, ptf->strm,
404
0
                       "pdf_open_temp_stream(strm)");
405
0
        ptf->strm = 0;
406
0
        return_error(gs_error_VMerror);
407
0
    }
408
126k
    swrite_file(ptf->strm, ptf->file, ptf->strm_buf, sbuf_size);
409
126k
    return 0;
410
126k
}
411
412
/* Initialize the IDs allocated at startup. */
413
void
414
pdf_initialize_ids(gx_device_pdf * pdev)
415
39.3k
{
416
39.3k
    gs_param_string nstr;
417
418
39.3k
    pdev->next_id = pdev->FirstObjectNumber;
419
420
    /* Initialize the Catalog. */
421
422
39.3k
    param_string_from_string(nstr, "{Catalog}");
423
39.3k
    pdf_create_named_dict(pdev, &nstr, &pdev->Catalog, 0L);
424
425
    /* Initialize the Info dictionary. */
426
427
39.3k
    param_string_from_string(nstr, "{DocInfo}");
428
39.3k
    pdf_create_named_dict(pdev, &nstr, &pdev->Info, 0L);
429
39.3k
    {
430
39.3k
        char buf[PDF_MAX_PRODUCER];
431
432
39.3k
        pdf_store_default_Producer(buf);
433
39.3k
        if (pdev->CompatibilityLevel <= 1.7)
434
39.3k
            cos_dict_put_c_key_string(pdev->Info, "/Producer", (byte *)buf,
435
39.3k
                                  strlen(buf));
436
39.3k
    }
437
    /*
438
     * Acrobat Distiller sets CreationDate and ModDate to the current
439
     * date and time, rather than (for example) %%CreationDate from the
440
     * PostScript file.  We think this is wrong, but we do the same.
441
     */
442
39.3k
    if (!pdev->OmitInfoDate)
443
39.3k
    {
444
39.3k
        struct tm tms;
445
39.3k
        time_t t;
446
39.3k
        char buf[1+2+4+2+2+2+2+2+1+2+1+2+1+1+1]; /* (D:yyyymmddhhmmssZhh'mm')\0 */
447
39.3k
        int timeoffset;
448
39.3k
        char timesign;
449
450
#ifdef CLUSTER
451
        memset(&t, 0, sizeof(t));
452
        memset(&tms, 0, sizeof(tms));
453
        timesign = 'Z';
454
        timeoffset = 0;
455
#else
456
39.3k
        time(&t);
457
39.3k
        tms = *gmtime(&t);
458
39.3k
        tms.tm_isdst = -1;
459
39.3k
        timeoffset = (int)difftime(t, mktime(&tms)); /* tz+dst in seconds */
460
39.3k
        timesign = (timeoffset == 0 ? 'Z' : timeoffset < 0 ? '-' : '+');
461
39.3k
        timeoffset = any_abs(timeoffset) / 60;
462
39.3k
        tms = *localtime(&t);
463
39.3k
#endif
464
465
39.3k
        gs_snprintf(buf, sizeof(buf), "(D:%04d%02d%02d%02d%02d%02d%c%02d\'%02d\')",
466
39.3k
            tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
467
39.3k
            tms.tm_hour, tms.tm_min, tms.tm_sec,
468
39.3k
            timesign, timeoffset / 60, timeoffset % 60);
469
470
39.3k
        cos_dict_put_c_key_string(pdev->Info, "/CreationDate", (byte *)buf,
471
39.3k
                                  strlen(buf));
472
39.3k
        cos_dict_put_c_key_string(pdev->Info, "/ModDate", (byte *)buf,
473
39.3k
                                  strlen(buf));
474
39.3k
    }
475
476
    /* Allocate the root of the pages tree. */
477
478
39.3k
    pdf_create_named_dict(pdev, NULL, &pdev->Pages, 0L);
479
39.3k
}
480
481
static int
482
pdf_compute_fileID(gx_device_pdf * pdev)
483
39.3k
{
484
485
    /* We compute a file identifier when beginning a document
486
       to allow its usage with PDF encryption. Due to that,
487
       in contradiction to the Adobe recommendation, our
488
       ID doesn't depend on the document size.
489
    */
490
39.3k
    gs_memory_t *mem = pdev->pdf_memory;
491
39.3k
    stream *strm = pdev->strm;
492
39.3k
    uint ignore;
493
39.3k
    int code;
494
39.3k
    stream *s = s_MD5E_make_stream(mem, pdev->fileID, sizeof(pdev->fileID));
495
39.3k
    long secs_ns[2];
496
39.3k
    uint KeyLength = pdev->KeyLength;
497
498
39.3k
    if (s == NULL)
499
0
        return_error(gs_error_VMerror);
500
39.3k
    pdev->KeyLength = 0; /* Disable encryption. Not so important though. */
501
#ifdef CLUSTER
502
    secs_ns[0] = 0;
503
    secs_ns[1] = 0;
504
#else
505
39.3k
    gp_get_realtime(secs_ns);
506
39.3k
#endif
507
39.3k
    sputs(s, (byte *)secs_ns, sizeof(secs_ns), &ignore);
508
#ifdef CLUSTER
509
    /* Don't have the ID's vary by filename output in the cluster testing.
510
     * This prevents us comparing gs to gpdl results, and makes it harder
511
     * to manually reproduce results. */
512
    sputs(s, (const byte *)"ClusterTest.pdf", strlen("ClusterTest.pdf"), &ignore);
513
#else
514
39.3k
    sputs(s, (const byte *)pdev->fname, strlen(pdev->fname), &ignore);
515
39.3k
#endif
516
39.3k
    pdev->strm = s;
517
39.3k
    code = cos_dict_elements_write(pdev->Info, pdev);
518
39.3k
    pdev->strm = strm;
519
39.3k
    pdev->KeyLength = KeyLength;
520
39.3k
    if (code < 0)
521
0
        return code;
522
    /* Generally we would call s_close_filters() here in order to free the data buffer
523
     * associated with the MD5 filter, but the data buffer we passed in to s_MD5E_make_stream()
524
     * is part of the device structure, so we must *NOT* free that buffer. Therefore we must
525
     * instead call sclose(). This confusion over ownership of the stream buffers causes
526
     * a lot of problems......
527
     */
528
39.3k
    sclose(s);
529
39.3k
    gs_free_object(mem, s, "pdf_compute_fileID");
530
39.3k
    return 0;
531
39.3k
}
532
533
static const byte pad[32] = { 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
534
                               0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
535
                               0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
536
                               0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A};
537
538
static inline void
539
copy_padded(byte buf[32], gs_param_string *str)
540
0
{
541
0
    memcpy(buf, str->data, min(str->size, 32));
542
0
    if (32 > str->size)
543
0
        memcpy(buf + str->size, pad, 32 - str->size);
544
0
}
545
546
static void
547
Adobe_magic_loop_50(byte digest[16], int key_length)
548
0
{
549
0
    gs_md5_state_t md5;
550
0
    int i;
551
552
0
    for (i = 0; i < 50; i++) {
553
0
        gs_md5_init(&md5);
554
0
        gs_md5_append(&md5, digest, key_length);
555
0
        gs_md5_finish(&md5, digest);
556
0
    }
557
0
}
558
559
static void
560
Adobe_magic_loop_19(byte *data, int data_size, const byte *key, int key_size)
561
0
{
562
0
    stream_arcfour_state sarc4;
563
0
    byte key_buf[16];
564
0
    int i, j;
565
566
0
    for (i = 1; i <= 19; i++) {
567
0
        for (j = 0; j < key_size; j++)
568
0
            key_buf[j] = key[j] ^ (byte)i;
569
0
        s_arcfour_set_key(&sarc4, key_buf, key_size);
570
0
        s_arcfour_process_buffer(&sarc4, data, data_size);
571
0
    }
572
0
}
573
574
static int
575
pdf_compute_encryption_data(gx_device_pdf * pdev)
576
0
{
577
0
    gs_md5_state_t md5;
578
0
    byte digest[16], buf[32], t;
579
0
    stream_arcfour_state sarc4;
580
581
0
    if (pdev->PDFX > 1 && pdev->KeyLength != 0) {
582
0
        emprintf(pdev->memory,
583
0
                 "Encryption is not allowed in a PDF/X-3 doucment.\n");
584
0
        return_error(gs_error_rangecheck);
585
0
    }
586
0
    if (pdev->KeyLength == 0)
587
0
        pdev->KeyLength = 40;
588
0
    if (pdev->EncryptionV == 0 && pdev->KeyLength == 40)
589
0
        pdev->EncryptionV = 1;
590
0
    if (pdev->EncryptionV == 0 && pdev->KeyLength > 40)
591
0
        pdev->EncryptionV = 2;
592
0
    if (pdev->EncryptionV > 1 && pdev->CompatibilityLevel < 1.4) {
593
0
        emprintf(pdev->memory, "PDF 1.3 only supports 40 bits keys.\n");
594
0
        return_error(gs_error_rangecheck);
595
0
    }
596
0
    if (pdev->EncryptionR == 0)
597
0
        pdev->EncryptionR = 2;
598
0
    if (pdev->EncryptionR < 2 || pdev->EncryptionR > 3) {
599
0
        emprintf(pdev->memory,
600
0
                 "Encryption revisions 2 and 3 are only supported.\n");
601
0
        return_error(gs_error_rangecheck);
602
0
    }
603
0
    if (pdev->EncryptionR > 2 && pdev->CompatibilityLevel < 1.4) {
604
0
        emprintf(pdev->memory,
605
0
                 "PDF 1.3 only supports the encryption revision 2.\n");
606
0
        return_error(gs_error_rangecheck);
607
0
    }
608
0
    if (pdev->KeyLength > 128) {
609
0
        emprintf(pdev->memory,
610
0
                 "The maximal length of PDF encryption key is 128 bits.\n");
611
0
        return_error(gs_error_rangecheck);
612
0
    }
613
0
    if (pdev->KeyLength % 8) {
614
0
        emprintf(pdev->memory,
615
0
                 "PDF encryption key length must be a multiple of 8.\n");
616
0
        return_error(gs_error_rangecheck);
617
0
    }
618
0
    if (pdev->EncryptionR == 2 &&
619
0
        ((pdev->Permissions & (0xFFFFFFC3)) != 0xFFFFFFC0)) {
620
0
        emprintf(pdev->memory,
621
0
                 "Some of Permissions are not allowed with R=2.\n");
622
0
        return_error(gs_error_rangecheck);
623
0
    }
624
0
    if (pdev->EncryptionV == 2 && pdev->EncryptionR == 2 && pdev->KeyLength > 40) {
625
0
        emprintf(pdev->memory, "Encryption version 2 revision 2 with "
626
0
                 "KeyLength > 40 appears incompatible to some viewers. With "
627
0
                 "long keys use revision 3.\n");
628
0
        return_error(gs_error_rangecheck);
629
0
    }
630
    /* Compute O : */
631
0
    gs_md5_init(&md5);
632
0
    copy_padded(buf, &pdev->OwnerPassword);
633
0
    gs_md5_append(&md5, buf, sizeof(buf));
634
0
    gs_md5_finish(&md5, digest);
635
0
    if (pdev->EncryptionR == 3)
636
0
        Adobe_magic_loop_50(digest, pdev->KeyLength / 8);
637
0
    copy_padded(buf, &pdev->UserPassword);
638
0
    s_arcfour_set_key(&sarc4, digest, pdev->KeyLength / 8);
639
0
    s_arcfour_process_buffer(&sarc4, buf, sizeof(buf));
640
0
    if (pdev->EncryptionR == 3)
641
0
        Adobe_magic_loop_19(buf, sizeof(buf), digest, pdev->KeyLength / 8);
642
0
    memcpy(pdev->EncryptionO, buf, sizeof(pdev->EncryptionO));
643
    /* Compute Key : */
644
0
    gs_md5_init(&md5);
645
0
    copy_padded(buf, &pdev->UserPassword);
646
0
    gs_md5_append(&md5, buf, sizeof(buf));
647
0
    gs_md5_append(&md5, pdev->EncryptionO, sizeof(pdev->EncryptionO));
648
0
    t = (byte)(pdev->Permissions >>  0);  gs_md5_append(&md5, &t, 1);
649
0
    t = (byte)(pdev->Permissions >>  8);  gs_md5_append(&md5, &t, 1);
650
0
    t = (byte)(pdev->Permissions >> 16);  gs_md5_append(&md5, &t, 1);
651
0
    t = (byte)(pdev->Permissions >> 24);  gs_md5_append(&md5, &t, 1);
652
0
    gs_md5_append(&md5, pdev->fileID, sizeof(pdev->fileID));
653
0
    if (pdev->EncryptionR == 3)
654
0
        if (!pdev->EncryptMetadata) {
655
0
            const byte v[4] = {0xFF, 0xFF, 0xFF, 0xFF};
656
657
0
            gs_md5_append(&md5, v, 4);
658
0
        }
659
0
    gs_md5_finish(&md5, digest);
660
0
    if (pdev->EncryptionR == 3)
661
0
        Adobe_magic_loop_50(digest, pdev->KeyLength / 8);
662
0
    memcpy(pdev->EncryptionKey, digest, pdev->KeyLength / 8);
663
    /* Compute U : */
664
0
    if (pdev->EncryptionR == 3) {
665
0
        gs_md5_init(&md5);
666
0
        gs_md5_append(&md5, pad, sizeof(pad));
667
0
        gs_md5_append(&md5, pdev->fileID, sizeof(pdev->fileID));
668
0
        gs_md5_finish(&md5, digest);
669
0
        s_arcfour_set_key(&sarc4, pdev->EncryptionKey, pdev->KeyLength / 8);
670
0
        s_arcfour_process_buffer(&sarc4, digest, sizeof(digest));
671
0
        Adobe_magic_loop_19(digest, sizeof(digest), pdev->EncryptionKey, pdev->KeyLength / 8);
672
0
        memcpy(pdev->EncryptionU, digest, sizeof(digest));
673
0
        memcpy(pdev->EncryptionU + sizeof(digest), pad,
674
0
                sizeof(pdev->EncryptionU) - sizeof(digest));
675
0
    } else {
676
0
        memcpy(pdev->EncryptionU, pad, sizeof(pdev->EncryptionU));
677
0
        s_arcfour_set_key(&sarc4, pdev->EncryptionKey, pdev->KeyLength / 8);
678
0
        s_arcfour_process_buffer(&sarc4, pdev->EncryptionU, sizeof(pdev->EncryptionU));
679
0
    }
680
0
    return 0;
681
0
}
682
683
#ifdef __DECC
684
/* The ansi alias rules are violated in this next routine.  Tell the compiler
685
   to ignore this.
686
 */
687
#pragma optimize save
688
#pragma optimize ansi_alias=off
689
#endif
690
/*
691
 * Update the color mapping procedures after setting ProcessColorModel.
692
 *
693
 * The 'index' value indicates the ProcessColorModel.
694
 *  0 = DeviceGray
695
 *  1 = DeviceRGB
696
 *  2 = DeviceCMYK
697
 *  3 = DeviceN (treat like CMYK except for color model name)
698
 */
699
void
700
pdf_set_process_color_model(gx_device_pdf * pdev, int index)
701
26.9k
{
702
26.9k
    const static gx_device_color_info pcm_color_info[] = {
703
26.9k
        dci_values(1, 8, 255, 0, 256, 0),   /* Gray */
704
26.9k
        dci_values(3, 24, 255, 255, 256, 256),    /* RGB */
705
26.9k
        dci_values(4, 32, 255, 255, 256, 256),    /* CMYK */
706
26.9k
        dci_values(4, 32, 255, 255, 256, 256) /* Treat DeviceN like CMYK */
707
26.9k
    };
708
    /* Don't blow away the ICC information */
709
710
26.9k
    pdev->pcm_color_info_index = index;
711
26.9k
    pdev->color_info = pcm_color_info[index];
712
    /* Set the separable and linear shift, masks, bits. */
713
26.9k
    set_linear_color_bits_mask_shift((gx_device *)pdev);
714
26.9k
    pdev->color_info.separable_and_linear = GX_CINFO_SEP_LIN;
715
    /*
716
     * The conversion from PS to PDF should be transparent as possible.
717
     * Particularly it should not change representation of colors.
718
     * Perhaps due to historical reasons the source color information
719
     * sometimes isn't accessible from device methods, and
720
     * therefore they perform a mapping of colors to
721
     * an output color model. Here we handle some color models,
722
     * which were selected almost due to antique reasons.
723
     */
724
26.9k
    switch (index) {
725
0
        case 0:   /* DeviceGray */
726
0
            set_dev_proc(pdev, map_rgb_color, gx_default_gray_map_rgb_color);
727
0
            set_dev_proc(pdev, map_color_rgb, gx_default_gray_map_color_rgb);
728
0
            set_dev_proc(pdev, map_cmyk_color, NULL);
729
0
            set_dev_proc(pdev, get_color_mapping_procs,
730
0
                        gx_default_DevGray_get_color_mapping_procs);
731
0
            set_dev_proc(pdev, get_color_comp_index,
732
0
                        gx_default_DevGray_get_color_comp_index);
733
0
            set_dev_proc(pdev, encode_color, gx_default_gray_encode);
734
0
            set_dev_proc(pdev, decode_color, gx_default_decode_color);
735
0
            break;
736
26.9k
        case 1:   /* DeviceRGB */
737
26.9k
            set_dev_proc(pdev, map_rgb_color, gx_default_rgb_map_rgb_color);
738
26.9k
            set_dev_proc(pdev, map_color_rgb, gx_default_rgb_map_color_rgb);
739
26.9k
            set_dev_proc(pdev, map_cmyk_color, NULL);
740
26.9k
            set_dev_proc(pdev, get_color_mapping_procs,
741
26.9k
                        gx_default_DevRGB_get_color_mapping_procs);
742
26.9k
            set_dev_proc(pdev, get_color_comp_index,
743
26.9k
                        gx_default_DevRGB_get_color_comp_index);
744
26.9k
            set_dev_proc(pdev, encode_color, gx_default_rgb_map_rgb_color);
745
26.9k
            set_dev_proc(pdev, decode_color, gx_default_rgb_map_color_rgb);
746
26.9k
            break;
747
0
        case 3:   /* DeviceN - treat like DeviceCMYK except for cm_name */
748
0
            pdev->color_info.cm_name = "DeviceN";
749
0
        case 2:   /* DeviceCMYK */
750
0
            set_dev_proc(pdev, map_rgb_color, NULL);
751
0
            set_dev_proc(pdev, map_color_rgb, cmyk_8bit_map_color_rgb);
752
           /* possible problems with aliassing on next statement */
753
0
            set_dev_proc(pdev, map_cmyk_color, cmyk_8bit_map_cmyk_color);
754
0
            set_dev_proc(pdev, get_color_mapping_procs,
755
0
                        gx_default_DevCMYK_get_color_mapping_procs);
756
0
            set_dev_proc(pdev, get_color_comp_index,
757
0
                        gx_default_DevCMYK_get_color_comp_index);
758
0
            set_dev_proc(pdev, encode_color, cmyk_8bit_map_cmyk_color);
759
0
            set_dev_proc(pdev, decode_color, cmyk_8bit_map_color_cmyk);
760
0
            break;
761
0
        default:  /* can't happen - see the call from gdev_pdf_put_params. */
762
0
            DO_NOTHING;
763
26.9k
    }
764
26.9k
}
765
#ifdef __DECC
766
#pragma optimize restore
767
#endif
768
769
/*
770
 * Reset the text state parameters to initial values.
771
 */
772
void
773
pdf_reset_text(gx_device_pdf * pdev)
774
641k
{
775
    /* we need to flush the text buffer, in case we have (eg) Tr set,
776
     * but have reset it to 0 for the current (buffered) text. If we restore to a
777
     * graphics state which also has Tr 0 then we won't ever write out the change.
778
     * I suspect this can theoretically happen with other graphics state values too
779
     * See PCL file enter.test.
780
     */
781
641k
    sync_text_state(pdev);
782
641k
    pdf_reset_text_state(pdev->text);
783
641k
}
784
785
static int
786
pdfwrite_initialize_device(gx_device *dev)
787
208k
{
788
#if OCR_VERSION > 0
789
    gx_device_pdf *pdev = (gx_device_pdf *) dev;
790
    const char *default_ocr_lang = "eng";
791
    pdev->ocr_language[0] = '\0';
792
    strcpy(pdev->ocr_language, default_ocr_lang);
793
#endif
794
208k
    return 0;
795
208k
}
796
797
798
/* Open the device. */
799
static int
800
pdf_open(gx_device * dev)
801
39.3k
{
802
39.3k
    gx_device_pdf *pdev = (gx_device_pdf *) dev;
803
39.3k
    gs_memory_t *mem = pdev->pdf_memory = gs_memory_stable(pdev->memory);
804
39.3k
    int code;
805
806
39.3k
    pdev->InOutputPage = false;
807
808
39.3k
    if ((code = pdf_open_temp_file(pdev, &pdev->xref)) < 0 ||
809
39.3k
        (code = pdf_open_temp_stream(pdev, &pdev->asides)) < 0 ||
810
39.3k
        (code = pdf_open_temp_stream(pdev, &pdev->streams))
811
39.3k
        )
812
0
        goto fail;
813
39.3k
    code = gdev_vector_open_file((gx_device_vector *) pdev, sbuf_size);
814
39.3k
    if (code < 0)
815
0
        goto fail;
816
39.3k
    while (pdev->child) {
817
        /* we've been subclassed by gdev_vector_open_file. Ordinarily we would want to call
818
         * open_file last, in order to make sure that we don't care if we are subclessed
819
         * but we want to set up the stream, so we can't do that....
820
         */
821
0
        pdev = (gx_device_pdf *)pdev->child;
822
0
    }
823
39.3k
    if (pdev->ComputeDocumentDigest) {
824
39.3k
        stream *s = s_MD5C_make_stream(pdev->pdf_memory, pdev->strm);
825
826
39.3k
        if (s == NULL)
827
0
            return_error(gs_error_VMerror);
828
39.3k
        pdev->strm = s;
829
39.3k
    }
830
39.3k
    gdev_vector_init((gx_device_vector *) pdev);
831
#ifdef CLUSTER
832
    memset(&pdev->uuid_time, 0, sizeof(pdev->uuid_time));
833
#else
834
39.3k
    gp_get_realtime(pdev->uuid_time);
835
39.3k
#endif
836
39.3k
    pdev->vec_procs = &pdf_vector_procs;
837
39.3k
    pdev->fill_options = pdev->stroke_options = gx_path_type_optimize;
838
    /* Set in_page so the vector routines won't try to call */
839
    /* any vector implementation procedures. */
840
39.3k
    pdev->in_page = true;
841
    /*
842
     * pdf_initialize_ids allocates some (global) named objects, so we must
843
     * initialize the named objects dictionary now.
844
     */
845
39.3k
    pdev->local_named_objects =
846
39.3k
        pdev->global_named_objects =
847
39.3k
        cos_dict_alloc(pdev, "pdf_open(global_named_objects)");
848
39.3k
    if (pdev->local_named_objects == NULL) {
849
0
        code = gs_error_VMerror;
850
0
        goto fail;
851
0
    }
852
    /* Initialize internal structures that don't have IDs. */
853
39.3k
    pdev->NI_stack = cos_array_alloc(pdev, "pdf_open(NI stack)");
854
39.3k
    if (pdev->NI_stack == NULL) {
855
0
        code = gs_error_VMerror;
856
0
        goto fail;
857
0
    }
858
39.3k
    pdev->vgstack = (pdf_viewer_state *)gs_alloc_bytes(pdev->pdf_memory, 11 * sizeof(pdf_viewer_state), "pdf_open(graphics state stack)");
859
39.3k
    if (pdev->vgstack == 0) {
860
0
        code = gs_error_VMerror;
861
0
        goto fail;
862
0
    }
863
39.3k
    memset(pdev->vgstack, 0x00, 11 * sizeof(pdf_viewer_state));
864
39.3k
    pdev->vgstack_size = 11;
865
39.3k
    pdev->Namespace_stack = cos_array_alloc(pdev, "pdf_open(Namespace stack)");
866
39.3k
    if (pdev->Namespace_stack == NULL) {
867
0
        code = gs_error_VMerror;
868
0
        goto fail;
869
0
    }
870
39.3k
    pdf_initialize_ids(pdev);
871
39.3k
    code = pdf_compute_fileID(pdev);
872
39.3k
    if (code < 0)
873
0
        goto fail;
874
39.3k
    if (pdev->OwnerPassword.size > 0) {
875
0
        code = pdf_compute_encryption_data(pdev);
876
0
        if (code < 0)
877
0
            goto fail;
878
39.3k
    } else if(pdev->UserPassword.size > 0) {
879
0
        emprintf(pdev->memory,
880
0
                 "User password is specified. Need an Owner password or both.\n");
881
0
        return_error(gs_error_rangecheck);
882
39.3k
    } else if (pdev->KeyLength) {
883
0
        emprintf(pdev->memory,
884
0
                 "Can't accept encryption options without a password.\n");
885
0
        return_error(gs_error_rangecheck);
886
0
    }
887
    /* Now create a new dictionary for the local named objects. */
888
39.3k
    pdev->local_named_objects =
889
39.3k
        cos_dict_alloc(pdev, "pdf_open(local_named_objects)");
890
39.3k
    if (pdev->local_named_objects == NULL) {
891
0
        code = gs_error_VMerror;
892
0
        goto fail;
893
0
    }
894
39.3k
    pdev->outlines_id = 0;
895
39.3k
    pdev->next_page = 0;
896
39.3k
    pdev->text = pdf_text_data_alloc(mem);
897
39.3k
    pdev->sbstack_size = pdev->vgstack_size; /* Overestimated a few. */
898
39.3k
    pdev->sbstack = gs_alloc_struct_array(mem, pdev->sbstack_size, pdf_substream_save,
899
39.3k
                                 &st_pdf_substream_save_element, "pdf_open");
900
39.3k
    pdev->pages =
901
39.3k
        gs_alloc_struct_array(mem, initial_num_pages, pdf_page_t,
902
39.3k
                              &st_pdf_page_element, "pdf_open(pages)");
903
39.3k
    if (pdev->text == 0 || pdev->pages == 0 || pdev->sbstack == 0) {
904
0
        code = gs_error_VMerror;
905
0
        goto fail;
906
0
    }
907
39.3k
    memset(pdev->sbstack, 0, pdev->sbstack_size * sizeof(pdf_substream_save));
908
39.3k
    memset(pdev->pages, 0, initial_num_pages * sizeof(pdf_page_t));
909
39.3k
    pdev->num_pages = initial_num_pages;
910
39.3k
    {
911
39.3k
        int i, j;
912
913
668k
        for (i = 0; i < NUM_RESOURCE_TYPES; ++i)
914
10.7M
            for (j = 0; j < NUM_RESOURCE_CHAINS; ++j)
915
10.0M
                pdev->resources[i].chains[j] = 0;
916
39.3k
    }
917
39.3k
    pdev->outline_levels = (pdf_outline_level_t *)gs_alloc_bytes(mem, INITIAL_MAX_OUTLINE_DEPTH * sizeof(pdf_outline_level_t), "outline_levels array");
918
39.3k
    if (pdev->outline_levels == NULL) {
919
0
        code = gs_error_VMerror;
920
0
        goto fail;
921
0
    }
922
923
39.3k
    memset(pdev->outline_levels, 0x00, INITIAL_MAX_OUTLINE_DEPTH * sizeof(pdf_outline_level_t));
924
39.3k
    pdev->max_outline_depth = INITIAL_MAX_OUTLINE_DEPTH;
925
39.3k
    pdev->outline_levels[0].first.id = 0;
926
39.3k
    pdev->outline_levels[0].left = max_int;
927
39.3k
    pdev->outline_levels[0].first.action = 0;
928
39.3k
    pdev->outline_levels[0].last.action = 0;
929
39.3k
    pdev->outline_depth = 0;
930
39.3k
    pdev->closed_outline_depth = 0;
931
39.3k
    pdev->outlines_open = 0;
932
39.3k
    pdev->articles = 0;
933
39.3k
    pdev->Dests = 0;
934
39.3k
    pdev->EmbeddedFiles = 0;
935
39.3k
    pdev->AF = 0;
936
    /* {global,local}_named_objects was initialized above */
937
39.3k
    pdev->PageLabels = 0;
938
39.3k
    pdev->PageLabels_current_page = 0;
939
39.3k
    pdev->PageLabels_current_label = 0;
940
39.3k
    pdev->pte = NULL;
941
39.3k
    pdf_reset_page(pdev);
942
39.3k
    pdev->BBox.p.x = pdev->width;
943
39.3k
    pdev->BBox.p.y = pdev->height;
944
39.3k
    pdev->BBox.q.x = 0;
945
39.3k
    pdev->BBox.q.y = 0;
946
947
39.3k
    if(pdev->UseCIEColor) {
948
0
        emprintf(pdev->memory, "\n\nUse of -dUseCIEColor detected!\nSince the release of version 9.11 of Ghostscript we recommend you do not set\n-dUseCIEColor with the pdfwrite/ps2write device family.\n\n");
949
0
    }
950
951
    /* Build a font cache for pdfwrite, see 'pdf_free_pdf_font_cache' for why we need this. */
952
39.3k
    pdev->pdf_font_dir = gs_font_dir_alloc2(pdev->memory->stable_memory, pdev->memory->non_gc_memory);
953
39.3k
    if (pdev->pdf_font_dir == 0) {
954
0
        code = gs_error_VMerror;
955
0
        goto fail;
956
0
    }
957
    /* If we have a gs_lib_ctx, then we need to copy these function pointers from it (we are in PostScript).
958
     * We can't fill them in otherwise, as the functions are declared static in gsfont.c.
959
     * If we don't have one then we are in PCL/PXL/XPS, and cannot copy these function pointers. Fortunately
960
     * we don't need them for fonts in these languages.
961
     */
962
39.3k
    if (pdev->memory->gs_lib_ctx->font_dir) {
963
39.3k
        pdev->pdf_font_dir->ccache.mark_glyph = pdev->memory->gs_lib_ctx->font_dir->ccache.mark_glyph;
964
39.3k
        pdev->pdf_font_dir->global_glyph_code = pdev->memory->gs_lib_ctx->font_dir->global_glyph_code;
965
39.3k
    }
966
967
    /* gs_opendevice() sets the device 'is_open' flag which is now of course the parent. We
968
     * still need to set the child's flag, we'll do it here to avoid setting it if we get any
969
     * failures, as those will also leave the parent not open.
970
     */
971
39.3k
    if (pdev->parent)
972
0
        pdev->is_open = true;
973
974
39.3k
    return 0;
975
0
  fail:
976
0
    gdev_vector_close_file((gx_device_vector *) pdev);
977
0
    return pdf_close_files(pdev, code);
978
39.3k
}
979
980
/* Detect I/O errors. */
981
static int
982
pdf_ferror(gx_device_pdf *pdev)
983
133k
{
984
133k
    int code = 0;
985
986
133k
    if (pdev->file != NULL) {
987
133k
        gp_fflush(pdev->file);
988
133k
        code = gp_ferror(pdev->file);
989
133k
    }
990
133k
    gp_fflush(pdev->xref.file);
991
133k
    if (pdev->strm->file != NULL)
992
0
        sflush(pdev->strm);
993
133k
    if (pdev->asides.strm->file != NULL)
994
133k
        sflush(pdev->asides.strm);
995
133k
    if (pdev->streams.strm->file != NULL)
996
133k
        sflush(pdev->streams.strm);
997
133k
    if (pdev->ObjStm.strm != NULL && pdev->ObjStm.strm->file != NULL) {
998
82.6k
        int code2;
999
82.6k
        sflush(pdev->ObjStm.strm);
1000
82.6k
        code2 = gp_ferror(pdev->ObjStm.file);
1001
82.6k
        if (code >= 0) code = code2;
1002
82.6k
    }
1003
133k
    return gp_ferror(pdev->xref.file) || gp_ferror(pdev->asides.file) ||
1004
133k
           gp_ferror(pdev->streams.file) || code;
1005
133k
}
1006
1007
/* Compute the dominant text orientation of a page. */
1008
static int
1009
pdf_dominant_rotation(const pdf_text_rotation_t *ptr)
1010
55.4k
{
1011
55.4k
    int i, imax = -1;
1012
55.4k
    int64_t max_count = 0;
1013
55.4k
    static const int angles[] = { pdf_text_rotation_angle_values };
1014
1015
332k
    for (i = 0; i < countof(ptr->counts); ++i) {
1016
277k
        int64_t count = ptr->counts[i];
1017
1018
277k
        if (count > max_count)
1019
20.2k
            imax = i, max_count = count;
1020
277k
    }
1021
55.4k
    return (imax < 0 ? imax : angles[imax]);
1022
55.4k
}
1023
1024
/* Print a Rotate command, if requested and possible. */
1025
static void
1026
pdf_print_orientation(gx_device_pdf * pdev, pdf_page_t *page)
1027
74.9k
{
1028
74.9k
    stream *s = pdev->strm;
1029
74.9k
    int dsc_orientation = -1;
1030
74.9k
    const pdf_page_dsc_info_t *ppdi;
1031
1032
74.9k
    if (pdev->params.AutoRotatePages == arp_None)
1033
19.4k
        return; /* Not requested. */
1034
1035
55.4k
    ppdi = (page != NULL ? &page->dsc_info : &pdev->doc_dsc_info);
1036
1037
    /* Determine DSC orientation : */
1038
55.4k
    if (ppdi->viewing_orientation >= 0)
1039
0
        dsc_orientation = ppdi->viewing_orientation;
1040
55.4k
    else if (ppdi->orientation >= 0)
1041
0
        dsc_orientation = ppdi->orientation;
1042
55.4k
    if ((page == NULL && pdev->params.AutoRotatePages == arp_All) || /* document */
1043
55.4k
        (page != NULL && page->text_rotation.Rotate >= 0) || /* page */
1044
43.1k
        dsc_orientation >= 0 /* have DSC */) {
1045
12.2k
        const pdf_text_rotation_t *ptr =
1046
12.2k
            (page != NULL ? &page->text_rotation : &pdev->text_rotation);
1047
12.2k
        int angle = -1;
1048
1049
        /* Combine DSC rotation with text rotation : */
1050
12.2k
        if (dsc_orientation == 0) {
1051
0
            if (ptr->Rotate == 0 || ptr->Rotate == 180)
1052
0
                angle = ptr->Rotate;
1053
12.2k
        } else if (dsc_orientation == 1) {
1054
0
            if (ptr->Rotate == 90 || ptr->Rotate == 270)
1055
0
                angle = ptr->Rotate;
1056
0
            else
1057
0
                angle = 90;
1058
0
        }
1059
1060
12.2k
        if (angle < 0) {
1061
        /* If DSC and heuristic disagree, prefer dsc rotation to match the documented Adobe behaviour */
1062
12.2k
            if (dsc_orientation >= 0)
1063
0
                angle = dsc_orientation * 90;
1064
12.2k
            else
1065
12.2k
                angle = ptr->Rotate;
1066
12.2k
        }
1067
1068
        /* If got some, write it out : */
1069
12.2k
        if (angle >= 0)
1070
12.2k
            pprintd1(s, "/Rotate %d", angle);
1071
12.2k
    }
1072
55.4k
}
1073
1074
/* Close the current page. */
1075
static int
1076
pdf_close_page(gx_device_pdf * pdev, int num_copies)
1077
51.2k
{
1078
51.2k
    int page_num;
1079
51.2k
    pdf_page_t *page;
1080
51.2k
    int code, i;
1081
1082
51.2k
    while (pdev->FormDepth > 0) {
1083
2
        pdev->FormDepth--;
1084
2
        code = pdf_exit_substream(pdev);
1085
2
        if (code < 0)
1086
2
            return code;
1087
2
    }
1088
1089
    /*
1090
     * If the very first page is blank, we need to open the document
1091
     * before doing anything else.
1092
     */
1093
1094
51.2k
    code = pdfwrite_pdf_open_document(pdev);
1095
51.2k
    if (code < 0)
1096
0
        return code;
1097
51.2k
    if (pdev->ForOPDFRead && pdev->context == PDF_IN_NONE) {
1098
        /* Must create a context stream for empty pages. */
1099
6
        code = pdf_open_contents(pdev, PDF_IN_STREAM);
1100
6
        if (code < 0)
1101
3
            return code;
1102
6
    }
1103
51.2k
    pdf_close_contents(pdev, true);
1104
1105
51.2k
    if (!pdev->DoNumCopies)
1106
51.2k
        num_copies = 1;
1107
1108
102k
    for(i=0;i<num_copies;i++) {
1109
51.2k
        bool clear_resource_use = i < num_copies - 1 ? 0 : 1;
1110
1111
51.2k
        page_num = ++(pdev->next_page);
1112
        /*
1113
         * We can't write the page object or the annotations array yet, because
1114
         * later pdfmarks might add elements to them.  Write the other objects
1115
         * that the page references, and record what we'll need later.
1116
         *
1117
         * Start by making sure the pages array element exists.
1118
         */
1119
1120
51.2k
        pdf_page_id(pdev, page_num);
1121
51.2k
        page = &pdev->pages[page_num - 1];
1122
51.2k
        page->MediaBox.x = pdev->MediaSize[0];
1123
51.2k
        page->MediaBox.y = pdev->MediaSize[1];
1124
51.2k
        page->contents_id = pdev->contents_id;
1125
51.2k
        page->NumCopies_set = pdev->NumCopies_set;
1126
51.2k
        page->NumCopies = pdev->NumCopies;
1127
51.2k
        page->UserUnit = pdev->UserUnit;
1128
51.2k
        pdf_record_usage(pdev, pdev->contents_id, pdev->next_page);
1129
51.2k
        pdf_record_usage(pdev, pdev->contents_length_id, pdev->next_page);
1130
51.2k
        pdf_record_usage(pdev, page->Page->id, pdev->next_page);
1131
1132
        /* pdf_store_page_resources sets procsets, resource_ids[]. */
1133
51.2k
        code = pdf_store_page_resources(pdev, page, clear_resource_use);
1134
51.2k
        if (code < 0)
1135
0
            return code;
1136
1137
        /* Write the Functions. */
1138
1139
51.2k
        code = pdf_write_resource_objects(pdev, resourceFunction);
1140
51.2k
        if (code < 0)
1141
0
            return code;
1142
1143
        /* Close use of text on the page. */
1144
1145
51.2k
        pdf_close_text_page(pdev);
1146
1147
        /* Accumulate text rotation. */
1148
1149
51.2k
        page->text_rotation.Rotate =
1150
51.2k
            (pdev->params.AutoRotatePages == arp_PageByPage ?
1151
31.8k
            pdf_dominant_rotation(&page->text_rotation) : -1);
1152
51.2k
        {
1153
51.2k
            int i;
1154
1155
307k
            for (i = 0; i < countof(page->text_rotation.counts); ++i)
1156
256k
                pdev->text_rotation.counts[i] += page->text_rotation.counts[i];
1157
51.2k
        }
1158
1159
        /* Record information from DSC comments. */
1160
1161
51.2k
        page->dsc_info = pdev->page_dsc_info;
1162
51.2k
        if (page->dsc_info.orientation < 0)
1163
51.2k
            page->dsc_info.orientation = pdev->doc_dsc_info.orientation;
1164
        /* Bug 688793 */
1165
51.2k
        if (page->dsc_info.viewing_orientation < 0)
1166
51.2k
        page->dsc_info.viewing_orientation =
1167
51.2k
           pdev->doc_dsc_info.viewing_orientation;
1168
51.2k
        if (page->dsc_info.bounding_box.p.x >= page->dsc_info.bounding_box.q.x ||
1169
0
            page->dsc_info.bounding_box.p.y >= page->dsc_info.bounding_box.q.y
1170
51.2k
            )
1171
51.2k
            page->dsc_info.bounding_box = pdev->doc_dsc_info.bounding_box;
1172
1173
        /* Finish up. */
1174
1175
51.2k
        if(pdf_ferror(pdev))
1176
0
            return(gs_note_error(gs_error_ioerror));
1177
51.2k
    }
1178
51.2k
    pdf_reset_page(pdev);
1179
51.2k
    return (pdf_ferror(pdev) ? gs_note_error(gs_error_ioerror) : 0);
1180
51.2k
}
1181
1182
/* Write the page object. */
1183
static double
1184
round_box_coord(double xy)
1185
102k
{
1186
102k
    return (int)(xy * 100 + 0.5) / 100.0;
1187
102k
}
1188
static int check_annot_in_named(void *client_data, const byte *key_data, uint key_size, const cos_value_t *value)
1189
2.35M
{
1190
2.35M
    cos_value_t *v = (cos_value_t *)client_data;
1191
1192
2.35M
    if (value->contents.object == v->contents.object)
1193
0
        return 1;
1194
2.35M
    return 0;
1195
2.35M
}
1196
1197
static int
1198
pdf_write_page(gx_device_pdf *pdev, int page_num)
1199
51.2k
{
1200
51.2k
    int64_t page_id;
1201
51.2k
    pdf_page_t *page;
1202
51.2k
    double mediabox[4] = {0, 0};
1203
51.2k
    stream *s;
1204
51.2k
    const cos_value_t *v_mediabox = NULL;
1205
1206
51.2k
    if (pdev->pages == NULL)
1207
0
        return_error(gs_error_undefined);
1208
1209
51.2k
    page = &pdev->pages[page_num - 1];
1210
51.2k
    if (page->Page != NULL)
1211
51.2k
        v_mediabox = cos_dict_find_c_key(page->Page, "/MediaBox");
1212
51.2k
    page_id = pdf_page_id(pdev, page_num);
1213
1214
    /* If we have not been given a MediaBox overriding pdfmark, use the current media size. */
1215
51.2k
    s = pdev->strm;
1216
51.2k
    pdf_open_obj(pdev, page_id, resourcePage);
1217
1218
51.2k
    if (v_mediabox == NULL ) {
1219
51.2k
        mediabox[2] = round_box_coord(page->MediaBox.x);
1220
51.2k
        mediabox[3] = round_box_coord(page->MediaBox.y);
1221
51.2k
        pprintg2(s, "<</Type/Page/MediaBox [0 0 %g %g]\n",
1222
51.2k
                mediabox[2], mediabox[3]);
1223
51.2k
    } else {
1224
0
        const byte *p = v_mediabox->contents.chars.data;
1225
0
        char buf[100];
1226
0
        int i, l = min (v_mediabox->contents.chars.size, sizeof(buf) - 1);
1227
0
        float temp[4]; /* the type is float for sscanf. */
1228
1229
0
        temp[0] = temp[1] = 0;
1230
0
        temp[2] = round_box_coord(page->MediaBox.x);
1231
0
        temp[3] = round_box_coord(page->MediaBox.y);
1232
0
        memcpy(buf, p, l);
1233
0
        buf[l] = 0;
1234
0
        if (sscanf(buf, "[ %g %g %g %g ]",
1235
0
                &temp[0], &temp[1], &temp[2], &temp[3]) == 4) {
1236
0
            if (page->Page)
1237
0
             cos_dict_delete_c_key(page->Page, "/MediaBox");
1238
0
        }
1239
0
        pprintg4(s, "<</Type/Page/MediaBox [%g %g %g %g]\n",
1240
0
                temp[0], temp[1], temp[2], temp[3]);
1241
0
        for (i=0;i<4;i++)
1242
0
            mediabox[i] = temp[i];
1243
0
    }
1244
51.2k
    if (pdev->PDFX != 0) {
1245
0
        const cos_value_t *v_trimbox = NULL;
1246
0
        const cos_value_t *v_artbox = NULL;
1247
0
        const cos_value_t *v_cropbox = NULL;
1248
0
        const cos_value_t *v_bleedbox = NULL;
1249
0
        float trimbox[4] = {0, 0}, bleedbox[4] = {0, 0}, artbox[4] = {0, 0}, cropbox[4] = {0, 0};
1250
0
        bool print_bleedbox = false;
1251
1252
0
        if (page->Page != NULL) {
1253
0
            v_trimbox = cos_dict_find_c_key(page->Page, "/TrimBox");
1254
0
            v_artbox = cos_dict_find_c_key(page->Page, "/ArtBox");
1255
0
            v_cropbox = cos_dict_find_c_key(page->Page, "/CropBox");
1256
0
            v_bleedbox = cos_dict_find_c_key(page->Page, "/BleedBox");
1257
0
        }
1258
1259
0
        cropbox[2] = trimbox[2] = bleedbox[2] = mediabox[2];
1260
0
        cropbox[3] = trimbox[3] = bleedbox[3] = mediabox[3];
1261
        /* Offsets are [left right top bottom] according to the Acrobat 7.0
1262
           distiller parameters manual, 12/7/2004, pp. 102-103. */
1263
0
        if (v_trimbox != NULL && v_trimbox->value_type == COS_VALUE_SCALAR) {
1264
0
            const byte *p = v_trimbox->contents.chars.data;
1265
0
            char buf[100];
1266
0
            int l = min (v_trimbox->contents.chars.size, sizeof(buf) - 1);
1267
0
            float temp[4]; /* the type is float for sscanf. */
1268
1269
0
            memcpy(buf, p, l);
1270
0
            buf[l] = 0;
1271
0
            if (sscanf(buf, "[ %g %g %g %g ]",
1272
0
                    &temp[0], &temp[1], &temp[2], &temp[3]) == 4) {
1273
0
                trimbox[0] = temp[0];
1274
0
                trimbox[1] = temp[1];
1275
0
                trimbox[2] = temp[2];
1276
0
                trimbox[3] = temp[3];
1277
0
                if (page->Page != NULL)
1278
0
                    cos_dict_delete_c_key(page->Page, "/TrimBox");
1279
0
            }
1280
0
            if (v_artbox != NULL && v_artbox->value_type == COS_VALUE_SCALAR && page->Page != NULL)
1281
0
                cos_dict_delete_c_key(page->Page, "/ArtBox");
1282
1283
0
        } else if (v_artbox != NULL && v_artbox->value_type == COS_VALUE_SCALAR) {
1284
            /* We have no TrimBox, but we ahve an ArtBox, set the TrimBox to be
1285
             * the supplied ArtBox (TrimBox is preferred for PDF/X)
1286
             */
1287
0
            const byte *p = v_artbox->contents.chars.data;
1288
0
            char buf[100];
1289
0
            int l = min (v_artbox->contents.chars.size, sizeof(buf) - 1);
1290
0
            float temp[4]; /* the type is float for sscanf. */
1291
1292
0
            memcpy(buf, p, l);
1293
0
            buf[l] = 0;
1294
0
            if (sscanf(buf, "[ %g %g %g %g ]",
1295
0
                    &temp[0], &temp[1], &temp[2], &temp[3]) == 4) {
1296
0
                if (pdev->PDFX == 3) {
1297
0
                    trimbox[0] = temp[0];
1298
0
                    trimbox[1] = temp[1];
1299
0
                    trimbox[2] = temp[2];
1300
0
                    trimbox[3] = temp[3];
1301
0
                    if (page->Page != NULL)
1302
0
                        cos_dict_delete_c_key(page->Page, "/ArtBox");
1303
0
                } else {
1304
0
                    artbox[0] = temp[0];
1305
0
                    artbox[1] = temp[1];
1306
0
                    artbox[2] = temp[2];
1307
0
                    artbox[3] = temp[3];
1308
0
                }
1309
0
            }
1310
0
        } else {
1311
0
            if (pdev->PDFXTrimBoxToMediaBoxOffset.size >= 4 &&
1312
0
                    pdev->PDFXTrimBoxToMediaBoxOffset.data[0] >= 0 &&
1313
0
                    pdev->PDFXTrimBoxToMediaBoxOffset.data[1] >= 0 &&
1314
0
                    pdev->PDFXTrimBoxToMediaBoxOffset.data[2] >= 0 &&
1315
0
                    pdev->PDFXTrimBoxToMediaBoxOffset.data[3] >= 0) {
1316
0
                trimbox[0] = mediabox[0] + pdev->PDFXTrimBoxToMediaBoxOffset.data[0];
1317
0
                trimbox[1] = mediabox[1] + pdev->PDFXTrimBoxToMediaBoxOffset.data[3];
1318
0
                trimbox[2] = mediabox[2] - pdev->PDFXTrimBoxToMediaBoxOffset.data[1];
1319
0
                trimbox[3] = mediabox[3] - pdev->PDFXTrimBoxToMediaBoxOffset.data[2];
1320
0
            }
1321
0
        }
1322
1323
0
        if (v_bleedbox != NULL && v_bleedbox->value_type == COS_VALUE_SCALAR) {
1324
0
            const byte *p = v_bleedbox->contents.chars.data;
1325
0
            char buf[100];
1326
0
            int l = min (v_bleedbox->contents.chars.size, sizeof(buf) - 1);
1327
0
            float temp[4]; /* the type is float for sscanf. */
1328
1329
0
            memcpy(buf, p, l);
1330
0
            buf[l] = 0;
1331
0
            if (sscanf(buf, "[ %g %g %g %g ]",
1332
0
                    &temp[0], &temp[1], &temp[2], &temp[3]) == 4) {
1333
0
                if (temp[0] < mediabox[0])
1334
0
                    bleedbox[0] = mediabox[0];
1335
0
                else
1336
0
                    bleedbox[0] = temp[0];
1337
0
                if (temp[1] < mediabox[1])
1338
0
                    bleedbox[1] = mediabox[1];
1339
0
                else
1340
0
                    bleedbox[1] = temp[1];
1341
0
                if (temp[2] > mediabox[2])
1342
0
                    bleedbox[2] = mediabox[2];
1343
0
                else
1344
0
                    bleedbox[2] = temp[2];
1345
0
                if (temp[3] > mediabox[3])
1346
0
                    bleedbox[3] = mediabox[3];
1347
0
                else
1348
0
                    bleedbox[3] = temp[3];
1349
0
                print_bleedbox = true;
1350
0
                if (page->Page != NULL)
1351
0
                    cos_dict_delete_c_key(page->Page, "/BleedBox");
1352
0
            }
1353
0
        } else if (pdev->PDFXSetBleedBoxToMediaBox)
1354
0
            print_bleedbox = true;
1355
0
        else if (pdev->PDFXBleedBoxToTrimBoxOffset.size >= 4 &&
1356
0
                pdev->PDFXBleedBoxToTrimBoxOffset.data[0] >= 0 &&
1357
0
                pdev->PDFXBleedBoxToTrimBoxOffset.data[1] >= 0 &&
1358
0
                pdev->PDFXBleedBoxToTrimBoxOffset.data[2] >= 0 &&
1359
0
                pdev->PDFXBleedBoxToTrimBoxOffset.data[3] >= 0) {
1360
0
            bleedbox[0] = trimbox[0] - pdev->PDFXBleedBoxToTrimBoxOffset.data[0];
1361
0
            bleedbox[1] = trimbox[1] - pdev->PDFXBleedBoxToTrimBoxOffset.data[3];
1362
0
            bleedbox[2] = trimbox[2] + pdev->PDFXBleedBoxToTrimBoxOffset.data[1];
1363
0
            bleedbox[3] = trimbox[3] + pdev->PDFXBleedBoxToTrimBoxOffset.data[2];
1364
0
            print_bleedbox = true;
1365
0
        }
1366
1367
0
        if (print_bleedbox == true) {
1368
0
            if (trimbox[0] < bleedbox[0] || trimbox[1] < bleedbox[1] ||
1369
0
                trimbox[2] > bleedbox[2] || trimbox[3] > bleedbox[3]) {
1370
0
                switch (pdev->PDFACompatibilityPolicy) {
1371
0
                    case 0:
1372
0
                        emprintf(pdev->memory,
1373
0
                         "TrimBox does not fit inside BleedBox, not permitted in PDF/X-3, reverting to normal PDF output\n");
1374
0
                        pdev->AbortPDFAX = true;
1375
0
                        pdev->PDFX = 0;
1376
0
                        break;
1377
0
                    case 1:
1378
0
                        emprintf(pdev->memory,
1379
0
                         "TrimBox does not fit inside BleedBox, not permitted in PDF/X-3, reducing TrimBox\n");
1380
0
                        if (trimbox[0] < bleedbox[0])
1381
0
                            trimbox[0] = bleedbox[0];
1382
0
                        if (trimbox[1] < bleedbox[1])
1383
0
                            trimbox[1] = bleedbox[1];
1384
0
                        if (trimbox[2] > bleedbox[2])
1385
0
                            trimbox[2] = bleedbox[2];
1386
0
                        if (trimbox[3] > bleedbox[3])
1387
0
                            trimbox[3] = bleedbox[3];
1388
0
                        break;
1389
0
                    case 2:
1390
0
                        emprintf(pdev->memory,
1391
0
                         "TrimBox does not fit inside BleedBox, not permitted in PDF/X-3, aborting conversion\n");
1392
0
      return_error(gs_error_unknownerror);
1393
0
                        break;
1394
0
                    default:
1395
0
                        emprintf(pdev->memory,
1396
0
                         "TrimBox does not fit inside BleedBox, not permitted in PDF/X-3\nunrecognised PDFACompatibilityLevel,\nreverting to normal PDF output\n");
1397
0
                        pdev->AbortPDFAX = true;
1398
0
                        pdev->PDFX = 0;
1399
0
                        break;
1400
0
                }
1401
0
            }
1402
0
        }
1403
1404
0
        if (v_cropbox != NULL && v_cropbox->value_type == COS_VALUE_SCALAR) {
1405
0
            const byte *p = v_cropbox->contents.chars.data;
1406
0
            char buf[100];
1407
0
            int l = min (v_cropbox->contents.chars.size, sizeof(buf) - 1);
1408
0
            float temp[4]; /* the type is float for sscanf. */
1409
1410
0
            memcpy(buf, p, l);
1411
0
            buf[l] = 0;
1412
0
            if (sscanf(buf, "[ %g %g %g %g ]",
1413
0
                    &temp[0], &temp[1], &temp[2], &temp[3]) == 4) {
1414
0
                if (page->Page != NULL)
1415
0
                    cos_dict_delete_c_key(page->Page, "/CropBox");
1416
                /* Ensure that CropBox is no larger than MediaBox. The spec says *nothing* about
1417
                 * this, but Acrobat Preflight complains if it is larger. This can happen because
1418
                 * we apply 'round_box_coord' to the mediabox at the start of this rouinte.
1419
                 */
1420
0
                if (temp[0] < mediabox[0])
1421
0
                    temp[0] = mediabox[0];
1422
0
                if (temp[1] < mediabox[1])
1423
0
                    temp[1] = mediabox[1];
1424
0
                if (temp[2] > mediabox[2])
1425
0
                    temp[2] = mediabox[2];
1426
0
                if (temp[3] > mediabox[3])
1427
0
                    temp[3] = mediabox[3];
1428
0
                cropbox[0] = temp[0];
1429
0
                cropbox[1] = temp[1];
1430
0
                cropbox[2] = temp[2];
1431
0
                cropbox[3] = temp[3];
1432
0
                pprintg4(s, "/CropBox [%g %g %g %g]\n",
1433
0
                    temp[0], temp[1], temp[2], temp[3]);
1434
                /* Make sure TrimBox fits inside CropBox. Spec says 'must not extend
1435
                 * beyond the boundaries' but Acrobat Preflight complains if they
1436
                 * are the same value.
1437
                 */
1438
0
                if (trimbox[0] < temp[0] || trimbox[1] < temp[1] ||
1439
0
                    trimbox[2] > temp[2] || trimbox[3] > temp[3]) {
1440
0
                    switch (pdev->PDFACompatibilityPolicy) {
1441
0
                        case 0:
1442
0
                            emprintf(pdev->memory,
1443
0
                             "TrimBox does not fit inside CropBox, not permitted in PDF/X-3, reverting to normal PDF output\n");
1444
0
                            pdev->AbortPDFAX = true;
1445
0
                            pdev->PDFX = 0;
1446
0
                            break;
1447
0
                        case 1:
1448
0
                            emprintf(pdev->memory,
1449
0
                             "TrimBox does not fit inside CropBox, not permitted in PDF/X-3, reducing TrimBox\n");
1450
0
                            if (trimbox[0] < temp[0])
1451
0
                                trimbox[0] = temp[0];
1452
0
                            if (trimbox[1] < temp[1])
1453
0
                                trimbox[1] = temp[1];
1454
0
                            if (trimbox[2] > temp[2])
1455
0
                                trimbox[2] = temp[2];
1456
0
                            if (trimbox[3] > temp[3])
1457
0
                                trimbox[3] = temp[3];
1458
0
                            break;
1459
0
                        case 2:
1460
0
                            emprintf(pdev->memory,
1461
0
                             "TrimBox does not fit inside CropBox, not permitted in PDF/X-3, aborting conversion\n");
1462
0
          return_error(gs_error_unknownerror);
1463
0
                            break;
1464
0
                        default:
1465
0
                            emprintf(pdev->memory,
1466
0
                             "TrimBox does not fit inside CropBox, not permitted in PDF/X-3\nunrecognised PDFACompatibilityLevel,\nreverting to normal PDF output\n");
1467
0
                            pdev->AbortPDFAX = true;
1468
0
                            pdev->PDFX = 0;
1469
0
                            break;
1470
0
                    }
1471
0
                }
1472
0
            }
1473
0
        }
1474
1475
0
        if (pdev->PDFX > 1 && page->Page != NULL) {
1476
0
            if (cos_dict_find_c_key(page->Page, "/TrimBox") == NULL &&
1477
0
                cos_dict_find_c_key(page->Page, "/ArtBox") == NULL)
1478
0
                pprintg4(s, "/TrimBox [%g %g %g %g]\n",
1479
0
                    trimbox[0], trimbox[1], trimbox[2], trimbox[3]);
1480
0
            if (print_bleedbox &&
1481
0
                cos_dict_find_c_key(page->Page, "/BleedBox") == NULL)
1482
0
                pprintg4(s, "/BleedBox [%g %g %g %g]\n",
1483
0
                    bleedbox[0], bleedbox[1], bleedbox[2], bleedbox[3]);
1484
0
        }
1485
0
        if (pdev->PDFX == 1 && page->Page != NULL) {
1486
0
            if (cos_dict_find_c_key(page->Page, "/ArtBox") == NULL) {
1487
0
                artbox[0] = mediabox[0];
1488
0
                artbox[1] = mediabox[1];
1489
0
                artbox[2] = mediabox[2];
1490
0
                artbox[3] = mediabox[3];
1491
0
            }
1492
0
            if (cos_dict_find_c_key(page->Page, "/CropBox") != NULL) {
1493
0
                if (artbox[0] < cropbox[0])
1494
0
                    artbox[0] = cropbox[0];
1495
0
                if (artbox[1] < cropbox[1])
1496
0
                    artbox[1] = cropbox[1];
1497
0
                if (artbox[2] < cropbox[2])
1498
0
                    artbox[2] = cropbox[2];
1499
0
                if (artbox[3] < cropbox[3])
1500
0
                    artbox[3] = cropbox[3];
1501
0
            }
1502
0
            if (cos_dict_find_c_key(page->Page, "/BleedBox") != NULL) {
1503
0
                if (artbox[0] < bleedbox[0])
1504
0
                    artbox[0] = bleedbox[0];
1505
0
                if (artbox[1] < bleedbox[1])
1506
0
                    artbox[1] = bleedbox[1];
1507
0
                if (artbox[2] < bleedbox[2])
1508
0
                    artbox[2] = bleedbox[2];
1509
0
                if (artbox[3] < bleedbox[3])
1510
0
                    artbox[3] = bleedbox[3];
1511
0
            }
1512
0
            pprintg4(s, "/ArtBox [%g %g %g %g]\n",
1513
0
                artbox[0], artbox[1], artbox[2], artbox[3]);
1514
0
        }
1515
0
    }
1516
51.2k
    pdf_print_orientation(pdev, page);
1517
51.2k
    if (page->UserUnit != 1)
1518
5
        pprintg1(s, "/UserUnit %g\n", page->UserUnit);
1519
1520
51.2k
    pprinti64d1(s, "/Parent %"PRId64" 0 R\n", pdev->Pages->id);
1521
51.2k
    if (pdev->ForOPDFRead && pdev->DoNumCopies && !pdev->ProduceDSC) {
1522
0
        if (page->NumCopies_set)
1523
0
            pprinti64d1(s, "/NumCopies %"PRId64"\n", page->NumCopies);
1524
0
    }
1525
51.2k
    if (page->group_id > 0) {
1526
906
        pprinti64d1(s, "/Group %"PRId64" 0 R\n", page->group_id);
1527
906
    }
1528
51.2k
    if (pdev->CompatibilityLevel <= 1.7) {
1529
51.2k
            stream_puts(s, "/Resources<</ProcSet[/PDF");
1530
51.2k
        if (page->procsets & ImageB)
1531
349
            stream_puts(s, " /ImageB");
1532
51.2k
        if (page->procsets & ImageC)
1533
3.83k
            stream_puts(s, " /ImageC");
1534
51.2k
        if (page->procsets & ImageI)
1535
937
            stream_puts(s, " /ImageI");
1536
51.2k
        if (page->procsets & Text)
1537
11.7k
            stream_puts(s, " /Text");
1538
51.2k
        stream_puts(s, "]\n");
1539
51.2k
    } else {
1540
3
        stream_puts(s, "/Resources<<");
1541
3
    }
1542
51.2k
    {
1543
51.2k
        int i;
1544
1545
461k
        for (i = 0; i < countof(page->resource_ids); ++i)
1546
410k
            if (page->resource_ids[i] && pdf_resource_type_names[i]) {
1547
41.1k
                stream_puts(s, pdf_resource_type_names[i]);
1548
41.1k
                pprinti64d1(s, " %"PRId64" 0 R\n", page->resource_ids[i]);
1549
41.1k
            }
1550
51.2k
    }
1551
51.2k
    stream_puts(s, ">>\n");
1552
1553
    /* Write the annotations array if any. */
1554
1555
51.2k
    if (page->Annots) {
1556
2.57k
        const cos_value_t *value = NULL;
1557
2.57k
        const cos_array_element_t *e = NULL, *next = NULL;
1558
2.57k
        int64_t index = 0;
1559
1560
2.57k
        stream_puts(s, "/Annots");
1561
2.57k
        COS_WRITE(page->Annots, pdev);
1562
        /* More complications caused by cos objects. Simply calling COS_FREE
1563
         * will free the array, but it won't free the elements of the array
1564
         * if they have non-zero IDs (see the comments regarding cleanup of
1565
         * resources in pdf_close at around line 1090 below). Because we've
1566
         * already written out the annotations, the dictionary contents have
1567
         * already been freed, but we need the IDs until this point when we
1568
         * write out the array in the page dictionary. So after using them,
1569
         * we must go through the array and set the ids to 0 so that COS_FREE
1570
         * will free the array elements as well as the array itself.
1571
         */
1572
2.57k
        e = cos_array_element_first(page->Annots);
1573
52.8k
        while (e != NULL) {
1574
50.3k
            next = cos_array_element_next(e, &index, &value);
1575
50.3k
            if (value->contents.object != NULL) {
1576
                /* Check to see if this is a local named object, if it is do not
1577
                 * zero the ID! This object has not yet been written, because it
1578
                 * is a named object it can be modified after creation. We must
1579
                 * allow the named object code to write out the object and free it.
1580
                 */
1581
50.3k
                if (cos_dict_forall(pdev->local_named_objects, (void *)value,
1582
50.3k
                                    check_annot_in_named) == 0)
1583
50.3k
                    value->contents.object->id = 0;
1584
50.3k
            }
1585
50.3k
            e = next;
1586
50.3k
        }
1587
2.57k
        COS_FREE(page->Annots, "pdf_write_page(Annots)");
1588
2.57k
        page->Annots = 0;
1589
2.57k
    }
1590
    /*
1591
     * The PDF documentation allows, and this code formerly emitted,
1592
     * a Contents entry whose value was an empty array.  Acrobat Reader
1593
     * 3 and 4 accept this, but Acrobat Reader 5.0 rejects it.
1594
     * Fortunately, the Contents entry is optional.
1595
     */
1596
51.2k
    if (page->contents_id != 0)
1597
51.2k
        pprinti64d1(s, "/Contents %"PRId64" 0 R\n", page->contents_id);
1598
1599
    /* Write any elements stored by pdfmarks. */
1600
1601
51.2k
    if (page->Page != NULL)
1602
51.2k
        cos_dict_elements_write(page->Page, pdev);
1603
1604
51.2k
    stream_puts(s, ">>\n");
1605
51.2k
    pdf_end_obj(pdev, resourcePage);
1606
51.2k
    return 0;
1607
51.2k
}
1608
1609
/* Wrap up ("output") a page. */
1610
/* if we are doing separate pages, call pdf_close to emit the file, then */
1611
/* pdf_open to open the next page as a new file */
1612
/* NB: converting an input PDF with offpage links will generate warnings */
1613
static int
1614
pdf_output_page(gx_device * dev, int num_copies, int flush)
1615
35.5k
{
1616
35.5k
    gx_device_pdf *const pdev = (gx_device_pdf *) dev;
1617
35.5k
    int code;
1618
1619
35.5k
    if (pdev->Eps2Write && pdev->next_page != 0 && !gx_outputfile_is_separate_pages(pdev->fname, dev->memory)) {
1620
4.44k
       emprintf(pdev->memory, "\n   *** EPS files may not contain multiple pages.\n   *** Use of the %%d filename format is required to output pages to multiple EPS files.\n");
1621
4.44k
       return_error(gs_error_ioerror);
1622
4.44k
    }
1623
1624
31.1k
    if (pdev->ForOPDFRead) {
1625
12.1k
        code = pdf_close_page(pdev, num_copies);
1626
12.1k
        if (code < 0)
1627
0
            return code;
1628
1629
12.1k
        while (pdev->sbstack_depth) {
1630
8
            code = pdf_exit_substream(pdev);
1631
8
            if (code < 0)
1632
4
                return code;
1633
8
        }
1634
19.0k
    } else {
1635
19.0k
        while (pdev->sbstack_depth) {
1636
12
            code = pdf_exit_substream(pdev);
1637
12
            if (code < 0)
1638
0
                return code;
1639
12
        }
1640
19.0k
        code = pdf_close_page(pdev, num_copies);
1641
19.0k
        if (code < 0)
1642
0
            return code;
1643
19.0k
    }
1644
1645
31.1k
    if(pdev->UseCIEColor) {
1646
0
        emprintf(pdev->memory, "\n\nUse of -dUseCIEColor detected!\nSince the release of version 9.11 of Ghostscript we recommend you do not set\n-dUseCIEColor with the pdfwrite/ps2write device family.\n\n");
1647
0
    }
1648
31.1k
    if (pdf_ferror(pdev))
1649
0
        return_error(gs_error_ioerror);
1650
1651
31.1k
    if ((code = gx_finish_output_page(dev, num_copies, flush)) < 0)
1652
0
        return code;
1653
1654
31.1k
    if (gx_outputfile_is_separate_pages(((gx_device_vector *)dev)->fname, dev->memory)) {
1655
0
        pdev->InOutputPage = true;
1656
0
        if ((code = pdf_close(dev)) < 0)
1657
0
            return code;
1658
0
        code = pdf_open(dev);
1659
0
        dev->is_open = true;
1660
0
    }
1661
31.1k
    return code;
1662
31.1k
}
1663
1664
static int find_end_xref_section (gx_device_pdf *pdev, gp_file *tfile, int64_t start, gs_offset_t resource_pos)
1665
71.3k
{
1666
71.3k
    int64_t start_offset;
1667
1668
71.3k
    if (pdev->doubleXref)
1669
71.3k
        start_offset = (start - pdev->FirstObjectNumber) * sizeof(gs_offset_t) * 2;
1670
0
    else
1671
0
        start_offset = (start - pdev->FirstObjectNumber) * sizeof(gs_offset_t);
1672
1673
71.3k
    if (gp_fseek(tfile, start_offset, SEEK_SET) == 0)
1674
71.3k
    {
1675
71.3k
        int64_t i, r;
1676
1677
1.56M
        for (i = start; i < pdev->next_id; ++i) {
1678
1.49M
            gs_offset_t pos, index = -1;
1679
1680
1.49M
            r = gp_fread(&pos, sizeof(pos), 1, tfile);
1681
1.49M
            if (r != 1)
1682
0
                return(gs_note_error(gs_error_ioerror));
1683
1.49M
            if (pdev->doubleXref) {
1684
1.49M
                index = pos;
1685
1.49M
                r = gp_fread(&pos, sizeof(pos), 1, tfile);
1686
1.49M
                if (r != 1)
1687
0
                    return(gs_note_error(gs_error_ioerror));
1688
1.49M
            } else
1689
0
                index = 0;
1690
1.49M
            if (pos & ASIDES_BASE_POSITION) {
1691
400k
                pos &= ~ASIDES_BASE_POSITION;
1692
400k
                pos += resource_pos;
1693
400k
            }
1694
1.49M
            pos -= pdev->OPDFRead_procset_length;
1695
1.49M
            if (pos == 0 && index == 0) {
1696
538
                return i;
1697
538
            }
1698
1.49M
        }
1699
71.3k
    }
1700
70.7k
    return pdev->next_id;
1701
71.3k
}
1702
1703
static int write_xref_section(gx_device_pdf *pdev, gp_file *tfile, int64_t start, int end, gs_offset_t resource_pos, gs_offset_t *Offsets)
1704
13
{
1705
13
    int64_t start_offset;
1706
1707
13
    if (pdev->doubleXref)
1708
13
        start_offset = (start - pdev->FirstObjectNumber) * sizeof(gs_offset_t) * 2;
1709
0
    else
1710
0
        start_offset = (start - pdev->FirstObjectNumber) * sizeof(gs_offset_t);
1711
1712
13
    if (gp_fseek(tfile, start_offset, SEEK_SET) == 0)
1713
13
    {
1714
13
        int64_t i, r;
1715
1716
99
        for (i = start; i < end; ++i) {
1717
86
            gs_offset_t pos;
1718
86
            char str[21];
1719
1720
86
            r = gp_fread(&pos, sizeof(pos), 1, tfile);
1721
86
            if (r != 1)
1722
0
                return(gs_note_error(gs_error_ioerror));
1723
86
            if (pdev->doubleXref) {
1724
86
                r = gp_fread(&pos, sizeof(pos), 1, tfile);
1725
86
                if (r != 1)
1726
0
                    return(gs_note_error(gs_error_ioerror));
1727
86
            }
1728
1729
86
            if (pos & ASIDES_BASE_POSITION) {
1730
27
                pos &= ~ASIDES_BASE_POSITION;
1731
27
                pos += resource_pos;
1732
27
            }
1733
86
            pos -= pdev->OPDFRead_procset_length;
1734
1735
            /* check to see we haven't got an offset which is too large to represent
1736
             * in an xref (10 digits). Throw an error if we do.
1737
             */
1738
86
            if (pos > 9999999999) {
1739
0
                emprintf(pdev->pdf_memory, "ERROR - Attempt to create an xref entry with more than 10 digits which is illegal.\n");
1740
0
                emprintf(pdev->pdf_memory, "PDF file production has been aborted.\n");
1741
0
                return_error(gs_error_rangecheck);
1742
0
            }
1743
1744
            /* If we are linearising there's no point in writing an xref we will
1745
             * later replace. Also makes the file slightly smaller reducing the
1746
             * chances of needing to write white space to pad the file out.
1747
             */
1748
86
            if (!pdev->Linearise) {
1749
86
                gs_snprintf(str, sizeof(str), "%010"PRId64" 00000 n \n", pos);
1750
86
                stream_puts(pdev->strm, str);
1751
86
            }
1752
86
            if (Offsets)
1753
0
                Offsets[i] = pos;
1754
86
        }
1755
13
    }
1756
13
    return 0;
1757
13
}
1758
1759
static int write_xrefstm_section(gx_device_pdf *pdev, gp_file *tfile, int64_t start, int end, gs_offset_t resource_pos, int offset_size, stream *s)
1760
23.8k
{
1761
23.8k
    int64_t start_offset;
1762
1763
23.8k
    if (pdev->doubleXref)
1764
23.8k
        start_offset = (start - pdev->FirstObjectNumber) * sizeof(gs_offset_t) * 2;
1765
0
    else
1766
0
        start_offset = (start - pdev->FirstObjectNumber) * sizeof(gs_offset_t);
1767
1768
23.8k
    if (gp_fseek(tfile, start_offset, SEEK_SET) == 0)
1769
23.8k
    {
1770
23.8k
        int64_t i, j, r;
1771
1772
521k
        for (i = start; i < end; ++i) {
1773
497k
            gs_offset_t pos, objstm = -1, index = 0;
1774
1775
497k
            r = gp_fread(&pos, sizeof(pos), 1, tfile);
1776
497k
            if (r != 1)
1777
0
                return(gs_note_error(gs_error_ioerror));
1778
1779
497k
            if (pdev->doubleXref) {
1780
497k
                objstm = pos;
1781
497k
                r = gp_fread(&index, sizeof(pos), 1, tfile);
1782
497k
                if (r != 1)
1783
0
                    return(gs_note_error(gs_error_ioerror));
1784
497k
                pos = index;
1785
497k
            }
1786
1787
497k
            if (!pdev->doubleXref || objstm == 0) {
1788
245k
                if (pos & ASIDES_BASE_POSITION) {
1789
133k
                    pos &= ~ASIDES_BASE_POSITION;
1790
133k
                    pos += resource_pos;
1791
133k
                }
1792
245k
                pos -= pdev->OPDFRead_procset_length;
1793
1794
                /* check to see we haven't got an offset which is too large to represent
1795
                 * in an xref (10 digits). Throw an error if we do.
1796
                 */
1797
245k
                if (pos > 9999999999) {
1798
0
                    emprintf(pdev->pdf_memory, "ERROR - Attempt to create an xref entry with more than 10 digits which is illegal.\n");
1799
0
                    emprintf(pdev->pdf_memory, "PDF file production has been aborted.\n");
1800
0
                    return_error(gs_error_rangecheck);
1801
0
                }
1802
245k
            }
1803
1804
497k
            if (objstm > 0) {
1805
252k
                stream_putc(s, 0x02);
1806
252k
                pos = objstm;
1807
252k
            }
1808
245k
            else
1809
245k
                stream_putc(s, 0x01);
1810
1.63M
            for (j = 1; j <= offset_size; j++)
1811
1.13M
                stream_putc(s, (pos >> ((offset_size - j) * 8)) & 0xFF);
1812
497k
            stream_putc(s, 0x00);
1813
497k
            if (objstm > 0)
1814
252k
                stream_putc(s, index);
1815
245k
            else
1816
245k
                stream_putc(s, 0x00);
1817
497k
        }
1818
23.8k
    }
1819
23.8k
    return 0;
1820
23.8k
}
1821
1822
static int
1823
rewrite_object(gx_device_pdf *const pdev, pdf_linearisation_t *linear_params, int object)
1824
0
{
1825
0
    uint64_t read, Size;
1826
0
    char c, *Scratch, *source, *target, Buf[280], *next;
1827
0
    int code, ID, ScratchSize=16384;
1828
1829
0
    Size = pdev->ResourceUsage[object].Length;
1830
1831
0
    Scratch = (char *)gs_alloc_bytes(pdev->pdf_memory, ScratchSize, "Working memory for object rewriting");
1832
0
    if (Scratch == 0L)
1833
0
        return (gs_note_error(gs_error_VMerror));
1834
1835
0
    pdev->ResourceUsage[object].LinearisedOffset = gp_ftell(linear_params->Lin_File.file);
1836
0
    code = gp_fseek(linear_params->sfile, pdev->ResourceUsage[object].OriginalOffset, SEEK_SET);
1837
0
    if (code < 0)
1838
0
        return code;
1839
1840
0
    read = 0;
1841
0
    do {
1842
0
        code = gp_fread(&c, 1, 1, linear_params->sfile);
1843
0
        read++;
1844
0
    } while (c != '\n' && code > 0);
1845
0
    gs_snprintf(Scratch, ScratchSize, "%d 0 obj\n", pdev->ResourceUsage[object].NewObjectNumber);
1846
0
    gp_fwrite(Scratch, strlen(Scratch), 1, linear_params->Lin_File.file);
1847
1848
0
    code = gp_fread(&c, 1, 1, linear_params->sfile);
1849
0
    if (code != 1)
1850
0
        return_error(gs_error_ioerror);
1851
1852
0
    read++;
1853
0
    if (c == '<' || c == '[') {
1854
0
        int index = 0;
1855
0
        Scratch[index++] = c;
1856
0
        do {
1857
0
            do {
1858
0
                code = gp_fread(&c, 1, 1, linear_params->sfile);
1859
0
                Scratch[index++] = c;
1860
0
                read++;
1861
0
                if (index == ScratchSize - 2) {
1862
0
                    char *Temp;
1863
1864
0
                    Temp = (char *)gs_alloc_bytes(pdev->pdf_memory, ScratchSize * 2, "Working memory for object rewriting");
1865
0
                    if (Temp == 0L) {
1866
0
                        gs_free_object(pdev->pdf_memory, Scratch, "Free working memory for object rewriting");
1867
0
                        return (gs_note_error(gs_error_VMerror));
1868
0
                    }
1869
0
                    memcpy(Temp, Scratch, ScratchSize);
1870
0
                    gs_free_object(pdev->pdf_memory, Scratch, "Increase working memory for object rewriting");
1871
0
                    Scratch = Temp;
1872
0
                    ScratchSize *= 2;
1873
0
                }
1874
0
            }while (c != '\r' && c != '\n');
1875
0
            Scratch[index] = 0;
1876
0
            if (strncmp(&Scratch[index - 7], "endobj", 6) == 0  || strncmp(&Scratch[index - 7], "stream", 6) == 0)
1877
0
                break;
1878
0
        } while (code);
1879
0
    } else {
1880
0
        Scratch[0] = 0;
1881
0
        gp_fwrite(&c, 1, 1, linear_params->Lin_File.file);
1882
0
    }
1883
1884
0
    Size -= read;
1885
1886
0
    source = Scratch;
1887
0
    do {
1888
0
        target = strstr(source, " 0 R");
1889
0
        if (target) {
1890
0
            next = target + 4;
1891
0
            do {
1892
0
                target--;
1893
0
            }while (*target >= '0' && *target <= '9');
1894
0
            target++;
1895
0
            (void)sscanf(target, "%d 0 R", &ID);
1896
0
            gp_fwrite(source, target - source, 1, linear_params->Lin_File.file);
1897
0
            gs_snprintf(Buf, sizeof(Buf), "%d 0 R", pdev->ResourceUsage[ID].NewObjectNumber);
1898
0
            gp_fwrite(Buf, strlen(Buf), 1, linear_params->Lin_File.file);
1899
0
            source = next;
1900
0
        } else {
1901
0
            gp_fwrite(source, strlen(source), 1, linear_params->Lin_File.file);
1902
0
        }
1903
0
    } while (target);
1904
1905
0
    while (Size) {
1906
0
        if (Size > ScratchSize) {
1907
0
            code = gp_fread(Scratch, ScratchSize, 1, linear_params->sfile);
1908
0
            if (code != 1)
1909
0
        return_error(gs_error_ioerror);
1910
0
            gp_fwrite(Scratch, ScratchSize, 1, linear_params->Lin_File.file);
1911
0
            Size -= ScratchSize;
1912
0
        } else {
1913
0
            code = gp_fread(Scratch, Size, 1, linear_params->sfile);
1914
0
            if (code != 1)
1915
0
        return_error(gs_error_ioerror);
1916
0
            gp_fwrite(Scratch, Size, 1, linear_params->Lin_File.file);
1917
0
            Size = 0;
1918
0
        }
1919
0
    };
1920
1921
0
    gs_free_object(pdev->pdf_memory, Scratch, "Free working memory for object rewriting");
1922
0
    return 0;
1923
0
}
1924
1925
static int flush_hint_stream(pdf_linearisation_t *linear_params)
1926
0
{
1927
0
    int code;
1928
1929
0
    code = gp_fwrite(linear_params->HintBuffer, linear_params->HintByte, 1, linear_params->sfile);
1930
0
    linear_params->HintBits = 0;
1931
0
    linear_params->HintByte = 0;
1932
0
    return code;
1933
0
}
1934
1935
static int write_hint_stream(pdf_linearisation_t *linear_params, gs_offset_t val, char size_bits)
1936
0
{
1937
0
    unsigned int input_mask, output_mask;
1938
1939
0
    if (size_bits == 0)
1940
0
        return 0;
1941
1942
0
    while(size_bits) {
1943
0
        input_mask = 1 << (size_bits - 1);
1944
0
        output_mask = 0x80 >> linear_params->HintBits;
1945
0
        if (input_mask & val)
1946
0
            linear_params->HintBuffer[linear_params->HintByte] |= output_mask;
1947
0
        else
1948
0
            linear_params->HintBuffer[linear_params->HintByte] &= ~output_mask;
1949
0
        size_bits--;
1950
0
        linear_params->HintBits++;
1951
0
        if (linear_params->HintBits == 8) {
1952
0
            linear_params->HintByte++;
1953
0
            if (linear_params->HintByte > 254) {
1954
0
                flush_hint_stream(linear_params);
1955
0
                memset(linear_params->HintBuffer, 0x00, 256);
1956
0
            }
1957
0
            linear_params->HintBits = 0;
1958
0
        }
1959
0
    }
1960
0
    return 0;
1961
0
}
1962
1963
static int pdf_linearise(gx_device_pdf *pdev, pdf_linearisation_t *linear_params)
1964
0
{
1965
0
    char Buffer[1024];
1966
0
    char Header[32], Binary[9] = "%\307\354\217\242\n", LDict[1024], fileID[35], Pad;
1967
0
    int level = (int)(pdev->CompatibilityLevel * 10 + 0.5), i, j;
1968
0
    int code=0, Part1To6 = 2; /* Include space for linearisation dict */
1969
0
    int Part7To8 = 1;
1970
0
    int PartNone = 1;
1971
0
    int Part9 = 1;
1972
0
    int LDictObj, HintStreamObj, k;
1973
0
    char T;
1974
0
    int64_t mainxref, Length, HintStreamLen, HintStreamStart, HintLength, SharedHintOffset;
1975
1976
0
    fileID[0] = '<';
1977
0
    fileID[33] = '>';
1978
0
    fileID[34] = 0x00;
1979
0
    for (i = 0;i< sizeof(pdev->fileID);i++) {
1980
0
        T = pdev->fileID[i] >> 4;
1981
0
        if (T > 9) {
1982
0
            fileID[(i*2) + 1] = T - 10 + 'A';
1983
0
        } else {
1984
0
            fileID[(i*2) + 1] = T + '0';
1985
0
        }
1986
0
        T = pdev->fileID[i] & 0x0f;
1987
0
        if (T > 9) {
1988
0
            fileID[(i*2) + 2] = T - 10 + 'A';
1989
0
        } else {
1990
0
            fileID[(i*2) + 2] = T + '0';
1991
0
        }
1992
0
    }
1993
1994
    /* Make sure we've written everything to the main file */
1995
0
    sflush(pdev->strm);
1996
0
    linear_params->sfile = pdev->file;
1997
0
    linear_params->MainFileEnd = gp_ftell(pdev->file);
1998
1999
0
    linear_params->PageHints = NULL;
2000
0
    linear_params->SharedHints = NULL;
2001
2002
#ifdef LINEAR_DEBUGGING
2003
    code = gx_device_open_output_file((gx_device *)pdev, "/temp/linear.pdf",
2004
                                   true, true, &linear_params->Lin_File.file);
2005
#else
2006
0
    code = pdf_open_temp_file(pdev, &linear_params->Lin_File);
2007
0
#endif
2008
0
    if (code < 0)
2009
0
        return code;
2010
2011
0
    linear_params->Lin_File.strm = 0x0;
2012
2013
    /* Count resources used by page 1 */
2014
0
    linear_params->NumPage1Resources=0;
2015
0
    for (i = 0;i < pdev->ResourceUsageSize; i++) {
2016
0
        if (pdev->ResourceUsage[i].PageUsage == 1)
2017
0
            linear_params->NumPage1Resources++;
2018
0
        if (pdev->ResourceUsage[i].PageUsage == resource_usage_part1_structure)
2019
0
            linear_params->NumPart1StructureResources++;
2020
0
    }
2021
2022
    /* Count resources associated with pages */
2023
0
    linear_params->NumUniquePageResources=0;
2024
0
    linear_params->NumSharedResources=0;
2025
0
    for (i = 0;i < pdev->ResourceUsageSize; i++) {
2026
0
        if (pdev->ResourceUsage[i].PageUsage > 1)
2027
0
            linear_params->NumUniquePageResources++;
2028
0
        if (pdev->ResourceUsage[i].PageUsage == resource_usage_page_shared)
2029
0
            linear_params->NumSharedResources++;
2030
0
    }
2031
2032
    /* Count resources not associated with pages */
2033
0
    linear_params->NumNonPageResources=0;
2034
0
    for (i = 1;i < pdev->ResourceUsageSize; i++) {
2035
0
        if (pdev->ResourceUsage[i].PageUsage == 0)
2036
0
            linear_params->NumNonPageResources++;
2037
0
    }
2038
2039
    /* Count resources not associated with pages */
2040
0
    linear_params->NumPart9Resources=0;
2041
0
    for (i = 0;i < pdev->ResourceUsageSize; i++) {
2042
0
        if (pdev->ResourceUsage[i].PageUsage == resource_usage_part9_structure)
2043
0
            linear_params->NumPart9Resources++;
2044
0
    }
2045
2046
0
    Part1To6 += linear_params->NumUniquePageResources + linear_params->NumSharedResources + linear_params->NumNonPageResources + linear_params->NumPart9Resources;
2047
0
    PartNone += linear_params->NumUniquePageResources + linear_params->NumSharedResources;
2048
0
    Part9 += linear_params->NumUniquePageResources + linear_params->NumSharedResources + linear_params->NumNonPageResources;
2049
0
    LDictObj = linear_params->NumUniquePageResources + linear_params->NumSharedResources + linear_params->NumNonPageResources + linear_params->NumPart9Resources + 1;
2050
2051
    /* Record length and positions of all the objects and calculate the new object number */
2052
0
    for (i = 1;i < pdev->ResourceUsageSize; i++) {
2053
0
        int j;
2054
0
        gs_offset_t end;
2055
2056
0
        pdev->ResourceUsage[i].OriginalOffset = linear_params->Offsets[i];
2057
2058
0
        end = linear_params->xref;
2059
0
        for (j=0;j<=linear_params->LastResource;j++) {
2060
0
            if (linear_params->Offsets[j] > linear_params->Offsets[i] && linear_params->Offsets[j] < end)
2061
0
                end = linear_params->Offsets[j];
2062
0
        }
2063
0
        pdev->ResourceUsage[i].Length = end - linear_params->Offsets[i];
2064
2065
0
        if (pdev->ResourceUsage[i].PageUsage == 1 || pdev->ResourceUsage[i].PageUsage == resource_usage_part1_structure)
2066
0
            pdev->ResourceUsage[i].NewObjectNumber = Part1To6++;
2067
0
        else {
2068
0
            if (pdev->ResourceUsage[i].PageUsage == resource_usage_not_referenced)
2069
0
                pdev->ResourceUsage[i].NewObjectNumber = PartNone++;
2070
0
            else {
2071
0
                if (pdev->ResourceUsage[i].PageUsage == resource_usage_part9_structure)
2072
0
                    pdev->ResourceUsage[i].NewObjectNumber = Part9++;
2073
0
                else
2074
0
                    pdev->ResourceUsage[i].NewObjectNumber = Part7To8++;
2075
0
            }
2076
0
        }
2077
0
    }
2078
0
    gs_free_object(pdev->pdf_memory, linear_params->Offsets, "free temp xref storage");
2079
2080
#ifdef LINEAR_DEBUGGING
2081
    {
2082
    dmprintf6(pdev->pdf_memory, "NumPage1Resources %ld\tNumPart1StructureResources %ld\t\tNumUniquePageResources %ld\tNumSharedResources %ld\t\tNumNonPageResources %d\nNumPart9Resources %ld\n", linear_params->NumPage1Resources, linear_params->NumPart1StructureResources, linear_params->NumUniquePageResources, linear_params->NumSharedResources, linear_params->NumNonPageResources, linear_params->NumPart9Resources);
2083
    dmprintf(pdev->pdf_memory, "Old ID\tPage Usage\tNew ID\n");
2084
    for (i = 1;i < pdev->ResourceUsageSize; i++) {
2085
        dmprintf3(pdev->pdf_memory, "%d\t%d\t%d\n", i, pdev->ResourceUsage[i].PageUsage, pdev->ResourceUsage[i].NewObjectNumber);
2086
    }
2087
    }
2088
#endif
2089
    /* Linearisation. Part 1, file header */
2090
0
    gs_snprintf(Header, sizeof(Header), "%%PDF-%d.%d\n", level / 10, level % 10);
2091
0
    gp_fwrite(Header, strlen(Header), 1, linear_params->Lin_File.file);
2092
0
    if (pdev->binary_ok)
2093
0
        gp_fwrite(Binary, strlen(Binary), 1, linear_params->Lin_File.file);
2094
0
    pdfwrite_fwrite_args_comment(pdev, linear_params->Lin_File.file);
2095
2096
0
    pdf_record_usage(pdev, linear_params->LastResource + 1, resource_usage_part1_structure);
2097
0
    pdev->ResourceUsage[linear_params->LastResource + 1].OriginalOffset = 0;
2098
0
    pdev->ResourceUsage[linear_params->LastResource + 1].NewObjectNumber = LDictObj;
2099
0
    pdev->ResourceUsage[linear_params->LastResource + 1].LinearisedOffset = gp_ftell(linear_params->Lin_File.file);
2100
2101
    /* Linearisation. Part 2, the Linearisation dictioanry */
2102
0
    linear_params->LDictOffset = gp_ftell(linear_params->Lin_File.file);
2103
0
    gs_snprintf(LDict, sizeof(LDict), "%d 0 obj\n<<                                                                                                                        \n",
2104
0
        LDictObj);
2105
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->Lin_File.file);
2106
2107
    /* First page cross-reference table here (Part 3) */
2108
0
    linear_params->FirstxrefOffset = gp_ftell(linear_params->Lin_File.file);
2109
0
    gs_snprintf(Header, sizeof(Header), "xref\n%d %d\n", LDictObj, Part1To6 - LDictObj + 1); /* +1 for the primary hint stream */
2110
0
    gp_fwrite(Header, strlen(Header), 1, linear_params->Lin_File.file);
2111
2112
0
    gs_snprintf(Header, sizeof(Header), "0000000000 00000 n \n");
2113
2114
0
    for (i = LDictObj;i <= linear_params->LastResource + 2; i++) {
2115
0
        gp_fwrite(Header, 20, 1, linear_params->Lin_File.file);
2116
0
    }
2117
2118
    /* Size below is given as the Last Resource in the original file, +1 for object 0 (always free)
2119
     * +1 for the linearisation dict and +1 for the primary hint stream.
2120
     */
2121
0
    linear_params->FirsttrailerOffset = gp_ftell(linear_params->Lin_File.file);
2122
0
    if (pdev->OmitID)
2123
0
        gs_snprintf(LDict, sizeof(LDict), "\ntrailer\n<</Size %"PRId64"/Info %d 0 R/Root %d 0 R/Prev %d>>\nstartxref\r\n0\n%%%%EOF\n        \n",
2124
0
        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber, 0);
2125
0
    else
2126
0
        gs_snprintf(LDict, sizeof(LDict), "\ntrailer\n<</Size %"PRId64"/Info %d 0 R/Root %d 0 R/ID[%s%s]/Prev %d>>\nstartxref\r\n0\n%%%%EOF\n        \n",
2127
0
        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber, fileID, fileID, 0);
2128
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->Lin_File.file);
2129
2130
    /* Write document catalog (Part 4) */
2131
0
    code = rewrite_object(pdev, linear_params, linear_params->Catalog_id);
2132
0
    if (code < 0)
2133
0
        goto error;
2134
2135
    /* In here we need the ViewerPreferences (don't think we support this),
2136
     * the PageMode entry (I think this would be direct in the catalog), The
2137
     * Threads entry (if any), The OpenAction (again, direct object ?) The
2138
     * AcroForm object (don't think we support this) and (TaDa) the Encrypt entry
2139
     * in the first page trailer dictionary.
2140
     */
2141
2142
    /* First page section (Part 6) NB we do not currently support the OpenAction
2143
     * In the Catalogso this is always page 0, this needs to change if we ever
2144
     * support the OpenAction. The 1.7 PDF Reference says in implementation note 181
2145
     * that Acrobat always treats page 0 as the first page for linearisation purposes
2146
     * EVEN IF there is an OpenAction, so we are Acrobat-compatible :-)
2147
     */
2148
0
    code = rewrite_object(pdev, linear_params, pdev->pages[0].Page->id);
2149
0
    if (code < 0)
2150
0
        goto error;
2151
0
    for (i = 0;i < pdev->ResourceUsageSize; i++) {
2152
        /* we explicitly write the page objct above, make sure when writing the
2153
         * 'objects uniquely used on the page' that we don't write the page object again!
2154
         */
2155
0
        if (pdev->ResourceUsage[i].PageUsage == 1 && i != pdev->pages[0].Page->id) {
2156
0
            code = rewrite_object(pdev, linear_params, i);
2157
0
            if (code < 0)
2158
0
                goto error;
2159
0
        }
2160
0
    }
2161
0
    linear_params->E = gp_ftell(linear_params->Lin_File.file);
2162
2163
    /* Primary Hint Stream here (Part 5)
2164
     * this is a FIXME
2165
     */
2166
0
    HintStreamObj = linear_params->LastResource + 2;
2167
0
    pdf_record_usage(pdev, HintStreamObj, resource_usage_part1_structure);
2168
0
    pdev->ResourceUsage[HintStreamObj].OriginalOffset = 0;
2169
0
    pdev->ResourceUsage[HintStreamObj].NewObjectNumber = HintStreamObj;
2170
0
    pdev->ResourceUsage[HintStreamObj].LinearisedOffset = gp_ftell(linear_params->Lin_File.file);
2171
2172
    /* We don't actually embed the hint stream yet. We will do this when we copy the 'linearised'
2173
     * PDF file from the temp file back to the main file, and will insert the hint stream at this point.
2174
     * We will then know all the offsets of all the objects following the hint stream, so we can
2175
     * write these correctly into the hint stream. Since we will then know the size of the hint
2176
     * stream, we can add this to the stored offsets to generate the 'real' offsets for teh xref.
2177
     */
2178
2179
    /* All remaining pages (part 7) */
2180
0
    for (i = 1;i < pdev->next_page;i++) {
2181
0
        code = rewrite_object(pdev, linear_params, pdev->pages[i].Page->id);
2182
0
        if (code < 0)
2183
0
            goto error;
2184
0
        for (j = 0;j < pdev->ResourceUsageSize; j++) {
2185
            /* we explicitly write the page objct above, make sure when writing the
2186
             * 'objects uniquely used on the page' that we don't write the page object again!
2187
             */
2188
0
            if (pdev->ResourceUsage[j].PageUsage - 1 == i && j != pdev->pages[i].Page->id) {
2189
0
                code = rewrite_object(pdev, linear_params, j);
2190
0
                if (code < 0)
2191
0
                    goto error;
2192
0
            }
2193
0
        }
2194
0
    }
2195
2196
    /* Shared objects for all pages except the first (part 8) */
2197
0
    for (i = 0;i < pdev->ResourceUsageSize; i++) {
2198
0
        if (pdev->ResourceUsage[i].PageUsage == resource_usage_page_shared) {
2199
0
            code = rewrite_object(pdev, linear_params, i);
2200
0
            if (code < 0)
2201
0
                goto error;
2202
0
        }
2203
0
    }
2204
2205
    /* All objects not on any page (Part 9) */
2206
0
    for (i = 1;i < pdev->ResourceUsageSize; i++) {
2207
0
        if (pdev->ResourceUsage[i].PageUsage == resource_usage_not_referenced ||
2208
0
            pdev->ResourceUsage[i].PageUsage == resource_usage_part9_structure) {
2209
0
            code = rewrite_object(pdev, linear_params, i);
2210
0
            if (code < 0)
2211
0
                goto error;
2212
0
        }
2213
0
    }
2214
2215
    /* We won't bother with an overflow hint stream (I Hope) (part 10)
2216
     * Implementation Note 181 in the 1.7 PDF Reference Manual says Acrobat
2217
     * doesn't support overflow hint streams anyway....
2218
     */
2219
2220
    /* Now copy the linearised data back to the main file, as far as the offset of the
2221
     * primary hint stream
2222
     */
2223
0
    if (gp_fseek(linear_params->Lin_File.file, 0, SEEK_SET) != 0) {
2224
0
        code = gs_error_ioerror;
2225
0
        goto error;
2226
0
    }
2227
0
    if (gp_fseek(linear_params->sfile, 0, SEEK_SET) != 0){
2228
0
        code = gs_error_ioerror;
2229
0
        goto error;
2230
0
    }
2231
0
    Length = pdev->ResourceUsage[HintStreamObj].LinearisedOffset;
2232
0
    while (Length && code >= 0) {
2233
0
        if (Length > 1024) {
2234
0
            code = gp_fread(Buffer, 1024, 1, linear_params->Lin_File.file);
2235
0
            gp_fwrite(Buffer, 1024, 1, linear_params->sfile);
2236
0
            Length -= 1024;
2237
0
        } else {
2238
0
            code = gp_fread(Buffer, Length, 1, linear_params->Lin_File.file);
2239
0
            gp_fwrite(Buffer, Length, 1, linear_params->sfile);
2240
0
            Length = 0;
2241
0
        }
2242
0
    }
2243
    /* insert the primary hint stream */
2244
0
    gs_snprintf(LDict, sizeof(LDict), "%d 0 obj\n<</Length           \n/S           >>\nstream\n", HintStreamObj);
2245
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2246
2247
0
    HintStreamStart = gp_ftell(linear_params->sfile);
2248
0
    memset(linear_params->HintBuffer, 0x00, 256);
2249
0
    linear_params->HintBits = linear_params->HintByte = 0;
2250
2251
0
    linear_params->PageHints = (page_hint_stream_t *)gs_alloc_bytes(pdev->pdf_memory, (size_t)(pdev->next_page) * sizeof(page_hint_stream_t), "Hints for the pages");
2252
0
    if (linear_params->PageHints == NULL) {
2253
0
        code = gs_error_VMerror;
2254
0
        goto error;
2255
0
    }
2256
0
    memset(linear_params->PageHints, 0x00, pdev->next_page * sizeof(page_hint_stream_t));
2257
0
    linear_params->NumPageHints = pdev->next_page;
2258
2259
0
    linear_params->SharedHints = (shared_hint_stream_t *)gs_alloc_bytes(pdev->pdf_memory, (size_t)(linear_params->NumPage1Resources + linear_params->NumSharedResources) * sizeof(shared_hint_stream_t), "Hints for the shared objects");
2260
0
    if (linear_params->SharedHints == NULL) {
2261
0
        code = gs_error_VMerror;
2262
0
        goto error;
2263
0
    }
2264
0
    memset(linear_params->SharedHints, 0x00, (linear_params->NumPage1Resources + linear_params->NumSharedResources) * sizeof(shared_hint_stream_t));
2265
0
    linear_params->NumSharedHints = linear_params->NumPage1Resources + linear_params->NumSharedResources;
2266
2267
0
    memset(&linear_params->PageHintHeader,0x00, sizeof(page_hint_stream_header_t));
2268
0
    memset(&linear_params->SharedHintHeader,0x00, sizeof(shared_hint_stream_header_t));
2269
2270
0
    linear_params->PageHintHeader.LeastObjectsPerPage = 0x7fffffff;
2271
0
    linear_params->PageHintHeader.LeastPageLength = 0x7fffffff;
2272
0
    linear_params->PageHintHeader.LeastPageOffset = 0x7fffffff;
2273
0
    linear_params->PageHintHeader.LeastContentLength = 0x7fffffff;
2274
2275
    /* Record the offset and length of the content stream for each page */
2276
0
    for (i=0;i<pdev->next_page;i++) {
2277
0
        int PageContentID = pdev->pages[i].contents_id;
2278
0
        pdf_linearisation_record_t *record = &pdev->ResourceUsage[PageContentID];
2279
0
        page_hint_stream_t *pagehint = &linear_params->PageHints[i];
2280
2281
0
        pagehint->ContentOffset = record->LinearisedOffset;
2282
0
        pagehint->ContentLength = record->Length;
2283
0
    }
2284
2285
    /* For every object, record it in the page hints and shared hints. k is a counter
2286
     * of the current shared object, we increment it each time we find a new one.
2287
     */
2288
0
    k = 0;
2289
0
    for (i = 1;i < pdev->ResourceUsageSize; i++) {
2290
0
        pdf_linearisation_record_t *record = &pdev->ResourceUsage[i];
2291
2292
0
        if (record->PageUsage < resource_usage_page_shared || record->PageUsage == resource_usage_not_referenced)
2293
0
            continue;
2294
0
        if (record->PageUsage == resource_usage_page_shared) {
2295
            /* shared objects are recorded in the shared object hints, and also the page hints */
2296
0
            for (j=0;j<record->NumPagesUsing;j++) {
2297
0
                int page = record->PageList[j];
2298
0
                page_hint_stream_t *pagehint;
2299
2300
0
                if (page >= pdev->next_page)
2301
                    /* This can happen if the job makes marks, but does not call showpage */
2302
0
                    continue;
2303
2304
0
                pagehint = &linear_params->PageHints[page - 1];
2305
0
                if (pagehint->SharedObjectRef){
2306
0
                    int *Temp = (int *)gs_alloc_bytes(pdev->pdf_memory, (size_t)(pagehint->NumSharedObjects + 1) * sizeof(int), "realloc shared object hints");
2307
0
                    if (Temp == NULL) {
2308
0
                        code = gs_note_error(gs_error_VMerror);
2309
0
                        goto error;
2310
0
                    }
2311
0
                    memcpy(Temp, pagehint->SharedObjectRef, (pagehint->NumSharedObjects) * sizeof(int));
2312
0
                    gs_free_object(pdev->pdf_memory, pagehint->SharedObjectRef, "realloc shared object hints");
2313
0
                    pagehint->SharedObjectRef = (unsigned int *)Temp;
2314
0
                } else {
2315
0
                    pagehint->SharedObjectRef = (unsigned int *)gs_alloc_bytes(pdev->pdf_memory, (size_t)(pagehint->NumSharedObjects + 1) * sizeof(int), "shared object hints");
2316
0
                    if (pagehint->SharedObjectRef == NULL) {
2317
0
                        code = gs_note_error(gs_error_VMerror);
2318
0
                        goto error;
2319
0
                    }
2320
0
                }
2321
0
                pagehint->SharedObjectRef[pagehint->NumSharedObjects] = i;
2322
0
                pagehint->NumSharedObjects++;
2323
0
            }
2324
0
            linear_params->SharedHints[k].ObjectNumber = record->NewObjectNumber;
2325
0
            linear_params->SharedHints[k].ObjectOffset = record->LinearisedOffset;
2326
0
            linear_params->SharedHints[k++].ObjectLength = record->Length;
2327
0
        } else {
2328
            /* Objects uniquely used on a page are stored in the page hints table, except
2329
             * page 1 whose objects are *also* stored in the shared objects hints.
2330
             */
2331
0
            int page = record->PageUsage, pageID = pdev->pages[page - 1].Page->id;
2332
0
            int64_t LinearisedPageOffset = pdev->ResourceUsage[pageID].LinearisedOffset;
2333
0
            page_hint_stream_t *pagehint;
2334
2335
            /* If the final page makes marks but does not call showpage we don't emit it
2336
             * which can lead to references to non-existent pages.
2337
             */
2338
0
            if (page <= pdev->next_page) {
2339
0
                pagehint = &linear_params->PageHints[page - 1];
2340
0
                pagehint->NumUniqueObjects++;
2341
0
                if (record->LinearisedOffset - LinearisedPageOffset > pagehint->PageLength)
2342
0
                    pagehint->PageLength = (record->LinearisedOffset + record->Length) - LinearisedPageOffset;
2343
0
                if (page == 1) {
2344
0
                    linear_params->SharedHintHeader.FirstPageEntries++;
2345
0
                }
2346
0
            }
2347
0
        }
2348
0
    }
2349
2350
0
    linear_params->PageHintHeader.LargestSharedObject = k;
2351
2352
0
    for (i = 0;i < linear_params->NumPageHints;i++) {
2353
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2354
2355
0
        if (hint->NumUniqueObjects + hint->NumSharedObjects < linear_params->PageHintHeader.LeastObjectsPerPage)
2356
0
            linear_params->PageHintHeader.LeastObjectsPerPage = hint->NumUniqueObjects + hint->NumSharedObjects;
2357
0
        if (hint->NumUniqueObjects + hint->NumSharedObjects > linear_params->PageHintHeader.MostObjectsPerPage)
2358
0
            linear_params->PageHintHeader.MostObjectsPerPage = hint->NumUniqueObjects + hint->NumSharedObjects;
2359
0
        if (hint->PageLength < linear_params->PageHintHeader.LeastPageLength)
2360
0
            linear_params->PageHintHeader.LeastPageLength = hint->PageLength;
2361
0
        if (hint->PageLength > linear_params->PageHintHeader.MostPageLength)
2362
0
            linear_params->PageHintHeader.MostPageLength = hint->PageLength;
2363
0
        if (hint->ContentOffset < linear_params->PageHintHeader.LeastPageOffset)
2364
0
            linear_params->PageHintHeader.LeastPageOffset = hint->ContentOffset;
2365
0
        if (hint->ContentOffset > linear_params->PageHintHeader.MostPageOffset)
2366
0
            linear_params->PageHintHeader.MostPageOffset = hint->ContentOffset;
2367
0
        if (hint->ContentLength < linear_params->PageHintHeader.LeastContentLength)
2368
0
            linear_params->PageHintHeader.LeastContentLength = hint->ContentLength;
2369
0
        if (hint->ContentLength > linear_params->PageHintHeader.MostContentLength)
2370
0
            linear_params->PageHintHeader.MostContentLength = hint->ContentLength;
2371
0
        if (hint->NumSharedObjects > linear_params->PageHintHeader.MostSharedObjects)
2372
0
            linear_params->PageHintHeader.MostSharedObjects = hint->NumSharedObjects;
2373
0
    }
2374
2375
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.LeastObjectsPerPage, 32);
2376
0
    write_hint_stream(linear_params, (gs_offset_t)pdev->ResourceUsage[pdev->pages[0].Page->id].LinearisedOffset, 32);
2377
0
    i = (linear_params->PageHintHeader.MostObjectsPerPage - linear_params->PageHintHeader.MostObjectsPerPage + 1);
2378
0
    j = 0;
2379
0
    while (i) {
2380
0
        i = i / 2;
2381
0
        j++;
2382
0
    }
2383
0
    linear_params->PageHintHeader.ObjectNumBits = j;
2384
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.ObjectNumBits, 16);
2385
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.LeastPageLength, 32);
2386
0
    i = (linear_params->PageHintHeader.MostPageLength - linear_params->PageHintHeader.LeastPageLength + 1);
2387
0
    j = 0;
2388
0
    while (i) {
2389
0
        i = i / 2;
2390
0
        j++;
2391
0
    }
2392
0
    linear_params->PageHintHeader.PageLengthNumBits = j;
2393
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.PageLengthNumBits, 16);
2394
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.LeastPageOffset, 32);
2395
0
    i = (linear_params->PageHintHeader.MostPageOffset - linear_params->PageHintHeader.LeastPageOffset + 1);
2396
0
    j = 0;
2397
0
    while (i) {
2398
0
        i = i / 2;
2399
0
        j++;
2400
0
    }
2401
0
    linear_params->PageHintHeader.PageOffsetNumBits = j;
2402
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.PageOffsetNumBits, 16);
2403
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.LeastContentLength, 32);
2404
0
    i = (linear_params->PageHintHeader.MostContentLength - linear_params->PageHintHeader.LeastContentLength + 1);
2405
0
    j = 0;
2406
0
    while (i) {
2407
0
        i = i / 2;
2408
0
        j++;
2409
0
    }
2410
0
    linear_params->PageHintHeader.ContentLengthNumBits = j;
2411
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.ContentLengthNumBits, 16);
2412
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.MostSharedObjects, 16);
2413
0
    i = (linear_params->PageHintHeader.LargestSharedObject + 1);
2414
0
    j = 0;
2415
0
    while (i) {
2416
0
        i = i / 2;
2417
0
        j++;
2418
0
    }
2419
0
    linear_params->PageHintHeader.SharedObjectNumBits = j;
2420
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->PageHintHeader.SharedObjectNumBits, 16);
2421
0
    j = 1;
2422
0
    write_hint_stream(linear_params, (gs_offset_t)j, 16);
2423
0
    write_hint_stream(linear_params, (gs_offset_t)j, 16);
2424
2425
#ifdef LINEAR_DEBUGGING
2426
    dmprintf1(pdev->pdf_memory, "LeastObjectsPerPage %d\n", linear_params->PageHintHeader.LeastObjectsPerPage);
2427
    dmprintf1(pdev->pdf_memory, "Page 1 Offset %"PRId64"\n", pdev->ResourceUsage[pdev->pages[0].Page->id].LinearisedOffset);
2428
    dmprintf1(pdev->pdf_memory, "ObjectNumBits %d\n", linear_params->PageHintHeader.ObjectNumBits);
2429
    dmprintf1(pdev->pdf_memory, "LeastPageLength %d\n", linear_params->PageHintHeader.LeastPageLength);
2430
    dmprintf1(pdev->pdf_memory, "MostPagelength %d\n", linear_params->PageHintHeader.MostPageLength);
2431
    dmprintf1(pdev->pdf_memory, "PaegLengthNumBits %d\n", linear_params->PageHintHeader.PageLengthNumBits);
2432
    dmprintf1(pdev->pdf_memory, "LeastPageOffset %d\n", linear_params->PageHintHeader.LeastPageOffset);
2433
    dmprintf1(pdev->pdf_memory, "MostPageOffset %d\n", linear_params->PageHintHeader.MostPageOffset);
2434
    dmprintf1(pdev->pdf_memory, "PageOffsetNumBits %d\n", linear_params->PageHintHeader.PageOffsetNumBits);
2435
    dmprintf1(pdev->pdf_memory, "LeastContentLength %d\n", linear_params->PageHintHeader.LeastContentLength);
2436
    dmprintf1(pdev->pdf_memory, "MostContentLength %d\n", linear_params->PageHintHeader.MostContentLength);
2437
    dmprintf1(pdev->pdf_memory, "COntentLengthNumBits %d\n", linear_params->PageHintHeader.ContentLengthNumBits);
2438
    dmprintf1(pdev->pdf_memory, "MostSharedObjects %d\n", linear_params->PageHintHeader.MostSharedObjects);
2439
    dmprintf1(pdev->pdf_memory, "LargetsSharedObject %d\n", linear_params->PageHintHeader.LargestSharedObject);
2440
    dmprintf1(pdev->pdf_memory, "SharedObjectNumBits %d\n", linear_params->PageHintHeader.SharedObjectNumBits);
2441
    dmprintf(pdev->pdf_memory, "Position Numerator 1\n");
2442
    dmprintf(pdev->pdf_memory, "Position Denominator 1\n\n");
2443
#endif
2444
2445
0
    for (i=0;i < pdev->next_page;i++) {
2446
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2447
0
        int Num;
2448
2449
0
        Num = hint->NumUniqueObjects - linear_params->PageHintHeader.LeastObjectsPerPage;
2450
0
        write_hint_stream(linear_params, (gs_offset_t)Num, linear_params->PageHintHeader.ObjectNumBits);
2451
0
        dmprintf2(pdev->pdf_memory, "Page %d NumUniqueObjects %d\n", i, Num);
2452
0
    }
2453
0
    for (i=0;i < pdev->next_page;i++) {
2454
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2455
0
        int Num;
2456
2457
0
        Num = hint->PageLength - linear_params->PageHintHeader.LeastPageLength;
2458
0
        write_hint_stream(linear_params, (gs_offset_t)Num, linear_params->PageHintHeader.PageLengthNumBits);
2459
0
        dmprintf2(pdev->pdf_memory, "Page %d PageLength %d\n", i, Num);
2460
0
    }
2461
0
    for (i=0;i < pdev->next_page;i++) {
2462
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2463
2464
0
        if (i == 0) {
2465
0
            write_hint_stream(linear_params, (gs_offset_t)i, linear_params->PageHintHeader.SharedObjectNumBits);
2466
0
            dmprintf2(pdev->pdf_memory, "Page %d NumSharedObjects %d\n", i, 1);
2467
0
        }
2468
0
        else {
2469
0
            write_hint_stream(linear_params, (gs_offset_t)hint->NumSharedObjects, linear_params->PageHintHeader.SharedObjectNumBits);
2470
0
            dmprintf2(pdev->pdf_memory, "Page %d NumSharedObjects %d\n", i, hint->NumSharedObjects);
2471
0
        }
2472
0
    }
2473
0
    for (i=1;i < pdev->next_page;i++) {
2474
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2475
2476
0
        for (j=0;j < hint->NumSharedObjects;j++) {
2477
0
            write_hint_stream(linear_params, (gs_offset_t)hint->SharedObjectRef[j], linear_params->PageHintHeader.SharedObjectNumBits);
2478
0
            dmprintf3(pdev->pdf_memory, "Page %d SharedObject %d ObjectRef %d\n", i, j, hint->SharedObjectRef[j]);
2479
0
        }
2480
0
    }
2481
2482
0
    for (i=0;i < pdev->next_page;i++) {
2483
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2484
2485
0
        for (j=0;j < hint->NumSharedObjects;j++) {
2486
0
            write_hint_stream(linear_params, (gs_offset_t)j, 1);
2487
0
            dmprintf2(pdev->pdf_memory, "Page %d SharedObject %d Position Numerator 1\n", i, j);
2488
0
        }
2489
0
    }
2490
0
    for (i=1;i < pdev->next_page;i++) {
2491
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2492
0
        int Num;
2493
2494
0
        Num = hint->ContentOffset - linear_params->PageHintHeader.LeastPageOffset;
2495
0
        write_hint_stream(linear_params, (gs_offset_t)Num, linear_params->PageHintHeader.PageOffsetNumBits);
2496
0
        dmprintf2(pdev->pdf_memory, "Page %d ContentStreamOffset %d\n", i, Num);
2497
0
    }
2498
0
    for (i=1;i < pdev->next_page;i++) {
2499
0
        page_hint_stream_t *hint = &linear_params->PageHints[i];
2500
0
        int Num;
2501
2502
0
        Num = hint->ContentLength - linear_params->PageHintHeader.LeastContentLength;
2503
0
        write_hint_stream(linear_params, (gs_offset_t)Num, linear_params->PageHintHeader.ContentLengthNumBits);
2504
0
        dmprintf2(pdev->pdf_memory, "Page %d ContentStreamLength %d\n", i, Num);
2505
0
    }
2506
0
    flush_hint_stream(linear_params);
2507
2508
0
    SharedHintOffset = gp_ftell(linear_params->sfile) - HintStreamStart;
2509
0
    linear_params->SharedHintHeader.FirstSharedObject = linear_params->SharedHints[0].ObjectNumber;
2510
0
    linear_params->SharedHintHeader.LeastObjectLength = linear_params->SharedHints[0].ObjectLength;
2511
0
    linear_params->SharedHintHeader.MostObjectLength = linear_params->SharedHints[0].ObjectLength;
2512
2513
0
    for (i = 1; i< linear_params->NumSharedHints; i++) {
2514
0
        if (linear_params->SharedHints[i].ObjectNumber < linear_params->SharedHintHeader.FirstSharedObject) {
2515
0
            linear_params->SharedHintHeader.FirstSharedObject = linear_params->SharedHints[1].ObjectNumber;
2516
0
            linear_params->SharedHintHeader.FirstObjectOffset = linear_params->SharedHints[1].ObjectOffset;
2517
0
        }
2518
0
        if (linear_params->SharedHints[i].ObjectLength < linear_params->SharedHintHeader.LeastObjectLength) {
2519
0
            linear_params->SharedHintHeader.LeastObjectLength = linear_params->SharedHints[i].ObjectLength;
2520
0
        }
2521
0
        if (linear_params->SharedHints[i].ObjectLength > linear_params->SharedHintHeader.MostObjectLength) {
2522
0
            linear_params->SharedHintHeader.MostObjectLength = linear_params->SharedHints[i].ObjectLength;
2523
0
        }
2524
0
    }
2525
2526
0
    linear_params->SharedHintHeader.FirstPageEntries = linear_params->NumPage1Resources;
2527
0
    linear_params->SharedHintHeader.NumSharedObjects = linear_params->NumSharedResources + linear_params->SharedHintHeader.FirstPageEntries;
2528
2529
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.FirstSharedObject, 32);
2530
0
    dmprintf1(pdev->pdf_memory, "\nFirstSharedObject %d\n", linear_params->SharedHintHeader.FirstSharedObject);
2531
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.FirstObjectOffset, 32);
2532
0
    dmprintf1(pdev->pdf_memory, "FirstObjectOffset %"PRId64"\n", linear_params->SharedHintHeader.FirstObjectOffset);
2533
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.FirstPageEntries, 32);
2534
0
    dmprintf1(pdev->pdf_memory, "FirstPageEntries %d\n", linear_params->SharedHintHeader.FirstPageEntries);
2535
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.NumSharedObjects, 32);
2536
0
    dmprintf1(pdev->pdf_memory, "NumSharedObjects %d\n", linear_params->SharedHintHeader.NumSharedObjects);
2537
0
    j = 1;
2538
0
    write_hint_stream(linear_params, (gs_offset_t)j, 32);
2539
0
    dmprintf(pdev->pdf_memory, "GreatestObjectsNumBits 1\n");
2540
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.FirstObjectOffset, 16);
2541
0
    dmprintf1(pdev->pdf_memory, "FirstObjectOffset %"PRId64"\n", linear_params->SharedHintHeader.FirstObjectOffset);
2542
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.LeastObjectLength, 32);
2543
0
    dmprintf1(pdev->pdf_memory, "LeastObjectLength %d\n", linear_params->SharedHintHeader.LeastObjectLength);
2544
2545
0
    i = (linear_params->SharedHintHeader.MostObjectLength - linear_params->SharedHintHeader.LeastObjectLength + 1) / 2;
2546
0
    j = 0;
2547
0
    while (i) {
2548
0
        i = i / 2;
2549
0
        j++;
2550
0
    }
2551
0
    linear_params->SharedHintHeader.LengthNumBits = j + 1;
2552
0
    write_hint_stream(linear_params, (gs_offset_t)linear_params->SharedHintHeader.LengthNumBits, 16);
2553
2554
0
    for (i = 0; i< linear_params->NumSharedHints; i++) {
2555
0
        unsigned int Length = linear_params->SharedHints[i].ObjectLength - linear_params->SharedHintHeader.LeastObjectLength;
2556
2557
0
        write_hint_stream(linear_params, (gs_offset_t)Length, linear_params->SharedHintHeader.LengthNumBits);
2558
0
        dmprintf2(pdev->pdf_memory, "Shared Object group %d, Length %d\n", i, Length);
2559
0
    }
2560
2561
0
    j = 0;
2562
0
    for (i = 0; i< linear_params->NumSharedHints; i++) {
2563
0
        write_hint_stream(linear_params, (gs_offset_t)j, 1);
2564
0
        dmprintf1(pdev->pdf_memory, "Shared Object group %d, SignatureFlag false\n", i);
2565
0
    }
2566
0
    for (i = 0; i< linear_params->NumSharedHints; i++) {
2567
0
        write_hint_stream(linear_params, (gs_offset_t)j, 1);
2568
0
        dmprintf1(pdev->pdf_memory, "Shared Object group %d, NumObjects 1\n", i);
2569
0
    }
2570
2571
0
    flush_hint_stream(linear_params);
2572
0
    HintLength = gp_ftell(linear_params->sfile) - HintStreamStart;
2573
2574
0
    gs_snprintf(LDict, sizeof(LDict), "\nendstream\nendobj\n");
2575
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2576
    /* Calculate the length of the primary hint stream */
2577
0
    HintStreamLen = gp_ftell(linear_params->sfile) - pdev->ResourceUsage[HintStreamObj].LinearisedOffset;
2578
    /* Read remainder of linearised file and write to the final file */
2579
0
    do {
2580
0
        code = gp_fread(Buffer, 1, 1024, linear_params->Lin_File.file);
2581
0
        if (code > 0)
2582
0
            gp_fwrite(Buffer, 1, code, linear_params->sfile);
2583
0
    } while (code > 0);
2584
2585
    /* Main xref (part 11) */
2586
0
    mainxref = gp_ftell(linear_params->sfile);
2587
    /* Acrobat 9 and X (possibly other versions) won't recognise a file as
2588
     * optimised unless the file is at least 4k bytes in length (!!!)
2589
     * Also, it is possible that the new file might be smaller than the old one, If a
2590
     * frequently used object changed to a lower number (eg form object 100 to object 10)
2591
     * We don't close and reopen the file, so we need to make sure that any difference
2592
     * is filled in with white space.
2593
     */
2594
0
    if (linear_params->MainFileEnd < 4096)
2595
0
        Length = 4096 - (mainxref + strlen(LDict) + strlen(Header) + LDictObj * 20);
2596
0
    else
2597
0
        Length = linear_params->MainFileEnd - (mainxref + strlen(LDict) + strlen(Header) + LDictObj * 20);
2598
0
    Pad = ' ';
2599
2600
0
    while(Length > 0) {
2601
0
        gp_fwrite(&Pad, 1, 1, linear_params->sfile);
2602
0
        Length--;
2603
0
    }
2604
2605
    /* Now the file is long enough, write the xref */
2606
0
    mainxref = gp_ftell(linear_params->sfile);
2607
0
    gs_snprintf(Header, sizeof(Header), "xref\n0 %d\n", LDictObj);
2608
0
    gp_fwrite(Header, strlen(Header), 1, linear_params->sfile);
2609
2610
0
    linear_params->T = gp_ftell(linear_params->sfile) - 1;
2611
0
    gs_snprintf(Header, sizeof(Header), "0000000000 65535 f \n");
2612
0
    gp_fwrite(Header, strlen(Header), 1, linear_params->sfile);
2613
2614
0
    for (i = 1;i < LDictObj; i++) {
2615
0
        for (j = 0; j < pdev->ResourceUsageSize;j++) {
2616
0
            if (pdev->ResourceUsage[j].NewObjectNumber == i) {
2617
0
                gs_snprintf(Header, sizeof(Header), "%010"PRId64" 00000 n \n", pdev->ResourceUsage[j].LinearisedOffset + HintStreamLen);
2618
0
                gp_fwrite(Header, 20, 1, linear_params->sfile);
2619
0
            }
2620
0
        }
2621
0
    }
2622
2623
0
    gs_snprintf(LDict, sizeof(LDict), "trailer\n<</Size %d>>\nstartxref\n%"PRId64"\n%%%%EOF\n",
2624
0
        LDictObj, linear_params->FirstxrefOffset);
2625
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2626
2627
0
    linear_params->FileLength = gp_ftell(linear_params->sfile);
2628
    /* Return to the linearisation dictionary and write it again filling
2629
     * in the missing data.
2630
     */
2631
    /* Implementation Note 178 in the PDF Reference 1.7 says that Acrobat requires
2632
     * a white space after the '[' for the hint stream offset. This appears not to be true
2633
     * for current versions, but we follow it anyway for the possible benefit of older
2634
     * versions.
2635
     */
2636
0
    gp_fseek(linear_params->sfile, linear_params->LDictOffset, SEEK_SET);
2637
0
    gs_snprintf(LDict, sizeof(LDict), "%d 0 obj\n<</Linearized 1/L %"PRId64"/H[ ", LDictObj, linear_params->FileLength);
2638
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2639
2640
0
    gs_snprintf(LDict, sizeof(LDict), "%"PRId64"", pdev->ResourceUsage[HintStreamObj].LinearisedOffset);
2641
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2642
0
    gs_snprintf(LDict, sizeof(LDict), " %"PRId64"]", HintStreamLen);
2643
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2644
    /* Implementation Note 180 in hte PDF Reference 1.7 says that Acrobat
2645
     * gets the 'E' value wrong. So its probably not important....
2646
     */
2647
0
    gs_snprintf(LDict, sizeof(LDict), "/O %d/E %"PRId64"",pdev->ResourceUsage[pdev->pages[0].Page->id].NewObjectNumber, linear_params->E);
2648
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2649
0
    gs_snprintf(LDict, sizeof(LDict), "/N %d/T %"PRId64">>\nendobj\n", pdev->next_page, linear_params->T);
2650
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2651
2652
    /* Return to the secondary xref and write it again filling
2653
     * in the missing offsets.
2654
     */
2655
0
    if (gp_fseek(linear_params->sfile, linear_params->FirstxrefOffset, SEEK_SET) != 0) {
2656
0
        code = gs_error_ioerror;
2657
0
        goto error;
2658
0
    }
2659
0
    gs_snprintf(Header, sizeof(Header), "xref\n%d %d\n", LDictObj, Part1To6 - LDictObj + 1); /* +1 for the primary hint stream */
2660
0
    gp_fwrite(Header, strlen(Header), 1, linear_params->sfile);
2661
2662
0
    for (i = LDictObj;i <= linear_params->LastResource + 2; i++) {
2663
0
        for (j = 0; j < pdev->ResourceUsageSize;j++) {
2664
0
            if (pdev->ResourceUsage[j].NewObjectNumber == i) {
2665
0
                gs_snprintf(Header, sizeof(Header), "%010"PRId64" 00000 n \n", pdev->ResourceUsage[j].LinearisedOffset);
2666
0
                gp_fwrite(Header, 20, 1, linear_params->sfile);
2667
0
            }
2668
0
        }
2669
0
    }
2670
2671
    /* Return to the secondary trailer dict and write it again filling
2672
     * in the missing values.
2673
     */
2674
0
    code = gp_fseek(linear_params->sfile, linear_params->FirsttrailerOffset, SEEK_SET);
2675
0
    if (code != 0)
2676
0
        return_error(gs_error_ioerror);
2677
2678
0
    if (pdev->OmitID)
2679
0
        gs_snprintf(LDict, sizeof(LDict), "\ntrailer\n<</Size %"PRId64"/Info %d 0 R/Root %d 0 R/Prev %"PRId64">>\nstartxref\r\n0\n%%%%EOF\n",
2680
0
        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber, mainxref);
2681
0
    else
2682
0
        gs_snprintf(LDict, sizeof(LDict), "\ntrailer\n<</Size %"PRId64"/Info %d 0 R/Root %d 0 R/ID[%s%s]/Prev %"PRId64">>\nstartxref\r\n0\n%%%%EOF\n",
2683
0
        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber, fileID, fileID, mainxref);
2684
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2685
2686
0
    code = gp_fseek(linear_params->sfile, pdev->ResourceUsage[HintStreamObj].LinearisedOffset, SEEK_SET);
2687
0
    if (code != 0)
2688
0
        return_error(gs_error_ioerror);
2689
2690
0
    gs_snprintf(LDict, sizeof(LDict), "%d 0 obj\n<</Length %10"PRId64"", HintStreamObj, HintLength);
2691
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2692
0
    gs_snprintf(LDict, sizeof(LDict), "\n/S %10"PRId64">>\nstream\n", SharedHintOffset);
2693
0
    gp_fwrite(LDict, strlen(LDict), 1, linear_params->sfile);
2694
2695
0
error:
2696
#ifdef LINEAR_DEBUGGING
2697
    fclose(linear_params->Lin_File.file);
2698
#else
2699
0
    pdf_close_temp_file(pdev, &linear_params->Lin_File, code);
2700
0
#endif
2701
        /* FIXME free all the linearisation records */
2702
2703
0
    if (linear_params->PageHints != NULL) {
2704
0
        for (i=0;i<pdev->next_page;i++) {
2705
0
            page_hint_stream_t *pagehint = &linear_params->PageHints[i];
2706
2707
0
            if (pagehint && pagehint->SharedObjectRef)
2708
0
                gs_free_object(pdev->pdf_memory, pagehint->SharedObjectRef, "Free Shared object references");
2709
0
        }
2710
0
    }
2711
2712
0
    gs_free_object(pdev->pdf_memory, linear_params->PageHints, "Free Page Hint data");
2713
0
    gs_free_object(pdev->pdf_memory, linear_params->SharedHints, "Free Shared hint data");
2714
2715
0
    return code;
2716
0
}
2717
2718
int pdf_record_usage(gx_device_pdf *const pdev, int64_t resource_id, int page_num)
2719
447k
{
2720
447k
    int i;
2721
447k
    void *Temp;
2722
447k
    pdf_linearisation_record_t *resize;
2723
2724
447k
    if (!pdev->Linearise)
2725
447k
        return 0;
2726
2727
0
    if (resource_id < 0)
2728
0
        return 0;
2729
2730
0
    if (resource_id >= pdev->ResourceUsageSize) {
2731
0
        if (pdev->ResourceUsageSize == 0) {
2732
0
            pdev->ResourceUsageSize = resource_id + 1;
2733
0
            pdev->ResourceUsage = gs_alloc_struct_array(pdev->pdf_memory->non_gc_memory, resource_id + 1, pdf_linearisation_record_t,
2734
0
                              &st_pdf_linearisation_record_element, "start resource usage array");
2735
0
            if (pdev->ResourceUsage == NULL)
2736
0
                return_error(gs_error_VMerror);
2737
0
            memset((char *)pdev->ResourceUsage, 0x00, (resource_id + 1) * sizeof(pdf_linearisation_record_t));
2738
0
        } else {
2739
0
            resize = gs_resize_object(pdev->pdf_memory->non_gc_memory, pdev->ResourceUsage, resource_id + 1, "resize resource usage array");
2740
0
            if (resize == NULL)
2741
0
                return_error(gs_error_VMerror);
2742
0
            memset(&resize[pdev->ResourceUsageSize], 0x00, sizeof(pdf_linearisation_record_t) * (resource_id - pdev->ResourceUsageSize + 1));
2743
0
            pdev->ResourceUsageSize = resource_id + 1;
2744
0
            pdev->ResourceUsage = resize;
2745
0
        }
2746
0
    }
2747
0
    if (page_num > 0) {
2748
0
        if (pdev->ResourceUsage[resource_id].PageUsage == 0)
2749
0
            pdev->ResourceUsage[resource_id].PageUsage = page_num;
2750
0
        else {
2751
0
            if (pdev->ResourceUsage[resource_id].PageUsage > 1)
2752
0
                pdev->ResourceUsage[resource_id].PageUsage = resource_usage_page_shared;
2753
0
            else {
2754
                /* Should not happen, raise an error */
2755
0
            }
2756
0
        }
2757
0
    } else {
2758
0
        if (pdev->ResourceUsage[resource_id].PageUsage != 0)
2759
           /* Should not happen, raise an error */
2760
0
            ;
2761
0
        pdev->ResourceUsage[resource_id].PageUsage = page_num;
2762
0
    }
2763
2764
    /* First check we haven't already recorded this Resource being used by this page */
2765
0
    if (pdev->ResourceUsage[resource_id].NumPagesUsing != 0) {
2766
0
        for (i=0;i < pdev->ResourceUsage[resource_id].NumPagesUsing; i++) {
2767
0
            if (pdev->ResourceUsage[resource_id].PageList[i] == page_num)
2768
0
                return 0;
2769
0
        }
2770
0
    }
2771
0
    Temp = gs_alloc_bytes(pdev->pdf_memory->non_gc_memory, (size_t)(pdev->ResourceUsage[resource_id].NumPagesUsing + 1) * sizeof (int), "Page usage records");
2772
0
    if (Temp == NULL)
2773
0
        return_error(gs_error_VMerror);
2774
0
    memset((char *)Temp, 0x00, (pdev->ResourceUsage[resource_id].NumPagesUsing + 1) * sizeof (int));
2775
0
    memcpy((char *)Temp, pdev->ResourceUsage[resource_id].PageList, pdev->ResourceUsage[resource_id].NumPagesUsing * sizeof (int));
2776
0
    gs_free_object(pdev->pdf_memory->non_gc_memory, (byte *)pdev->ResourceUsage[resource_id].PageList, "Free old page usage records");
2777
0
    pdev->ResourceUsage[resource_id].PageList = (int *)Temp;
2778
0
    pdev->ResourceUsage[resource_id].PageList[pdev->ResourceUsage[resource_id].NumPagesUsing] = page_num;
2779
0
    pdev->ResourceUsage[resource_id].NumPagesUsing++;
2780
2781
0
    return 0;
2782
0
}
2783
2784
int pdf_record_usage_by_parent(gx_device_pdf *const pdev, int64_t resource_id, int64_t parent_id)
2785
154k
{
2786
154k
    int i;
2787
154k
    if (!pdev->Linearise)
2788
154k
        return 0;
2789
2790
0
    if (pdev->ResourceUsage[parent_id].PageUsage >= 0)
2791
0
        pdf_record_usage(pdev, resource_id, pdev->ResourceUsage[parent_id].PageUsage);
2792
0
    else {
2793
0
        for (i = 0; i < pdev->ResourceUsage[parent_id].NumPagesUsing; i++) {
2794
0
            pdf_record_usage(pdev, resource_id, pdev->ResourceUsage[parent_id].PageList[i]);
2795
0
        }
2796
0
    }
2797
0
    return 0;
2798
154k
}
2799
2800
/* This routine is related to the PCL interpreter. Because of the way that
2801
 * PCL pass through works, the PCL interpreter can shut down and free its font cache
2802
 * while still running. This leaves us with copies of fonts, which point to a now
2803
 * freed font cache. Large parts of the code which retrieve font information require
2804
 * that the font cache be present, and fail badly if it isn't. So we construct a
2805
 * font cache of our own, and when we copy fonts from the interpreter we point the
2806
 * copied font at this font cache, instead of the one the original font used.
2807
 * This allows the PCL interpreter to shut down and free its cache, thus eliminating
2808
 * a memory leak, while still allowing pdfwrite to retrieve the information it needs
2809
 * from the copied fonts.
2810
 * Here we need to shut down and free our font cache.
2811
 */
2812
static void pdf_free_pdf_font_cache(gx_device_pdf *pdev)
2813
39.3k
{
2814
39.3k
    if (pdev->pdf_font_dir == NULL)
2815
0
        return;
2816
39.3k
    gs_free_object(pdev->pdf_font_dir->memory, pdev->pdf_font_dir, "pdf_free_pdf_font_cache");
2817
39.3k
    pdev->pdf_font_dir = NULL;
2818
39.3k
}
2819
2820
static int discard_dict_refs(void *client_data, const byte *key_data, uint key_size, const cos_value_t *v);
2821
2822
static int discard_array_refs(gx_device_pdf *pdev, cos_object_t *pco)
2823
5.40k
{
2824
5.40k
    int i;
2825
5.40k
    int64_t index;
2826
5.40k
    cos_array_t *pca = (cos_array_t *)pco;
2827
5.40k
    const cos_array_element_t *element = cos_array_element_first(pca);
2828
5.40k
    cos_value_t *v;
2829
2830
27.0k
    while (element) {
2831
21.6k
        element = cos_array_element_next(element, &index, (const cos_value_t **)&v);
2832
21.6k
        if (v->value_type == COS_VALUE_OBJECT) {
2833
0
            for (i=0;i<NUM_RESOURCE_TYPES;i++) {
2834
0
                if (i == resourceOther)
2835
0
                    continue;
2836
0
                if (pdf_find_resource_by_resource_id(pdev, i, v->contents.object->id)){
2837
0
                    v->value_type = COS_VALUE_CONST;
2838
0
                    break;
2839
0
                }
2840
0
                if (cos_type(v->contents.object) == cos_type_array) {
2841
0
                    discard_array_refs(pdev, v->contents.object);
2842
0
                }
2843
0
                if (cos_type(v->contents.object) == cos_type_dict) {
2844
0
                    cos_dict_forall((const cos_dict_t *)v->contents.object, pdev, discard_dict_refs);
2845
0
                }
2846
0
            }
2847
0
        }
2848
21.6k
    }
2849
5.40k
    return 0;
2850
5.40k
}
2851
2852
static int discard_dict_refs(void *client_data, const byte *key_data, uint key_size, const cos_value_t *v)
2853
768
{
2854
768
    int i;
2855
768
    gx_device_pdf *pdev = (gx_device_pdf *)client_data;
2856
768
    cos_value_t *v1 = (cos_value_t *)v;
2857
2858
768
    if (v->value_type == COS_VALUE_OBJECT) {
2859
6.52k
        for (i=0;i<NUM_RESOURCE_TYPES;i++) {
2860
6.14k
            if (i == resourceOther)
2861
384
                continue;
2862
5.76k
            if (pdf_find_resource_by_resource_id(pdev, i, v->contents.object->id)){
2863
0
                v1->value_type = COS_VALUE_CONST;
2864
0
                break;
2865
0
            }
2866
5.76k
            if (cos_type(v->contents.object) == cos_type_array) {
2867
5.40k
                discard_array_refs(pdev, v->contents.object);
2868
5.40k
            }
2869
5.76k
            if (cos_type(v->contents.object) == cos_type_dict) {
2870
360
                cos_dict_forall((const cos_dict_t *)v->contents.object, pdev, discard_dict_refs);
2871
360
            }
2872
5.76k
        }
2873
384
    }
2874
768
    return 0;
2875
768
}
2876
2877
/* Close the device. */
2878
static int
2879
pdf_close(gx_device * dev)
2880
39.3k
{
2881
39.3k
    gx_device_pdf *const pdev = (gx_device_pdf *) dev;
2882
39.3k
    gs_memory_t *mem = pdev->pdf_memory;
2883
39.3k
    stream *s = NULL;
2884
39.3k
    gp_file *tfile = pdev->xref.file;
2885
39.3k
    gs_offset_t xref = 0;
2886
39.3k
    gs_offset_t resource_pos = 0;
2887
39.3k
    int64_t Catalog_id = 0, Info_id = 0,
2888
39.3k
        Pages_id = 0, Encrypt_id = 0;
2889
39.3k
    int64_t Threads_id = 0;
2890
39.3k
    bool partial_page = (pdev->contents_id != 0 && pdev->next_page != 0);
2891
39.3k
    int code = 0, code1, pagecount=0;
2892
39.3k
    int64_t start_section, end_section;
2893
39.3k
    char str[256];
2894
39.3k
    pdf_linearisation_t linear_params;
2895
39.3k
    bool file_per_page = false;
2896
39.3k
    int bottom = (pdev->ResourcesBeforeUsage ? 1 : 0);
2897
2898
39.3k
    if (!dev->is_open)
2899
0
        return_error(gs_error_undefined);
2900
39.3k
    dev->is_open = false;
2901
2902
39.3k
    if (pdev->sbstack_depth > bottom) {
2903
16
        emprintf(pdev->pdf_memory, "Error closing device; open substreams detected!\n");
2904
16
        emprintf(pdev->pdf_memory, "Probably due to errors in the input. Output file is incorrect/invalid.\n");
2905
16
    }
2906
2907
39.3k
    while(pdev->sbstack_depth > bottom)
2908
        /* This is an error, and we are trying to recover, so ignore any further errors */
2909
16
        (void)pdf_exit_substream(pdev);
2910
2911
39.3k
    if (pdev->initial_pattern_states != NULL) {
2912
2
        int pdepth = 0;
2913
2914
4
        while (pdev->initial_pattern_states[pdepth] != 0x00) {
2915
2
            gs_free_object(pdev->pdf_memory, pdev->initial_pattern_states[pdepth], "Freeing dangling pattern state");
2916
2
            pdev->initial_pattern_states[pdepth] = NULL;
2917
2
            pdepth++;
2918
2
        }
2919
2
        gs_free_object(pdev->pdf_memory->non_gc_memory, pdev->initial_pattern_states, "Freeing dangling pattern state stack");
2920
2
        pdev->initial_pattern_states = NULL;
2921
2
    }
2922
2923
39.3k
    if (pdev->Catalog)
2924
39.3k
        Catalog_id = pdev->Catalog->id;
2925
39.3k
    if (pdev->Info)
2926
39.3k
        Info_id = pdev->Info->id;
2927
39.3k
    if (pdev->Pages)
2928
39.3k
        Pages_id = pdev->Pages->id;
2929
2930
39.3k
    memset(&linear_params, 0x00, sizeof(linear_params));
2931
39.3k
    linear_params.Info_id = Info_id;
2932
39.3k
    linear_params.Pages_id = Pages_id;
2933
39.3k
    linear_params.Catalog_id = Catalog_id;
2934
2935
    /*
2936
     * If this is an EPS file, or if the file didn't end with a showpage for
2937
     * some other reason, or if the file has produced no marks at all, we
2938
     * need to tidy up a little so as not to produce illegal PDF.  However,
2939
     * if there is at least one complete page, we discard any leftover
2940
     * marks.
2941
     */
2942
39.3k
    if (pdev->next_page == 0) {
2943
19.1k
        file_per_page = !pdev->InOutputPage &&
2944
19.1k
            gx_outputfile_is_separate_pages(pdev->fname, pdev->memory);
2945
19.1k
        if (!file_per_page) {
2946
19.1k
            code = pdf_open_page(pdev, PDF_IN_STREAM);
2947
2948
19.1k
            if (code < 0)
2949
0
                return code;
2950
19.1k
        }
2951
19.1k
    }
2952
39.3k
    if (pdev->contents_id != 0)
2953
20.1k
        pdf_close_page(pdev, 1);
2954
2955
    /* Write the page objects. */
2956
39.3k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC)) {
2957
55.4k
        for (pagecount = 1; pagecount <= pdev->next_page; ++pagecount)
2958
31.8k
            pdf_write_page(pdev, pagecount);
2959
23.6k
    }
2960
2961
39.3k
    if (pdev->PrintStatistics)
2962
0
        pdf_print_resource_statistics(pdev);
2963
2964
    /* Write the font resources and related resources. */
2965
39.3k
    code1 = pdf_write_resource_objects(pdev, resourceXObject);
2966
39.3k
    if (code >= 0)
2967
39.3k
        code = code1;
2968
39.3k
    code1 = pdf_free_resource_objects(pdev, resourceXObject);
2969
39.3k
    if (code >= 0)
2970
39.3k
        code = code1;
2971
39.3k
    code1 = pdf_free_resource_objects(pdev, resourceProperties);
2972
39.3k
    if (code >= 0)
2973
39.3k
        code = code1;
2974
39.3k
    code1 = pdf_write_resource_objects(pdev, resourceGroup);
2975
39.3k
    if (code >= 0)
2976
39.3k
        code = code1;
2977
39.3k
    code1 = pdf_free_resource_objects(pdev, resourceGroup);
2978
39.3k
    if (code >= 0)
2979
39.3k
        code = code1;
2980
39.3k
    code1 = pdf_write_resource_objects(pdev, resourceSoftMaskDict);
2981
39.3k
    if (code >= 0)
2982
39.3k
        code = code1;
2983
39.3k
    code1 = pdf_free_resource_objects(pdev, resourceSoftMaskDict);
2984
39.3k
    if (code >= 0)
2985
39.3k
        code = code1;
2986
    /* This was in pdf_close_document, but that made no sense, so moved here
2987
     * for more consistency (and ease of finding it). This code deals with
2988
     * emitting fonts and FontDescriptors
2989
     */
2990
39.3k
    pdf_clean_standard_fonts(pdev);
2991
39.3k
    code1 = pdf_free_font_cache(pdev);
2992
39.3k
    if (code >= 0)
2993
39.3k
        code = code1;
2994
39.3k
    code1 = pdf_write_resource_objects(pdev, resourceCharProc);
2995
39.3k
    if (code >= 0)
2996
39.3k
        code = code1;
2997
39.3k
    code1 = pdf_finish_resources(pdev, resourceFont, pdf_convert_truetype_font);
2998
39.3k
    if (code >= 0)
2999
39.3k
        code = code1;
3000
39.3k
    code1 = pdf_finish_resources(pdev, resourceFontDescriptor, pdf_finish_FontDescriptor);
3001
39.3k
    if (code >= 0)
3002
39.3k
        code = code1;
3003
39.3k
    code1 = write_font_resources(pdev, &pdev->resources[resourceCIDFont]);
3004
39.3k
    if (code >= 0)
3005
39.2k
        code = code1;
3006
39.3k
    code1 = write_font_resources(pdev, &pdev->resources[resourceFont]);
3007
39.3k
    if (code >= 0)
3008
39.2k
        code = code1;
3009
39.3k
    code1 = pdf_finish_resources(pdev, resourceFontDescriptor, pdf_write_FontDescriptor);
3010
39.3k
    if (code >= 0)
3011
39.2k
        code = code1;
3012
    /* If required, write the Encoding for Type 3 bitmap fonts. */
3013
39.3k
    code1 = pdf_write_bitmap_fonts_Encoding(pdev);
3014
39.3k
    if (code >= 0)
3015
39.2k
        code = code1;
3016
3017
39.3k
    code1 = pdf_write_resource_objects(pdev, resourceCMap);
3018
39.3k
    if (code >= 0)
3019
39.2k
        code = code1;
3020
39.3k
    code1 = pdf_free_resource_objects(pdev, resourceCMap);
3021
39.3k
    if (code >= 0)
3022
39.2k
        code = code1;
3023
39.3k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC)) {
3024
23.6k
        if (pdev->ResourcesBeforeUsage)
3025
0
            pdf_reverse_resource_chain(pdev, resourcePage);
3026
23.6k
        code1 = pdf_write_resource_objects(pdev, resourcePage);
3027
23.6k
        if (code >= 0)
3028
23.5k
            code = code1;
3029
23.6k
        code1 = pdf_free_resource_objects(pdev, resourcePage);
3030
23.6k
        if (code >= 0)
3031
23.5k
            code = code1;
3032
23.6k
    }
3033
3034
    /* Create the Pages tree. */
3035
39.3k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC) && pdev->strm != NULL) {
3036
23.6k
        pdf_open_obj(pdev, Pages_id, resourcePagesTree);
3037
23.6k
        pdf_record_usage(pdev, Pages_id, resource_usage_part9_structure);
3038
3039
23.6k
        s = pdev->strm;
3040
23.6k
        stream_puts(s, "<< /Type /Pages /Kids [\n");
3041
        /* Omit the last page if it was incomplete. */
3042
23.6k
        if (partial_page)
3043
17
            --(pdev->next_page);
3044
23.6k
        {
3045
23.6k
            int i;
3046
3047
55.4k
            for (i = 0; i < pdev->next_page; ++i)
3048
31.7k
                pprinti64d1(s, "%"PRId64" 0 R\n", pdev->pages[i].Page->id);
3049
23.6k
        }
3050
23.6k
        pprintd1(s, "] /Count %d\n", pdev->next_page);
3051
3052
        /* If the last file was PostScript, its possible that DSC comments might be lying around
3053
         * and pdf_print_orientation will use that if its present. So make sure we get rid of those
3054
         * before considering the dominant page direction for the Pages tree.
3055
         */
3056
23.6k
        pdev->doc_dsc_info.viewing_orientation = pdev->doc_dsc_info.orientation = -1;
3057
23.6k
        pdev->text_rotation.Rotate = pdf_dominant_rotation(&pdev->text_rotation);
3058
23.6k
        pdf_print_orientation(pdev, NULL);
3059
3060
23.6k
        cos_dict_elements_write(pdev->Pages, pdev);
3061
23.6k
        stream_puts(s, ">>\n");
3062
23.6k
        pdf_end_obj(pdev, resourcePagesTree);
3063
3064
        /* Close outlines and articles. */
3065
3066
23.6k
        if (pdev->outlines_id != 0) {
3067
444
            pdf_record_usage(pdev, pdev->outlines_id, resource_usage_part9_structure);
3068
            /* depth > 0 is only possible for an incomplete outline tree. */
3069
463
            while (pdev->outline_depth > 0) {
3070
19
                code1 = pdfmark_close_outline(pdev);
3071
19
                if (code >= 0)
3072
19
                    code = code1;
3073
19
            }
3074
444
            code = pdfmark_close_outline(pdev);
3075
444
            if (code >= 0)
3076
444
                code = code1;
3077
444
            pdf_open_obj(pdev, pdev->outlines_id, resourceOutline);
3078
444
            pprintd1(s, "<< /Type /Outlines /Count %d", pdev->outlines_open);
3079
444
            pprinti64d2(s, " /First %"PRId64" 0 R /Last %"PRId64" 0 R >>\n",
3080
444
                  pdev->outline_levels[0].first.id,
3081
444
                  pdev->outline_levels[0].last.id);
3082
444
            pdf_end_obj(pdev, resourceOutline);
3083
444
        }
3084
23.6k
        if (pdev->articles != 0) {
3085
0
            pdf_article_t *part;
3086
3087
            /* Write the remaining information for each article. */
3088
0
            for (part = pdev->articles; part != 0; part = part->next)
3089
0
                pdfmark_write_article(pdev, part);
3090
0
        }
3091
3092
        /* Write named destinations.  (We can't free them yet.) */
3093
3094
23.6k
        if (pdev->CompatibilityLevel < 1.2) {
3095
2
            if (pdev->Dests) {
3096
0
                pdf_record_usage(pdev, pdev->Dests->id, resource_usage_part9_structure);
3097
0
                COS_WRITE_OBJECT(pdev->Dests, pdev, resourceDests);
3098
0
            }
3099
23.6k
        } else {
3100
23.6k
            if (pdev->Dests) {
3101
0
                pdf_record_usage(pdev, pdev->Dests->id, resource_usage_part9_structure);
3102
0
                cos_write_dict_as_ordered_array((cos_object_t *)pdev->Dests, pdev, resourceDests);
3103
0
            }
3104
            /* Write Embedded files.  (We can't free them yet.) */
3105
3106
23.6k
            if (pdev->EmbeddedFiles) {
3107
31
                pdf_record_usage(pdev, pdev->EmbeddedFiles->id, resource_usage_part9_structure);
3108
31
                cos_write_dict_as_ordered_array((cos_object_t *)pdev->EmbeddedFiles, pdev, resourceEmbeddedFiles);
3109
31
            }
3110
23.6k
            if (pdev->AF) {
3111
0
                pdf_record_usage(pdev, pdev->AF->id, resource_usage_part9_structure);
3112
0
                COS_WRITE_OBJECT(pdev->AF, pdev, resourceEmbeddedFiles);
3113
0
            }
3114
23.6k
        }
3115
3116
        /* Write the PageLabel array */
3117
23.6k
        pdfmark_end_pagelabels(pdev);
3118
23.6k
        if (pdev->PageLabels) {
3119
0
            pdf_record_usage(pdev, pdev->PageLabels->id, resource_usage_part9_structure);
3120
0
            COS_WRITE_OBJECT(pdev->PageLabels, pdev, resourceLabels);
3121
0
        }
3122
3123
23.6k
        if (!pdev->OmitXMP) {
3124
23.6k
            bool saved = pdev->WriteObjStms;
3125
3126
23.6k
            if (pdev->WriteObjStms)
3127
23.6k
                pdev->WriteObjStms = false;
3128
            /* Write the document metadata. */
3129
23.6k
            code1 = pdf_document_metadata(pdev);
3130
23.6k
            pdev->WriteObjStms = saved;
3131
23.6k
            if (code >= 0)
3132
23.5k
                code = code1;
3133
23.6k
        }
3134
3135
        /* Write the Catalog. */
3136
3137
        /*
3138
         * The PDF specification requires Threads to be an indirect object.
3139
         * Write the threads now, if any.
3140
         */
3141
23.6k
        if (pdev->articles != 0) {
3142
0
            pdf_article_t *part;
3143
3144
0
            Threads_id = pdf_begin_obj(pdev, resourceThread);
3145
0
            pdf_record_usage(pdev, Threads_id, resource_usage_part9_structure);
3146
0
            s = pdev->strm;
3147
0
            stream_puts(s, "[ ");
3148
0
            while ((part = pdev->articles) != 0) {
3149
0
                pdev->articles = part->next;
3150
0
                pprinti64d1(s, "%"PRId64" 0 R\n", part->contents->id);
3151
0
                COS_FREE(part->contents, "pdf_close(article contents)");
3152
0
                gs_free_object(mem, part, "pdf_close(article)");
3153
0
            }
3154
0
            stream_puts(s, "]\n");
3155
0
            pdf_end_obj(pdev, resourceThread);
3156
0
        }
3157
23.6k
        pdf_open_obj(pdev, Catalog_id, resourceCatalog);
3158
23.6k
        pdf_record_usage(pdev, Catalog_id, resource_usage_part1_structure);
3159
3160
23.6k
        s = pdev->strm;
3161
23.6k
        stream_puts(s, "<<");
3162
23.6k
        pprinti64d1(s, "/Type /Catalog /Pages %"PRId64" 0 R\n", Pages_id);
3163
23.6k
        if (pdev->outlines_id != 0)
3164
444
            pprinti64d1(s, "/Outlines %"PRId64" 0 R\n", pdev->outlines_id);
3165
23.6k
        if (Threads_id) {
3166
0
            pprinti64d1(s, "/Threads %"PRId64" 0 R\n", Threads_id);
3167
0
            pdf_record_usage(pdev, Threads_id, resource_usage_part1_structure);
3168
0
        }
3169
23.6k
        if (pdev->CompatibilityLevel < 1.2) {
3170
2
            if (pdev->Dests)
3171
0
                pprinti64d1(s, "/Dests %"PRId64" 0 R\n", pdev->Dests->id);
3172
23.6k
        } else {
3173
23.6k
            if (pdev->Dests || pdev->EmbeddedFiles) {
3174
31
                stream_puts(s, "/Names <<\n");
3175
31
                if (pdev->Dests)
3176
0
                    pprinti64d1(s, "/Dests <</Kids [%"PRId64" 0 R]>>\n", pdev->Dests->id);
3177
31
                if (pdev->EmbeddedFiles)
3178
31
                    pprinti64d1(s, "/EmbeddedFiles << /Kids [%"PRId64" 0 R]>>\n", pdev->EmbeddedFiles->id);
3179
31
                stream_puts(s, ">>\n");
3180
31
            }
3181
23.6k
            if (pdev->AF)
3182
0
                if (!cos_dict_find_c_key(pdev->Catalog, "/AF"))
3183
0
                    pprinti64d1(s, "/AF %"PRId64" 0 R\n", pdev->AF->id);
3184
23.6k
        }
3185
23.6k
        if (pdev->PageLabels)
3186
0
            pprinti64d1(s, "/PageLabels << /Nums  %"PRId64" 0 R >>\n",
3187
0
                  pdev->PageLabels->id);
3188
23.6k
        cos_dict_elements_write(pdev->Catalog, pdev);
3189
23.6k
        stream_puts(s, ">>\n");
3190
23.6k
        pdf_end_obj(pdev, resourceCatalog);
3191
23.6k
        if (pdev->Dests) {
3192
0
            COS_FREE(pdev->Dests, "pdf_close(Dests)");
3193
0
            pdev->Dests = 0;
3194
0
        }
3195
23.6k
        if (pdev->EmbeddedFiles) {
3196
31
            COS_FREE(pdev->EmbeddedFiles, "pdf_close(EmbeddFiles)");
3197
31
            pdev->EmbeddedFiles = 0;
3198
31
        }
3199
23.6k
        if (pdev->AF) {
3200
0
            COS_FREE(pdev->AF, "pdf_close(AF)");
3201
0
            pdev->AF = 0;
3202
0
        }
3203
23.6k
        if (pdev->PageLabels) {
3204
0
            COS_FREE(pdev->PageLabels, "pdf_close(PageLabels)");
3205
0
            pdev->PageLabels = 0;
3206
0
            pdev->PageLabels_current_label = 0;
3207
0
        }
3208
3209
        /* Prevent writing special named objects twice. */
3210
3211
23.6k
        pdev->Catalog->id = 0;
3212
        /*pdev->Info->id = 0;*/ /* Info should get written */
3213
23.6k
        pdf_record_usage(pdev, pdev->Info->id, resource_usage_part9_structure);
3214
3215
23.6k
    } else {
3216
15.6k
        if (pdev->Info != NULL)
3217
15.6k
            pdev->Info->id = 0; /* Don't write Info dict for DSC PostScript */
3218
15.6k
    }
3219
    /*
3220
     * Write the definitions of the named objects.
3221
     * Note that this includes Form XObjects created by BP/EP, named PS
3222
     * XObjects, and images named by NI.
3223
     */
3224
3225
39.3k
    if(pdev->local_named_objects != NULL) {
3226
39.3k
        do {
3227
39.3k
            cos_dict_objects_write(pdev->local_named_objects, pdev);
3228
39.3k
        } while (pdf_pop_namespace(pdev) >= 0);
3229
39.3k
    }
3230
39.3k
    if (pdev->global_named_objects != NULL)
3231
39.3k
        cos_dict_objects_write(pdev->global_named_objects, pdev);
3232
3233
39.3k
    if (pdev->ForOPDFRead && pdev->ProduceDSC) {
3234
15.6k
        int pages;
3235
3236
50.8k
        for (pages = 0; pages <= pdev->next_page; ++pages)
3237
35.1k
            ;
3238
3239
15.6k
        code1 = ps2write_dsc_header(pdev, pages - 1);
3240
15.6k
        if (code >= 0)
3241
15.6k
            code = code1;
3242
15.6k
    }
3243
3244
    /* Copy the resources into the main file. */
3245
3246
39.3k
    if (pdev->WriteObjStms) {
3247
23.6k
        FlushObjStm(pdev);
3248
23.6k
        pdev->WriteObjStms = false;
3249
23.6k
    }
3250
39.3k
    if (pdev->strm != NULL) {
3251
39.3k
        s = pdev->strm;
3252
39.3k
        resource_pos = stell(s);
3253
39.3k
        sflush(pdev->asides.strm);
3254
39.3k
        {
3255
39.3k
            gp_file *rfile = pdev->asides.file;
3256
39.3k
            int64_t res_end = gp_ftell(rfile);
3257
3258
39.3k
            gp_fseek(rfile, 0L, SEEK_SET);
3259
39.3k
            code1 = pdf_copy_data(s, rfile, res_end, NULL);
3260
39.3k
            if (code >= 0)
3261
39.0k
                code = code1;
3262
39.3k
        }
3263
39.3k
    }
3264
3265
39.3k
    if (pdev->ForOPDFRead && pdev->ProduceDSC && s != NULL) {
3266
15.6k
        int j;
3267
3268
15.6k
        pagecount = 1;
3269
3270
        /* All resources and procsets written, end the prolog */
3271
15.6k
        stream_puts(pdev->strm, "%%EndProlog\n");
3272
3273
15.6k
        if (pdev->params.PSDocOptions.data) {
3274
0
            int i;
3275
0
            char *p = (char *)pdev->params.PSDocOptions.data;
3276
3277
0
            stream_puts(pdev->strm, "%%BeginSetup\n");
3278
0
            for (i=0;i<pdev->params.PSDocOptions.size;i++)
3279
0
                stream_putc(s, *p++);
3280
0
            stream_puts(pdev->strm, "\n");
3281
0
            stream_puts(pdev->strm, "\n%%EndSetup\n");
3282
0
        }
3283
3284
15.6k
        if (pdev->ResourcesBeforeUsage)
3285
15.6k
            pdf_reverse_resource_chain(pdev, resourcePage);
3286
266k
        for (j = 0; j < NUM_RESOURCE_CHAINS && code >= 0; ++j) {
3287
251k
            pdf_resource_t *pres = pdev->resources[resourcePage].chains[j];
3288
3289
270k
            for (; pres != 0; pres = pres->next)
3290
19.4k
                if ((!pres->named || pdev->ForOPDFRead)
3291
19.4k
                    && !pres->object->written) {
3292
19.4k
                    pdf_page_t *page = &pdev->pages[pagecount - 1];
3293
3294
19.4k
                    pprintd2(pdev->strm, "%%%%Page: %d %d\n",
3295
19.4k
                        pagecount, pagecount);
3296
19.4k
                    if (!pdev->Eps2Write)
3297
5.14k
                        pprintd2(pdev->strm, "%%%%PageBoundingBox: 0 0 %d %d\n", (int)page->MediaBox.x, (int)page->MediaBox.y);
3298
19.4k
                    stream_puts(pdev->strm, "%%BeginPageSetup\n");
3299
3300
19.4k
                    if (pdev->params.PSPageOptions.size) {
3301
0
                        if (pdev->params.PSPageOptionsWrap || (pagecount - 1) < pdev->params.PSPageOptions.size) {
3302
0
                            int i, index = (pagecount - 1) % pdev->params.PSPageOptions.size;
3303
0
                            char *p = (char *)pdev->params.PSPageOptions.data[index].data;
3304
3305
0
                            for (i=0;i<pdev->params.PSPageOptions.data[index].size;i++)
3306
0
                                stream_putc(s, *p++);
3307
0
                            stream_puts(pdev->strm, "\n");
3308
0
                        }
3309
0
                    }
3310
3311
19.4k
                    pdf_write_page(pdev, pagecount++);
3312
3313
19.4k
                    stream_puts(pdev->strm, "%%EndPageSetup\n");
3314
19.4k
                    pprinti64d1(pdev->strm, "%"PRId64" 0 obj\n", pres->object->id);
3315
19.4k
                    code = cos_write(pres->object, pdev, pres->object->id);
3316
19.4k
                    stream_puts(pdev->strm, "endobj\n");
3317
19.4k
                    pres->object->written = true;
3318
19.4k
                    stream_puts(pdev->strm, "%%PageTrailer\n");
3319
19.4k
                }
3320
251k
        }
3321
15.6k
        code1 = pdf_free_resource_objects(pdev, resourcePage);
3322
15.6k
        if (code >= 0)
3323
15.6k
            code = code1;
3324
15.6k
        stream_puts(pdev->strm, "%%Trailer\n");
3325
15.6k
        stream_puts(pdev->strm, "end\n");
3326
15.6k
        stream_puts(pdev->strm, "%%EOF\n");
3327
15.6k
    }
3328
3329
39.3k
    if (pdev->params.PSPageOptions.size) {
3330
0
        int ix;
3331
3332
0
        for (ix = 0; ix < pdev->params.PSPageOptions.size;ix++)
3333
0
            gs_free_object(mem->non_gc_memory, (byte *)pdev->params.PSPageOptions.data[ix].data, "freeing old string array copy");
3334
0
        gs_free_object(mem->non_gc_memory, (byte *)pdev->params.PSPageOptions.data, "freeing old string array");
3335
0
    }
3336
3337
39.3k
    if (pdev->Linearise) {
3338
0
        linear_params.LastResource = pdev->next_id - 1;
3339
0
        linear_params.Offsets = (gs_offset_t *)gs_alloc_bytes(pdev->pdf_memory, pdev->next_id * sizeof(gs_offset_t), "temp xref storage");
3340
0
        if (linear_params.Offsets == NULL) {
3341
0
            code = gs_error_VMerror;
3342
0
            goto error_cleanup;
3343
0
        }
3344
0
        memset(linear_params.Offsets, 0x00, linear_params.LastResource * sizeof(gs_offset_t));
3345
0
    }
3346
3347
39.3k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC) && pdev->strm != NULL) {
3348
        /* Write Encrypt. */
3349
23.6k
        if (pdev->OwnerPassword.size > 0) {
3350
0
            Encrypt_id = pdf_obj_ref(pdev);
3351
3352
0
            pdf_open_obj(pdev, Encrypt_id, resourceEncrypt);
3353
0
            s = pdev->strm;
3354
0
            stream_puts(s, "<<");
3355
0
            stream_puts(s, "/Filter /Standard ");
3356
0
            pprintld1(s, "/V %ld ", pdev->EncryptionV);
3357
0
            pprintld1(s, "/Length %ld ", pdev->KeyLength);
3358
0
            pprintld1(s, "/R %ld ", pdev->EncryptionR);
3359
0
            pprintd1(s, "/P %d ", pdev->Permissions);
3360
0
            stream_puts(s, "/O ");
3361
0
            pdf_put_string(pdev, pdev->EncryptionO, sizeof(pdev->EncryptionO));
3362
0
            stream_puts(s, "\n/U ");
3363
0
            pdf_put_string(pdev, pdev->EncryptionU, sizeof(pdev->EncryptionU));
3364
0
            stream_puts(s, ">>\n");
3365
0
            pdf_end_obj(pdev, resourceEncrypt);
3366
0
            s = pdev->strm;
3367
0
        }
3368
3369
        /* Write the cross-reference section. */
3370
3371
23.6k
        start_section = pdev->FirstObjectNumber;
3372
23.6k
        end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3373
3374
23.6k
        xref = pdf_stell(pdev) - pdev->OPDFRead_procset_length;
3375
23.6k
        if (pdev->Linearise)
3376
0
            linear_params.xref = xref;
3377
3378
23.6k
        if (!pdev->WriteXRefStm) {
3379
12
            if (pdev->FirstObjectNumber == 1) {
3380
12
                gs_snprintf(str, sizeof(str), "xref\n0 %"PRId64"\n0000000000 65535 f \n",
3381
12
                      end_section);
3382
12
                stream_puts(s, str);
3383
12
            }
3384
0
            else {
3385
0
                gs_snprintf(str, sizeof(str), "xref\n0 1\n0000000000 65535 f \n%"PRId64" %"PRId64"\n",
3386
0
                      start_section,
3387
0
                      end_section - start_section);
3388
0
                stream_puts(s, str);
3389
0
            }
3390
3391
13
            do {
3392
13
                code = write_xref_section(pdev, tfile, start_section, end_section, resource_pos, linear_params.Offsets);
3393
13
                if (code < 0)
3394
0
                    goto error_cleanup;
3395
3396
13
                if (end_section >= pdev->next_id)
3397
12
                    break;
3398
1
                do {
3399
1
                    start_section = end_section + 1;
3400
1
                    end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3401
1
                    if (end_section < 0)
3402
0
                        return end_section;
3403
1
                } while (start_section == end_section);
3404
1
                gs_snprintf(str, sizeof(str), "%"PRId64" %"PRId64"\n", start_section, end_section - start_section);
3405
1
                stream_puts(s, str);
3406
1
            } while (1);
3407
3408
            /* Write the trailer. */
3409
12
            if (!pdev->Linearise) {
3410
12
                char xref_str[32];
3411
12
                stream_puts(s, "trailer\n");
3412
12
                pprinti64d3(s, "<< /Size %"PRId64" /Root %"PRId64" 0 R /Info %"PRId64" 0 R\n",
3413
12
                      pdev->next_id, Catalog_id, Info_id);
3414
12
                if (!pdev->OmitID) {
3415
12
                    stream_puts(s, "/ID [");
3416
12
                    psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3417
12
                    psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3418
12
                    stream_puts(s, "]\n");
3419
12
                }
3420
12
                if (pdev->OwnerPassword.size > 0) {
3421
0
                    pprinti64d1(s, "/Encrypt %"PRId64" 0 R ", Encrypt_id);
3422
0
                }
3423
12
                stream_puts(s, ">>\n");
3424
12
                gs_snprintf(xref_str, sizeof(xref_str), "startxref\n%"PRId64"\n%%%%EOF\n", xref);
3425
12
                stream_puts(s, xref_str);
3426
12
            }
3427
23.6k
        } else {
3428
23.6k
            char xref_str[32];
3429
23.6k
            gs_offset_t maxoffs = xref, offs_bytes = 0, length = 0;
3430
23.6k
            int i;
3431
3432
72.2k
            while(maxoffs > 0) {
3433
48.5k
                maxoffs = maxoffs >> 8;
3434
48.5k
                offs_bytes++;
3435
48.5k
            }
3436
3437
23.6k
            gs_snprintf(str, sizeof(str), "%"PRId64" 0 obj\n<<\n/Type /XRef\n", (int64_t)pdev->next_id);
3438
23.6k
            stream_puts(s, str);
3439
23.6k
            gs_snprintf(str, sizeof(str), "/Size %"PRId64"\n", (int64_t)(pdev->next_id + 1));
3440
23.6k
            stream_puts(s, str);
3441
3442
23.6k
            pprinti64d2(s, "/Root %"PRId64" 0 R /Info %"PRId64" 0 R\n", Catalog_id, Info_id);
3443
23.6k
            if (!pdev->OmitID) {
3444
23.6k
                stream_puts(s, "/ID [");
3445
23.6k
                psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3446
23.6k
                psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3447
23.6k
                stream_puts(s, "]\n");
3448
23.6k
            }
3449
23.6k
            if (pdev->OwnerPassword.size > 0) {
3450
0
                pprinti64d1(s, "/Encrypt %"PRId64" 0 R ", Encrypt_id);
3451
0
            }
3452
3453
23.6k
            end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3454
23.6k
            if (end_section == pdev->next_id)
3455
23.5k
                end_section++;
3456
3457
23.6k
            length += (end_section - start_section) * (offs_bytes + 3);
3458
3459
23.6k
            if (pdev->FirstObjectNumber == 1) {
3460
23.6k
                gs_snprintf(str, sizeof(str), "/Index [0 %"PRId64" ", end_section);
3461
23.6k
                stream_puts(s, str);
3462
23.6k
            } else {
3463
0
                gs_snprintf(str, sizeof(str), "/Index [0 1 %"PRId64" %"PRId64" ", pdev->FirstObjectNumber, end_section);
3464
0
                stream_puts(s, str);
3465
0
            }
3466
3467
23.7k
            do {
3468
23.7k
                if (end_section >= pdev->next_id)
3469
23.6k
                    break;
3470
3471
208
                do {
3472
208
                    start_section = end_section + 1;
3473
208
                    end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3474
208
                    if (end_section < 0)
3475
0
                        return end_section;
3476
208
                } while (start_section == end_section);
3477
134
                gs_snprintf(str, sizeof(str), "%"PRId64" %"PRId64" ", start_section, end_section - start_section);
3478
134
                stream_puts(s, str);
3479
134
            }while (1);
3480
3481
23.6k
            {
3482
23.6k
                pdf_temp_file_t xref_temp;
3483
23.6k
                stream *xs = NULL, *xs1;
3484
23.6k
                char xrefbuf[256];
3485
23.6k
                int read = 0;
3486
23.6k
                stream_state *st = NULL;
3487
23.6k
                code = pdf_open_temp_stream(pdev, &xref_temp);
3488
23.6k
                if (code < 0)
3489
0
                    return code;
3490
3491
23.6k
                xs1 = xref_temp.strm;
3492
23.6k
                if (pdev->CompressStreams) {
3493
23.6k
                    if (pdev->UseBrotli) {
3494
0
                        st = s_alloc_state(pdev->pdf_memory, s_brotliE_template.stype, "write_xref_strm");
3495
0
                        if (st == NULL)
3496
0
                            return_error(gs_error_VMerror);
3497
0
                        s_brotliE_template.set_defaults (st);
3498
0
                        xs = s_add_filter(&xref_temp.strm, &s_brotliE_template, st, pdev->pdf_memory);
3499
0
                        if (xs == NULL)
3500
0
                            xs = xref_temp.strm;
3501
23.6k
                    } else {
3502
23.6k
                        st = s_alloc_state(pdev->pdf_memory, s_zlibE_template.stype, "write_xref_strm");
3503
23.6k
                        if (st == NULL)
3504
0
                            return_error(gs_error_VMerror);
3505
23.6k
                        s_zlibE_template.set_defaults (st);
3506
23.6k
                        xs = s_add_filter(&xref_temp.strm, &s_zlibE_template, st, pdev->pdf_memory);
3507
23.6k
                        if (xs == NULL)
3508
0
                            xs = xref_temp.strm;
3509
23.6k
                    }
3510
23.6k
                } else
3511
0
                    xs = xref_temp.strm;
3512
3513
                /* write the free entry */
3514
23.6k
                stream_putc(xs, 0x00);
3515
72.2k
                for (i = 0; i < offs_bytes; i++)
3516
48.5k
                    stream_putc(xs, 0x00);
3517
23.6k
                stream_putc(xs, 0xFF);
3518
23.6k
                stream_putc(xs, 0xFF);
3519
3520
23.6k
                start_section = pdev->FirstObjectNumber;
3521
23.8k
                do {
3522
23.8k
                    end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3523
23.8k
                    if (end_section < 0)
3524
0
                    {
3525
0
                        gs_free_object(pdev->memory, st, "write_xref_strm");
3526
0
                        return end_section;
3527
0
                    }
3528
3529
23.8k
                    code = write_xrefstm_section(pdev, tfile, start_section, end_section, resource_pos, offs_bytes, xs);
3530
23.8k
                    if (code < 0)
3531
0
                    {
3532
0
                        gs_free_object(pdev->memory, st, "write_xref_strm");
3533
0
                        goto error_cleanup;
3534
0
                    }
3535
3536
23.8k
                    start_section = end_section + 1;
3537
23.8k
                } while (end_section < pdev->next_id);
3538
3539
                /* write the entry for this XRefStm */
3540
23.6k
                stream_putc(xs, 0x01);
3541
72.2k
                for (i = 1; i <= offs_bytes; i++)
3542
48.5k
                    stream_putc(xs, (xref >> ((offs_bytes - i) * 8)) & 0xFF);
3543
23.6k
                stream_putc(xs, 0x00);
3544
23.6k
                stream_putc(xs, 0x00);
3545
3546
23.6k
                sflush(xs);
3547
23.6k
                if (pdev->CompressStreams)
3548
23.6k
                    s_close_filters(&xref_temp.strm, xs1);
3549
23.6k
                sflush(xref_temp.strm);
3550
23.6k
                length = stell(xref_temp.strm);
3551
3552
23.6k
                if (pdev->CompressStreams) {
3553
23.6k
                    if (pdev->UseBrotli)
3554
0
                        gs_snprintf(str, sizeof(str), "]\n/W [1 %"PRId64" 2]\n/Filter /BrotliDecode/Length %"PRId64"\n>>\nstream\n", offs_bytes, length);
3555
23.6k
                    else
3556
23.6k
                        gs_snprintf(str, sizeof(str), "]\n/W [1 %"PRId64" 2]\n/Filter /FlateDecode/Length %"PRId64"\n>>\nstream\n", offs_bytes, length);
3557
23.6k
                }
3558
0
                else
3559
0
                    gs_snprintf(str, sizeof(str), "]\n/W [1 %"PRId64" 2]\n/Length %"PRId64"\n>>\nstream\n", offs_bytes, length);
3560
23.6k
                stream_puts(s, str);
3561
3562
23.6k
                code = gp_fseek(xref_temp.file , 0, SEEK_SET);
3563
23.6k
                if (code < 0)
3564
0
                    return code;
3565
25.1k
                do {
3566
25.1k
                    read = gp_fread(&xrefbuf, 1, 256, xref_temp.file);
3567
25.1k
                    if (read < 0)
3568
0
                    {
3569
0
                        gs_free_object(pdev->memory, st, "write_xref_strm");
3570
0
                        return_error(gs_error_VMerror);
3571
0
                    }
3572
25.1k
                    stream_write(s, xrefbuf, read);
3573
25.1k
                } while (read == 256);
3574
3575
23.6k
                pdf_close_temp_file(pdev, &xref_temp, 0);
3576
23.6k
            }
3577
3578
0
            gs_snprintf(str, sizeof(str), "\nendstream\nendobj\n");
3579
23.6k
            stream_puts(s, str);
3580
23.6k
            pdev->next_id++;
3581
3582
23.6k
            gs_snprintf(str, sizeof(xref_str), "startxref\n%"PRId64"\n%%%%EOF\n", xref);
3583
23.6k
            stream_puts(s, str);
3584
23.6k
        }
3585
23.6k
    }
3586
3587
39.3k
    if (pdev->Linearise && pdev->strm != NULL) {
3588
0
        int i;
3589
3590
0
        code = pdf_linearise(pdev, &linear_params);
3591
0
        for (i=0; i<pdev->ResourceUsageSize; i++) {
3592
0
            if (pdev->ResourceUsage[i].PageList)
3593
0
                gs_free_object(pdev->pdf_memory->non_gc_memory, pdev->ResourceUsage[i].PageList, "Free linearisation Page Usage list records");
3594
0
        }
3595
0
        gs_free_object(pdev->pdf_memory->non_gc_memory, pdev->ResourceUsage, "Free linearisation resource usage records");
3596
0
    }
3597
3598
39.3k
error_cleanup:
3599
    /* Require special handling for Fonts, ColorSpace and Pattern resources
3600
     * These are tracked in pdev->last_resource, and are complex structures which may
3601
     * contain other memory allocations. All other resource types can be simply dicarded
3602
     * as above.
3603
     */
3604
3605
    /* Memory management of resources in pdfwrite is bizarre and complex. Originally there was no means
3606
     * to free any resources on completion, pdfwrite simply relied on the garbage collector to clean up
3607
     * and all the resource objects are GC-visible. However, this doesn't work well when the interpreter
3608
     * does not use GC, ie PCL or XPS, and even when GC is available, the time taken to clean up the
3609
     * (sometimes enormous numbers) of objects can be surprisingly significant. So code was added above
3610
     * to handle the simple cases using pdf_free_resource_object(), and below to handle the more complex
3611
     * situations.
3612
     * The way this works is that for each resource type we free the 'object', if the object is itself
3613
     * a 'cos' object (array, dictionary) then we free each of its members. However, if any of the objects
3614
     * have an ID which is not zero, then we don't free them (this is true only for contents, all the
3615
     * objects of a given type are freed regardless of whether their ID is 0). These are taken to be
3616
     * references to resource objects of a type which has not yet been freed, and will be freed when
3617
     * that resource type is freed. For the simple resources, which is most of them, this works well.
3618
     *
3619
     * However, there are complications; colour spaces and functions can contain cos objects
3620
     * whose members pointers to other objects of the same resource type (eg a type 3 stitching function
3621
     * can point to an array of type 0 functions). We can't afford to have these free the object, because
3622
     * the resource chain is still pointing at it, and will try to free it again. The same is also true if
3623
     * we should encounter the object which is referenced before we find the reference. So for these cases
3624
     * we first scan the members of each resource (if present) to see if they are references to another
3625
     * resource of the same type. If they are we simply 'corrupt' the reference by changing the object type.
3626
     * The resource has already been written, and the reference will free the memory, so this is safe to do.
3627
     *
3628
     * The final case is 'resourceOther' which can contain pretty much anything. In particular it can contain
3629
     * Colorant dictionaries for colour spaces, but technically it could contain cos objects pointing at any
3630
     * resource type. So far I have only found this to be possible with colorspace and function resources, but
3631
     * the routines 'discard_array_refs' and 'discard_dict_refs' actually check for *all* the resource types except
3632
     * resourceOther. We can't free the resourceOther types because they cvan contain resources that are being used
3633
     * by resources, eg the spot colour names for /Separation and DeviceN spaces.
3634
     *
3635
     * There is a 'gotcha' here; previously we used to free the 'resourceOther' resources *before* calling
3636
     * pdf_document_metadata(), now we call it after. The problem is that the metadata is stored as a resourceOther
3637
     * resource *and* referenced from the Catalog dictionary, which is a 'global named resource'. We free global
3638
     * named resoruces as the absolute last action. Previously because we had free resourceOther resources before
3639
     * creating the new reference to the Metadata, the fact that it was freed by the action of releasing the
3640
     * global named resources wasn't a problem, now it is. If we free the metadata as a 'resourceOther' then when
3641
     * we try to free it as a global named resource we will run into trouble again. So pdf_document_metadata() has been
3642
     * specifically altered to remove the reference to the metadata from the resourceOther resource chain immediately
3643
     * after it has been created. Ick.....
3644
     */
3645
39.3k
    {
3646
39.3k
        int j;
3647
3648
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3649
629k
            pdf_resource_t *pres = pdev->resources[resourceOther].chains[j];
3650
3651
720k
            for (; pres != 0;) {
3652
90.6k
                if (pres->object) {
3653
90.6k
                    if (cos_type(pres->object) == cos_type_array) {
3654
0
                        discard_array_refs(pdev, pres->object);
3655
0
                    }
3656
90.6k
                    if (cos_type(pres->object) == cos_type_dict) {
3657
24
                        cos_dict_forall((const cos_dict_t *)pres->object, pdev, discard_dict_refs);
3658
24
                    }
3659
90.6k
                }
3660
90.6k
                pres = pres->next;
3661
90.6k
            }
3662
629k
        }
3663
39.3k
    }
3664
3665
39.3k
    {
3666
        /* PDF font records and all their associated contents need to be
3667
         * freed by means other than the garbage collector, or the memory
3668
         * usage will increase with languages other than PostScript. In addition
3669
         * debug builds of non-PS languages take a long time to close down
3670
         * due to reporting the dangling memory allocations.
3671
         */
3672
39.3k
        int j;
3673
3674
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3675
629k
            pdf_resource_t *pres = pdev->resources[resourceFont].chains[j];
3676
3677
674k
            for (; pres != 0;) {
3678
45.2k
                pdf_font_resource_t *pdfont = (pdf_font_resource_t *)pres;
3679
3680
45.2k
                font_resource_free(pdev, pdfont);
3681
45.2k
                pres = pres->next;
3682
45.2k
            }
3683
629k
        }
3684
39.3k
    }
3685
3686
39.3k
    {
3687
39.3k
        int j;
3688
3689
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3690
629k
            pdf_resource_t *pres = pdev->resources[resourceCIDFont].chains[j];
3691
3692
631k
            for (; pres != 0;) {
3693
1.84k
                pdf_font_resource_t *pdfont = (pdf_font_resource_t *)pres;
3694
3695
1.84k
                font_resource_free(pdev, pdfont);
3696
1.84k
                pres = pres->next;
3697
1.84k
            }
3698
629k
        }
3699
39.3k
    }
3700
3701
39.3k
    {
3702
39.3k
        int j;
3703
3704
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3705
629k
            pdf_resource_t *pres = pdev->resources[resourceFontDescriptor].chains[j];
3706
666k
            for (; pres != 0;) {
3707
37.4k
                pdf_font_descriptor_free(pdev, pres);
3708
37.4k
                pres = pres->next;
3709
37.4k
            }
3710
629k
        }
3711
39.3k
    }
3712
3713
39.3k
    {
3714
39.3k
        int j;
3715
3716
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3717
629k
            pdf_resource_t *pres = pdev->resources[resourceCharProc].chains[j];
3718
3719
757k
            for (; pres != 0;) {
3720
127k
                if (pres->object) {
3721
127k
                    cos_free(pres->object, "free CharProc resource");
3722
127k
                    pres->object = 0;
3723
127k
                }
3724
127k
                pres = pres->next;
3725
127k
            }
3726
629k
        }
3727
39.3k
    }
3728
3729
39.3k
    {
3730
39.3k
        int j;
3731
3732
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3733
629k
            pdf_resource_t *pres = pdev->resources[resourceExtGState].chains[j];
3734
3735
656k
            for (; pres != 0;) {
3736
26.5k
                if (pres->object) {
3737
26.5k
                    cos_release(pres->object, "release ExtGState object");
3738
26.5k
                    gs_free_object(pdev->pdf_memory, pres->object, "free ExtGState");
3739
26.5k
                    pres->object = 0;
3740
26.5k
                }
3741
26.5k
                pres = pres->next;
3742
26.5k
            }
3743
629k
        }
3744
39.3k
    }
3745
3746
39.3k
    {
3747
39.3k
        int j;
3748
3749
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3750
629k
            pdf_resource_t *pres = pdev->resources[resourcePattern].chains[j];
3751
3752
645k
            for (; pres != 0;) {
3753
16.4k
                if (pres->object) {
3754
15.0k
                    cos_release(pres->object, "free pattern dict");
3755
15.0k
                    gs_free_object(pdev->pdf_memory, pres->object, "free pattern resources");
3756
15.0k
                    pres->object = 0;
3757
15.0k
                }
3758
16.4k
                pres = pres->next;
3759
16.4k
            }
3760
629k
        }
3761
39.3k
    }
3762
3763
39.3k
    {
3764
39.3k
        int j;
3765
3766
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3767
629k
            pdf_resource_t *pres = pdev->resources[resourceShading].chains[j];
3768
3769
631k
            for (; pres != 0;) {
3770
2.02k
                if (pres->object) {
3771
2.02k
                    cos_release(pres->object, "free Shading dict");
3772
2.02k
                    gs_free_object(pdev->pdf_memory, pres->object, "free Shading resources");
3773
2.02k
                    pres->object = 0;
3774
2.02k
                }
3775
2.02k
                pres = pres->next;
3776
2.02k
            }
3777
629k
        }
3778
39.3k
    }
3779
3780
39.3k
    {
3781
39.3k
        int j;
3782
3783
        /* prescan the colour space arrays to see if any of them reference other colour
3784
         * spaces. If they do, then remove the reference by changing it from a COS_VALUE_OBJECT
3785
         * into a COS_VALUE_CONST, see comment at the start of this section as to why this is safe.
3786
         */
3787
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3788
629k
            pdf_resource_t *pres = pdev->resources[resourceColorSpace].chains[j];
3789
636k
            for (; pres != 0;) {
3790
6.86k
                if (cos_type(pres->object) == cos_type_array) {
3791
6.23k
                    int64_t index;
3792
6.23k
                    cos_array_t *pca = (cos_array_t *)pres->object;
3793
6.23k
                    const cos_array_element_t *element = cos_array_element_first(pca);
3794
6.23k
                    cos_value_t *v;
3795
3796
23.1k
                    while (element) {
3797
16.9k
                        element = cos_array_element_next(element, &index, (const cos_value_t **)&v);
3798
16.9k
                        if (v->value_type == COS_VALUE_OBJECT) {
3799
5.56k
                            if (pdf_find_resource_by_resource_id(pdev, resourceColorSpace, v->contents.object->id)){
3800
288
                                v->value_type = COS_VALUE_CONST;
3801
288
                            }
3802
5.56k
                        }
3803
16.9k
                    }
3804
6.23k
                }
3805
6.86k
                pres = pres->next;
3806
6.86k
            }
3807
629k
        }
3808
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3809
629k
            pdf_resource_t *pres = pdev->resources[resourceColorSpace].chains[j];
3810
636k
            for (; pres != 0;) {
3811
6.86k
                free_color_space(pdev, pres);
3812
6.86k
                pres = pres->next;
3813
6.86k
            }
3814
629k
        }
3815
39.3k
    }
3816
3817
39.3k
    {
3818
39.3k
        int j;
3819
3820
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3821
629k
            pdf_resource_t *pres = pdev->resources[resourceGroup].chains[j];
3822
3823
629k
            for (; pres != 0;) {
3824
0
                if (pres->object) {
3825
0
                    cos_release(pres->object, "free Group dict");
3826
0
                    gs_free_object(pdev->pdf_memory, pres->object, "free Group resources");
3827
0
                    pres->object = 0;
3828
0
                }
3829
0
                pres = pres->next;
3830
0
            }
3831
629k
        }
3832
39.3k
    }
3833
3834
39.3k
    {
3835
39.3k
        int j;
3836
3837
        /* prescan the function arrays and dictionariesto see if any of them reference other
3838
         * functions. If they do, then remove the reference by changing it from a COS_VALUE_OBJECT
3839
         * into a COS_VALUE_CONST, see comment at the start of this section as to why this is safe.
3840
         */
3841
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3842
629k
            pdf_resource_t *pnext = 0, *pres = pdev->resources[resourceFunction].chains[j];
3843
3844
636k
            for (; pres != 0;) {
3845
6.65k
                if (pres->object) {
3846
6.65k
                    free_function_refs(pdev, pres->object);
3847
6.65k
                }
3848
6.65k
                pnext = pres->next;
3849
6.65k
                pres = pnext;
3850
6.65k
            }
3851
629k
        }
3852
668k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3853
629k
            pdf_resource_t *pnext = 0, *pres = pdev->resources[resourceFunction].chains[j];
3854
3855
636k
            for (; pres != 0;) {
3856
6.65k
                if (pres->object) {
3857
6.65k
                    cos_release(pres->object, "free function dict");
3858
6.65k
                    gs_free_object(pdev->pdf_memory, pres->object, "free function resources");
3859
6.65k
                    pres->object = 0;
3860
6.65k
                }
3861
6.65k
                pnext = pres->next;
3862
6.65k
                pres = pnext;
3863
6.65k
            }
3864
629k
        }
3865
39.3k
    }
3866
3867
    /* Free named objects. */
3868
3869
39.3k
    if (pdev->NI_stack != NULL) {
3870
39.3k
        cos_release((cos_object_t *)pdev->NI_stack, "Release Name Index stack");
3871
39.3k
        gs_free_object(mem, pdev->NI_stack, "Free Name Index stack");
3872
39.3k
        pdev->NI_stack = 0;
3873
39.3k
    }
3874
3875
39.3k
    if (pdev->local_named_objects != NULL) {
3876
39.3k
        cos_dict_objects_delete(pdev->local_named_objects);
3877
39.3k
        COS_FREE(pdev->local_named_objects, "pdf_close(local_named_objects)");
3878
39.3k
        pdev->local_named_objects = 0;
3879
39.3k
    }
3880
3881
39.3k
    if (pdev->global_named_objects != NULL) {
3882
        /* global resources include the Catalog object and apparently the Info dict */
3883
39.3k
        cos_dict_objects_delete(pdev->global_named_objects);
3884
39.3k
        COS_FREE(pdev->global_named_objects, "pdf_close(global_named_objects)");
3885
39.3k
        pdev->global_named_objects = 0;
3886
39.3k
    }
3887
3888
39.3k
    code1 = pdf_free_resource_objects(pdev, resourceOther);
3889
39.3k
    if (code >= 0)
3890
39.3k
        code = code1;
3891
3892
39.3k
    if (code >= 0) {
3893
39.3k
        int i, j;
3894
3895
668k
        for (i = 0; i < NUM_RESOURCE_TYPES; i++) {
3896
10.7M
            for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3897
10.0M
                pdev->resources[i].chains[j] = 0;
3898
10.0M
            }
3899
629k
        }
3900
39.3k
    }
3901
3902
    /* Release the resource records. */
3903
    /* So what exactly is stored in this list ? I believe the following types of resource:
3904
     *
3905
     * resourceCharProc
3906
     * resourceFont
3907
     * resourceCIDFont
3908
     * resourceFontDescriptor
3909
     * resourceColorSpace
3910
     * resourceExtGState
3911
     * resourceXObject
3912
     * resourceSoftMaskDict
3913
     * resourceGroup
3914
     * resourcePattern
3915
     * resourceShading
3916
     *
3917
     * resourceCMap resourcePage and resourceFunction don't appear to be tracked. I note
3918
     * that resourcePage and resourceCMap are freed above, as is resourceXObject and resourceSoftmaskDict.
3919
     * So presumably reourceFunction just leaks.
3920
     *
3921
     * It seems that all these types of resources are added when they are created
3922
     * in addition there are 'pdf_forget_resource' and pdf_cancel_resource which
3923
     * remove entries from this list.
3924
     */
3925
39.3k
    {
3926
39.3k
        pdf_resource_t *pres;
3927
39.3k
        pdf_resource_t *prev;
3928
3929
469k
        for (prev = pdev->last_resource; (pres = prev) != 0;) {
3930
430k
            prev = pres->prev;
3931
430k
            gs_free_object(mem, pres, "pdf_resource_t");
3932
430k
        }
3933
39.3k
        pdev->last_resource = 0;
3934
39.3k
    }
3935
3936
    /* Wrap up. */
3937
3938
39.3k
    pdev->font_cache = 0;
3939
3940
39.3k
    if (pdev->pages != NULL)
3941
39.3k
    {
3942
39.3k
        int i;
3943
90.6k
        for (i=0;i < pdev->next_page;i++) {
3944
51.2k
            cos_release((cos_object_t *)pdev->pages[i].Page, "Free page dict");
3945
51.2k
            if (pdev->pages[i].Annots) {
3946
0
                cos_release((cos_object_t *)pdev->pages[i].Annots, "Release Annots dict");
3947
0
                gs_free_object(mem, pdev->pages[i].Annots, "Free Annots dict");
3948
0
            }
3949
51.2k
            gs_free_object(mem, pdev->pages[i].Page, "Free Page object");
3950
51.2k
            pdev->pages[i].Page = NULL;
3951
51.2k
        }
3952
2.00M
        for (i=0;i < pdev->num_pages;i++) {
3953
1.96M
            if (pdev->pages[i].Page != NULL) {
3954
23
                emprintf(pdev->memory,
3955
23
                         "Page object was reserved for an Annotation destination, but no such page was drawn, annotation in output will be invalid.\n");
3956
23
                gs_free_object(mem, pdev->pages[i].Page, "Free Page object");
3957
23
                pdev->pages[i].Page = NULL;
3958
23
            }
3959
1.96M
        }
3960
39.3k
    }
3961
39.3k
    gs_free_object(mem, pdev->pages, "pages");
3962
39.3k
    pdev->pages = 0;
3963
3964
39.3k
    pdev->num_pages = 0;
3965
3966
39.3k
    gs_free_object(mem, pdev->sbstack, "Free sbstack");
3967
39.3k
    pdev->sbstack = 0;
3968
3969
39.3k
    if (pdev->text != NULL)
3970
39.3k
        text_data_free(mem, pdev->text);
3971
39.3k
    pdev->text = 0;
3972
3973
39.3k
    if (pdev->Pages != NULL) {
3974
39.3k
        cos_release((cos_object_t *)pdev->Pages, "release Pages dict");
3975
39.3k
        gs_free_object(mem, pdev->Pages, "Free Pages dict");
3976
39.3k
        pdev->Pages = 0;
3977
39.3k
    }
3978
3979
39.3k
    if (pdev->vgstack != NULL)
3980
39.3k
    {
3981
39.3k
        int i;
3982
472k
        for (i=0;i < pdev->vgstack_size;i++) {
3983
432k
            if (pdev->vgstack[i].dash_pattern != NULL)
3984
426
                gs_free_object(pdev->memory->non_gc_memory, pdev->vgstack[i].dash_pattern, "pdfwrite final free stored dash in gstate");
3985
432k
        }
3986
39.3k
        gs_free_object(pdev->pdf_memory, pdev->vgstack, "pdf_close(graphics state stack)");
3987
39.3k
        pdev->vgstack = 0;
3988
39.3k
    }
3989
3990
39.3k
    if (pdev->Namespace_stack != NULL) {
3991
39.3k
        cos_release((cos_object_t *)pdev->Namespace_stack, "release Name space stack");
3992
39.3k
        gs_free_object(mem, pdev->Namespace_stack, "Free Name space stack");
3993
39.3k
        pdev->Namespace_stack = 0;
3994
39.3k
    }
3995
3996
39.3k
    pdev->Catalog = 0;
3997
39.3k
    pdev->Info = 0;
3998
3999
39.3k
    gs_free_object(mem, pdev->outline_levels, "outline_levels array");
4000
39.3k
    pdev->outline_levels = 0;
4001
39.3k
    pdev->outline_depth = -1;
4002
39.3k
    pdev->max_outline_depth = 0;
4003
4004
39.3k
    if (s != NULL)
4005
39.3k
    {
4006
        /* pdf_open_dcument could set up filters for entire document.
4007
           Removing them now. */
4008
39.3k
        int status;
4009
4010
39.3k
        if (!pdev->ProduceDSC)
4011
0
            stream_putc(s, 0x04);
4012
78.7k
        while (s->strm) {
4013
39.3k
            s = s->strm;
4014
39.3k
        }
4015
39.3k
        status = s_close_filters(&pdev->strm, s);
4016
39.3k
        if (status < 0 && code == 0)
4017
0
            code = gs_error_ioerror;
4018
39.3k
    }
4019
4020
39.3k
    pdf_free_pdf_font_cache(pdev);
4021
4022
39.3k
    code1 = gdev_vector_close_file((gx_device_vector *) pdev);
4023
39.3k
    if (code >= 0)
4024
39.3k
        code = code1;
4025
39.3k
    if (pdev->max_referred_page >= pdev->next_page + 1 && pdev->next_page != 0 && !file_per_page) {
4026
        /* Note : pdev->max_referred_page counts from 1,
4027
           and pdev->next_page counts from 0. */
4028
1
        emprintf2(pdev->memory, "ERROR: A pdfmark destination page %d "
4029
1
                  "points beyond the last page %d.\n",
4030
1
                  pdev->max_referred_page, pdev->next_page);
4031
1
    }
4032
39.3k
    code = pdf_close_files(pdev, code);
4033
39.3k
    if (code < 0)
4034
0
        return code;
4035
4036
    /* If we didn't get called from pdf_output_page, and we are doign file-per-page
4037
     * output, then the call from close_device will leave an empty file which we don't
4038
     * want. So here we delete the file.
4039
     * NOTE: We needed to let it process the whole page in order to make sure everything
4040
     * got properly freed.
4041
     */
4042
39.3k
    if (file_per_page) {
4043
0
        code = gx_device_delete_output_file((const gx_device *)pdev, pdev->fname);
4044
0
        if (code != 0)
4045
0
            code = gs_note_error(gs_error_ioerror);
4046
0
    }
4047
4048
39.3k
    return code;
4049
39.3k
}