Coverage Report

Created: 2026-11-12 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/psi/imain.c
Line
Count
Source
1
/* Copyright (C) 2001-2026 Artifex Software, Inc.
2
   All Rights Reserved.
3
4
   This software is provided AS-IS with no warranty, either express or
5
   implied.
6
7
   This software is distributed under license and may not be copied,
8
   modified or distributed except as expressly authorized under the terms
9
   of the license contained in the file LICENSE in this distribution.
10
11
   Refer to licensing information at http://www.artifex.com or contact
12
   Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
13
   CA 94129, USA, for further information.
14
*/
15
16
17
/* Common support for interpreter front ends */
18
19
20
#include "malloc_.h"
21
#include "memory_.h"
22
#include "string_.h"
23
#include "ghost.h"
24
#include "gp.h"
25
#include "gscdefs.h"            /* for gs_init_file */
26
#include "gslib.h"
27
#include "gsmatrix.h"           /* for gxdevice.h */
28
#include "gsutil.h"             /* for bytes_compare */
29
#include "gspaint.h"    /* for gs_erasepage */
30
#include "gxdevice.h"
31
#include "gxdevsop.h"   /* for gxdso_* enums */
32
#include "gxclpage.h"
33
#include "gdevprn.h"
34
#include "gxalloc.h"
35
#include "gxiodev.h"            /* for iodev struct */
36
#include "gzstate.h"
37
#include "ierrors.h"
38
#include "oper.h"
39
#include "iconf.h"              /* for gs_init_* imports */
40
#include "idebug.h"
41
#include "iddict.h"
42
#include "iname.h"              /* for name_init */
43
#include "dstack.h"
44
#include "estack.h"
45
#include "ostack.h"             /* put here for files.h */
46
#include "stream.h"             /* for files.h */
47
#include "files.h"
48
#include "ialloc.h"
49
#include "iinit.h"
50
#include "strimpl.h"            /* for sfilter.h */
51
#include "sfilter.h"            /* for iscan.h */
52
#include "iscan.h"
53
#include "main.h"
54
#include "store.h"
55
#include "isave.h"              /* for prototypes */
56
#include "interp.h"
57
#include "ivmspace.h"
58
#include "idisp.h"              /* for setting display device callback */
59
#include "iplugin.h"
60
#include "zfile.h"
61
62
#include "valgrind.h"
63
64
/* ------ Exported data ------ */
65
66
/** using backpointers retrieve minst from any memory pointer
67
 *
68
 */
69
gs_main_instance*
70
get_minst_from_memory(const gs_memory_t *mem)
71
396M
{
72
396M
    return (gs_main_instance*)mem->gs_lib_ctx->top_of_system;
73
396M
}
74
75
/** construct main instance caller needs to retain */
76
gs_main_instance *
77
gs_main_alloc_instance(gs_memory_t *mem)
78
166k
{
79
166k
    gs_main_instance *minst;
80
166k
    if (mem == NULL)
81
0
        return NULL;
82
83
166k
    minst = (gs_main_instance *)gs_alloc_bytes_immovable(mem,
84
166k
                                                         sizeof(gs_main_instance),
85
166k
                                                         "init_main_instance");
86
166k
    if (minst == NULL)
87
0
        return NULL;
88
166k
    memset(minst, 0, sizeof(gs_main_instance));
89
166k
    memcpy(minst, &gs_main_instance_init_values, sizeof(gs_main_instance_init_values));
90
166k
    minst->heap = mem;
91
166k
    mem->gs_lib_ctx->top_of_system = minst;
92
166k
    return minst;
93
166k
}
94
95
op_array_table *
96
get_op_array(const gs_memory_t *mem, int size)
97
250M
{
98
250M
    gs_main_instance *minst = get_minst_from_memory(mem);
99
250M
    return op_index_op_array_table(minst->i_ctx_p,size);
100
250M
}
101
102
op_array_table *
103
get_global_op_array(const gs_memory_t *mem)
104
332k
{
105
332k
    gs_main_instance *minst = get_minst_from_memory(mem);
106
332k
    return &minst->i_ctx_p->op_array_table_global;
107
332k
}
108
109
op_array_table *
110
get_local_op_array(const gs_memory_t *mem)
111
332k
{
112
332k
    gs_main_instance *minst = get_minst_from_memory(mem);
113
332k
    return &minst->i_ctx_p->op_array_table_local;
114
332k
}
115
116
/* ------ Forward references ------ */
117
118
static int gs_run_init_file(gs_main_instance *, int *, ref *);
119
void print_resource_usage(const gs_main_instance *,
120
                                  gs_dual_memory_t *, const char *);
121
122
/* ------ Initialization ------ */
123
124
/* Initialization to be done before anything else. */
125
int
126
gs_main_init0(gs_main_instance * minst, gp_file * in, gp_file * out, gp_file * err,
127
              int max_lib_paths)
128
166k
{
129
166k
    ref *array;
130
166k
    int code = 0;
131
132
166k
    if (gs_debug_c(gs_debug_flag_init_details))
133
166k
        dmprintf1(minst->heap, "%% Init phase 0 started, instance "PRI_INTPTR"\n",
134
166k
                  (intptr_t)minst);
135
136
    /* Do platform-dependent initialization. */
137
    /* We have to do this as the very first thing, */
138
    /* because it detects attempts to run 80N86 executables (N>0) */
139
    /* on incompatible processors. */
140
166k
    gp_init();
141
142
    /* Initialize the imager. */
143
144
    /* Reset debugging flags */
145
166k
#ifdef PACIFY_VALGRIND
146
166k
    VALGRIND_HG_DISABLE_CHECKING(gs_debug, 128);
147
166k
#endif
148
166k
    memset(gs_debug, 0, 128);
149
166k
    gs_log_errors = 0;  /* gs_debug['#'] = 0 */
150
151
166k
    gp_get_realtime(minst->base_time);
152
153
    /* Initialize the file search paths. */
154
166k
    array = (ref *) gs_alloc_byte_array(minst->heap, max_lib_paths, sizeof(ref),
155
166k
                                        "lib_path array");
156
166k
    if (array == 0) {
157
0
        gs_lib_finit(1, gs_error_VMerror, minst->heap);
158
0
        code = gs_note_error(gs_error_VMerror);
159
0
        goto fail;
160
0
    }
161
166k
    make_array(&minst->lib_path.container, avm_foreign, max_lib_paths,
162
166k
               array);
163
166k
    make_array(&minst->lib_path.list, avm_foreign | a_readonly, 0,
164
166k
               minst->lib_path.container.value.refs);
165
166k
    minst->lib_path.env = NULL;
166
166k
    minst->lib_path.final = NULL;
167
166k
    minst->lib_path.count = 0;
168
166k
    minst->lib_path.first_is_current = 0;
169
166k
    minst->user_errors = 1;
170
166k
    minst->init_done = 0;
171
172
166k
fail:
173
166k
    if (gs_debug_c(gs_debug_flag_init_details))
174
166k
        dmprintf2(minst->heap, "%% Init phase 0 %s, instance "PRI_INTPTR"\n",
175
166k
                  code < 0 ? "failed" : "done", (intptr_t)minst);
176
177
166k
    return code;
178
166k
}
179
180
/* Initialization to be done before constructing any objects. */
181
int
182
gs_main_init1(gs_main_instance * minst)
183
2.66M
{
184
2.66M
    gs_dual_memory_t idmem;
185
2.66M
    name_table *nt = NULL;
186
2.66M
    int code;
187
188
2.66M
    if (minst->init_done >= 1)
189
2.49M
        return 0;
190
191
166k
    if (gs_debug_c(gs_debug_flag_init_details))
192
166k
        dmprintf1(minst->heap, "%% Init phase 1 started, instance "PRI_INTPTR"\n",
193
166k
                  (intptr_t)minst);
194
195
166k
    code = ialloc_init(&idmem, minst->heap,
196
166k
                       minst->memory_clump_size, gs_have_level2());
197
198
166k
    if (code < 0)
199
0
        goto fail_early;
200
201
166k
    code = gs_lib_init1((gs_memory_t *)idmem.space_system);
202
166k
    if (code < 0)
203
0
        goto fail;
204
166k
    alloc_save_init(&idmem);
205
166k
    {
206
166k
        gs_memory_t *mem = (gs_memory_t *)idmem.space_system;
207
166k
        nt = names_init(minst->name_table_size, idmem.space_system);
208
209
166k
        if (nt == 0) {
210
0
            code = gs_note_error(gs_error_VMerror);
211
0
            goto fail;
212
0
        }
213
166k
        mem->gs_lib_ctx->gs_name_table = nt;
214
166k
        code = gs_register_struct_root(mem, &mem->gs_lib_ctx->name_table_root,
215
166k
                                       (void **)&mem->gs_lib_ctx->gs_name_table,
216
166k
                                       "the_gs_name_table");
217
166k
        if (code < 0)
218
0
            goto fail;
219
166k
    }
220
166k
    code = obj_init(&minst->i_ctx_p, &idmem);  /* requires name_init */
221
166k
    if (code < 0)
222
0
        goto fail;
223
166k
    minst->init_done = 1;
224
166k
    code = i_plugin_init(minst->i_ctx_p);
225
166k
    if (code < 0)
226
0
        goto fail;
227
166k
    code = i_iodev_init(&idmem);
228
166k
    if (code < 0) {
229
0
fail:
230
0
        names_free(nt);
231
0
        if (minst->i_ctx_p == NULL)
232
0
            ialloc_finit(&idmem);
233
0
    }
234
166k
fail_early:
235
236
166k
    if (gs_debug_c(gs_debug_flag_init_details))
237
166k
        dmprintf2(minst->heap, "%% Init phase 1 %s, instance "PRI_INTPTR"\n",
238
166k
                  code < 0 ? "failed" : "done", (intptr_t)minst);
239
240
166k
    return code;
241
166k
}
242
243
/*
244
 * Invoke the interpreter. This layer doesn't do much (previously stdio
245
 * callouts were handled here instead of in the stream processing.
246
 */
