int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
                size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
                BN_CTX *ctx)
{
    BN_CTX *new_ctx = NULL;
    const EC_POINT *generator = NULL;
    EC_POINT *tmp = NULL;
    size_t totalnum;
    size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
    size_t pre_points_per_block = 0;
    size_t i, j;
    int k;
    int r_is_inverted = 0;
    int r_is_at_infinity = 1;
    size_t *wsize = NULL;       /* individual window sizes */
    signed char **wNAF = NULL;  /* individual wNAFs */
    size_t *wNAF_len = NULL;
    size_t max_len = 0;
    size_t num_val;
    EC_POINT **val = NULL;      /* precomputation */
    EC_POINT **v;
    EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
                                 * 'pre_comp->points' */
    const EC_PRE_COMP *pre_comp = NULL;
    int num_scalar = 0;         /* flag: will be set to 1 if 'scalar' must be
                                 * treated like other scalars, i.e.
                                 * precomputation is not available */
    int ret = 0;

    if (group->meth != r->meth) {
        ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
        return 0;
    }

    if ((scalar == NULL) && (num == 0)) {
        return EC_POINT_set_to_infinity(group, r);
    }

    for (i = 0; i < num; i++) {
        if (group->meth != points[i]->meth) {
            ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
            return 0;
        }
    }

    if (ctx == NULL) {
        ctx = new_ctx = BN_CTX_new();
        if (ctx == NULL)
            goto err;
    }

    if (scalar != NULL) {
        generator = EC_GROUP_get0_generator(group);
        if (generator == NULL) {
            ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
            goto err;
        }

        /* look if we can use precomputed multiples of generator */

        pre_comp =
            EC_EX_DATA_get_data(group->extra_data, ec_pre_comp_dup,
                                ec_pre_comp_free, ec_pre_comp_clear_free);

        if (pre_comp && pre_comp->numblocks
            && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
                0)) {
            blocksize = pre_comp->blocksize;

            /*
             * determine maximum number of blocks that wNAF splitting may
             * yield (NB: maximum wNAF length is bit length plus one)
             */
            numblocks = (BN_num_bits(scalar) / blocksize) + 1;

            /*
             * we cannot use more blocks than we have precomputation for
             */
            if (numblocks > pre_comp->numblocks)
                numblocks = pre_comp->numblocks;

            pre_points_per_block = (size_t)1 << (pre_comp->w - 1);

            /* check that pre_comp looks sane */
            if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
                ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                goto err;
            }
        } else {
            /* can't use precomputation */
            pre_comp = NULL;
            numblocks = 1;
            num_scalar = 1;     /* treat 'scalar' like 'num'-th element of
                                 * 'scalars' */
        }
    }

    totalnum = num + numblocks;

    wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0]));
    wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0]));
    /* include space for pivot */
    wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0]));
    val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0]));

    /* Ensure wNAF is initialised in case we end up going to err */
    if (wNAF)
        wNAF[0] = NULL;         /* preliminary pivot */

    if (!wsize || !wNAF_len || !wNAF || !val_sub) {
        ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    /*
     * num_val will be the total number of temporarily precomputed points
     */
    num_val = 0;

    for (i = 0; i < num + num_scalar; i++) {
        size_t bits;

        bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
        wsize[i] = EC_window_bits_for_scalar_size(bits);
        num_val += (size_t)1 << (wsize[i] - 1);
        wNAF[i + 1] = NULL;     /* make sure we always have a pivot */
        wNAF[i] =
            compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
                         &wNAF_len[i]);
        if (wNAF[i] == NULL)
            goto err;
        if (wNAF_len[i] > max_len)
            max_len = wNAF_len[i];
    }

    if (numblocks) {
        /* we go here iff scalar != NULL */

        if (pre_comp == NULL) {
            if (num_scalar != 1) {
                ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                goto err;
            }
            /* we have already generated a wNAF for 'scalar' */
        } else {
            signed char *tmp_wNAF = NULL;
            size_t tmp_len = 0;

            if (num_scalar != 0) {
                ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                goto err;
            }

            /*
             * use the window size for which we have precomputation
             */
            wsize[num] = pre_comp->w;
            tmp_wNAF = compute_wNAF(scalar, wsize[num], &tmp_len);
            if (!tmp_wNAF)
                goto err;

            if (tmp_len <= max_len) {
                /*
                 * One of the other wNAFs is at least as long as the wNAF
                 * belonging to the generator, so wNAF splitting will not buy
                 * us anything.
                 */

                numblocks = 1;
                totalnum = num + 1; /* don't use wNAF splitting */
                wNAF[num] = tmp_wNAF;
                wNAF[num + 1] = NULL;
                wNAF_len[num] = tmp_len;
                if (tmp_len > max_len)
                    max_len = tmp_len;
                /*
                 * pre_comp->points starts with the points that we need here:
                 */
                val_sub[num] = pre_comp->points;
            } else {
                /*
                 * don't include tmp_wNAF directly into wNAF array - use wNAF
                 * splitting and include the blocks
                 */

                signed char *pp;
                EC_POINT **tmp_points;

                if (tmp_len < numblocks * blocksize) {
                    /*
                     * possibly we can do with fewer blocks than estimated
                     */
                    numblocks = (tmp_len + blocksize - 1) / blocksize;
                    if (numblocks > pre_comp->numblocks) {
                        ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                        goto err;
                    }
                    totalnum = num + numblocks;
                }

                /* split wNAF in 'numblocks' parts */
                pp = tmp_wNAF;
                tmp_points = pre_comp->points;

                for (i = num; i < totalnum; i++) {
                    if (i < totalnum - 1) {
                        wNAF_len[i] = blocksize;
                        if (tmp_len < blocksize) {
                            ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                            goto err;
                        }
                        tmp_len -= blocksize;
                    } else
                        /*
                         * last block gets whatever is left (this could be
                         * more or less than 'blocksize'!)
                         */
                        wNAF_len[i] = tmp_len;

                    wNAF[i + 1] = NULL;
                    wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
                    if (wNAF[i] == NULL) {
                        ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
                        OPENSSL_free(tmp_wNAF);
                        goto err;
                    }
                    memcpy(wNAF[i], pp, wNAF_len[i]);
                    if (wNAF_len[i] > max_len)
                        max_len = wNAF_len[i];

                    if (*tmp_points == NULL) {
                        ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                        OPENSSL_free(tmp_wNAF);
                        goto err;
                    }
                    val_sub[i] = tmp_points;
                    tmp_points += pre_points_per_block;
                    pp += blocksize;
                }
                OPENSSL_free(tmp_wNAF);
            }
        }
    }

    /*
     * All points we precompute now go into a single array 'val'.
     * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
     * subarray of 'pre_comp->points' if we already have precomputation.
     */
    val = OPENSSL_malloc((num_val + 1) * sizeof(val[0]));
    if (val == NULL) {
        ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
        goto err;
    }
    val[num_val] = NULL;        /* pivot element */

    /* allocate points for precomputation */
    v = val;
    for (i = 0; i < num + num_scalar; i++) {
        val_sub[i] = v;
        for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
            *v = EC_POINT_new(group);
            if (*v == NULL)
                goto err;
            v++;
        }
    }
    if (!(v == val + num_val)) {
        ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
        goto err;
    }

    if (!(tmp = EC_POINT_new(group)))
        goto err;

    /*-
     * prepare precomputed values:
     *    val_sub[i][0] :=     points[i]
     *    val_sub[i][1] := 3 * points[i]
     *    val_sub[i][2] := 5 * points[i]
     *    ...
     */
    for (i = 0; i < num + num_scalar; i++) {
        if (i < num) {
            if (!EC_POINT_copy(val_sub[i][0], points[i]))
                goto err;
        } else {
            if (!EC_POINT_copy(val_sub[i][0], generator))
                goto err;
        }

        if (wsize[i] > 1) {
            if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
                goto err;
            for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
                if (!EC_POINT_add
                    (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
                    goto err;
            }
        }
    }

#if 1                           /* optional; EC_window_bits_for_scalar_size
                                 * assumes we do this step */
    if (!EC_POINTs_make_affine(group, num_val, val, ctx))
        goto err;
#endif

    r_is_at_infinity = 1;

    for (k = max_len - 1; k >= 0; k--) {
        if (!r_is_at_infinity) {
            if (!EC_POINT_dbl(group, r, r, ctx))
                goto err;
        }

        for (i = 0; i < totalnum; i++) {
            if (wNAF_len[i] > (size_t)k) {
                int digit = wNAF[i][k];
                int is_neg;

                if (digit) {
                    is_neg = digit < 0;

                    if (is_neg)
                        digit = -digit;

                    if (is_neg != r_is_inverted) {
                        if (!r_is_at_infinity) {
                            if (!EC_POINT_invert(group, r, ctx))
                                goto err;
                        }
                        r_is_inverted = !r_is_inverted;
                    }

                    /* digit > 0 */

                    if (r_is_at_infinity) {
                        if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
                            goto err;
                        r_is_at_infinity = 0;
                    } else {
                        if (!EC_POINT_add
                            (group, r, r, val_sub[i][digit >> 1], ctx))
                            goto err;
                    }
                }
            }
        }
    }

    if (r_is_at_infinity) {
        if (!EC_POINT_set_to_infinity(group, r))
            goto err;
    } else {
        if (r_is_inverted)
            if (!EC_POINT_invert(group, r, ctx))
                goto err;
    }

    ret = 1;

 err:
    if (new_ctx != NULL)
        BN_CTX_free(new_ctx);
    if (tmp != NULL)
        EC_POINT_free(tmp);
    if (wsize != NULL)
        OPENSSL_free(wsize);
    if (wNAF_len != NULL)
        OPENSSL_free(wNAF_len);
    if (wNAF != NULL) {
        signed char **w;

        for (w = wNAF; *w != NULL; w++)
            OPENSSL_free(*w);

        OPENSSL_free(wNAF);
    }
    if (val != NULL) {
        for (v = val; *v != NULL; v++)
            EC_POINT_clear_free(*v);

        OPENSSL_free(val);
    }
    if (val_sub != NULL) {
        OPENSSL_free(val_sub);
    }
    return ret;
}


void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
{
    BN_ULONG t;
    int i;

    bn_wcheck_size(a, nwords);
    bn_wcheck_size(b, nwords);

    assert(a != b);
    assert((condition & (condition - 1)) == 0);
    assert(sizeof(BN_ULONG) >= sizeof(int));

    condition = ((condition - 1) >> (BN_BITS2 - 1)) - 1;

    t = (a->top ^ b->top) & condition;
    a->top ^= t;
    b->top ^= t;

#define BN_CONSTTIME_SWAP(ind) \
        do { \
                t = (a->d[ind] ^ b->d[ind]) & condition; \
                a->d[ind] ^= t; \
                b->d[ind] ^= t; \
        } while (0)

    switch (nwords) {
    default:
        for (i = 10; i < nwords; i++)
            BN_CONSTTIME_SWAP(i);
        /* Fallthrough */
    case 10:
        BN_CONSTTIME_SWAP(9);   /* Fallthrough */
    case 9:
        BN_CONSTTIME_SWAP(8);   /* Fallthrough */
    case 8:
        BN_CONSTTIME_SWAP(7);   /* Fallthrough */
    case 7:
        BN_CONSTTIME_SWAP(6);   /* Fallthrough */
    case 6:
        BN_CONSTTIME_SWAP(5);   /* Fallthrough */
    case 5:
        BN_CONSTTIME_SWAP(4);   /* Fallthrough */
    case 4:
        BN_CONSTTIME_SWAP(3);   /* Fallthrough */
    case 3:
        BN_CONSTTIME_SWAP(2);   /* Fallthrough */
    case 2:
        BN_CONSTTIME_SWAP(1);   /* Fallthrough */
    case 1:
        BN_CONSTTIME_SWAP(0);
    }
#undef BN_CONSTTIME_SWAP
}


