static avifDecoderItem * avifMetaFindItem(avifMeta * meta, uint32_t itemID)
{
    if (itemID == 0) {
        return NULL;
    }

    for (uint32_t i = 0; i < meta->items.count; ++i) {
        if (meta->items.item[i].id == itemID) {
            return &meta->items.item[i];
        }
    }

    avifDecoderItem * item = (avifDecoderItem *)avifArrayPushPtr(&meta->items);
    avifArrayCreate(&item->properties, sizeof(avifProperty), 16);
    item->id = itemID;
    item->meta = meta;
    return item;
}

static const size_t VISUALSAMPLEENTRY_SIZE = 78;

static const char xmpContentType[] = CONTENT_TYPE_XMP;

static const size_t xmpContentTypeSize = sizeof(xmpContentType);

typedef struct avifFileType
{
    uint8_t majorBrand[4];
    uint32_t minorVersion;
    // If not null, points to a memory block of 4 * compatibleBrandsCount bytes.
    const uint8_t * compatibleBrands;
    int compatibleBrandsCount;
} avifFileType;

typedef struct avifImageSpatialExtents
{
    uint32_t width;
    uint32_t height;
} avifImageSpatialExtents;

struct avifMeta

typedef struct avifProperty
{
    uint8_t type[4];
    union
    {
        avifImageSpatialExtents ispe;
        avifAuxiliaryType auxC;
        avifColourInformationBox colr;
        avifCodecConfigurationBox av1C;
        avifPixelAspectRatioBox pasp;
        avifCleanApertureBox clap;
        avifImageRotation irot;
        avifImageMirror imir;
        avifPixelInformationProperty pixi;
    } u;
} avifProperty;

typedef struct avifDecoderItem
{
    uint32_t id;
    struct avifMeta * meta; // Unowned; A back-pointer for convenience
    uint8_t type[4];
    uint32_t offset;
    uint32_t size;
    uint32_t idatID; // If non-zero, offset is relative to this idat box (iloc construction_method==1)
    avifContentType contentType;
    avifPropertyArray properties;
    uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
    uint32_t auxForID;       // if non-zero, this item is an auxC plane for Item #{auxForID}
    uint32_t descForID;      // if non-zero, this item is a content description for Item #{descForID}
    uint32_t dimgForID;      // if non-zero, this item is a derived image for Item #{dimgForID}
    avifBool hasUnsupportedEssentialProperty; // If true, this item cites a property flagged as 'essential' that libavif doesn't support (yet). Ignore the item, if so.
} avifDecoderItem;

typedef struct avifDecoderItemData
{
    uint32_t id;
    avifROData data;
} avifDecoderItemData;

typedef struct avifImageGrid
{
    uint8_t rows;
    uint8_t columns;
    uint32_t outputWidth;
    uint32_t outputHeight;
} avifImageGrid;

typedef struct avifSampleTableSampleToChunk
{
    uint32_t firstChunk;
    uint32_t samplesPerChunk;
    uint32_t sampleDescriptionIndex;
} avifSampleTableSampleToChunk;

typedef struct avifSampleTableSampleSize
{
    uint32_t size;
} avifSampleTableSampleSize;

typedef struct avifSampleTableTimeToSample
{
    uint32_t sampleCount;
    uint32_t sampleDelta;
} avifSampleTableTimeToSample;

typedef struct avifSyncSample
{
    uint32_t sampleNumber;
} avifSyncSample;

typedef struct avifSampleDescription
{
    uint8_t format[4];
    avifPropertyArray properties;
} avifSampleDescription;


static avifBool avifParseItemDataBox(avifMeta * meta, const uint8_t * raw, size_t rawLen)
{
    // Check to see if we've already seen an idat box for this meta box. If so, bail out
    for (uint32_t i = 0; i < meta->idats.count; ++i) {
        if (meta->idats.idat[i].id == meta->idatID) {
            return AVIF_FALSE;
        }
    }

    int index = avifArrayPushIndex(&meta->idats);
    avifDecoderItemData * idat = &meta->idats.idat[index];
    idat->id = meta->idatID;
    idat->data.data = raw;
    idat->data.size = rawLen;
    return AVIF_TRUE;
}

Set max image size to 16384 * 16384

Fix https://crbug.com/oss-fuzz/24728 and
https://crbug.com/oss-fuzz/24734.

static const size_t VISUALSAMPLEENTRY_SIZE = 78;

static const char xmpContentType[] = CONTENT_TYPE_XMP;

static const size_t xmpContentTypeSize = sizeof(xmpContentType);

typedef struct avifFileType
{
    uint8_t majorBrand[4];
    uint32_t minorVersion;
    // If not null, points to a memory block of 4 * compatibleBrandsCount bytes.
    const uint8_t * compatibleBrands;
    int compatibleBrandsCount;
} avifFileType;

typedef struct avifImageSpatialExtents
{
    uint32_t width;
    uint32_t height;
} avifImageSpatialExtents;

typedef struct avifColourInformationBox
{
    avifBool hasICC;
    const uint8_t * icc;
    size_t iccSize;

    avifBool hasNCLX;
    avifColorPrimaries colorPrimaries;
    avifTransferCharacteristics transferCharacteristics;
    avifMatrixCoefficients matrixCoefficients;
    avifRange range;
} avifColourInformationBox;

typedef struct avifPixelInformationProperty
{
    uint8_t planeDepths[MAX_PIXI_PLANE_DEPTHS];
    uint8_t planeCount;
} avifPixelInformationProperty;

struct avifMeta

typedef struct avifProperty
{
    uint8_t type[4];
    union
    {
        avifImageSpatialExtents ispe;
        avifAuxiliaryType auxC;
        avifColourInformationBox colr;
        avifCodecConfigurationBox av1C;
        avifPixelAspectRatioBox pasp;
        avifCleanApertureBox clap;
        avifImageRotation irot;
        avifImageMirror imir;
        avifPixelInformationProperty pixi;
    } u;
} avifProperty;

typedef struct avifDecoderItem
{
    uint32_t id;
    struct avifMeta * meta; // Unowned; A back-pointer for convenience
    uint8_t type[4];
    uint32_t offset;
    uint32_t size;
    uint32_t idatID; // If non-zero, offset is relative to this idat box (iloc construction_method==1)
    avifContentType contentType;
    avifPropertyArray properties;
    uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
    uint32_t auxForID;       // if non-zero, this item is an auxC plane for Item #{auxForID}
    uint32_t descForID;      // if non-zero, this item is a content description for Item #{descForID}
    uint32_t dimgForID;      // if non-zero, this item is a derived image for Item #{dimgForID}
    avifBool hasUnsupportedEssentialProperty; // If true, this item cites a property flagged as 'essential' that libavif doesn't support (yet). Ignore the item, if so.
} avifDecoderItem;

typedef struct avifDecoderItemData
{
    uint32_t id;
    avifROData data;
} avifDecoderItemData;