247
static int
248
gs_main_interpret(gs_main_instance *minst, ref * pref, int user_errors,
249
                  int *pexit_code, ref * perror_object)
250
2.95M
{
251
2.95M
    int code;
252
253
    /* set interpreter pointer to lib_path */
254
2.95M
    minst->i_ctx_p->lib_path = &minst->lib_path;
255
256
2.95M
    code = gs_interpret(&minst->i_ctx_p, pref,
257
2.95M
                        user_errors, pexit_code, perror_object);
258
2.95M
    return code;
259
2.95M
}
260
261
/* gcc wants prototypes for all external functions. */
262
int gs_main_init2aux(gs_main_instance * minst);
263
264
static const op_array_table empty_table = { { { 0 } } };
265
266
/* This is an external function to work around      */
267
/* a bug in gcc 4.5.1 optimizer. See bug 692684.    */
268
166k
int gs_main_init2aux(gs_main_instance * minst) {
269
166k
    i_ctx_t * i_ctx_p = minst->i_ctx_p;
270
271
166k
    if (minst->init_done < 2) {
272
166k
        int code, exit_code;
273
166k
        ref error_object, ifa;
274
275
        /* Set up enough so that we can safely be garbage collected */
276
166k
        i_ctx_p->op_array_table_global = empty_table;
277
166k
        i_ctx_p->op_array_table_local = empty_table;
278
279
166k
        code = zop_init(i_ctx_p);
280
166k
        if (code < 0)
281
0
            return code;
282
166k
        code = op_init(i_ctx_p);        /* requires obj_init */
283
166k
        if (code < 0)
284
0
            return code;
285
286
        /* Set up the array of additional initialization files. */
287
166k
        make_const_string(&ifa, a_readonly | avm_foreign, gs_init_files_sizeof - 2, gs_init_files);
288
166k
        code = i_initial_enter_name(i_ctx_p, "INITFILES", &ifa);
289
166k
        if (code < 0)
290
0
            return code;
291
292
        /* Set up the array of emulator names. */
293
166k
        make_const_string(&ifa, a_readonly | avm_foreign, gs_emulators_sizeof - 2, gs_emulators);
294
166k
        code = i_initial_enter_name(i_ctx_p, "EMULATORS", &ifa);
295
166k
        if (code < 0)
296
0
            return code;
297
298
        /* Pass the search path. */
299
166k
        code = i_initial_enter_name(i_ctx_p, "LIBPATH", &minst->lib_path.list);
300
166k
        if (code < 0)
301
0
            return code;
302
303
        /* Execute the standard initialization file. */
304
166k
        code = gs_run_init_file(minst, &exit_code, &error_object);
305
166k
        if (code < 0)
306
409
            return code;
307
166k
        minst->init_done = 2;
308
309
        /* NB this is to be done with device parameters
310
         * both minst->display and  display_set_callback() are going away
311
        */
312
166k
        if ((code = reopen_device_if_required(minst)) < 0)
313
0
            return code;
314
315
166k
        if ((code = gs_main_run_string(minst,
316
166k
                "JOBSERVER "
317
166k
                " { false 0 .startnewjob } "
318
166k
                " { NOOUTERSAVE not { save pop } if } "
319
166k
                "ifelse", 0, &exit_code,
320
166k
                &error_object)) < 0)
321
0
           return code;
322
166k
    }
323
166k
    return 0;
324
166k
}
325
326
int
327
gs_main_set_language_param(gs_main_instance *minst,
328
                           gs_param_list    *plist)
