Commit message: Sanitize op stack for error conditions

We save the stacks to an array and store the array for the error handler to
access.

For SAFER, we traverse the array, and deep copy any op arrays (procedures). As
we make these copies, we check for operators that do *not* exist in systemdict,
when we find one, we replace the operator with a name object (of the form
"/--opname--").
CVE: None
Vulnerability description: None

Project: ghostpdl
File: interp.c

gs_interpret(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, int *pexit_code,
             ref * perror_object)
{
    i_ctx_t *i_ctx_p = *pi_ctx_p;
    gs_gc_root_t error_root, *r = &error_root;
    int code;

    gs_register_ref_root(imemory_system, &r,
                         (void **)&perror_object, "gs_interpret");
    code = gs_call_interp(pi_ctx_p, pref, user_errors, pexit_code,
                          perror_object);
    i_ctx_p = *pi_ctx_p;
    gs_unregister_root(imemory_system, &error_root, "gs_interpret");
    /* Avoid a dangling reference to the lib context GC signal. */
    set_gc_signal(i_ctx_p, 0);
    return code;
}

Project: ghostpdl
File: istack.c

ref_stack_cleanup(ref_stack_t *pstack)
{
    ref_stack_block *pblock =
        (ref_stack_block *) pstack->current.value.refs;

    refset_null_new(pstack->p + 1, pstack->top - pstack->p, 0);
    pblock->used = pstack->current;	/* set attrs */
    pblock->used.value.refs = pstack->bot;
    r_set_size(&pblock->used, pstack->p + 1 - pstack->bot);
}

Project: ghostpdl
File: interp.c

errorexec_pop(i_ctx_t *i_ctx_p)
{
    esp -= 2;
    return o_pop_estack;
}

Project: ghostpdl
File: istack.c

ref_stack_store(const ref_stack_t *pstack, ref *parray, uint count,
                uint skip, int age, bool check, gs_dual_memory_t *idmemory,
                client_name_t cname)
{
    uint left, pass;
    ref *to;
    ref_stack_enum_t rsenum;

    if (count > ref_stack_count(pstack) || count > r_size(parray))
        return_error(gs_error_rangecheck);
    if (check) {
        int code = ref_stack_store_check(pstack, parray, count, skip);

        if (code < 0)
            return code;
    }
    to = parray->value.refs + count;
    left = count, pass = skip;
    ref_stack_enum_begin(&rsenum, pstack);
    do {
        ref *from = rsenum.ptr;
        uint size = rsenum.size;

        if (size <= pass)
            pass -= size;
        else {
            if (pass != 0)
                size -= pass, pass = 0;
            from += size;
            if (size > left)
                size = left;
            left -= size;
            switch (age) {
            case -1:		/* not an array */
                while (size--) {
                    from--, to--;
                    ref_assign(to, from);
                }
                break;
            case 0:		/* old array */
                while (size--) {
                    from--, to--;
                    ref_assign_old(parray, to, from, cname);
                }
                break;
            case 1:		/* new array */
                while (size--) {
                    from--, to--;
                    ref_assign_new(to, from);
                }
                break;
            }
            if (left == 0)
                break;
        }
    } while (ref_stack_enum_next(&rsenum));
    r_set_size(parray, count);
    return 0;
}

Project: ghostpdl
File: interp.c

gs_interp_make_oper(ref * opref, op_proc_t proc, int idx)
{
    int i;

    for (i = num_special_ops; i > 0 && proc != interp1_op_defs[i].proc; --i)
        DO_NOTHING;
    if (i > 0)
        make_tasv(opref, tx_op + (i - 1), a_executable, i, opproc, proc);
    else
        make_tasv(opref, t_operator, a_executable, idx, opproc, proc);
}

Project: ghostpdl
File: interp.c

copy_stack(i_ctx_t *i_ctx_p, const ref_stack_t * pstack, int skip, ref * arr)
{
    uint size = ref_stack_count(pstack) - skip;
    uint save_space = ialloc_space(idmemory);
    int code, i;
    ref *safety, *safe;

    if (size > 65535)
        size = 65535;
    ialloc_set_space(idmemory, avm_local);
    code = ialloc_ref_array(arr, a_all, size, "copy_stack");
    if (code >= 0)
        code = ref_stack_store(pstack, arr, size, 0, 1, true, idmemory,
                               "copy_stack");
    /* If we are copying the exec stack, try to replace any oparrays with
     * with the operator than references them
     */
    if (pstack == &e_stack) {
        for (i = 0; i < size; i++) {
            if (errorexec_find(i_ctx_p, &arr->value.refs[i]) < 0)
                make_null(&arr->value.refs[i]);
        }
    }
    if (pstack == &o_stack && dict_find_string(systemdict, "SAFETY", &safety) > 0 &&
        dict_find_string(safety, "safe", &safe) > 0 && r_has_type(safe, t_boolean) &&
        safe->value.boolval == true) {
        code = ref_stack_array_sanitize(i_ctx_p, arr, arr);
        if (code < 0)
            return code;
    }
    ialloc_set_space(idmemory, save_space);
    return code;
}

Project: ghostpdl
File: istack.c

ref_stack_index(const ref_stack_t *pstack, long idx)
{
    ref_stack_block *pblock;
    uint used = pstack->p + 1 - pstack->bot;

    if (idx < 0)
        return NULL;
    if (idx < used)		/* common case */
        return pstack->p - (uint) idx;
    pblock = (ref_stack_block *) pstack->current.value.refs;
    do {
        pblock = (ref_stack_block *) pblock->next.value.refs;
        if (pblock == 0)
            return NULL;
        idx -= used;
        used = r_size(&pblock->used);
    } while (idx >= used);
    return pblock->used.value.refs + (used - 1 - (uint) idx);
}

Project: ghostpdl
File: istack.c

ref_stack_free(ref_stack_t *pstack)
{
    gs_memory_t *mem = (gs_memory_t *)pstack->memory;

    ref_stack_release(pstack);
    gs_free_object(mem, pstack, "ref_stack_free");
}

Project: ghostpdl
File: interp.c

gs_interp_init(i_ctx_t **pi_ctx_p, const ref *psystem_dict,
               gs_dual_memory_t *dmem)
{
    /* Create and initialize a context state. */
    gs_context_state_t *pcst = 0;
    int code = context_state_alloc(&pcst, psystem_dict, dmem);
    if (code >= 0) {
        code = context_state_load(pcst);
        if (code < 0) {
            context_state_free(pcst);
            pcst = NULL;
        }
    }

    if (code < 0)
        lprintf1("Fatal error %d in gs_interp_init!\n", code);
    *pi_ctx_p = pcst;

    return code;
}

Project: ghostpdl
File: istack.c

ref_stack_enum_next(ref_stack_enum_t *prse)
{
    ref_stack_block *block =
        prse->block = (ref_stack_block *)prse->block->next.value.refs;

    if (block == 0)
        return false;
    prse->ptr = block->used.value.refs;
    prse->size = r_size(&block->used);
    return true;
}

Project: ghostpdl
File: istack.c