typedef struct avifImageGrid
{
    uint8_t rows;
    uint8_t columns;
    uint32_t outputWidth;
    uint32_t outputHeight;
} avifImageGrid;

typedef struct avifSampleTableSampleToChunk
{
    uint32_t firstChunk;
    uint32_t samplesPerChunk;
    uint32_t sampleDescriptionIndex;
} avifSampleTableSampleToChunk;

typedef struct avifSampleTableSampleSize
{
    uint32_t size;
} avifSampleTableSampleSize;


static avifBool avifParse(avifDecoderData * data, const uint8_t * raw, size_t rawLen)
{
    BEGIN_STREAM(s, raw, rawLen);

    while (avifROStreamHasBytesLeft(&s, 1)) {
        avifBoxHeader header;
        CHECK(avifROStreamReadBoxHeader(&s, &header));

        if (!memcmp(header.type, "ftyp", 4)) {
            CHECK(avifParseFileTypeBox(&data->ftyp, avifROStreamCurrent(&s), header.size));
        } else if (!memcmp(header.type, "meta", 4)) {
            CHECK(avifParseMetaBox(data->meta, avifROStreamCurrent(&s), header.size));
        } else if (!memcmp(header.type, "moov", 4)) {
            CHECK(avifParseMoovBox(data, avifROStreamCurrent(&s), header.size));
        }

        CHECK(avifROStreamSkip(&s, header.size));
    }
    return AVIF_TRUE;
}

static const size_t VISUALSAMPLEENTRY_SIZE = 78;

static const char xmpContentType[] = CONTENT_TYPE_XMP;

static const size_t xmpContentTypeSize = sizeof(xmpContentType);

typedef struct avifFileType
{
    uint8_t majorBrand[4];
    uint32_t minorVersion;
    // If not null, points to a memory block of 4 * compatibleBrandsCount bytes.
    const uint8_t * compatibleBrands;
    int compatibleBrandsCount;
} avifFileType;

typedef struct avifColourInformationBox
{
    avifBool hasICC;
    const uint8_t * icc;
    size_t iccSize;

    avifBool hasNCLX;
    avifColorPrimaries colorPrimaries;
    avifTransferCharacteristics transferCharacteristics;
    avifMatrixCoefficients matrixCoefficients;
    avifRange range;
} avifColourInformationBox;

typedef struct avifPixelInformationProperty
{
    uint8_t planeDepths[MAX_PIXI_PLANE_DEPTHS];
    uint8_t planeCount;
} avifPixelInformationProperty;

typedef struct avifProperty
{
    uint8_t type[4];
    union
    {
        avifImageSpatialExtents ispe;
        avifAuxiliaryType auxC;
        avifColourInformationBox colr;
        avifCodecConfigurationBox av1C;
        avifPixelAspectRatioBox pasp;
        avifCleanApertureBox clap;
        avifImageRotation irot;
        avifImageMirror imir;
        avifPixelInformationProperty pixi;
    } u;
} avifProperty;

typedef struct avifDecoderItem
{
    uint32_t id;
    struct avifMeta * meta; // Unowned; A back-pointer for convenience
    uint8_t type[4];
    uint32_t offset;
    uint32_t size;
    uint32_t idatID; // If non-zero, offset is relative to this idat box (iloc construction_method==1)
    avifContentType contentType;
    avifPropertyArray properties;
    uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
    uint32_t auxForID;       // if non-zero, this item is an auxC plane for Item #{auxForID}
    uint32_t descForID;      // if non-zero, this item is a content description for Item #{descForID}
    uint32_t dimgForID;      // if non-zero, this item is a derived image for Item #{dimgForID}
    avifBool hasUnsupportedEssentialProperty; // If true, this item cites a property flagged as 'essential' that libavif doesn't support (yet). Ignore the item, if so.
} avifDecoderItem;

typedef struct avifDecoderItemData
{
    uint32_t id;
    avifROData data;
} avifDecoderItemData;

typedef struct avifImageGrid
{
    uint8_t rows;
    uint8_t columns;
    uint32_t outputWidth;
    uint32_t outputHeight;
} avifImageGrid;

typedef struct avifSampleTableSampleSize
{
    uint32_t size;
} avifSampleTableSampleSize;

typedef struct avifSampleDescription
{
    uint8_t format[4];
    avifPropertyArray properties;
} avifSampleDescription;


static avifBool avifParsePixelAspectRatioBoxProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen)
{
    BEGIN_STREAM(s, raw, rawLen);

    avifPixelAspectRatioBox * pasp = &prop->u.pasp;
    CHECK(avifROStreamReadU32(&s, &pasp->hSpacing)); // unsigned int(32) hSpacing;
    CHECK(avifROStreamReadU32(&s, &pasp->vSpacing)); // unsigned int(32) vSpacing;
    return AVIF_TRUE;
}

static const size_t VISUALSAMPLEENTRY_SIZE = 78;

static const char xmpContentType[] = CONTENT_TYPE_XMP;

static const size_t xmpContentTypeSize = sizeof(xmpContentType);

typedef struct avifFileType
{
    uint8_t majorBrand[4];
    uint32_t minorVersion;
    // If not null, points to a memory block of 4 * compatibleBrandsCount bytes.
    const uint8_t * compatibleBrands;
    int compatibleBrandsCount;
} avifFileType;

typedef struct avifColourInformationBox
{
    avifBool hasICC;
    const uint8_t * icc;
    size_t iccSize;

    avifBool hasNCLX;
    avifColorPrimaries colorPrimaries;
    avifTransferCharacteristics transferCharacteristics;
    avifMatrixCoefficients matrixCoefficients;
    avifRange range;
} avifColourInformationBox;

typedef struct avifPixelInformationProperty
{
    uint8_t planeDepths[MAX_PIXI_PLANE_DEPTHS];
    uint8_t planeCount;
} avifPixelInformationProperty;

typedef struct avifProperty
{
    uint8_t type[4];
    union
    {
        avifImageSpatialExtents ispe;
        avifAuxiliaryType auxC;
        avifColourInformationBox colr;
        avifCodecConfigurationBox av1C;
        avifPixelAspectRatioBox pasp;
        avifCleanApertureBox clap;
        avifImageRotation irot;
        avifImageMirror imir;
        avifPixelInformationProperty pixi;
    } u;
} avifProperty;

typedef struct avifDecoderItem
{
    uint32_t id;
    struct avifMeta * meta; // Unowned; A back-pointer for convenience
    uint8_t type[4];
    uint32_t offset;
    uint32_t size;
    uint32_t idatID; // If non-zero, offset is relative to this idat box (iloc construction_method==1)
    avifContentType contentType;
    avifPropertyArray properties;
    uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
    uint32_t auxForID;       // if non-zero, this item is an auxC plane for Item #{auxForID}
    uint32_t descForID;      // if non-zero, this item is a content description for Item #{descForID}
    uint32_t dimgForID;      // if non-zero, this item is a derived image for Item #{dimgForID}
    avifBool hasUnsupportedEssentialProperty; // If true, this item cites a property flagged as 'essential' that libavif doesn't support (yet). Ignore the item, if so.
} avifDecoderItem;