329
73.9k
{
330
73.9k
    ref value;
331
73.9k
    int code = 0;
332
73.9k
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
333
73.9k
    uint space = icurrent_space;
334
73.9k
    gs_param_enumerator_t enumerator;
335
73.9k
    gs_param_key_t key;
336
73.9k
    gs_lib_ctx_t *ctx = minst->heap->gs_lib_ctx;
337
73.9k
    ref error_object;
338
339
    /* If we're up and running as a jobserver, exit encapsulation. */
340
73.9k
    if (minst->init_done > 1) {
341
128
        code = gs_main_run_string(minst,
342
128
                                  "JOBSERVER {true 0 startjob pop} if",
343
128
                                  0, &code, &error_object);
344
128
        if (code < 0) return code;
345
128
    }
346
347
73.9k
    ialloc_set_space(idmemory, avm_system);
348
349
73.9k
    param_init_enumerator(&enumerator);
350
258k
    while ((code = param_get_next_key(plist, &enumerator, &key)) == 0) {
351
184k
        char string_key[256]; /* big enough for any reasonable key */
352
184k
        gs_param_typed_value pvalue;
353
354
184k
        if (key.size > sizeof(string_key) - 1) {
355
0
            code = gs_note_error(gs_error_rangecheck);
356
0
            break;
357
0
        }
358
184k
        memcpy(string_key, key.data, key.size);
359
184k
        string_key[key.size] = 0;
360
184k
        if ((code = param_read_typed(plist, string_key, &pvalue)) != 0) {
361
0
            code = (code > 0 ? gs_note_error(gs_error_unknownerror) : code);
362
0
            break;
363
0
        }
364
184k
        switch (pvalue.type) {
365
0
        case gs_param_type_null:
366
0
            make_null(&value);
367
0
            break;
368
166k
        case gs_param_type_bool:
369
166k
            if (pvalue.value.b)
370
166k
                make_true(&value);
371
0
            else
372
166k
                make_false(&value);
373
166k
            break;
374
0
        case gs_param_type_int:
375
0
            make_int(&value, (ps_int)pvalue.value.i);
376
0
            break;
377
0
        case gs_param_type_i64:
378
0
            make_int(&value, (ps_int)pvalue.value.i64);
379
0
            break;
380
0
        case gs_param_type_long:
381
0
            make_int(&value, (ps_int)pvalue.value.l);
382
0
            break;
383
0
        case gs_param_type_size_t:
384
0
            make_int(&value, (ps_int)pvalue.value.z);
385
0
            break;
386
0
        case gs_param_type_float:
387
0
            make_real(&value, pvalue.value.f);
388
0
            break;
389
0
        case gs_param_type_dict:
390
            /* We don't support dicts for now */
391
0
            continue;
392
0
        case gs_param_type_dict_int_keys:
393
            /* We don't support dicts with int keys for now */
394
0
            continue;
395
0
        case gs_param_type_array:
396
            /* We don't support arrays for now */
397
0
            continue;
398
18.4k
        case gs_param_type_string:
399
18.4k
            if (pvalue.value.s.data == NULL || pvalue.value.s.size == 0)
400
18.4k
                make_empty_string(&value, a_readonly);
401
18.4k
            else {
402
18.4k
                size_t len = pvalue.value.s.size;
403
18.4k
                byte *body = ialloc_string(len, "-s");
404
405
18.4k
                if (body == NULL)
406
0
                    return gs_error_Fatal;
407
18.4k
                memcpy(body, pvalue.value.s.data, len);
408
18.4k
                make_const_string(&value, a_readonly | avm_system, len, body);
409
18.4k
            }
410
18.4k
            break;
411
18.4k
        case gs_param_type_name:
412
0
            code = name_ref(ctx->memory, pvalue.value.n.data, pvalue.value.n.size, &value, 1);
413
0
            break;
414
0
        case gs_param_type_int_array:
415
            /* We don't support arrays for now */
416
0
            continue;
417
41
        case gs_param_type_float_array:
418
            /* We don't support arrays for now */
419
41
            continue;
420
0
        case gs_param_type_string_array:
421
            /* We don't support arrays for now */
422
0
            continue;
423
0
        default:
424
0
            continue;
425
184k
        }
426
184k
        if (code < 0)
427
0
            break;
428
429
184k
        ialloc_set_space(idmemory, space);
430
        /* Enter the name in systemdict. */
431
184k
        i_initial_enter_name_copy(minst->i_ctx_p, string_key, &value);
432
184k
    }
433
434
73.9k
    if (minst->init_done > 1) {
435
128
        int code2 = 0;
436
128
        code2 = gs_main_run_string(minst,
437
128
                                   "JOBSERVER {false 0 startjob pop} if",
438
128
                                   0, &code2, &error_object);
439
128
        if (code >= 0)
440
128
            code = code2;
441
128
    }
442
443
73.9k
    return code;
444
73.9k
}
445
446
static int
447
gs_main_push_params(gs_main_instance *minst)
448
274k
{
449
274k
    int code;
450
274k
    gs_c_param_list *plist;
451
452
274k
    plist = minst->param_list;
453
274k
    if (!plist)
454
274k
        return 0;
455
456
0
    code = gs_putdeviceparams(minst->i_ctx_p->pgs->device,
457
0
                              (gs_param_list *)plist);
458
0
    if (code < 0)
459
0
        return code;
460
461
0
    code = gs_main_set_language_param(minst, (gs_param_list *)plist);
462
0
    if (code < 0)
463
0
        return code;
464
465
0
    gs_c_param_list_release(plist);
466
467
0
    return code;
468
0
}
469
470
int
471
gs_main_init2(gs_main_instance * minst)
472
274k
{
473
274k
    i_ctx_t *i_ctx_p;
474
274k
    int code = gs_main_init1(minst);
475
476
274k
    if (code < 0)
477
0
        return code;
478
479
274k
    code = gs_main_push_params(minst);
480
274k
    if (code < 0)
481
0
        return code;
482
483
274k
    if (minst->init_done >= 2)
484
107k
        return 0;
485
486
166k
    if (gs_debug_c(gs_debug_flag_init_details))
487
166k
        dmprintf1(minst->heap, "%% Init phase 2 started, instance "PRI_INTPTR"\n",
488
166k
                  (intptr_t)minst);
489
490
166k
    code = gs_main_init2aux(minst);
491
166k
    if (code < 0)
492
409
       goto fail;
493
494
166k
    i_ctx_p = minst->i_ctx_p; /* reopen_device_if_display or run_string may change it */
495
496
    /* Now process the initial saved-pages=... argument, if any as well as saved-pages-test */
497
166k
    {
498
166k
       gx_device *pdev = gs_currentdevice(minst->i_ctx_p->pgs); /* get the current device */
499
166k
       gx_device_printer *ppdev = (gx_device_printer *)pdev;
500
501
166k
        if (minst->saved_pages_test_mode) {
502
0
            if ((dev_proc(pdev, dev_spec_op)(pdev, gxdso_supports_saved_pages, NULL, 0) <= 0)) {
503
                /* no warning or error if saved-pages-test mode is used, just disable it */
504
0
                minst->saved_pages_test_mode = false;  /* device doesn't support it */
505
0
            } else {
506
0
                if ((code = gx_saved_pages_param_process(ppdev, (byte *)"begin", 5)) < 0)
507
0
                    goto fail;
508
0
                if (code > 0)
509
0
                    if ((code = gs_erasepage(minst->i_ctx_p->pgs)) < 0)
510
0
                        goto fail;
511
0
            }
512
166k
        } else if (minst->saved_pages_initial_arg != NULL) {
513
0
            if (dev_proc(pdev, dev_spec_op)(pdev, gxdso_supports_saved_pages, NULL, 0) <= 0) {
514
0
                while (pdev->child)
515
0
                    pdev = pdev->child;   /* so we get the real device name */
516
0
                outprintf(minst->heap,
517
0
                          "   --saved-pages not supported by the '%s' device.\n",
518
0
                          pdev->dname);
519
0
                code = gs_error_Fatal;
520
0
                goto fail;
521
0
            }
522
0
            code = gx_saved_pages_param_process(ppdev, (byte *)minst->saved_pages_initial_arg,
523
0
                                                strlen(minst->saved_pages_initial_arg));
524
0
            if (code > 0)
525
0
                if ((code = gs_erasepage(minst->i_ctx_p->pgs)) < 0)
526
0
                    goto fail;
527
0
        }
528
166k
    }
529
530
166k
    if (code >= 0) {
531
166k
        if (gs_debug_c(':'))
532
0
            print_resource_usage(minst, i_ctx_p ? &gs_imemory : NULL, "Start");
533
166k
        gp_readline_init(&minst->readline_data, minst->heap); /* lgtm [cpp/useless-expression] */
534
166k
    }
535
536
166k
fail:
537
166k
    if (gs_debug_c(gs_debug_flag_init_details))
538
166k
        dmprintf2(minst->heap, "%% Init phase 2 %s, instance "PRI_INTPTR"\n",
539
166k
                  code < 0 ? "failed" : "done", (intptr_t)minst);
540
541
166k
    return code;
542
166k
}
543
544
/* ------ Search paths ------ */
545
546
#define LIB_PATH_EXTEND 5
547
548
/* If the existing array is full, extend it */
549
static int
550
extend_path_list_container (gs_main_instance * minst, gs_file_path * pfp)
551
0
{
552
0
    uint len = r_size(&minst->lib_path.container);
553
0
    ref *paths, *opaths = minst->lib_path.container.value.refs;
554
555
    /* Add 5 entries at a time to reduce VM thrashing */
556
0
    paths = (ref *) gs_alloc_byte_array(minst->heap, len + LIB_PATH_EXTEND, sizeof(ref),
557
0
                                        "extend_path_list_container array");
558
559
0
    if (paths == 0) {
560
0
        return_error(gs_error_VMerror);
561
0
    }
562
0
    make_array(&minst->lib_path.container, avm_foreign, len + LIB_PATH_EXTEND, paths);
563
0
    make_array(&minst->lib_path.list, avm_foreign | a_readonly, 0,
564
0
               minst->lib_path.container.value.refs);
565
566
0
    memcpy(paths, opaths, len * sizeof(ref));
567
0
    r_set_size(&minst->lib_path.list, len);
568
569
0
    gs_free_object (minst->heap, opaths, "extend_path_list_container");
570
0
    return(0);
571
0
}
572
573
static int
574
lib_path_insert_copy_of_string(gs_main_instance *minst, int pos, size_t strlen, const char *str)
575
19.2M
{
576
19.2M
    ref *paths;
577
19.2M
    int listlen = r_size(&minst->lib_path.list); /* The real number of entries currently in the list */
578
19.2M
    byte *newstr;
579
19.2M
    int code;
580
581
    /* Extend the container if required */
582
19.2M
    if (listlen == r_size(&minst->lib_path.container)) {
583
0
        code = extend_path_list_container(minst, &minst->lib_path);
584
0
        if (code < 0) {
585
0
            emprintf(minst->heap, "\nAdding path to search paths failed.\n");
586
0
            return(code);
587
0
        }
588
0
    }
589
590
    /* Copy the string */
591
19.2M
    newstr = gs_alloc_string(minst->heap, strlen, "lib_path_add");
592
19.2M
    if (newstr == NULL)
593
0
        return gs_error_VMerror;
594
19.2M
    memcpy(newstr, str, strlen);
595
596
    /* Shuffle up the entries */
597
19.2M
    paths = &minst->lib_path.container.value.refs[pos];
598
19.2M
    if (pos != listlen)
599
0
        memmove(paths + 1, paths, (listlen-pos) * sizeof(*paths));
600
601
    /* And insert the new string, converted to a PS thing */
602
19.2M
    make_const_string(paths, avm_foreign | a_readonly,
603
19.2M
                      strlen,
604
19.2M
                      newstr);
605
606
    /* Update the list length */
607
19.2M
    r_set_size(&minst->lib_path.list, listlen+1);
608
609
19.2M
    return 0;
610
19.2M
}
611
612
/* Internal routine to add a set of directories to a search list. */
613
/* Returns 0 or an error code. */
614
615
static int
616
lib_path_add(gs_main_instance * minst, const char *dirs)
617
4.45M
{
618
4.45M
    gs_file_path * pfp = &minst->lib_path;
619
4.45M
    uint len = r_size(&pfp->list);
620
4.45M
    const char *dpath = dirs;
621
4.45M
    int code;
622
623
4.45M
    if (dirs == 0)
624
0
        return 0;
625
626
19.2M
    for (;;) {                  /* Find the end of the next directory name. */
627
19.2M
        const char *npath = dpath;
628
629
662M
        while (*npath != 0 && *npath != gp_file_name_list_separator)
630
642M
            npath++;
631
19.2M
        if (npath > dpath) {
632
19.2M
            code = gs_add_control_path_len(minst->heap, gs_permit_file_reading, dpath, npath - dpath);
633
19.2M
            if (code < 0) return code;
634
635
19.2M
            code = lib_path_insert_copy_of_string(minst, len, npath - dpath, dpath);
636
19.2M
            if (code < 0)
637
0
                return code;
638
19.2M
            len++;
639
            /* Update length/count so we don't lose entries if a later
640
             * iteration fails. */
641
19.2M
            r_set_size(&pfp->list, len);
642
19.2M
        }
643
19.2M
        if (!*npath)
644
4.45M
            break;
645
14.8M
        dpath = npath + 1;
646
14.8M
    }
647
4.45M
    return 0;
648
4.45M
}
649
650
static void
651
set_lib_path_length(gs_main_instance * minst, int newsize)
652
1.65M
{
653
1.65M
    gs_file_path * pfp = &minst->lib_path;
654
1.65M
    uint len = r_size(&pfp->list); /* Yes, list, not container */
655
1.65M
    uint i;
656
657
    /* Free any entries that are discarded by us shortening the list */
658
20.9M
    for (i = newsize; i < len; i++)
659
19.2M
        gs_free_object(minst->heap, pfp->container.value.refs[i].value.bytes, "lib_path entry");
660
1.65M
    r_set_size(&pfp->list, newsize);
661
1.65M
}
662
663
/* Add a library search path to the list. */
664
int
665
gs_main_add_lib_path(gs_main_instance * minst, const char *lpath)
666
0
{
667
0
    gs_file_path * pfp = &minst->lib_path;
668
0
    int code;
669
670
    /* Throw away all the elements after the user ones. */
671
0
    set_lib_path_length(minst, pfp->count + pfp->first_is_current);
672
673
    /* Now add the new one */
674
0
    code = lib_path_add(minst, lpath);
675
0
    if (code < 0)
676
0
        return code;
677
678
    /* Update the count of user paths */
679
0
    pfp->count = r_size(&pfp->list) - pfp->first_is_current;
680
681
    /* Now add back in the others */
682
0
    return gs_main_set_lib_paths(minst);
683
0
}
684
685
/* ------ Execution ------ */
686
687
extern_gx_io_device_table();
688
689
/* Complete the list of library search paths. */
690
/* This may involve adding the %rom%Resource/Init and %rom%lib/ paths (for COMPILE_INITS) */
691
/* and adding or removing the current directory as the first element (for -P and -P-). */
692
int
693
gs_main_set_lib_paths(gs_main_instance * minst)
694
1.48M
{
695
1.48M
    int code = 0;
696
1.48M
    int i, have_rom_device = 0;
697
698
    /* We are entered with a list potentially full of stuff already.
699
     * In general the list is of the form:
700
     *    <optionally, the current directory>
701
     *    <any -I specified directories, "count" of them>
702
     *    <any directories from the environment variable>
703
     *    <if there is a romfs, the romfs paths>
704
     *    <any directories from the 'final' variable>
705
     *
706
     * Unfortunately, the value read from the environment variable may not
707
     * have actually been read the first time this function is called, so
708
     * we can see the value change over time. Short of a complete rewrite
709
     * this requires us to clear the latter part of the list and repopulate
710
     * it each time we run through.
711
     */
712
713
    /* First step, ensure that we have the current directory as our
714
     * first entry, iff we need it. */
715
1.48M
    if (minst->search_here_first && !minst->lib_path.first_is_current) {
716
        /* We should have a "gp_current_directory" at the start, and we haven't.
717
         * So insert one. */
718
719
0
        code = gs_add_control_path_len(minst->heap, gs_permit_file_reading,
720
0
                gp_current_directory_name, strlen(gp_current_directory_name));
721
0
        if (code < 0) return code;
722
723
0
        code = lib_path_insert_copy_of_string(minst, 0,
724
0
                                              strlen(gp_current_directory_name),
725
0
                                              gp_current_directory_name);
726
0
        if (code < 0)
727
0
            return code;
728
1.48M
    } else if (!minst->search_here_first && minst->lib_path.first_is_current) {
729
        /* We have a "gp_current_directory" at the start, and we shouldn't have.
730
         * Remove it. */
731
0
        int listlen = r_size(&minst->lib_path.list); /* The real number of entries currently in the list */
732
0
        ref *paths = minst->lib_path.container.value.refs;
733
734
0
        gs_free_object(minst->heap, paths->value.bytes, "lib_path entry");
735
0
        --listlen;
736
0
        memmove(paths, paths + 1, listlen * sizeof(*paths));
737
0
        r_set_size(&minst->lib_path.list, listlen);
738
739
0
        code = gs_remove_control_path_len(minst->heap, gs_permit_file_reading,
740
0
                gp_current_directory_name, strlen(gp_current_directory_name));
741
0
        if (code < 0) return code;
742
0
    }
743
1.48M
    minst->lib_path.first_is_current = minst->search_here_first;
744
745
    /* Now, the horrid bit. We throw away all the entries after the user entries */
746
1.48M
    set_lib_path_length(minst, minst->lib_path.count + minst->lib_path.first_is_current);
747
748
    /* Now we (re)populate the end of the list. */
749
1.48M
    if (minst->lib_path.env != 0) {
750
0
        code = lib_path_add(minst, minst->lib_path.env);
751
0
        if (code < 0) return code;
752
753
0
        code = gs_add_control_path(minst->heap, gs_permit_file_reading, minst->lib_path.env);
754
0
        if (code < 0) return code;
755
0
    }
756
    /* now put the %rom%lib/ device path before the gs_lib_default_path on the list */
757
10.3M
    for (i = 0; i < gx_io_device_table_count; i++) {
758
10.3M
        const gx_io_device *iodev = gx_io_device_table[i];
759
10.3M
        const char *dname = iodev->dname;
760
10.3M
        const char *fcheckname = "Resource/Init/gs_init.ps";
761
762
10.3M
        if (dname && strlen(dname) == 5 && !memcmp("%rom%", dname, 5)) {
763
1.48M
            struct stat pstat;
764
            /* gs_error_unregistered means no usable romfs is available */
765
            /* gpdl always includes a real romfs, but it may or may have the Postscript
766
               resources in it, so we explicitly check for a fairly vital file
767
             */
768
1.48M
            int code = iodev->procs.file_status((gx_io_device *)iodev, fcheckname, &pstat);
769
1.48M
            if (code != gs_error_unregistered && code != gs_error_undefinedfilename){
770
1.48M
                have_rom_device = 1;
771
1.48M
            }
772
1.48M
            break;
773
1.48M
        }
774
10.3M
    }
775
1.48M
    if (have_rom_device) {
776
1.48M
        code = lib_path_add(minst, "%rom%Resource/Init/");
777
1.48M
        if (code < 0)
778
0
            return code;
779
1.48M
        code = lib_path_add(minst, "%rom%lib/");
780
1.48M
    }
781
0
    else code = 0;
782
783
1.48M
    if (minst->lib_path.final != NULL && code >= 0)
784
1.48M
        code = lib_path_add(minst, minst->lib_path.final);
785
1.48M
    return code;
786
1.48M
}
787
788
/* Open a file, using the search paths. */
789
int
790
gs_main_lib_open(gs_main_instance * minst, const char *file_name, ref * pfile)
791
166k
{
792
    /* This is a separate procedure only to avoid tying up */
793
    /* extra stack space while running the file. */
794
166k
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
795
166k
#define maxfn 2048
796
166k
    char fn[maxfn];
797
166k
    uint len;
798
799
166k
    return lib_file_open(&minst->lib_path, imemory,
800
166k
                         NULL, /* Don't check permissions here, because permlist
801
                                  isn't ready running init files. */
802
166k
                          file_name, strlen(file_name), fn, maxfn, &len, pfile);
803
166k
}
804
805
/* Open and execute a file. */
806
int
807
gs_main_run_file(gs_main_instance * minst, const char *file_name, int user_errors, int *pexit_code, ref * perror_object)
808
0
{
809
0
    ref initial_file;
810
0
    int code = gs_main_run_file_open(minst, file_name, &initial_file);
811
812
0
    if (code < 0)
813
0
        return code;
814
0
    return gs_main_interpret(minst, &initial_file, user_errors,
815
0
                        pexit_code, perror_object);
816
0
}
817
int
818
gs_main_run_file_open(gs_main_instance * minst, const char *file_name, ref * pfref)
819
166k
{
820
166k
    gs_main_set_lib_paths(minst);
821
166k
    if (gs_main_lib_open(minst, file_name, pfref) < 0) {
822
0
        emprintf1(minst->heap,
823
0
                  "Can't find initialization file %s.\n",
824
0
                  file_name);
825
0
        return_error(gs_error_Fatal);
826
0
    }
827
166k
    r_set_attrs(pfref, a_execute + a_executable);
828
166k
    return 0;
829
166k
}
830
831
/* Open and run the very first initialization file. */
832
static int
833
gs_run_init_file(gs_main_instance * minst, int *pexit_code, ref * perror_object)
834
166k
{
835
166k
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
836
166k
    ref ifile;
837
166k
    ref first_token;
838
166k
    int code;
839
166k
    scanner_state state;
840
841
166k
    gs_main_set_lib_paths(minst);
842
166k
    code = gs_main_run_file_open(minst, gs_init_file, &ifile);
843
166k
    if (code < 0) {
844
0
        *pexit_code = 255;
845
0
        return code;
846
0
    }
847
    /* Check to make sure the first token is an integer */
848
    /* (for the version number check.) */
849
166k
    gs_scanner_init(&state, &ifile);
850
166k
    code = gs_scan_token(i_ctx_p, &first_token, &state);
851
166k
    if (code != 0 || !r_has_type(&first_token, t_integer)) {
852
0
        emprintf1(minst->heap,
853
0
                  "Initialization file %s does not begin with an integer.\n",
854
0
                  gs_init_file);
855
0
        *pexit_code = 255;
856
0
        return_error(gs_error_Fatal);
857
0
    }
858
166k
    *++osp = first_token;
859
166k
    r_set_attrs(&ifile, a_executable);
860
166k
    return gs_main_interpret(minst, &ifile, minst->user_errors,
861
166k
                        pexit_code, perror_object);
862
166k
}
863
864
/* Run a string. */
865
int
866
gs_main_run_string(gs_main_instance * minst, const char *str, int user_errors,
867
                   int *pexit_code, ref * perror_object)
