pdf14_push_transparency_group(pdf14_ctx	*ctx, gs_int_rect *rect, bool isolated,
                              bool knockout, byte alpha, byte shape,
                              gs_blend_mode_t blend_mode, bool idle, uint mask_id,
                              int numcomps, bool cm_back_drop,
                              cmm_profile_t *group_profile,
                              cmm_profile_t *tos_profile, gs_gstate *pgs,
                              gx_device *dev)
{
    pdf14_buf *tos = ctx->stack;
    pdf14_buf *buf, *backdrop;
    bool has_shape, has_tags;

    if_debug1m('v', ctx->memory,
               "[v]pdf14_push_transparency_group, idle = %d\n", idle);

    /* We are going to use the shape in the knockout computation.  If previous
       buffer has a shape or if this is a knockout then we will have a shape here */
    has_shape = tos->has_shape || tos->knockout;
    /* If previous buffer has tags, then add tags here */
    has_tags = tos->has_tags;

    /* If the group is NOT isolated we add in the alpha_g plane.  This enables
       recompositing to be performed ala art_pdf_recomposite_group_8 so that
       the backdrop is only included one time in the computation. */
    /* Order of buffer data is color data, followed by alpha channel, followed by
       shape (if present), then alpha_g (if present), then tags (if present) */
    buf = pdf14_buf_new(rect, has_tags, !isolated, has_shape, idle, numcomps + 1,
                        tos->num_spots, ctx->memory);
    if_debug4m('v', ctx->memory,
               "[v]base buf: %d x %d, %d color channels, %d planes\n",
               buf->rect.q.x, buf->rect.q.y, buf->n_chan, buf->n_planes);
    if (buf == NULL)
        return_error(gs_error_VMerror);
    buf->isolated = isolated;
    buf->knockout = knockout;
    buf->alpha = alpha;
    buf->shape = shape;
    buf->blend_mode = blend_mode;
    buf->mask_id = mask_id;
    buf->mask_stack = ctx->mask_stack; /* Save because the group rendering may
                                          set up another (nested) mask. */
    ctx->mask_stack = NULL; /* Clean the mask field for rendering this group.
                            See pdf14_pop_transparency_group how to handle it. */
    buf->saved = tos;
    ctx->stack = buf;
    if (buf->data == NULL)
        return 0;
    if (idle)
        return 0;
    backdrop = pdf14_find_backdrop_buf(ctx);
    if (backdrop == NULL) {
        memset(buf->data, 0, buf->planestride * (buf->n_chan +
                                                 (buf->has_shape ? 1 : 0) +
                                                 (buf->has_alpha_g ? 1 : 0) +
                                                 (buf->has_tags ? 1 : 0)));
    } else {
        if (!buf->knockout) {
            if (!cm_back_drop) {
                pdf14_preserve_backdrop(buf, tos, false);
            } else {
                /* We must have an non-isolated group with a mismatch in color spaces.
                   In this case, we can't just copy the buffer but must CM it */
                pdf14_preserve_backdrop_cm(buf, group_profile, tos, tos_profile,
                                           ctx->memory, pgs, dev, false);
            }
        }
    }

    /* If knockout, we have to maintain a copy of the backdrop in case we are
       drawing nonisolated groups on top of the knockout group. */
    if (buf->knockout) {
        buf->backdrop = gs_alloc_bytes(ctx->memory, buf->planestride * buf->n_chan,
                                        "pdf14_push_transparency_group");
        if (buf->backdrop == NULL) {
            gs_free_object(ctx->memory, buf->backdrop, "pdf14_push_transparency_group");
            return gs_throw(gs_error_VMerror, "Knockout backdrop allocation failed");
        }
        if (buf->isolated) {
            /* We will have opaque backdrop for non-isolated compositing */
            memset(buf->backdrop, 0, buf->planestride * buf->n_chan);
        } else {
            /* Save knockout backdrop for non-isolated compositing */
            /* Note that we need to drill down through the non-isolated groups in our
               stack and make sure that we are not embedded in another knockout group */
            pdf14_buf *check = tos;
            pdf14_buf *child = NULL;  /* Needed so we can get profile */
            cmm_profile_t *prev_knockout_profile;

            while (check != NULL) {
                if (check->isolated)
                    break;
                if (check->knockout) {
                    break;
                }
                child = check;
                check = check->saved;
            }
            /* Here we need to grab a back drop from a knockout parent group and
                potentially worry about color differences. */
            if (check == NULL) {
                prev_knockout_profile = tos_profile;
                check = tos;
            } else {
                if (child == NULL) {
                    prev_knockout_profile = tos_profile;
                } else {
                    prev_knockout_profile  = child->parent_color_info_procs->icc_profile;
                }
            }
            if (!cm_back_drop) {
                pdf14_preserve_backdrop(buf, check, false);
            } else {
                /* We must have an non-isolated group with a mismatch in color spaces.
                   In this case, we can't just copy the buffer but must CM it */
                pdf14_preserve_backdrop_cm(buf, group_profile, check,
                                           prev_knockout_profile, ctx->memory, pgs,
                                           dev, false);
            }
            memcpy(buf->backdrop, buf->data, buf->planestride * buf->n_chan);
        }
#if RAW_DUMP
        /* Dump the current buffer to see what we have. */
        dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y,
                    ctx->stack->rowstride, buf->n_chan,
                    ctx->stack->planestride, ctx->stack->rowstride,
                    "KnockoutBackDrop", buf->backdrop);
        global_index++;
#endif
    } else {
        buf->backdrop = NULL;
    }
#if RAW_DUMP
    /* Dump the current buffer to see what we have. */
    dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y,
                ctx->stack->rowstride, ctx->stack->n_planes,
                ctx->stack->planestride, ctx->stack->rowstride,
                "TransGroupPush", ctx->stack->data);
    global_index++;
#endif
    return 0;
}


 */
static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd,
					struct io_context *ioc,
					struct request_queue *q)
{
	if (ioc) {
		unsigned long flags;
		struct bfq_io_cq *icq;

		spin_lock_irqsave(&q->queue_lock, flags);
		icq = icq_to_bic(ioc_lookup_icq(ioc, q));
		spin_unlock_irqrestore(&q->queue_lock, flags);

		return icq;
	}

	return NULL;


PHP_METHOD(Phar, offsetSet)
{
	char *fname, *cont_str = NULL;
	size_t fname_len, cont_len;
	zval *zresource;
	PHAR_ARCHIVE_OBJECT();

	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
                return;
        }

       if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "pr", &fname, &fname_len, &zresource) == FAILURE
       && zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) {
                return;
        }

	if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname);
		return;
	}

	if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname);
		return;
	}

	if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
		return;
	}

	phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource);
}


static MagickBooleanType IsBoundsCleared(const Image *image1,
  const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception)
{
  register const Quantum
    *p,
    *q;

  register ssize_t
    x;

  ssize_t
    y;

  if (bounds->x < 0)
    return(MagickFalse);
  for (y=0; y < (ssize_t) bounds->height; y++)
  {
    p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1,exception);
    q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1,exception);
    if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
      break;
    for (x=0; x < (ssize_t) bounds->width; x++)
    {
      if ((GetPixelAlpha(image1,p) >= (Quantum) (QuantumRange/2)) &&
          (GetPixelAlpha(image2,q) < (Quantum) (QuantumRange/2)))
        break;
      p+=GetPixelChannels(image1);
      q+=GetPixelChannels(image2);
    }
    if (x < (ssize_t) bounds->width)
      break;
  }
  return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse);
}


 RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy(RTCPeerConnectionHandlerClient* client)
     : m_client(client)
 {
    ASSERT(m_client);
 }


static int __init pppoe_init(void)
{
	int err;

	err = register_pernet_device(&pppoe_net_ops);
	if (err)
		goto out;

	err = proto_register(&pppoe_sk_proto, 0);
	if (err)
		goto out_unregister_net_ops;

	err = register_pppox_proto(PX_PROTO_OE, &pppoe_proto);
	if (err)
		goto out_unregister_pppoe_proto;

	dev_add_pack(&pppoes_ptype);
	dev_add_pack(&pppoed_ptype);
	register_netdevice_notifier(&pppoe_notifier);

	return 0;

out_unregister_pppoe_proto:
	proto_unregister(&pppoe_sk_proto);
out_unregister_net_ops:
	unregister_pernet_device(&pppoe_net_ops);
out:
	return err;
}


GF_Err pssh_box_write(GF_Box *s, GF_BitStream *bs)
{
	GF_Err e;
	GF_ProtectionSystemHeaderBox *ptr = (GF_ProtectionSystemHeaderBox *) s;
	if (!s) return GF_BAD_PARAM;
	e = gf_isom_full_box_write(s, bs);
	if (e) return e;

	gf_bs_write_data(bs, (char *) ptr->SystemID, 16);
	if (ptr->version > 0) {
		u32 i;
		gf_bs_write_u32(bs, ptr->KID_count);
		for (i=0; i<ptr->KID_count; i++)
			gf_bs_write_data(bs, (char *) ptr->KIDs[i], 16);
	}
	if (ptr->private_data) {
		gf_bs_write_u32(bs, ptr->private_data_size);
		gf_bs_write_data(bs, (char *) ptr->private_data, ptr->private_data_size);
	} else
		gf_bs_write_u32(bs, 0);
	return GF_OK;
}


static int cg_opendir(const char *path, struct fuse_file_info *fi)
{
	struct fuse_context *fc = fuse_get_context();
	const char *cgroup;
	struct file_info *dir_info;
	char *controller = NULL;

	if (!fc)
		return -EIO;

	if (strcmp(path, "/cgroup") == 0) {
		cgroup = NULL;
		controller = NULL;
	} else {
		// return list of keys for the controller, and list of child cgroups
		controller = pick_controller_from_path(fc, path);
		if (!controller)
			return -EIO;

		cgroup = find_cgroup_in_path(path);
		if (!cgroup) {
			/* this is just /cgroup/controller, return its contents */
			cgroup = "/";
		}
	}

	if (cgroup) {
		if (!caller_may_see_dir(fc->pid, controller, cgroup))
			return -ENOENT;
		if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY))
			return -EACCES;
	}

	/* we'll free this at cg_releasedir */
	dir_info = malloc(sizeof(*dir_info));
	if (!dir_info)
		return -ENOMEM;
	dir_info->controller = must_copy_string(controller);
	dir_info->cgroup = must_copy_string(cgroup);
	dir_info->type = LXC_TYPE_CGDIR;
	dir_info->buf = NULL;
	dir_info->file = NULL;
	dir_info->buflen = 0;

	fi->fh = (unsigned long)dir_info;
	return 0;
}


void scsi_req_dequeue(SCSIRequest *req)

{

    trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);

    if (req->enqueued) {

        QTAILQ_REMOVE(&req->dev->requests, req, next);

        req->enqueued = false;

        scsi_req_unref(req);

    }

}


static void add_codec(FFServerStream *stream, AVCodecContext *av)

{

    AVStream *st;

    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))

        return;

    /* compute default parameters */

    switch(av->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->sample_rate == 0)

            av->sample_rate = 22050;

        if (av->channels == 0)

            av->channels = 1;

        break;

    case AVMEDIA_TYPE_VIDEO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->time_base.num == 0){

            av->time_base.den = 5;

            av->time_base.num = 1;

        }

        if (av->width == 0 || av->height == 0) {

            av->width = 160;

            av->height = 128;

        }

        /* Bitrate tolerance is less for streaming */

        if (av->bit_rate_tolerance == 0)

            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,

                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);

        if (av->qmin == 0)

            av->qmin = 3;

        if (av->qmax == 0)

            av->qmax = 31;

        if (av->max_qdiff == 0)

            av->max_qdiff = 3;

        av->qcompress = 0.5;

        av->qblur = 0.5;

        if (!av->nsse_weight)

            av->nsse_weight = 8;

        av->frame_skip_cmp = FF_CMP_DCTMAX;

        if (!av->me_method)

            av->me_method = ME_EPZS;

        av->rc_buffer_aggressivity = 1.0;

        if (!av->rc_eq)

            av->rc_eq = av_strdup("tex^qComp");

        if (!av->i_quant_factor)

            av->i_quant_factor = -0.8;

        if (!av->b_quant_factor)

            av->b_quant_factor = 1.25;

        if (!av->b_quant_offset)

            av->b_quant_offset = 1.25;

        if (!av->rc_max_rate)

            av->rc_max_rate = av->bit_rate * 2;

        if (av->rc_max_rate && !av->rc_buffer_size) {

            av->rc_buffer_size = av->rc_max_rate;

        }

        break;

    default:

        abort();

    }

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return;

    st->codec = avcodec_alloc_context3(NULL);

    stream->streams[stream->nb_streams++] = st;

    memcpy(st->codec, av, sizeof(AVCodecContext));

}


static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas) {
    char *p;
    if (!settings.inline_ascii_response) {
        *suffix = ' ';
        p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), suffix+1);
        *p = ' ';
        p = itoa_u32(it->nbytes-2, p+1);
    } else {
        p = suffix;
    }
    if (return_cas) {
        *p = ' ';
        p = itoa_u64(ITEM_get_cas(it), p+1);
    }
    *p = '\r';
    *(p+1) = '\n';
    *(p+2) = '\0';
    return (p - suffix) + 2;
}