typedef struct avifImageGrid
{
    uint8_t rows;
    uint8_t columns;
    uint32_t outputWidth;
    uint32_t outputHeight;
} avifImageGrid;

typedef struct avifSampleDescription
{
    uint8_t format[4];
    avifPropertyArray properties;
} avifSampleDescription;

#define BEGIN_STREAM(VARNAME, PTR, SIZE) \
    avifROStream VARNAME;                \
    avifROData VARNAME##_roData;         \
    VARNAME##_roData.data = PTR;         \
    VARNAME##_roData.size = SIZE;        \
    avifROStreamStart(&VARNAME, &VARNAME##_roData)


static avifBool avifParseItemReferenceBox(avifMeta * meta, const uint8_t * raw, size_t rawLen)
{
    BEGIN_STREAM(s, raw, rawLen);

    uint8_t version;
    CHECK(avifROStreamReadVersionAndFlags(&s, &version, NULL));

    while (avifROStreamHasBytesLeft(&s, 1)) {
        avifBoxHeader irefHeader;
        CHECK(avifROStreamReadBoxHeader(&s, &irefHeader));

        uint32_t fromID = 0;
        if (version == 0) {
            uint16_t tmp;
            CHECK(avifROStreamReadU16(&s, &tmp)); // unsigned int(16) from_item_ID;
            fromID = tmp;
        } else if (version == 1) {
            CHECK(avifROStreamReadU32(&s, &fromID)); // unsigned int(32) from_item_ID;
        } else {
            // unsupported iref version, skip it
            break;
        }

        uint16_t referenceCount = 0;
        CHECK(avifROStreamReadU16(&s, &referenceCount)); // unsigned int(16) reference_count;

        for (uint16_t refIndex = 0; refIndex < referenceCount; ++refIndex) {
            uint32_t toID = 0;
            if (version == 0) {
                uint16_t tmp;
                CHECK(avifROStreamReadU16(&s, &tmp)); // unsigned int(16) to_item_ID;
                toID = tmp;
            } else if (version == 1) {
                CHECK(avifROStreamReadU32(&s, &toID)); // unsigned int(32) to_item_ID;
            } else {
                // unsupported iref version, skip it
                break;
            }

            // Read this reference as "{fromID} is a {irefType} for {toID}"
            if (fromID && toID) {
                avifDecoderItem * item = avifMetaFindItem(meta, fromID);
                if (!item) {
                    return AVIF_FALSE;
                }

                if (!memcmp(irefHeader.type, "thmb", 4)) {
                    item->thumbnailForID = toID;
                }
                if (!memcmp(irefHeader.type, "auxl", 4)) {
                    item->auxForID = toID;
                }
                if (!memcmp(irefHeader.type, "cdsc", 4)) {
                    item->descForID = toID;
                }
                if (!memcmp(irefHeader.type, "dimg", 4)) {
                    // derived images refer in the opposite direction
                    avifDecoderItem * dimg = avifMetaFindItem(meta, toID);
                    if (!dimg) {
                        return AVIF_FALSE;
                    }

                    dimg->dimgForID = fromID;
                }
            }
        }
    }

    return AVIF_TRUE;
}


static avifBool avifParseChunkOffsetBox(avifSampleTable * sampleTable, avifBool largeOffsets, const uint8_t * raw, size_t rawLen)
{
    BEGIN_STREAM(s, raw, rawLen);

    CHECK(avifROStreamReadAndEnforceVersion(&s, 0));

    uint32_t entryCount;
    CHECK(avifROStreamReadU32(&s, &entryCount)); // unsigned int(32) entry_count;
    for (uint32_t i = 0; i < entryCount; ++i) {
        uint64_t offset;
        if (largeOffsets) {
            CHECK(avifROStreamReadU64(&s, &offset)); // unsigned int(32) chunk_offset;
        } else {
            uint32_t offset32;
            CHECK(avifROStreamReadU32(&s, &offset32)); // unsigned int(32) chunk_offset;
            offset = (uint64_t)offset32;
        }

        avifSampleTableChunk * chunk = (avifSampleTableChunk *)avifArrayPushPtr(&sampleTable->chunks);
        chunk->offset = offset;
    }
    return AVIF_TRUE;
}

static const size_t VISUALSAMPLEENTRY_SIZE = 78;

static const char xmpContentType[] = CONTENT_TYPE_XMP;

static const size_t xmpContentTypeSize = sizeof(xmpContentType);

typedef struct avifFileType
{
    uint8_t majorBrand[4];
    uint32_t minorVersion;
    // If not null, points to a memory block of 4 * compatibleBrandsCount bytes.
    const uint8_t * compatibleBrands;
    int compatibleBrandsCount;
} avifFileType;

typedef struct avifImageSpatialExtents
{
    uint32_t width;
    uint32_t height;
} avifImageSpatialExtents;

typedef struct avifColourInformationBox
{
    avifBool hasICC;
    const uint8_t * icc;
    size_t iccSize;

    avifBool hasNCLX;
    avifColorPrimaries colorPrimaries;
    avifTransferCharacteristics transferCharacteristics;
    avifMatrixCoefficients matrixCoefficients;
    avifRange range;
} avifColourInformationBox;

typedef struct avifPixelInformationProperty
{
    uint8_t planeDepths[MAX_PIXI_PLANE_DEPTHS];
    uint8_t planeCount;
} avifPixelInformationProperty;

typedef struct avifProperty
{
    uint8_t type[4];
    union
    {
        avifImageSpatialExtents ispe;
        avifAuxiliaryType auxC;
        avifColourInformationBox colr;
        avifCodecConfigurationBox av1C;
        avifPixelAspectRatioBox pasp;
        avifCleanApertureBox clap;
        avifImageRotation irot;
        avifImageMirror imir;
        avifPixelInformationProperty pixi;
    } u;
} avifProperty;

typedef struct avifDecoderItem
{
    uint32_t id;
    struct avifMeta * meta; // Unowned; A back-pointer for convenience
    uint8_t type[4];
    uint32_t offset;
    uint32_t size;
    uint32_t idatID; // If non-zero, offset is relative to this idat box (iloc construction_method==1)
    avifContentType contentType;
    avifPropertyArray properties;
    uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
    uint32_t auxForID;       // if non-zero, this item is an auxC plane for Item #{auxForID}
    uint32_t descForID;      // if non-zero, this item is a content description for Item #{descForID}
    uint32_t dimgForID;      // if non-zero, this item is a derived image for Item #{dimgForID}
    avifBool hasUnsupportedEssentialProperty; // If true, this item cites a property flagged as 'essential' that libavif doesn't support (yet). Ignore the item, if so.
} avifDecoderItem;

typedef struct avifDecoderItemData
{
    uint32_t id;
    avifROData data;
} avifDecoderItemData;

typedef struct avifImageGrid
{
    uint8_t rows;
    uint8_t columns;
    uint32_t outputWidth;
    uint32_t outputHeight;
} avifImageGrid;

typedef struct avifSampleTableChunk
{
    uint64_t offset;
} avifSampleTableChunk;

typedef struct avifSampleTableSampleToChunk
{
    uint32_t firstChunk;
    uint32_t samplesPerChunk;
    uint32_t sampleDescriptionIndex;
} avifSampleTableSampleToChunk;

typedef struct avifSampleTableSampleSize
{
    uint32_t size;
} avifSampleTableSampleSize;


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;
    int code;

    gs_register_ref_root(imemory_system, &error_root,
                         (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;
}

Bug 699708 (part 1): 'Hide' non-replaceable error handlers for SAFER

We already had a 'private' dictionary for non-standard errors: gserrordict.

This now includes all the default error handlers, the dictionary is made
noaccess and all the prodedures are bound and executeonly.

When running with -dSAFER, in the event of a Postscript error, instead of
pulling the handler from errordict, we'll pull it from gserrordict - thus
malicious input cannot trigger problems by the use of custom error handlers.

errordict remains open and writeable, so files such as the Quality Logic tests
that install their own handlers will still 'work', with the exception that the
custom error handlers will not be called.

This is a 'first pass', 'sledgehammer' approach: a nice addition would to allow
an integrator to specify a list of errors that are not to be replaced (for
example, embedded applications would probably want to ensure that VMerror is
always handled as they intend).

static int estack_underflow(i_ctx_t *);

static int interp(i_ctx_t **, const ref *, ref *);

static int interp_exit(i_ctx_t *);

static void set_gc_signal(i_ctx_t *, int);

static int copy_stack(i_ctx_t *, const ref_stack_t *, int skip, ref *);

static int oparray_pop(i_ctx_t *);

static int oparray_cleanup(i_ctx_t *);

static int zerrorexec(i_ctx_t *);

static int zfinderrorobject(i_ctx_t *);

static int errorexec_find(i_ctx_t *, ref *);

static int errorexec_pop(i_ctx_t *);

static int errorexec_cleanup(i_ctx_t *);

static int zsetstackprotect(i_ctx_t *);

static int zcurrentstackprotect(i_ctx_t *);

const int gs_interp_max_op_num_args = MIN_BLOCK_OSTACK;

#define num_special_ops ((int)tx_next_op - tx_op)

const int gs_interp_num_special_ops = num_special_ops;

const int tx_next_index = tx_next_op;

#define make_null_proc(pref)\
  make_empty_const_array(pref, a_executable + a_readonly)

static int gs_call_interp(i_ctx_t **, ref *, int, int *, ref *);


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;
    int code;

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

    gs_register_struct_root(imemory_system, &ctx_root,
                            (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, &ctx_root, "interp_reclaim(pi_ctx_p)");
    return code;
}

static int estack_underflow(i_ctx_t *);

static int interp(i_ctx_t **, const ref *, ref *);

static int interp_exit(i_ctx_t *);

static void set_gc_signal(i_ctx_t *, int);

static int copy_stack(i_ctx_t *, const ref_stack_t *, int skip, ref *);

static int oparray_pop(i_ctx_t *);

static int oparray_cleanup(i_ctx_t *);

static int zerrorexec(i_ctx_t *);

static int zfinderrorobject(i_ctx_t *);

static int errorexec_find(i_ctx_t *, ref *);

static int errorexec_pop(i_ctx_t *);

static int errorexec_cleanup(i_ctx_t *);

static int zsetstackprotect(i_ctx_t *);

static int zcurrentstackprotect(i_ctx_t *);

const int gs_interp_max_op_num_args = MIN_BLOCK_OSTACK;

#define num_special_ops ((int)tx_next_op - tx_op)

const int gs_interp_num_special_ops = num_special_ops;

const int tx_next_index = tx_next_op;

static int gs_call_interp(i_ctx_t **, ref *, int, int *, ref *);


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 o_reschedule:
                    store_state(iesp);
                    goto res;
                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;

                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 o_reschedule:
                                store_state(iesp);
                                goto res;
                            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 o_reschedule:
                                store_state_short(iesp);
                                goto res;
                            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;

                                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;
res:
    /* Some operator has asked for context rescheduling. */
    /* We've done a store_state. */
    *pi_ctx_p = i_ctx_p;
    code = (*i_ctx_p->reschedule_proc)(pi_ctx_p);
    i_ctx_p = *pi_ctx_p;
  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 if (i_ctx_p->time_slice_proc != NULL) {
        *pi_ctx_p = i_ctx_p;
        code = (*i_ctx_p->time_slice_proc)(pi_ctx_p);
        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);
}

#define PACKED_SPECIAL_OPS 1

#define call_operator(proc, p) (*call_operator_fn)(proc, p)

#  define call_operator(proc, p) ((*(proc))(p))

struct stats_interp_s {
    long top;
    long lit, lit_array, exec_array, exec_operator, exec_name;
    long x_add, x_def, x_dup, x_exch, x_if, x_ifelse,
        x_index, x_pop, x_roll, x_sub;
    long find_name, name_lit, name_proc, name_oparray, name_operator;
    long p_full, p_exec_operator, p_exec_oparray, p_exec_non_x_operator,
        p_integer, p_lit_name, p_exec_name;
    long p_find_name, p_name_lit, p_name_proc;
} stats_interp;

# define INCR(v) (++(stats_interp.v))

# define INCR(v) DO_NOTHING

static int estack_underflow(i_ctx_t *);

static int interp(i_ctx_t **, const ref *, ref *);

static int interp_exit(i_ctx_t *);

static void set_gc_signal(i_ctx_t *, int);

static int copy_stack(i_ctx_t *, const ref_stack_t *, int skip, ref *);

static int oparray_pop(i_ctx_t *);

static int oparray_cleanup(i_ctx_t *);

static int zerrorexec(i_ctx_t *);

static int zfinderrorobject(i_ctx_t *);

static int errorexec_find(i_ctx_t *, ref *);

static int errorexec_pop(i_ctx_t *);

static int errorexec_cleanup(i_ctx_t *);

static int zsetstackprotect(i_ctx_t *);

static int zcurrentstackprotect(i_ctx_t *);

#  define MAX_OSTACK 800

#define MIN_BLOCK_OSTACK 16

const int gs_interp_max_op_num_args = MIN_BLOCK_OSTACK;

#  define MAX_ESTACK 5000

#define MIN_BLOCK_ESTACK 8

#define ES_HEADROOM 20

#  define MAX_DSTACK 20

#define MIN_BLOCK_DSTACK 3

#define OS_GUARD_UNDER 10

#define OS_GUARD_OVER 10

#define OS_REFS_SIZE(body_size)\
  (stack_block_refs + OS_GUARD_UNDER + (body_size) + OS_GUARD_OVER)

#define ES_GUARD_UNDER 1

#define ES_GUARD_OVER 10

#define ES_REFS_SIZE(body_size)\
  (stack_block_refs + ES_GUARD_UNDER + (body_size) + ES_GUARD_OVER)

#define DS_REFS_SIZE(body_size)\
  (stack_block_refs + (body_size))

#define tx_op t_next_index

typedef enum {
    tx_op_add = tx_op,
    tx_op_def,
    tx_op_dup,
    tx_op_exch,
    tx_op_if,
    tx_op_ifelse,
    tx_op_index,
    tx_op_pop,
    tx_op_roll,
    tx_op_sub,
    tx_next_op
} special_op_types;

#define num_special_ops ((int)tx_next_op - tx_op)

const int gs_interp_num_special_ops = num_special_ops;

const int tx_next_index = tx_next_op;

const op_def interp1_op_defs[] = {
    /*
     * The very first entry, which corresponds to operator index 0,
     * must not contain an actual operator.
     */
    op_def_begin_dict("systemdict"),
    {"2add", zadd},
    {"2def", zdef},
    {"1dup", zdup},
    {"2exch", zexch},
    {"2if", zif},
    {"3ifelse", zifelse},
    {"1index", zindex},
    {"1pop", zpop},
    {"2roll", zroll},
    {"2sub", zsub},
    op_def_end(0)
};


int sqlite3VdbeAddOp4(
  Vdbe *p,            /* Add the opcode to this VM */
  int op,             /* The new opcode */
  int p1,             /* The P1 operand */
  int p2,             /* The P2 operand */
  int p3,             /* The P3 operand */
  const char *zP4,    /* The P4 operand */
  int p4type          /* P4 operand type */
){
  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  return addr;
}

When an error occurs while rewriting the parser tree for window functions
in the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set,
and make sure that this shuts down any subsequent code generation that might
depend on the transformations that were implemented.  This fixes a problem
discovered by the Yongheng and Rui fuzzer.

FossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f


void sqlite3WindowLink(Select *pSel, Window *pWin){
  if( pSel!=0
   && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
  ){
    pWin->pNextWin = pSel->pWin;
    if( pSel->pWin ){
      pSel->pWin->ppThis = &pWin->pNextWin;
    }
    pSel->pWin = pWin;
    pWin->ppThis = &pSel->pWin;
  }
}

struct WindowRewrite {
  Window *pWin;
  SrcList *pSrc;
  ExprList *pSub;
  Table *pTab;
  Select *pSubSelect;             /* Current sub-select, if any */
}

struct WindowCodeArg {
  Parse *pParse;             /* Parse context */
  Window *pMWin;             /* First in list of functions being processed */
  Vdbe *pVdbe;               /* VDBE object */
  int addrGosub;             /* OP_Gosub to this address to return one row */
  int regGosub;              /* Register used with OP_Gosub(addrGosub) */
  int regArg;                /* First in array of accumulator registers */
  int eDelete;               /* See above */

  WindowCsrAndReg start;
  WindowCsrAndReg current;
  WindowCsrAndReg end;
}


void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  assert( i<(int)sizeof(p->btreeMask)*8 );
  DbMaskSet(p->btreeMask, i);
  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
    DbMaskSet(p->lockMask, i);
  }
}