int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
{
    int al, i, j, ret;
    unsigned int n;
    SSL3_RECORD *rr;
    void (*cb) (const SSL *ssl, int type2, int val) = NULL;

    if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
        if (!ssl3_setup_buffers(s))
            return (-1);

    /* XXX: check what the second '&& type' is about */
    if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
         (type != SSL3_RT_HANDSHAKE) && type) ||
        (peek && (type != SSL3_RT_APPLICATION_DATA))) {
        SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
        return -1;
    }

    /*
     * check whether there's a handshake message (client hello?) waiting
     */
    if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
        return ret;

    /*
     * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
     */

#ifndef OPENSSL_NO_SCTP
    /*
     * Continue handshake if it had to be interrupted to read app data with
     * SCTP.
     */
    if ((!s->in_handshake && SSL_in_init(s)) ||
        (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
         (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
          || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)
         && s->s3->in_read_app_data != 2))
#else
    if (!s->in_handshake && SSL_in_init(s))
#endif
    {
        /* type == SSL3_RT_APPLICATION_DATA */
        i = s->handshake_func(s);
        if (i < 0)
            return (i);
        if (i == 0) {
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
            return (-1);
        }
    }

 start:
    s->rwstate = SSL_NOTHING;

    /*-
     * s->s3->rrec.type         - is the type of record
     * s->s3->rrec.data,    - data
     * s->s3->rrec.off,     - offset into 'data' for next read
     * s->s3->rrec.length,  - number of bytes.
     */
    rr = &(s->s3->rrec);

    /*
     * We are not handshaking and have no data yet, so process data buffered
     * during the last handshake in advance, if any.
     */
    if (s->state == SSL_ST_OK && rr->length == 0) {
        pitem *item;
        item = pqueue_pop(s->d1->buffered_app_data.q);
        if (item) {
#ifndef OPENSSL_NO_SCTP
            /* Restore bio_dgram_sctp_rcvinfo struct */
            if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
                DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
                BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
                         sizeof(rdata->recordinfo), &rdata->recordinfo);
            }
#endif

            dtls1_copy_record(s, item);

            OPENSSL_free(item->data);
            pitem_free(item);
        }
    }

    /* Check for timeout */
    if (dtls1_handle_timeout(s) > 0)
        goto start;

    /* get new packet if necessary */
    if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
        ret = dtls1_get_record(s);
        if (ret <= 0) {
            ret = dtls1_read_failed(s, ret);
            /* anything other than a timeout is an error */
            if (ret <= 0)
                return (ret);
            else
                goto start;
        }
    }

    if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) {
        rr->length = 0;
        goto start;
    }

    /*
     * Reset the count of consecutive warning alerts if we've got a non-empty
     * record that isn't an alert.
     */
    if (rr->type != SSL3_RT_ALERT && rr->length != 0)
        s->cert->alert_count = 0;

    /* we now have a packet which can be read and processed */

    if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
                                   * reset by ssl3_get_finished */
        && (rr->type != SSL3_RT_HANDSHAKE)) {
        /*
         * We now have application data between CCS and Finished. Most likely
         * the packets were reordered on their way, so buffer the application
         * data for later processing rather than dropping the connection.
         */
        if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) <
            0) {
            SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
            return -1;
        }
        rr->length = 0;
        goto start;
    }

    /*
     * If the other end has shut down, throw anything we read away (even in
     * 'peek' mode)
     */
    if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
        rr->length = 0;
        s->rwstate = SSL_NOTHING;
        return (0);
    }

    if (type == rr->type) {     /* SSL3_RT_APPLICATION_DATA or
                                 * SSL3_RT_HANDSHAKE */
        /*
         * make sure that we are not getting application data when we are
         * doing a handshake for the first time
         */
        if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
            (s->enc_read_ctx == NULL)) {
            al = SSL_AD_UNEXPECTED_MESSAGE;
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
            goto f_err;
        }

        if (len <= 0)
            return (len);

        if ((unsigned int)len > rr->length)
            n = rr->length;
        else
            n = (unsigned int)len;

        memcpy(buf, &(rr->data[rr->off]), n);
        if (!peek) {
            rr->length -= n;
            rr->off += n;
            if (rr->length == 0) {
                s->rstate = SSL_ST_READ_HEADER;
                rr->off = 0;
            }
        }
#ifndef OPENSSL_NO_SCTP
        /*
         * We were about to renegotiate but had to read belated application
         * data first, so retry.
         */
        if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
            rr->type == SSL3_RT_APPLICATION_DATA &&
            (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
             || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) {
            s->rwstate = SSL_READING;
            BIO_clear_retry_flags(SSL_get_rbio(s));
            BIO_set_retry_read(SSL_get_rbio(s));
        }

        /*
         * We might had to delay a close_notify alert because of reordered
         * app data. If there was an alert and there is no message to read
         * anymore, finally set shutdown.
         */
        if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
            s->d1->shutdown_received
            && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
            s->shutdown |= SSL_RECEIVED_SHUTDOWN;
            return (0);
        }
#endif
        return (n);
    }

    /*
     * If we get here, then type != rr->type; if we have a handshake message,
     * then it was unexpected (Hello Request or Client Hello).
     */

    /*
     * In case of record types for which we have 'fragment' storage, fill
     * that so that we can process the data at a fixed place.
     */
    {
        unsigned int k, dest_maxlen = 0;
        unsigned char *dest = NULL;
        unsigned int *dest_len = NULL;

        if (rr->type == SSL3_RT_HANDSHAKE) {
            dest_maxlen = sizeof(s->d1->handshake_fragment);
            dest = s->d1->handshake_fragment;
            dest_len = &s->d1->handshake_fragment_len;
        } else if (rr->type == SSL3_RT_ALERT) {
            dest_maxlen = sizeof(s->d1->alert_fragment);
            dest = s->d1->alert_fragment;
            dest_len = &s->d1->alert_fragment_len;
        }
#ifndef OPENSSL_NO_HEARTBEATS
        else if (rr->type == TLS1_RT_HEARTBEAT) {
            dtls1_process_heartbeat(s);

            /* Exit and notify application to read again */
            rr->length = 0;
            s->rwstate = SSL_READING;
            BIO_clear_retry_flags(SSL_get_rbio(s));
            BIO_set_retry_read(SSL_get_rbio(s));
            return (-1);
        }
#endif
        /* else it's a CCS message, or application data or wrong */
        else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
            /*
             * Application data while renegotiating is allowed. Try again
             * reading.
             */
            if (rr->type == SSL3_RT_APPLICATION_DATA) {
                BIO *bio;
                s->s3->in_read_app_data = 2;
                bio = SSL_get_rbio(s);
                s->rwstate = SSL_READING;
                BIO_clear_retry_flags(bio);
                BIO_set_retry_read(bio);
                return (-1);
            }

            /* Not certain if this is the right error handling */
            al = SSL_AD_UNEXPECTED_MESSAGE;
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
            goto f_err;
        }

        if (dest_maxlen > 0) {
            /*
             * XDTLS: In a pathalogical case, the Client Hello may be
             * fragmented--don't always expect dest_maxlen bytes
             */
            if (rr->length < dest_maxlen) {
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
                /*
                 * for normal alerts rr->length is 2, while
                 * dest_maxlen is 7 if we were to handle this
                 * non-existing alert...
                 */
                FIX ME
#endif
                 s->rstate = SSL_ST_READ_HEADER;
                rr->length = 0;
                goto start;
            }

            /* now move 'n' bytes: */
            for (k = 0; k < dest_maxlen; k++) {
                dest[k] = rr->data[rr->off++];
                rr->length--;
            }
            *dest_len = dest_maxlen;
        }
    }

    /*-
     * s->d1->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
     * s->d1->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
     * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
     */

    /* If we are a client, check for an incoming 'Hello Request': */
    if ((!s->server) &&
        (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
        (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
        (s->session != NULL) && (s->session->cipher != NULL)) {
        s->d1->handshake_fragment_len = 0;

        if ((s->d1->handshake_fragment[1] != 0) ||
            (s->d1->handshake_fragment[2] != 0) ||
            (s->d1->handshake_fragment[3] != 0)) {
            al = SSL_AD_DECODE_ERROR;
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
            goto f_err;
        }

        /*
         * no need to check sequence number on HELLO REQUEST messages
         */

        if (s->msg_callback)
            s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
                            s->d1->handshake_fragment, 4, s,
                            s->msg_callback_arg);

        if (SSL_is_init_finished(s) &&
            !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
            !s->s3->renegotiate) {
            s->d1->handshake_read_seq++;
            s->new_session = 1;
            ssl3_renegotiate(s);
            if (ssl3_renegotiate_check(s)) {
                i = s->handshake_func(s);
                if (i < 0)
                    return (i);
                if (i == 0) {
                    SSLerr(SSL_F_DTLS1_READ_BYTES,
                           SSL_R_SSL_HANDSHAKE_FAILURE);
                    return (-1);
                }

                if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
                    if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
                        BIO *bio;
                        /*
                         * In the case where we try to read application data,
                         * but we trigger an SSL handshake, we return -1 with
                         * the retry option set.  Otherwise renegotiation may
                         * cause nasty problems in the blocking world
                         */
                        s->rwstate = SSL_READING;
                        bio = SSL_get_rbio(s);
                        BIO_clear_retry_flags(bio);
                        BIO_set_retry_read(bio);
                        return (-1);
                    }
                }
            }
        }
        /*
         * we either finished a handshake or ignored the request, now try
         * again to obtain the (application) data we were asked for
         */
        goto start;
    }

    /*
     * If we are a server and get a client hello when renegotiation isn't
     * allowed send back a no renegotiation alert and carry on.
     */
    if (s->server
            && SSL_is_init_finished(s)
            && !s->s3->send_connection_binding
            && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH
            && s->d1->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO
            && s->s3->previous_client_finished_len != 0
            && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) {
        s->d1->handshake_fragment_len = 0;
        rr->length = 0;
        ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
        goto start;
    }

    if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
        int alert_level = s->d1->alert_fragment[0];
        int alert_descr = s->d1->alert_fragment[1];

        s->d1->alert_fragment_len = 0;

        if (s->msg_callback)
            s->msg_callback(0, s->version, SSL3_RT_ALERT,
                            s->d1->alert_fragment, 2, s, s->msg_callback_arg);

        if (s->info_callback != NULL)
            cb = s->info_callback;
        else if (s->ctx->info_callback != NULL)
            cb = s->ctx->info_callback;

        if (cb != NULL) {
            j = (alert_level << 8) | alert_descr;
            cb(s, SSL_CB_READ_ALERT, j);
        }

        if (alert_level == SSL3_AL_WARNING) {
            s->s3->warn_alert = alert_descr;

            s->cert->alert_count++;
            if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) {
                al = SSL_AD_UNEXPECTED_MESSAGE;
                SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
                goto f_err;
            }

            if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
#ifndef OPENSSL_NO_SCTP
                /*
                 * With SCTP and streams the socket may deliver app data
                 * after a close_notify alert. We have to check this first so
                 * that nothing gets discarded.
                 */
                if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
                    BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
                    s->d1->shutdown_received = 1;
                    s->rwstate = SSL_READING;
                    BIO_clear_retry_flags(SSL_get_rbio(s));
                    BIO_set_retry_read(SSL_get_rbio(s));
                    return -1;
                }
#endif
                s->shutdown |= SSL_RECEIVED_SHUTDOWN;
                return (0);
            }
