Coverage Report

Created: 2025-08-28 07:06

/src/ghostpdl/devices/vector/gdevpdf.c
Line
Count
Source (jump to first uncovered line)
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
146k
#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
147M
ENUM_PTRS_WITH(device_pdfwrite_enum_ptrs, gx_device_pdf *pdev)
69
125M
{
70
125M
    index -= gx_device_pdf_num_ptrs + gx_device_pdf_num_param_strings;
71
125M
    if (index < NUM_RESOURCE_TYPES * NUM_RESOURCE_CHAINS)
72
115M
        ENUM_RETURN(pdev->resources[index / NUM_RESOURCE_CHAINS].chains[index % NUM_RESOURCE_CHAINS]);
73
10.1M
    index -= NUM_RESOURCE_TYPES * NUM_RESOURCE_CHAINS;
74
10.1M
    if (index <= pdev->outline_depth && pdev->outline_levels)
75
104k
        ENUM_RETURN(pdev->outline_levels[index].first.action);
76
10.0M
    index -= pdev->outline_depth + 1;
77
10.0M
    if (index <= pdev->outline_depth && pdev->outline_levels)
78
104k
        ENUM_RETURN(pdev->outline_levels[index].last.action);
79
9.92M
    index -= pdev->outline_depth + 1;
80
81
9.92M
    if (index < pdev->PatternDepth) {
82
2
       ENUM_RETURN(pdev->initial_pattern_states[index]);
83
2
    }
84
9.92M
    index -= pdev->PatternDepth;
85
9.92M
    ENUM_PREFIX(st_device_psdf, 0);
86
87
9.92M
}
88
9.92M
 ENUM_PTR(0, gx_device_pdf, asides.strm);
89
9.92M
 ENUM_PTR(1, gx_device_pdf, asides.strm_buf);
90
9.92M
 ENUM_PTR(2, gx_device_pdf, asides.save_strm);
91
9.92M
 ENUM_PTR(3, gx_device_pdf, streams.strm);
92
9.92M
 ENUM_PTR(4, gx_device_pdf, streams.strm_buf);
93
9.92M
 ENUM_PTR(5, gx_device_pdf, ObjStm.strm);
94
9.92M
 ENUM_PTR(6, gx_device_pdf, ObjStm.strm_buf);
95
9.92M
 ENUM_PTR(7, gx_device_pdf, ObjStm.save_strm);
96
9.92M
 ENUM_PTR(8, gx_device_pdf, Catalog);
97
9.92M
 ENUM_PTR(9, gx_device_pdf, Info);
98
9.92M
 ENUM_PTR(10, gx_device_pdf, Pages);
99
9.92M
 ENUM_PTR(11, gx_device_pdf, text);
100
9.92M
 ENUM_PTR(12, gx_device_pdf, pages);
101
9.92M
 ENUM_PTR(13, gx_device_pdf, cs_Patterns[0]);
102
9.92M
 ENUM_PTR(14, gx_device_pdf, cs_Patterns[1]);
103
9.92M
 ENUM_PTR(15, gx_device_pdf, cs_Patterns[3]);
104
9.92M
 ENUM_PTR(16, gx_device_pdf, cs_Patterns[4]);
105
9.92M
 ENUM_PTR(17, gx_device_pdf, last_resource);
106
9.92M
 ENUM_PTR(18, gx_device_pdf, articles);
107
9.92M
 ENUM_PTR(19, gx_device_pdf, Dests);
108
9.92M
 ENUM_PTR(20, gx_device_pdf, global_named_objects);
109
9.92M
 ENUM_PTR(21, gx_device_pdf, local_named_objects);
110
9.92M
 ENUM_PTR(22, gx_device_pdf, NI_stack);
111
9.92M
 ENUM_PTR(23, gx_device_pdf, Namespace_stack);
112
9.92M
 ENUM_PTR(24, gx_device_pdf, font_cache);
113
9.92M
 ENUM_PTR(25, gx_device_pdf, clip_path);
114
9.92M
 ENUM_PTR(26, gx_device_pdf, PageLabels);
115
9.92M
 ENUM_PTR(27, gx_device_pdf, PageLabels_current_label);
116
9.92M
 ENUM_PTR(28, gx_device_pdf, sbstack);
117
9.92M
 ENUM_PTR(29, gx_device_pdf, substream_Resources);
118
9.92M
 ENUM_PTR(30, gx_device_pdf, font3);
119
9.92M
 ENUM_PTR(31, gx_device_pdf, accumulating_substream_resource);
120
9.92M
 ENUM_PTR(32, gx_device_pdf, pres_soft_mask_dict);
121
9.92M
 ENUM_PTR(33, gx_device_pdf, PDFXTrimBoxToMediaBoxOffset.data);
122
9.92M
 ENUM_PTR(34, gx_device_pdf, PDFXBleedBoxToTrimBoxOffset.data);
123
9.92M
 ENUM_PTR(35, gx_device_pdf, Identity_ToUnicode_CMaps[0]);
124
9.92M
 ENUM_PTR(36, gx_device_pdf, Identity_ToUnicode_CMaps[1]);
125
9.92M
 ENUM_PTR(37, gx_device_pdf, vgstack);
126
9.92M
 ENUM_PTR(38, gx_device_pdf, outline_levels);
127
9.92M
 ENUM_PTR(39, gx_device_pdf, EmbeddedFiles);
128
9.92M
 ENUM_PTR(40, gx_device_pdf, AF);
129
9.92M
 ENUM_PTR(41, gx_device_pdf, pdf_font_dir);
130
9.92M
 ENUM_PTR(42, gx_device_pdf, ExtensionMetadata);
131
9.92M
 ENUM_PTR(43, gx_device_pdf, PassThroughWriter);
132
2.25M
#define e1(i,elt) ENUM_PARAM_STRING_PTR(i + gx_device_pdf_num_ptrs, gx_device_pdf, elt);
133
9.92M
gx_device_pdf_do_param_strings(e1)
134
0
#undef e1
135
451k
#define e1(i,elt) ENUM_STRING_PTR(i + gx_device_pdf_num_ptrs + gx_device_pdf_num_param_strings,\
136
451k
                                 gx_device_pdf, elt);