static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);

static void vdbeFreeOpArray(sqlite3 *, Op *, int);

struct VdbeOpIter {
  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
  SubProgram **apSub;        /* Array of subprograms */
  int nSub;                  /* Number of entries in apSub */
  int iAddr;                 /* Address of next instruction to return */
  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
}


static void dense_rankValueFunc(sqlite3_context *pCtx){
  struct CallCount *p;
  p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  if( p ){
    if( p->nStep ){
      p->nValue++;
      p->nStep = 0;
    }
    sqlite3_result_int64(pCtx, p->nValue);
  }
}

struct CallCount {
  i64 nValue;
  i64 nStep;
  i64 nTotal;
}

struct NthValueCtx {
  i64 nStep;
  sqlite3_value *pValue;
}

struct NtileCtx {
  i64 nTotal;                     /* Total rows in partition */
  i64 nParam;                     /* Parameter passed to ntile(N) */
  i64 iRow;                       /* Current row */
}

struct LastValueCtx {
  sqlite3_value *pVal;
  int nVal;
}

static const char row_numberName[] =   "row_number";

static const char dense_rankName[] =   "dense_rank";

static const char rankName[] =         "rank";

static const char percent_rankName[] = "percent_rank";

static const char cume_distName[] =    "cume_dist";

static const char ntileName[] =        "ntile";