868
984k
{
869
984k
    return gs_main_run_string_with_length(minst, str, (uint) strlen(str),
870
984k
                                          user_errors,
871
984k
                                          pexit_code, perror_object);
872
984k
}
873
int
874
gs_main_run_string_with_length(gs_main_instance * minst, const char *str,
875
         uint length, int user_errors, int *pexit_code, ref * perror_object)
876
984k
{
877
984k
    int code;
878
879
984k
    code = gs_main_run_string_begin(minst, user_errors,
880
984k
                                    pexit_code, perror_object);
881
984k
    if (code < 0)
882
0
        return code;
883
984k
    code = gs_main_run_string_continue(minst, str, length, user_errors,
884
984k
                                       pexit_code, perror_object);
885
984k
    if (code != gs_error_NeedInput)
886
166k
        return code;
887
888
818k
    code = gs_main_run_string_end(minst, user_errors,
889
818k
                                  pexit_code, perror_object);
890
    /* Not okay for user to use .needinput
891
     * This treats it as a fatal error.
892
     */
893
818k
    if (code == gs_error_NeedInput)
894
32
        return_error(gs_error_Fatal);
895
818k
    return code;
896
818k
}
897
898
/* Set up for a suspendable run_string. */
899
int
900
gs_main_run_string_begin(gs_main_instance * minst, int user_errors,
901
                         int *pexit_code, ref * perror_object)