static u8 GetByte(struct ngiflib_gif * g) {
#ifndef NGIFLIB_NO_FILE
	if(g->mode & NGIFLIB_MODE_FROM_MEM) {
#endif /* NGIFLIB_NO_FILE */
		return *(g->input.bytes++);
#ifndef NGIFLIB_NO_FILE
	} else {
		return (u8)(getc(g->input.file));
	}
#endif /* NGIFLIB_NO_FILE */
}


custom_basename_to_string (char    *format,
                           va_list  va)
{
    GFile *file;
    GFileInfo *info;
    char *name, *basename, *tmp;
    GMount *mount;

    file = va_arg (va, GFile *);

    if ((mount = nautilus_get_mounted_mount_for_root (file)) != NULL)
    {
        name = g_mount_get_name (mount);
        g_object_unref (mount);
    }
    else
    {
        info = g_file_query_info (file,
                                  G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
                                  0,
                                  g_cancellable_get_current (),
                                  NULL);
        name = NULL;
        if (info)
        {
            name = g_strdup (g_file_info_get_display_name (info));
            g_object_unref (info);
        }
    }

    if (name == NULL)
    {
        basename = g_file_get_basename (file);
        if (g_utf8_validate (basename, -1, NULL))
        {
            name = basename;
        }
        else
        {
            name = g_uri_escape_string (basename, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
            g_free (basename);
        }
    }

    /* Some chars can't be put in the markup we use for the dialogs... */
    if (has_invalid_xml_char (name))
    {
        tmp = name;
        name = g_uri_escape_string (name, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
        g_free (tmp);
    }

    /* Finally, if the string is too long, truncate it. */
    if (name != NULL)
    {
        tmp = name;
        name = eel_str_middle_truncate (tmp, MAXIMUM_DISPLAYED_FILE_NAME_LENGTH);
        g_free (tmp);
    }

    return name;
}


static void irq_handler(void *opaque, int irq, int level)

{

    struct xlx_pic *p = opaque;

    if (!(p->regs[R_MER] & 2)) {

        qemu_irq_lower(p->parent_irq);

        return;

    }

    /* edge triggered interrupt */

    if (p->c_kind_of_intr & (1 << irq) && p->regs[R_MER] & 2) {

        p->regs[R_ISR] |= (level << irq);

    }

    p->irq_pin_state &= ~(1 << irq);

    p->irq_pin_state |= level << irq;

    update_irq(p);

}


     BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex)
         : mGraphicBuffer(graphicBuffer),
          mCopyFromOmx(false),
          mCopyToOmx(false),
          mPortIndex(portIndex),
          mBackup(NULL) {
     }


inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,
                            const Dims<N>& check_dims_1,
                            const Dims<N>& check_dims_2) {
  for (int i = 0; i < N; ++i) {
    TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));
  }
  return MatchingFlatSize(dims, check_dims_1, check_dims_2);
}


qcrypto_tls_creds_check_cert_key_purpose(QCryptoTLSCredsX509 *creds,

                                         gnutls_x509_crt_t cert,

                                         const char *certFile,

                                         bool isServer,

                                         Error **errp)

{

    int status;

    size_t i;

    unsigned int purposeCritical;

    unsigned int critical;

    char *buffer = NULL;

    size_t size;

    bool allowClient = false, allowServer = false;

    critical = 0;

    for (i = 0; ; i++) {

        size = 0;

        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer,

                                                     &size, NULL);

        if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {

            /* If there is no data at all, then we must allow

               client/server to pass */

            if (i == 0) {

                allowServer = allowClient = true;

            }

            break;

        }

        if (status != GNUTLS_E_SHORT_MEMORY_BUFFER) {

            error_setg(errp,

                       "Unable to query certificate %s key purpose: %s",

                       certFile, gnutls_strerror(status));

            return -1;

        }

        buffer = g_new0(char, size);

        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer,

                                                     &size, &purposeCritical);

        if (status < 0) {

            trace_qcrypto_tls_creds_x509_check_key_purpose(

                creds, certFile, status, "<none>", purposeCritical);

            g_free(buffer);

            error_setg(errp,

                       "Unable to query certificate %s key purpose: %s",

                       certFile, gnutls_strerror(status));

            return -1;

        }

        trace_qcrypto_tls_creds_x509_check_key_purpose(

            creds, certFile, status, buffer, purposeCritical);

        if (purposeCritical) {

            critical = true;

        }

        if (g_str_equal(buffer, GNUTLS_KP_TLS_WWW_SERVER)) {

            allowServer = true;

        } else if (g_str_equal(buffer, GNUTLS_KP_TLS_WWW_CLIENT)) {

            allowClient = true;

        } else if (g_str_equal(buffer, GNUTLS_KP_ANY)) {

            allowServer = allowClient = true;

        }

        g_free(buffer);

    }

    if (isServer) {

        if (!allowServer) {

            if (critical) {

                error_setg(errp,

                           "Certificate %s purpose does not allow "

                           "use with a TLS server", certFile);

                return -1;

            }

        }

    } else {

        if (!allowClient) {

            if (critical) {

                error_setg(errp,

                           "Certificate %s purpose does not allow use "

                           "with a TLS client", certFile);

                return -1;

            }

        }

    }

    return 0;

}


parse_char_class(Node** np, PToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
  int r, neg, len, fetched, and_start;
  OnigCodePoint v, vs;
  UChar *p;
  Node* node;
  CClassNode *cc, *prev_cc;
  CClassNode work_cc;

  enum CCSTATE state;
  enum CCVALTYPE val_type, in_type;
  int val_israw, in_israw;

  *np = NULL_NODE;
  env->parse_depth++;
  if (env->parse_depth > ParseDepthLimit)
    return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
  prev_cc = (CClassNode* )NULL;
  r = fetch_token_in_cc(tok, src, end, env);
  if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) {
    neg = 1;
    r = fetch_token_in_cc(tok, src, end, env);
  }
  else {
    neg = 0;
  }

  if (r < 0) return r;
  if (r == TK_CC_CLOSE) {
    if (! code_exist_check((OnigCodePoint )']',
                           *src, env->pattern_end, 1, env))
      return ONIGERR_EMPTY_CHAR_CLASS;

    CC_ESC_WARN(env, (UChar* )"]");
    r = tok->type = TK_CHAR;  /* allow []...] */
  }

  *np = node = node_new_cclass();
  CHECK_NULL_RETURN_MEMERR(node);
  cc = CCLASS_(node);

  and_start = 0;
  state = CCS_START;
  p = *src;
  while (r != TK_CC_CLOSE) {
    fetched = 0;
    switch (r) {
    case TK_CHAR:
    any_char_in:
      len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c);
      if (len > 1) {
        in_type = CCV_CODE_POINT;
      }
      else if (len < 0) {
        r = len;
        goto err;
      }
      else {
        /* sb_char: */
        in_type = CCV_SB;
      }
      v = (OnigCodePoint )tok->u.c;
      in_israw = 0;
      goto val_entry2;
      break;

    case TK_RAW_BYTE:
      /* tok->base != 0 : octal or hexadec. */
      if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) {
        int i, j;
        UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
        UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN;
        UChar* psave = p;
        int base = tok->base;

        buf[0] = tok->u.c;
        for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) {
          r = fetch_token_in_cc(tok, &p, end, env);
          if (r < 0) goto err;
          if (r != TK_RAW_BYTE || tok->base != base) {
            fetched = 1;
            break;
          }
          buf[i] = tok->u.c;
        }

        if (i < ONIGENC_MBC_MINLEN(env->enc)) {
          r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
          goto err;
        }

        /* clear buf tail */
        for (j = i; j < ONIGENC_CODE_TO_MBC_MAXLEN; j++) buf[j] = '\0';

        len = enclen(env->enc, buf);
        if (i < len) {
          r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
          goto err;
        }
        else if (i > len) { /* fetch back */
          p = psave;
          for (i = 1; i < len; i++) {
            r = fetch_token_in_cc(tok, &p, end, env);
          }
          fetched = 0;
        }

        if (i == 1) {
          v = (OnigCodePoint )buf[0];
          goto raw_single;
        }
        else {
          v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe);
          in_type = CCV_CODE_POINT;
        }
      }
      else {
        v = (OnigCodePoint )tok->u.c;
      raw_single:
        in_type = CCV_SB;
      }
      in_israw = 1;
      goto val_entry2;
      break;

    case TK_CODE_POINT:
      v = tok->u.code;
      in_israw = 1;
    val_entry:
      len = ONIGENC_CODE_TO_MBCLEN(env->enc, v);
      if (len < 0) {
        r = len;
        goto err;
      }
      in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT);
    val_entry2:
      r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type,
                         &state, env);
      if (r != 0) goto err;
      break;

    case TK_POSIX_BRACKET_OPEN:
      r = parse_posix_bracket(cc, &p, end, env);
      if (r < 0) goto err;
      if (r == 1) {  /* is not POSIX bracket */
        CC_ESC_WARN(env, (UChar* )"[");
        p = tok->backp;
        v = (OnigCodePoint )tok->u.c;
        in_israw = 0;
        goto val_entry;
      }
      goto next_class;
      break;

    case TK_CHAR_TYPE:
      r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env);
      if (r != 0) goto err;

    next_class:
      r = next_state_class(cc, &vs, &val_type, &state, env);
      if (r != 0) goto err;
      break;

    case TK_CHAR_PROPERTY:
      {
        int ctype = fetch_char_property_to_ctype(&p, end, env);
        if (ctype < 0) {
          r = ctype;
          goto err;
        }
        r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env);
        if (r != 0) goto err;
        goto next_class;
      }
      break;

    case TK_CC_RANGE:
      if (state == CCS_VALUE) {
        r = fetch_token_in_cc(tok, &p, end, env);
        if (r < 0) goto err;
        fetched = 1;
        if (r == TK_CC_CLOSE) { /* allow [x-] */
        range_end_val:
          v = (OnigCodePoint )'-';
          in_israw = 0;
          goto val_entry;
        }
        else if (r == TK_CC_AND) {
          CC_ESC_WARN(env, (UChar* )"-");
          goto range_end_val;
        }

        if (val_type == CCV_CLASS) {
          r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS;
          goto err;
        }

        state = CCS_RANGE;
      }
      else if (state == CCS_START) {
        /* [-xa] is allowed */
        v = (OnigCodePoint )tok->u.c;
        in_israw = 0;

        r = fetch_token_in_cc(tok, &p, end, env);
        if (r < 0) goto err;
        fetched = 1;
        /* [--x] or [a&&-x] is warned. */
        if (r == TK_CC_RANGE || and_start != 0)
          CC_ESC_WARN(env, (UChar* )"-");

        goto val_entry;
      }
      else if (state == CCS_RANGE) {
        CC_ESC_WARN(env, (UChar* )"-");
        goto any_char_in;  /* [!--x] is allowed */
      }
      else { /* CCS_COMPLETE */
        r = fetch_token_in_cc(tok, &p, end, env);
        if (r < 0) goto err;
        fetched = 1;
        if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */
        else if (r == TK_CC_AND) {
          CC_ESC_WARN(env, (UChar* )"-");
          goto range_end_val;
        }

        if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) {
          CC_ESC_WARN(env, (UChar* )"-");
          goto range_end_val;   /* [0-9-a] is allowed as [0-9\-a] */
        }
        r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS;
        goto err;
      }
      break;

    case TK_CC_CC_OPEN: /* [ */
      {
        Node *anode;
        CClassNode* acc;

        r = parse_char_class(&anode, tok, &p, end, env);
        if (r != 0) {
          onig_node_free(anode);
          goto cc_open_err;
        }
        acc = CCLASS_(anode);
        r = or_cclass(cc, acc, env->enc);
        onig_node_free(anode);

      cc_open_err:
        if (r != 0) goto err;
      }
      break;

    case TK_CC_AND: /* && */
      {
        if (state == CCS_VALUE) {
          r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type,
                             &val_type, &state, env);
          if (r != 0) goto err;
        }
        /* initialize local variables */
        and_start = 1;
        state = CCS_START;

        if (IS_NOT_NULL(prev_cc)) {
          r = and_cclass(prev_cc, cc, env->enc);
          if (r != 0) goto err;
          bbuf_free(cc->mbuf);
        }
        else {
          prev_cc = cc;
          cc = &work_cc;
        }
        initialize_cclass(cc);
      }
      break;

    case TK_EOT:
      r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS;
      goto err;
      break;
    default:
      r = ONIGERR_PARSER_BUG;
      goto err;
      break;
    }

    if (fetched)
      r = tok->type;
    else {
      r = fetch_token_in_cc(tok, &p, end, env);
      if (r < 0) goto err;
    }
  }

  if (state == CCS_VALUE) {
    r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type,
                       &val_type, &state, env);
    if (r != 0) goto err;
  }

  if (IS_NOT_NULL(prev_cc)) {
    r = and_cclass(prev_cc, cc, env->enc);
    if (r != 0) goto err;
    bbuf_free(cc->mbuf);
    cc = prev_cc;
  }

  if (neg != 0)
    NCCLASS_SET_NOT(cc);
  else
    NCCLASS_CLEAR_NOT(cc);
  if (IS_NCCLASS_NOT(cc) &&
      IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) {
    int is_empty = (IS_NULL(cc->mbuf) ? 1 : 0);
    if (is_empty != 0)
      BITSET_IS_EMPTY(cc->bs, is_empty);

    if (is_empty == 0) {
#define NEWLINE_CODE    0x0a

      if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) {
        if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1)
          BITSET_SET_BIT(cc->bs, NEWLINE_CODE);
        else
          add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE);
      }
    }
  }
  *src = p;
  env->parse_depth--;
  return 0;

 err:
  if (cc != CCLASS_(*np))
    bbuf_free(cc->mbuf);
  return r;
}