static const char last_valueName[] =   "last_value";

static const char nth_valueName[] =    "nth_value";

static const char first_valueName[] =  "first_value";

static const char leadName[] =         "lead";

static const char lagName[] =          "lag";

typedef struct WindowRewrite WindowRewrite;

struct WindowRewrite {
  Window *pWin;
  SrcList *pSrc;
  ExprList *pSub;
  Table *pTab;
  Select *pSubSelect;             /* Current sub-select, if any */
}

typedef struct WindowCodeArg WindowCodeArg;

typedef struct WindowCsrAndReg WindowCsrAndReg;

struct WindowCsrAndReg {
  int csr;                        /* Cursor number */
  int reg;                        /* First in array of peer values */
}

struct WindowCodeArg {
  Parse *pParse;             /* Parse context */
  Window *pMWin;             /* First in list of functions being processed */
  Vdbe *pVdbe;               /* VDBE object */
  int addrGosub;             /* OP_Gosub to this address to return one row */
  int regGosub;              /* Register used with OP_Gosub(addrGosub) */
  int regArg;                /* First in array of accumulator registers */
  int eDelete;               /* See above */

  WindowCsrAndReg start;
  WindowCsrAndReg current;
  WindowCsrAndReg end;
}


int sqlite3VdbeAddFunctionCall(
  Parse *pParse,        /* Parsing context */
  int p1,               /* Constant argument mask */
  int p2,               /* First argument register */
  int p3,               /* Register into which results are written */
  int nArg,             /* Number of argument */
  const FuncDef *pFunc, /* The function to be invoked */
  int eCallCtx          /* Calling context */
){
  Vdbe *v = pParse->pVdbe;
  int nByte;
  int addr;
  sqlite3_context *pCtx;
  assert( v );
  nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
  pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
  if( pCtx==0 ){
    assert( pParse->db->mallocFailed );
    freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
    return 0;
  }
  pCtx->pOut = 0;
  pCtx->pFunc = (FuncDef*)pFunc;
  pCtx->pVdbe = 0;
  pCtx->isError = 0;
  pCtx->argc = nArg;
  pCtx->iOp = sqlite3VdbeCurrentAddr(v);
  addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
                           p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
  sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
  return addr;
}