#if 0
            /* XXX: this is a possible improvement in the future */
            /* now check if it's a missing record */
            if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
                unsigned short seq;
                unsigned int frag_off;
                unsigned char *p = &(s->d1->alert_fragment[2]);

                n2s(p, seq);
                n2l3(p, frag_off);

                dtls1_retransmit_message(s,
                                         dtls1_get_queue_priority
                                         (frag->msg_header.seq, 0), frag_off,
                                         &found);
                if (!found && SSL_in_init(s)) {
                    /*
                     * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
                     */
                    /*
                     * requested a message not yet sent, send an alert
                     * ourselves
                     */
                    ssl3_send_alert(s, SSL3_AL_WARNING,
                                    DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
                }
            }
#endif
        } else if (alert_level == SSL3_AL_FATAL) {
            char tmp[16];

            s->rwstate = SSL_NOTHING;
            s->s3->fatal_alert = alert_descr;
            SSLerr(SSL_F_DTLS1_READ_BYTES,
                   SSL_AD_REASON_OFFSET + alert_descr);
            BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
            ERR_add_error_data(2, "SSL alert number ", tmp);
            s->shutdown |= SSL_RECEIVED_SHUTDOWN;
            SSL_CTX_remove_session(s->session_ctx, s->session);
            return (0);
        } else {
            al = SSL_AD_ILLEGAL_PARAMETER;
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
            goto f_err;
        }

        goto start;
    }

    if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
                                            * shutdown */
        s->rwstate = SSL_NOTHING;
        rr->length = 0;
        return (0);
    }

    if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
        struct ccs_header_st ccs_hdr;
        unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;

        dtls1_get_ccs_header(rr->data, &ccs_hdr);

        if (s->version == DTLS1_BAD_VER)
            ccs_hdr_len = 3;

        /*
         * 'Change Cipher Spec' is just a single byte, so we know exactly
         * what the record payload has to look like
         */
        /* XDTLS: check that epoch is consistent */
        if ((rr->length != ccs_hdr_len) ||
            (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
            al = SSL_AD_ILLEGAL_PARAMETER;
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
            goto f_err;
        }

        rr->length = 0;

        if (s->msg_callback)
            s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
                            rr->data, 1, s, s->msg_callback_arg);

        /*
         * We can't process a CCS now, because previous handshake messages
         * are still missing, so just drop it.
         */
        if (!s->d1->change_cipher_spec_ok) {
            goto start;
        }

        s->d1->change_cipher_spec_ok = 0;

        s->s3->change_cipher_spec = 1;
        if (!ssl3_do_change_cipher_spec(s))
            goto err;

        /* do this whenever CCS is processed */
        dtls1_reset_seq_numbers(s, SSL3_CC_READ);

        if (s->version == DTLS1_BAD_VER)
            s->d1->handshake_read_seq++;

#ifndef OPENSSL_NO_SCTP
        /*
         * Remember that a CCS has been received, so that an old key of
         * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
         * SCTP is used
         */
        BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