137
147M
gx_device_pdf_do_const_strings(e1)
138
147M
#undef e1
139
147M
ENUM_PTRS_END
140
451k
static RELOC_PTRS_WITH(device_pdfwrite_reloc_ptrs, gx_device_pdf *pdev)
141
451k
{
142
451k
    RELOC_PREFIX(st_device_psdf);
143
451k
 RELOC_PTR(gx_device_pdf, asides.strm);
144
451k
 RELOC_PTR(gx_device_pdf, asides.strm_buf);
145
451k
 RELOC_PTR(gx_device_pdf, asides.save_strm);
146
451k
 RELOC_PTR(gx_device_pdf, streams.strm);
147
451k
 RELOC_PTR(gx_device_pdf, streams.strm_buf);
148
451k
 RELOC_PTR(gx_device_pdf, ObjStm.strm);
149
451k
 RELOC_PTR(gx_device_pdf, ObjStm.strm_buf);
150
451k
 RELOC_PTR(gx_device_pdf, ObjStm.save_strm);
151
451k
 RELOC_PTR(gx_device_pdf, Catalog);
152
451k
 RELOC_PTR(gx_device_pdf, Info);
153
451k
 RELOC_PTR(gx_device_pdf, Pages);
154
451k
 RELOC_PTR(gx_device_pdf, text);
155
451k
 RELOC_PTR(gx_device_pdf, pages);
156
451k
 RELOC_PTR(gx_device_pdf, cs_Patterns[0]);
157
451k
 RELOC_PTR(gx_device_pdf, cs_Patterns[1]);
158
451k
 RELOC_PTR(gx_device_pdf, cs_Patterns[3]);
159
451k
 RELOC_PTR(gx_device_pdf, cs_Patterns[4]);
160
451k
 RELOC_PTR(gx_device_pdf, last_resource);
161
451k
 RELOC_PTR(gx_device_pdf, articles);
162
451k
 RELOC_PTR(gx_device_pdf, Dests);
163
451k
 RELOC_PTR(gx_device_pdf, global_named_objects);
164
451k
 RELOC_PTR(gx_device_pdf, local_named_objects);
165
451k
 RELOC_PTR(gx_device_pdf, NI_stack);
166
451k
 RELOC_PTR(gx_device_pdf, Namespace_stack);
167
451k
 RELOC_PTR(gx_device_pdf, font_cache);
168
451k
 RELOC_PTR(gx_device_pdf, clip_path);
169
451k
 RELOC_PTR(gx_device_pdf, PageLabels);
170
451k
 RELOC_PTR(gx_device_pdf, PageLabels_current_label);
171
451k
 RELOC_PTR(gx_device_pdf, sbstack);
172
451k
 RELOC_PTR(gx_device_pdf, substream_Resources);
173
451k
 RELOC_PTR(gx_device_pdf, font3);
174
451k
 RELOC_PTR(gx_device_pdf, accumulating_substream_resource);
175
451k
 RELOC_PTR(gx_device_pdf, pres_soft_mask_dict);
176
451k
 RELOC_PTR(gx_device_pdf, PDFXTrimBoxToMediaBoxOffset.data);
177
451k
 RELOC_PTR(gx_device_pdf, PDFXBleedBoxToTrimBoxOffset.data);
178
451k
 RELOC_PTR(gx_device_pdf, Identity_ToUnicode_CMaps[0]);
179
451k
 RELOC_PTR(gx_device_pdf, Identity_ToUnicode_CMaps[1]);
180
451k
 RELOC_PTR(gx_device_pdf, vgstack);
181
451k
 RELOC_PTR(gx_device_pdf, EmbeddedFiles);
182
451k
 RELOC_PTR(gx_device_pdf, AF);
183
451k
 RELOC_PTR(gx_device_pdf, pdf_font_dir);
184
451k
 RELOC_PTR(gx_device_pdf, ExtensionMetadata);
185
451k
 RELOC_PTR(gx_device_pdf, PassThroughWriter);
186
2.25M
#define r1(i,elt) RELOC_PARAM_STRING_PTR(gx_device_pdf,elt);
187
2.25M
        gx_device_pdf_do_param_strings(r1)
188
451k
#undef r1
189
451k
#define r1(i,elt) RELOC_CONST_STRING_PTR(gx_device_pdf,elt);
190
451k
        gx_device_pdf_do_const_strings(r1)
191
451k
#undef r1
192
451k
    {
193
451k
        int i, j;
194
195
7.66M
        for (i = 0; i < NUM_RESOURCE_TYPES; ++i)
196
122M
            for (j = 0; j < NUM_RESOURCE_CHAINS; ++j)
197
115M
                RELOC_PTR(gx_device_pdf, resources[i].chains[j]);
198
451k
        if (pdev->outline_levels) {
199
208k
            for (i = 0; i <= pdev->outline_depth; ++i) {
200
104k
                RELOC_PTR(gx_device_pdf, outline_levels[i].first.action);
201
104k
                RELOC_PTR(gx_device_pdf, outline_levels[i].last.action);
202
104k
            }
203
104k
        }
204
451k
        for (i = 0; i < pdev->PatternDepth; i++) {
205
2
            RELOC_PTR(gx_device_pdf, initial_pattern_states[i]);
206
2
        }
207
451k
    }
208
451k
 RELOC_PTR(gx_device_pdf, outline_levels);
209
451k
}
210
451k
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
216k
{
217
216k
    gx_device_finalize(cmem, vpdev);
218
216k
}
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
216k
{
239
216k
    set_dev_proc(dev, initialize_device, pdfwrite_initialize_device);
240
216k
    set_dev_proc(dev, open_device, pdf_open);
241
216k
    set_dev_proc(dev, get_initial_matrix, gx_upright_get_initial_matrix);
242
216k
    set_dev_proc(dev, output_page, pdf_output_page);
243
216k
    set_dev_proc(dev, close_device, pdf_close);
244
216k
    set_dev_proc(dev, map_rgb_color, gx_default_rgb_map_rgb_color);
245
216k
    set_dev_proc(dev, map_color_rgb, gx_default_rgb_map_color_rgb);
246
216k
    set_dev_proc(dev, fill_rectangle, gdev_pdf_fill_rectangle);
247
216k
    set_dev_proc(dev, copy_mono, gdev_pdf_copy_mono);
248
216k
    set_dev_proc(dev, copy_color, gdev_pdf_copy_color);
249
216k
    set_dev_proc(dev, get_params, gdev_pdf_get_params);
250
216k
    set_dev_proc(dev, put_params, gdev_pdf_put_params);
251
216k
    set_dev_proc(dev, get_page_device, gx_page_device_get_page_device);
252
216k
    set_dev_proc(dev, fill_path, gdev_pdf_fill_path);
253
216k
    set_dev_proc(dev, stroke_path, gdev_pdf_stroke_path);
254
216k
    set_dev_proc(dev, fill_mask, gdev_pdf_fill_mask);
255
216k
    set_dev_proc(dev, strip_tile_rectangle, gdev_pdf_strip_tile_rectangle);
256
216k
    set_dev_proc(dev, begin_typed_image, gdev_pdf_begin_typed_image);
257
216k
    set_dev_proc(dev, get_bits_rectangle, psdf_get_bits_rectangle);
258
216k
    set_dev_proc(dev, composite, gdev_pdf_composite);
259
216k
    set_dev_proc(dev, text_begin, gdev_pdf_text_begin);
260
216k
    set_dev_proc(dev, begin_transparency_group, gdev_pdf_begin_transparency_group);
261
216k
    set_dev_proc(dev, end_transparency_group, gdev_pdf_end_transparency_group);
262
216k
    set_dev_proc(dev, begin_transparency_mask ,gdev_pdf_begin_transparency_mask);
263
216k
    set_dev_proc(dev, end_transparency_mask, gdev_pdf_end_transparency_mask);
264
216k
    set_dev_proc(dev, fill_rectangle_hl_color, gdev_pdf_fill_rectangle_hl_color);
265
216k
    set_dev_proc(dev, include_color_space, gdev_pdf_include_color_space);
266
216k
    set_dev_proc(dev, fillpage, gdev_pdf_fillpage);
267
216k
    set_dev_proc(dev, dev_spec_op, gdev_pdf_dev_spec_op);
268
216k
    set_dev_proc(dev, fill_stroke_path, gdev_pdf_fill_stroke_path);
269
216k
}
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
246k
{
317
246k
    int err = 0;
318
246k
    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
246k
    if (ptf->strm) {
326
146k
        if (s_is_valid(ptf->strm)) {
327
146k
            sflush(ptf->strm);
328
            /* Prevent freeing the stream from closing the file. */
329
146k
            ptf->strm->file = 0;
330
146k
        } else
331
0
            ptf->file = file = 0; /* file was closed by finalization */
332
146k
        gs_free_object(pdev->pdf_memory, ptf->strm_buf,
333
146k
                       "pdf_close_temp_file(strm_buf)");
334
146k
        ptf->strm_buf = 0;
335
146k
        gs_free_object(pdev->pdf_memory, ptf->strm,
336
146k
                       "pdf_close_temp_file(strm)");
337
146k
        ptf->strm = 0;
338
146k
    }
339
246k
    if (file) {
340
196k
        err = gp_ferror(file) | gp_fclose(file);
341
196k
        gp_unlink(pdev->memory, ptf->file_name);
342
196k
        ptf->file = 0;
343
196k
    }
344
246k
    ptf->save_strm = 0;
345
246k
    return
346
246k
        (code < 0 ? code : err != 0 ? gs_note_error(gs_error_ioerror) : code);
347
246k
}
348
static int
349
pdf_close_files(gx_device_pdf * pdev, int code)
350
50.0k
{
351
50.0k
    code = pdf_close_temp_file(pdev, &pdev->ObjStm, code);
352
50.0k
    code = pdf_close_temp_file(pdev, &pdev->streams, code);
353
50.0k
    code = pdf_close_temp_file(pdev, &pdev->asides, code);
354
50.0k
    return pdf_close_temp_file(pdev, &pdev->xref, code);
355
50.0k
}
356
357
/* Reset the state of the current page. */
358
static void
359
pdf_reset_page(gx_device_pdf * pdev)
360
116k
{
361
116k
    pdev->page_dsc_info = gs_pdfwrite_device.page_dsc_info;
362
116k
    pdev->contents_id = 0;
363
116k
    pdf_reset_graphics(pdev);
364
116k
    pdev->procsets = NoMarks;
365
116k
    memset(pdev->cs_Patterns, 0, sizeof(pdev->cs_Patterns));  /* simplest to create for each page */
366
116k
    pdf_reset_text_page(pdev->text);
367
116k
    pdf_remember_clip_path(pdev, 0);
368
116k
    pdev->clip_path_id = pdev->no_clip_path_id;
369
116k
}
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
196k
{
375
196k
    char fmode[4];
376
377
196k
    if (strlen(gp_fmode_binary_suffix) > 2)
378
0
        return_error(gs_error_invalidfileaccess);
379
380
196k
    strcpy(fmode, "w+");
381
196k
    strcat(fmode, gp_fmode_binary_suffix);
382
196k
    ptf->file = gp_open_scratch_file(pdev->memory,
383
196k
                                     gp_scratch_file_name_prefix,
384
196k
                                     ptf->file_name,
385
196k
                                     fmode);
386
196k
    if (ptf->file == 0)
387
0
        return_error(gs_error_invalidfileaccess);
388
196k
    return 0;
389
196k
}
390
int
391
pdf_open_temp_stream(gx_device_pdf *pdev, pdf_temp_file_t *ptf)
392
146k
{
393
146k
    int code = pdf_open_temp_file(pdev, ptf);
394
395
146k
    if (code < 0)
396
0
        return code;
397
146k
    ptf->strm = s_alloc(pdev->pdf_memory, "pdf_open_temp_stream(strm)");
398
146k
    if (ptf->strm == 0)
399
0
        return_error(gs_error_VMerror);
400
146k
    ptf->strm_buf = gs_alloc_bytes(pdev->pdf_memory, sbuf_size,
401
146k
                                   "pdf_open_temp_stream(strm_buf)");
402
146k
    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
146k
    swrite_file(ptf->strm, ptf->file, ptf->strm_buf, sbuf_size);
409
146k
    return 0;
410
146k
}
411
412
/* Initialize the IDs allocated at startup. */
413
void
414
pdf_initialize_ids(gx_device_pdf * pdev)
415
50.0k
{
416
50.0k
    gs_param_string nstr;
417
418
50.0k
    pdev->next_id = pdev->FirstObjectNumber;
419
420
    /* Initialize the Catalog. */
421
422
50.0k
    param_string_from_string(nstr, "{Catalog}");
423
50.0k
    pdf_create_named_dict(pdev, &nstr, &pdev->Catalog, 0L);
424
425
    /* Initialize the Info dictionary. */
426
427
50.0k
    param_string_from_string(nstr, "{DocInfo}");
428
50.0k
    pdf_create_named_dict(pdev, &nstr, &pdev->Info, 0L);
429
50.0k
    {
430
50.0k
        char buf[PDF_MAX_PRODUCER];
431
432
50.0k
        pdf_store_default_Producer(buf);
433
50.0k
        if (pdev->CompatibilityLevel <= 1.7)
434
50.0k
            cos_dict_put_c_key_string(pdev->Info, "/Producer", (byte *)buf,
435
50.0k
                                  strlen(buf));
436
50.0k
    }
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
50.0k
    if (!pdev->OmitInfoDate)
443
50.0k
    {
444
50.0k
        struct tm tms;
445
50.0k
        time_t t;
446
50.0k
        char buf[1+2+4+2+2+2+2+2+1+2+1+2+1+1+1]; /* (D:yyyymmddhhmmssZhh'mm')\0 */
447
50.0k
        int timeoffset;
448
50.0k
        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
50.0k
        time(&t);
457
50.0k
        tms = *gmtime(&t);
458
50.0k
        tms.tm_isdst = -1;
459
50.0k
        timeoffset = (int)difftime(t, mktime(&tms)); /* tz+dst in seconds */
460
50.0k
        timesign = (timeoffset == 0 ? 'Z' : timeoffset < 0 ? '-' : '+');
461
50.0k
        timeoffset = any_abs(timeoffset) / 60;
462
50.0k
        tms = *localtime(&t);
463
50.0k
#endif
464
465
50.0k
        gs_snprintf(buf, sizeof(buf), "(D:%04d%02d%02d%02d%02d%02d%c%02d\'%02d\')",
466
50.0k
            tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
467
50.0k
            tms.tm_hour, tms.tm_min, tms.tm_sec,
468
50.0k
            timesign, timeoffset / 60, timeoffset % 60);
469
470
50.0k
        cos_dict_put_c_key_string(pdev->Info, "/CreationDate", (byte *)buf,
471
50.0k
                                  strlen(buf));
472
50.0k
        cos_dict_put_c_key_string(pdev->Info, "/ModDate", (byte *)buf,
473
50.0k
                                  strlen(buf));
474
50.0k
    }
475
476
    /* Allocate the root of the pages tree. */
477
478
50.0k
    pdf_create_named_dict(pdev, NULL, &pdev->Pages, 0L);
479
50.0k
}
480
481
static int
482
pdf_compute_fileID(gx_device_pdf * pdev)
483
50.0k
{
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
50.0k
    gs_memory_t *mem = pdev->pdf_memory;
491
50.0k
    stream *strm = pdev->strm;
492
50.0k
    uint ignore;
493
50.0k
    int code;
494
50.0k
    stream *s = s_MD5E_make_stream(mem, pdev->fileID, sizeof(pdev->fileID));
495
50.0k
    long secs_ns[2];
496
50.0k
    uint KeyLength = pdev->KeyLength;
497
498
50.0k
    if (s == NULL)
499
0
        return_error(gs_error_VMerror);
500
50.0k
    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
50.0k
    gp_get_realtime(secs_ns);
506
50.0k
#endif
507
50.0k
    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
50.0k
    sputs(s, (const byte *)pdev->fname, strlen(pdev->fname), &ignore);
515
50.0k
#endif
516
50.0k
    pdev->strm = s;
517
50.0k
    code = cos_dict_elements_write(pdev->Info, pdev);
518
50.0k
    pdev->strm = strm;
519
50.0k
    pdev->KeyLength = KeyLength;
520
50.0k
    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
50.0k
    sclose(s);
529
50.0k
    gs_free_object(mem, s, "pdf_compute_fileID");
530
50.0k
    return 0;
531
50.0k
}
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
32.1k
{
702
32.1k
    const static gx_device_color_info pcm_color_info[] = {
703
32.1k
        dci_values(1, 8, 255, 0, 256, 0),   /* Gray */
704
32.1k
        dci_values(3, 24, 255, 255, 256, 256),    /* RGB */
705
32.1k
        dci_values(4, 32, 255, 255, 256, 256),    /* CMYK */
706
32.1k
        dci_values(4, 32, 255, 255, 256, 256) /* Treat DeviceN like CMYK */
707
32.1k
    };
708
    /* Don't blow away the ICC information */
709
710
32.1k
    pdev->pcm_color_info_index = index;
711
32.1k
    pdev->color_info = pcm_color_info[index];
712
    /* Set the separable and linear shift, masks, bits. */
713
32.1k
    set_linear_color_bits_mask_shift((gx_device *)pdev);
714
32.1k
    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
32.1k
    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
32.1k
        case 1:   /* DeviceRGB */
737
32.1k
            set_dev_proc(pdev, map_rgb_color, gx_default_rgb_map_rgb_color);
738
32.1k
            set_dev_proc(pdev, map_color_rgb, gx_default_rgb_map_color_rgb);
739
32.1k
            set_dev_proc(pdev, map_cmyk_color, NULL);
740
32.1k
            set_dev_proc(pdev, get_color_mapping_procs,
741
32.1k
                        gx_default_DevRGB_get_color_mapping_procs);
742
32.1k
            set_dev_proc(pdev, get_color_comp_index,
743
32.1k
                        gx_default_DevRGB_get_color_comp_index);
744
32.1k
            set_dev_proc(pdev, encode_color, gx_default_rgb_map_rgb_color);
745
32.1k
            set_dev_proc(pdev, decode_color, gx_default_rgb_map_color_rgb);
746
32.1k
            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
32.1k
    }