int sqlite3VdbeSetColName(
  Vdbe *p,                         /* Vdbe being configured */
  int idx,                         /* Index of column zName applies to */
  int var,                         /* One of the COLNAME_* constants */
  const char *zName,               /* Pointer to buffer containing name */
  void (*xDel)(void*)              /* Memory management strategy for zName */
){
  int rc;
  Mem *pColName;
  assert( idx<p->nResColumn );
  assert( var<COLNAME_N );
  if( p->db->mallocFailed ){
    assert( !zName || xDel!=SQLITE_DYNAMIC );
    return SQLITE_NOMEM_BKPT;
  }
  assert( p->aColName!=0 );
  pColName = &(p->aColName[idx+var*p->nResColumn]);
  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  return rc;
}


void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
}


static ExprList *exprListAppendList(
  Parse *pParse,          /* Parsing context */
  ExprList *pList,        /* List to which to append. Might be NULL */
  ExprList *pAppend,      /* List of values to append. Might be NULL */
  int bIntToNull
){
  if( pAppend ){
    int i;
    int nInit = pList ? pList->nExpr : 0;
    for(i=0; i<pAppend->nExpr; i++){
      Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
      assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
      if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
        pDup->op = TK_NULL;
        pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
        pDup->u.zToken = 0;
      }
      pList = sqlite3ExprListAppend(pParse, pList, pDup);
      if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
    }
  }
  return pList;
}

struct LastValueCtx {
  sqlite3_value *pVal;
  int nVal;
}

static const char row_numberName[] =   "row_number";

static const char dense_rankName[] =   "dense_rank";

static const char rankName[] =         "rank";

static const char percent_rankName[] = "percent_rank";

static const char cume_distName[] =    "cume_dist";

static const char ntileName[] =        "ntile";

static const char last_valueName[] =   "last_value";

static const char nth_valueName[] =    "nth_value";

static const char first_valueName[] =  "first_value";

static const char leadName[] =         "lead";

static const char lagName[] =          "lag";

struct WindowRewrite {
  Window *pWin;
  SrcList *pSrc;
  ExprList *pSub;
  Table *pTab;
  Select *pSubSelect;             /* Current sub-select, if any */
}

struct WindowCsrAndReg {
  int csr;                        /* Cursor number */
  int reg;                        /* First in array of peer values */
}

struct WindowCodeArg {
  Parse *pParse;             /* Parse context */
  Window *pMWin;             /* First in list of functions being processed */
  Vdbe *pVdbe;               /* VDBE object */
  int addrGosub;             /* OP_Gosub to this address to return one row */
  int regGosub;              /* Register used with OP_Gosub(addrGosub) */
  int regArg;                /* First in array of accumulator registers */
  int eDelete;               /* See above */

  WindowCsrAndReg start;
  WindowCsrAndReg current;
  WindowCsrAndReg end;
}


int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  sqlite3 *db = p->db;
  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
   || (!deferred && p->nFkConstraint>0)
  ){
    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
    p->errorAction = OE_Abort;
    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
}


static int translateP(char c, const Op *pOp){
  if( c=='1' ) return pOp->p1;
  if( c=='2' ) return pOp->p2;
  if( c=='3' ) return pOp->p3;
  if( c=='4' ) return pOp->p4.i;
  return pOp->p5;
}


void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  va_list ap;
  int i;
  char c;
  va_start(ap, zTypes);
  for(i=0; (c = zTypes[i])!=0; i++){
    if( c=='s' ){
      const char *z = va_arg(ap, const char*);
      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
    }else if( c=='i' ){
      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
    }else{
      goto skip_op_resultrow;
    }
  }
  sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
skip_op_resultrow:
  va_end(ap);
}


static int vdbeRecordCompareInt(
  int nKey1, const void *pKey1, /* Left key */
  UnpackedRecord *pPKey2        /* Right key */
){
  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  int serial_type = ((const u8*)pKey1)[1];
  int res;
  u32 y;
  u64 x;
  i64 v;
  i64 lhs;

  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  switch( serial_type ){
    case 1: { /* 1-byte signed integer */
      lhs = ONE_BYTE_INT(aKey);
      testcase( lhs<0 );
      break;
    }
    case 2: { /* 2-byte signed integer */
      lhs = TWO_BYTE_INT(aKey);
      testcase( lhs<0 );
      break;
    }
    case 3: { /* 3-byte signed integer */
      lhs = THREE_BYTE_INT(aKey);
      testcase( lhs<0 );
      break;
    }
    case 4: { /* 4-byte signed integer */
      y = FOUR_BYTE_UINT(aKey);
      lhs = (i64)*(int*)&y;
      testcase( lhs<0 );
      break;
    }
    case 5: { /* 6-byte signed integer */
      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
      testcase( lhs<0 );
      break;
    }
    case 6: { /* 8-byte signed integer */
      x = FOUR_BYTE_UINT(aKey);
      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
      lhs = *(i64*)&x;
      testcase( lhs<0 );
      break;
    }
    case 8:
      lhs = 0;
      break;
    case 9:
      lhs = 1;
      break;

    /* This case could be removed without changing the results of running
    ** this code. Including it causes gcc to generate a faster switch
    ** statement (since the range of switch targets now starts at zero and
    ** is contiguous) but does not cause any duplicate code to be generated
    ** (as gcc is clever enough to combine the two like cases). Other
    ** compilers might be similar.  */
    case 0: case 7:
      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);

    default:
      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  }

  v = pPKey2->aMem[0].u.i;
  if( v>lhs ){
    res = pPKey2->r1;
  }else if( v<lhs ){
    res = pPKey2->r2;
  }else if( pPKey2->nField>1 ){
    /* The first fields of the two keys are equal. Compare the trailing
    ** fields.  */
    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  }else{
    /* The first fields of the two keys are equal and there are no trailing
    ** fields. Return pPKey2->default_rc in this case. */
    res = pPKey2->default_rc;
    pPKey2->eqSeen = 1;
  }

  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  return res;
}

static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);

static void vdbeFreeOpArray(sqlite3 *, Op *, int);

struct VdbeOpIter {
  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
  SubProgram **apSub;        /* Array of subprograms */
  int nSub;                  /* Number of entries in apSub */
  int iAddr;                 /* Address of next instruction to return */
  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
}

struct ReusableSpace {
  u8 *pSpace;            /* Available memory */
  sqlite3_int64 nFree;   /* Bytes of available memory */
  sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
}


void sqlite3WindowListDelete(sqlite3 *db, Window *p){
  while( p ){
    Window *pNext = p->pNextWin;
    sqlite3WindowDelete(db, p);
    p = pNext;
  }
}