902
984k
{
903
984k
    const char *setup = ".runstringbegin";
904
984k
    ref rstr;
905
984k
    int code;
906
907
984k
    gs_main_set_lib_paths(minst);
908
984k
    make_const_string(&rstr, avm_foreign | a_readonly | a_executable,
909
984k
                      strlen(setup), (const byte *)setup);
910
984k
    code = gs_main_interpret(minst, &rstr, user_errors, pexit_code,
911
984k
                             perror_object);
912
984k
    return (code == gs_error_NeedInput ? 0 : code == 0 ? gs_error_Fatal : code);
913
984k
}
914
/* Continue running a string with the option of suspending. */
915
int
916
gs_main_run_string_continue(gs_main_instance * minst, const char *str,
917
         uint length, int user_errors, int *pexit_code, ref * perror_object)
918
984k
{
919
984k
    ref rstr;
920
921
984k
    if (length == 0)
922
0
        return 0;               /* empty string signals EOF */
923
984k
    make_const_string(&rstr, avm_foreign | a_readonly, length,
924
984k
                      (const byte *)str);
925
984k
    return gs_main_interpret(minst, &rstr, user_errors, pexit_code,
926
984k
                             perror_object);
927
984k
}
928
uint
929
gs_main_get_uel_offset(gs_main_instance * minst)
930
0
{
931
0
    if (minst->i_ctx_p == NULL)
932
0
        return 0;
933
0
    return (uint)minst->i_ctx_p->uel_position;
934
0
}
935
936
/* Signal EOF when suspended. */
937
int
938
gs_main_run_string_end(gs_main_instance * minst, int user_errors,
939
                       int *pexit_code, ref * perror_object)
940
818k
{
941
818k
    ref rstr;
942
943
818k
    make_empty_const_string(&rstr, avm_foreign | a_readonly);
944
818k
    return gs_main_interpret(minst, &rstr, user_errors, pexit_code,
945
818k
                             perror_object);
946
818k
}
947
948
gs_memory_t *
949
gs_main_get_device_memory(gs_main_instance * minst)
950
18.4k
{
951
18.4k
  gs_memory_t *dev_mem = NULL;
952
18.4k
  if (minst && minst->init_done >= 1) {
953
18.4k
      i_ctx_t * i_ctx_p = minst->i_ctx_p;
954
18.4k
      dev_mem = imemory_global->stable_memory;
955
18.4k
  }
956
18.4k
  return dev_mem;
957
18.4k
}
958
959
int
960
gs_main_set_device(gs_main_instance * minst, gx_device *pdev)
961
2.19k
{
962
2.19k
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
963
2.19k
    ref error_object;
964
2.19k
    int code;
965
966
2.19k
    if (pdev == NULL) {
967
        /* Leave job encapsulation, restore the graphics state gsaved below (so back to the nullpage device)
968
           and re-enter job encapsulation.
969
           We rely on the end of job encapsulation restore to the put the gstate stack back how it was when
970
           we entered job encapsulation below, so the grestore will pickup the correct gstate.
971
         */
972
1.09k
        code = gs_main_run_string(minst,
973
1.09k
                                 "true 0 startjob pop grestore false 0 startjob pop",
974
1.09k
                                 0, &code, &error_object);
975
1.09k
        if (code < 0) goto done;
976
1.09k
    }
977
1.09k
    else {
978
        /* Leave job encapsulation, and save the graphics state (including the device: nullpage)
979
           Store the page size in a dictionary, which we'll use to configure the incoming device */
980
1.09k
        code = gs_main_run_string(minst,
981
1.09k
                                  "true 0 startjob pop gsave "
982
                                  /* /PageSize /GetDeviceParam .special_op will either return:
983
                                   * /PageSize [ <width> <height> ] true   (if it exists) or
984
                                   * false                                 (if it does not) */
985
1.09k
                                  "<< /PageSize /GetDeviceParam .special_op "
986
                                  /* If we wanted to force a default pagesize, we'd do:
987
                                   * "not { /PageSize [595 842] } if "
988
                                   * but for now we'll just leave the default as it is, and do: */
989
1.09k
                                  "pop "
990
1.09k
                                  ">> "
991
1.09k
                                  , 0, &code, &error_object);
992
1.09k
        if (code < 0) goto done;
993
        /* First call goes to the C directly to actually set the device. This
994
         * avoids the SAFER checks. */
995
1.09k
        code = zsetdevice_no_safer(i_ctx_p, pdev);
996
1.09k
        if (code < 0) goto done;
997
1.09k
        code = zcurrentdevice(i_ctx_p);
998
1.09k
        if (code < 0) goto done;
999
1.09k
        code = gs_main_run_string(minst,
1000
                                  /* Set the device again to the same one. This determines
1001
                                   * whether to erase page or not, but passes the safer
1002
                                   * checks as the device is unchanged. */
1003
1.09k
                                  "setdevice "
1004
1.09k
                                  "setpagedevice "
1005
                                  /* GS specifics: Force the cached copy of the params to be updated. */
1006
1.09k
                                  "currentpagedevice pop "
1007
                                  /* Setup the halftone */
1008
1.09k
                                  ".setdefaultscreen "
1009
                                  /* Re-run the scheduled initialisation procs, in case we've just set pdfwrite */
1010
1.09k
                                  "1183615869 internaldict /.execute_scheduled_inits get exec "
1011
                                  /* Re-enter job encapsulation */
1012
1.09k
                                  "false 0 startjob pop "
1013
1.09k
                                  , 0, &code, &error_object);
1014
1.09k
        if (code < 0) goto done;
1015
1.09k
    }
1016
2.19k
done:
1017
2.19k
    return code;
1018
2.19k
}
1019
1020
/* ------ Operand stack access ------ */
1021
1022
/* These are built for comfort, not for speed. */
1023
1024
static int
1025
push_value(gs_main_instance *minst, ref * pvalue)
1026
0
{
1027
0
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1028
0
    int code = ref_stack_push(&o_stack, 1);
1029
0
    ref *o = ref_stack_index(&o_stack, 0L);
1030
1031
0
    if (o == NULL)
1032
0
        return_error(gs_error_stackoverflow);
1033
1034
0
    if (code < 0)
1035
0
        return code;
1036
0
    *o = *pvalue;
1037
0
    return 0;
1038
0
}
1039
1040
int
1041
gs_push_boolean(gs_main_instance * minst, bool value)
1042
0
{
1043
0
    ref vref;
1044
1045
0
    make_bool(&vref, value);
1046
0
    return push_value(minst, &vref);
1047
0
}
1048
1049
int
1050
gs_push_integer(gs_main_instance * minst, long value)
1051
0
{
1052
0
    ref vref;
1053
1054
0
    make_int(&vref, value);
1055
0
    return push_value(minst, &vref);
1056
0
}
1057
1058
int
1059
gs_push_real(gs_main_instance * minst, double value)
1060
0
{
1061
0
    ref vref;
1062
1063
0
    make_real(&vref, value);
1064
0
    return push_value(minst, &vref);
1065
0
}
1066
1067
int
1068
gs_push_string(gs_main_instance * minst, byte * chars, uint length,
1069
               bool read_only)