#endif

        goto start;
    }

    /*
     * Unexpected handshake message (Client Hello, or protocol violation)
     */
    if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
        !s->in_handshake) {
        struct hm_header_st msg_hdr;

        /* this may just be a stale retransmit */
        dtls1_get_message_header(rr->data, &msg_hdr);
        if (rr->epoch != s->d1->r_epoch) {
            rr->length = 0;
            goto start;
        }

        /*
         * If we are server, we may have a repeated FINISHED of the client
         * here, then retransmit our CCS and FINISHED.
         */
        if (msg_hdr.type == SSL3_MT_FINISHED) {
            if (dtls1_check_timeout_num(s) < 0)
                return -1;

            dtls1_retransmit_buffered_messages(s);
            rr->length = 0;
            goto start;
        }

        if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
            !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
#if 0                           /* worked only because C operator preferences
                                 * are not as expected (and because this is
                                 * not really needed for clients except for
                                 * detecting protocol violations): */
            s->state = SSL_ST_BEFORE | (s->server)
                ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#else
            s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
#endif
            s->renegotiate = 1;
            s->new_session = 1;
        }
        i = s->handshake_func(s);
        if (i < 0)
            return (i);
        if (i == 0) {
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
            return (-1);
        }

        if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
            if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
                BIO *bio;
                /*
                 * In the case where we try to read application data, but we
                 * trigger an SSL handshake, we return -1 with the retry
                 * option set.  Otherwise renegotiation may cause nasty
                 * problems in the blocking world
                 */
                s->rwstate = SSL_READING;
                bio = SSL_get_rbio(s);
                BIO_clear_retry_flags(bio);
                BIO_set_retry_read(bio);
                return (-1);
            }
        }
        goto start;
    }

    switch (rr->type) {
    default:
#ifndef OPENSSL_NO_TLS
        /* TLS just ignores unknown message types */
        if (s->version == TLS1_VERSION) {
            rr->length = 0;
            goto start;
        }
#endif
        al = SSL_AD_UNEXPECTED_MESSAGE;
        SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
        goto f_err;
    case SSL3_RT_CHANGE_CIPHER_SPEC:
    case SSL3_RT_ALERT:
    case SSL3_RT_HANDSHAKE:
        /*
         * we already handled all of these, with the possible exception of
         * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
         * happen when type != rr->type
         */
        al = SSL_AD_UNEXPECTED_MESSAGE;
        SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
        goto f_err;
    case SSL3_RT_APPLICATION_DATA:
        /*
         * At this point, we were expecting handshake data, but have
         * application data.  If the library was running inside ssl3_read()
         * (i.e. in_read_app_data is set) and it makes sense to read
         * application data at this point (session renegotiation not yet
         * started), we will indulge it.
         */
        if (s->s3->in_read_app_data &&
            (s->s3->total_renegotiations != 0) &&
            (((s->state & SSL_ST_CONNECT) &&
              (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
              (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
             ) || ((s->state & SSL_ST_ACCEPT) &&
                   (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
                   (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
             )
            )) {
            s->s3->in_read_app_data = 2;
            return (-1);
        } else {
            al = SSL_AD_UNEXPECTED_MESSAGE;
            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
            goto f_err;
        }
    }
    /* not reached */

 f_err:
    ssl3_send_alert(s, SSL3_AL_FATAL, al);
 err:
    return (-1);
}


static inline void pcnet_rmd_store ( PCNetState * s , struct pcnet_RMD * rmd , hwaddr addr ) {
 if ( ! BCR_SSIZE32 ( s ) ) {
 struct {
 uint32_t rbadr ;
 int16_t buf_length ;
 int16_t msg_length ;
 }
 rda ;
 rda . rbadr = cpu_to_le32 ( ( rmd -> rbadr & 0xffffff ) | ( ( rmd -> status & 0xff00 ) << 16 ) ) ;
 rda . buf_length = cpu_to_le16 ( rmd -> buf_length ) ;
 rda . msg_length = cpu_to_le16 ( rmd -> msg_length ) ;
 s -> phys_mem_write ( s -> dma_opaque , addr , ( void * ) & rda , sizeof ( rda ) , 0 ) ;
 }
 else {
 struct {
 uint32_t rbadr ;
 int16_t buf_length ;
 int16_t status ;
 uint32_t msg_length ;
 uint32_t res ;
 }
 rda ;
 rda . rbadr = cpu_to_le32 ( rmd -> rbadr ) ;
 rda . buf_length = cpu_to_le16 ( rmd -> buf_length ) ;
 rda . status = cpu_to_le16 ( rmd -> status ) ;
 rda . msg_length = cpu_to_le32 ( rmd -> msg_length ) ;
 rda . res = cpu_to_le32 ( rmd -> res ) ;
 if ( BCR_SWSTYLE ( s ) == 3 ) {
 uint32_t tmp = rda . rbadr ;
 rda . rbadr = rda . msg_length ;
 rda . msg_length = tmp ;
 }
 s -> phys_mem_write ( s -> dma_opaque , addr , ( void * ) & rda , sizeof ( rda ) , 0 ) ;
 }
 }


array_value_internal (s, quoted, flags, rtype, indp)
     char *s;
     int quoted, flags, *rtype;
     arrayind_t *indp;
{
  int len;
  arrayind_t ind;
  char *akey;
  char *retval, *t, *temp;
  WORD_LIST *l;
  SHELL_VAR *var;

  var = array_variable_part (s, &t, &len);

  /* Expand the index, even if the variable doesn't exist, in case side
     effects are needed, like ${w[i++]} where w is unset. */
#if 0
  if (var == 0)
    return (char *)NULL;
#endif

  if (len == 0)
    return ((char *)NULL);	/* error message already printed */

  /* [ */
  akey = 0;
  if (ALL_ELEMENT_SUB (t[0]) && t[1] == ']')
    {
      if (rtype)
	*rtype = (t[0] == '*') ? 1 : 2;
      if ((flags & AV_ALLOWALL) == 0)
	{
	  err_badarraysub (s);
	  return ((char *)NULL);
	}
      else if (var == 0 || value_cell (var) == 0)	/* XXX - check for invisible_p(var) ? */
	return ((char *)NULL);
      else if (array_p (var) == 0 && assoc_p (var) == 0)
	l = add_string_to_list (value_cell (var), (WORD_LIST *)NULL);
      else if (assoc_p (var))
	{
	  l = assoc_to_word_list (assoc_cell (var));
	  if (l == (WORD_LIST *)NULL)
	    return ((char *)NULL);
	}
      else
	{
	  l = array_to_word_list (array_cell (var));
	  if (l == (WORD_LIST *)NULL)
	    return ((char *) NULL);
	}

      if (t[0] == '*' && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
	{
	  temp = string_list_dollar_star (l);
	  retval = quote_string (temp);		/* XXX - leak here */
	  free (temp);
	}
      else	/* ${name[@]} or unquoted ${name[*]} */
	retval = string_list_dollar_at (l, quoted, 0);	/* XXX - leak here */

      dispose_words (l);
    }
  else
    {
      if (rtype)
	*rtype = 0;
      if (var == 0 || array_p (var) || assoc_p (var) == 0)
	{
	  if ((flags & AV_USEIND) == 0 || indp == 0)
	    {
	      ind = array_expand_index (var, t, len);
	      if (ind < 0)
		{
		  /* negative subscripts to indexed arrays count back from end */
		  if (var && array_p (var))
		    ind = array_max_index (array_cell (var)) + 1 + ind;
		  if (ind < 0)
		    INDEX_ERROR();
		}
	      if (indp)
		*indp = ind;
	    }
	  else if (indp)
	    ind = *indp;
	}
      else if (assoc_p (var))
	{
	  t[len - 1] = '\0';
	  akey = expand_assignment_string_to_string (t, 0);	/* [ */
	  t[len - 1] = ']';
	  if (akey == 0 || *akey == 0)
	    {
	      FREE (akey);
	      INDEX_ERROR();
	    }
	}

      if (var == 0 || value_cell (var) == 0)	/* XXX - check invisible_p(var) ? */
	{
          FREE (akey);
	  return ((char *)NULL);
	}
      if (array_p (var) == 0 && assoc_p (var) == 0)
	return (ind == 0 ? value_cell (var) : (char *)NULL);
      else if (assoc_p (var))
        {
	  retval = assoc_reference (assoc_cell (var), akey);
	  free (akey);
        }
      else
	retval = array_reference (array_cell (var), ind);
    }

  return retval;
}


static void opt_format(const char *arg) { /* compatibility stuff for pgmyuv */ if (!strcmp(arg, "pgmyuv")) { opt_image_format(arg); arg = "image"; } file_iformat = av_find_input_format(arg); file_oformat = guess_format(arg, NULL, NULL); if (!file_iformat && !file_oformat) { fprintf(stderr, "Unknown input or output format: %s\n", arg); exit(1); } }


void memory_region_add_eventfd(MemoryRegion *mr, hwaddr addr, unsigned size, bool match_data, uint64_t data, EventNotifier *e) { MemoryRegionIoeventfd mrfd = { .addr.start = int128_make64(addr), .addr.size = int128_make64(size), .match_data = match_data, .data = data, .e = e, }; unsigned i; if (size) { adjust_endianness(mr, &mrfd.data, size); memory_region_transaction_begin(); for (i = 0; i < mr->ioeventfd_nb; ++i) { if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) { break; ++mr->ioeventfd_nb; mr->ioeventfds = g_realloc(mr->ioeventfds, sizeof(*mr->ioeventfds) * mr->ioeventfd_nb); memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i], sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i)); mr->ioeventfds[i] = mrfd; ioeventfd_update_pending |= mr->enabled; memory_region_transaction_commit();


void proto_register_applemidi ( void ) {
 static hf_register_info hf [ ] = {
 {
 & hf_applemidi_signature , {
 "Signature" , "applemidi.signature" , FT_UINT16 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_command , {
 "Command" , "applemidi.command" , FT_UINT16 , BASE_HEX , VALS ( applemidi_commands ) , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_protocol_version , {
 "Protocol Version" , "applemidi.protocol_version" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_token , {
 "Initiator Token" , "applemidi.initiator_token" , FT_UINT32 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_ssrc , {
 "Sender SSRC" , "applemidi.sender_ssrc" , FT_UINT32 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_name , {
 "Name" , "applemidi.name" , FT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_count , {
 "Count" , "applemidi.count" , FT_UINT8 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_padding , {
 "Padding" , "applemidi.padding" , FT_UINT24 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_timestamp1 , {
 "Timestamp 1" , "applemidi.timestamp1" , FT_UINT64 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_timestamp2 , {
 "Timestamp 2" , "applemidi.timestamp2" , FT_UINT64 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_timestamp3 , {
 "Timestamp 3" , "applemidi.timestamp3" , FT_UINT64 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_sequence_num , {
 "Sequence Number" , "applemidi.sequence_number" , FT_UINT32 , BASE_HEX , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_rtp_sequence_num , {
 "RTP Sequence Number" , "applemidi.rtp_sequence_number" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_rtp_bitrate_limit , {
 "Bitrate limit" , "applemidi.bitrate_limit" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL }
 }
 , {
 & hf_applemidi_unknown_data , {
 "Unknown Data" , "applemidi.unknown_data" , FT_BYTES , BASE_NONE , NULL , 0x00 , NULL , HFILL }
 }
 , }
 ;
 static gint * ett [ ] = {
 & ett_applemidi , & ett_applemidi_seq_num }
 ;
 proto_applemidi = proto_register_protocol ( APPLEMIDI_DISSECTOR_NAME , APPLEMIDI_DISSECTOR_SHORTNAME , APPLEMIDI_DISSECTOR_ABBREVIATION ) ;
 proto_register_field_array ( proto_applemidi , hf , array_length ( hf ) ) ;
 proto_register_subtree_array ( ett , array_length ( ett ) ) ;
 }


static int do_fail ( xd3_stream * stream , const char * buf ) {
 int ret ;
 ret = system ( buf ) ;
 if ( ! WIFEXITED ( ret ) || WEXITSTATUS ( ret ) != 1 ) {
 stream -> msg = "command should have not succeeded" ;
 XPR ( NT "command was %s\n" , buf ) ;
 return XD3_INTERNAL ;
 }
 return 0 ;
 }


char *g_strdup(const char *s) { char *dup; size_t i; if (!s) { return NULL; } __coverity_string_null_sink__(s); __coverity_string_size_sink__(s); dup = __coverity_alloc_nosize__(); __coverity_mark_as_afm_allocated__(dup, AFM_free); for (i = 0; (dup[i] = s[i]); i++) ; return dup; }


int change_logfile ( const char * fname , int leave_crumbs ) {
 FILE * new_file ;
 const char * log_fname ;
 char * abs_fname ;
 # if ! defined ( SYS_WINNT ) && ! defined ( SYS_VXWORKS ) && ! defined ( VMS ) char curdir [ 512 ] ;
 size_t cd_octets ;
 size_t octets ;
 # endif REQUIRE ( fname != NULL ) ;
 log_fname = fname ;
 if ( syslog_file != NULL && syslog_fname != NULL && == strcmp ( syslog_fname , log_fname ) ) return 0 ;
 if ( 0 == strcmp ( log_fname , "stderr" ) ) {
 new_file = stderr ;
 abs_fname = estrdup ( log_fname ) ;
 }
 else if ( 0 == strcmp ( log_fname , "stdout" ) ) {
 new_file = stdout ;
 abs_fname = estrdup ( log_fname ) ;
 }
 else {
 if ( syslog_fname != NULL && == strcmp ( log_fname , syslog_fname ) ) log_fname = syslog_abs_fname ;
 # if ! defined ( SYS_WINNT ) && ! defined ( SYS_VXWORKS ) && ! defined ( VMS ) if ( log_fname != syslog_abs_fname && DIR_SEP != log_fname [ 0 ] && != strcmp ( log_fname , "stderr" ) && != strcmp ( log_fname , "stdout" ) && NULL != getcwd ( curdir , sizeof ( curdir ) ) ) {
 cd_octets = strlen ( curdir ) ;
 if ( cd_octets > 1 && DIR_SEP == curdir [ cd_octets - 1 ] ) cd_octets -- ;
 octets = cd_octets ;
 octets += 1 ;
 octets += strlen ( log_fname ) ;
 octets += 1 ;
 abs_fname = emalloc ( octets ) ;
 snprintf ( abs_fname , octets , "%.*s%c%s" , ( int ) cd_octets , curdir , DIR_SEP , log_fname ) ;
 }
 else # endif abs_fname = estrdup ( log_fname ) ;
 TRACE ( 1 , ( "attempting to open log %s\n" , abs_fname ) ) ;
 new_file = fopen ( abs_fname , "a" ) ;
 }
 if ( NULL == new_file ) {
 free ( abs_fname ) ;
 return - 1 ;
 }
 if ( leave_crumbs && ( syslogit || log_fname != syslog_abs_fname ) ) msyslog ( LOG_NOTICE , "switching logging to file %s" , abs_fname ) ;
 if ( syslog_file != NULL && syslog_file != stderr && syslog_file != stdout && fileno ( syslog_file ) != fileno ( new_file ) ) fclose ( syslog_file ) ;
 syslog_file = new_file ;
 if ( log_fname == syslog_abs_fname ) {
 free ( abs_fname ) ;
 }
 else {
 if ( syslog_abs_fname != NULL && syslog_abs_fname != syslog_fname ) free ( syslog_abs_fname ) ;
 if ( syslog_fname != NULL ) free ( syslog_fname ) ;
 syslog_fname = estrdup ( log_fname ) ;
 syslog_abs_fname = abs_fname ;
 }
 syslogit = FALSE ;
 return 0 ;
 }


initialize_subshell ()
{
#if defined (ALIAS)
  /* Forget about any aliases that we knew of.  We are in a subshell. */
  delete_all_aliases ();
#endif /* ALIAS */

#if defined (HISTORY)
  /* Forget about the history lines we have read.  This is a non-interactive
     subshell. */
  history_lines_this_session = 0;
#endif

#if defined (JOB_CONTROL)
  /* Forget about the way job control was working. We are in a subshell. */
  without_job_control ();
  set_sigchld_handler ();
  init_job_stats ();
#endif /* JOB_CONTROL */

  /* Reset the values of the shell flags and options. */
  reset_shell_flags ();
  reset_shell_options ();
  reset_shopt_options ();

  /* Zero out builtin_env, since this could be a shell script run from a
     sourced file with a temporary environment supplied to the `source/.'
     builtin.  Such variables are not supposed to be exported (empirical
     testing with sh and ksh).  Just throw it away; don't worry about a
     memory leak. */
  if (vc_isbltnenv (shell_variables))
    shell_variables = shell_variables->down;

  clear_unwind_protect_list (0);
  /* XXX -- are there other things we should be resetting here? */
  parse_and_execute_level = 0;		/* nothing left to restore it */

  /* We're no longer inside a shell function. */
  variable_context = return_catch_flag = funcnest = evalnest = sourcenest = 0;

  executing_list = 0;		/* XXX */

  /* If we're not interactive, close the file descriptor from which we're
     reading the current shell script. */
  if (interactive_shell == 0)
    unset_bash_input (0);
}


static int dissect_t38_UDPTLPacket ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 # line 232 "../../asn1/t38/t38.cnf" Data_Field_field_type_value = 1 ;
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_t38_UDPTLPacket , UDPTLPacket_sequence ) ;
 return offset ;
 }


bash_filename_stat_hook (dirname)
     char **dirname;
{
  char *local_dirname, *new_dirname, *t;
  int should_expand_dirname, return_value;
  int global_nounset;
  WORD_LIST *wl;
  struct stat sb;

  local_dirname = *dirname;
  should_expand_dirname = return_value = 0;
  if (t = mbschr (local_dirname, '$'))
    should_expand_dirname = '$';
  else if (t = mbschr (local_dirname, '`'))	/* XXX */
    should_expand_dirname = '`';

  if (should_expand_dirname && directory_exists (local_dirname))
    should_expand_dirname = 0;

  if (should_expand_dirname)
    {
      new_dirname = savestring (local_dirname);
      /* no error messages, and expand_prompt_string doesn't longjmp so we don't
	 have to worry about restoring this setting. */
      global_nounset = unbound_vars_is_error;
      unbound_vars_is_error = 0;
      wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB);	/* does the right thing */
      unbound_vars_is_error = global_nounset;
      if (wl)
	{
	  free (new_dirname);
	  new_dirname = string_list (wl);
	  /* Tell the completer we actually expanded something and change
	     *dirname only if we expanded to something non-null -- stat
	     behaves unpredictably when passed null or empty strings */
	  if (new_dirname && *new_dirname)
	    {
	      free (local_dirname);	/* XXX */
	      local_dirname = *dirname = new_dirname;
	      return_value = STREQ (local_dirname, *dirname) == 0;
	    }
	  else
	    free (new_dirname);
	  dispose_words (wl);
	}
      else
	free (new_dirname);
    }

  /* This is very similar to the code in bash_directory_completion_hook below,
     but without spelling correction and not worrying about whether or not
     we change relative pathnames. */
  if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
    {
      char *temp1, *temp2;

      t = get_working_directory ("symlink-hook");
      temp1 = make_absolute (local_dirname, t);
      free (t);
      temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);

      /* If we can't canonicalize, bail. */
      if (temp2 == 0)
	{
	  free (temp1);
	  return return_value;
	}

      free (local_dirname);
      *dirname = temp2;
      free (temp1);
    }

  return (return_value);
}


static int dissect_h225_SEQUENCE_SIZE_1_512_OF_EnumeratedParameter ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_sequence_of ( tvb , offset , actx , tree , hf_index , ett_h225_SEQUENCE_SIZE_1_512_OF_EnumeratedParameter , SEQUENCE_SIZE_1_512_OF_EnumeratedParameter_sequence_of , 1 , 512 , FALSE ) ;
 return offset ;
 }


static __inline __uint64_t __uint64_identity ( __uint64_t __x ) {
 return __x ;
 }


u32cconv (c, s)
     unsigned long c;
     char *s;
{
  wchar_t wc;
  int n;
#if HAVE_ICONV
  const char *charset;
  char obuf[25], *optr;
  size_t obytesleft;
  const char *iptr;
  size_t sn;
#endif

  wc = c;

#if __STDC_ISO_10646__
  if (sizeof (wchar_t) == 4)
    {
      n = wctomb (s, wc);
      return n;
    }
#endif

#if HAVE_NL_LANGINFO
  codeset = nl_langinfo (CODESET);
  if (STREQ (codeset, "UTF-8"))
    {
      n = u32toutf8 (c, s);
      return n;
    }
#endif

#if HAVE_ICONV
  /* this is mostly from coreutils-8.5/lib/unicodeio.c */
  if (u32init == 0)
    {
#  if HAVE_LOCALE_CHARSET
      charset = locale_charset ();	/* XXX - fix later */
#  else
      charset = stub_charset ();
#  endif
      if (STREQ (charset, "UTF-8"))
	utf8locale = 1;
      else
	{
	  localconv = iconv_open (charset, "UTF-8");
	  if (localconv == (iconv_t)-1)
	    localconv = iconv_open (charset, "ASCII");
	}
      u32init = 1;
    }

  if (utf8locale)
    {
      n = u32toutf8 (c, s);
      return n;
    }

  if (localconv == (iconv_t)-1)
    {
      n = u32tochar (wc, s);
      return n;
    }

  n = u32toutf8 (c, s);

  optr = obuf;
  obytesleft = sizeof (obuf);
  iptr = s;
  sn = n;

  iconv (localconv, NULL, NULL, NULL, NULL);

  if (iconv (localconv, (ICONV_CONST char **)&iptr, &sn, &optr, &obytesleft) == (size_t)-1)
    return n;	/* You get utf-8 if iconv fails */

  *optr = '\0';

  /* number of chars to be copied is optr - obuf if we want to do bounds
     checking */
  strcpy (s, obuf);
  return (optr - obuf);
#endif

  n = u32tochar (wc, s);	/* fallback */
  return n;
}


void printEachBackward ( UBreakIterator * boundary , UChar * str ) {
 int32_t start ;
 int32_t end = ubrk_last ( boundary ) ;
 for ( start = ubrk_previous ( boundary ) ;
 start != UBRK_DONE ;
 end = start , start = ubrk_previous ( boundary ) ) {
 printTextRange ( str , start , end ) ;
 }
 }


void rand_fork(void)
{
    rand_fork_count++;
}


static int dissect_h225_H245TransportAddress ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 # line 556 "./asn1/h225/h225.cnf" h225_packet_info * h225_pi ;
 ipv4_address = 0 ;
 ipv6_address = ipv6_address_zeros ;
 ip_port = 0 ;
 offset = dissect_per_choice ( tvb , offset , actx , tree , hf_index , ett_h225_H245TransportAddress , H245TransportAddress_choice , NULL ) ;
 # line 564 "./asn1/h225/h225.cnf" h225_pi = ( h225_packet_info * ) p_get_proto_data ( wmem_packet_scope ( ) , actx -> pinfo , proto_h225 , 0 ) ;
 if ( h225_pi ) {
 h225_pi -> is_h245 = TRUE ;
 h225_pi -> h245_address = ipv4_address ;
 h225_pi -> h245_port = ip_port ;
 }
 if ( ! actx -> pinfo -> fd -> flags . visited && h245_handle && ip_port != 0 ) {
 address src_addr ;
 conversation_t * conv = NULL ;
 if ( ipv4_address != 0 ) {
 set_address ( & src_addr , AT_IPv4 , 4 , & ipv4_address ) ;
 }
 else if ( memcmp ( ipv6_address . bytes , ipv6_address_zeros . bytes , sizeof ( ipv6_address . bytes ) ) != 0 ) {
 set_address ( & src_addr , AT_IPv6 , 16 , ipv6_address . bytes ) ;
 }
 else {
 return offset ;
 }
 conv = find_conversation ( actx -> pinfo -> num , & src_addr , & src_addr , PT_TCP , ip_port , ip_port , NO_ADDR_B | NO_PORT_B ) ;
 if ( ! conv ) {
 conv = conversation_new ( actx -> pinfo -> num , & src_addr , & src_addr , PT_TCP , ip_port , ip_port , NO_ADDR2 | NO_PORT2 ) ;
 conversation_set_dissector ( conv , h245_handle ) ;
 }
 }
 return offset ;
 }


static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
                                          CMS_RecipientInfo *ri)
{
    CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
    EVP_PKEY *pkey = ktri->pkey;
    unsigned char *ek = NULL;
    size_t eklen;
    int ret = 0;
    CMS_EncryptedContentInfo *ec;
    ec = cms->d.envelopedData->encryptedContentInfo;

    if (ktri->pkey == NULL) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
        return 0;
    }

    ktri->pctx = EVP_PKEY_CTX_new(pkey, NULL);
    if (ktri->pctx == NULL)
        return 0;

    if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
        goto err;

    if (!cms_env_asn1_ctrl(ri, 1))
        goto err;

    if (EVP_PKEY_CTX_ctrl(ktri->pctx, -1, EVP_PKEY_OP_DECRYPT,
                          EVP_PKEY_CTRL_CMS_DECRYPT, 0, ri) <= 0) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CTRL_ERROR);
        goto err;
    }

    if (EVP_PKEY_decrypt(ktri->pctx, NULL, &eklen,
                         ktri->encryptedKey->data,
                         ktri->encryptedKey->length) <= 0)
        goto err;

    ek = OPENSSL_malloc(eklen);

    if (ek == NULL) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    if (EVP_PKEY_decrypt(ktri->pctx, ek, &eklen,
                         ktri->encryptedKey->data,
                         ktri->encryptedKey->length) <= 0) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CMS_LIB);
        goto err;
    }

    ret = 1;

    OPENSSL_clear_free(ec->key, ec->keylen);
    ec->key = ek;
    ec->keylen = eklen;

 err:
    EVP_PKEY_CTX_free(ktri->pctx);
    ktri->pctx = NULL;
    if (!ret)
        OPENSSL_free(ek);

    return ret;
}


static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
                                          CMS_RecipientInfo *ri)
{
    CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
    EVP_PKEY *pkey = ktri->pkey;
    unsigned char *ek = NULL;
    size_t eklen;
    int ret = 0;
    CMS_EncryptedContentInfo *ec;
    ec = cms->d.envelopedData->encryptedContentInfo;

    if (ktri->pkey == NULL) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
        return 0;
    }

    ktri->pctx = EVP_PKEY_CTX_new(pkey, NULL);
    if (!ktri->pctx)
        return 0;

    if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
        goto err;

    if (!cms_env_asn1_ctrl(ri, 1))
        goto err;

    if (EVP_PKEY_CTX_ctrl(ktri->pctx, -1, EVP_PKEY_OP_DECRYPT,
                          EVP_PKEY_CTRL_CMS_DECRYPT, 0, ri) <= 0) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CTRL_ERROR);
        goto err;
    }

    if (EVP_PKEY_decrypt(ktri->pctx, NULL, &eklen,
                         ktri->encryptedKey->data,
                         ktri->encryptedKey->length) <= 0)
        goto err;

    ek = OPENSSL_malloc(eklen);

    if (ek == NULL) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, ERR_R_MALLOC_FAILURE);
        goto err;
    }

    if (EVP_PKEY_decrypt(ktri->pctx, ek, &eklen,
                         ktri->encryptedKey->data,
                         ktri->encryptedKey->length) <= 0) {
        CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CMS_LIB);
        goto err;
    }

    ret = 1;

    if (ec->key) {
        OPENSSL_cleanse(ec->key, ec->keylen);
        OPENSSL_free(ec->key);
    }

    ec->key = ek;
    ec->keylen = eklen;

 err:
    if (ktri->pctx) {
        EVP_PKEY_CTX_free(ktri->pctx);
        ktri->pctx = NULL;
    }
    if (!ret && ek)
        OPENSSL_free(ek);

    return ret;
}