764
32.1k
}
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
728k
{
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
728k
    sync_text_state(pdev);
782
728k
    pdf_reset_text_state(pdev->text);
783
728k
}
784
785
static int
786
pdfwrite_initialize_device(gx_device *dev)
787
216k
{
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
216k
    return 0;
795
216k
}
796
797
798
/* Open the device. */
799
static int
800
pdf_open(gx_device * dev)
801
50.0k
{
802
50.0k
    gx_device_pdf *pdev = (gx_device_pdf *) dev;
803
50.0k
    gs_memory_t *mem = pdev->pdf_memory = gs_memory_stable(pdev->memory);
804
50.0k
    int code;
805
806
50.0k
    pdev->InOutputPage = false;
807
808
50.0k
    if ((code = pdf_open_temp_file(pdev, &pdev->xref)) < 0 ||
809
50.0k
        (code = pdf_open_temp_stream(pdev, &pdev->asides)) < 0 ||
810
50.0k
        (code = pdf_open_temp_stream(pdev, &pdev->streams))
811
50.0k
        )
812
0
        goto fail;
813
50.0k
    code = gdev_vector_open_file((gx_device_vector *) pdev, sbuf_size);
814
50.0k
    if (code < 0)
815
0
        goto fail;
816
50.0k
    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
50.0k
    if (pdev->ComputeDocumentDigest) {
824
50.0k
        stream *s = s_MD5C_make_stream(pdev->pdf_memory, pdev->strm);
825
826
50.0k
        if (s == NULL)
827
0
            return_error(gs_error_VMerror);
828
50.0k
        pdev->strm = s;
829
50.0k
    }
830
50.0k
    gdev_vector_init((gx_device_vector *) pdev);
831
#ifdef CLUSTER
832
    memset(&pdev->uuid_time, 0, sizeof(pdev->uuid_time));
833
#else
834
50.0k
    gp_get_realtime(pdev->uuid_time);
835
50.0k
#endif
836
50.0k
    pdev->vec_procs = &pdf_vector_procs;
837
50.0k
    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
50.0k
    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
50.0k
    pdev->local_named_objects =
846
50.0k
        pdev->global_named_objects =
847
50.0k
        cos_dict_alloc(pdev, "pdf_open(global_named_objects)");
848
50.0k
    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
50.0k
    pdev->NI_stack = cos_array_alloc(pdev, "pdf_open(NI stack)");
854
50.0k
    if (pdev->NI_stack == NULL) {
855
0
        code = gs_error_VMerror;
856
0
        goto fail;
857
0
    }
858
50.0k
    pdev->vgstack = (pdf_viewer_state *)gs_alloc_bytes(pdev->pdf_memory, 11 * sizeof(pdf_viewer_state), "pdf_open(graphics state stack)");
859
50.0k
    if (pdev->vgstack == 0) {
860
0
        code = gs_error_VMerror;
861
0
        goto fail;
862
0
    }
863
50.0k
    memset(pdev->vgstack, 0x00, 11 * sizeof(pdf_viewer_state));
864
50.0k
    pdev->vgstack_size = 11;
865
50.0k
    pdev->Namespace_stack = cos_array_alloc(pdev, "pdf_open(Namespace stack)");
866
50.0k
    if (pdev->Namespace_stack == NULL) {
867
0
        code = gs_error_VMerror;
868
0
        goto fail;
869
0
    }
870
50.0k
    pdf_initialize_ids(pdev);
871
50.0k
    code = pdf_compute_fileID(pdev);
872
50.0k
    if (code < 0)
873
0
        goto fail;
874
50.0k
    if (pdev->OwnerPassword.size > 0) {
875
0
        code = pdf_compute_encryption_data(pdev);
876
0
        if (code < 0)
877
0
            goto fail;
878
50.0k
    } 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
50.0k
    } 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
50.0k
    pdev->local_named_objects =
889
50.0k
        cos_dict_alloc(pdev, "pdf_open(local_named_objects)");
890
50.0k
    if (pdev->local_named_objects == NULL) {
891
0
        code = gs_error_VMerror;
892
0
        goto fail;
893
0
    }
894
50.0k
    pdev->outlines_id = 0;
895
50.0k
    pdev->next_page = 0;
896
50.0k
    pdev->text = pdf_text_data_alloc(mem);
897
50.0k
    pdev->sbstack_size = pdev->vgstack_size; /* Overestimated a few. */
898
50.0k
    pdev->sbstack = gs_alloc_struct_array(mem, pdev->sbstack_size, pdf_substream_save,
899
50.0k
                                 &st_pdf_substream_save_element, "pdf_open");
900
50.0k
    pdev->pages =
901
50.0k
        gs_alloc_struct_array(mem, initial_num_pages, pdf_page_t,
902
50.0k
                              &st_pdf_page_element, "pdf_open(pages)");
903
50.0k
    if (pdev->text == 0 || pdev->pages == 0 || pdev->sbstack == 0) {
904
0
        code = gs_error_VMerror;
905
0
        goto fail;
906
0
    }
907
50.0k
    memset(pdev->sbstack, 0, pdev->sbstack_size * sizeof(pdf_substream_save));
908
50.0k
    memset(pdev->pages, 0, initial_num_pages * sizeof(pdf_page_t));
909
50.0k
    pdev->num_pages = initial_num_pages;
910
50.0k
    {
911
50.0k
        int i, j;
912
913
851k
        for (i = 0; i < NUM_RESOURCE_TYPES; ++i)
914
13.6M
            for (j = 0; j < NUM_RESOURCE_CHAINS; ++j)
915
12.8M
                pdev->resources[i].chains[j] = 0;
916
50.0k
    }
917
50.0k
    pdev->outline_levels = (pdf_outline_level_t *)gs_alloc_bytes(mem, INITIAL_MAX_OUTLINE_DEPTH * sizeof(pdf_outline_level_t), "outline_levels array");
918
50.0k
    if (pdev->outline_levels == NULL) {
919
0
        code = gs_error_VMerror;
920
0
        goto fail;
921
0
    }
922
923
50.0k
    memset(pdev->outline_levels, 0x00, INITIAL_MAX_OUTLINE_DEPTH * sizeof(pdf_outline_level_t));
924
50.0k
    pdev->max_outline_depth = INITIAL_MAX_OUTLINE_DEPTH;
925
50.0k
    pdev->outline_levels[0].first.id = 0;
926
50.0k
    pdev->outline_levels[0].left = max_int;
927
50.0k
    pdev->outline_levels[0].first.action = 0;
928
50.0k
    pdev->outline_levels[0].last.action = 0;
929
50.0k
    pdev->outline_depth = 0;
930
50.0k
    pdev->closed_outline_depth = 0;
931
50.0k
    pdev->outlines_open = 0;
932
50.0k
    pdev->articles = 0;
933
50.0k
    pdev->Dests = 0;
934
50.0k
    pdev->EmbeddedFiles = 0;
935
50.0k
    pdev->AF = 0;
936
    /* {global,local}_named_objects was initialized above */
937
50.0k
    pdev->PageLabels = 0;
938
50.0k
    pdev->PageLabels_current_page = 0;
939
50.0k
    pdev->PageLabels_current_label = 0;
940
50.0k
    pdev->pte = NULL;
941
50.0k
    pdf_reset_page(pdev);
942
50.0k
    pdev->BBox.p.x = pdev->width;
943
50.0k
    pdev->BBox.p.y = pdev->height;
944
50.0k
    pdev->BBox.q.x = 0;
945
50.0k
    pdev->BBox.q.y = 0;
946
947
50.0k
    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
50.0k
    pdev->pdf_font_dir = gs_font_dir_alloc2(pdev->memory->stable_memory, pdev->memory->non_gc_memory);
953
50.0k
    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
50.0k
    if (pdev->memory->gs_lib_ctx->font_dir) {
963
50.0k
        pdev->pdf_font_dir->ccache.mark_glyph = pdev->memory->gs_lib_ctx->font_dir->ccache.mark_glyph;
964
50.0k
        pdev->pdf_font_dir->global_glyph_code = pdev->memory->gs_lib_ctx->font_dir->global_glyph_code;
965
50.0k
    }
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
50.0k
    if (pdev->parent)
972
0
        pdev->is_open = true;
973
974
50.0k
    return 0;
975
0
  fail:
976
0
    gdev_vector_close_file((gx_device_vector *) pdev);
977
0
    return pdf_close_files(pdev, code);