1070
0
{
1071
0
    ref vref;
1072
1073
0
    make_string(&vref, avm_foreign | (read_only ? a_readonly : a_all),
1074
0
                length, (byte *) chars);
1075
0
    return push_value(minst, &vref);
1076
0
}
1077
1078
static int
1079
pop_value(i_ctx_t *i_ctx_p, ref * pvalue)
1080
0
{
1081
0
    if (!ref_stack_count(&o_stack))
1082
0
        return_error(gs_error_stackunderflow);
1083
0
    *pvalue = *ref_stack_index(&o_stack, 0L);
1084
0
    return 0;
1085
0
}
1086
1087
int
1088
gs_pop_boolean(gs_main_instance * minst, bool * result)
1089
0
{
1090
0
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1091
0
    ref vref;
1092
0
    int code = pop_value(i_ctx_p, &vref);
1093
1094
0
    if (code < 0)
1095
0
        return code;
1096
0
    check_type_only(vref, t_boolean);
1097
0
    *result = vref.value.boolval;
1098
0
    ref_stack_pop(&o_stack, 1);
1099
0
    return 0;
1100
0
}
1101
1102
int
1103
gs_pop_integer(gs_main_instance * minst, long *result)
1104
0
{
1105
0
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1106
0
    ref vref;
1107
0
    int code = pop_value(i_ctx_p, &vref);
1108
1109
0
    if (code < 0)
1110
0
        return code;
1111
0
    check_type_only(vref, t_integer);
1112
0
    *result = vref.value.intval;
1113
0
    ref_stack_pop(&o_stack, 1);
1114
0
    return 0;
1115
0
}
1116
1117
int
1118
gs_pop_real(gs_main_instance * minst, float *result)
1119
0
{
1120
0
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1121
0
    ref vref;
1122
0
    int code = pop_value(i_ctx_p, &vref);
1123
1124
0
    if (code < 0)
1125
0
        return code;
1126
0
    switch (r_type(&vref)) {
1127
0
        case t_real:
1128
0
            *result = vref.value.realval;
1129
0
            break;
1130
0
        case t_integer:
1131
0
            *result = (float)(vref.value.intval);
1132
0
            break;
1133
0
        default:
1134
0
            return_error(gs_error_typecheck);
1135
0
    }
1136
0
    ref_stack_pop(&o_stack, 1);
1137
0
    return 0;
1138
0
}
1139
1140
int
1141
gs_pop_string(gs_main_instance * minst, gs_string * result)
1142
0
{
1143
0
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1144
0
    ref vref;
1145
0
    int code = pop_value(i_ctx_p, &vref);
1146
1147
0
    if (code < 0)
1148
0
        return code;
1149
0
    switch (r_type(&vref)) {
1150
0
        case t_name:
1151
0
            name_string_ref(minst->heap, &vref, &vref);
1152
0
            code = 1;
1153
0
            goto rstr;
1154
0
        case t_string:
1155
0
            code = (r_has_attr(&vref, a_write) ? 0 : 1);
1156
0
          rstr:result->data = vref.value.bytes;
1157
0
            result->size = r_size(&vref);
1158
0
            break;
1159
0
        default:
1160
0
            return_error(gs_error_typecheck);
1161
0
    }
1162
0
    ref_stack_pop(&o_stack, 1);
1163
0
    return code;
1164
0
}
1165
1166
/* ------ Termination ------ */
1167
1168
/* Get the names of temporary files.
1169
 * Each name is null terminated, and the last name is
1170
 * terminated by a double null.
1171
 * We retrieve the names of temporary files just before
1172
 * the interpreter finishes, and then delete the files
1173
 * after the interpreter has closed all files.
1174
 */