void vp9_save_layer_context ( VP9_COMP * const cpi ) {
 const VP9EncoderConfig * const oxcf = & cpi -> oxcf ;
 LAYER_CONTEXT * const lc = get_layer_context ( cpi ) ;
 lc -> rc = cpi -> rc ;
 lc -> twopass = cpi -> twopass ;
 lc -> target_bandwidth = ( int ) oxcf -> target_bandwidth ;
 lc -> alt_ref_source = cpi -> alt_ref_source ;
 }


int ssh_scp_push_directory(ssh_scp scp, const char *dirname, int mode){
  char buffer[1024];
  int r;
  uint8_t code;
  char *dir;
  char *perms;
  if(scp==NULL)
      return SSH_ERROR;
  if(scp->state != SSH_SCP_WRITE_INITED){
    ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_push_directory called under invalid state");
    return SSH_ERROR;
  }
  dir=ssh_basename(dirname);
  perms=ssh_scp_string_mode(mode);
  snprintf(buffer, sizeof(buffer), "D%s 0 %s\n", perms, dir);
  SAFE_FREE(dir);
  SAFE_FREE(perms);
  r=ssh_channel_write(scp->channel,buffer,strlen(buffer));
  if(r==SSH_ERROR){
    scp->state=SSH_SCP_ERROR;
    return SSH_ERROR;
  }
  r=ssh_channel_read(scp->channel,&code,1,0);
  if(r<=0){
    ssh_set_error(scp->session,SSH_FATAL, "Error reading status code: %s",ssh_get_error(scp->session));
    scp->state=SSH_SCP_ERROR;
    return SSH_ERROR;
  }
  if(code != 0){
    ssh_set_error(scp->session,SSH_FATAL, "scp status code %ud not valid", code);
    scp->state=SSH_SCP_ERROR;
    return SSH_ERROR;
  }
  return SSH_OK;
}


static int rv30_decode_intra_types ( RV34DecContext * r , GetBitContext * gb , int8_t * dst ) {
 int i , j , k ;
 for ( i = 0 ;
 i < 4 ;
 i ++ , dst += r -> intra_types_stride - 4 ) {
 for ( j = 0 ;
 j < 4 ;
 j += 2 ) {
 unsigned code = svq3_get_ue_golomb ( gb ) << 1 ;
 if ( code >= 81 * 2 ) {
 av_log ( r -> s . avctx , AV_LOG_ERROR , "Incorrect intra prediction code\n" ) ;
 return - 1 ;
 }
 for ( k = 0 ;
 k < 2 ;
 k ++ ) {
 int A = dst [ - r -> intra_types_stride ] + 1 ;
 int B = dst [ - 1 ] + 1 ;
 * dst ++ = rv30_itype_from_context [ A * 90 + B * 9 + rv30_itype_code [ code + k ] ] ;
 if ( dst [ - 1 ] == 9 ) {
 av_log ( r -> s . avctx , AV_LOG_ERROR , "Incorrect intra prediction mode\n" ) ;
 return - 1 ;
 }
 }
 }
 }
 return 0 ;
 }


void ssh_scp_free(ssh_scp scp)
{
  if(scp==NULL)
      return;
  if(scp->state != SSH_SCP_NEW)
    ssh_scp_close(scp);
  if(scp->channel)
    ssh_channel_free(scp->channel);
  SAFE_FREE(scp->location);
  SAFE_FREE(scp->request_name);
  SAFE_FREE(scp->warning);
  SAFE_FREE(scp);
}