static void setup_delta_attr_check ( struct git_attr_check * check ) {
 static struct git_attr * attr_delta ;
 if ( ! attr_delta ) attr_delta = git_attr ( "delta" ) ;
 check [ 0 ] . attr = attr_delta ;
 }


    OVS_REQUIRES(ipf->ipf_lock)
{
    bool duped_frag = ipf_is_frag_duped(ipf_list->frag_list,
        ipf_list->last_inuse_idx, start_data_byte, end_data_byte);
    int last_inuse_idx = ipf_list->last_inuse_idx;

    if (!duped_frag) {
        if (last_inuse_idx < ipf_list->size - 1) {
            /* In the case of dpdk, it would be unfortunate if we had
             * to create a clone fragment outside the dpdk mp due to the
             * mempool size being too limited. We will otherwise need to
             * recommend not setting the mempool number of buffers too low
             * and also clamp the number of fragments. */
            struct ipf_frag *frag = &ipf_list->frag_list[last_inuse_idx + 1];
            frag->pkt = dp_packet_clone(pkt);
            frag->start_data_byte = start_data_byte;
            frag->end_data_byte = end_data_byte;
            ipf_list->last_inuse_idx++;
            atomic_count_inc(&ipf->nfrag);
            ipf_count(ipf, v6, IPF_NFRAGS_ACCEPTED);
            ipf_list_state_transition(ipf, ipf_list, ff, lf, v6);
        } else {
            OVS_NOT_REACHED();
        }
    } else {
        ipf_count(ipf, v6, IPF_NFRAGS_OVERLAP);
        pkt->md.ct_state = CS_INVALID;
        return false;
    }
    return true;
}


 void UpdateContentLengthPrefs(
    int received_content_length, int original_content_length,
    bool with_data_reduction_proxy_enabled, bool via_data_reduction_proxy,
     PrefService* prefs) {
   int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength);
   int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength);
  total_received += received_content_length;
  total_original += original_content_length;
  prefs->SetInt64(prefs::kHttpReceivedContentLength, total_received);
  prefs->SetInt64(prefs::kHttpOriginalContentLength, total_original);

#if defined(OS_ANDROID) || defined(OS_IOS)
  UpdateContentLengthPrefsForDataReductionProxy(
       received_content_length,
       original_content_length,
       with_data_reduction_proxy_enabled,
      via_data_reduction_proxy,
       base::Time::Now(),
       prefs);
 #endif  // defined(OS_ANDROID) || defined(OS_IOS)

}


RenderFrameImpl::CreateWorkerFetchContext() {
  ServiceWorkerNetworkProviderForFrame* provider =
      static_cast<ServiceWorkerNetworkProviderForFrame*>(
          frame_->GetDocumentLoader()->GetServiceWorkerNetworkProvider());
  DCHECK(provider);

  blink::mojom::RendererPreferenceWatcherPtr watcher;
  blink::mojom::RendererPreferenceWatcherRequest watcher_request =
      mojo::MakeRequest(&watcher);
  render_view()->RegisterRendererPreferenceWatcher(std::move(watcher));

  scoped_refptr<WebWorkerFetchContextImpl> worker_fetch_context =
      WebWorkerFetchContextImpl::Create(
          provider->context(), render_view_->renderer_preferences(),
          std::move(watcher_request), GetLoaderFactoryBundle()->Clone(),
          GetLoaderFactoryBundle()->CloneWithoutAppCacheFactory());

  worker_fetch_context->set_ancestor_frame_id(routing_id_);
  worker_fetch_context->set_frame_request_blocker(frame_request_blocker_);
  worker_fetch_context->set_site_for_cookies(
      frame_->GetDocument().SiteForCookies());
  worker_fetch_context->set_top_frame_origin(
      frame_->GetDocument().TopFrameOrigin());
  worker_fetch_context->set_is_secure_context(
      frame_->GetDocument().IsSecureContext());
  worker_fetch_context->set_origin_url(
      GURL(frame_->GetDocument().Url()).GetOrigin());

  for (auto& observer : observers_)
    observer.WillCreateWorkerFetchContext(worker_fetch_context.get());
  return worker_fetch_context;
}


void FileReaderLoader::OnStartLoading(uint64_t total_bytes) {
  total_bytes_ = total_bytes;

  DCHECK(!raw_data_);

  if (read_type_ != kReadByClient) {
    if (total_bytes > std::numeric_limits<unsigned>::max()) {
      Failed(FileErrorCode::kNotReadableErr, FailureType::kTotalBytesTooLarge);
      return;
    }

    raw_data_ = std::make_unique<ArrayBufferBuilder>(total_bytes);
    if (!raw_data_->IsValid()) {
      Failed(FileErrorCode::kNotReadableErr,
             FailureType::kArrayBufferBuilderCreation);
      return;
    }
    raw_data_->SetVariableCapacity(false);
  }

  if (client_)
    client_->DidStartLoading();
}


BOOL subst_param(char *str, int size, char *param, char *value) {
   int len;
   char *p1, *p2, *s, param_enc[256], str2[256];

   strlcpy(param_enc, param, sizeof(param_enc));
   url_slash_encode(param_enc, sizeof(param_enc));

   if (!value[0]) {

      /* remove parameter */
      s = param_in_str(str, param_enc);

      if (s == NULL)
         return FALSE;

      /* remove parameter */
      p1 = s - 1;

      for (p2 = p1 + strlen(param_enc) + 1; *p2 && *p2 != '&'; p2++);
      strlcpy(str2, p2, sizeof(str2));
      strlcpy(p1, str2, size - (p1 - str));

      if (!strchr(str, '?') && strchr(str, '&'))
         *strchr(str, '&') = '?';

      return TRUE;
   }

   if ((p1 = param_in_str(str, param_enc)) == NULL) {
      if (strchr(str, '?'))
         strlcat(str, "&", size);
      else
         strlcat(str, "?", size);

      strlcat(str, param_enc, size);
      strlcat(str, "=", size);
      strlcat(str, value, size);
      return FALSE;
   }

   p1 += strlen(param_enc) + 1;
   for (p2 = p1; *p2 && *p2 != '&'; p2++);
   len = p2 - p1;
   if (len > (int) strlen(value)) {
      /* new value is shorter than old one */
      strlcpy(str2, value, size - (p1 - str));
      strlcpy(str2 + strlen(value), p2, size - (p1 + strlen(value) - str));
      strlcpy(p1, str2, size - (p1 - str));
   } else {
      /* new value is longer than old one */
      s = (char *) xmalloc(size);
      strlcpy(s, p2, size);
      strlcpy(str2, value, size - (p1 - str));
      strlcat(str2, s, size - (p1 + strlen(value) - str));
      strlcpy(p1, str2, size - (p1 - str));
      xfree(s);
   }

   return TRUE;
}


GF_Err maxr_box_read(GF_Box *s, GF_BitStream *bs)
{
	GF_MAXRBox *ptr = (GF_MAXRBox *)s;
	if (ptr == NULL) return GF_BAD_PARAM;
	ISOM_DECREASE_SIZE(ptr, 8);
	ptr->granularity = gf_bs_read_u32(bs);
	ptr->maxDataRate = gf_bs_read_u32(bs);
	return GF_OK;
}


_warc_find_eoh(const char *buf, size_t bsz)
{
	static const char _marker[] = "\r\n\r\n";
	const char *hit = xmemmem(buf, bsz, _marker, sizeof(_marker) - 1U);

	if (hit != NULL) {
		hit += sizeof(_marker) - 1U;
	}
	return hit;
}


static gint handle_message_sasl ( tvbuff_t * tvb , packet_info * pinfo , gint offset , proto_tree * message_tree ) {
 gint return_value = offset ;
 const sasl_cmd * command ;
 command = find_sasl_command ( tvb , offset ) ;
 if ( command ) {
 gint newline_offset = tvb_find_guint8 ( tvb , offset + command -> length , - 1 , '\n' ) + 1 ;
 if ( 0 == newline_offset ) {
 if ( ( guint ) tvb_captured_length_remaining ( tvb , offset ) < MAX_SASL_PACKET_LENGTH && set_pinfo_desegment ( pinfo , offset , DESEGMENT_ONE_MORE_SEGMENT ) ) {
 return_value = offset + command -> length ;
 }
 else {
 return_value = 0 ;
 }
 return return_value ;
 }
 if ( newline_offset > 0 ) {
 gint length = command -> length ;
 col_add_fstr ( pinfo -> cinfo , COL_INFO , "SASL-%s" , command -> text ) ;
 proto_tree_add_item ( message_tree , hf_alljoyn_sasl_command , tvb , offset , length , ENC_ASCII | ENC_NA ) ;
 offset += length ;
 length = newline_offset - offset ;
 proto_tree_add_item ( message_tree , hf_alljoyn_sasl_parameter , tvb , offset , length , ENC_ASCII | ENC_NA ) ;
 return_value = newline_offset ;
 }
 }
 return return_value ;
 }


const char *tty_driver_name(const struct tty_struct *tty)
{
	if (!tty || !tty->driver)
		return "";
	return tty->driver->name;
}


static void sig_channel_joined ( CHANNEL_REC * channel ) {
 if ( settings_get_bool ( "show_names_on_join" ) && ! channel -> session_rejoin ) fe_channels_nicklist ( channel , CHANNEL_NICKLIST_FLAG_ALL ) ;
 }


error_t httpClientParseContentLengthField(HttpClientContext *context,
   const char_t *value)
{
   char_t *p;

   //If a valid Content-Length header field is present without
   //Transfer-Encoding, its decimal value defines the expected message
   //body length in octets (refer to RFC 7230, section 3.3.3)
   if(!context->chunkedEncoding)
   {
      //Retrieve the length of the body
      context->bodyLen = osStrtoul(value, &p, 10);

      //Any parsing error?
      if(*p != '\0')
         return ERROR_INVALID_SYNTAX;
   }

   //Successful processing
   return NO_ERROR;
}


static int proc_releaseinterface ( struct usb_dev_state * ps , void __user * arg ) {
 unsigned int ifnum ;
 int ret ;
 if ( get_user ( ifnum , ( unsigned int __user * ) arg ) ) return - EFAULT ;
 ret = releaseintf ( ps , ifnum ) ;
 if ( ret < 0 ) return ret ;
 destroy_async_on_interface ( ps , ifnum ) ;
 return 0 ;
 }


TfLiteRegistration* Register_SUB() {
#ifdef USE_NEON
  return Register_SUB_NEON_OPT();
#else
  return Register_SUB_GENERIC_OPT();
#endif
}


static int read_private_key(RSA *rsa)
{
	int r;
	sc_path_t path;
	sc_file_t *file;
	const sc_acl_entry_t *e;

	u8 buf[2048], *p = buf;
	size_t bufsize, keysize;

	r = select_app_df();
	if (r)
		return 1;
	sc_format_path("I0012", &path);
	r = sc_select_file(card, &path, &file);
	if (r) {
		fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
		return 2;
	}
 	e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
 	if (e == NULL || e->method == SC_AC_NEVER)
 		return 10;
	bufsize = MIN(file->size, sizeof buf);
 	sc_file_free(file);
 	r = sc_read_binary(card, 0, buf, bufsize, 0);
 	if (r < 0) {
		fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
		return 2;
	}
	bufsize = r;
	do {
		if (bufsize < 4)
			return 3;
		keysize = (p[0] << 8) | p[1];
		if (keysize == 0)
			break;
		if (keysize < 3)
			return 3;
		if (p[2] == opt_key_num)
			break;
		p += keysize;
		bufsize -= keysize;
	} while (1);
	if (keysize == 0) {
		printf("Key number %d not found.\n", opt_key_num);
		return 2;
	}
	return parse_private_key(p, keysize, rsa);
}


xmlSAXParseFile(xmlSAXHandlerPtr sax, const char *filename,
 int recovery) {
 return(xmlSAXParseFileWithData(sax,filename,recovery,NULL));
}


static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

    const int num = get_be32(pb);

    const int den = get_be32(pb);

    AVStream * const st = c->fc->streams[c->fc->nb_streams-1];

    if (den != 0) {

        if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default

            (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))

            av_log(c->fc, AV_LOG_WARNING,

                   "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",

                   st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);

        st->sample_aspect_ratio.num = num;

        st->sample_aspect_ratio.den = den;

    }

    return 0;

}