1175
static char *gs_main_tempnames(gs_main_instance *minst)
1176
166k
{
1177
166k
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1178
166k
    ref *SAFETY;
1179
166k
    ref *tempfiles;
1180
166k
    ref keyval[2];      /* for key and value */
1181
166k
    char *tempnames = NULL;
1182
166k
    int i;
1183
166k
    int idict;
1184
166k
    int len = 0;
1185
166k
    const byte *data = NULL;
1186
166k
    uint size;
1187
166k
    if (minst->init_done >= 2) {
1188
166k
        if (dict_find_string(systemdict, "SAFETY", &SAFETY) <= 0 ||
1189
166k
            dict_find_string(SAFETY, "tempfiles", &tempfiles) <= 0)
1190
0
            return NULL;
1191
        /* get lengths of temporary filenames */
1192
166k
        idict = dict_first(tempfiles);
1193
166k
        while ((idict = dict_next(tempfiles, idict, &keyval[0])) >= 0) {
1194
0
            if (obj_string_data(minst->heap, &keyval[0], &data, &size) >= 0)
1195
0
                len += size + 1;
1196
0
        }
1197
166k
        if (len != 0)
1198
0
            tempnames = (char *)malloc(len+1);
1199
166k
        if (tempnames) {
1200
0
            memset(tempnames, 0, len+1);
1201
            /* copy temporary filenames */
1202
0
            idict = dict_first(tempfiles);
1203
0
            i = 0;
1204
0
            while ((idict = dict_next(tempfiles, idict, &keyval[0])) >= 0) {
1205
0
                if (obj_string_data(minst->heap, &keyval[0], &data, &size) >= 0) {
1206
0
                    memcpy(tempnames+i, (const char *)data, size);
1207
0
                    i+= size;
1208
0
                    tempnames[i++] = '\0';
1209
0
                }
1210
0
            }
1211
0
        }
1212
166k
    }
1213
166k
    return tempnames;
1214
166k
}
1215
1216
static void
1217
gs_finit_push_systemdict(i_ctx_t *i_ctx_p)
1218
166k
{
1219
166k
    if (i_ctx_p == NULL)
1220
0
        return;
1221
166k
    if (dsp == dstop ) {
1222
6
        if (ref_stack_extend(&d_stack, 1) < 0) {
1223
            /* zend() cannot fail */
1224
0
            (void)zend(i_ctx_p);
1225
0
        }
1226
6
    }
1227
166k
    dsp++;
1228
166k
    ref_assign(dsp, systemdict);
1229
166k
}
1230
1231
/* Free all resources and return. */
1232
int
1233
gs_main_finit(gs_main_instance * minst, int exit_status, int env_code)
1234
166k
{
1235
166k
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1236
166k
    gs_dual_memory_t dmem = {0};
1237
166k
    int exit_code;
1238
166k
    ref error_object;
1239
166k
    char *tempnames = NULL;
1240
166k
    gs_lib_ctx_core_t *core;
1241
1242
    /* NB: need to free gs_name_table
1243
     */
1244
1245
    /*
1246
     * Previous versions of this code closed the devices in the
1247
     * device list here.  Since these devices are now prototypes,
1248
     * they cannot be opened, so they do not need to be closed;
1249
     * alloc_restore_all will close dynamically allocated devices.
1250
     */
1251
166k
    tempnames = gs_main_tempnames(minst);
1252
1253
    /* by the time we get here, we *must* avoid any random redefinitions of
1254
     * operators etc, so we push systemdict onto the top of the dict stack.
1255
     * We do this in C to avoid running into any other re-defininitions in the
1256
     * Postscript world.
1257
     */
1258
166k
    gs_finit_push_systemdict(i_ctx_p);
1259
1260
    /* We have to disable BGPrint before we call interp_reclaim() to prevent the
1261
     * parent rendering thread initialising for the next page, whilst we are
1262
     * removing objects it may want to access - for example, the I/O device table.
1263
     * We also have to mess with the BeginPage/EndPage procs so that we don't
1264
     * trigger a spurious extra page to be emitted.
1265
     */
1266
166k
    if (minst->init_done >= 2) {
1267
166k
        gs_main_run_string(minst,
1268
166k
            "/BGPrint /GetDeviceParam .special_op \
1269
166k
            {{ <</BeginPage {pop} /EndPage {pop pop //false } \
1270
166k
              /BGPrint false /NumRenderingThreads 0>> setpagedevice} if} if \
1271
166k
              serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
1272
166k
              .systemvar exec",
1273
166k
            0 , &exit_code, &error_object);
1274
166k
    }
1275
1276
    /*
1277
     * Close the "main" device, because it may need to write out
1278
     * data before destruction. pdfwrite needs so.
1279
     */
1280
166k
    if (minst->init_done >= 2) {
1281
166k
        int code = 0;
1282
1283
166k
        if (idmemory->reclaim != 0) {
1284
            /* In extreme error conditions, these references can persist, despite the
1285
             * arrays themselves having been restored away.
1286
             */
1287
166k
            gs_main_run_string(minst,
1288
166k
                "$error /dstack undef \
1289
166k
                 $error /estack undef \
1290
166k
                 $error /ostack undef \
1291
166k
                 serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse \
1292
166k
                 .systemvar exec",
1293
166k
                 0 , &exit_code, &error_object);
1294
1295
166k
            ref_stack_clear(&o_stack);
1296
166k
            code = interp_reclaim(&minst->i_ctx_p, avm_global);
1297
1298
            /* We ignore gs_error_VMerror because it comes from gs_vmreclaim()
1299
            calling context_state_load(), and we don't seem to depend on the
1300
            missing fields. */
1301
166k
            if (code == gs_error_VMerror) {
1302
0
                if (exit_status == 0 || exit_status == gs_error_Quit) {
1303
0
                    exit_status = gs_error_VMerror;
1304
0
                }
1305
0
            }
1306
166k
            else if (code < 0) {
1307
0
                ref error_name;
1308
0
                if (tempnames)
1309
0
                    free(tempnames);
1310
1311
0
                if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
1312
0
                    char err_str[32] = {0};
1313
0
                    name_string_ref(imemory, &error_name, &error_name);
1314
0
                    memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
1315
0
                    emprintf2(imemory, "ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n", err_str, code);
1316
0
                }
1317
0
                else {
1318
0
                    emprintf1(imemory, "UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n", code);
1319
0
                }
1320
#ifdef MEMENTO
1321
                if (Memento_squeezing() && code != gs_error_VMerror ) return gs_error_Fatal;
1322
#endif
1323
0
                return gs_error_Fatal;
1324
0
            }
1325
166k
            i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */
1326
166k
        }
1327
1328
166k
        if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL &&
1329
166k
            gx_device_is_null(i_ctx_p->pgs->device)) {
1330
            /* if the job replaced the device with the nulldevice, we we need to grestore
1331
               away that device, so the block below can properly dispense
1332
               with the default device.
1333
             */
1334
77
            int code = gs_grestoreall(i_ctx_p->pgs);
1335
77
            if (code < 0) {
1336
0
                free(tempnames);
1337
0
                return_error(gs_error_Fatal);
1338
0
            }
1339
77
        }
1340
1341
166k
        if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {
1342
166k
            gx_device *pdev = i_ctx_p->pgs->device;
1343
166k
            const char * dname = pdev->dname;
1344
166k
            gs_gc_root_t dev_root;
1345
166k
            gs_gc_root_t *dev_root_ptr = &dev_root;
1346
            /* There is a chance that, during the call to gs_main_run_string(), the interpreter may
1347
             * decide to call the garbager - the device is in gc memory, and the only reference to it
1348
             * (in the gstate) has been removed, thus it can be destroyed by the garbager.
1349
             * Counter-intuitively, adjusting the reference count makes not difference to that.
1350
             * Register the device as a gc 'root' so it will be implicitely marked by garbager, and
1351
             * and thus surive until control returns here.
1352
             */
1353
166k
            if (gs_register_struct_root(pdev->memory, &dev_root_ptr, (void **)&pdev, "gs_main_finit") < 0) {
1354
0
                free(tempnames);
1355
0
                return_error(gs_error_Fatal);
1356
0
            }
1357
1358
            /* make sure device doesn't isn't freed by .uninstalldevice */
1359
166k
            rc_adjust(pdev, 1, "gs_main_finit");
1360
            /* deactivate the device just before we close it for the last time */
1361
166k
            gs_main_run_string(minst,
1362
                /* we need to do the 'quit' so we don't loop for input (double quit) */
1363
166k
                ".uninstallpagedevice serverdict \
1364
166k
                /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemvar exec",
1365
166k
                0 , &exit_code, &error_object);
1366
166k
            code = gs_closedevice(pdev);
1367
166k
            if (code < 0) {
1368
0
                ref error_name;
1369
0
                if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {
1370
0
                    char err_str[32] = {0};
1371
0
                    name_string_ref(imemory, &error_name, &error_name);
1372
0
                    memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));
1373
0
                    emprintf3(imemory, "ERROR: %s (%d) on closing %s device.\n", err_str, code, dname);
1374
0
                }
1375
0
                else {
1376
0
                    emprintf2(imemory, "UNKNOWN ERROR %d closing %s device.\n", code, dname);
1377
0
               }
1378
0
            }
1379
166k
            gs_unregister_root(pdev->memory, dev_root_ptr, "gs_main_finit");
1380
166k
            rc_decrement(pdev, "gs_main_finit");                /* device might be freed */
1381
166k
            if (exit_status == 0 || exit_status == gs_error_Quit)
1382
166k
                exit_status = code;
1383
166k
        }
1384
1385
      /* Flush stdout and stderr */
1386
166k
      gs_main_run_string(minst,
1387
166k
        "(%stdout) (w) file closefile (%stderr) (w) file closefile \
1388
166k
        serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \
1389
166k
          systemdict /savedinitialgstate .forceundef",
1390
166k
        0 , &exit_code, &error_object);
1391
166k
    }
1392
166k
    gp_readline_finit(minst->readline_data);
1393
166k
    gs_free_object(minst->heap, minst->saved_pages_initial_arg, "gs_main_finit");
1394
166k
    i_ctx_p = minst->i_ctx_p;   /* get current interp context */
1395
166k
    if (gs_debug_c(':')) {
1396
0
        print_resource_usage(minst, i_ctx_p ? &gs_imemory : NULL, "Final");
1397
0
        dmprintf1(minst->heap, "%% Exiting instance "PRI_INTPTR"\n", (intptr_t)minst);
1398
0
    }
1399
1400
#ifdef MEMENTO
1401
    /* We only do this for Memento builds, because the strings themselves are allocated by one
1402
     * of the GS memory allocators, which are cleaned up and closed down by ialloc_finit()
1403
     * called at the end of this function, so they can't leak.
1404
     * But Memento can't know that, all it knows is we did an allocation without a corresponding free
1405
     * so this code just gets rid of the leak warnings to make the output cleaner.
1406
     */
1407
    if (i_ctx_p->system_params.FontResourceDir != NULL)
1408
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.FontResourceDir, "gs_main_finit");
1409
    if (i_ctx_p->system_params.GenericResourceDir != NULL)
1410
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.GenericResourceDir, "gs_main_finit");
1411
    if (i_ctx_p->system_params.GenericResourcePathSep != NULL)
1412
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.GenericResourcePathSep, "gs_main_finit");
1413
    if (i_ctx_p->system_params.PercentDiskFontResourceDir != NULL)