978
50.0k
}
979
980
/* Detect I/O errors. */
981
static int
982
pdf_ferror(gx_device_pdf *pdev)
983
171k
{
984
171k
    int code = 0;
985
986
171k
    if (pdev->file != NULL) {
987
171k
        gp_fflush(pdev->file);
988
171k
        code = gp_ferror(pdev->file);
989
171k
    }
990
171k
    gp_fflush(pdev->xref.file);
991
171k
    if (pdev->strm->file != NULL)
992
0
        sflush(pdev->strm);
993
171k
    if (pdev->asides.strm->file != NULL)
994
171k
        sflush(pdev->asides.strm);
995
171k
    if (pdev->streams.strm->file != NULL)
996
171k
        sflush(pdev->streams.strm);
997
171k
    if (pdev->ObjStm.strm != NULL && pdev->ObjStm.strm->file != NULL) {
998
78.9k
        int code2;
999
78.9k
        sflush(pdev->ObjStm.strm);
1000
78.9k
        code2 = gp_ferror(pdev->ObjStm.file);
1001
78.9k
        if (code >= 0) code = code2;
1002
78.9k
    }
1003
171k
    return gp_ferror(pdev->xref.file) || gp_ferror(pdev->asides.file) ||
1004
171k
           gp_ferror(pdev->streams.file) || code;
1005
171k
}
1006
1007
/* Compute the dominant text orientation of a page. */
1008
static int
1009
pdf_dominant_rotation(const pdf_text_rotation_t *ptr)
1010
53.4k
{
1011
53.4k
    int i, imax = -1;
1012
53.4k
    int64_t max_count = 0;
1013
53.4k
    static const int angles[] = { pdf_text_rotation_angle_values };
1014
1015
320k
    for (i = 0; i < countof(ptr->counts); ++i) {
1016
267k
        int64_t count = ptr->counts[i];
1017
1018
267k
        if (count > max_count)
1019
18.9k
            imax = i, max_count = count;
1020
267k
    }
1021
53.4k
    return (imax < 0 ? imax : angles[imax]);
1022
53.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
88.9k
{
1028
88.9k
    stream *s = pdev->strm;
1029
88.9k
    int dsc_orientation = -1;
1030
88.9k
    const pdf_page_dsc_info_t *ppdi;
1031
1032
88.9k
    if (pdev->params.AutoRotatePages == arp_None)
1033
35.4k
        return; /* Not requested. */
1034
1035
53.4k
    ppdi = (page != NULL ? &page->dsc_info : &pdev->doc_dsc_info);
1036
1037
    /* Determine DSC orientation : */
1038
53.4k
    if (ppdi->viewing_orientation >= 0)
1039
0
        dsc_orientation = ppdi->viewing_orientation;
1040
53.4k
    else if (ppdi->orientation >= 0)
1041
0
        dsc_orientation = ppdi->orientation;
1042
53.4k
    if ((page == NULL && pdev->params.AutoRotatePages == arp_All) || /* document */
1043
53.4k
        (page != NULL && page->text_rotation.Rotate >= 0) || /* page */
1044
53.4k
        dsc_orientation >= 0 /* have DSC */) {
1045
11.4k
        const pdf_text_rotation_t *ptr =
1046
11.4k
            (page != NULL ? &page->text_rotation : &pdev->text_rotation);
1047
11.4k
        int angle = -1;
1048
1049
        /* Combine DSC rotation with text rotation : */
1050
11.4k
        if (dsc_orientation == 0) {
1051
0
            if (ptr->Rotate == 0 || ptr->Rotate == 180)
1052
0
                angle = ptr->Rotate;
1053
11.4k
        } 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
11.4k
        if (angle < 0) {
1061
        /* If DSC and heuristic disagree, prefer dsc rotation to match the documented Adobe behaviour */
1062
11.4k
            if (dsc_orientation >= 0)
1063
0
                angle = dsc_orientation * 90;
1064
11.4k
            else
1065
11.4k
                angle = ptr->Rotate;
1066
11.4k
        }
1067
1068
        /* If got some, write it out : */
1069
11.4k
        if (angle >= 0)
1070
11.4k
            pprintd1(s, "/Rotate %d", angle);
1071
11.4k
    }
1072
53.4k
}
1073
1074
/* Close the current page. */
1075
static int
1076
pdf_close_page(gx_device_pdf * pdev, int num_copies)
1077
66.0k
{
1078
66.0k
    int page_num;
1079
66.0k
    pdf_page_t *page;
1080
66.0k
    int code, i;
1081
1082
66.0k
    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
66.0k
    code = pdfwrite_pdf_open_document(pdev);
1095
66.0k
    if (code < 0)
1096
0
        return code;
1097
66.0k
    if (pdev->ForOPDFRead && pdev->context == PDF_IN_NONE) {
1098
        /* Must create a context stream for empty pages. */
1099
11
        code = pdf_open_contents(pdev, PDF_IN_STREAM);
1100
11
        if (code < 0)
1101
3
            return code;
1102
11
    }
1103
66.0k
    pdf_close_contents(pdev, true);
1104
1105
66.0k
    if (!pdev->DoNumCopies)
1106
66.0k
        num_copies = 1;
1107
1108
132k
    for(i=0;i<num_copies;i++) {
1109
66.0k
        bool clear_resource_use = i < num_copies - 1 ? 0 : 1;
1110
1111
66.0k
        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
66.0k
        pdf_page_id(pdev, page_num);
1121
66.0k
        page = &pdev->pages[page_num - 1];
1122
66.0k
        page->MediaBox.x = pdev->MediaSize[0];
1123
66.0k
        page->MediaBox.y = pdev->MediaSize[1];
1124
66.0k
        page->contents_id = pdev->contents_id;
1125
66.0k
        page->NumCopies_set = pdev->NumCopies_set;
1126
66.0k
        page->NumCopies = pdev->NumCopies;
1127
66.0k
        page->UserUnit = pdev->UserUnit;
1128
66.0k
        pdf_record_usage(pdev, pdev->contents_id, pdev->next_page);
1129
66.0k
        pdf_record_usage(pdev, pdev->contents_length_id, pdev->next_page);
1130
66.0k
        pdf_record_usage(pdev, page->Page->id, pdev->next_page);
1131
1132
        /* pdf_store_page_resources sets procsets, resource_ids[]. */
1133
66.0k
        code = pdf_store_page_resources(pdev, page, clear_resource_use);
1134
66.0k
        if (code < 0)
1135
0
            return code;
1136
1137
        /* Write the Functions. */
1138
1139
66.0k
        code = pdf_write_resource_objects(pdev, resourceFunction);
1140
66.0k
        if (code < 0)
1141
0
            return code;
1142
1143
        /* Close use of text on the page. */
1144
1145
66.0k
        pdf_close_text_page(pdev);
1146
1147
        /* Accumulate text rotation. */
1148
1149
66.0k
        page->text_rotation.Rotate =
1150
66.0k
            (pdev->params.AutoRotatePages == arp_PageByPage ?
1151
35.4k
            pdf_dominant_rotation(&page->text_rotation) : -1);
1152
66.0k
        {
1153
66.0k
            int i;
1154
1155
396k
            for (i = 0; i < countof(page->text_rotation.counts); ++i)
1156
330k
                pdev->text_rotation.counts[i] += page->text_rotation.counts[i];
1157
66.0k
        }
1158
1159
        /* Record information from DSC comments. */
1160
1161
66.0k
        page->dsc_info = pdev->page_dsc_info;
1162
66.0k
        if (page->dsc_info.orientation < 0)
1163
66.0k
            page->dsc_info.orientation = pdev->doc_dsc_info.orientation;
1164
        /* Bug 688793 */
1165
66.0k
        if (page->dsc_info.viewing_orientation < 0)
1166
66.0k
        page->dsc_info.viewing_orientation =
1167
66.0k
           pdev->doc_dsc_info.viewing_orientation;
1168
66.0k
        if (page->dsc_info.bounding_box.p.x >= page->dsc_info.bounding_box.q.x ||
1169
66.0k
            page->dsc_info.bounding_box.p.y >= page->dsc_info.bounding_box.q.y
1170
66.0k
            )
1171
66.0k
            page->dsc_info.bounding_box = pdev->doc_dsc_info.bounding_box;
1172
1173
        /* Finish up. */
1174
1175
66.0k
        if(pdf_ferror(pdev))
1176
0
            return(gs_note_error(gs_error_ioerror));
1177
66.0k
    }
1178
66.0k
    pdf_reset_page(pdev);
1179
66.0k
    return (pdf_ferror(pdev) ? gs_note_error(gs_error_ioerror) : 0);
1180
66.0k
}
1181
1182
/* Write the page object. */
1183
static double
1184
round_box_coord(double xy)
1185
132k
{
1186
132k
    return (int)(xy * 100 + 0.5) / 100.0;
1187
132k
}
1188
static int check_annot_in_named(void *client_data, const byte *key_data, uint key_size, const cos_value_t *value)
1189
2.47M
{
1190
2.47M
    cos_value_t *v = (cos_value_t *)client_data;
1191
1192
2.47M
    if (value->contents.object == v->contents.object)
1193
0
        return 1;
1194
2.47M
    return 0;
1195
2.47M
}
1196
1197
static int
1198
pdf_write_page(gx_device_pdf *pdev, int page_num)
1199
66.0k
{
1200
66.0k
    int64_t page_id;
1201
66.0k
    pdf_page_t *page;
1202
66.0k
    double mediabox[4] = {0, 0};
1203
66.0k
    stream *s;
1204
66.0k
    const cos_value_t *v_mediabox = NULL;
1205
1206
66.0k
    if (pdev->pages == NULL)
1207
0
        return_error(gs_error_undefined);
1208
1209
66.0k
    page = &pdev->pages[page_num - 1];
1210
66.0k
    if (page->Page != NULL)
1211
66.0k
        v_mediabox = cos_dict_find_c_key(page->Page, "/MediaBox");
1212
66.0k
    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
66.0k
    s = pdev->strm;
1216
66.0k
    pdf_open_obj(pdev, page_id, resourcePage);
1217
1218
66.0k
    if (v_mediabox == NULL ) {
1219
66.0k
        mediabox[2] = round_box_coord(page->MediaBox.x);
1220
66.0k
        mediabox[3] = round_box_coord(page->MediaBox.y);
1221
66.0k
        pprintg2(s, "<</Type/Page/MediaBox [0 0 %g %g]\n",
1222
66.0k
                mediabox[2], mediabox[3]);
1223
66.0k
    } 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
66.0k
    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
66.0k
    pdf_print_orientation(pdev, page);
1517
66.0k
    if (page->UserUnit != 1)
1518
5
        pprintg1(s, "/UserUnit %g\n", page->UserUnit);
1519
1520
66.0k
    pprinti64d1(s, "/Parent %"PRId64" 0 R\n", pdev->Pages->id);
1521
66.0k
    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
66.0k
    if (page->group_id > 0) {
1526
736
        pprinti64d1(s, "/Group %"PRId64" 0 R\n", page->group_id);
1527
736
    }
1528
66.0k
    if (pdev->CompatibilityLevel <= 1.7) {
1529
66.0k
            stream_puts(s, "/Resources<</ProcSet[/PDF");
1530
66.0k
        if (page->procsets & ImageB)
1531
299
            stream_puts(s, " /ImageB");
1532
66.0k
        if (page->procsets & ImageC)
1533
3.56k
            stream_puts(s, " /ImageC");
1534
66.0k
        if (page->procsets & ImageI)
1535
884
            stream_puts(s, " /ImageI");
1536
66.0k
        if (page->procsets & Text)
1537
10.9k
            stream_puts(s, " /Text");
1538
66.0k
        stream_puts(s, "]\n");
1539
66.0k
    } else {
1540
3
        stream_puts(s, "/Resources<<");
1541
3
    }
1542
66.0k
    {
1543
66.0k
        int i;
1544
1545
594k
        for (i = 0; i < countof(page->resource_ids); ++i)
1546
528k
            if (page->resource_ids[i] && pdf_resource_type_names[i]) {
1547
43.0k
                stream_puts(s, pdf_resource_type_names[i]);
1548
43.0k
                pprinti64d1(s, " %"PRId64" 0 R\n", page->resource_ids[i]);
1549
43.0k
            }
1550
66.0k
    }
1551
66.0k
    stream_puts(s, ">>\n");
1552
1553
    /* Write the annotations array if any. */
1554
1555
66.0k
    if (page->Annots) {
1556
2.52k
        const cos_value_t *value = NULL;
1557
2.52k
        const cos_array_element_t *e = NULL, *next = NULL;
1558
2.52k
        int64_t index = 0;
1559
1560
2.52k
        stream_puts(s, "/Annots");
1561
2.52k
        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.52k
        e = cos_array_element_first(page->Annots);
1573
54.0k
        while (e != NULL) {
1574
51.4k
            next = cos_array_element_next(e, &index, &value);
1575
51.4k
            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
51.4k
                if (cos_dict_forall(pdev->local_named_objects, (void *)value,
1582
51.4k
                                    check_annot_in_named) == 0)
1583
51.4k
                    value->contents.object->id = 0;
1584
51.4k
            }
1585
51.4k
            e = next;
1586
51.4k
        }
1587
2.52k
        COS_FREE(page->Annots, "pdf_write_page(Annots)");
1588
2.52k
        page->Annots = 0;
1589
2.52k
    }
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
66.0k
    if (page->contents_id != 0)
1597
66.0k
        pprinti64d1(s, "/Contents %"PRId64" 0 R\n", page->contents_id);
1598
1599
    /* Write any elements stored by pdfmarks. */
1600
1601
66.0k
    if (page->Page != NULL)
1602
66.0k
        cos_dict_elements_write(page->Page, pdev);
1603
1604
66.0k
    stream_puts(s, ">>\n");
1605
66.0k
    pdf_end_obj(pdev, resourcePage);
1606
66.0k
    return 0;
1607
66.0k
}
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
43.3k
{
1616
43.3k
    gx_device_pdf *const pdev = (gx_device_pdf *) dev;
1617
43.3k
    int code;
1618
1619
43.3k
    if (pdev->Eps2Write && pdev->next_page != 0 && !gx_outputfile_is_separate_pages(pdev->fname, dev->memory)) {
1620
4.40k
       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.40k
       return_error(gs_error_ioerror);
1622
4.40k
    }
1623
1624
38.9k
    if (pdev->ForOPDFRead) {
1625
21.1k
        code = pdf_close_page(pdev, num_copies);
1626
21.1k
        if (code < 0)
1627
0
            return code;
1628
1629
21.1k
        while (pdev->sbstack_depth) {
1630
12
            code = pdf_exit_substream(pdev);
1631
12
            if (code < 0)
1632
6
                return code;
1633
12
        }
1634
21.1k
    } else {
1635
17.8k
        while (pdev->sbstack_depth) {
1636
8
            code = pdf_exit_substream(pdev);
1637
8
            if (code < 0)
1638
0
                return code;
1639
8
        }
1640
17.8k
        code = pdf_close_page(pdev, num_copies);
1641
17.8k
        if (code < 0)
1642
0
            return code;
1643
17.8k
    }
1644
1645
38.9k
    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
38.9k
    if (pdf_ferror(pdev))
1649
0
        return_error(gs_error_ioerror);
1650
1651
38.9k
    if ((code = gx_finish_output_page(dev, num_copies, flush)) < 0)
1652
0
        return code;
1653
1654
38.9k
    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
38.9k
    return code;
1662
38.9k
}
1663
1664
static int find_end_xref_section (gx_device_pdf *pdev, gp_file *tfile, int64_t start, gs_offset_t resource_pos)
1665
68.9k
{
1666
68.9k
    int64_t start_offset;
1667
1668
68.9k
    if (pdev->doubleXref)
1669
68.9k
        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
68.9k
    if (gp_fseek(tfile, start_offset, SEEK_SET) == 0)
1674
68.9k
    {
1675
68.9k
        int64_t i, r;
1676
1677
1.48M
        for (i = start; i < pdev->next_id; ++i) {
1678
1.41M
            gs_offset_t pos, index = -1;
1679
1680
1.41M
            r = gp_fread(&pos, sizeof(pos), 1, tfile);
1681
1.41M
            if (r != 1)
1682
0
                return(gs_note_error(gs_error_ioerror));
1683
1.41M
            if (pdev->doubleXref) {
1684
1.41M
                index = pos;
1685
1.41M
                r = gp_fread(&pos, sizeof(pos), 1, tfile);
1686
1.41M
                if (r != 1)
1687
0
                    return(gs_note_error(gs_error_ioerror));
1688
1.41M
            } else
1689
0
                index = 0;
1690
1.41M
            if (pos & ASIDES_BASE_POSITION) {
1691
377k
                pos &= ~ASIDES_BASE_POSITION;
1692
377k
                pos += resource_pos;
1693
377k
            }
1694
1.41M
            pos -= pdev->OPDFRead_procset_length;
1695
1.41M
            if (pos == 0 && index == 0) {
1696
499
                return i;
1697
499
            }
1698
1.41M
        }
1699
68.9k
    }
1700
68.4k
    return pdev->next_id;
1701
68.9k
}
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
14
{
1705
14
    int64_t start_offset;
1706
1707
14
    if (pdev->doubleXref)
1708
14
        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
14
    if (gp_fseek(tfile, start_offset, SEEK_SET) == 0)
1713
14
    {
1714
14
        int64_t i, r;
1715
1716
107
        for (i = start; i < end; ++i) {
1717
93
            gs_offset_t pos;
1718
93
            char str[21];
1719
1720
93
            r = gp_fread(&pos, sizeof(pos), 1, tfile);
1721
93
            if (r != 1)
1722
0
                return(gs_note_error(gs_error_ioerror));
1723
93
            if (pdev->doubleXref) {
1724
93
                r = gp_fread(&pos, sizeof(pos), 1, tfile);
1725
93
                if (r != 1)
1726
0
                    return(gs_note_error(gs_error_ioerror));
1727
93
            }
1728
1729
93
            if (pos & ASIDES_BASE_POSITION) {
1730
29
                pos &= ~ASIDES_BASE_POSITION;
1731
29
                pos += resource_pos;
1732
29
            }
1733
93
            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
93
            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
93
            if (!pdev->Linearise) {
1749
93
                gs_snprintf(str, sizeof(str), "%010"PRId64" 00000 n \n", pos);
1750
93
                stream_puts(pdev->strm, str);
1751
93
            }
1752
93
            if (Offsets)
1753
0
                Offsets[i] = pos;
1754
93
        }
1755
14
    }
1756
14
    return 0;
1757
14
}
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.0k
{
1761
23.0k
    int64_t start_offset;
1762
1763
23.0k
    if (pdev->doubleXref)
1764
23.0k
        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.0k
    if (gp_fseek(tfile, start_offset, SEEK_SET) == 0)
1769
23.0k
    {
1770
23.0k
        int64_t i, j, r;
1771
1772
496k
        for (i = start; i < end; ++i) {
1773
473k
            gs_offset_t pos, objstm = -1, index = 0;
1774
1775
473k
            r = gp_fread(&pos, sizeof(pos), 1, tfile);
1776
473k
            if (r != 1)
1777
0
                return(gs_note_error(gs_error_ioerror));
1778
1779
473k
            if (pdev->doubleXref) {
1780
473k
                objstm = pos;
1781
473k
                r = gp_fread(&index, sizeof(pos), 1, tfile);
1782
473k
                if (r != 1)
1783
0
                    return(gs_note_error(gs_error_ioerror));
1784
473k
                pos = index;
1785
473k
            }
1786
1787
473k
            if (!pdev->doubleXref || objstm == 0) {
1788
233k
                if (pos & ASIDES_BASE_POSITION) {
1789
126k
                    pos &= ~ASIDES_BASE_POSITION;
1790
126k
                    pos += resource_pos;
1791
126k
                }
1792
233k
                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
233k
                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
233k
            }
1803
1804
473k
            if (objstm > 0) {
1805
239k
                stream_putc(s, 0x02);
1806
239k
                pos = objstm;
1807
239k
            }
1808
233k
            else
1809
233k
                stream_putc(s, 0x01);
1810
1.55M
            for (j = 1; j <= offset_size; j++)
1811
1.08M
                stream_putc(s, (pos >> ((offset_size - j) * 8)) & 0xFF);
1812
473k
            stream_putc(s, 0x00);
1813
473k
            if (objstm > 0)
1814
239k
                stream_putc(s, index);
1815
233k
            else
1816
233k
                stream_putc(s, 0x00);
1817
473k
        }
1818
23.0k
    }
1819
23.0k
    return 0;
1820
23.0k
}
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
485k
{
2720
485k
    int i;
2721
485k
    void *Temp;
2722
485k
    pdf_linearisation_record_t *resize;
2723
2724
485k
    if (!pdev->Linearise)
2725
485k
        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
165k
{
2786
165k
    int i;
2787
165k
    if (!pdev->Linearise)
2788
165k
        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
165k
}
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
50.0k
{
2814
50.0k
    if (pdev->pdf_font_dir == NULL)
2815
0
        return;
2816
50.0k
    gs_free_object(pdev->pdf_font_dir->memory, pdev->pdf_font_dir, "pdf_free_pdf_font_cache");
2817
50.0k
    pdev->pdf_font_dir = NULL;
2818
50.0k
}
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.17k
{
2824
5.17k
    int i;
2825
5.17k
    int64_t index;
2826
5.17k
    cos_array_t *pca = (cos_array_t *)pco;
2827
5.17k
    const cos_array_element_t *element = cos_array_element_first(pca);
2828
5.17k
    cos_value_t *v;
2829
2830
25.8k
    while (element) {
2831
20.7k
        element = cos_array_element_next(element, &index, (const cos_value_t **)&v);
2832
20.7k
        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
20.7k
    }
2849
5.17k
    return 0;
2850
5.17k
}
2851
2852
static int discard_dict_refs(void *client_data, const byte *key_data, uint key_size, const cos_value_t *v)
2853
736
{
2854
736
    int i;
2855
736
    gx_device_pdf *pdev = (gx_device_pdf *)client_data;
2856
736
    cos_value_t *v1 = (cos_value_t *)v;
2857
2858
736
    if (v->value_type == COS_VALUE_OBJECT) {
2859
6.25k
        for (i=0;i<NUM_RESOURCE_TYPES;i++) {
2860
5.88k
            if (i == resourceOther)
2861
368
                continue;
2862
5.52k
            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.52k
            if (cos_type(v->contents.object) == cos_type_array) {
2867
5.17k
                discard_array_refs(pdev, v->contents.object);
2868
5.17k
            }
2869
5.52k
            if (cos_type(v->contents.object) == cos_type_dict) {
2870
345
                cos_dict_forall((const cos_dict_t *)v->contents.object, pdev, discard_dict_refs);
2871
345
            }
2872
5.52k
        }
2873
368
    }
2874
736
    return 0;
2875
736
}
2876
2877
/* Close the device. */
2878
static int
2879
pdf_close(gx_device * dev)
2880
50.0k
{
2881
50.0k
    gx_device_pdf *const pdev = (gx_device_pdf *) dev;
2882
50.0k
    gs_memory_t *mem = pdev->pdf_memory;
2883
50.0k
    stream *s = NULL;
2884
50.0k
    gp_file *tfile = pdev->xref.file;
2885
50.0k
    gs_offset_t xref = 0;
2886
50.0k
    gs_offset_t resource_pos = 0;
2887
50.0k
    int64_t Catalog_id = 0, Info_id = 0,
2888
50.0k
        Pages_id = 0, Encrypt_id = 0;
2889
50.0k
    int64_t Threads_id = 0;
2890
50.0k
    bool partial_page = (pdev->contents_id != 0 && pdev->next_page != 0);
2891
50.0k
    int code = 0, code1, pagecount=0;
2892
50.0k
    int64_t start_section, end_section;
2893
50.0k
    char str[256];
2894
50.0k
    pdf_linearisation_t linear_params;
2895
50.0k
    bool file_per_page = false;
2896
50.0k
    int bottom = (pdev->ResourcesBeforeUsage ? 1 : 0);
2897
2898
50.0k
    if (!dev->is_open)
2899
0
        return_error(gs_error_undefined);
2900
50.0k
    dev->is_open = false;
2901
2902
50.0k
    if (pdev->sbstack_depth > bottom) {
2903
30
        emprintf(pdev->pdf_memory, "Error closing device; open substreams detected!\n");
2904
30
        emprintf(pdev->pdf_memory, "Probably due to errors in the input. Output file is incorrect/invalid.\n");
2905
30
    }
2906
2907
50.1k
    while(pdev->sbstack_depth > bottom)
2908
        /* This is an error, and we are trying to recover, so ignore any further errors */
2909
39
        (void)pdf_exit_substream(pdev);
2910
2911
50.0k
    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
50.0k
    if (pdev->Catalog)
2924
50.0k
        Catalog_id = pdev->Catalog->id;
2925
50.0k
    if (pdev->Info)
2926
50.0k
        Info_id = pdev->Info->id;
2927
50.0k
    if (pdev->Pages)
2928
50.0k
        Pages_id = pdev->Pages->id;
2929
2930
50.0k
    memset(&linear_params, 0x00, sizeof(linear_params));
2931
50.0k
    linear_params.Info_id = Info_id;
2932
50.0k
    linear_params.Pages_id = Pages_id;
2933
50.0k
    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
50.0k
    if (pdev->next_page == 0) {
2943
26.0k
        file_per_page = !pdev->InOutputPage &&
2944
26.0k
            gx_outputfile_is_separate_pages(pdev->fname, pdev->memory);
2945
26.0k
        if (!file_per_page) {
2946
26.0k
            code = pdf_open_page(pdev, PDF_IN_STREAM);
2947
2948
26.0k
            if (code < 0)
2949
0
                return code;
2950
26.0k
        }
2951
26.0k
    }
2952
50.0k
    if (pdev->contents_id != 0)
2953
27.0k
        pdf_close_page(pdev, 1);
2954
2955
    /* Write the page objects. */
2956
50.0k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC)) {
2957
53.4k
        for (pagecount = 1; pagecount <= pdev->next_page; ++pagecount)
2958
30.6k
            pdf_write_page(pdev, pagecount);
2959
22.8k
    }