static int snd_seq_ioctl_pversion(struct snd_seq_client *client, void *arg)
{
	int *pversion = arg;

	*pversion = SNDRV_SEQ_VERSION;
	return 0;
}


static void cit_send_x_00(struct gspca_dev *gspca_dev, unsigned short x)
{
	cit_write_reg(gspca_dev, x,      0x0127);
	cit_write_reg(gspca_dev, 0x0000, 0x0124);
}


static unsigned append_symbol_coins(Coin* coins, const unsigned* frequencies, unsigned numcodes, size_t sum)
{
  unsigned i;
  unsigned j = 0; /*index of present symbols*/
  for(i = 0; i < numcodes; i++)
  {
    if(frequencies[i] != 0) /*only include symbols that are present*/
    {
      coins[j].weight = frequencies[i] / (float)sum;
      uivector_push_back(&coins[j].symbols, i);
      j++;
    }
  }
  return 0;
}


static void gen_nabs(DisasContext *ctx)

{

    int l1 = gen_new_label();

    int l2 = gen_new_label();

    tcg_gen_brcondi_tl(TCG_COND_GT, cpu_gpr[rA(ctx->opcode)], 0, l1);

    tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_neg_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    gen_set_label(l2);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);

}


static void ipv4_link_failure(struct sk_buff *skb)
{
	struct rtable *rt;

	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0);

	rt = skb_rtable(skb);
	if (rt)
		dst_set_expires(&rt->dst, 0);
}


ztoken_continue(i_ctx_t *i_ctx_p)
{
    os_ptr op = osp;
    scanner_state *pstate;

    check_stype(*op, st_scanner_state_dynamic);
    pstate = r_ptr(op, scanner_state);
    return token_continue(i_ctx_p, pstate, false);
}


static void start_unregistering(struct ctl_table_header *p)
{
	/*
	 * if p->used is 0, nobody will ever touch that entry again;
	 * we'll eliminate all paths to it before dropping sysctl_lock
	 */
	if (unlikely(p->used)) {
		struct completion wait;
		init_completion(&wait);
		p->unregistering = &wait;
		spin_unlock(&sysctl_lock);
		wait_for_completion(&wait);
		spin_lock(&sysctl_lock);
	} else {
		/* anything non-NULL; we'll never dereference it */
		p->unregistering = ERR_PTR(-EINVAL);
	}
	/*
	 * do not remove from the list until nobody holds it; walking the
	 * list in do_sysctl() relies on that.
	 */
	erase_header(p);
}


_shift_data_right_pages(struct page **pages, size_t pgto_base,
		size_t pgfrom_base, size_t len)
{
	struct page **pgfrom, **pgto;
	char *vfrom, *vto;
	size_t copy;

	BUG_ON(pgto_base <= pgfrom_base);

	if (!len)
		return;

	pgto_base += len;
	pgfrom_base += len;

	pgto = pages + (pgto_base >> PAGE_SHIFT);
	pgfrom = pages + (pgfrom_base >> PAGE_SHIFT);

	pgto_base &= ~PAGE_MASK;
	pgfrom_base &= ~PAGE_MASK;

	do {
		/* Are any pointers crossing a page boundary? */
		if (pgto_base == 0) {
			pgto_base = PAGE_SIZE;
			pgto--;
		}
		if (pgfrom_base == 0) {
			pgfrom_base = PAGE_SIZE;
			pgfrom--;
		}

		copy = len;
		if (copy > pgto_base)
			copy = pgto_base;
		if (copy > pgfrom_base)
			copy = pgfrom_base;
		pgto_base -= copy;
		pgfrom_base -= copy;

		vto = kmap_atomic(*pgto);
		if (*pgto != *pgfrom) {
			vfrom = kmap_atomic(*pgfrom);
			memcpy(vto + pgto_base, vfrom + pgfrom_base, copy);
			kunmap_atomic(vfrom);
		} else
			memmove(vto + pgto_base, vto + pgfrom_base, copy);
		flush_dcache_page(*pgto);
		kunmap_atomic(vto);

	} while ((len -= copy) != 0);
}


static void req_nonce ( struct recvbuf * rbufp , int restrict_mask ) {
 char buf [ 64 ] ;
 generate_nonce ( rbufp , buf , sizeof ( buf ) ) ;
 ctl_putunqstr ( "nonce" , buf , strlen ( buf ) ) ;
 ctl_flushpkt ( 0 ) ;
 }


static int register_xaction_notifier(struct notifier_block *nb)
{
	return atomic_notifier_chain_register(&xaction_notifier_list, nb);
}


ldbm_back_bind(Slapi_PBlock *pb)
{
    backend *be;
    ldbm_instance *inst;
    ber_tag_t method;
    struct berval *cred;
    struct ldbminfo *li;
    struct backentry *e;
    Slapi_Attr *attr;
    Slapi_Value **bvals;
    entry_address *addr;
    back_txn txn = {NULL};
    int rc = SLAPI_BIND_SUCCESS;
    int result_sent = 0;

    /* get parameters */
    slapi_pblock_get(pb, SLAPI_BACKEND, &be);
    slapi_pblock_get(pb, SLAPI_PLUGIN_PRIVATE, &li);
    slapi_pblock_get(pb, SLAPI_TARGET_ADDRESS, &addr);
    slapi_pblock_get(pb, SLAPI_BIND_METHOD, &method);
    slapi_pblock_get(pb, SLAPI_BIND_CREDENTIALS, &cred);
    slapi_pblock_get(pb, SLAPI_TXN, &txn.back_txn_txn);

    if (!txn.back_txn_txn) {
        dblayer_txn_init(li, &txn);
        slapi_pblock_set(pb, SLAPI_TXN, txn.back_txn_txn);
    }

    inst = (ldbm_instance *)be->be_instance_info;
    if (inst->inst_ref_count) {
        slapi_counter_increment(inst->inst_ref_count);
    } else {
        slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_bind",
                      "instance %s does not exist.\n", inst->inst_name);
        return (SLAPI_BIND_FAIL);
    }

    /* always allow noauth simple binds (front end will send the result) */
    if (method == LDAP_AUTH_SIMPLE && cred->bv_len == 0) {
        rc = SLAPI_BIND_ANONYMOUS;
        goto bail;
    }

    /*
     * find the target entry.  find_entry() takes care of referrals
     *   and sending errors if the entry does not exist.
     */
    if ((e = find_entry(pb, be, addr, &txn, &result_sent)) == NULL) {
        rc = SLAPI_BIND_FAIL;
        /* In the failure case, the result is supposed to be sent in the backend. */
        if (!result_sent) {
            slapi_send_ldap_result(pb, LDAP_INAPPROPRIATE_AUTH, NULL, NULL, 0, NULL);
        }
        goto bail;
    }

    switch (method) {
    case LDAP_AUTH_SIMPLE: {
        Slapi_Value cv;
        if (slapi_entry_attr_find(e->ep_entry, "userpassword", &attr) != 0) {
            slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, "Entry does not have userpassword set");
            slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);
            CACHE_RETURN(&inst->inst_cache, &e);
            rc = SLAPI_BIND_FAIL;
            goto bail;
        }
        bvals = attr_get_present_values(attr);
        slapi_value_init_berval(&cv, cred);
        if (slapi_pw_find_sv(bvals, &cv) != 0) {
            slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, "Invalid credentials");
            slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);
            CACHE_RETURN(&inst->inst_cache, &e);
            value_done(&cv);
            rc = SLAPI_BIND_FAIL;
            goto bail;
        }
        value_done(&cv);
    } break;

    default:
        slapi_send_ldap_result(pb, LDAP_STRONG_AUTH_NOT_SUPPORTED, NULL,
                               "auth method not supported", 0, NULL);
        CACHE_RETURN(&inst->inst_cache, &e);
        rc = SLAPI_BIND_FAIL;
        goto bail;
    }

    CACHE_RETURN(&inst->inst_cache, &e);
bail:
    if (inst->inst_ref_count) {
        slapi_counter_decrement(inst->inst_ref_count);
    }
    /* success:  front end will send result */
    return rc;
}


static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)

{

    if (!buffer->cmd) {

        AVBufferRef *buf = buffer->user_data;

        av_buffer_unref(&buf);

    }

    mmal_buffer_header_release(buffer);

}


static long vnc_client_read_plain(VncState *vs)
{
    int ret;
    VNC_DEBUG("Read plain %p size %zd offset %zd\n",
              vs->input.buffer, vs->input.capacity, vs->input.offset);
    buffer_reserve(&vs->input, 4096);
    ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
    if (!ret)
        return 0;
    vs->input.offset += ret;
    return ret;
}


static bool is_special_wait_psw(CPUState *cs)

{

    /* signal quiesce */

    return cs->kvm_run->psw_addr == 0xfffUL;

}


static void cma_translate_ib(struct sockaddr_ib *sib, struct rdma_dev_addr *dev_addr)
{
	dev_addr->dev_type = ARPHRD_INFINIBAND;
	rdma_addr_set_sgid(dev_addr, (union ib_gid *) &sib->sib_addr);
	ib_addr_set_pkey(dev_addr, ntohs(sib->sib_pkey));
}


static int hidp_session(void *arg)
{
	struct hidp_session *session = arg;
	struct sock *ctrl_sk = session->ctrl_sock->sk;
	struct sock *intr_sk = session->intr_sock->sk;
	struct sk_buff *skb;
	wait_queue_t ctrl_wait, intr_wait;

	BT_DBG("session %p", session);

	__module_get(THIS_MODULE);
	set_user_nice(current, -15);

	init_waitqueue_entry(&ctrl_wait, current);
	init_waitqueue_entry(&intr_wait, current);
	add_wait_queue(sk_sleep(ctrl_sk), &ctrl_wait);
	add_wait_queue(sk_sleep(intr_sk), &intr_wait);
	session->waiting_for_startup = 0;
	wake_up_interruptible(&session->startup_queue);
	set_current_state(TASK_INTERRUPTIBLE);
	while (!atomic_read(&session->terminate)) {
		if (ctrl_sk->sk_state != BT_CONNECTED ||
				intr_sk->sk_state != BT_CONNECTED)
			break;

		while ((skb = skb_dequeue(&intr_sk->sk_receive_queue))) {
			skb_orphan(skb);
			if (!skb_linearize(skb))
				hidp_recv_intr_frame(session, skb);
			else
				kfree_skb(skb);
		}

		hidp_process_intr_transmit(session);

		while ((skb = skb_dequeue(&ctrl_sk->sk_receive_queue))) {
			skb_orphan(skb);
			if (!skb_linearize(skb))
				hidp_recv_ctrl_frame(session, skb);
			else
				kfree_skb(skb);
		}

		hidp_process_ctrl_transmit(session);

		schedule();
		set_current_state(TASK_INTERRUPTIBLE);
	}
	set_current_state(TASK_RUNNING);
	remove_wait_queue(sk_sleep(intr_sk), &intr_wait);
	remove_wait_queue(sk_sleep(ctrl_sk), &ctrl_wait);

	clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags);
	clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
	wake_up_interruptible(&session->report_queue);

	down_write(&hidp_session_sem);

	hidp_del_timer(session);

	if (session->input) {
		input_unregister_device(session->input);
		session->input = NULL;
	}

	if (session->hid) {
		hid_destroy_device(session->hid);
		session->hid = NULL;
	}

	/* Wakeup user-space polling for socket errors */
	session->intr_sock->sk->sk_err = EUNATCH;
	session->ctrl_sock->sk->sk_err = EUNATCH;

	hidp_schedule(session);

	fput(session->intr_sock->file);

	wait_event_timeout(*(sk_sleep(ctrl_sk)),
		(ctrl_sk->sk_state == BT_CLOSED), msecs_to_jiffies(500));

	fput(session->ctrl_sock->file);

	__hidp_unlink_session(session);

	up_write(&hidp_session_sem);

	kfree(session->rd_data);
	kfree(session);
	module_put_and_exit(0);
	return 0;
}


void options_defaults() {
    SERVICE_OPTIONS *service;

    /* initialize globals *before* opening the config file */
    memset(&new_global_options, 0, sizeof(GLOBAL_OPTIONS));
    memset(&new_service_options, 0, sizeof(SERVICE_OPTIONS));
    new_service_options.next=NULL;

    parse_global_option(CMD_SET_DEFAULTS, &new_global_options, NULL, NULL);
    service=&new_service_options;
    parse_service_option(CMD_SET_DEFAULTS, &service, NULL, NULL);
}


decode_OFPAT_RAW15_SET_FIELD(const struct ofp12_action_set_field *oasf,
                             enum ofp_version ofp_version OVS_UNUSED,
                             const struct vl_mff_map *vl_mff_map,
                             uint64_t *tlv_bitmap, struct ofpbuf *ofpacts)
{
    return decode_ofpat_set_field(oasf, true, vl_mff_map, tlv_bitmap, ofpacts);
}