int hmp_pcie_aer_inject_error(Monitor *mon, const QDict *qdict, QObject **ret_data) { const char *id = qdict_get_str(qdict, "id"); const char *error_name; uint32_t error_status; bool correctable; PCIDevice *dev; PCIEAERErr err; int ret; ret = pci_qdev_find_device(id, &dev); if (ret < 0) { monitor_printf(mon, "id or pci device path is invalid or device not " "found. %s\n", id); return ret; } if (!pci_is_express(dev)) { monitor_printf(mon, "the device doesn't support pci express. %s\n", id); return -ENOSYS; } error_name = qdict_get_str(qdict, "error_status"); if (pcie_aer_parse_error_string(error_name, &error_status, &correctable)) { char *e = NULL; error_status = strtoul(error_name, &e, 0); correctable = qdict_get_try_bool(qdict, "correctable", 0); if (!e || *e != '\0') { monitor_printf(mon, "invalid error status value. \"%s\"", error_name); return -EINVAL; } } err.status = error_status; err.source_id = (pci_bus_num(dev->bus) << 8) | dev->devfn; err.flags = 0; if (correctable) { err.flags |= PCIE_AER_ERR_IS_CORRECTABLE; } if (qdict_get_try_bool(qdict, "advisory_non_fatal", 0)) { err.flags |= PCIE_AER_ERR_MAYBE_ADVISORY; } if (qdict_haskey(qdict, "header0")) { err.flags |= PCIE_AER_ERR_HEADER_VALID; } if (qdict_haskey(qdict, "prefix0")) { err.flags |= PCIE_AER_ERR_TLP_PREFIX_PRESENT; } err.header[0] = qdict_get_try_int(qdict, "header0", 0); err.header[1] = qdict_get_try_int(qdict, "header1", 0); err.header[2] = qdict_get_try_int(qdict, "header2", 0); err.header[3] = qdict_get_try_int(qdict, "header3", 0); err.prefix[0] = qdict_get_try_int(qdict, "prefix0", 0); err.prefix[1] = qdict_get_try_int(qdict, "prefix1", 0); err.prefix[2] = qdict_get_try_int(qdict, "prefix2", 0); err.prefix[3] = qdict_get_try_int(qdict, "prefix3", 0); ret = pcie_aer_inject_error(dev, &err); *ret_data = qobject_from_jsonf("{'id': %s, " "'root_bus': %s, 'bus': %d, 'devfn': %d, " "'ret': %d}", id, pci_root_bus_path(dev), pci_bus_num(dev->bus), dev->devfn, ret); assert(*ret_data); return 0; }


int ssh_scp_push_file64(ssh_scp scp, const char *filename, uint64_t size,
                        int mode)
{
    char buffer[1024] = {0};
    int rc;
    char *file = NULL;
    char *perms = NULL;
    uint8_t code;

    if (scp == NULL) {
        return SSH_ERROR;
    }

    if (scp->state != SSH_SCP_WRITE_INITED) {
        ssh_set_error(scp->session, SSH_FATAL,
                      "ssh_scp_push_file called under invalid state");
        return SSH_ERROR;
    }

    file = ssh_basename(filename);
    perms = ssh_scp_string_mode(mode);
    SSH_LOG(SSH_LOG_PROTOCOL,
            "SCP pushing file %s, size %" PRIu64 " with permissions '%s'",
            file, size, perms);
    snprintf(buffer, sizeof(buffer), "C%s %" PRIu64 " %s\n", perms, size, file);
    SAFE_FREE(file);
    SAFE_FREE(perms);

    rc = ssh_channel_write(scp->channel, buffer, strlen(buffer));
    if (rc == SSH_ERROR) {
        scp->state = SSH_SCP_ERROR;
        return SSH_ERROR;
    }

    rc = ssh_channel_read(scp->channel, &code, 1, 0);
    if (rc <= 0) {
        ssh_set_error(scp->session, SSH_FATAL,
                      "Error reading status code: %s",
                      ssh_get_error(scp->session));
        scp->state = SSH_SCP_ERROR;
        return SSH_ERROR;
    }

    if (code != 0) {
        ssh_set_error(scp->session, SSH_FATAL,
                      "scp status code %ud not valid", code);
        scp->state = SSH_SCP_ERROR;
        return SSH_ERROR;
    }

    scp->filelen = size;
    scp->processed = 0;
    scp->state = SSH_SCP_WRITE_WRITING;

    return SSH_OK;
}


avs_decode_frame(AVCodecContext * avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; const uint8_t *buf_end = avpkt->data + avpkt->size; int buf_size = avpkt->size; AvsContext *const avs = avctx->priv_data; AVFrame *picture = data; AVFrame *const p = &avs->picture; const uint8_t *table, *vect; uint8_t *out; int i, j, x, y, stride, vect_w = 3, vect_h = 3; AvsVideoSubType sub_type; AvsBlockType type; GetBitContext change_map; if (avctx->reget_buffer(avctx, p)) { av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n"); return -1; } p->reference = 3; p->pict_type = AV_PICTURE_TYPE_P; p->key_frame = 0; out = avs->picture.data[0]; stride = avs->picture.linesize[0]; if (buf_end - buf < 4) return AVERROR_INVALIDDATA; sub_type = buf[0]; type = buf[1]; buf += 4; if (type == AVS_PALETTE) { int first, last; uint32_t *pal = (uint32_t *) avs->picture.data[1]; first = AV_RL16(buf); last = first + AV_RL16(buf + 2); if (first >= 256 || last > 256 || buf_end - buf < 4 + 4 + 3 * (last - first)) return AVERROR_INVALIDDATA; buf += 4; for (i=first; i<last; i++, buf+=3) { pal[i] = (buf[0] << 18) | (buf[1] << 10) | (buf[2] << 2); pal[i] |= 0xFFU << 24 | (pal[i] >> 6) & 0x30303; } sub_type = buf[0]; type = buf[1]; buf += 4; } if (type != AVS_VIDEO) return -1; switch (sub_type) { case AVS_I_FRAME: p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; case AVS_P_FRAME_3X3: vect_w = 3; vect_h = 3; break; case AVS_P_FRAME_2X2: vect_w = 2; vect_h = 2; break; case AVS_P_FRAME_2X3: vect_w = 2; vect_h = 3; break; default: return -1; } if (buf_end - buf < 256 * vect_w * vect_h) return AVERROR_INVALIDDATA; table = buf + (256 * vect_w * vect_h); if (sub_type != AVS_I_FRAME) { int map_size = ((318 / vect_w + 7) / 8) * (198 / vect_h); if (buf_end - table < map_size) return AVERROR_INVALIDDATA; init_get_bits(&change_map, table, map_size * 8); table += map_size; } for (y=0; y<198; y+=vect_h) { for (x=0; x<318; x+=vect_w) { if (sub_type == AVS_I_FRAME || get_bits1(&change_map)) { if (buf_end - table < 1) return AVERROR_INVALIDDATA; vect = &buf[*table++ * (vect_w * vect_h)]; for (j=0; j<vect_w; j++) { out[(y + 0) * stride + x + j] = vect[(0 * vect_w) + j]; out[(y + 1) * stride + x + j] = vect[(1 * vect_w) + j]; if (vect_h == 3) out[(y + 2) * stride + x + j] = vect[(2 * vect_w) + j]; } } } if (sub_type != AVS_I_FRAME) align_get_bits(&change_map); } *picture = avs->picture; *got_frame = 1; return buf_size; }


static void xilinx_axidma_init(Object *obj) { XilinxAXIDMA *s = XILINX_AXI_DMA(obj); SysBusDevice *sbd = SYS_BUS_DEVICE(obj); Error *errp = NULL; object_property_add_link(obj, "axistream-connected", TYPE_STREAM_SLAVE, (Object **) &s->tx_dev, NULL); object_initialize(&s->rx_data_dev, TYPE_XILINX_AXI_DMA_DATA_STREAM); object_property_add_child(OBJECT(s), "axistream-connected-target", (Object *)&s->rx_data_dev, &errp); assert_no_error(errp); sysbus_init_irq(sbd, &s->streams[0].irq); sysbus_init_irq(sbd, &s->streams[1].irq); memory_region_init_io(&s->iomem, &axidma_ops, s, "xlnx.axi-dma", R_MAX * 4 * 2); sysbus_init_mmio(sbd, &s->iomem); }


void tlb_fill (target_ulong addr, int is_write, int mmu_idx, void *retaddr) { TranslationBlock *tb; CPUState *saved_env; unsigned long pc; int ret; /* XXX: hack to restore env in all cases, even if not called from generated code */ saved_env = env; env = cpu_single_env; D_LOG("%s pc=%x tpc=%x ra=%x\n", __func__, env->pc, env->debug1, retaddr); ret = cpu_cris_handle_mmu_fault(env, addr, is_write, mmu_idx); if (unlikely(ret)) { if (retaddr) { /* now we have a real cpu fault */ pc = (unsigned long)retaddr; tb = tb_find_pc(pc); if (tb) { /* the PC is inside the translated code. It means that we have a virtual CPU fault */ cpu_restore_state(tb, env, pc); /* Evaluate flags after retranslation. */ helper_top_evaluate_flags(); } } cpu_loop_exit(env); } env = saved_env; }


main( int argc, char *argv[] ) { GMainLoop *loop; GIOChannel *channel_stdin; char *qemu_host; char *qemu_port; VCardEmulOptions *command_line_options = NULL; char *cert_names[MAX_CERTS]; char *emul_args = NULL; int cert_count = 0; int c, sock; if (socket_init() != 0) return 1; while ((c = getopt(argc, argv, "c:e:pd:")) != -1) { switch (c) { case 'c': if (cert_count >= MAX_CERTS) { printf("too many certificates (max = %d)\n", MAX_CERTS); exit(5); } cert_names[cert_count++] = optarg; break; case 'e': emul_args = optarg; break; case 'p': print_usage(); exit(4); break; case 'd': verbose = get_id_from_string(optarg, 1); break; } } if (argc - optind != 2) { print_usage(); exit(4); } if (cert_count > 0) { char *new_args; int len, i; /* if we've given some -c options, we clearly we want do so some * software emulation. add that emulation now. this is NSS Emulator * specific */ if (emul_args == NULL) { emul_args = (char *)"db=\"/etc/pki/nssdb\""; } #define SOFT_STRING ",soft=(,Virtual Reader,CAC,," /* 2 == close paren & null */ len = strlen(emul_args) + strlen(SOFT_STRING) + 2; for (i = 0; i < cert_count; i++) { len += strlen(cert_names[i])+1; /* 1 == comma */ } new_args = g_malloc(len); strcpy(new_args, emul_args); strcat(new_args, SOFT_STRING); for (i = 0; i < cert_count; i++) { strcat(new_args, cert_names[i]); strcat(new_args, ","); } strcat(new_args, ")"); emul_args = new_args; } if (emul_args) { command_line_options = vcard_emul_options(emul_args); } qemu_host = g_strdup(argv[argc - 2]); qemu_port = g_strdup(argv[argc - 1]); sock = connect_to_qemu(qemu_host, qemu_port); if (sock == -1) { fprintf(stderr, "error opening socket, exiting.\n"); exit(5); } socket_to_send = g_byte_array_new(); qemu_mutex_init(&socket_to_send_lock); qemu_mutex_init(&pending_reader_lock); qemu_cond_init(&pending_reader_condition); vcard_emul_init(command_line_options); loop = g_main_loop_new(NULL, true); printf("> "); fflush(stdout); #ifdef _WIN32 channel_stdin = g_io_channel_win32_new_fd(STDIN_FILENO); #else channel_stdin = g_io_channel_unix_new(STDIN_FILENO); #endif g_io_add_watch(channel_stdin, G_IO_IN, do_command, NULL); #ifdef _WIN32 channel_socket = g_io_channel_win32_new_socket(sock); #else channel_socket = g_io_channel_unix_new(sock); #endif g_io_channel_set_encoding(channel_socket, NULL, NULL); /* we buffer ourself for thread safety reasons */ g_io_channel_set_buffered(channel_socket, FALSE); /* Send init message, Host responds (and then we send reader attachments) */ VSCMsgInit init = { .version = htonl(VSCARD_VERSION), .magic = VSCARD_MAGIC, .capabilities = {0} }; send_msg(VSC_Init, 0, &init, sizeof(init)); g_main_loop_run(loop); g_main_loop_unref(loop); g_io_channel_unref(channel_stdin); g_io_channel_unref(channel_socket); g_byte_array_free(socket_to_send, TRUE); closesocket(sock); return 0; }


int tls_choose_sigalg(SSL *s, int fatalerrs)
{
    const SIGALG_LOOKUP *lu = NULL;
    int sig_idx = -1;

    s->s3.tmp.cert = NULL;
    s->s3.tmp.sigalg = NULL;

    if (SSL_IS_TLS13(s)) {
        size_t i;
#ifndef OPENSSL_NO_EC
        int curve = -1;
#endif

        /* Look for a certificate matching shared sigalgs */
        for (i = 0; i < s->shared_sigalgslen; i++) {
            lu = s->shared_sigalgs[i];
            sig_idx = -1;

            /* Skip SHA1, SHA224, DSA and RSA if not PSS */
            if (lu->hash == NID_sha1
                || lu->hash == NID_sha224
                || lu->sig == EVP_PKEY_DSA
                || lu->sig == EVP_PKEY_RSA)
                continue;
            /* Check that we have a cert, and signature_algorithms_cert */
            if (!tls1_lookup_md(lu, NULL) || !has_usable_cert(s, lu, -1))
                continue;
            if (lu->sig == EVP_PKEY_EC) {
#ifndef OPENSSL_NO_EC
                if (curve == -1) {
                    EC_KEY *ec = EVP_PKEY_get0_EC_KEY(s->cert->pkeys[SSL_PKEY_ECC].privatekey);

                    curve = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
                }
                if (lu->curve != NID_undef && curve != lu->curve)
                    continue;
#else
                continue;
#endif
            } else if (lu->sig == EVP_PKEY_RSA_PSS) {
                /* validate that key is large enough for the signature algorithm */
                EVP_PKEY *pkey;

                pkey = s->cert->pkeys[lu->sig_idx].privatekey;
                if (!rsa_pss_check_min_key_size(EVP_PKEY_get0(pkey), lu))
                    continue;
            }
            break;
        }
        if (i == s->shared_sigalgslen) {
            if (!fatalerrs)
                return 1;
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_CHOOSE_SIGALG,
                     SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
            return 0;
        }
    } else {
        /* If ciphersuite doesn't require a cert nothing to do */
        if (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aCERT))
            return 1;
        if (!s->server && !ssl_has_cert(s, s->cert->key - s->cert->pkeys))
                return 1;

        if (SSL_USE_SIGALGS(s)) {
            size_t i;
            if (s->s3.tmp.peer_sigalgs != NULL) {
#ifndef OPENSSL_NO_EC
                int curve;

                /* For Suite B need to match signature algorithm to curve */
                if (tls1_suiteb(s)) {
                    EC_KEY *ec = EVP_PKEY_get0_EC_KEY(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
                    curve = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
                } else {
                    curve = -1;
                }
#endif

                /*
                 * Find highest preference signature algorithm matching
                 * cert type
                 */
                for (i = 0; i < s->shared_sigalgslen; i++) {
                    lu = s->shared_sigalgs[i];

                    if (s->server) {
                        if ((sig_idx = tls12_get_cert_sigalg_idx(s, lu)) == -1)
                            continue;
                    } else {
                        int cc_idx = s->cert->key - s->cert->pkeys;

                        sig_idx = lu->sig_idx;
                        if (cc_idx != sig_idx)
                            continue;
                    }
                    /* Check that we have a cert, and sig_algs_cert */
                    if (!has_usable_cert(s, lu, sig_idx))
                        continue;
                    if (lu->sig == EVP_PKEY_RSA_PSS) {
                        /* validate that key is large enough for the signature algorithm */
                        EVP_PKEY *pkey = s->cert->pkeys[sig_idx].privatekey;

                        if (!rsa_pss_check_min_key_size(EVP_PKEY_get0(pkey), lu))
                            continue;
                    }
#ifndef OPENSSL_NO_EC
                    if (curve == -1 || lu->curve == curve)
#endif
                        break;
                }
                if (i == s->shared_sigalgslen) {
                    if (!fatalerrs)
                        return 1;
                    SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
                             SSL_F_TLS_CHOOSE_SIGALG,
                             SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
                    return 0;
                }
            } else {
                /*
                 * If we have no sigalg use defaults
                 */
                const uint16_t *sent_sigs;
                size_t sent_sigslen;

                if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
                    if (!fatalerrs)
                        return 1;
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CHOOSE_SIGALG,
                             ERR_R_INTERNAL_ERROR);
                    return 0;
                }

                /* Check signature matches a type we sent */
                sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
                for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
                    if (lu->sigalg == *sent_sigs
                            && has_usable_cert(s, lu, lu->sig_idx))
                        break;
                }
                if (i == sent_sigslen) {
                    if (!fatalerrs)
                        return 1;
                    SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
                             SSL_F_TLS_CHOOSE_SIGALG,
                             SSL_R_WRONG_SIGNATURE_TYPE);
                    return 0;
                }
            }
        } else {
            if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
                if (!fatalerrs)
                    return 1;
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CHOOSE_SIGALG,
                         ERR_R_INTERNAL_ERROR);
                return 0;
            }
        }
    }
    if (sig_idx == -1)
        sig_idx = lu->sig_idx;
    s->s3.tmp.cert = &s->cert->pkeys[sig_idx];
    s->cert->key = s->s3.tmp.cert;
    s->s3.tmp.sigalg = lu;
    return 1;
}