2960
2961
50.0k
    if (pdev->PrintStatistics)
2962
0
        pdf_print_resource_statistics(pdev);
2963
2964
    /* Write the font resources and related resources. */
2965
50.0k
    code1 = pdf_write_resource_objects(pdev, resourceXObject);
2966
50.0k
    if (code >= 0)
2967
50.0k
        code = code1;
2968
50.0k
    code1 = pdf_free_resource_objects(pdev, resourceXObject);
2969
50.0k
    if (code >= 0)
2970
50.0k
        code = code1;
2971
50.0k
    code1 = pdf_free_resource_objects(pdev, resourceProperties);
2972
50.0k
    if (code >= 0)
2973
50.0k
        code = code1;
2974
50.0k
    code1 = pdf_write_resource_objects(pdev, resourceGroup);
2975
50.0k
    if (code >= 0)
2976
50.0k
        code = code1;
2977
50.0k
    code1 = pdf_free_resource_objects(pdev, resourceGroup);
2978
50.0k
    if (code >= 0)
2979
50.0k
        code = code1;
2980
50.0k
    code1 = pdf_write_resource_objects(pdev, resourceSoftMaskDict);
2981
50.0k
    if (code >= 0)
2982
50.0k
        code = code1;
2983
50.0k
    code1 = pdf_free_resource_objects(pdev, resourceSoftMaskDict);
2984
50.0k
    if (code >= 0)
2985
50.0k
        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
50.0k
    pdf_clean_standard_fonts(pdev);
2991
50.0k
    code1 = pdf_free_font_cache(pdev);
2992
50.0k
    if (code >= 0)
2993
50.0k
        code = code1;
2994
50.0k
    code1 = pdf_write_resource_objects(pdev, resourceCharProc);
2995
50.0k
    if (code >= 0)