static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
	int err = simple_setattr(dentry, iattr);

	if (!err && (iattr->ia_valid & ATTR_UID)) {
		struct socket *sock = SOCKET_I(d_inode(dentry));

		sock->sk->sk_uid = iattr->ia_uid;
	}

	return err;
}


PyImaging_MapperNew(const char* filename, int readonly)
{
    ImagingMapperObject *mapper;

    if (PyType_Ready(&ImagingMapperType) < 0)
        return NULL;

    mapper = PyObject_New(ImagingMapperObject, &ImagingMapperType);
    if (mapper == NULL)
        return NULL;

    mapper->base = NULL;
    mapper->size = mapper->offset = 0;

#ifdef _WIN32
    mapper->hFile = (HANDLE)-1;
    mapper->hMap  = (HANDLE)-1;

    /* FIXME: currently supports readonly mappings only */
    mapper->hFile = CreateFile(
        filename,
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if (mapper->hFile == (HANDLE)-1) {
        PyErr_SetString(PyExc_IOError, "cannot open file");
        Py_DECREF(mapper);
        return NULL;
    }

    mapper->hMap = CreateFileMapping(
        mapper->hFile, NULL,
        PAGE_READONLY,
        0, 0, NULL);
    if (mapper->hMap == (HANDLE)-1) {
        CloseHandle(mapper->hFile);
        PyErr_SetString(PyExc_IOError, "cannot map file");
        Py_DECREF(mapper);
        return NULL;
    }

    mapper->base = (char*) MapViewOfFile(
        mapper->hMap,
        FILE_MAP_READ,
        0, 0, 0);

    mapper->size = GetFileSize(mapper->hFile, 0);
#endif

    return mapper;
}


static char *sapi_cgi_getenv(char *name, size_t name_len TSRMLS_DC)
{
	return getenv(name);
}


static void load_sb_block(AVFormatContext *s, VividasDemuxContext *viv, unsigned expected_size)
{
    uint32_t size = 0;
    int i;
    AVIOContext *pb = 0;

    if (viv->sb_pb) {
        av_free(viv->sb_pb);
        viv->sb_pb = NULL;
    }

    if (viv->sb_buf)
        av_free(viv->sb_buf);

    viv->sb_buf = read_sb_block(s->pb, &size, &viv->sb_key, expected_size);
    if (!viv->sb_buf) {
        return;
    }

    pb = avio_alloc_context(viv->sb_buf, size, 0, NULL, NULL, NULL, NULL);
    if (!pb)
        return;

    viv->sb_pb = pb;

    avio_r8(pb); //  'S'
    avio_r8(pb); //  'B'
    ffio_read_varlen(pb); //  size
    avio_r8(pb); //  junk
    ffio_read_varlen(pb); // first packet

    viv->n_sb_entries = viv->sb_blocks[viv->current_sb].n_packets;

    for (i = 0; i < viv->n_sb_entries; i++) {
        viv->sb_entries[i].size = ffio_read_varlen(pb);
        viv->sb_entries[i].flag = avio_r8(pb);
    }

    ffio_read_varlen(pb);
    avio_r8(pb);

    viv->current_sb_entry = 0;
}


put_stringbuf (struct stringbuf *sb, const char *text)
{
  size_t n = strlen (text);

  if (sb->out_of_core)
    return;

  if (sb->len + n >= sb->size)
    {
      char *p;

      sb->size += n + 100;
      p = xtryrealloc (sb->buf, sb->size);
      if ( !p)
        {
          sb->out_of_core = 1;
          return;
        }
      sb->buf = p;
    }
  memcpy (sb->buf+sb->len, text, n);
  sb->len += n;
}


void TestingAutomationProvider::GetType(int handle, int* type_as_int) {
  *type_as_int = -1;  // -1 is the error code

  if (browser_tracker_->ContainsHandle(handle)) {
    Browser* browser = browser_tracker_->GetResource(handle);
    *type_as_int = static_cast<int>(browser->type());
  }
}


static void math_error(struct pt_regs *regs, int error_code, int trapnr)
{
	struct task_struct *task = current;
	siginfo_t info;
	unsigned short err;
	char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" :
						"simd exception";

	if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, SIGFPE) == NOTIFY_STOP)
		return;
	conditional_sti(regs);

	if (!user_mode_vm(regs))
	{
		if (!fixup_exception(regs)) {
			task->thread.error_code = error_code;
			task->thread.trap_nr = trapnr;
			die(str, regs, error_code);
		}
		return;
	}

	/*
	 * Save the info for the exception handler and clear the error.
	 */
	save_init_fpu(task);
	task->thread.trap_nr = trapnr;
	task->thread.error_code = error_code;
	info.si_signo = SIGFPE;
	info.si_errno = 0;
	info.si_addr = (void __user *)uprobe_get_trap_addr(regs);
	if (trapnr == X86_TRAP_MF) {
		unsigned short cwd, swd;
		/*
		 * (~cwd & swd) will mask out exceptions that are not set to unmasked
		 * status.  0x3f is the exception bits in these regs, 0x200 is the
		 * C1 reg you need in case of a stack fault, 0x040 is the stack
		 * fault bit.  We should only be taking one exception at a time,
		 * so if this combination doesn't produce any single exception,
		 * then we have a bad program that isn't synchronizing its FPU usage
		 * and it will suffer the consequences since we won't be able to
		 * fully reproduce the context of the exception
		 */
		cwd = get_fpu_cwd(task);
		swd = get_fpu_swd(task);

		err = swd & ~cwd;
	} else {
		/*
		 * The SIMD FPU exceptions are handled a little differently, as there
		 * is only a single status/control register.  Thus, to determine which
		 * unmasked exception was caught we must mask the exception mask bits
		 * at 0x1f80, and then use these to mask the exception bits at 0x3f.
		 */
		unsigned short mxcsr = get_fpu_mxcsr(task);
		err = ~(mxcsr >> 7) & mxcsr;
	}

	if (err & 0x001) {	/* Invalid op */
		/*
		 * swd & 0x240 == 0x040: Stack Underflow
		 * swd & 0x240 == 0x240: Stack Overflow
		 * User must clear the SF bit (0x40) if set
		 */
		info.si_code = FPE_FLTINV;
	} else if (err & 0x004) { /* Divide by Zero */
		info.si_code = FPE_FLTDIV;
	} else if (err & 0x008) { /* Overflow */
		info.si_code = FPE_FLTOVF;
	} else if (err & 0x012) { /* Denormal, Underflow */
		info.si_code = FPE_FLTUND;
	} else if (err & 0x020) { /* Precision */
		info.si_code = FPE_FLTRES;
	} else {
		/*
		 * If we're using IRQ 13, or supposedly even some trap
		 * X86_TRAP_MF implementations, it's possible
		 * we get a spurious trap, which is not an error.
		 */
		return;
	}
	force_sig_info(SIGFPE, &info, task);
}


static void compute_exp_strategy(AC3EncodeContext *s)

{

    int ch, blk, blk1;

    for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {

        uint8_t *exp_strategy = s->exp_strategy[ch];

        uint8_t *exp          = s->blocks[0].exp[ch];

        int exp_diff;

        /* estimate if the exponent variation & decide if they should be

           reused in the next frame */

        exp_strategy[0] = EXP_NEW;

        exp += AC3_MAX_COEFS;

        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {

            if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||

                (ch  > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {

                exp_strategy[blk] = EXP_NEW;

                continue;

            }

            exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);

            exp_strategy[blk] = EXP_REUSE;

            if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))

                exp_strategy[blk] = EXP_NEW;

            else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)

                exp_strategy[blk] = EXP_NEW;

        }

        /* now select the encoding strategy type : if exponents are often

           recoded, we use a coarse encoding */

        blk = 0;

        while (blk < AC3_MAX_BLOCKS) {

            blk1 = blk + 1;

            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)

                blk1++;

            switch (blk1 - blk) {

            case 1:  exp_strategy[blk] = EXP_D45; break;

            case 2:

            case 3:  exp_strategy[blk] = EXP_D25; break;

            default: exp_strategy[blk] = EXP_D15; break;

            }

            blk = blk1;

        }

    }

    if (s->lfe_on) {

        ch = s->lfe_channel;

        s->exp_strategy[ch][0] = EXP_D15;

        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)

            s->exp_strategy[ch][blk] = EXP_REUSE;

    }

}


static CURLcode glob_set ( URLGlob * glob , char * * patternp , size_t * posp , unsigned long * amount , int globindex ) {
 URLPattern * pat ;
 bool done = FALSE ;
 char * buf = glob -> glob_buffer ;
 char * pattern = * patternp ;
 char * opattern = pattern ;
 size_t opos = * posp - 1 ;
 pat = & glob -> pattern [ glob -> size ] ;
 pat -> type = UPTSet ;
 pat -> content . Set . size = 0 ;
 pat -> content . Set . ptr_s = 0 ;
 pat -> content . Set . elements = NULL ;
 pat -> globindex = globindex ;
 while ( ! done ) {
 switch ( * pattern ) {
 case '\0' : return GLOBERROR ( "unmatched brace" , opos , CURLE_URL_MALFORMAT ) ;
 case '{
' : case '[' : return GLOBERROR ( "nested brace" , * posp , CURLE_URL_MALFORMAT ) ;
 case '}
' : if ( opattern == pattern ) return GLOBERROR ( "empty string within braces" , * posp , CURLE_URL_MALFORMAT ) ;
 if ( multiply ( amount , pat -> content . Set . size + 1 ) ) return GLOBERROR ( "range overflow" , 0 , CURLE_URL_MALFORMAT ) ;
 case ',' : * buf = '\0' ;
 if ( pat -> content . Set . elements ) {
 char * * new_arr = realloc ( pat -> content . Set . elements , ( pat -> content . Set . size + 1 ) * sizeof ( char * ) ) ;
 if ( ! new_arr ) return GLOBERROR ( "out of memory" , 0 , CURLE_OUT_OF_MEMORY ) ;
 pat -> content . Set . elements = new_arr ;
 }
 else pat -> content . Set . elements = malloc ( sizeof ( char * ) ) ;
 if ( ! pat -> content . Set . elements ) return GLOBERROR ( "out of memory" , 0 , CURLE_OUT_OF_MEMORY ) ;
 pat -> content . Set . elements [ pat -> content . Set . size ] = strdup ( glob -> glob_buffer ) ;
 if ( ! pat -> content . Set . elements [ pat -> content . Set . size ] ) return GLOBERROR ( "out of memory" , 0 , CURLE_OUT_OF_MEMORY ) ;
 ++ pat -> content . Set . size ;
 if ( * pattern == '}
' ) {
 pattern ++ ;
 done = TRUE ;
 continue ;
 }
 buf = glob -> glob_buffer ;
 ++ pattern ;
 ++ ( * posp ) ;
 break ;
 case ']' : return GLOBERROR ( "unexpected close bracket" , * posp , CURLE_URL_MALFORMAT ) ;
 case '\\' : if ( pattern [ 1 ] ) {
 ++ pattern ;
 ++ ( * posp ) ;
 }
 default : * buf ++ = * pattern ++ ;
 ++ ( * posp ) ;
 }
 }
 * patternp = pattern ;
 return CURLE_OK ;
 }


base::Time SendTabToSelfEntry::GetSharedTime() const {
  return shared_time_;
}


static int nfs4_do_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
{
	struct nfs_server *server = NFS_SERVER(state->inode);
	struct nfs4_exception exception = { };
	int err;

	do {
		err = _nfs4_open_expired(ctx, state);
		switch (err) {
		default:
			goto out;
		case -NFS4ERR_GRACE:
		case -NFS4ERR_DELAY:
			nfs4_handle_exception(server, err, &exception);
			err = 0;
		}
	} while (exception.retry);
out:
	return err;
}


SkColor background_color() const { return background_color_; }


void kvm_free_physmem(struct kvm *kvm)
{
	struct kvm_memslots *slots = kvm->memslots;
	struct kvm_memory_slot *memslot;

	kvm_for_each_memslot(memslot, slots)
		kvm_free_physmem_slot(memslot, NULL);

	kfree(kvm->memslots);
}


static void fast_gray_to_rgb(fz_context *ctx, fz_pixmap *dst, fz_pixmap *src, fz_colorspace *prf, const fz_default_colorspaces *default_cs, const fz_color_params *color_params, int copy_spots)
{
	unsigned char *s = src->samples;
	unsigned char *d = dst->samples;
	size_t w = src->w;
	int h = src->h;
	int sn = src->n;
	int ss = src->s;
	int sa = src->alpha;
	int dn = dst->n;
	int ds = dst->s;
	int da = dst->alpha;
	ptrdiff_t d_line_inc = dst->stride - w * dn;
	ptrdiff_t s_line_inc = src->stride - w * sn;

	/* If copying spots, they must match, and we can never drop alpha (but we can invent it) */
	if ((copy_spots && ss != ds) || (!da && sa))
	{
		assert("This should never happen" == NULL);
		fz_throw(ctx, FZ_ERROR_GENERIC, "Cannot convert between incompatible pixmaps");
	}

	if ((int)w < 0 || h < 0)
		return;

	if (d_line_inc == 0 && s_line_inc == 0)
	{
		w *= h;
		h = 1;
	}

	if (ss == 0 && ds == 0)
	{
		/* Common, no spots case */
		if (da)
		{
			if (sa)
			{
				while (h--)
				{
					size_t ww = w;
					while (ww--)
					{
						d[0] = s[0];
						d[1] = s[0];
						d[2] = s[0];
						d[3] = s[1];
						s += 2;
						d += 4;
					}
					d += d_line_inc;
					s += s_line_inc;
				}
			}
			else
			{
				while (h--)
				{
					size_t ww = w;
					while (ww--)
					{
						d[0] = s[0];
						d[1] = s[0];
						d[2] = s[0];
						d[3] = 255;
						s++;
						d += 4;
					}
					d += d_line_inc;
					s += s_line_inc;
				}
			}
		}
		else
		{
			while (h--)
			{
				size_t ww = w;
				while (ww--)
				{
					d[0] = s[0];
					d[1] = s[0];
					d[2] = s[0];
					s++;
					d += 3;
				}
				d += d_line_inc;
				s += s_line_inc;
			}
		}
	}
	else if (copy_spots)
	{
		/* Slower, spots capable version */
		int i;
		while (h--)
		{
			size_t ww = w;
			while (ww--)
			{
				d[0] = s[0];
				d[1] = s[0];
				d[2] = s[0];
				s += 1;
				d += 3;
				for (i=ss; i > 0; i--)
					*d++ = *s++;
				if (da)
					*d++ = sa ? *s++ : 255;
			}
			d += d_line_inc;
			s += s_line_inc;
		}
	}
	else
	{
		while (h--)
		{
			size_t ww = w;
			while (ww--)
			{
				d[0] = s[0];
				d[1] = s[0];
				d[2] = s[0];
				s += sn;
				d += dn;
				if (da)
					d[-1] = sa ? s[-1] : 255;
			}
			d += d_line_inc;
			s += s_line_inc;
		}
	}
}


TEST_F(RouterTest, RetryTimeoutDuringRetryDelay) {
  NiceMock<Http::MockRequestEncoder> encoder1;
  Http::ResponseDecoder* response_decoder = nullptr;
  expectNewStreamWithImmediateEncoder(encoder1, &response_decoder, Http::Protocol::Http10);

  expectResponseTimerCreate();

  Http::TestRequestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}};
  HttpTestUtility::addDefaultHeaders(headers);
  router_.decodeHeaders(headers, true);
  EXPECT_EQ(1U,
            callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());

  // 5xx response.
  router_.retry_state_->expectHeadersRetry();
  Http::ResponseHeaderMapPtr response_headers1(
      new Http::TestResponseHeaderMapImpl{{":status", "503"}});
  EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,
              putHttpResponseCode(503));
  response_decoder->decodeHeaders(std::move(response_headers1), true);
  EXPECT_TRUE(verifyHostUpstreamStats(0, 1));

  // Fire timeout.
  EXPECT_CALL(callbacks_.stream_info_,
              setResponseFlag(StreamInfo::ResponseFlag::UpstreamRequestTimeout));

  EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_, putResponseTime(_))
      .Times(0);
  Http::TestResponseHeaderMapImpl response_headers{
      {":status", "504"}, {"content-length", "24"}, {"content-type", "text/plain"}};
  EXPECT_CALL(callbacks_, encodeHeaders_(HeaderMapEqualRef(&response_headers), false));
  EXPECT_CALL(callbacks_, encodeData(_, true));
  response_timeout_->invokeCallback();
  EXPECT_TRUE(verifyHostUpstreamStats(0, 1));
}