int sqlite3VdbeReset(Vdbe *p){
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  int i;
#endif

  sqlite3 *db;
  db = p->db;

  /* If the VM did not run to completion or if it encountered an
  ** error, then it might not have been halted properly.  So halt
  ** it now.
  */
  sqlite3VdbeHalt(p);

  /* If the VDBE has been run even partially, then transfer the error code
  ** and error message from the VDBE into the main database structure.  But
  ** if the VDBE has just been set to run but has not actually executed any
  ** instructions yet, leave the main database error information unchanged.
  */
  if( p->pc>=0 ){
    vdbeInvokeSqllog(p);
    sqlite3VdbeTransferError(p);
    if( p->runOnlyOnce ) p->expired = 1;
  }else if( p->rc && p->expired ){
    /* The expired flag was set on the VDBE before the first call
    ** to sqlite3_step(). For consistency (since sqlite3_step() was
    ** called), set the database error in this case as well.
    */
    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  }

  /* Reset register contents and reclaim error message memory.
  */
#ifdef SQLITE_DEBUG
  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  ** Vdbe.aMem[] arrays have already been cleaned up.  */
  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  if( p->aMem ){
    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  }
#endif
  sqlite3DbFree(db, p->zErrMsg);
  p->zErrMsg = 0;
  p->pResultSet = 0;
#ifdef SQLITE_DEBUG
  p->nWrite = 0;
#endif

  /* Save profiling information from this VDBE run.
  */
#ifdef VDBE_PROFILE
  {
    FILE *out = fopen("vdbe_profile.out", "a");
    if( out ){
      fprintf(out, "---- ");
      for(i=0; i<p->nOp; i++){
        fprintf(out, "%02x", p->aOp[i].opcode);
      }
      fprintf(out, "\n");
      if( p->zSql ){
        char c, pc = 0;
        fprintf(out, "-- ");
        for(i=0; (c = p->zSql[i])!=0; i++){
          if( pc=='\n' ) fprintf(out, "-- ");
          putc(c, out);
          pc = c;
        }
        if( pc!='\n' ) fprintf(out, "\n");
      }
      for(i=0; i<p->nOp; i++){
        char zHdr[100];
        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
           p->aOp[i].cnt,
           p->aOp[i].cycles,
           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
        );
        fprintf(out, "%s", zHdr);
        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
      }
      fclose(out);
    }
  }
#endif
  p->magic = VDBE_MAGIC_RESET;
  return p->rc & db->errMask;
}

static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);

static void vdbeFreeOpArray(sqlite3 *, Op *, int);

struct VdbeOpIter {
  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
  SubProgram **apSub;        /* Array of subprograms */
  int nSub;                  /* Number of entries in apSub */
  int iAddr;                 /* Address of next instruction to return */
  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
}

struct ReusableSpace {
  u8 *pSpace;            /* Available memory */
  sqlite3_int64 nFree;   /* Bytes of available memory */
  sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
}

# define vdbeInvokeSqllog(x)


static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
  struct WindowRewrite *p = pWalker->u.pRewrite;
  Select *pSave = p->pSubSelect;
  if( pSave==pSelect ){
    return WRC_Continue;
  }else{
    p->pSubSelect = pSelect;
    sqlite3WalkSelect(pWalker, pSelect);
    p->pSubSelect = pSave;
  }
  return WRC_Prune;
}


void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  Vdbe tmp, *pTmp;
  char *zTmp;
  assert( pA->db==pB->db );
  tmp = *pA;
  *pA = *pB;
  *pB = tmp;
  pTmp = pA->pNext;
  pA->pNext = pB->pNext;
  pB->pNext = pTmp;
  pTmp = pA->pPrev;
  pA->pPrev = pB->pPrev;
  pB->pPrev = pTmp;
  zTmp = pA->zSql;
  pA->zSql = pB->zSql;
  pB->zSql = zTmp;
#ifdef SQLITE_ENABLE_NORMALIZE
  zTmp = pA->zNormSql;
  pA->zNormSql = pB->zNormSql;
  pB->zNormSql = zTmp;
#endif
  pB->expmask = pA->expmask;
  pB->prepFlags = pA->prepFlags;
  memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
}


void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
  if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
}


void sqlite3VdbeIOTraceSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( sqlite3IoTrace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
    int i, j;
    char z[1000];
    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
    for(i=0; sqlite3Isspace(z[i]); i++){}
    for(j=0; z[i]; i++){
      if( sqlite3Isspace(z[i]) ){
        if( z[i-1]!=' ' ){
          z[j++] = ' ';
        }
      }else{
        z[j++] = z[i];
      }
    }
    z[j] = 0;
    sqlite3IoTrace("SQL %s\n", z);
  }
}


static int isAllZero(const char *z, int n){
  int i;
  for(i=0; i<n; i++){
    if( z[i] ) return 0;
  }
  return 1;
}


static int windowArgCount(Window *pWin){
  ExprList *pList = pWin->pOwner->x.pList;
  return (pList ? pList->nExpr : 0);
}


void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
  char *zP4;
  char zPtr[50];
  char zCom[100];
  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  if( pOut==0 ) pOut = stdout;
  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  displayComment(pOp, zP4, zCom, sizeof(zCom));
#else
  zCom[0] = 0;
#endif
  /* NB:  The sqlite3OpcodeName() function is implemented by code created
  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  ** information from the vdbe.c source text */
  fprintf(pOut, zFormat1, pc,
      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
      zCom
  );
  fflush(pOut);
}


static void row_numberValueFunc(sqlite3_context *pCtx){
  i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  sqlite3_result_int64(pCtx, (p ? *p : 0));
}

struct CallCount {
  i64 nValue;
  i64 nStep;
  i64 nTotal;
}

struct NthValueCtx {
  i64 nStep;
  sqlite3_value *pValue;
}

struct NtileCtx {
  i64 nTotal;                     /* Total rows in partition */
  i64 nParam;                     /* Parameter passed to ntile(N) */
  i64 iRow;                       /* Current row */
}

static const char row_numberName[] =   "row_number";

static const char dense_rankName[] =   "dense_rank";

static const char rankName[] =         "rank";

static const char percent_rankName[] = "percent_rank";

static const char cume_distName[] =    "cume_dist";

static const char ntileName[] =        "ntile";

static const char last_valueName[] =   "last_value";

static const char nth_valueName[] =    "nth_value";

static const char first_valueName[] =  "first_value";

static const char leadName[] =         "lead";

static const char lagName[] =          "lag";


void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  assert( p->nOp>0 || p->db->mallocFailed );
  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
}