ref_stack_init(ref_stack_t *pstack, const ref *pblock_array,
               uint bot_guard, uint top_guard, const ref *pguard_value,
               gs_ref_memory_t *mem, ref_stack_params_t *params)
{
    uint size = r_size(pblock_array);
    uint avail = size - (stack_block_refs + bot_guard + top_guard);
    ref_stack_block *pblock = (ref_stack_block *)pblock_array->value.refs;
    s_ptr body = (s_ptr)(pblock + 1);

    if (params == 0) {
        params = gs_alloc_struct((gs_memory_t *)mem, ref_stack_params_t,
                                 &st_ref_stack_params,
                                 "ref_stack_alloc(stack.params)");
        if (params == 0)
            return_error(-1);	/* avoid binding in any error codes */
    }

    pstack->bot = body + bot_guard;
    pstack->p = pstack->bot - 1;
    pstack->top = pstack->p + avail;
    pstack->current = *pblock_array;
    pstack->extension_size = 0;
    pstack->extension_used = 0;

    make_int(&pstack->max_stack, avail);
    pstack->requested = 0;
    pstack->margin = 0;
    pstack->body_size = avail;

    pstack->params = params;
    pstack->memory = mem;

    params->bot_guard = bot_guard;
    params->top_guard = top_guard;
    params->block_size = size;
    params->data_size = avail;
    if (pguard_value != 0)
        params->guard_value = *pguard_value;
    else
        make_tav(&params->guard_value, t__invalid, 0, intval, 0);
    params->underflow_error = -1;
    params->overflow_error = -1;
    params->allow_expansion = true;
    init_block(pstack, pblock_array, 0);
    refset_null_new(pstack->bot, avail, 0);
    make_empty_array(&pblock->next, 0);
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_release(ref_stack_t *pstack)
{
    gs_ref_memory_t *mem = pstack->memory;

    ref_stack_clear(pstack);
    /* Free the parameter structure. */
    gs_free_object((gs_memory_t *)mem, pstack->params,
                   "ref_stack_release(stack.params)");
    /* Free the original (bottom) block. */
    gs_free_ref_array(mem, &pstack->current, "ref_stack_release");
}

Project: ghostpdl
File: interp.c

gs_interp_free_stacks(gs_ref_memory_t * smem, gs_context_state_t * pcst)
{
    /* Free the stacks in inverse order of allocation. */
    ref_stack_release(&pcst->dict_stack.stack);
    ref_stack_release(&pcst->exec_stack.stack);
    ref_stack_release(&pcst->op_stack.stack);
}

Project: ghostpdl
File: istack.c

ref_stack_array_sanitize(i_ctx_t *i_ctx_p, ref *sarr, ref *darr)
{
    int i, code;
    ref obj, arr2;
    ref *pobj2;
    gs_memory_t *mem = (gs_memory_t *)idmemory->current;

    if (!r_is_array(sarr) || !r_has_type(darr, t_array))
        return_error(gs_error_typecheck);

    for (i = 0; i < r_size(sarr); i++) {
        code = array_get(mem, sarr, i, &obj);
        if (code < 0)
            make_null(&obj);
        switch(r_type(&obj)) {
          case t_operator:
          {
            int index = op_index(&obj);

            if (index > 0 && index < op_def_count) {
                const byte *data = (const byte *)(op_index_def(index)->oname + 1);
                if (dict_find_string(systemdict, (const char *)data, &pobj2) <= 0) {
                    byte *s = gs_alloc_bytes(mem, strlen((char *)data) + 5, "ref_stack_array_sanitize");
                    if (s) {
                        s[0] =  '\0';
                        strcpy((char *)s, "--");
                        strcpy((char *)s + 2, (char *)data);
                        strcpy((char *)s + strlen((char *)data) + 2, "--");
                    }
                    else {
                        s = (byte *)data;
                    }
                    code = name_ref(imemory, s, strlen((char *)s), &obj, 1);
                    if (code < 0) make_null(&obj);
                    if (s != data)
                        gs_free_object(mem, s, "ref_stack_array_sanitize");
                }
            }
            else {
                make_null(&obj);
            }
            ref_assign(darr->value.refs + i, &obj);
            break;
          }
          case t_array:
          case t_shortarray:
          case t_mixedarray:
          {
            int attrs = r_type_attrs(&obj) & (a_write | a_read | a_execute | a_executable);
            /* We only want to copy executable arrays */
            if (attrs & (a_execute | a_executable)) {
                code = ialloc_ref_array(&arr2, attrs, r_size(&obj), "ref_stack_array_sanitize");
                if (code < 0) {
                    make_null(&arr2);
                }
                else {
                    code = ref_stack_array_sanitize(i_ctx_p, &obj, &arr2);
                }
                ref_assign(darr->value.refs + i, &arr2);
            }
            else {
                ref_assign(darr->value.refs + i, &obj);
            }
            break;
          }
          default:
            ref_assign(darr->value.refs + i, &obj);
        }
    }
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_allow_expansion(ref_stack_t *pstack, bool expand)
{
    pstack->params->allow_expansion = expand;
}

Project: ghostpdl
File: interp.c

gs_errorinfo_put_string(i_ctx_t *i_ctx_p, const char *str)
{
    ref rstr;
    ref *pderror;
    int code = string_to_ref(str, &rstr, iimemory, "gs_errorinfo_put_string");

    if (code < 0)
        return code;
    if (dict_find_string(systemdict, "$error", &pderror) <= 0 ||
        !r_has_type(pderror, t_dictionary) ||
        idict_put_string(pderror, "errorinfo", &rstr) < 0
        )
        return_error(gs_error_Fatal);
    return 0;
}

Project: ghostpdl
File: interp.c

zerrorexec(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    int code;

    check_op(2);
    check_estack(4);            /* mark/cleanup, errobj, pop, obj */
    push_mark_estack(es_other, errorexec_cleanup);
    *++esp = op[-1];
    push_op_estack(errorexec_pop);
    code = zexec(i_ctx_p);
    if (code >= 0)
        pop(1);
    else
        esp -= 3;               /* undo our additions to estack */
    return code;
}

Project: ghostpdl
File: istack.c

ref_stack_enum_begin(ref_stack_enum_t *prse, const ref_stack_t *pstack)
{
    prse->block = (ref_stack_block *)pstack->current.value.refs;
    prse->ptr = pstack->bot;
    prse->size = pstack->p + 1 - pstack->bot;
}

Project: ghostpdl
File: interp.c

do_call_operator_verbose(op_proc_t op_proc, i_ctx_t *i_ctx_p)
{
    int code;

#ifndef SHOW_STACK_DEPTHS
    if_debug1m('!', imemory, "[!]operator %s\n", op_get_name_string(op_proc));
#else
    if_debug3m('!', imemory, "[!][es=%d os=%d]operator %s\n",
            esp-i_ctx_p->exec_stack.stack.bot,
            osp-i_ctx_p->op_stack.stack.bot,
            op_get_name_string(op_proc));
#endif
    code = do_call_operator(op_proc, i_ctx_p);
#if defined(SHOW_STACK_DEPTHS)
    if_debug2m('!', imemory, "[!][es=%d os=%d]\n",
            esp-i_ctx_p->exec_stack.stack.bot,
            osp-i_ctx_p->op_stack.stack.bot);
#endif
    if (gs_debug_c(gs_debug_flag_validate_clumps))
        ivalidate_clean_spaces(i_ctx_p);
    return code; /* A good place for a conditional breakpoint. */
}

Project: ghostpdl
File: interp.c

zforceinterp_exit(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    stream *s;

    check_file(s, op);
    i_ctx_p->uel_position = stell(s)-1;
    /* resetfile */
    if (file_is_valid(s, op))
        sreset(s);

    if (!gs_lib_ctx_get_act_on_uel((gs_memory_t *)(i_ctx_p->memory.current)))
        return 0;

    gs_interp_reset(i_ctx_p);
    /* gs_interp_reset() actually leaves the op stack one entry below
     * the bottom of the stack, and that can cause problems depending
     * on the interpreter state at the end of the job.
     * So push a null object, and the return code before continuing.
     */
    push(2);
    op = osp;
    make_null(op - 1);
    make_int(op, gs_error_InterpreterExit);
    return_error(gs_error_Quit);
}

Project: ghostpdl
File: interp.c

gs_interp_alloc_stacks(gs_ref_memory_t *mem, gs_context_state_t * pcst)
{
    int code;
    gs_ref_memory_t *smem =
        (gs_ref_memory_t *)gs_memory_stable((gs_memory_t *)mem);
    ref stk;

#define REFS_SIZE_OSTACK OS_REFS_SIZE(MAX_OSTACK)
#define REFS_SIZE_ESTACK ES_REFS_SIZE(MAX_ESTACK)
#define REFS_SIZE_DSTACK DS_REFS_SIZE(MAX_DSTACK)
    code = gs_alloc_ref_array(smem, &stk, 0,
                       REFS_SIZE_OSTACK + REFS_SIZE_ESTACK +
                       REFS_SIZE_DSTACK, "gs_interp_alloc_stacks");
    if (code < 0)
        return code;

    {
        ref_stack_t *pos = &pcst->op_stack.stack;

        r_set_size(&stk, REFS_SIZE_OSTACK);
        code = ref_stack_init(pos, &stk, OS_GUARD_UNDER, OS_GUARD_OVER, NULL,
                              smem, NULL);
	if (code < 0)
            return code;
        ref_stack_set_error_codes(pos, gs_error_stackunderflow, gs_error_stackoverflow);
        ref_stack_set_max_count(pos, MAX_OSTACK);
        stk.value.refs += REFS_SIZE_OSTACK;
    }

    {
        ref_stack_t *pes = &pcst->exec_stack.stack;
        ref euop;

        r_set_size(&stk, REFS_SIZE_ESTACK);
        make_oper(&euop, 0, estack_underflow);
        code = ref_stack_init(pes, &stk, ES_GUARD_UNDER, ES_GUARD_OVER, &euop,
                       smem, NULL);
	if (code < 0)
            return code;
        ref_stack_set_error_codes(pes, gs_error_ExecStackUnderflow,
                                  gs_error_execstackoverflow);
        /**************** E-STACK EXPANSION IS NYI. ****************/
        ref_stack_allow_expansion(pes, false);
        ref_stack_set_max_count(pes, MAX_ESTACK);
        stk.value.refs += REFS_SIZE_ESTACK;
    }

    {
        ref_stack_t *pds = &pcst->dict_stack.stack;

        r_set_size(&stk, REFS_SIZE_DSTACK);
        code = ref_stack_init(pds, &stk, 0, 0, NULL, smem, NULL);
        if (code < 0)
            return code;
        ref_stack_set_error_codes(pds, gs_error_dictstackunderflow,
                                  gs_error_dictstackoverflow);
        ref_stack_set_max_count(pds, MAX_DSTACK);
    }

#undef REFS_SIZE_OSTACK
#undef REFS_SIZE_ESTACK
#undef REFS_SIZE_DSTACK
    return 0;
}

Project: ghostpdl
File: interp.c

zcurrentstackprotect(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    ref *ep = oparray_find(i_ctx_p);

    if (ep == 0)
        return_error(gs_error_rangecheck);
    push(1);
    make_bool(op, ep->value.opproc == oparray_cleanup);
    return 0;
}

Project: ghostpdl
File: interp.c

interp_exit(i_ctx_t *i_ctx_p)
{
    return gs_error_InterpreterExit;
}

Project: ghostpdl
File: istack.c

ref_stack_counttomark(const ref_stack_t *pstack)
{
    uint scanned = 0;
    ref_stack_enum_t rsenum;

    ref_stack_enum_begin(&rsenum, pstack);
    do {
        uint count = rsenum.size;
        const ref *p = rsenum.ptr + count - 1;

        for (; count; count--, p--)
            if (r_has_type(p, t_mark))
                return scanned + (rsenum.size - count + 1);
        scanned += rsenum.size;
    } while (ref_stack_enum_next(&rsenum));
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_set_max_count(ref_stack_t *pstack, long nmax)
{
    long nmin;

    /* Bypass checking if we're setting the amximum to -1 'no limits' */
    if (nmax == -1) {
        pstack->max_stack.value.intval = nmax;
        return 0;
    }

    /* check how many items we already have on the stack, don't allow
     * a maximum less than this.
     */
    nmin = ref_stack_count_inline(pstack);

    if (nmax < nmin)
        nmax = nmin;
    if (nmax > max_uint / sizeof(ref))
        nmax = max_uint / sizeof(ref);
    if (!pstack->params->allow_expansion) {
        uint ncur = pstack->body_size;

        if (nmax > ncur)
            nmax = ncur;
    }
    pstack->max_stack.value.intval = nmax;
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_push(ref_stack_t *pstack, uint count)
{
    /* Don't bother to pre-check for overflow: we must be able to */
    /* back out in the case of a VMerror anyway, and */
    /* ref_stack_push_block will make the check itself. */
    uint needed = count;
    uint added;

    for (; (added = pstack->top - pstack->p) < needed; needed -= added) {
        int code;

        pstack->p = pstack->top;
        code = ref_stack_push_block(pstack,
                                    (pstack->top - pstack->bot + 1) / 3,
                                    added);
        if (code < 0) {
            /* Back out. */
            ref_stack_pop(pstack, count - needed + added);
            pstack->requested = count;
            return code;
        }
    }
    pstack->p += needed;
    return 0;
}

Project: ghostpdl
File: interp.c

zsetstackprotect(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    ref *ep = oparray_find(i_ctx_p);

    check_type(*op, t_boolean);
    if (ep == 0)
        return_error(gs_error_rangecheck);
    ep->value.opproc =
        (op->value.boolval ? oparray_cleanup : oparray_no_cleanup);
    pop(1);
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_push_block(ref_stack_t *pstack, uint keep, uint add)
{
    const ref_stack_params_t *params = pstack->params;
    uint count = pstack->p - pstack->bot + 1;
    uint move = count - keep;
    ref_stack_block *pcur = (ref_stack_block *) pstack->current.value.refs;
    ref next;
    ref_stack_block *pnext;
    ref *body;
    int code;

    if (keep > count)
        return_error(gs_error_Fatal);
    /* Check for overflowing the maximum size, */
    /* or expansion not allowed.  */
    /* Or specifically allowing unlimited expansion */
    if (pstack->max_stack.value.intval > 0) {
        if (pstack->extension_used + (pstack->top - pstack->bot) + add >=
            pstack->max_stack.value.intval ||
            !params->allow_expansion
            )
            return_error(params->overflow_error);
    }
    code = gs_alloc_ref_array(pstack->memory, &next, 0,
                              params->block_size, "ref_stack_push_block");
    if (code < 0)
        return code;
    pnext = (ref_stack_block *) next.value.refs;
    body = (ref *) (pnext + 1);
    /* Copy the top keep elements into the new block, */
    /* and make the new block the top block. */
    init_block(pstack, &next, keep);
    body += params->bot_guard;
    memcpy(body, pstack->bot + move, keep * sizeof(ref));
    /* Clear the elements above the top of the new block. */
    refset_null_new(body + keep, params->data_size - keep, 0);
    /* Clear the elements above the top of the old block. */
    refset_null_new(pstack->bot + move, keep, 0);
    pnext->next = pstack->current;
    pcur->used.value.refs = pstack->bot;
    r_set_size(&pcur->used, move);
    pstack->current = next;
    pstack->bot = body;
    pstack->top = pstack->bot + pstack->body_size - 1;
    pstack->p = pstack->bot + keep - 1;
    pstack->extension_size += pstack->body_size;
    pstack->extension_used += move;
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_set_margin(ref_stack_t *pstack, uint margin)
{
    const ref_stack_params_t *params = pstack->params;
    uint data_size = params->data_size;

    if (margin <= pstack->margin) {
        refset_null_new(pstack->top + 1, pstack->margin - margin, 0);
    } else {
        if (margin > data_size >> 1)
            return_error(gs_error_rangecheck);
        if (pstack->top - pstack->p < margin) {
            uint used = pstack->p + 1 - pstack->bot;
            uint keep = data_size - margin;
            int code = ref_stack_push_block(pstack, keep, used - keep);

            if (code < 0)
                return code;
        }
    }
    pstack->margin = margin;
    pstack->body_size = data_size - margin;
    pstack->top = pstack->bot + pstack->body_size - 1;
    return 0;
}

Project: ghostpdl
File: interp.c

zactonuel(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;

    push(1);
    make_bool(op, !!gs_lib_ctx_get_act_on_uel((gs_memory_t *)(i_ctx_p->memory.current)));
    return 0;
}

Project: ghostpdl
File: istack.c

static RELOC_PTRS_WITH(ref_stack_reloc_ptrs, ref_stack_t *sptr)
{
    /* Note that the relocation must be a multiple of sizeof(ref_packed) */
    /* * align_packed_per_ref, but it need not be a multiple of */
    /* sizeof(ref).  Therefore, we must do the adjustments using */
    /* ref_packed pointers rather than ref pointers. */
    ref_packed *bot = (ref_packed *) sptr->current.value.refs;
    long reloc;

    RELOC_REF_VAR(sptr->current);
    r_clear_attrs(&sptr->current, l_mark);
    reloc = bot - (ref_packed *) sptr->current.value.refs;
#define RELOC_P(p)\
  sptr->p = (ref *)((ref_packed *)sptr->p - reloc);
    RELOC_P(p);
    RELOC_P(bot);
    RELOC_P(top);
#undef RELOC_P
    RELOC_OBJ_VAR(sptr->params);
} RELOC_PTRS_END

Project: ghostpdl
File: interp.c

oparray_cleanup(i_ctx_t *i_ctx_p)
{                               /* esp points just below the cleanup procedure. */
    es_ptr ep = esp;
    uint ocount_old = (uint) ep[3].value.intval;
    uint dcount_old = (uint) ep[4].value.intval;
    uint ocount = ref_stack_count(&o_stack);
    uint dcount = ref_stack_count(&d_stack);

    if (ocount > ocount_old)
        ref_stack_pop(&o_stack, ocount - ocount_old);
    if (dcount > dcount_old) {
        ref_stack_pop(&d_stack, dcount - dcount_old);
        dict_set_top();
    }
    return 0;
}

Project: ghostpdl
File: interp.c

errorexec_cleanup(i_ctx_t *i_ctx_p)
{
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_set_error_codes(ref_stack_t *pstack, int underflow_error,
                          int overflow_error)
{
    pstack->params->underflow_error = underflow_error;
    pstack->params->overflow_error = overflow_error;
}

Project: ghostpdl
File: interp.c

oparray_pop(i_ctx_t *i_ctx_p)
{
    esp -= 4;
    return o_pop_estack;
}

Project: ghostpdl
File: interp.c

gs_interp_reset(i_ctx_t *i_ctx_p)
{   /* Reset the stacks. */
    ref_stack_clear(&o_stack);
    ref_stack_clear(&e_stack);
    esp++;
    make_oper(esp, 0, interp_exit);
    ref_stack_pop_to(&d_stack, min_dstack_size);
    dict_set_top();
}

Project: ghostpdl
File: interp.c

interp_reclaim(i_ctx_t **pi_ctx_p, int space)
{
    i_ctx_t *i_ctx_p = *pi_ctx_p;
    gs_gc_root_t ctx_root, *r = &ctx_root;
    int code;

#ifdef DEBUG
    if (gs_debug_c(gs_debug_flag_gc_disable))
        return 0;
#endif

    gs_register_struct_root(imemory_system, &r,
                            (void **)pi_ctx_p, "interp_reclaim(pi_ctx_p)");
    code = (*idmemory->reclaim)(idmemory, space);
    i_ctx_p = *pi_ctx_p;        /* may have moved */
    gs_unregister_root(imemory_system, r, "interp_reclaim(pi_ctx_p)");
    return code;
}

Project: ghostpdl
File: istack.c

ref_stack_count(const ref_stack_t *pstack)
{
    return ref_stack_count_inline(pstack);
}

Project: ghostpdl
File: istack.c

ref_stack_pop_block(ref_stack_t *pstack)
{
    s_ptr bot = pstack->bot;
    uint count = pstack->p + 1 - bot;
    ref_stack_block *pcur =
    (ref_stack_block *) pstack->current.value.refs;
    ref_stack_block *pnext =
    (ref_stack_block *) pcur->next.value.refs;
    uint used;
    ref *body;
    ref next;

    if (pnext == 0)
        return_error(pstack->params->underflow_error);
    used = r_size(&pnext->used);
    body = (ref *) (pnext + 1) + pstack->params->bot_guard;
    next = pcur->next;
    /*
       * If the contents of the two blocks won't fit in a single block, we
       * move up the used part of the top block, and copy up as much of
       * the contents of the next block under it as will fit.  If the
       * contents of both blocks fit in a single block, we copy the used
       * part of the top block to the top of the next block, and free the
       * top block.
     */
    if (used + count > pstack->body_size) {
        /*
         * The contents of the two blocks won't fit into a single block.
         * On the assumption that we're recovering from a local stack
         * underflow and need to increase the number of contiguous
         * elements available, move up the used part of the top block, and
         * copy up as much of the contents of the next block under it as
         * will fit.
         */
        uint moved = pstack->body_size - count;
        uint left;

        if (moved == 0)
            return_error(gs_error_Fatal);
        memmove(bot + moved, bot, count * sizeof(ref));
        left = used - moved;
        memcpy(bot, body + left, moved * sizeof(ref));
        refset_null_new(body + left, moved, 0);
        r_dec_size(&pnext->used, moved);
        pstack->p = pstack->top;
        pstack->extension_used -= moved;
    } else {
        /*
           * The contents of the two blocks will fit into a single block.
           * Copy the used part of the top block to the top of the next
           * block, and free the top block.
         */
        memcpy(body + used, bot, count * sizeof(ref));
        pstack->bot = bot = body;
        pstack->top = bot + pstack->body_size - 1;
        gs_free_ref_array(pstack->memory, &pstack->current,
                          "ref_stack_pop_block");
        pstack->current = next;
        pstack->p = bot + (used + count - 1);
        pstack->extension_size -= pstack->body_size;
        pstack->extension_used -= used;
    }
    return 0;
}

Project: ghostpdl
File: interp.c

estack_underflow(i_ctx_t *i_ctx_p)
{
    return gs_error_ExecStackUnderflow;
}

Project: ghostpdl
File: interp.c

gs_errorname(i_ctx_t *i_ctx_p, int code, ref * perror_name)
{
    ref *perrordict, *pErrorNames;

    if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
        dict_find_string(systemdict, "ErrorNames", &pErrorNames) <= 0
        )
        return_error(gs_error_undefined);      /* errordict or ErrorNames not found?! */
    return array_get(imemory, pErrorNames, (long)(-code - 1), perror_name);
}

Project: ghostpdl
File: istack.c

ref_stack_pop(ref_stack_t *pstack, uint count)
{
    uint used;

    while ((used = pstack->p + 1 - pstack->bot) < count) {
        count -= used;
        pstack->p = pstack->bot - 1;
        ref_stack_pop_block(pstack);
    }
    pstack->p -= count;
}

Project: ghostpdl
File: interp.c

do_call_operator(op_proc_t op_proc, i_ctx_t *i_ctx_p)
{
    int code;
    code = op_proc(i_ctx_p);
    if (gs_debug_c(gs_debug_flag_validate_clumps))
        ivalidate_clean_spaces(i_ctx_p);
    return code; /* A good place for a conditional breakpoint. */
}

Project: ghostpdl
File: istack.c

init_block(ref_stack_t *pstack, const ref *psb, uint used)
{
    ref_stack_params_t *params = pstack->params;
    ref *brefs = psb->value.refs;
    uint i;
    ref *p;

    for (i = params->bot_guard, p = brefs + stack_block_refs;
         i != 0; i--, p++
        )
        ref_assign(p, &params->guard_value);
    /* The top guard elements will never be read, */
    /* but we need to initialize them for the sake of the GC. */
    /* We can use refset_null for this, because even though it uses */
    /* make_null_new and stack elements must not be marked new, */
    /* these slots will never actually be read or written. */
    if (params->top_guard) {
        ref *top = brefs + r_size(psb);
        int top_guard = params->top_guard;

        refset_null_new(top - top_guard, top_guard, 0);
    } {
        ref_stack_block *const pblock = (ref_stack_block *) brefs;

        pblock->used = *psb;
        pblock->used.value.refs = brefs + stack_block_refs + params->bot_guard;
        r_set_size(&pblock->used, 0);
    }
}

Project: ghostpdl
File: interp.c

oparray_no_cleanup(i_ctx_t *i_ctx_p)
{
    return 0;
}

Project: ghostpdl
File: interp.c

interp(i_ctx_t **pi_ctx_p /* context for execution, updated if resched */,
       const ref * pref /* object to interpret */,
       ref * perror_object)
{
    i_ctx_t *i_ctx_p = *pi_ctx_p;
    /*
     * Note that iref may actually be either a ref * or a ref_packed *.
     * Certain DEC compilers assume that a ref * is ref-aligned even if it
     * is cast to a short *, and generate code on this assumption, leading
     * to "unaligned access" errors.  For this reason, we declare
     * iref_packed, and use a macro to cast it to the more aligned type
     * where necessary (which is almost everywhere it is used).  This may
     * lead to compiler warnings about "cast increases alignment
     * requirements", but this is less harmful than expensive traps at run
     * time.
     */
    register const ref_packed *iref_packed = (const ref_packed *)pref;
    /*
     * To make matters worse, some versions of gcc/egcs have a bug that
     * leads them to assume that if iref_packed is EVER cast to a ref *,
     * it is ALWAYS ref-aligned.  We detect this in stdpre.h and provide
     * the following workaround:
     */
#ifdef ALIGNMENT_ALIASING_BUG
    const ref *iref_temp;
#  define IREF (iref_temp = (const ref *)iref_packed, iref_temp)
#else
#  define IREF ((const ref *)iref_packed)
#endif
#define SET_IREF(rp) (iref_packed = (const ref_packed *)(rp))
    register int icount = 0;    /* # of consecutive tokens at iref */
    register os_ptr iosp = osp; /* private copy of osp */
    register es_ptr iesp = esp; /* private copy of esp */
    int code;
    ref token;                  /* token read from file or string, */
                                /* must be declared in this scope */
    ref *pvalue;
    ref refnull;
    uint opindex;               /* needed for oparrays */
    os_ptr whichp;

    /*
     * We have to make the error information into a struct;
     * otherwise, the Watcom compiler will assign it to registers
     * strictly on the basis of textual frequency.
     * We also have to use ref_assign_inline everywhere, and
     * avoid direct assignments of refs, so that esi and edi
     * will remain available on Intel processors.
     */
    struct interp_error_s {
        int code;
        int line;
        const ref *obj;
        ref full;
    } ierror;

    /*
     * Get a pointer to the name table so that we can use the
     * inline version of name_index_ref.
     */
    const name_table *const int_nt = imemory->gs_lib_ctx->gs_name_table;

#define set_error(ecode)\
  { ierror.code = ecode; ierror.line = __LINE__; }
#define return_with_error(ecode, objp)\
  { set_error(ecode); ierror.obj = objp; goto rwe; }
#define return_with_error_iref(ecode)\
  { set_error(ecode); goto rwei; }
#define return_with_code_iref()\
  { ierror.line = __LINE__; goto rweci; }
#define return_with_stackoverflow(objp)\
  { o_stack.requested = 1; return_with_error(gs_error_stackoverflow, objp); }
#define return_with_stackoverflow_iref()\
  { o_stack.requested = 1; return_with_error_iref(gs_error_stackoverflow); }
/*
 * If control reaches the special operators (x_add, etc.) as a result of
 * interpreting an executable name, iref points to the name, not the
 * operator, so the name rather than the operator becomes the error object,
 * which is wrong.  We detect and handle this case explicitly when an error
 * occurs, so as not to slow down the non-error case.
 */
#define return_with_error_tx_op(err_code)\
  { if (r_has_type(IREF, t_name)) {\
        return_with_error(err_code, pvalue);\
    } else {\
        return_with_error_iref(err_code);\
    }\
  }

    int *ticks_left = &imemory_system->gs_lib_ctx->gcsignal;

#if defined(DEBUG_TRACE_PS_OPERATORS) || defined(DEBUG)
    int (*call_operator_fn)(op_proc_t, i_ctx_t *) = do_call_operator;

    if (gs_debug_c('!'))
        call_operator_fn = do_call_operator_verbose;
#endif

    *ticks_left = i_ctx_p->time_slice_ticks;

     make_null(&ierror.full);
     ierror.obj = &ierror.full;
     make_null(&refnull);
     pvalue = &refnull;

    /*
     * If we exceed the VMThreshold, set *ticks_left to -100
     * to alert the interpreter that we need to garbage collect.
     */
    set_gc_signal(i_ctx_p, -100);

    esfile_clear_cache();
    /*
     * From here on, if icount > 0, iref and icount correspond
     * to the top entry on the execution stack: icount is the count
     * of sequential entries remaining AFTER the current one.
     */
#define IREF_NEXT(ip)\
  ((const ref_packed *)((const ref *)(ip) + 1))
#define IREF_NEXT_EITHER(ip)\
  ( r_is_packed(ip) ? (ip) + 1 : IREF_NEXT(ip) )
#define store_state(ep)\
  ( icount > 0 ? (ep->value.const_refs = IREF + 1, r_set_size(ep, icount)) : 0 )
#define store_state_short(ep)\
  ( icount > 0 ? (ep->value.packed = iref_packed + 1, r_set_size(ep, icount)) : 0 )
#define store_state_either(ep)\
  ( icount > 0 ? (ep->value.packed = IREF_NEXT_EITHER(iref_packed), r_set_size(ep, icount)) : 0 )
#define next()\
  if ( --icount > 0 ) { iref_packed = IREF_NEXT(iref_packed); goto top; } else goto out
#define next_short()\
  if ( --icount <= 0 ) { if ( icount < 0 ) goto up; iesp--; }\
  ++iref_packed; goto top
#define next_either()\
  if ( --icount <= 0 ) { if ( icount < 0 ) goto up; iesp--; }\
  iref_packed = IREF_NEXT_EITHER(iref_packed); goto top

#if !PACKED_SPECIAL_OPS
#  undef next_either
#  define next_either() next()
#  undef store_state_either
#  define store_state_either(ep) store_state(ep)
#endif

    /* We want to recognize executable arrays here, */
    /* so we push the argument on the estack and enter */
    /* the loop at the bottom. */
    if (iesp >= estop)
        return_with_error(gs_error_execstackoverflow, pref);
    ++iesp;
    ref_assign_inline(iesp, pref);
    goto bot;
  top:
        /*
         * This is the top of the interpreter loop.
         * iref points to the ref being interpreted.
         * Note that this might be an element of a packed array,
         * not a real ref: we carefully arranged the first 16 bits of
         * a ref and of a packed array element so they could be distinguished
         * from each other.  (See ghost.h and packed.h for more detail.)
         */
    INCR(top);
#ifdef DEBUG
    /* Do a little validation on the top o-stack entry. */
    if (iosp >= osbot &&
        (r_type(iosp) == t__invalid || r_type(iosp) >= tx_next_op)
        ) {
        mlprintf(imemory, "Invalid value on o-stack!\n");
        return_with_error_iref(gs_error_Fatal);
    }
    if (gs_debug['I'] ||
        (gs_debug['i'] &&
         (r_is_packed(iref_packed) ?
          r_packed_is_name(iref_packed) :
          r_has_type(IREF, t_name)))
        ) {
        os_ptr save_osp = osp;  /* avoid side-effects */
        es_ptr save_esp = esp;

        osp = iosp;
        esp = iesp;
        dmlprintf5(imemory, "d%u,e%u<%u>0x%lx(%d): ",
                  ref_stack_count(&d_stack), ref_stack_count(&e_stack),
                  ref_stack_count(&o_stack), (ulong)IREF, icount);
        debug_print_ref(imemory, IREF);
        if (iosp >= osbot) {
            dmputs(imemory, " // ");
            debug_print_ref(imemory, iosp);
        }
        dmputc(imemory, '\n');
        osp = save_osp;
        esp = save_esp;
        dmflush(imemory);
    }
#endif
/* Objects that have attributes (arrays, dictionaries, files, and strings) */
/* use lit and exec; other objects use plain and plain_exec. */
#define lit(t) type_xe_value(t, a_execute)
#define exec(t) type_xe_value(t, a_execute + a_executable)
#define nox(t) type_xe_value(t, 0)
#define nox_exec(t) type_xe_value(t, a_executable)
#define plain(t) type_xe_value(t, 0)
#define plain_exec(t) type_xe_value(t, a_executable)
    /*
     * We have to populate enough cases of the switch statement to force
     * some compilers to use a dispatch rather than a testing loop.
     * What a nuisance!
     */
    switch (r_type_xe(iref_packed)) {
            /* Access errors. */
#define cases_invalid()\
  case plain(t__invalid): case plain_exec(t__invalid)
          cases_invalid():
            return_with_error_iref(gs_error_Fatal);
#define cases_nox()\
  case nox_exec(t_array): case nox_exec(t_dictionary):\
  case nox_exec(t_file): case nox_exec(t_string):\
  case nox_exec(t_mixedarray): case nox_exec(t_shortarray)
          cases_nox():
            return_with_error_iref(gs_error_invalidaccess);
            /*
             * Literal objects.  We have to enumerate all the types.
             * In fact, we have to include some extra plain_exec entries
             * just to populate the switch.  We break them up into groups
             * to avoid overflowing some preprocessors.
             */
#define cases_lit_1()\
  case lit(t_array): case nox(t_array):\
  case plain(t_boolean): case plain_exec(t_boolean):\
  case lit(t_dictionary): case nox(t_dictionary)
#define cases_lit_2()\
  case lit(t_file): case nox(t_file):\
  case plain(t_fontID): case plain_exec(t_fontID):\
  case plain(t_integer): case plain_exec(t_integer):\
  case plain(t_mark): case plain_exec(t_mark)
#define cases_lit_3()\
  case plain(t_name):\
  case plain(t_null):\
  case plain(t_oparray):\
  case plain(t_operator)
#define cases_lit_4()\
  case plain(t_real): case plain_exec(t_real):\
  case plain(t_save): case plain_exec(t_save):\
  case lit(t_string): case nox(t_string)
#define cases_lit_5()\
  case lit(t_mixedarray): case nox(t_mixedarray):\
  case lit(t_shortarray): case nox(t_shortarray):\
  case plain(t_device): case plain_exec(t_device):\
  case plain(t_struct): case plain_exec(t_struct):\
  case plain(t_astruct): case plain_exec(t_astruct)
            /* Executable arrays are treated as literals in direct execution. */
#define cases_lit_array()\
  case exec(t_array): case exec(t_mixedarray): case exec(t_shortarray)
          cases_lit_1():
          cases_lit_2():
          cases_lit_3():
          cases_lit_4():
          cases_lit_5():
            INCR(lit);
            break;
          cases_lit_array():
            INCR(lit_array);
            break;
            /* Special operators. */
        case plain_exec(tx_op_add):
x_add:      INCR(x_add);
            osp = iosp; /* sync o_stack */
            if ((code = zop_add(i_ctx_p)) < 0)
                return_with_error_tx_op(code);
            iosp--;
            next_either();
        case plain_exec(tx_op_def):
x_def:      INCR(x_def);
            osp = iosp; /* sync o_stack */
            if ((code = zop_def(i_ctx_p)) < 0)
                return_with_error_tx_op(code);
            iosp -= 2;
            next_either();
        case plain_exec(tx_op_dup):
x_dup:      INCR(x_dup);
            if (iosp < osbot)
                return_with_error_tx_op(gs_error_stackunderflow);
            if (iosp >= ostop) {
                o_stack.requested = 1;
                return_with_error_tx_op(gs_error_stackoverflow);
            }
            iosp++;
            ref_assign_inline(iosp, iosp - 1);
            next_either();
        case plain_exec(tx_op_exch):
x_exch:     INCR(x_exch);
            if (iosp <= osbot)
                return_with_error_tx_op(gs_error_stackunderflow);
            ref_assign_inline(&token, iosp);
            ref_assign_inline(iosp, iosp - 1);
            ref_assign_inline(iosp - 1, &token);
            next_either();
        case plain_exec(tx_op_if):
x_if:       INCR(x_if);
            if (!r_is_proc(iosp))
                return_with_error_tx_op(check_proc_failed(iosp));
            if (!r_has_type(iosp - 1, t_boolean))
                return_with_error_tx_op((iosp <= osbot ?
                                        gs_error_stackunderflow : gs_error_typecheck));
            if (!iosp[-1].value.boolval) {
                iosp -= 2;
                next_either();
            }
            if (iesp >= estop)
                return_with_error_tx_op(gs_error_execstackoverflow);
            store_state_either(iesp);
            whichp = iosp;
            iosp -= 2;
            goto ifup;
        case plain_exec(tx_op_ifelse):
x_ifelse:   INCR(x_ifelse);
            if (!r_is_proc(iosp))
                return_with_error_tx_op(check_proc_failed(iosp));
            if (!r_is_proc(iosp - 1))
                return_with_error_tx_op(check_proc_failed(iosp - 1));
            if (!r_has_type(iosp - 2, t_boolean))
                return_with_error_tx_op((iosp < osbot + 2 ?
                                        gs_error_stackunderflow : gs_error_typecheck));
            if (iesp >= estop)
                return_with_error_tx_op(gs_error_execstackoverflow);
            store_state_either(iesp);
            whichp = (iosp[-2].value.boolval ? iosp - 1 : iosp);
            iosp -= 3;
            /* Open code "up" for the array case(s) */
          ifup:if ((icount = r_size(whichp) - 1) <= 0) {
                if (icount < 0)
                    goto up;    /* 0-element proc */
                SET_IREF(whichp->value.refs);   /* 1-element proc */
                if (--(*ticks_left) > 0)
                    goto top;
            }
            ++iesp;
            /* Do a ref_assign, but also set iref. */
            iesp->tas = whichp->tas;
            SET_IREF(iesp->value.refs = whichp->value.refs);
            if (--(*ticks_left) > 0)
                goto top;
            goto slice;
        case plain_exec(tx_op_index):
x_index:    INCR(x_index);
            osp = iosp; /* zindex references o_stack */
            if ((code = zindex(i_ctx_p)) < 0)
                return_with_error_tx_op(code);
            next_either();
        case plain_exec(tx_op_pop):
x_pop:      INCR(x_pop);
            if (iosp < osbot)
                return_with_error_tx_op(gs_error_stackunderflow);
            iosp--;
            next_either();
        case plain_exec(tx_op_roll):
x_roll:     INCR(x_roll);
            osp = iosp; /* zroll references o_stack */
            if ((code = zroll(i_ctx_p)) < 0)
                return_with_error_tx_op(code);
            iosp -= 2;
            next_either();
        case plain_exec(tx_op_sub):
x_sub:      INCR(x_sub);
            osp = iosp; /* sync o_stack */
            if ((code = zop_sub(i_ctx_p)) < 0)
                return_with_error_tx_op(code);
            iosp--;
            next_either();
            /* Executable types. */
        case plain_exec(t_null):
            goto bot;
        case plain_exec(t_oparray):
            /* Replace with the definition and go again. */
            INCR(exec_array);
            opindex = op_index(IREF);
            pvalue = (ref *)IREF->value.const_refs;
          opst:         /* Prepare to call a t_oparray procedure in *pvalue. */
            store_state(iesp);
          oppr:         /* Record the stack depths in case of failure. */
            if (iesp >= estop - 4)
                return_with_error_iref(gs_error_execstackoverflow);
            iesp += 5;
            osp = iosp;         /* ref_stack_count_inline needs this */
            make_mark_estack(iesp - 4, es_other, oparray_cleanup);
            make_int(iesp - 3, opindex); /* for .errorexec effect */
            make_int(iesp - 2, ref_stack_count_inline(&o_stack));
            make_int(iesp - 1, ref_stack_count_inline(&d_stack));
            make_op_estack(iesp, oparray_pop);
            goto pr;
          prst:         /* Prepare to call the procedure (array) in *pvalue. */
            store_state(iesp);
          pr:                   /* Call the array in *pvalue.  State has been stored. */
            /* We want to do this check before assigning icount so icount is correct
             * in the event of a gs_error_execstackoverflow
             */
            if (iesp >= estop) {
                return_with_error_iref(gs_error_execstackoverflow);
            }
            if ((icount = r_size(pvalue) - 1) <= 0) {
                if (icount < 0)
                    goto up;    /* 0-element proc */
                SET_IREF(pvalue->value.refs);   /* 1-element proc */
                if (--(*ticks_left) > 0)
                    goto top;
            }
            ++iesp;
            /* Do a ref_assign, but also set iref. */
            iesp->tas = pvalue->tas;
            SET_IREF(iesp->value.refs = pvalue->value.refs);
            if (--(*ticks_left) > 0)
                goto top;
            goto slice;
        case plain_exec(t_operator):
            INCR(exec_operator);
            if (--(*ticks_left) <= 0) {    /* The following doesn't work, */
                /* and I can't figure out why. */
/****** goto sst; ******/
            }
            esp = iesp;         /* save for operator */
            osp = iosp;         /* ditto */
            /* Operator routines take osp as an argument. */
            /* This is just a convenience, since they adjust */
            /* osp themselves to reflect the results. */
            /* Operators that (net) push information on the */
            /* operand stack must check for overflow: */
            /* this normally happens automatically through */
            /* the push macro (in oper.h). */
            /* Operators that do not typecheck their operands, */
            /* or take a variable number of arguments, */
            /* must check explicitly for stack underflow. */
            /* (See oper.h for more detail.) */
            /* Note that each case must set iosp = osp: */
            /* this is so we can switch on code without having to */
            /* store it and reload it (for dumb compilers). */
            switch (code = call_operator(real_opproc(IREF), i_ctx_p)) {
                case 0: /* normal case */
                case 1: /* alternative success case */
                    iosp = osp;
                    next();
                case o_push_estack:     /* store the state and go to up */
                    store_state(iesp);
                  opush:iosp = osp;
                    iesp = esp;
                    if (--(*ticks_left) > 0)
                        goto up;
                    goto slice;
                case o_pop_estack:      /* just go to up */
                  opop:iosp = osp;
                    if (esp == iesp)
                        goto bot;
                    iesp = esp;
                    goto up;
                case gs_error_Remap_Color:
oe_remap:           store_state(iesp);
remap:              if (iesp + 2 >= estop) {
                        esp = iesp;
                        code = ref_stack_extend(&e_stack, 2);
                        if (code < 0)
                            return_with_error_iref(code);
                        iesp = esp;
                    }
                    packed_get(imemory, iref_packed, iesp + 1);
                    make_oper(iesp + 2, 0,
                              r_ptr(&istate->remap_color_info,
                                    int_remap_color_info_t)->proc);
                    iesp += 2;
                    goto up;
            }
            iosp = osp;
            iesp = esp;
            return_with_code_iref();
        case plain_exec(t_name):
            INCR(exec_name);
            pvalue = IREF->value.pname->pvalue;
            if (!pv_valid(pvalue)) {
                uint nidx = names_index(int_nt, IREF);
                uint htemp = 0;

                INCR(find_name);
                if ((pvalue = dict_find_name_by_index_inline(nidx, htemp)) == 0)
                    return_with_error_iref(gs_error_undefined);
            }
            /* Dispatch on the type of the value. */
            /* Again, we have to over-populate the switch. */
            switch (r_type_xe(pvalue)) {
                  cases_invalid():
                    return_with_error_iref(gs_error_Fatal);
                  cases_nox():  /* access errors */
                    return_with_error_iref(gs_error_invalidaccess);
                  cases_lit_1():
                  cases_lit_2():
                  cases_lit_3():
                  cases_lit_4():
                  cases_lit_5():
                      INCR(name_lit);
                    /* Just push the value */
                    if (iosp >= ostop)
                        return_with_stackoverflow(pvalue);
                    ++iosp;
                    ref_assign_inline(iosp, pvalue);
                    next();
                case exec(t_array):
                case exec(t_mixedarray):
                case exec(t_shortarray):
                    INCR(name_proc);
                    /* This is an executable procedure, execute it. */
                    goto prst;
                case plain_exec(tx_op_add):
                    goto x_add;
                case plain_exec(tx_op_def):
                    goto x_def;
                case plain_exec(tx_op_dup):
                    goto x_dup;
                case plain_exec(tx_op_exch):
                    goto x_exch;
                case plain_exec(tx_op_if):
                    goto x_if;
                case plain_exec(tx_op_ifelse):
                    goto x_ifelse;
                case plain_exec(tx_op_index):
                    goto x_index;
                case plain_exec(tx_op_pop):
                    goto x_pop;
                case plain_exec(tx_op_roll):
                    goto x_roll;
                case plain_exec(tx_op_sub):
                    goto x_sub;
                case plain_exec(t_null):
                    goto bot;
                case plain_exec(t_oparray):
                    INCR(name_oparray);
                    opindex = op_index(pvalue);
                    pvalue = (ref *)pvalue->value.const_refs;
                    goto opst;
                case plain_exec(t_operator):
                    INCR(name_operator);
                    {           /* Shortcut for operators. */
                        /* See above for the logic. */
                        if (--(*ticks_left) <= 0) {        /* The following doesn't work, */
                            /* and I can't figure out why. */
/****** goto sst; ******/
                        }
                        esp = iesp;
                        osp = iosp;
                        switch (code = call_operator(real_opproc(pvalue),
                                                     i_ctx_p)
                                ) {
                            case 0:     /* normal case */
                            case 1:     /* alternative success case */
                                iosp = osp;
                                next();
                            case o_push_estack:
                                store_state(iesp);
                                goto opush;
                            case o_pop_estack:
                                goto opop;
                            case gs_error_Remap_Color:
                                goto oe_remap;
                        }
                        iosp = osp;
                        iesp = esp;
                        return_with_error(code, pvalue);
                    }
                case plain_exec(t_name):
                case exec(t_file):
                case exec(t_string):
                default:
                    /* Not a procedure, reinterpret it. */
                    store_state(iesp);
                    icount = 0;
                    SET_IREF(pvalue);
                    goto top;
            }
        case exec(t_file):
            {   /* Executable file.  Read the next token and interpret it. */
                stream *s;
                scanner_state sstate;

                check_read_known_file(i_ctx_p, s, IREF, return_with_error_iref);
            rt:
                if (iosp >= ostop)      /* check early */
                    return_with_stackoverflow_iref();
                osp = iosp;     /* gs_scan_token uses ostack */
                gs_scanner_init_options(&sstate, IREF, i_ctx_p->scanner_options);
            again:
                code = gs_scan_token(i_ctx_p, &token, &sstate);
                iosp = osp;     /* ditto */
                switch (code) {
                    case 0:     /* read a token */
                        /* It's worth checking for literals, which make up */
                        /* the majority of input tokens, before storing the */
                        /* state on the e-stack.  Note that because of //, */
                        /* the token may have *any* type and attributes. */
                        /* Note also that executable arrays aren't executed */
                        /* at the top level -- they're treated as literals. */
                        if (!r_has_attr(&token, a_executable) ||
                            r_is_array(&token)
                            ) { /* If gs_scan_token used the o-stack, */
                            /* we know we can do a push now; if not, */
                            /* the pre-check is still valid. */
                            iosp++;
                            ref_assign_inline(iosp, &token);
                            goto rt;
                        }
                        store_state(iesp);
                        /* Push the file on the e-stack */
                        if (iesp >= estop)
                            return_with_error_iref(gs_error_execstackoverflow);
                        esfile_set_cache(++iesp);
                        ref_assign_inline(iesp, IREF);
                        SET_IREF(&token);
                        icount = 0;
                        goto top;
                    case gs_error_undefined:   /* //name undefined */
                        gs_scanner_error_object(i_ctx_p, &sstate, &token);
                        return_with_error(code, &token);
                    case scan_EOF:      /* end of file */
                        esfile_clear_cache();
                        goto bot;
                    case scan_BOS:
                        /* Binary object sequences */
                        /* ARE executed at the top level. */
                        store_state(iesp);
                        /* Push the file on the e-stack */
                        if (iesp >= estop)
                            return_with_error_iref(gs_error_execstackoverflow);
                        esfile_set_cache(++iesp);
                        ref_assign_inline(iesp, IREF);
                        pvalue = &token;
                        goto pr;
                    case scan_Refill:
                        store_state(iesp);
                        /* iref may point into the exec stack; */
                        /* save its referent now. */
                        ref_assign_inline(&token, IREF);
                        /* Push the file on the e-stack */
                        if (iesp >= estop)
                            return_with_error_iref(gs_error_execstackoverflow);
                        ++iesp;
                        ref_assign_inline(iesp, &token);
                        esp = iesp;
                        osp = iosp;
                        code = gs_scan_handle_refill(i_ctx_p, &sstate, true,
                                                     ztokenexec_continue);
                scan_cont:
                        iosp = osp;
                        iesp = esp;
                        switch (code) {
                            case 0:
                                iesp--;         /* don't push the file */
                                goto again;     /* stacks are unchanged */
                            case o_push_estack:
                                esfile_clear_cache();
                                if (--(*ticks_left) > 0)
                                    goto up;
                                goto slice;
                        }
                        /* must be an error */
                        iesp--; /* don't push the file */
                        return_with_code_iref();
                    case scan_Comment:
                    case scan_DSC_Comment: {
                        /* See scan_Refill above for comments. */
                        ref file_token;

                        store_state(iesp);
                        ref_assign_inline(&file_token, IREF);
                        if (iesp >= estop)
                            return_with_error_iref(gs_error_execstackoverflow);
                        ++iesp;
                        ref_assign_inline(iesp, &file_token);
                        esp = iesp;
                        osp = iosp;
                        code = ztoken_handle_comment(i_ctx_p,
                                                     &sstate, &token,
                                                     code, true, true,
                                                     ztokenexec_continue);
                    }
                        goto scan_cont;
                    default:    /* error */
                        ref_assign_inline(&token, IREF);
                        gs_scanner_error_object(i_ctx_p, &sstate, &token);
                        return_with_error(code, &token);
                }
            }
        case exec(t_string):
            {                   /* Executable string.  Read a token and interpret it. */
                stream ss;
                scanner_state sstate;

                s_init(&ss, NULL);
                sread_string(&ss, IREF->value.bytes, r_size(IREF));
                gs_scanner_init_stream_options(&sstate, &ss, SCAN_FROM_STRING);
                osp = iosp;     /* gs_scan_token uses ostack */
                code = gs_scan_token(i_ctx_p, &token, &sstate);
                iosp = osp;     /* ditto */
                switch (code) {
                    case 0:     /* read a token */
                    case scan_BOS:      /* binary object sequence */
                        store_state(iesp);
                        /* If the updated string isn't empty, push it back */
                        /* on the e-stack. */
                        {
                            /* This is just the available buffer size, so
                               a signed int is plenty big
                             */
                            int size = sbufavailable(&ss);

                            if (size > 0) {
                                if (iesp >= estop)
                                    return_with_error_iref(gs_error_execstackoverflow);
                                ++iesp;
                                iesp->tas.type_attrs = IREF->tas.type_attrs;
                                iesp->value.const_bytes = sbufptr(&ss);
                                r_set_size(iesp, size);
                            }
                        }
                        if (code == 0) {
                            SET_IREF(&token);
                            icount = 0;
                            goto top;
                        }
                        /* Handle BOS specially */
                        pvalue = &token;
                        goto pr;
                    case scan_EOF:      /* end of string */
                        goto bot;
                    case scan_Refill:   /* error */
                        code = gs_note_error(gs_error_syntaxerror);
                        /* fall through */
                    default:    /* error */
                        ref_assign_inline(&token, IREF);
                        gs_scanner_error_object(i_ctx_p, &sstate, &token);
                        return_with_error(code, &token);
                }
            }
            /* Handle packed arrays here by re-dispatching. */
            /* This also picks up some anomalous cases of non-packed arrays. */
        default:
            {
                uint index;

                switch (*iref_packed >> r_packed_type_shift) {
                    case pt_full_ref:
                    case pt_full_ref + 1:
                        INCR(p_full);
                        if (iosp >= ostop)
                            return_with_stackoverflow_iref();
                        /* We know this can't be an executable object */
                        /* requiring special handling, so we just push it. */
                        ++iosp;
                        /* We know that refs are properly aligned: */
                        /* see packed.h for details. */
                        ref_assign_inline(iosp, IREF);
                        next();
                    case pt_executable_operator:
                        index = *iref_packed & packed_value_mask;
                        if (--(*ticks_left) <= 0) {        /* The following doesn't work, */
                            /* and I can't figure out why. */
/****** goto sst_short; ******/
                        }
                        if (!op_index_is_operator(index)) {
                            INCR(p_exec_oparray);
                            store_state_short(iesp);
                            opindex = index;
                            /* Call the operator procedure. */
                            index -= op_def_count;
                            pvalue = (ref *)
                                (index < r_size(&i_ctx_p->op_array_table_global.table) ?
                                 i_ctx_p->op_array_table_global.table.value.const_refs +
                                 index :
                                 i_ctx_p->op_array_table_local.table.value.const_refs +
                                 (index - r_size(&i_ctx_p->op_array_table_global.table)));
                            goto oppr;
                        }
                        INCR(p_exec_operator);
                        /* See the main plain_exec(t_operator) case */
                        /* for details of what happens here. */
#if PACKED_SPECIAL_OPS
                        /*
                         * We arranged in iinit.c that the special ops
                         * have operator indices starting at 1.
                         *
                         * The (int) cast in the next line is required
                         * because some compilers don't allow arithmetic
                         * involving two different enumerated types.
                         */
#  define case_xop(xop) case xop - (int)tx_op + 1
                        switch (index) {
                              case_xop(tx_op_add):goto x_add;
                              case_xop(tx_op_def):goto x_def;
                              case_xop(tx_op_dup):goto x_dup;
                              case_xop(tx_op_exch):goto x_exch;
                              case_xop(tx_op_if):goto x_if;
                              case_xop(tx_op_ifelse):goto x_ifelse;
                              case_xop(tx_op_index):goto x_index;
                              case_xop(tx_op_pop):goto x_pop;
                              case_xop(tx_op_roll):goto x_roll;
                              case_xop(tx_op_sub):goto x_sub;
                            case 0:     /* for dumb compilers */
                            default:
                                ;
                        }
#  undef case_xop
#endif
                        INCR(p_exec_non_x_operator);
                        esp = iesp;
                        osp = iosp;
                        switch (code = call_operator(op_index_proc(index), i_ctx_p)) {
                            case 0:
                            case 1:
                                iosp = osp;
                                next_short();
                            case o_push_estack:
                                store_state_short(iesp);
                                goto opush;
                            case o_pop_estack:
                                iosp = osp;
                                if (esp == iesp) {
                                    next_short();
                                }
                                iesp = esp;
                                goto up;
                            case gs_error_Remap_Color:
                                store_state_short(iesp);
                                goto remap;
                        }
                        iosp = osp;
                        iesp = esp;
                        return_with_code_iref();
                    case pt_integer:
                        INCR(p_integer);
                        if (iosp >= ostop)
                            return_with_stackoverflow_iref();
                        ++iosp;
                        make_int(iosp,
                                 ((int)*iref_packed & packed_int_mask) +
                                 packed_min_intval);
                        next_short();
                    case pt_literal_name:
                        INCR(p_lit_name);
                        {
                            uint nidx = *iref_packed & packed_value_mask;

                            if (iosp >= ostop)
                                return_with_stackoverflow_iref();
                            ++iosp;
                            name_index_ref_inline(int_nt, nidx, iosp);
                            next_short();
                        }
                    case pt_executable_name:
                        INCR(p_exec_name);
                        {
                            uint nidx = *iref_packed & packed_value_mask;

                            pvalue = name_index_ptr_inline(int_nt, nidx)->pvalue;
                            if (!pv_valid(pvalue)) {
                                uint htemp = 0;

                                INCR(p_find_name);
                                if ((pvalue = dict_find_name_by_index_inline(nidx, htemp)) == 0) {
                                    names_index_ref(int_nt, nidx, &token);
                                    return_with_error(gs_error_undefined, &token);
                                }
                            }
                            if (r_has_masked_attrs(pvalue, a_execute, a_execute + a_executable)) {      /* Literal, push it. */
                                INCR(p_name_lit);
                                if (iosp >= ostop)
                                    return_with_stackoverflow_iref();
                                ++iosp;
                                ref_assign_inline(iosp, pvalue);
                                next_short();
                            }
                            if (r_is_proc(pvalue)) {    /* This is an executable procedure, */
                                /* execute it. */
                                INCR(p_name_proc);
                                store_state_short(iesp);
                                goto pr;
                            }
                            /* Not a literal or procedure, reinterpret it. */
                            store_state_short(iesp);
                            icount = 0;
                            SET_IREF(pvalue);
                            goto top;
                        }
                        /* default can't happen here */
                }
            }
    }
    /* Literal type, just push it. */
    if (iosp >= ostop)
        return_with_stackoverflow_iref();
    ++iosp;
    ref_assign_inline(iosp, IREF);
  bot:next();
  out:                          /* At most 1 more token in the current procedure. */
    /* (We already decremented icount.) */
    if (!icount) {
        /* Pop the execution stack for tail recursion. */
        iesp--;
        iref_packed = IREF_NEXT(iref_packed);
        goto top;
    }
  up:if (--(*ticks_left) < 0)
        goto slice;
    /* See if there is anything left on the execution stack. */
    if (!r_is_proc(iesp)) {
        SET_IREF(iesp--);
        icount = 0;
        goto top;
    }
    SET_IREF(iesp->value.refs); /* next element of array */
    icount = r_size(iesp) - 1;
    if (icount <= 0) {          /* <= 1 more elements */
        iesp--;                 /* pop, or tail recursion */
        if (icount < 0)
            goto up;
    }
    goto top;
  sched:                        /* We've just called a scheduling procedure. */
    /* The interpreter state is in memory; iref is not current. */
    if (code < 0) {
        set_error(code);
        /*
         * We need a real object to return as the error object.
         * (It only has to last long enough to store in
         * *perror_object.)
         */
        make_null_proc(&ierror.full);
        SET_IREF(ierror.obj = &ierror.full);
        goto error_exit;
    }
    /* Reload state information from memory. */
    iosp = osp;
    iesp = esp;
    goto up;
#if 0                           /****** ****** ***** */
  sst:                          /* Time-slice, but push the current object first. */
    store_state(iesp);
    if (iesp >= estop)
        return_with_error_iref(gs_error_execstackoverflow);
    iesp++;
    ref_assign_inline(iesp, iref);
#endif /****** ****** ***** */
  slice:                        /* It's time to time-slice or garbage collect. */
    /* iref is not live, so we don't need to do a store_state. */
    osp = iosp;
    esp = iesp;
    /* If *ticks_left <= -100, we need to GC now. */
    if ((*ticks_left) <= -100) {   /* We need to garbage collect now. */
        *pi_ctx_p = i_ctx_p;
        code = interp_reclaim(pi_ctx_p, -1);
        i_ctx_p = *pi_ctx_p;
    } else
        code = 0;
    *ticks_left = i_ctx_p->time_slice_ticks;
    set_code_on_interrupt(imemory, &code);
    goto sched;

    /* Error exits. */

  rweci:
    ierror.code = code;
  rwei:
    ierror.obj = IREF;
  rwe:
    if (!r_is_packed(iref_packed))
        store_state(iesp);
    else {
        /*
         * We need a real object to return as the error object.
         * (It only has to last long enough to store in *perror_object.)
         */
        packed_get(imemory, (const ref_packed *)ierror.obj, &ierror.full);
        store_state_short(iesp);
        if (IREF == ierror.obj)
            SET_IREF(&ierror.full);
        ierror.obj = &ierror.full;
    }
  error_exit:
    if (GS_ERROR_IS_INTERRUPT(ierror.code)) {      /* We must push the current object being interpreted */
        /* back on the e-stack so it will be re-executed. */
        /* Currently, this is always an executable operator, */
        /* but it might be something else someday if we check */
        /* for interrupts in the interpreter loop itself. */
        if (iesp >= estop)
            ierror.code = gs_error_execstackoverflow;
        else {
            iesp++;
            ref_assign_inline(iesp, IREF);
        }
    }
    esp = iesp;
    osp = iosp;
    ref_assign_inline(perror_object, ierror.obj);
#ifdef DEBUG
    if (ierror.code == gs_error_InterpreterExit) {
        /* Do not call gs_log_error to reduce the noise. */
        return gs_error_InterpreterExit;
    }
#endif
    return gs_log_error(ierror.code, __FILE__, ierror.line);
}

Project: ghostpdl
File: interp.c

oparray_find(i_ctx_t *i_ctx_p)
{
    long i;
    ref *ep;

    for (i = 0; (ep = ref_stack_index(&e_stack, i)) != 0; ++i) {
        if (r_is_estack_mark(ep) &&
            (ep->value.opproc == oparray_cleanup ||
             ep->value.opproc == oparray_no_cleanup)
            )
            return ep;
    }
    return 0;
}

Project: ghostpdl
File: istack.c

CLEAR_MARKS_PROC(ref_stack_clear_marks)
{
    ref_stack_t *const sptr = vptr;

    r_clear_attrs(&sptr->current, l_mark);
}

Project: ghostpdl
File: interp.c

errorexec_find(i_ctx_t *i_ctx_p, ref *perror_object)
{
    long i;
    const ref *ep;

    for (i = 0; (ep = ref_stack_index(&e_stack, i)) != 0; ++i) {
        if (r_is_estack_mark(ep)) {
            if (ep->value.opproc == oparray_cleanup) {
                /* See oppr: above. */
                uint opindex = (uint)ep[1].value.intval;
                if (opindex == 0) /* internal operator, ignore */
                    continue;
                op_index_ref(imemory, opindex, perror_object);
                return 1;
            }
            if (ep->value.opproc == oparray_no_cleanup)
                return 0;       /* protection disabled */
            if (ep->value.opproc == errorexec_cleanup) {
                if (r_has_type(ep + 1, t_null))
                    return 0;
                *perror_object = ep[1]; /* see .errorexec above */
                return 1;
            }
        }
    }
    return 0;
}

Project: ghostpdl
File: istack.c

ref_stack_store_check(const ref_stack_t *pstack, ref *parray, uint count,
                      uint skip)
{
    uint space = r_space(parray);

    if (space != avm_local) {
        uint left = count, pass = skip;
        ref_stack_enum_t rsenum;

        ref_stack_enum_begin(&rsenum, pstack);
        do {
            ref *ptr = rsenum.ptr;
            uint size = rsenum.size;

            if (size <= pass)
                pass -= size;
            else {
                int code;

                if (pass != 0)
                    size -= pass, pass = 0;
                ptr += size;
                if (size > left)
                    size = left;
                left -= size;
                code = refs_check_space(ptr - size, size, space);
                if (code < 0)
                    return code;
                if (left == 0)
                    break;
            }
        } while (ref_stack_enum_next(&rsenum));
    }
    return 0;
}

Project: ghostpdl
File: interp.c

zfinderrorobject(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    ref errobj;

    if (errorexec_find(i_ctx_p, &errobj)) {
        push(2);
        op[-1] = errobj;
        make_true(op);
    } else {
        push(1);
        make_false(op);
    }
    return 0;
}

Project: ghostpdl
File: interp.c

set_gc_signal(i_ctx_t *i_ctx_p, int value)
{
    gs_memory_gc_status_t stat;
    int i;

    for (i = 0; i < countof(idmemory->spaces_indexed); i++) {
        gs_ref_memory_t *mem = idmemory->spaces_indexed[i];
        gs_ref_memory_t *mem_stable;

        if (mem == 0)
            continue;
        for (;; mem = mem_stable) {
            mem_stable = (gs_ref_memory_t *)
                gs_memory_stable((gs_memory_t *)mem);
            gs_memory_gc_status(mem, &stat);
            stat.signal_value = value;
            gs_memory_set_gc_status(mem, &stat);
            if (mem_stable == mem)
                break;
        }
    }
}

Project: ghostpdl
File: istack.c

ref_stack_extend(ref_stack_t *pstack, uint request)
{
    uint keep = (pstack->top - pstack->bot + 1) / 3;
    uint count = pstack->p - pstack->bot + 1;
    const ref_stack_params_t *params = pstack->params;

    if (request > params->data_size)
        return_error(params->overflow_error);
    if (keep + request > pstack->body_size)
        keep = pstack->body_size - request;
    if (keep > count)
        keep = count;		/* required by ref_stack_push_block */
    return ref_stack_push_block(pstack, keep, request);
}