1414
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.PercentDiskFontResourceDir, "gs_main_finit");
1415
    if (i_ctx_p->system_params.PercentDiskGenericResourceDir != NULL)
1416
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.PercentDiskGenericResourceDir, "gs_main_finit");
1417
    if (i_ctx_p->system_params.StartJobPassword != NULL)
1418
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.StartJobPassword, "gs_main_finit");
1419
    if (i_ctx_p->system_params.SystemParamsPassword != NULL)
1420
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->system_params.SystemParamsPassword, "gs_main_finit");
1421
    if (i_ctx_p->user_params.JobName != NULL)
1422
        gs_free_object(i_ctx_p->memory.current->non_gc_memory, i_ctx_p->user_params.JobName, "gs_main_finit");
1423
#endif
1424
1425
    /* Do the equivalent of a restore "past the bottom". */
1426
    /* This will release all memory, close all open files, etc. */
1427
166k
    if (minst->init_done >= 1) {
1428
166k
        gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;
1429
166k
        i_plugin_holder *h = i_ctx_p->plugin_list;
1430
1431
166k
        dmem = *idmemory;
1432
166k
        env_code = alloc_restore_all(i_ctx_p);
1433
166k
        if (env_code < 0)
1434
0
            emprintf1(mem_raw,
1435
166k
                      "ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n",
1436
166k
                      env_code);
1437
166k
        i_iodev_finit(&dmem);
1438
166k
        i_plugin_finit(mem_raw, h);
1439
166k
    }
1440
1441
    /* clean up redirected stdout */
1442
166k
    core = minst->heap->gs_lib_ctx->core;
1443
166k
    if (core->fstdout2
1444
145k
        && (gp_get_file(core->fstdout2) != core->fstdout)
1445
145k
        && (gp_get_file(core->fstdout2) != core->fstderr)) {
1446
145k
        gp_fclose(core->fstdout2);
1447
145k
        core->fstdout2 = NULL;
1448
145k
    }
1449
1450
166k
    minst->heap->gs_lib_ctx->core->stdout_is_redirected = 0;
1451
166k
    minst->heap->gs_lib_ctx->core->stdout_to_stderr = 0;
1452
    /* remove any temporary files, after ghostscript has closed files */
1453
166k
    if (tempnames) {
1454
0
        char *p = tempnames;
1455
0
        while (*p) {
1456
0
            gp_unlink(minst->heap, p);
1457
0
            p += strlen(p) + 1;
1458
0
        }
1459
0
        free(tempnames);
1460
0
    }
1461
166k
    gs_lib_finit(exit_status, env_code, minst->heap);
1462
1463
166k
    set_lib_path_length(minst, 0);
1464
166k
    gs_free_object(minst->heap, minst->lib_path.container.value.refs, "lib_path array");
1465
166k
    if (minst->init_done == 0 && i_ctx_p) {
1466
        /* This fixes leak if memento forces failure in gs_main_init1(). */
1467
0
        dmem = *idmemory;
1468
0
    }
1469
166k
    ialloc_finit(&dmem);
1470
166k
    return exit_status;
1471
166k
}
1472
int
1473
gs_to_exit_with_code(const gs_memory_t *mem, int exit_status, int code)
1474
166k
{
1475
166k
    return gs_main_finit(get_minst_from_memory(mem), exit_status, code);
1476
166k
}
1477
int
1478
gs_to_exit(const gs_memory_t *mem, int exit_status)
1479
166k
{
1480
166k
    return gs_to_exit_with_code(mem, exit_status, 0);
1481
166k
}
1482
void
1483
gs_abort(const gs_memory_t *mem)
1484
0
{
1485
    /* In previous versions, we tried to do a cleanup (using gs_to_exit),
1486
     * but more often than not, that will trip another abort and create
1487
     * an infinite recursion. So just abort without trying to cleanup.
1488
     */
1489
0
    gp_do_exit(1);
1490
0
}
1491
1492
/* ------ Debugging ------ */
1493
1494
/* Print resource usage statistics. */
1495
void
1496
print_resource_usage(const gs_main_instance * minst, gs_dual_memory_t * dmem,
1497
                     const char *msg)
1498
0
{
1499
0
    ulong used = 0;   /* this we accumulate for the PS memories */
1500
0
    long utime[2];
1501
0
    int i;
1502
0
    gs_memory_status_t status = { 0 };
1503
1504
0
    gp_get_realtime(utime);
1505
1506
0
    if (dmem)
1507
0
    {
1508
0
        for (i = 0; i < countof(dmem->spaces_indexed); ++i) {
1509
0
            gs_ref_memory_t *mem = dmem->spaces_indexed[i];
1510
1511
0
            if (mem != 0 && (i == 0 || mem != dmem->spaces_indexed[i - 1])) {
1512
0
                gs_ref_memory_t *mem_stable =
1513
0
                    (gs_ref_memory_t *)gs_memory_stable((gs_memory_t *)mem);
1514
1515
0
                gs_memory_status((gs_memory_t *)mem, &status);
1516
0
                used += status.used;
1517
0
                if (mem_stable != mem) {
1518
0
                    gs_memory_status((gs_memory_t *)mem_stable, &status);
1519
0
                    used += status.used;
1520
0
                }
1521
0
            }
1522
0
        }
1523
0
    }
1524
    /* Now get the overall values from the heap memory */
1525
0
    gs_memory_status(minst->heap, &status);
1526
0
    dmprintf5(minst->heap, "%% %s time = %g, memory allocated = %lu, used = %lu, max_used = %lu\n",
1527
0
              msg, utime[0] - minst->base_time[0] +
1528
0
              (utime[1] - minst->base_time[1]) / 1000000000.0,
1529
0
              status.allocated, used, status.max_used);
1530
0
}
1531
1532
/* Dump the stacks after interpretation */
1533
void
1534
gs_main_dump_stack(gs_main_instance *minst, int code, ref * perror_object)
1535
0
{
1536
0
    i_ctx_t *i_ctx_p = minst->i_ctx_p;
1537
1538
0
    zflush(i_ctx_p);            /* force out buffered output */
1539
0
    dmprintf1(minst->heap, "\nUnexpected interpreter error %d.\n", code);
1540
0
    if (perror_object != 0) {
1541
0
        dmputs(minst->heap, "Error object: ");
1542
0
        debug_print_ref(minst->heap, perror_object);
1543
0
        dmputc(minst->heap, '\n');
1544
0
    }
1545
0
    debug_dump_stack(minst->heap, &o_stack, "Operand stack");
1546
0
    debug_dump_stack(minst->heap, &e_stack, "Execution stack");
1547
0
    debug_dump_stack(minst->heap, &d_stack, "Dictionary stack");
1548
0
}
1549
1550
int
1551
gs_main_force_resolutions(gs_main_instance * minst, const float *resolutions)
1552
166k
{
1553
166k
    ref value;
1554
166k
    int code;
1555
1556
166k
    if (resolutions == NULL)
1557
0
        return 0;
1558
1559
166k
    if (minst == NULL)
1560
0
        return gs_error_Fatal;
1561
1562
166k
    make_true(&value);
1563
166k
    code = i_initial_enter_name(minst->i_ctx_p, "FIXEDRESOLUTION", &value);
1564
166k
    if (code < 0)
1565
0
        return code;
1566
166k
    make_real(&value, resolutions[0]);
1567
166k
    code = i_initial_enter_name(minst->i_ctx_p, "DEVICEXRESOLUTION", &value);
1568
166k
    if (code < 0)
1569
0
        return code;
1570
166k
    make_real(&value, resolutions[1]);
1571
166k
    return i_initial_enter_name(minst->i_ctx_p, "DEVICEYRESOLUTION", &value);
1572
166k
}
1573
1574
int
1575
gs_main_force_dimensions(gs_main_instance *minst, const long *dimensions)
1576
18.4k
{
1577
18.4k
    ref value;
1578
18.4k
    int code = 0;
1579
1580
18.4k
    if (dimensions == NULL)
1581
18.4k
        return 0;
1582
0
    if (minst == NULL)
1583
0
        return gs_error_Fatal;
1584
1585
0
    make_true(&value);
1586
0
    code = i_initial_enter_name(minst->i_ctx_p, "FIXEDMEDIA", &value);
1587
0
    if (code < 0)
1588
0
        return code;
1589
0
    make_int(&value, dimensions[0]);
1590
0
    code = i_initial_enter_name(minst->i_ctx_p, "DEVICEWIDTH", &value);
1591
0
    if (code < 0)
1592
0
        return code;
1593
0
    make_int(&value, dimensions[1]);
1594
0
    return i_initial_enter_name(minst->i_ctx_p, "DEVICEHEIGHT", &value);
1595
0
}