static void windowReturnOneRow(WindowCodeArg *p){
  Window *pMWin = p->pMWin;
  Vdbe *v = p->pVdbe;

  if( pMWin->regStartRowid ){
    windowFullScan(p);
  }else{
    Parse *pParse = p->pParse;
    Window *pWin;

    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
      FuncDef *pFunc = pWin->pFunc;
      if( pFunc->zName==nth_valueName
       || pFunc->zName==first_valueName
      ){
        int csr = pWin->csrApp;
        int lbl = sqlite3VdbeMakeLabel(pParse);
        int tmpReg = sqlite3GetTempReg(pParse);
        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);

        if( pFunc->zName==nth_valueName ){
          sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
          windowCheckValue(pParse, tmpReg, 2);
        }else{
          sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
        }
        sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
        sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
        VdbeCoverageNeverNull(v);
        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
        VdbeCoverageNeverTaken(v);
        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
        sqlite3VdbeResolveLabel(v, lbl);
        sqlite3ReleaseTempReg(pParse, tmpReg);
      }
      else if( pFunc->zName==leadName || pFunc->zName==lagName ){
        int nArg = pWin->pOwner->x.pList->nExpr;
        int csr = pWin->csrApp;
        int lbl = sqlite3VdbeMakeLabel(pParse);
        int tmpReg = sqlite3GetTempReg(pParse);
        int iEph = pMWin->iEphCsr;

        if( nArg<3 ){
          sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
        }else{
          sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
        }
        sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
        if( nArg<2 ){
          int val = (pFunc->zName==leadName ? 1 : -1);
          sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
        }else{
          int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
          int tmpReg2 = sqlite3GetTempReg(pParse);
          sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
          sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
          sqlite3ReleaseTempReg(pParse, tmpReg2);
        }

        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
        VdbeCoverage(v);
        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
        sqlite3VdbeResolveLabel(v, lbl);
        sqlite3ReleaseTempReg(pParse, tmpReg);
      }
    }
  }
  sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
}

struct LastValueCtx {
  sqlite3_value *pVal;
  int nVal;
}

static const char row_numberName[] =   "row_number";

static const char dense_rankName[] =   "dense_rank";

static const char rankName[] =         "rank";

static const char percent_rankName[] = "percent_rank";

static const char cume_distName[] =    "cume_dist";

static const char ntileName[] =        "ntile";

static const char last_valueName[] =   "last_value";

static const char nth_valueName[] =    "nth_value";

static const char first_valueName[] =  "first_value";

static const char leadName[] =         "lead";

static const char lagName[] =          "lag";

#define WINDOWFUNCALL(name,nArg,extra) {                                   \
  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
  name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc,               \
  name ## InvFunc, name ## Name, {0}                                       \
}

#define WINDOWFUNCNOOP(name,nArg,extra) {                                  \
  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
  noopStepFunc, noopValueFunc, noopValueFunc,                              \
  noopStepFunc, name ## Name, {0}                                          \
}

#define WINDOWFUNCX(name,nArg,extra) {                                     \
  nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
  name ## StepFunc, name ## ValueFunc, name ## ValueFunc,                  \
  noopStepFunc, name ## Name, {0}                                          \
}

struct WindowRewrite {
  Window *pWin;
  SrcList *pSrc;
  ExprList *pSub;
  Table *pTab;
  Select *pSubSelect;             /* Current sub-select, if any */
}

typedef struct WindowCodeArg WindowCodeArg;

struct WindowCsrAndReg {
  int csr;                        /* Cursor number */
  int reg;                        /* First in array of peer values */
}

struct WindowCodeArg {
  Parse *pParse;             /* Parse context */
  Window *pMWin;             /* First in list of functions being processed */
  Vdbe *pVdbe;               /* VDBE object */
  int addrGosub;             /* OP_Gosub to this address to return one row */
  int regGosub;              /* Register used with OP_Gosub(addrGosub) */
  int regArg;                /* First in array of accumulator registers */
  int eDelete;               /* See above */

  WindowCsrAndReg start;
  WindowCsrAndReg current;
  WindowCsrAndReg end;
}


void sqlite3ExprCodeGeneratedColumn(
  Parse *pParse,
  Column *pCol,
  int regOut
){
  int iAddr;
  Vdbe *v = pParse->pVdbe;
  assert( v!=0 );
  assert( pParse->iSelfTab!=0 );
  if( pParse->iSelfTab>0 ){
    iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
  }else{
    iAddr = 0;
  }
  sqlite3ExprCode(pParse, pCol->pDflt, regOut);
  if( pCol->affinity>=SQLITE_AFF_TEXT ){
    sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
  }
  if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
}

static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);

static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);

struct IdxCover {
  Index *pIdx;     /* The index to be tested for coverage */
  int iCur;        /* Cursor number for the table corresponding to the index */
}

struct SrcCount {
  SrcList *pSrc;   /* One particular FROM clause in a nested query */
  int nThis;       /* Number of references to columns in pSrcList */
  int nOther;      /* Number of references to columns in other FROM clauses */
}


void sqlite3VdbeRecordUnpack(
  KeyInfo *pKeyInfo,     /* Information about the record format */
  int nKey,              /* Size of the binary record */
  const void *pKey,      /* The binary record */
  UnpackedRecord *p      /* Populate this structure before returning. */
){
  const unsigned char *aKey = (const unsigned char *)pKey;
  u32 d;
  u32 idx;                        /* Offset in aKey[] to read from */
  u16 u;                          /* Unsigned loop counter */
  u32 szHdr;
  Mem *pMem = p->aMem;

  p->default_rc = 0;
  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  idx = getVarint32(aKey, szHdr);
  d = szHdr;
  u = 0;
  while( idx<szHdr && d<=(u32)nKey ){
    u32 serial_type;

    idx += getVarint32(&aKey[idx], serial_type);
    pMem->enc = pKeyInfo->enc;
    pMem->db = pKeyInfo->db;
    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
    pMem->szMalloc = 0;
    pMem->z = 0;
    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
    pMem++;
    if( (++u)>=p->nField ) break;
  }
  if( d>(u32)nKey && u ){
    assert( CORRUPT_DB );
    /* In a corrupt record entry, the last pMem might have been set up using
    ** uninitialized memory. Overwrite its value with NULL, to prevent
    ** warnings from MSAN. */
    sqlite3VdbeMemSetNull(pMem-1);
  }
  assert( u<=pKeyInfo->nKeyField + 1 );
  p->nField = u;
}


static void vdbeAssertFieldCountWithinLimits(
  int nKey, const void *pKey,   /* The record to verify */
  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
){
  int nField = 0;
  u32 szHdr;
  u32 idx;
  u32 notUsed;
  const unsigned char *aKey = (const unsigned char*)pKey;

  if( CORRUPT_DB ) return;
  idx = getVarint32(aKey, szHdr);
  assert( nKey>=0 );
  assert( szHdr<=(u32)nKey );
  while( idx<szHdr ){
    idx += getVarint32(aKey+idx, notUsed);
    nField++;
  }
  assert( nField <= pKeyInfo->nAllField );
}


static void first_valueFinalizeFunc(sqlite3_context *pCtx){
  struct NthValueCtx *p;
  p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  if( p && p->pValue ){
    sqlite3_result_value(pCtx, p->pValue);
    sqlite3_value_free(p->pValue);
    p->pValue = 0;
  }
}