TRIO_PRIVATE double TrioLogarithmBase TRIO_ARGS1((base), int base)
{
	switch (base)
	{
		case BASE_BINARY:
			return 1.0;
		case BASE_OCTAL:
			return 3.0;
		case BASE_DECIMAL:
			return 3.321928094887362345;
		case BASE_HEX:
			return 4.0;
		default:
			return TrioLogarithm((double)base, 2);
	}
}


int ExtensionInstallDialogView::GetDefaultDialogButton() const {
  return ui::DIALOG_BUTTON_CANCEL;
}


set_num_723(unsigned char *p, uint16_t value)
{
	archive_le16enc(p, value);
	archive_be16enc(p+2, value);
}


static Jsi_OpCodes *code_ret(jsi_Pstate *p, jsi_Pline *line, int n) { JSI_NEW_CODESLN(0,OP_RET, n); }


OMX_ERRORTYPE SoftOpus::internalSetParameter(
        OMX_INDEXTYPE index, const OMX_PTR params) {
 switch ((int)index) {
 case OMX_IndexParamStandardComponentRole:
 {
 const OMX_PARAM_COMPONENTROLETYPE *roleParams =
 (const OMX_PARAM_COMPONENTROLETYPE *)params;

 if (!isValidOMXParam(roleParams)) {
 return OMX_ErrorBadParameter;
 }

 if (strncmp((const char *)roleParams->cRole,
 "audio_decoder.opus",
                        OMX_MAX_STRINGNAME_SIZE - 1)) {
 return OMX_ErrorUndefined;
 }

 return OMX_ErrorNone;
 }

 case OMX_IndexParamAudioAndroidOpus:
 {
 const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
 (const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;

 if (!isValidOMXParam(opusParams)) {
 return OMX_ErrorBadParameter;
 }

 if (opusParams->nPortIndex != 0) {
 return OMX_ErrorUndefined;
 }

 return OMX_ErrorNone;
 }

 default:
 return SimpleSoftOMXComponent::internalSetParameter(index, params);
 }
}


TabContents* Browser::GetOrCloneTabForDisposition(
       WindowOpenDisposition disposition) {
  TabContentsWrapper* current_tab = GetSelectedTabContentsWrapper();
  if (ShouldOpenNewTabForWindowDisposition(disposition)) {
    current_tab = current_tab->Clone();
    tab_handler_->GetTabStripModel()->AddTabContents(
        current_tab, -1, PageTransition::LINK,
        disposition == NEW_FOREGROUND_TAB ? TabStripModel::ADD_SELECTED :
                                            TabStripModel::ADD_NONE);
  }
  return current_tab->tab_contents();
}


void CopyOutputRequestCallback(base::Closure quit_closure,
                               gfx::Size expected_size,
                               std::unique_ptr<CopyOutputResult> result) {
  EXPECT_EQ(expected_size, result->size());
  quit_closure.Run();
}


ins_shift(int c, int lastc)
{
    if (stop_arrow() == FAIL)
	return;
    AppendCharToRedobuff(c);

    /*
     * 0^D and ^^D: remove all indent.
     */
    if (c == Ctrl_D && (lastc == '0' || lastc == '^')
						  && curwin->w_cursor.col > 0)
    {
	--curwin->w_cursor.col;
	(void)del_char(FALSE);		// delete the '^' or '0'
	// In Replace mode, restore the characters that '^' or '0' replaced.
	if (State & REPLACE_FLAG)
	    replace_pop_ins();
	if (lastc == '^')
	    old_indent = get_indent();	// remember curr. indent
	change_indent(INDENT_SET, 0, TRUE, 0, TRUE);
    }
    else
	change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE);

    if (did_ai && *skipwhite(ml_get_curline()) != NUL)
	did_ai = FALSE;
#ifdef FEAT_SMARTINDENT
    did_si = FALSE;
    can_si = FALSE;
    can_si_back = FALSE;
#endif
#ifdef FEAT_CINDENT
    can_cindent = FALSE;	// no cindenting after ^D or ^T
#endif
}


static void test_rewind ( void ) {
 MYSQL_STMT * stmt ;
 MYSQL_BIND my_bind ;
 int rc = 0 ;
 const char * stmt_text ;
 long unsigned int length = 4 , Data = 0 ;
 my_bool isnull = 0 ;
 myheader ( "test_rewind" ) ;
 stmt_text = "CREATE TABLE t1 (a int)" ;
 rc = mysql_real_query ( mysql , stmt_text , strlen ( stmt_text ) ) ;
 myquery ( rc ) ;
 stmt_text = "INSERT INTO t1 VALUES(2),(3),(4)" ;
 rc = mysql_real_query ( mysql , stmt_text , strlen ( stmt_text ) ) ;
 myquery ( rc ) ;
 stmt = mysql_stmt_init ( mysql ) ;
 stmt_text = "SELECT * FROM t1" ;
 rc = mysql_stmt_prepare ( stmt , stmt_text , strlen ( stmt_text ) ) ;
 check_execute ( stmt , rc ) ;
 memset ( & my_bind , 0 , sizeof ( MYSQL_BIND ) ) ;
 my_bind . buffer_type = MYSQL_TYPE_LONG ;
 my_bind . buffer = ( void * ) & Data ;
 my_bind . length = & length ;
 my_bind . is_null = & isnull ;
 rc = mysql_stmt_execute ( stmt ) ;
 check_execute ( stmt , rc ) ;
 rc = mysql_stmt_store_result ( stmt ) ;
 DIE_UNLESS ( rc == 0 ) ;
 rc = mysql_stmt_bind_result ( stmt , & my_bind ) ;
 DIE_UNLESS ( rc == 0 ) ;
 while ( ! mysql_stmt_fetch ( stmt ) ) if ( ! opt_silent ) printf ( "fetched result:%ld\n" , Data ) ;
 DIE_UNLESS ( rc != MYSQL_NO_DATA ) ;
 mysql_stmt_data_seek ( stmt , 0 ) ;
 while ( ! ( rc = mysql_stmt_fetch ( stmt ) ) ) if ( ! opt_silent ) printf ( "fetched result after seek:%ld\n" , Data ) ;
 DIE_UNLESS ( rc == MYSQL_NO_DATA ) ;
 stmt_text = "DROP TABLE t1" ;
 rc = mysql_real_query ( mysql , stmt_text , strlen ( stmt_text ) ) ;
 myquery ( rc ) ;
 rc = mysql_stmt_free_result ( stmt ) ;
 rc = mysql_stmt_close ( stmt ) ;
 }