2996
50.0k
        code = code1;
2997
50.0k
    code1 = pdf_finish_resources(pdev, resourceFont, pdf_convert_truetype_font);
2998
50.0k
    if (code >= 0)
2999
50.0k
        code = code1;
3000
50.0k
    code1 = pdf_finish_resources(pdev, resourceFontDescriptor, pdf_finish_FontDescriptor);
3001
50.0k
    if (code >= 0)
3002
50.0k
        code = code1;
3003
50.0k
    code1 = write_font_resources(pdev, &pdev->resources[resourceCIDFont]);
3004
50.0k
    if (code >= 0)
3005
49.9k
        code = code1;
3006
50.0k
    code1 = write_font_resources(pdev, &pdev->resources[resourceFont]);
3007
50.0k
    if (code >= 0)
3008
49.9k
        code = code1;
3009
50.0k
    code1 = pdf_finish_resources(pdev, resourceFontDescriptor, pdf_write_FontDescriptor);
3010
50.0k
    if (code >= 0)
3011
49.9k
        code = code1;
3012
    /* If required, write the Encoding for Type 3 bitmap fonts. */
3013
50.0k
    code1 = pdf_write_bitmap_fonts_Encoding(pdev);
3014
50.0k
    if (code >= 0)
3015
49.9k
        code = code1;
3016
3017
50.0k
    code1 = pdf_write_resource_objects(pdev, resourceCMap);
3018
50.0k
    if (code >= 0)
3019
49.9k
        code = code1;
3020
50.0k
    code1 = pdf_free_resource_objects(pdev, resourceCMap);
3021
50.0k
    if (code >= 0)
3022
49.9k
        code = code1;
3023
50.0k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC)) {
3024
22.8k
        if (pdev->ResourcesBeforeUsage)
3025
0
            pdf_reverse_resource_chain(pdev, resourcePage);
3026
22.8k
        code1 = pdf_write_resource_objects(pdev, resourcePage);
3027
22.8k
        if (code >= 0)
3028
22.7k
            code = code1;
3029
22.8k
        code1 = pdf_free_resource_objects(pdev, resourcePage);
3030
22.8k
        if (code >= 0)
3031
22.7k
            code = code1;
3032
22.8k
    }
3033
3034
    /* Create the Pages tree. */
3035
50.0k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC) && pdev->strm != NULL) {
3036
22.8k
        pdf_open_obj(pdev, Pages_id, resourcePagesTree);
3037
22.8k
        pdf_record_usage(pdev, Pages_id, resource_usage_part9_structure);
3038
3039
22.8k
        s = pdev->strm;
3040
22.8k
        stream_puts(s, "<< /Type /Pages /Kids [\n");
3041
        /* Omit the last page if it was incomplete. */
3042
22.8k
        if (partial_page)
3043
17
            --(pdev->next_page);
3044
22.8k
        {
3045
22.8k
            int i;
3046
3047
53.4k
            for (i = 0; i < pdev->next_page; ++i)
3048
30.5k
                pprinti64d1(s, "%"PRId64" 0 R\n", pdev->pages[i].Page->id);
3049
22.8k
        }
3050
22.8k
        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
22.8k
        pdev->doc_dsc_info.viewing_orientation = pdev->doc_dsc_info.orientation = -1;
3057
22.8k
        pdev->text_rotation.Rotate = pdf_dominant_rotation(&pdev->text_rotation);
3058
22.8k
        pdf_print_orientation(pdev, NULL);
3059
3060
22.8k
        cos_dict_elements_write(pdev->Pages, pdev);
3061
22.8k
        stream_puts(s, ">>\n");
3062
22.8k
        pdf_end_obj(pdev, resourcePagesTree);
3063
3064
        /* Close outlines and articles. */
3065
3066
22.8k
        if (pdev->outlines_id != 0) {
3067
405
            pdf_record_usage(pdev, pdev->outlines_id, resource_usage_part9_structure);
3068
            /* depth > 0 is only possible for an incomplete outline tree. */
3069
424
            while (pdev->outline_depth > 0) {
3070
19
                code1 = pdfmark_close_outline(pdev);
3071
19
                if (code >= 0)
3072
19
                    code = code1;
3073
19
            }
3074
405
            code = pdfmark_close_outline(pdev);
3075
405
            if (code >= 0)
3076
405
                code = code1;
3077
405
            pdf_open_obj(pdev, pdev->outlines_id, resourceOutline);
3078
405
            pprintd1(s, "<< /Type /Outlines /Count %d", pdev->outlines_open);
3079
405
            pprinti64d2(s, " /First %"PRId64" 0 R /Last %"PRId64" 0 R >>\n",
3080
405
                  pdev->outline_levels[0].first.id,
3081
405
                  pdev->outline_levels[0].last.id);
3082
405
            pdf_end_obj(pdev, resourceOutline);
3083
405
        }
3084
22.8k
        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
22.8k
        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
22.8k
        } else {
3100
22.8k
            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
22.8k
            if (pdev->EmbeddedFiles) {
3107
24
                pdf_record_usage(pdev, pdev->EmbeddedFiles->id, resource_usage_part9_structure);
3108
24
                cos_write_dict_as_ordered_array((cos_object_t *)pdev->EmbeddedFiles, pdev, resourceEmbeddedFiles);
3109
24
            }
3110
22.8k
            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
22.8k
        }
3115
3116
        /* Write the PageLabel array */
3117
22.8k
        pdfmark_end_pagelabels(pdev);
3118
22.8k
        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
22.8k
        if (!pdev->OmitXMP) {
3124
22.8k
            bool saved = pdev->WriteObjStms;
3125
3126
22.8k
            if (pdev->WriteObjStms)
3127
22.8k
                pdev->WriteObjStms = false;
3128
            /* Write the document metadata. */
3129
22.8k
            code1 = pdf_document_metadata(pdev);
3130
22.8k
            pdev->WriteObjStms = saved;
3131
22.8k
            if (code >= 0)
3132
22.7k
                code = code1;
3133
22.8k
        }
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
22.8k
        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
22.8k
        pdf_open_obj(pdev, Catalog_id, resourceCatalog);
3158
22.8k
        pdf_record_usage(pdev, Catalog_id, resource_usage_part1_structure);
3159
3160
22.8k
        s = pdev->strm;
3161
22.8k
        stream_puts(s, "<<");
3162
22.8k
        pprinti64d1(s, "/Type /Catalog /Pages %"PRId64" 0 R\n", Pages_id);
3163
22.8k
        if (pdev->outlines_id != 0)
3164
405
            pprinti64d1(s, "/Outlines %"PRId64" 0 R\n", pdev->outlines_id);
3165
22.8k
        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
22.8k
        if (pdev->CompatibilityLevel < 1.2) {
3170
2
            if (pdev->Dests)
3171
0
                pprinti64d1(s, "/Dests %"PRId64" 0 R\n", pdev->Dests->id);
3172
22.8k
        } else {
3173
22.8k
            if (pdev->Dests || pdev->EmbeddedFiles) {
3174
24
                stream_puts(s, "/Names <<\n");
3175
24
                if (pdev->Dests)
3176
0
                    pprinti64d1(s, "/Dests <</Kids [%"PRId64" 0 R]>>\n", pdev->Dests->id);
3177
24
                if (pdev->EmbeddedFiles)
3178
24
                    pprinti64d1(s, "/EmbeddedFiles << /Kids [%"PRId64" 0 R]>>\n", pdev->EmbeddedFiles->id);
3179
24
                stream_puts(s, ">>\n");
3180
24
            }
3181
22.8k
            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
22.8k
        }
3185
22.8k
        if (pdev->PageLabels)
3186
0
            pprinti64d1(s, "/PageLabels << /Nums  %"PRId64" 0 R >>\n",
3187
0
                  pdev->PageLabels->id);
3188
22.8k
        cos_dict_elements_write(pdev->Catalog, pdev);
3189
22.8k
        stream_puts(s, ">>\n");
3190
22.8k
        pdf_end_obj(pdev, resourceCatalog);
3191
22.8k
        if (pdev->Dests) {
3192
0
            COS_FREE(pdev->Dests, "pdf_close(Dests)");
3193
0
            pdev->Dests = 0;
3194
0
        }
3195
22.8k
        if (pdev->EmbeddedFiles) {
3196
24
            COS_FREE(pdev->EmbeddedFiles, "pdf_close(EmbeddFiles)");
3197
24
            pdev->EmbeddedFiles = 0;
3198
24
        }
3199
22.8k
        if (pdev->AF) {
3200
0
            COS_FREE(pdev->AF, "pdf_close(AF)");
3201
0
            pdev->AF = 0;
3202
0
        }
3203
22.8k
        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
22.8k
        pdev->Catalog->id = 0;
3212
        /*pdev->Info->id = 0;*/ /* Info should get written */
3213
22.8k
        pdf_record_usage(pdev, pdev->Info->id, resource_usage_part9_structure);
3214
3215
27.2k
    } else {
3216
27.2k
        if (pdev->Info != NULL)
3217
27.2k
            pdev->Info->id = 0; /* Don't write Info dict for DSC PostScript */
3218
27.2k
    }
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
50.0k
    if(pdev->local_named_objects != NULL) {
3226
50.0k
        do {
3227
50.0k
            cos_dict_objects_write(pdev->local_named_objects, pdev);
3228
50.0k
        } while (pdf_pop_namespace(pdev) >= 0);
3229
50.0k
    }
3230
50.0k
    if (pdev->global_named_objects != NULL)
3231
50.0k
        cos_dict_objects_write(pdev->global_named_objects, pdev);
3232
3233
50.0k
    if (pdev->ForOPDFRead && pdev->ProduceDSC) {
3234
27.2k
        int pages;
3235
3236
89.8k
        for (pages = 0; pages <= pdev->next_page; ++pages)
3237
62.6k
            ;
3238
3239
27.2k
        code1 = ps2write_dsc_header(pdev, pages - 1);
3240
27.2k
        if (code >= 0)
3241
27.2k
            code = code1;
3242
27.2k
    }
3243
3244
    /* Copy the resources into the main file. */
3245
3246
50.0k
    if (pdev->WriteObjStms) {
3247
22.8k
        FlushObjStm(pdev);
3248
22.8k
        pdev->WriteObjStms = false;
3249
22.8k
    }
3250
50.0k
    if (pdev->strm != NULL) {
3251
50.0k
        s = pdev->strm;
3252
50.0k
        resource_pos = stell(s);
3253
50.0k
        sflush(pdev->asides.strm);
3254
50.0k
        {
3255
50.0k
            gp_file *rfile = pdev->asides.file;
3256
50.0k
            int64_t res_end = gp_ftell(rfile);
3257
3258
50.0k
            gp_fseek(rfile, 0L, SEEK_SET);
3259
50.0k
            code1 = pdf_copy_data(s, rfile, res_end, NULL);
3260
50.0k
            if (code >= 0)
3261
49.8k
                code = code1;
3262
50.0k
        }
3263
50.0k
    }