static void U_CALLCONV _SCSUClose ( UConverter * cnv ) {
 if ( cnv -> extraInfo != NULL ) {
 if ( ! cnv -> isExtraLocal ) {
 uprv_free ( cnv -> extraInfo ) ;
 }
 cnv -> extraInfo = NULL ;
 }
 }


void TSHttpTxnUntransformedRespCache ( TSHttpTxn txnp , int on ) {
 sdk_assert ( sdk_sanity_check_txn ( txnp ) == TS_SUCCESS ) ;
 HttpSM * sm = ( HttpSM * ) txnp ;
 sm -> t_state . api_info . cache_untransformed = ( on ? true : false ) ;
 }


const EVP_CIPHER * EVP_aes_128_wrap_pad ( void ) {
 return & aes_128_wrap_pad ;
 }


static av_cold void dcadec_flush(AVCodecContext *avctx) { DCAContext *s = avctx->priv_data; ff_dca_core_flush(&s->core); ff_dca_xll_flush(&s->xll); ff_dca_lbr_flush(&s->lbr); s->core_residual_valid = 0; }


int av_read_play(AVFormatContext *s) { if (s->iformat->read_play) return s->iformat->read_play(s); if (s->pb && s->pb->read_pause) return av_url_read_fpause(s->pb, 0); return AVERROR(ENOSYS); }


static VALUE cState_init_copy ( VALUE obj , VALUE orig ) {
 JSON_Generator_State * objState , * origState ;
 if ( obj == orig ) return obj ;
 GET_STATE_TO ( obj , objState ) ;
 GET_STATE_TO ( orig , origState ) ;
 if ( ! objState ) rb_raise ( rb_eArgError , "unallocated JSON::State" ) ;
 MEMCPY ( objState , origState , JSON_Generator_State , 1 ) ;
 objState -> indent = fstrndup ( origState -> indent , origState -> indent_len ) ;
 objState -> space = fstrndup ( origState -> space , origState -> space_len ) ;
 objState -> space_before = fstrndup ( origState -> space_before , origState -> space_before_len ) ;
 objState -> object_nl = fstrndup ( origState -> object_nl , origState -> object_nl_len ) ;
 objState -> array_nl = fstrndup ( origState -> array_nl , origState -> array_nl_len ) ;
 if ( origState -> array_delim ) objState -> array_delim = fbuffer_dup ( origState -> array_delim ) ;
 if ( origState -> object_delim ) objState -> object_delim = fbuffer_dup ( origState -> object_delim ) ;
 if ( origState -> object_delim2 ) objState -> object_delim2 = fbuffer_dup ( origState -> object_delim2 ) ;
 return obj ;
 }


int gnutls_init(gnutls_session_t * session, unsigned int flags)
{
	int ret;

	FAIL_IF_LIB_ERROR;

	*session = gnutls_calloc(1, sizeof(struct gnutls_session_int));
	if (*session == NULL)
		return GNUTLS_E_MEMORY_ERROR;

	ret = gnutls_mutex_init(&(*session)->internals.post_negotiation_lock);
	if (ret < 0) {
		gnutls_assert();
		gnutls_free(*session);
		return ret;
	}

	ret = gnutls_mutex_init(&(*session)->internals.epoch_lock);
	if (ret < 0) {
		gnutls_assert();
		gnutls_mutex_deinit(&(*session)->internals.post_negotiation_lock);
		gnutls_free(*session);
		return ret;
	}

	ret = _gnutls_epoch_setup_next(*session, 1, NULL);
	if (ret < 0) {
		gnutls_mutex_deinit(&(*session)->internals.post_negotiation_lock);
		gnutls_mutex_deinit(&(*session)->internals.epoch_lock);
		gnutls_free(*session);
		return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
	}
	_gnutls_epoch_bump(*session);

	(*session)->security_parameters.entity =
	    (flags & GNUTLS_SERVER ? GNUTLS_SERVER : GNUTLS_CLIENT);

	/* the default certificate type for TLS */
	(*session)->security_parameters.client_ctype = DEFAULT_CERT_TYPE;
	(*session)->security_parameters.server_ctype = DEFAULT_CERT_TYPE;

	/* Initialize buffers */
	_gnutls_buffer_init(&(*session)->internals.handshake_hash_buffer);
	_gnutls_buffer_init(&(*session)->internals.post_handshake_hash_buffer);
	_gnutls_buffer_init(&(*session)->internals.hb_remote_data);
	_gnutls_buffer_init(&(*session)->internals.hb_local_data);
	_gnutls_buffer_init(&(*session)->internals.record_presend_buffer);
	_gnutls_buffer_init(&(*session)->internals.record_key_update_buffer);
	_gnutls_buffer_init(&(*session)->internals.reauth_buffer);

	_mbuffer_head_init(&(*session)->internals.record_buffer);
	_mbuffer_head_init(&(*session)->internals.record_send_buffer);
	_mbuffer_head_init(&(*session)->internals.record_recv_buffer);
	_mbuffer_head_init(&(*session)->internals.early_data_recv_buffer);
	_gnutls_buffer_init(&(*session)->internals.early_data_presend_buffer);

	_mbuffer_head_init(&(*session)->internals.handshake_send_buffer);
	_gnutls_handshake_recv_buffer_init(*session);

	(*session)->internals.expire_time = DEFAULT_EXPIRE_TIME;

	/* Ticket key rotation - set the default X to 3 times the ticket expire time */
	(*session)->key.totp.last_result = 0;

	gnutls_handshake_set_max_packet_length((*session),
					       MAX_HANDSHAKE_PACKET_SIZE);

	/* set the socket pointers to -1;
	 */
	(*session)->internals.transport_recv_ptr =
	    (gnutls_transport_ptr_t) - 1;
	(*session)->internals.transport_send_ptr =
	    (gnutls_transport_ptr_t) - 1;

	/* set the default maximum record size for TLS
	 */
	(*session)->security_parameters.max_record_recv_size =
	    DEFAULT_MAX_RECORD_SIZE;
	(*session)->security_parameters.max_record_send_size =
	    DEFAULT_MAX_RECORD_SIZE;
	(*session)->security_parameters.max_user_record_recv_size =
	    DEFAULT_MAX_RECORD_SIZE;
	(*session)->security_parameters.max_user_record_send_size =
	    DEFAULT_MAX_RECORD_SIZE;

	/* set the default early data size for TLS
	 */
	if ((*session)->security_parameters.entity == GNUTLS_SERVER) {
		(*session)->security_parameters.max_early_data_size =
			DEFAULT_MAX_EARLY_DATA_SIZE;
	} else {
		(*session)->security_parameters.max_early_data_size =
			UINT32_MAX;
	}

	/* Everything else not initialized here is initialized as NULL
	 * or 0. This is why calloc is used. However, we want to
	 * ensure that certain portions of data are initialized at
	 * runtime before being used. Mark such regions with a
	 * valgrind client request as undefined.
	 */
#ifdef HAVE_VALGRIND_MEMCHECK_H
	if (RUNNING_ON_VALGRIND) {
		if (flags & GNUTLS_CLIENT)
			VALGRIND_MAKE_MEM_UNDEFINED((*session)->security_parameters.client_random,
						    GNUTLS_RANDOM_SIZE);
		if (flags & GNUTLS_SERVER)
			VALGRIND_MAKE_MEM_UNDEFINED((*session)->security_parameters.server_random,
						    GNUTLS_RANDOM_SIZE);
	}
#endif
	handshake_internal_state_clear1(*session);

#ifdef HAVE_WRITEV
#ifdef MSG_NOSIGNAL
	if (flags & GNUTLS_NO_SIGNAL)
		gnutls_transport_set_vec_push_function(*session, system_writev_nosignal);
	else
#endif
		gnutls_transport_set_vec_push_function(*session, system_writev);
#else
	gnutls_transport_set_push_function(*session, system_write);
#endif
	(*session)->internals.pull_timeout_func = gnutls_system_recv_timeout;
	(*session)->internals.pull_func = system_read;
	(*session)->internals.errno_func = system_errno;

	(*session)->internals.saved_username_size = -1;

	/* heartbeat timeouts */
	(*session)->internals.hb_retrans_timeout_ms = 1000;
	(*session)->internals.hb_total_timeout_ms = 60000;

	if (flags & GNUTLS_DATAGRAM) {
		(*session)->internals.dtls.mtu = DTLS_DEFAULT_MTU;
		(*session)->internals.transport = GNUTLS_DGRAM;

		gnutls_dtls_set_timeouts(*session, DTLS_RETRANS_TIMEOUT, 60000);
	} else {
		(*session)->internals.transport = GNUTLS_STREAM;
	}

	/* Enable useful extensions */
	if ((flags & GNUTLS_CLIENT) && !(flags & GNUTLS_NO_EXTENSIONS)) {
#ifdef ENABLE_OCSP
		gnutls_ocsp_status_request_enable_client(*session, NULL, 0,
							 NULL);
#endif
	}

	/* session tickets in server side are enabled by setting a key */
	if (flags & GNUTLS_SERVER)
		flags |= GNUTLS_NO_TICKETS;

	(*session)->internals.flags = flags;

	if (_gnutls_disable_tls13 != 0)
		(*session)->internals.flags |= INT_FLAG_NO_TLS13;

	/* Install the default keylog function */
	gnutls_session_set_keylog_function(*session, _gnutls_nss_keylog_func);

	return 0;
}