bool GLES2DecoderImpl::ResizeOffscreenFrameBuffer(const gfx::Size& size) {
  bool is_offscreen = !!offscreen_target_frame_buffer_.get();
  if (!is_offscreen) {
    LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer called "
               << " with an onscreen framebuffer.";
    return false;
  }

  if (offscreen_size_ == size)
    return true;

  offscreen_size_ = size;
  int w = offscreen_size_.width();
  int h = offscreen_size_.height();
  if (w < 0 || h < 0 || h >= (INT_MAX / 4) / (w ? w : 1)) {
    LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer failed "
               << "to allocate storage due to excessive dimensions.";
    return false;
  }

  DCHECK(offscreen_target_color_format_);
  if (IsOffscreenBufferMultisampled()) {
    if (!offscreen_target_color_render_buffer_->AllocateStorage(
        offscreen_size_, offscreen_target_color_format_,
        offscreen_target_samples_)) {
      LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer failed "
                 << "to allocate storage for offscreen target color buffer.";
      return false;
    }
  } else {
    if (!offscreen_target_color_texture_->AllocateStorage(
        offscreen_size_, offscreen_target_color_format_)) {
      LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer failed "
                 << "to allocate storage for offscreen target color texture.";
      return false;
    }
  }
  if (offscreen_target_depth_format_ &&
      !offscreen_target_depth_render_buffer_->AllocateStorage(
      offscreen_size_, offscreen_target_depth_format_,
      offscreen_target_samples_)) {
    LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer failed "
               << "to allocate storage for offscreen target depth buffer.";
    return false;
  }
  if (offscreen_target_stencil_format_ &&
      !offscreen_target_stencil_render_buffer_->AllocateStorage(
      offscreen_size_, offscreen_target_stencil_format_,
      offscreen_target_samples_)) {
    LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer failed "
               << "to allocate storage for offscreen target stencil buffer.";
    return false;
  }
  TRACE_BACKBUFFER_MEMORY_TOTAL(this);

  if (IsOffscreenBufferMultisampled()) {
    offscreen_target_frame_buffer_->AttachRenderBuffer(
        GL_COLOR_ATTACHMENT0,
        offscreen_target_color_render_buffer_.get());
  } else {
    offscreen_target_frame_buffer_->AttachRenderTexture(
        offscreen_target_color_texture_.get());
  }
  if (offscreen_target_depth_format_) {
    offscreen_target_frame_buffer_->AttachRenderBuffer(
        GL_DEPTH_ATTACHMENT,
        offscreen_target_depth_render_buffer_.get());
  }
  const bool packed_depth_stencil =
      offscreen_target_depth_format_ == GL_DEPTH24_STENCIL8;
  if (packed_depth_stencil) {
    offscreen_target_frame_buffer_->AttachRenderBuffer(
        GL_STENCIL_ATTACHMENT,
        offscreen_target_depth_render_buffer_.get());
  } else if (offscreen_target_stencil_format_) {
    offscreen_target_frame_buffer_->AttachRenderBuffer(
        GL_STENCIL_ATTACHMENT,
        offscreen_target_stencil_render_buffer_.get());
  }

  if (offscreen_target_frame_buffer_->CheckStatus() !=
      GL_FRAMEBUFFER_COMPLETE) {
      LOG(ERROR) << "GLES2DecoderImpl::ResizeOffscreenFrameBuffer failed "
                 << "because offscreen FBO was incomplete.";
    return false;
  }

  {
    ScopedFrameBufferBinder binder(this, offscreen_target_frame_buffer_->id());
    glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat(
        offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glClearStencil(0);
    glStencilMaskSeparate(GL_FRONT, -1);
    glStencilMaskSeparate(GL_BACK, -1);
    glClearDepth(0);
    glDepthMask(GL_TRUE);
    glDisable(GL_SCISSOR_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    RestoreClearState();
  }

  if (offscreen_resolved_frame_buffer_.get())
    offscreen_resolved_frame_buffer_->Destroy();
  if (offscreen_resolved_color_texture_.get())
    offscreen_resolved_color_texture_->Destroy();
  offscreen_resolved_color_texture_.reset();
  offscreen_resolved_frame_buffer_.reset();

  return true;
}


findTiffCompression(FILE     *fp,
                    l_int32  *pcomptype)
{
l_uint16  tiffcomp;
TIFF     *tif;

    PROCNAME("findTiffCompression");

    if (!pcomptype)
        return ERROR_INT("&comptype not defined", procName, 1);
    *pcomptype = IFF_UNKNOWN;  /* init */
    if (!fp)
        return ERROR_INT("stream not defined", procName, 1);

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return ERROR_INT("tif not opened", procName, 1);
    TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);
    *pcomptype = getTiffCompressedFormat(tiffcomp);
    TIFFCleanup(tif);
    return 0;
}


gboolean proto_registrar_dump_fieldcount ( void ) {
 guint32 i ;
 header_field_info * hfinfo ;
 guint32 deregistered_count = 0 ;
 guint32 same_name_count = 0 ;
 guint32 protocol_count = 0 ;
 for ( i = 0 ;
 i < gpa_hfinfo . len ;
 i ++ ) {
 if ( gpa_hfinfo . hfi [ i ] == NULL ) {
 deregistered_count ++ ;
 continue ;
 }
 PROTO_REGISTRAR_GET_NTH ( i , hfinfo ) ;
 if ( proto_registrar_is_protocol ( i ) ) protocol_count ++ ;
 if ( hfinfo -> same_name_prev_id != - 1 ) same_name_count ++ ;
 }
 ws_debug_printf ( "There are %u header fields registered, of which:\n" "\t%u are deregistered\n" "\t%u are protocols\n" "\t%u have the same name as another field\n\n" , gpa_hfinfo . len , deregistered_count , protocol_count , same_name_count ) ;
 ws_debug_printf ( "%d fields were pre-allocated.\n%s" , PROTO_PRE_ALLOC_HF_FIELDS_MEM , ( gpa_hfinfo . allocated_len > PROTO_PRE_ALLOC_HF_FIELDS_MEM ) ? "* * Please increase PROTO_PRE_ALLOC_HF_FIELDS_MEM (in epan/proto.c)! * *\n\n" : "\n" ) ;
 ws_debug_printf ( "The header field table consumes %u KiB of memory.\n" , ( unsigned int ) ( gpa_hfinfo . allocated_len * sizeof ( header_field_info * ) / 1024 ) ) ;
 ws_debug_printf ( "The fields themselves consume %u KiB of memory.\n" , ( unsigned int ) ( gpa_hfinfo . len * sizeof ( header_field_info ) / 1024 ) ) ;
 return ( gpa_hfinfo . allocated_len > PROTO_PRE_ALLOC_HF_FIELDS_MEM ) ;
 }


u32 get_sys_col(int idx)
{
	u32 res;
	DWORD val = GetSysColor(idx);
	res = (val)&0xFF;
	res<<=8;
	res |= (val>>8)&0xFF;
	res<<=8;
	res |= (val>>16)&0xFF;
	return res;
}


void RenderViewImpl::OnNavigate(const ViewMsg_Navigate_Params& params) {
#if defined(OS_CHROMEOS)
  LOG(ERROR) << "OnNavigate: url=" << params.url
             << ", webview=" << webview()
             << ", reload=" << IsReload(params)
             << ", paerams.state.empty=" << params.state.empty();
#endif
  MaybeHandleDebugURL(params.url);
  if (!webview())
    return;

  FOR_EACH_OBSERVER(RenderViewObserver, observers_, Navigate(params.url));

  bool is_reload = IsReload(params);

  if (IsBackForwardToStaleEntry(params, is_reload))
    return;

  if (is_swapped_out_)
    SetSwappedOut(false);

  history_list_offset_ = params.current_history_list_offset;
  history_list_length_ = params.current_history_list_length;
  if (history_list_length_ >= 0)
    history_page_ids_.resize(history_list_length_, -1);
  if (params.pending_history_list_offset >= 0 &&
      params.pending_history_list_offset < history_list_length_)
    history_page_ids_[params.pending_history_list_offset] = params.page_id;

  content::GetContentClient()->SetActiveURL(params.url);

  WebFrame* main_frame = webview()->mainFrame();
  if (is_reload && main_frame->currentHistoryItem().isNull()) {
    is_reload = false;
  }

  pending_navigation_params_.reset(new ViewMsg_Navigate_Params);
  *pending_navigation_params_.get() = params;

  if (is_reload) {
    bool ignore_cache = (params.navigation_type ==
                             ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
    main_frame->reload(ignore_cache);
  } else if (!params.state.empty()) {
    DCHECK_NE(params.page_id, -1);
    main_frame->loadHistoryItem(
        webkit_glue::HistoryItemFromString(params.state));
  } else {
    WebURLRequest request(params.url);

    CHECK_EQ(params.page_id, -1);

    if (main_frame->isViewSourceModeEnabled())
      request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);

    if (params.referrer.url.is_valid()) {
      WebString referrer = WebSecurityPolicy::generateReferrerHeader(
          params.referrer.policy,
          params.url,
          WebString::fromUTF8(params.referrer.url.spec()));
      if (!referrer.isEmpty())
        request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
    }

    if (!params.extra_headers.empty()) {
      for (net::HttpUtil::HeadersIterator i(params.extra_headers.begin(),
                                            params.extra_headers.end(), "\n");
           i.GetNext(); ) {
        request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
                                   WebString::fromUTF8(i.values()));
      }
    }
#if defined(OS_CHROMEOS)
    LOG(ERROR) << " FrameLoader::loadRequest()";
#endif
    main_frame->loadRequest(request);
  }

  pending_navigation_params_.reset();
}


gfx::NativeView WebContentsImpl::GetContentNativeView() {
  return view_->GetContentNativeView();
}


free_cell_pool(void)
{
  /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  if (cell_pool) {
    mp_pool_destroy(cell_pool);
    cell_pool = NULL;
  }
}


static s32 brcmf_cfg80211_set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
	struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
	struct net_device *ndev = cfg_to_ndev(cfg);
	struct brcmf_if *ifp = netdev_priv(ndev);
	s32 err = 0;

	brcmf_dbg(TRACE, "Enter\n");
	if (!check_vif_up(ifp->vif))
		return -EIO;

	if (changed & WIPHY_PARAM_RTS_THRESHOLD &&
	    (cfg->conf->rts_threshold != wiphy->rts_threshold)) {
		cfg->conf->rts_threshold = wiphy->rts_threshold;
		err = brcmf_set_rts(ndev, cfg->conf->rts_threshold);
		if (!err)
			goto done;
	}
	if (changed & WIPHY_PARAM_FRAG_THRESHOLD &&
	    (cfg->conf->frag_threshold != wiphy->frag_threshold)) {
		cfg->conf->frag_threshold = wiphy->frag_threshold;
		err = brcmf_set_frag(ndev, cfg->conf->frag_threshold);
		if (!err)
			goto done;
	}
	if (changed & WIPHY_PARAM_RETRY_LONG
	    && (cfg->conf->retry_long != wiphy->retry_long)) {
		cfg->conf->retry_long = wiphy->retry_long;
		err = brcmf_set_retry(ndev, cfg->conf->retry_long, true);
		if (!err)
			goto done;
	}
	if (changed & WIPHY_PARAM_RETRY_SHORT
	    && (cfg->conf->retry_short != wiphy->retry_short)) {
		cfg->conf->retry_short = wiphy->retry_short;
		err = brcmf_set_retry(ndev, cfg->conf->retry_short, false);
		if (!err)
			goto done;
	}

done:
	brcmf_dbg(TRACE, "Exit\n");
	return err;
}


void HTMLConstructionSite::insertCommentOnHTMLHtmlElement(AtomicHTMLToken& token)
{
    ASSERT(token.type() == HTMLToken::Comment);
    attach(m_openElements.htmlElement(), Comment::create(m_document, token.comment()));
}


SDL_AllocPalette(int ncolors)
{
    SDL_Palette *palette;

    /* Input validation */
    if (ncolors < 1) {
      SDL_InvalidParamError("ncolors");
      return NULL;
    }

    palette = (SDL_Palette *) SDL_malloc(sizeof(*palette));
    if (!palette) {
        SDL_OutOfMemory();
        return NULL;
    }
    palette->colors =
        (SDL_Color *) SDL_malloc(ncolors * sizeof(*palette->colors));
    if (!palette->colors) {
        SDL_free(palette);
        return NULL;
    }
    palette->ncolors = ncolors;
    palette->version = 1;
    palette->refcount = 1;

    SDL_memset(palette->colors, 0xFF, ncolors * sizeof(*palette->colors));

    return palette;
}


ash::wm::WindowState* ClientControlledShellSurface::GetWindowState() {
  return ash::wm::GetWindowState(widget_->GetNativeWindow());
}


static void dissect_zcl_ota_upgradeendreq ( tvbuff_t * tvb , proto_tree * tree , guint * offset ) {
 proto_tree_add_item ( tree , hf_zbee_zcl_ota_status , tvb , * offset , 1 , ENC_NA ) ;
 * offset += 1 ;
 proto_tree_add_item ( tree , hf_zbee_zcl_ota_manufacturer_code , tvb , * offset , 2 , ENC_LITTLE_ENDIAN ) ;
 * offset += 2 ;
 proto_tree_add_item ( tree , hf_zbee_zcl_ota_image_type , tvb , * offset , 2 , ENC_LITTLE_ENDIAN ) ;
 * offset += 2 ;
 dissect_zcl_ota_file_version_field ( tvb , tree , offset ) ;
 }


backref_check_at_nested_level(regex_t* reg,
                              StackType* top, StackType* stk_base,
                              int nest, int mem_num, MemNumType* memp)
{
  int level;
  StackType* k;

  level = 0;
  k = top;
  k--;
  while (k >= stk_base) {
    if (k->type == STK_CALL_FRAME) {
      level--;
    }
    else if (k->type == STK_RETURN) {
      level++;
    }
    else if (level == nest) {
      if (k->type == STK_MEM_END) {
        if (mem_is_in_memp(k->zid, mem_num, memp)) {
          return 1;
        }
      }
    }
    k--;
  }

  return 0;
}


    **/
    static const CImg<Tuchar>& default_LUT256() {
      static CImg<Tuchar> colormap;
      cimg::mutex(8);
      if (!colormap) {
        colormap.assign(1,256,1,3);
        for (unsigned int index = 0, r = 16; r<256; r+=32)
          for (unsigned int g = 16; g<256; g+=32)
            for (unsigned int b = 32; b<256; b+=64) {
              colormap(0,index,0) = (Tuchar)r;
              colormap(0,index,1) = (Tuchar)g;
              colormap(0,index++,2) = (Tuchar)b;
            }
      }
      cimg::mutex(8,0);
      return colormap;


void WebGraphicsContext3DCommandBufferImpl::setVisibilityCHROMIUM(
    bool visible) {
  gl_->Flush();
  visible_ = visible;
  command_buffer_->SetSurfaceVisible(visible);
  if (!visible)
    gl_->FreeEverything();
}


test_decode_integer_overflow (xd3_stream *stream, int unused)
{
  return test_read_integer_error (stream, 0, "overflow in read_intger");
}


int netlink_remove_tap(struct netlink_tap *nt)
{
	int ret;

	ret = __netlink_remove_tap(nt);
	synchronize_net();

	return ret;
}


_kdc_is_weak_exception(krb5_principal principal, krb5_enctype etype)
{
    if (principal->name.name_string.len > 0 &&
	strcmp(principal->name.name_string.val[0], "afs") == 0 &&
	(etype == (krb5_enctype)ETYPE_DES_CBC_CRC
	 || etype == (krb5_enctype)ETYPE_DES_CBC_MD4
	 || etype == (krb5_enctype)ETYPE_DES_CBC_MD5))
	return TRUE;
    return FALSE;
}


static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
{
	struct task_struct *new_owner;
	struct futex_pi_state *pi_state = this->pi_state;
	u32 curval, newval;

	if (!pi_state)
		return -EINVAL;

	/*
	 * If current does not own the pi_state then the futex is
	 * inconsistent and user space fiddled with the futex value.
	 */
	if (pi_state->owner != current)
		return -EINVAL;

	raw_spin_lock(&pi_state->pi_mutex.wait_lock);
	new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);

	/*
	 * This happens when we have stolen the lock and the original
	 * pending owner did not enqueue itself back on the rt_mutex.
	 * Thats not a tragedy. We know that way, that a lock waiter
	 * is on the fly. We make the futex_q waiter the pending owner.
	 */
	if (!new_owner)
		new_owner = this->task;

	/*
	 * We pass it to the next owner. (The WAITERS bit is always
	 * kept enabled while there is PI state around. We must also
	 * preserve the owner died bit.)
	 */
	if (!(uval & FUTEX_OWNER_DIED)) {
		int ret = 0;

		newval = FUTEX_WAITERS | task_pid_vnr(new_owner);

		curval = cmpxchg_futex_value_locked(uaddr, uval, newval);

		if (curval == -EFAULT)
			ret = -EFAULT;
		else if (curval != uval)
			ret = -EINVAL;
		if (ret) {
			raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
			return ret;
		}
	}

	raw_spin_lock_irq(&pi_state->owner->pi_lock);
	WARN_ON(list_empty(&pi_state->list));
	list_del_init(&pi_state->list);
	raw_spin_unlock_irq(&pi_state->owner->pi_lock);

	raw_spin_lock_irq(&new_owner->pi_lock);
	WARN_ON(!list_empty(&pi_state->list));
	list_add(&pi_state->list, &new_owner->pi_state_list);
	pi_state->owner = new_owner;
	raw_spin_unlock_irq(&new_owner->pi_lock);

	raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
	rt_mutex_unlock(&pi_state->pi_mutex);

	return 0;
}