3264
3265
50.0k
    if (pdev->ForOPDFRead && pdev->ProduceDSC && s != NULL) {
3266
27.2k
        int j;
3267
3268
27.2k
        pagecount = 1;
3269
3270
        /* All resources and procsets written, end the prolog */
3271
27.2k
        stream_puts(pdev->strm, "%%EndProlog\n");
3272
3273
27.2k
        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
27.2k
        if (pdev->ResourcesBeforeUsage)
3285
27.2k
            pdf_reverse_resource_chain(pdev, resourcePage);
3286
462k
        for (j = 0; j < NUM_RESOURCE_CHAINS && code >= 0; ++j) {
3287
435k
            pdf_resource_t *pres = pdev->resources[resourcePage].chains[j];
3288
3289
470k
            for (; pres != 0; pres = pres->next)
3290
35.4k
                if ((!pres->named || pdev->ForOPDFRead)
3291
35.4k
                    && !pres->object->written) {
3292
35.4k
                    pdf_page_t *page = &pdev->pages[pagecount - 1];
3293
3294
35.4k
                    pprintd2(pdev->strm, "%%%%Page: %d %d\n",
3295
35.4k
                        pagecount, pagecount);
3296
35.4k
                    if (!pdev->Eps2Write)
3297
21.0k
                        pprintd2(pdev->strm, "%%%%PageBoundingBox: 0 0 %d %d\n", (int)page->MediaBox.x, (int)page->MediaBox.y);
3298
35.4k
                    stream_puts(pdev->strm, "%%BeginPageSetup\n");
3299
3300
35.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
35.4k
                    pdf_write_page(pdev, pagecount++);
3312
3313
35.4k
                    stream_puts(pdev->strm, "%%EndPageSetup\n");
3314
35.4k
                    pprinti64d1(pdev->strm, "%"PRId64" 0 obj\n", pres->object->id);
3315
35.4k
                    code = cos_write(pres->object, pdev, pres->object->id);
3316
35.4k
                    stream_puts(pdev->strm, "endobj\n");
3317
35.4k
                    pres->object->written = true;
3318
35.4k
                    stream_puts(pdev->strm, "%%PageTrailer\n");
3319
35.4k
                }
3320
435k
        }
3321
27.2k
        code1 = pdf_free_resource_objects(pdev, resourcePage);
3322
27.2k
        if (code >= 0)
3323
27.2k
            code = code1;
3324
27.2k
        stream_puts(pdev->strm, "%%Trailer\n");
3325
27.2k
        stream_puts(pdev->strm, "end\n");
3326
27.2k
        stream_puts(pdev->strm, "%%EOF\n");
3327
27.2k
    }
3328
3329
50.0k
    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
50.0k
    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
50.0k
    if (!(pdev->ForOPDFRead && pdev->ProduceDSC) && pdev->strm != NULL) {
3348
        /* Write Encrypt. */
3349
22.8k
        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
22.8k
        start_section = pdev->FirstObjectNumber;
3372
22.8k
        end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3373
3374
22.8k
        xref = pdf_stell(pdev) - pdev->OPDFRead_procset_length;
3375
22.8k
        if (pdev->Linearise)
3376
0
            linear_params.xref = xref;
3377
3378
22.8k
        if (!pdev->WriteXRefStm) {
3379
13
            if (pdev->FirstObjectNumber == 1) {
3380
13
                gs_snprintf(str, sizeof(str), "xref\n0 %"PRId64"\n0000000000 65535 f \n",
3381
13
                      end_section);
3382
13
                stream_puts(s, str);
3383
13
            }
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
14
            do {
3392
14
                code = write_xref_section(pdev, tfile, start_section, end_section, resource_pos, linear_params.Offsets);
3393
14
                if (code < 0)
3394
0
                    goto error_cleanup;
3395
3396
14
                if (end_section >= pdev->next_id)
3397
13
                    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
13
            if (!pdev->Linearise) {
3410
13
                char xref_str[32];
3411
13
                stream_puts(s, "trailer\n");
3412
13
                pprinti64d3(s, "<< /Size %"PRId64" /Root %"PRId64" 0 R /Info %"PRId64" 0 R\n",
3413
13
                      pdev->next_id, Catalog_id, Info_id);
3414
13
                if (!pdev->OmitID) {
3415
13
                    stream_puts(s, "/ID [");
3416
13
                    psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3417
13
                    psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3418
13
                    stream_puts(s, "]\n");
3419
13
                }
3420
13
                if (pdev->OwnerPassword.size > 0) {
3421
0
                    pprinti64d1(s, "/Encrypt %"PRId64" 0 R ", Encrypt_id);
3422
0
                }
3423
13
                stream_puts(s, ">>\n");
3424
13
                gs_snprintf(xref_str, sizeof(xref_str), "startxref\n%"PRId64"\n%%%%EOF\n", xref);
3425
13
                stream_puts(s, xref_str);
3426
13
            }
3427
22.8k
        } else {
3428
22.8k
            char xref_str[32];
3429
22.8k
            gs_offset_t maxoffs = xref, offs_bytes = 0, length = 0;
3430
22.8k
            int i;
3431
3432
69.8k
            while(maxoffs > 0) {
3433
47.0k
                maxoffs = maxoffs >> 8;
3434
47.0k
                offs_bytes++;
3435
47.0k
            }
3436
3437
22.8k
            gs_snprintf(str, sizeof(str), "%"PRId64" 0 obj\n<<\n/Type /XRef\n", (int64_t)pdev->next_id);
3438
22.8k
            stream_puts(s, str);
3439
22.8k
            gs_snprintf(str, sizeof(str), "/Size %"PRId64"\n", (int64_t)(pdev->next_id + 1));
3440
22.8k
            stream_puts(s, str);
3441
3442
22.8k
            pprinti64d2(s, "/Root %"PRId64" 0 R /Info %"PRId64" 0 R\n", Catalog_id, Info_id);
3443
22.8k
            if (!pdev->OmitID) {
3444
22.8k
                stream_puts(s, "/ID [");
3445
22.8k
                psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3446
22.8k
                psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
3447
22.8k
                stream_puts(s, "]\n");
3448
22.8k
            }
3449
22.8k
            if (pdev->OwnerPassword.size > 0) {
3450
0
                pprinti64d1(s, "/Encrypt %"PRId64" 0 R ", Encrypt_id);
3451
0
            }
3452
3453
22.8k
            end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3454
22.8k
            if (end_section == pdev->next_id)
3455
22.7k
                end_section++;
3456
3457
22.8k
            length += (end_section - start_section) * (offs_bytes + 3);
3458
3459
22.8k
            if (pdev->FirstObjectNumber == 1) {
3460
22.8k
                gs_snprintf(str, sizeof(str), "/Index [0 %"PRId64" ", end_section);
3461
22.8k
                stream_puts(s, str);
3462
22.8k
            } 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
22.9k
            do {
3468
22.9k
                if (end_section >= pdev->next_id)
3469
22.8k
                    break;
3470
3471
194
                do {
3472
194
                    start_section = end_section + 1;
3473
194
                    end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3474
194
                    if (end_section < 0)
3475
0
                        return end_section;
3476
194
                } while (start_section == end_section);
3477
122
                gs_snprintf(str, sizeof(str), "%"PRId64" %"PRId64" ", start_section, end_section - start_section);
3478
122
                stream_puts(s, str);
3479
122
            }while (1);
3480
3481
22.8k
            {
3482
22.8k
                pdf_temp_file_t xref_temp;
3483
22.8k
                stream *xs = NULL, *xs1;
3484
22.8k
                char xrefbuf[256];
3485
22.8k
                int read = 0;
3486
22.8k
                stream_state *st = NULL;
3487
22.8k
                code = pdf_open_temp_stream(pdev, &xref_temp);
3488
22.8k
                if (code < 0)
3489
0
                    return code;
3490
3491
22.8k
                xs1 = xref_temp.strm;
3492
22.8k
                if (pdev->CompressStreams) {
3493
22.8k
                    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
22.8k
                    } else {
3502
22.8k
                        st = s_alloc_state(pdev->pdf_memory, s_zlibE_template.stype, "write_xref_strm");
3503
22.8k
                        if (st == NULL)
3504
0
                            return_error(gs_error_VMerror);
3505
22.8k
                        s_zlibE_template.set_defaults (st);
3506
22.8k
                        xs = s_add_filter(&xref_temp.strm, &s_zlibE_template, st, pdev->pdf_memory);
3507
22.8k
                        if (xs == NULL)
3508
0
                            xs = xref_temp.strm;
3509
22.8k
                    }
3510
22.8k
                } else
3511
0
                    xs = xref_temp.strm;
3512
3513
                /* write the free entry */
3514
22.8k
                stream_putc(xs, 0x00);
3515
69.8k
                for (i = 0; i < offs_bytes; i++)
3516
47.0k
                    stream_putc(xs, 0x00);
3517
22.8k
                stream_putc(xs, 0xFF);
3518
22.8k
                stream_putc(xs, 0xFF);
3519
3520
22.8k
                start_section = pdev->FirstObjectNumber;
3521
23.0k
                do {
3522
23.0k
                    end_section = find_end_xref_section(pdev, tfile, start_section, resource_pos);
3523
23.0k
                    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.0k
                    code = write_xrefstm_section(pdev, tfile, start_section, end_section, resource_pos, offs_bytes, xs);
3530
23.0k
                    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.0k
                    start_section = end_section + 1;
3537
23.0k
                } while (end_section < pdev->next_id);
3538
3539
                /* write the entry for this XRefStm */
3540
22.8k
                stream_putc(xs, 0x01);
3541
69.8k
                for (i = 1; i <= offs_bytes; i++)
3542
47.0k
                    stream_putc(xs, (xref >> ((offs_bytes - i) * 8)) & 0xFF);
3543
22.8k
                stream_putc(xs, 0x00);
3544
22.8k
                stream_putc(xs, 0x00);
3545
3546
22.8k
                sflush(xs);
3547
22.8k
                if (pdev->CompressStreams)
3548
22.8k
                    s_close_filters(&xref_temp.strm, xs1);
3549
22.8k
                sflush(xref_temp.strm);
3550
22.8k
                length = stell(xref_temp.strm);
3551
3552
22.8k
                if (pdev->CompressStreams) {
3553
22.8k
                    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
22.8k
                    else
3556
22.8k
                        gs_snprintf(str, sizeof(str), "]\n/W [1 %"PRId64" 2]\n/Filter /FlateDecode/Length %"PRId64"\n>>\nstream\n", offs_bytes, length);
3557
22.8k
                }
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
22.8k
                stream_puts(s, str);
3561
3562
22.8k
                code = gp_fseek(xref_temp.file , 0, SEEK_SET);
3563
22.8k
                if (code < 0)
3564
0
                    return code;
3565
24.2k
                do {
3566
24.2k
                    read = gp_fread(&xrefbuf, 1, 256, xref_temp.file);
3567
24.2k
                    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
24.2k
                    stream_write(s, xrefbuf, read);
3573
24.2k
                } while (read == 256);
3574
3575
22.8k
                pdf_close_temp_file(pdev, &xref_temp, 0);
3576
22.8k
            }
3577
3578
0
            gs_snprintf(str, sizeof(str), "\nendstream\nendobj\n");
3579
22.8k
            stream_puts(s, str);
3580
22.8k
            pdev->next_id++;
3581
3582
22.8k
            gs_snprintf(str, sizeof(xref_str), "startxref\n%"PRId64"\n%%%%EOF\n", xref);
3583
22.8k
            stream_puts(s, str);
3584
22.8k
        }
3585
22.8k
    }
3586
3587
50.0k
    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
50.0k
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
50.0k
    {
3646
50.0k
        int j;
3647
3648
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3649
801k
            pdf_resource_t *pres = pdev->resources[resourceOther].chains[j];
3650
3651
891k
            for (; pres != 0;) {
3652
89.9k
                if (pres->object) {
3653
89.9k
                    if (cos_type(pres->object) == cos_type_array) {
3654
0
                        discard_array_refs(pdev, pres->object);
3655
0
                    }
3656
89.9k
                    if (cos_type(pres->object) == cos_type_dict) {
3657
23
                        cos_dict_forall((const cos_dict_t *)pres->object, pdev, discard_dict_refs);
3658
23
                    }
3659
89.9k
                }
3660
89.9k
                pres = pres->next;
3661
89.9k
            }
3662
801k
        }
3663
50.0k
    }
3664
3665
50.0k
    {
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
50.0k
        int j;
3673
3674
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3675
801k
            pdf_resource_t *pres = pdev->resources[resourceFont].chains[j];
3676
3677
849k
            for (; pres != 0;) {
3678
48.4k
                pdf_font_resource_t *pdfont = (pdf_font_resource_t *)pres;
3679
3680
48.4k
                font_resource_free(pdev, pdfont);
3681
48.4k
                pres = pres->next;
3682
48.4k
            }
3683
801k
        }
3684
50.0k
    }
3685
3686
50.0k
    {
3687
50.0k
        int j;
3688
3689
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3690
801k
            pdf_resource_t *pres = pdev->resources[resourceCIDFont].chains[j];
3691
3692
802k
            for (; pres != 0;) {
3693
1.60k
                pdf_font_resource_t *pdfont = (pdf_font_resource_t *)pres;
3694
3695
1.60k
                font_resource_free(pdev, pdfont);
3696
1.60k
                pres = pres->next;
3697
1.60k
            }
3698
801k
        }