display_set_color_format(gx_device_display *ddev, int nFormat)
{
    gx_device * pdev = (gx_device *) ddev;
    gx_device_color_info dci = ddev->color_info;
    int bpc;	/* bits per component */
    int bpp;	/* bits per pixel */
    int maxvalue;
    int align;

    switch (nFormat & DISPLAY_DEPTH_MASK) {
        case DISPLAY_DEPTH_1:
            bpc = 1;
            break;
        case DISPLAY_DEPTH_2:
            bpc = 2;
            break;
        case DISPLAY_DEPTH_4:
            bpc = 4;
            break;
        case DISPLAY_DEPTH_8:
            bpc = 8;
            break;
        case DISPLAY_DEPTH_12:
            bpc = 12;
            break;
        case DISPLAY_DEPTH_16:
            bpc = 16;
            break;
        default:
            return_error(gs_error_rangecheck);
    }
    maxvalue = (1 << bpc) - 1;
    ddev->devn_params.bitspercomponent = bpc;

    switch (ddev->nFormat & DISPLAY_ROW_ALIGN_MASK) {
        case DISPLAY_ROW_ALIGN_DEFAULT:
            align = ARCH_ALIGN_PTR_MOD;
            break;
        case DISPLAY_ROW_ALIGN_4:
            align = 4;
            break;
        case DISPLAY_ROW_ALIGN_8:
            align = 8;
            break;
        case DISPLAY_ROW_ALIGN_16:
            align = 16;
            break;
        case DISPLAY_ROW_ALIGN_32:
            align = 32;
            break;
        case DISPLAY_ROW_ALIGN_64:
            align = 64;
            break;
        default:
            align = 0;	/* not permitted */
    }
    if (align < ARCH_ALIGN_PTR_MOD)
        return_error(gs_error_rangecheck);

    switch (ddev->nFormat & DISPLAY_ALPHA_MASK) {
        case DISPLAY_ALPHA_FIRST:
        case DISPLAY_ALPHA_LAST:
            /* Not implemented and unlikely to ever be implemented
             * because they would interact with linear_and_separable
             */
            return_error(gs_error_rangecheck);
    }

    switch (nFormat & DISPLAY_COLORS_MASK) {
        case DISPLAY_COLORS_NATIVE:
            switch (nFormat & DISPLAY_DEPTH_MASK) {
                case DISPLAY_DEPTH_1:
                    /* 1bit/pixel, black is 1, white is 0 */
                    set_color_info(&dci, DISPLAY_MODEL_GRAY, 1, 1, 1, 0);
                    dci.separable_and_linear = GX_CINFO_SEP_LIN_NONE;
                    set_gray_color_procs(pdev, gx_b_w_gray_encode,
                                                gx_default_b_w_map_color_rgb);
                    break;
                case DISPLAY_DEPTH_4:
                    /* 4bit/pixel VGA color */
                    set_color_info(&dci, DISPLAY_MODEL_RGB, 3, 4, 3, 2);
                    dci.separable_and_linear = GX_CINFO_SEP_LIN_NONE;
                    set_rgb_color_procs(pdev, display_map_rgb_color_device4,
                                                display_map_color_rgb_device4);
                    break;
                case DISPLAY_DEPTH_8:
                    /* 8bit/pixel 96 color palette */
                    set_color_info(&dci, DISPLAY_MODEL_RGBK, 4, 8, 31, 3);
                    dci.separable_and_linear = GX_CINFO_SEP_LIN_NONE;
                    set_rgbk_color_procs(pdev, display_encode_color_device8,
                                                display_decode_color_device8);
                    break;
                case DISPLAY_DEPTH_16:
                    /* Windows 16-bit display */
                    /* Is maxgray = maxcolor = 63 correct? */
                    if ((ddev->nFormat & DISPLAY_555_MASK)
                        == DISPLAY_NATIVE_555)
                        set_color_info(&dci, DISPLAY_MODEL_RGB, 3, 16, 31, 31);
                    else
                        set_color_info(&dci, DISPLAY_MODEL_RGB, 3, 16, 63, 63);
                    set_rgb_color_procs(pdev, display_map_rgb_color_device16,
                                                display_map_color_rgb_device16);
                    break;
                default:
                    return_error(gs_error_rangecheck);
            }
            dci.gray_index = GX_CINFO_COMP_NO_INDEX;
            break;
        case DISPLAY_COLORS_GRAY:
            set_color_info(&dci, DISPLAY_MODEL_GRAY, 1, bpc, maxvalue, 0);
            if (bpc == 1)
                set_gray_color_procs(pdev, gx_default_gray_encode,
                                                gx_default_w_b_map_color_rgb);
            else
                set_gray_color_procs(pdev, gx_default_gray_encode,
                                                gx_default_gray_map_color_rgb);
            break;
        case DISPLAY_COLORS_RGB:
            if ((nFormat & DISPLAY_ALPHA_MASK) == DISPLAY_ALPHA_NONE)
                bpp = bpc * 3;
            else
                bpp = bpc * 4;
            set_color_info(&dci, DISPLAY_MODEL_RGB, 3, bpp, maxvalue, maxvalue);
            if (((nFormat & DISPLAY_DEPTH_MASK) == DISPLAY_DEPTH_8) &&
                ((nFormat & DISPLAY_ALPHA_MASK) == DISPLAY_ALPHA_NONE)) {
                if ((nFormat & DISPLAY_ENDIAN_MASK) == DISPLAY_BIGENDIAN)
                    set_rgb_color_procs(pdev, gx_default_rgb_map_rgb_color,
                                                gx_default_rgb_map_color_rgb);
                else
                    set_rgb_color_procs(pdev, display_map_rgb_color_bgr24,
                                                display_map_color_rgb_bgr24);
            }
            else {
                /* slower flexible functions for alpha/unused component */
                set_rgb_color_procs(pdev, display_map_rgb_color_rgb,
                                                display_map_color_rgb_rgb);
            }
            break;
        case DISPLAY_COLORS_CMYK:
            bpp = bpc * 4;
            set_color_info(&dci, DISPLAY_MODEL_CMYK, 4, bpp, maxvalue, maxvalue);
            if ((nFormat & DISPLAY_ALPHA_MASK) != DISPLAY_ALPHA_NONE)
                return_error(gs_error_rangecheck);
            if ((nFormat & DISPLAY_ENDIAN_MASK) != DISPLAY_BIGENDIAN)
                return_error(gs_error_rangecheck);

            if ((nFormat & DISPLAY_DEPTH_MASK) == DISPLAY_DEPTH_1)
                set_cmyk_color_procs(pdev, cmyk_1bit_map_cmyk_color,
                                                cmyk_1bit_map_color_cmyk);
            else if ((nFormat & DISPLAY_DEPTH_MASK) == DISPLAY_DEPTH_8)
                set_cmyk_color_procs(pdev, cmyk_8bit_map_cmyk_color,
                                                cmyk_8bit_map_color_cmyk);
            else
                return_error(gs_error_rangecheck);
            break;
        case DISPLAY_COLORS_SEPARATION:
            if ((nFormat & DISPLAY_ENDIAN_MASK) != DISPLAY_BIGENDIAN)
                return_error(gs_error_rangecheck);
            bpp = ARCH_SIZEOF_COLOR_INDEX * 8;
            set_color_info(&dci, DISPLAY_MODEL_SEP, bpp/bpc, bpp,
                maxvalue, maxvalue);
            if ((nFormat & DISPLAY_DEPTH_MASK) == DISPLAY_DEPTH_8) {
                ddev->devn_params.bitspercomponent = bpc;
                set_color_procs(pdev,
                    display_separation_encode_color,
                    display_separation_decode_color,
                    display_separation_get_color_mapping_procs,
                    display_separation_get_color_comp_index);
            }
            else
                return_error(gs_error_rangecheck);
            break;
        default:
            return_error(gs_error_rangecheck);
    }

    /* restore old anti_alias info */
    dci.anti_alias = ddev->color_info.anti_alias;
    ddev->color_info = dci;
    check_device_separable(pdev);
    switch (nFormat & DISPLAY_COLORS_MASK) {
        case DISPLAY_COLORS_NATIVE:
            ddev->color_info.gray_index = GX_CINFO_COMP_NO_INDEX;
            if ((nFormat & DISPLAY_DEPTH_MASK) == DISPLAY_DEPTH_1)
                ddev->color_info.gray_index = 0;
            else if ((nFormat & DISPLAY_DEPTH_MASK) == DISPLAY_DEPTH_8)
                ddev->color_info.gray_index = 3;
            break;
        case DISPLAY_COLORS_RGB:
            ddev->color_info.gray_index = GX_CINFO_COMP_NO_INDEX;
            break;
        case DISPLAY_COLORS_GRAY:
            ddev->color_info.gray_index = 0;
            break;
        case DISPLAY_COLORS_CMYK:
            ddev->color_info.gray_index = 3;
            break;
        case DISPLAY_COLORS_SEPARATION:
            ddev->color_info.gray_index = GX_CINFO_COMP_NO_INDEX;
            break;
    }
    ddev->nFormat = nFormat;

    return 0;
}