table_check_use(struct table *t, uint32_t tmask, uint32_t smask)
{
	return table_check_type(t, tmask) && table_check_service(t, smask);
}


void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
					  MonoArray *ctors, MonoArray *fields, MonoArray *properties,
					  MonoArray *events)
{
	MonoGenericClass *gclass;
	MonoDynamicGenericClass *dgclass;
	MonoClass *klass, *gklass;
	MonoType *gtype;
	int i;

	MONO_ARCH_SAVE_REGS;

	gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type);
	klass = mono_class_from_mono_type (gtype);
	g_assert (gtype->type == MONO_TYPE_GENERICINST);
	gclass = gtype->data.generic_class;

	if (!gclass->is_dynamic)
		return;

	dgclass = (MonoDynamicGenericClass *) gclass;

	if (dgclass->initialized)
		return;

	gklass = gclass->container_class;
	mono_class_init (gklass);

	dgclass->count_methods = methods ? mono_array_length (methods) : 0;
	dgclass->count_ctors = ctors ? mono_array_length (ctors) : 0;
	dgclass->count_fields = fields ? mono_array_length (fields) : 0;

	dgclass->methods = mono_image_set_new0 (gclass->owner, MonoMethod *, dgclass->count_methods);
	dgclass->ctors = mono_image_set_new0 (gclass->owner, MonoMethod *, dgclass->count_ctors);
	dgclass->fields = mono_image_set_new0 (gclass->owner, MonoClassField, dgclass->count_fields);
	dgclass->field_objects = mono_image_set_new0 (gclass->owner, MonoObject*, dgclass->count_fields);
	dgclass->field_generic_types = mono_image_set_new0 (gclass->owner, MonoType*, dgclass->count_fields);

	for (i = 0; i < dgclass->count_methods; i++) {
		MonoObject *obj = mono_array_get (methods, gpointer, i);

		dgclass->methods [i] = inflate_method ((MonoReflectionType*)type, obj);
	}

	for (i = 0; i < dgclass->count_ctors; i++) {
		MonoObject *obj = mono_array_get (ctors, gpointer, i);

		dgclass->ctors [i] = inflate_method ((MonoReflectionType*)type, obj);
	}

	for (i = 0; i < dgclass->count_fields; i++) {
		MonoObject *obj = mono_array_get (fields, gpointer, i);
		MonoClassField *field, *inflated_field = NULL;

		if (!strcmp (obj->vtable->klass->name, "FieldBuilder"))
			inflated_field = field = fieldbuilder_to_mono_class_field (klass, (MonoReflectionFieldBuilder *) obj);
		else if (!strcmp (obj->vtable->klass->name, "MonoField"))
			field = ((MonoReflectionField *) obj)->field;
		else {
			field = NULL; /* prevent compiler warning */
			g_assert_not_reached ();
		}

		dgclass->fields [i] = *field;
		dgclass->fields [i].parent = klass;
		dgclass->fields [i].type = mono_class_inflate_generic_type (
			field->type, mono_generic_class_get_context ((MonoGenericClass *) dgclass));
		dgclass->field_generic_types [i] = field->type;
		MONO_GC_REGISTER_ROOT_IF_MOVING (dgclass->field_objects [i]);
		dgclass->field_objects [i] = obj;

		if (inflated_field) {
			g_free (inflated_field);
		} else {
			dgclass->fields [i].name = mono_image_set_strdup (gclass->owner, dgclass->fields [i].name);
		}
	}

	dgclass->initialized = TRUE;


String WebFrame::contentsAsString() const
{
    if (!m_coreFrame)
        return String();

    if (isFrameSet()) {
        StringBuilder builder;
        for (Frame* child = m_coreFrame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
            if (!builder.isEmpty())
                builder.append(' ');
            builder.append(static_cast<WebFrameLoaderClient*>(child->loader()->client())->webFrame()->contentsAsString());
        }
        return builder.toString();
    }

    Document* document = m_coreFrame->document();
    if (!document)
        return String();

    RefPtr<Element> documentElement = document->documentElement();
    if (!documentElement)
        return String();

    RefPtr<Range> range = document->createRange();

    ExceptionCode ec = 0;
    range->selectNode(documentElement.get(), ec);
    if (ec)
        return String();

    return plainText(range.get());
}


void Statement::Work_BeginBind(Baton* baton) {
    STATEMENT_BEGIN(Bind);
}


ExtensionResource Extension::GetResource(
    const FilePath& relative_file_path) const {
  ExtensionResource r(id(), path(), relative_file_path);
  if ((creation_flags() & Extension::FOLLOW_SYMLINKS_ANYWHERE)) {
    r.set_follow_symlinks_anywhere();
  }
  return r;
}


static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
			    int addr_len)
{
	struct sock *sk = sock->sk;
	char name[15];
	struct net_device *dev;
	int err = -ENODEV;

	/*
	 *	Check legality
	 */

	if (addr_len != sizeof(struct sockaddr))
		return -EINVAL;
	strlcpy(name, uaddr->sa_data, sizeof(name));

	dev = dev_get_by_name(sock_net(sk), name);
	if (dev)
		err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
	return err;
}


static PGconn * get_db_conn ( ClusterInfo * cluster , const char * db_name ) {
 char conn_opts [ 2 * NAMEDATALEN + MAXPGPATH + 100 ] ;
 if ( cluster -> sockdir ) snprintf ( conn_opts , sizeof ( conn_opts ) , "dbname = '%s' user = '%s' host = '%s' port = %d" , db_name , os_info . user , cluster -> sockdir , cluster -> port ) ;
 else snprintf ( conn_opts , sizeof ( conn_opts ) , "dbname = '%s' user = '%s' port = %d" , db_name , os_info . user , cluster -> port ) ;
 return PQconnectdb ( conn_opts ) ;
 }


opts_next_list(Visitor *v, GenericList **list, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    GenericList **link;

    if (ov->repeated_opts_first) {

        ov->repeated_opts_first = false;

        link = list;

    } else {

        const QemuOpt *opt;

        opt = g_queue_pop_head(ov->repeated_opts);

        if (g_queue_is_empty(ov->repeated_opts)) {

            g_hash_table_remove(ov->unprocessed_opts, opt->name);

            return NULL;

        }

        link = &(*list)->next;

    }

    *link = g_malloc0(sizeof **link);

    return *link;

}


void PepperRendererConnection::OnMsgDidCreateInProcessInstance(
     PP_Instance instance,
     const PepperRendererInstanceData& instance_data) {
   PepperRendererInstanceData data = instance_data;
   data.render_process_id = render_process_id_;
   in_process_host_->AddInstance(instance, data);
 }


wait_for_job(conn c, int timeout)
{
    int r;

    c->state = STATE_WAIT;
    enqueue_waiting_conn(c);

    /* Set the pending timeout to the requested timeout amount */
    c->pending_timeout = timeout;

    /* this conn is waiting, but we want to know if they hang up */
    r = conn_update_evq(c, EV_READ | EV_PERSIST);
    if (r == -1) return twarnx("update events failed"), conn_close(c);
}


bool test_r_str_ansi_len(void) {
	int len;

	len = r_str_ansi_len ("radare2");
	mu_assert_eq (len, 7, "len(ascii only)");

	len = r_str_ansi_len ("r\x1b[38;2;208;80;0madare2");
	mu_assert_eq (len, 7, "len(ascii + ansi ending with m)");

	len = r_str_ansi_len ("r\x1b[0Jadare2");
	mu_assert_eq (len, 7, "len(ascii + ansi ending with J)");

	len = r_str_ansi_len ("r\x1b[42;42Hadare2");
	mu_assert_eq (len, 7, "len(ascii + ansi ending with H)");

	len = r_str_ansi_len ("r\xc3\xa4""dare2");
	mu_assert_eq (len, 8, "len(ascii + 2 byte utf-8 counted as 2 chars)");

	len = r_str_ansi_len ("radar\xe2\x82\xac""2");
	mu_assert_eq (len, 9, "len(ascii + 3 byte utf-8 counted as 3 chars)");

	len = r_str_ansi_len ("radar\xf0\x9d\x84\x9e""2");
	mu_assert_eq (len, 10, "len(ascii + 4 byte utf-8 counted as 4 chars)");

	mu_end;
}


static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)

{

    YADIFContext *s = ctx->priv;

    ThreadData *td  = arg;

    int refs = s->cur->linesize[td->plane];

    int df = (s->csp->comp[td->plane].depth_minus1 + 8) / 8;

    int pix_3 = 3 * df;

    int slice_h = td->h / nb_jobs;

    int slice_start = jobnr * slice_h;

    int slice_end   = (jobnr == nb_jobs - 1) ? td->h : (jobnr + 1) * slice_h;

    int y;

    /* filtering reads 3 pixels to the left/right; to avoid invalid reads,

     * we need to call the c variant which avoids this for border pixels

     */

    for (y = slice_start; y < slice_end; y++) {

        if ((y ^ td->parity) & 1) {

            uint8_t *prev = &s->prev->data[td->plane][y * refs];

            uint8_t *cur  = &s->cur ->data[td->plane][y * refs];

            uint8_t *next = &s->next->data[td->plane][y * refs];

            uint8_t *dst  = &td->frame->data[td->plane][y * td->frame->linesize[td->plane]];

            int     mode  = y == 1 || y + 2 == td->h ? 2 : s->mode;

            s->filter_line(dst + pix_3, prev + pix_3, cur + pix_3,

                           next + pix_3, td->w - 6,

                           y + 1 < td->h ? refs : -refs,

                           y ? -refs : refs,

                           td->parity ^ td->tff, mode);

            s->filter_edges(dst, prev, cur, next, td->w,

                            y + 1 < td->h ? refs : -refs,

                            y ? -refs : refs,

                            td->parity ^ td->tff, mode);

        } else {

            memcpy(&td->frame->data[td->plane][y * td->frame->linesize[td->plane]],

                   &s->cur->data[td->plane][y * refs], td->w * df);

        }

    }

    return 0;

}


static void __init early_reserve_initrd(void)
{
}


static struct async * async_getpending ( struct usb_dev_state * ps , void __user * userurb ) {
 struct async * as ;
 list_for_each_entry ( as , & ps -> async_pending , asynclist ) if ( as -> userurb == userurb ) {
 list_del_init ( & as -> asynclist ) ;
 return as ;
 }
 return NULL ;
 }


PassRefPtr<StyleRuleList> StyleResolver::styleRulesForElement(Element* element, unsigned rulesToInclude)
{
    ASSERT(element);
    StyleResolverState state(document(), element);
    ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
    collector.setMode(SelectorChecker::CollectingStyleRules);
    collectPseudoRulesForElement(element, collector, NOPSEUDO, rulesToInclude);
    return collector.matchedStyleRuleList();
}


void nested_load_control_from_vmcb12(struct vcpu_svm *svm,
				     struct vmcb_control_area *control)
{
	copy_vmcb_control_area(&svm->nested.ctl, control);

	/* Copy it here because nested_svm_check_controls will check it.  */
	svm->nested.ctl.asid           = control->asid;
	svm->nested.ctl.msrpm_base_pa &= ~0x0fffULL;
	svm->nested.ctl.iopm_base_pa  &= ~0x0fffULL;
}


static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)
{
	ext4_fsblk_t block = ext_pblock(ext);
	int len = ext4_ext_get_actual_len(ext);

	return ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);
}


void bdrv_init(void)

{

    module_call_init(MODULE_INIT_BLOCK);

}