3699
50.0k
    }
3700
3701
50.0k
    {
3702
50.0k
        int j;
3703
3704
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3705
801k
            pdf_resource_t *pres = pdev->resources[resourceFontDescriptor].chains[j];
3706
840k
            for (; pres != 0;) {
3707
39.3k
                pdf_font_descriptor_free(pdev, pres);
3708
39.3k
                pres = pres->next;
3709
39.3k
            }
3710
801k
        }
3711
50.0k
    }
3712
3713
50.0k
    {
3714
50.0k
        int j;
3715
3716
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3717
801k
            pdf_resource_t *pres = pdev->resources[resourceCharProc].chains[j];
3718
3719
938k
            for (; pres != 0;) {
3720
137k
                if (pres->object) {
3721
137k
                    cos_free(pres->object, "free CharProc resource");
3722
137k
                    pres->object = 0;
3723
137k
                }
3724
137k
                pres = pres->next;
3725
137k
            }
3726
801k
        }
3727
50.0k
    }
3728
3729
50.0k
    {
3730
50.0k
        int j;
3731
3732
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3733
801k
            pdf_resource_t *pres = pdev->resources[resourceExtGState].chains[j];
3734
3735
827k
            for (; pres != 0;) {
3736
26.2k
                if (pres->object) {
3737
26.2k
                    cos_release(pres->object, "release ExtGState object");
3738
26.2k
                    gs_free_object(pdev->pdf_memory, pres->object, "free ExtGState");
3739
26.2k
                    pres->object = 0;
3740
26.2k
                }
3741
26.2k
                pres = pres->next;
3742
26.2k
            }
3743
801k
        }
3744
50.0k
    }
3745
3746
50.0k
    {
3747
50.0k
        int j;
3748
3749
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3750
801k
            pdf_resource_t *pres = pdev->resources[resourcePattern].chains[j];
3751
3752
816k
            for (; pres != 0;) {
3753
15.1k
                if (pres->object) {
3754
13.5k
                    cos_release(pres->object, "free pattern dict");
3755
13.5k
                    gs_free_object(pdev->pdf_memory, pres->object, "free pattern resources");
3756
13.5k
                    pres->object = 0;
3757
13.5k
                }
3758
15.1k
                pres = pres->next;
3759
15.1k
            }
3760
801k
        }
3761
50.0k
    }
3762
3763
50.0k
    {
3764
50.0k
        int j;
3765
3766
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3767
801k
            pdf_resource_t *pres = pdev->resources[resourceShading].chains[j];
3768
3769
802k
            for (; pres != 0;) {
3770
1.41k
                if (pres->object) {
3771
1.41k
                    cos_release(pres->object, "free Shading dict");
3772
1.41k
                    gs_free_object(pdev->pdf_memory, pres->object, "free Shading resources");
3773
1.41k
                    pres->object = 0;
3774
1.41k
                }
3775
1.41k
                pres = pres->next;
3776
1.41k
            }
3777
801k
        }
3778
50.0k
    }
3779
3780
50.0k
    {
3781
50.0k
        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
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3788
801k
            pdf_resource_t *pres = pdev->resources[resourceColorSpace].chains[j];
3789
808k
            for (; pres != 0;) {
3790
7.09k
                if (cos_type(pres->object) == cos_type_array) {
3791
6.45k
                    int64_t index;
3792
6.45k
                    cos_array_t *pca = (cos_array_t *)pres->object;
3793
6.45k
                    const cos_array_element_t *element = cos_array_element_first(pca);
3794
6.45k
                    cos_value_t *v;
3795
3796
24.2k
                    while (element) {
3797
17.7k
                        element = cos_array_element_next(element, &index, (const cos_value_t **)&v);
3798
17.7k
                        if (v->value_type == COS_VALUE_OBJECT) {
3799
5.78k
                            if (pdf_find_resource_by_resource_id(pdev, resourceColorSpace, v->contents.object->id)){
3800
276
                                v->value_type = COS_VALUE_CONST;
3801
276
                            }
3802
5.78k
                        }
3803
17.7k
                    }
3804
6.45k
                }
3805
7.09k
                pres = pres->next;
3806
7.09k
            }
3807
801k
        }
3808
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3809
801k
            pdf_resource_t *pres = pdev->resources[resourceColorSpace].chains[j];
3810
808k
            for (; pres != 0;) {
3811
7.09k
                free_color_space(pdev, pres);
3812
7.09k
                pres = pres->next;
3813
7.09k
            }
3814
801k
        }
3815
50.0k
    }
3816
3817
50.0k
    {
3818
50.0k
        int j;
3819
3820
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3821
801k
            pdf_resource_t *pres = pdev->resources[resourceGroup].chains[j];
3822
3823
801k
            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
801k
        }
3832
50.0k
    }
3833
3834
50.0k
    {
3835
50.0k
        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
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3842
801k
            pdf_resource_t *pnext = 0, *pres = pdev->resources[resourceFunction].chains[j];
3843
3844
807k
            for (; pres != 0;) {
3845
6.79k
                if (pres->object) {
3846
6.79k
                    free_function_refs(pdev, pres->object);
3847
6.79k
                }
3848
6.79k
                pnext = pres->next;
3849
6.79k
                pres = pnext;
3850
6.79k
            }
3851
801k
        }
3852
851k
        for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3853
801k
            pdf_resource_t *pnext = 0, *pres = pdev->resources[resourceFunction].chains[j];
3854
3855
807k
            for (; pres != 0;) {
3856
6.79k
                if (pres->object) {
3857
6.79k
                    cos_release(pres->object, "free function dict");
3858
6.79k
                    gs_free_object(pdev->pdf_memory, pres->object, "free function resources");
3859
6.79k
                    pres->object = 0;
3860
6.79k
                }
3861
6.79k
                pnext = pres->next;
3862
6.79k
                pres = pnext;
3863
6.79k
            }
3864
801k
        }
3865
50.0k
    }
3866
3867
    /* Free named objects. */
3868
3869
50.0k
    if (pdev->NI_stack != NULL) {
3870
50.0k
        cos_release((cos_object_t *)pdev->NI_stack, "Release Name Index stack");
3871
50.0k
        gs_free_object(mem, pdev->NI_stack, "Free Name Index stack");
3872
50.0k
        pdev->NI_stack = 0;
3873
50.0k
    }
3874
3875
50.0k
    if (pdev->local_named_objects != NULL) {
3876
50.0k
        cos_dict_objects_delete(pdev->local_named_objects);
3877
50.0k
        COS_FREE(pdev->local_named_objects, "pdf_close(local_named_objects)");
3878
50.0k
        pdev->local_named_objects = 0;
3879
50.0k
    }
3880
3881
50.0k
    if (pdev->global_named_objects != NULL) {
3882
        /* global resources include the Catalog object and apparently the Info dict */
3883
50.0k
        cos_dict_objects_delete(pdev->global_named_objects);
3884
50.0k
        COS_FREE(pdev->global_named_objects, "pdf_close(global_named_objects)");
3885
50.0k
        pdev->global_named_objects = 0;
3886
50.0k
    }
3887
3888
50.0k
    code1 = pdf_free_resource_objects(pdev, resourceOther);
3889
50.0k
    if (code >= 0)
3890
50.0k
        code = code1;
3891
3892
50.0k
    if (code >= 0) {
3893
50.0k
        int i, j;
3894
3895
851k
        for (i = 0; i < NUM_RESOURCE_TYPES; i++) {
3896
13.6M
            for (j = 0; j < NUM_RESOURCE_CHAINS; ++j) {
3897
12.8M
                pdev->resources[i].chains[j] = 0;
3898
12.8M
            }
3899
801k
        }
3900
50.0k
    }
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
50.0k
    {
3926
50.0k
        pdf_resource_t *pres;
3927
50.0k
        pdf_resource_t *prev;
3928
3929
502k
        for (prev = pdev->last_resource; (pres = prev) != 0;) {
3930
452k
            prev = pres->prev;
3931
452k
            gs_free_object(mem, pres, "pdf_resource_t");
3932
452k
        }
3933
50.0k
        pdev->last_resource = 0;
3934
50.0k
    }
3935
3936
    /* Wrap up. */
3937
3938
50.0k
    pdev->font_cache = 0;
3939
3940
50.0k
    if (pdev->pages != NULL)
3941
50.0k
    {
3942
50.0k
        int i;
3943
116k
        for (i=0;i < pdev->next_page;i++) {
3944
66.0k
            cos_release((cos_object_t *)pdev->pages[i].Page, "Free page dict");
3945
66.0k
            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
66.0k
            gs_free_object(mem, pdev->pages[i].Page, "Free Page object");
3950
66.0k
            pdev->pages[i].Page = NULL;
3951
66.0k
        }
3952
2.55M
        for (i=0;i < pdev->num_pages;i++) {
3953
2.50M
            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
2.50M
        }
3960
50.0k
    }
3961
50.0k
    gs_free_object(mem, pdev->pages, "pages");
3962
50.0k
    pdev->pages = 0;
3963
3964
50.0k
    pdev->num_pages = 0;
3965
3966
50.0k
    gs_free_object(mem, pdev->sbstack, "Free sbstack");
3967
50.0k
    pdev->sbstack = 0;
3968
3969
50.0k
    if (pdev->text != NULL)
3970
50.0k
        text_data_free(mem, pdev->text);
3971
50.0k
    pdev->text = 0;
3972
3973
50.0k
    if (pdev->Pages != NULL) {
3974
50.0k
        cos_release((cos_object_t *)pdev->Pages, "release Pages dict");
3975
50.0k
        gs_free_object(mem, pdev->Pages, "Free Pages dict");
3976
50.0k
        pdev->Pages = 0;
3977
50.0k
    }
3978
3979
50.0k
    if (pdev->vgstack != NULL)
3980
50.0k
    {
3981
50.0k
        int i;
3982
600k
        for (i=0;i < pdev->vgstack_size;i++) {
3983
550k
            if (pdev->vgstack[i].dash_pattern != NULL)
3984
379
                gs_free_object(pdev->memory->non_gc_memory, pdev->vgstack[i].dash_pattern, "pdfwrite final free stored dash in gstate");
3985
550k
        }
3986
50.0k
        gs_free_object(pdev->pdf_memory, pdev->vgstack, "pdf_close(graphics state stack)");
3987
50.0k
        pdev->vgstack = 0;
3988
50.0k
    }
3989
3990
50.0k
    if (pdev->Namespace_stack != NULL) {
3991
50.0k
        cos_release((cos_object_t *)pdev->Namespace_stack, "release Name space stack");
3992
50.0k
        gs_free_object(mem, pdev->Namespace_stack, "Free Name space stack");
3993
50.0k
        pdev->Namespace_stack = 0;
3994
50.0k
    }
3995
3996
50.0k
    pdev->Catalog = 0;
3997
50.0k
    pdev->Info = 0;
3998
3999
50.0k
    gs_free_object(mem, pdev->outline_levels, "outline_levels array");
4000
50.0k
    pdev->outline_levels = 0;
4001
50.0k
    pdev->outline_depth = -1;
4002
50.0k
    pdev->max_outline_depth = 0;
4003
4004
50.0k
    if (s != NULL)
4005
50.0k
    {
4006
        /* pdf_open_dcument could set up filters for entire document.
4007
           Removing them now. */
4008
50.0k
        int status;
4009
4010
50.0k
        if (!pdev->ProduceDSC)
4011
0
            stream_putc(s, 0x04);
4012
100k
        while (s->strm) {
4013
50.0k
            s = s->strm;
4014
50.0k
        }
4015
50.0k
        status = s_close_filters(&pdev->strm, s);
4016
50.0k
        if (status < 0 && code == 0)
4017
0
            code = gs_error_ioerror;
4018
50.0k
    }
4019
4020
50.0k
    pdf_free_pdf_font_cache(pdev);
4021
4022
50.0k
    code1 = gdev_vector_close_file((gx_device_vector *) pdev);
4023
50.0k
    if (code >= 0)
4024
50.0k
        code = code1;
4025
50.0k
    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
50.0k
    code = pdf_close_files(pdev, code);
4033
50.0k
    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
50.0k
    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
50.0k
    return code;
4049
50.0k
}