bool ChromeDownloadManagerDelegate::ShouldOpenFileBasedOnExtension(
    const base::FilePath& path) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (path.Extension().empty())
    return false;
#if BUILDFLAG(ENABLE_EXTENSIONS)
  if (path.MatchesExtension(extensions::kExtensionFileExtension))
    return false;
#endif
  return download_prefs_->IsAutoOpenEnabledBasedOnExtension(path);
}


static int dns_stats_tree_packet ( stats_tree * st , packet_info * pinfo _U_ , epan_dissect_t * edt _U_ , const void * p ) {
 struct DnsTap * pi = ( struct DnsTap * ) p ;
 tick_stat_node ( st , st_str_packets , 0 , FALSE ) ;
 stats_tree_tick_pivot ( st , st_node_packet_qr , val_to_str ( pi -> packet_qr , dns_qr_vals , "Unknown qr (%d)" ) ) ;
 stats_tree_tick_pivot ( st , st_node_packet_qtypes , val_to_str ( pi -> packet_qtype , dns_types_description_vals , "Unknown packet type (%d)" ) ) ;
 stats_tree_tick_pivot ( st , st_node_packet_qclasses , val_to_str ( pi -> packet_qclass , dns_classes , "Unknown class (%d)" ) ) ;
 stats_tree_tick_pivot ( st , st_node_packet_rcodes , val_to_str ( pi -> packet_rcode , rcode_vals , "Unknown rcode (%d)" ) ) ;
 stats_tree_tick_pivot ( st , st_node_packet_opcodes , val_to_str ( pi -> packet_opcode , opcode_vals , "Unknown opcode (%d)" ) ) ;
 avg_stat_node_add_value ( st , st_str_packets_avg_size , 0 , FALSE , pi -> payload_size ) ;
 if ( pi -> packet_qr == 0 ) {
 avg_stat_node_add_value ( st , st_str_query_qname_len , 0 , FALSE , pi -> qname_len ) ;
 switch ( pi -> qname_labels ) {
 case 1 : tick_stat_node ( st , st_str_query_domains_l1 , 0 , FALSE ) ;
 break ;
 case 2 : tick_stat_node ( st , st_str_query_domains_l2 , 0 , FALSE ) ;
 break ;
 case 3 : tick_stat_node ( st , st_str_query_domains_l3 , 0 , FALSE ) ;
 break ;
 default : tick_stat_node ( st , st_str_query_domains_lmore , 0 , FALSE ) ;
 break ;
 }
 }
 else {
 avg_stat_node_add_value ( st , st_str_response_nquestions , 0 , FALSE , pi -> nquestions ) ;
 avg_stat_node_add_value ( st , st_str_response_nanswers , 0 , FALSE , pi -> nanswers ) ;
 avg_stat_node_add_value ( st , st_str_response_nauthorities , 0 , FALSE , pi -> nauthorities ) ;
 avg_stat_node_add_value ( st , st_str_response_nadditionals , 0 , FALSE , pi -> nadditionals ) ;
 }
 return 1 ;
 }


bool HttpUtil::HeadersIterator::GetNext() {
  while (lines_.GetNext()) {
    name_begin_ = lines_.token_begin();
    values_end_ = lines_.token_end();

    string::const_iterator colon = std::find(name_begin_, values_end_, ':');
    if (colon == values_end_)
      continue;  // skip malformed header

    name_end_ = colon;

    if (name_begin_ == name_end_ || IsLWS(*name_begin_))
      continue;

    TrimLWS(&name_begin_, &name_end_);
    if (name_begin_ == name_end_)
      continue;  // skip malformed header

    values_begin_ = colon + 1;
    TrimLWS(&values_begin_, &values_end_);

    return true;
  }
  return false;
}


status_t MyOpusExtractor::verifyOpusComments(MediaBuffer *buffer) {
 int32_t commentSize = buffer->range_length() + 1;
    sp<ABuffer> aBuf = new ABuffer(commentSize);
 if (aBuf->capacity() <= buffer->range_length()) {
 return ERROR_MALFORMED;
 }

 uint8_t* commentData = aBuf->data();
    memcpy(commentData,
 (uint8_t *)buffer->data() + buffer->range_offset(),
            buffer->range_length());

    ogg_buffer buf;
    buf.data = commentData;
    buf.size = commentSize;
    buf.refcount = 1;
    buf.ptr.owner = NULL;

    ogg_reference ref;
    ref.buffer = &buf;
    ref.begin = 0;
    ref.length = commentSize;
    ref.next = NULL;

    oggpack_buffer bits;
    oggpack_readinit(&bits, &ref);

 const char *OpusTags = "OpusTags";
 const int32_t headerLen = strlen(OpusTags);
 int32_t framingBitOffset = headerLen;
 for (int i = 0; i < headerLen; ++i) {
 char chr = oggpack_read(&bits, 8);
 if (chr != OpusTags[i]) {
 return ERROR_MALFORMED;
 }
 }

 int32_t vendorLen = oggpack_read(&bits, 32);
    framingBitOffset += 4;
 if (vendorLen < 0 || vendorLen > commentSize - 8) {
 return ERROR_MALFORMED;
 }
    framingBitOffset += vendorLen;
 for (int i = 0; i < vendorLen; ++i) {
        oggpack_read(&bits, 8);
 }

 int32_t n = oggpack_read(&bits, 32);
    framingBitOffset += 4;
 if (n < 0 || n > ((commentSize - oggpack_bytes(&bits)) >> 2)) {
 return ERROR_MALFORMED;
 }
 for (int i = 0; i < n; ++i) {
 int32_t len = oggpack_read(&bits, 32);
        framingBitOffset += 4;
 if (len  < 0 || len  > (commentSize - oggpack_bytes(&bits))) {
 return ERROR_MALFORMED;
 }
        framingBitOffset += len;
 for (int j = 0; j < len; ++j) {
            oggpack_read(&bits, 8);
 }
 }
 if (framingBitOffset < 0 || framingBitOffset >= commentSize) {
 return ERROR_MALFORMED;
 }
    commentData[framingBitOffset] = 1;

    buf.data = commentData + headerLen;
    buf.size = commentSize - headerLen;
    buf.refcount = 1;
    buf.ptr.owner = NULL;

    ref.buffer = &buf;
    ref.begin = 0;
    ref.length = commentSize - headerLen;
    ref.next = NULL;

    oggpack_readinit(&bits, &ref);
 int err = _vorbis_unpack_comment(&mVc, &bits);
 if (0 != err) {
 return ERROR_MALFORMED;
 }

    parseFileMetaData();
 return OK;
}


  virtual void AddObserver(Observer* observer) {
     if (!observers_.size()) {
       observer->FirstObserverIsAdded(this);
     }
     observers_.AddObserver(observer);
   }


void AudioSource::queueInputBuffer_l(MediaBuffer *buffer, int64_t timeUs) {
 const size_t bufferSize = buffer->range_length();
 const size_t frameSize = mRecord->frameSize();
 const int64_t timestampUs =
                mPrevSampleTimeUs +
 ((1000000LL * (bufferSize / frameSize)) +
 (mSampleRate >> 1)) / mSampleRate;

 if (mNumFramesReceived == 0) {
        buffer->meta_data()->setInt64(kKeyAnchorTime, mStartTimeUs);
 }

    buffer->meta_data()->setInt64(kKeyTime, mPrevSampleTimeUs);
    buffer->meta_data()->setInt64(kKeyDriftTime, timeUs - mInitialReadTimeUs);
    mPrevSampleTimeUs = timestampUs;
    mNumFramesReceived += bufferSize / frameSize;
    mBuffersReceived.push_back(buffer);
    mFrameAvailableCondition.signal();
}


void timer_deinit(QEMUTimer *ts)

{

    assert(ts->expire_time == -1);

    ts->timer_list = NULL;

}


Jsi_RC Jsi_ObjArraySet(Jsi_Interp *interp, Jsi_Obj *obj, Jsi_Value *value, int arrayindex)
{
    int m, n = arrayindex;
    if (Jsi_ObjArraySizer(interp, obj, n) <= 0)
        return JSI_ERROR;
    if (obj->arr[n] == value)
        return JSI_OK;
    if (obj->arr[n])
        Jsi_DecrRefCount(interp, obj->arr[n]);
    Assert(obj->arrCnt<=obj->arrMaxSize);
    obj->arr[n] = value;
    if (value)
        Jsi_IncrRefCount(interp, value);
    m = Jsi_ObjGetLength(interp, obj);
    if ((n+1) > m)
       Jsi_ObjSetLength(interp, obj, n+1);
    return JSI_OK;
}


static Image *ReadTTFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    buffer[MaxTextExtent],
    *text;

  const char
    *Text = (char *)
      "abcdefghijklmnopqrstuvwxyz\n"
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
      "0123456789.:,;(*!?}^)#${%^&-+@\n";

  const TypeInfo
    *type_info;

  DrawInfo
    *draw_info;

  Image
    *image;

  MagickBooleanType
    status;

  PixelPacket
    background_color;

  register ssize_t
    i,
    x;

  register PixelPacket
    *q;

  ssize_t
    y;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  image->columns=800;
  image->rows=480;
  type_info=GetTypeInfo(image_info->filename,exception);
  if ((type_info != (const TypeInfo *) NULL) &&
      (type_info->glyphs != (char *) NULL))
    (void) CopyMagickString(image->filename,type_info->glyphs,MaxTextExtent);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
       image=DestroyImageList(image);
       return((Image *) NULL);
     }
  status=SetImageExtent(image,image->columns,image->rows);
  if (status == MagickFalse)
    {
      InheritException(exception,&image->exception);
      return(DestroyImageList(image));
    }
   /*
     Color canvas with background color
   */
  background_color=image_info->background_color;
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
    if (q == (PixelPacket *) NULL)
      break;
    for (x=0; x < (ssize_t) image->columns; x++)
      *q++=background_color;
    if (SyncAuthenticPixels(image,exception) == MagickFalse)
      break;
  }
  (void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent);
  (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
  /*
    Prepare drawing commands
  */
  y=20;
  draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
  draw_info->font=AcquireString(image->filename);
  ConcatenateString(&draw_info->primitive,"push graphic-context\n");
  (void) FormatLocaleString(buffer,MaxTextExtent," viewbox 0 0 %.20g %.20g\n",
    (double) image->columns,(double) image->rows);
  ConcatenateString(&draw_info->primitive,buffer);
  ConcatenateString(&draw_info->primitive," font-size 18\n");
  (void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '",(double) y);
  ConcatenateString(&draw_info->primitive,buffer);
  text=EscapeString(Text,'"');
  ConcatenateString(&draw_info->primitive,text);
  text=DestroyString(text);
  (void) FormatLocaleString(buffer,MaxTextExtent,"'\n");
  ConcatenateString(&draw_info->primitive,buffer);
  y+=20*(ssize_t) MultilineCensus((char *) Text)+20;
  for (i=12; i <= 72; i+=6)
  {
    y+=i+12;
    ConcatenateString(&draw_info->primitive," font-size 18\n");
    (void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '%.20g'\n",
      (double) y,(double) i);
    ConcatenateString(&draw_info->primitive,buffer);
    (void) FormatLocaleString(buffer,MaxTextExtent," font-size %.20g\n",
      (double) i);
    ConcatenateString(&draw_info->primitive,buffer);
    (void) FormatLocaleString(buffer,MaxTextExtent," text 50,%.20g "
      "'That which does not destroy me, only makes me stronger.'\n",(double) y);
    ConcatenateString(&draw_info->primitive,buffer);
    if (i >= 24)
      i+=6;
  }
  ConcatenateString(&draw_info->primitive,"pop graphic-context");
  (void) DrawImage(image,draw_info);
  /*
    Relinquish resources.
  */
  draw_info=DestroyDrawInfo(draw_info);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


static VALUE ossl_asn1data_initialize ( VALUE self , VALUE value , VALUE tag , VALUE tag_class ) {
 if ( ! SYMBOL_P ( tag_class ) ) ossl_raise ( eASN1Error , "invalid tag class" ) ;
 if ( tag_class == sym_UNIVERSAL && NUM2INT ( tag ) > 31 ) ossl_raise ( eASN1Error , "tag number for Universal too large" ) ;
 ossl_asn1_set_tag ( self , tag ) ;
 ossl_asn1_set_value ( self , value ) ;
 ossl_asn1_set_tag_class ( self , tag_class ) ;
 ossl_asn1_set_infinite_length ( self , Qfalse ) ;
 return self ;
 }


void drop_privs()
{
	if (chroot(".") == -1)
		err(1, "chroot()");

	if (setgroups(0, NULL) == -1)
		err(1, "setgroups()");

	if (setgid(69) == -1)
		err(1, "setgid()");

	if (setuid(69) == -1)
		err(1, "setuid()");
}


Status Conv2DShapeImpl(shape_inference::InferenceContext* c,
                       bool supports_explicit_padding) {
  string data_format_str, filter_format_str;
  if (!c->GetAttr("data_format", &data_format_str).ok()) {
    data_format_str = "NHWC";
  }
  if (!c->GetAttr("filter_format", &filter_format_str).ok()) {
    filter_format_str = "HWIO";
  }

  TensorFormat data_format;
  if (!FormatFromString(data_format_str, &data_format)) {
    return errors::InvalidArgument("Invalid data format string: ",
                                   data_format_str);
  }
  FilterTensorFormat filter_format;
  if (!FilterFormatFromString(filter_format_str, &filter_format)) {
    return errors::InvalidArgument("Invalid filter format string: ",
                                   filter_format_str);
  }

  constexpr int num_spatial_dims = 2;
  const int rank = GetTensorDimsFromSpatialDims(num_spatial_dims, data_format);
  ShapeHandle conv_input_shape;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(0), rank, &conv_input_shape));
  TF_RETURN_IF_ERROR(CheckFormatConstraintsOnShape(
      data_format, conv_input_shape, "conv_input", c));

  // The filter rank should match the input (4 for NCHW, 5 for NCHW_VECT_C).
  ShapeHandle filter_shape;
  TF_RETURN_IF_ERROR(c->WithRank(c->input(1), rank, &filter_shape));
  TF_RETURN_IF_ERROR(
      CheckFormatConstraintsOnShape(data_format, filter_shape, "filter", c));

  std::vector<int32> dilations;
  TF_RETURN_IF_ERROR(c->GetAttr("dilations", &dilations));

  if (dilations.size() != 4) {
    return errors::InvalidArgument(
        "Conv2D requires the dilation attribute to contain 4 values, but got: ",
        dilations.size());
  }

  std::vector<int32> strides;
  TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));

  // strides.size() should be 4 (NCHW) even if the input is 5 (NCHW_VECT_C).
  if (strides.size() != 4) {
    return errors::InvalidArgument("Conv2D on data format ", data_format_str,
                                   " requires the stride attribute to contain"
                                   " 4 values, but got: ",
                                   strides.size());
  }

  const int32_t stride_rows = GetTensorDim(strides, data_format, 'H');
  const int32_t stride_cols = GetTensorDim(strides, data_format, 'W');
  const int32_t dilation_rows = GetTensorDim(dilations, data_format, 'H');
  const int32_t dilation_cols = GetTensorDim(dilations, data_format, 'W');

  DimensionHandle batch_size_dim;
  DimensionHandle input_depth_dim;
  gtl::InlinedVector<DimensionHandle, 2> input_spatial_dims(2);
  TF_RETURN_IF_ERROR(DimensionsFromShape(
      conv_input_shape, data_format, &batch_size_dim,
      absl::MakeSpan(input_spatial_dims), &input_depth_dim, c));

  DimensionHandle output_depth_dim = c->Dim(
      filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'O'));
  DimensionHandle filter_rows_dim = c->Dim(
      filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'H'));
  DimensionHandle filter_cols_dim = c->Dim(
      filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'W'));
  DimensionHandle filter_input_depth_dim;
  if (filter_format == FORMAT_OIHW_VECT_I) {
    TF_RETURN_IF_ERROR(c->Multiply(
        c->Dim(filter_shape,
               GetFilterDimIndex<num_spatial_dims>(filter_format, 'I')),
        c->Dim(filter_shape,
               GetFilterTensorInnerInputChannelsDimIndex(rank, filter_format)),
        &filter_input_depth_dim));
  } else {
    filter_input_depth_dim = c->Dim(
        filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'I'));
  }

  // Check that the input tensor and the filter tensor agree on the channel
  // count.
  if (c->ValueKnown(input_depth_dim) && c->ValueKnown(filter_input_depth_dim)) {
    int64_t input_depth_value = c->Value(input_depth_dim),
            filter_input_depth_value = c->Value(filter_input_depth_dim);
    if (input_depth_value % filter_input_depth_value != 0)
      return errors::InvalidArgument(
          "Depth of input (", input_depth_value,
          ") is not a multiple of input depth of filter (",
          filter_input_depth_value, ")");
    if (input_depth_value != filter_input_depth_value) {
      int64_t num_groups = input_depth_value / filter_input_depth_value;
      if (c->ValueKnown(output_depth_dim)) {
        int64_t output_depth_value = c->Value(output_depth_dim);
        if (output_depth_value % num_groups != 0)
          return errors::InvalidArgument(
              "Depth of output (", output_depth_value,
              ") is not a multiple of the number of groups (", num_groups, ")");
      }
    }
  }

  Padding padding;
  TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));

  std::vector<int64> explicit_paddings;
  if (supports_explicit_padding) {
    Status s = c->GetAttr("explicit_paddings", &explicit_paddings);
    // Use the default value, which is an empty list, if the attribute is not
    // found. Otherwise return the error to the caller.
    if (!s.ok() && !errors::IsNotFound(s)) {
      return s;
    }
    TF_RETURN_IF_ERROR(CheckValidPadding(padding, explicit_paddings,
                                         /*num_dims=*/4, data_format));
  } else {
    CHECK(padding != Padding::EXPLICIT);  // Crash ok.
  }

  DimensionHandle output_rows, output_cols;
  int64_t pad_rows_before = -1, pad_rows_after = -1;
  int64_t pad_cols_before = -1, pad_cols_after = -1;
  if (padding == Padding::EXPLICIT) {
    GetExplicitPaddingForDim(explicit_paddings, data_format, 'H',
                             &pad_rows_before, &pad_rows_after);
    GetExplicitPaddingForDim(explicit_paddings, data_format, 'W',
                             &pad_cols_before, &pad_cols_after);
  }
  TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(
      c, input_spatial_dims[0], filter_rows_dim, dilation_rows, stride_rows,
      padding, pad_rows_before, pad_rows_after, &output_rows));
  TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(
      c, input_spatial_dims[1], filter_cols_dim, dilation_cols, stride_cols,
      padding, pad_cols_before, pad_cols_after, &output_cols));

  absl::optional<DimensionHandle> vect_size;
  if (data_format == FORMAT_NCHW_VECT_C) {
    vect_size.emplace(c->Dim(conv_input_shape,
                             GetTensorInnerFeatureDimIndex(rank, data_format)));
  }
  ShapeHandle output_shape;
  TF_RETURN_IF_ERROR(ShapeFromDimensions(
      batch_size_dim, {output_rows, output_cols}, output_depth_dim, data_format,
      vect_size, c, &output_shape));
  c->set_output(0, output_shape);
  return Status::OK();
}


void AdjustComponent(int delta, url_parse::Component* component) {
  if (!component->is_valid())
    return;

  DCHECK(delta >= 0 || component->begin >= -delta);
  component->begin += delta;
}


static inline int gsm_mult(int a, int b)

{

    return (a * b + (1 << 14)) >> 15;

}


void pci_bridge_write_config(PCIDevice *d,

                             uint32_t address, uint32_t val, int len)

{

    PCIBridge *s = PCI_BRIDGE(d);

    uint16_t oldctl = pci_get_word(d->config + PCI_BRIDGE_CONTROL);

    uint16_t newctl;

    pci_default_write_config(d, address, val, len);

    if (ranges_overlap(address, len, PCI_COMMAND, 2) ||

        /* io base/limit */

        ranges_overlap(address, len, PCI_IO_BASE, 2) ||

        /* memory base/limit, prefetchable base/limit and

           io base/limit upper 16 */

        ranges_overlap(address, len, PCI_MEMORY_BASE, 20) ||

        /* vga enable */

        ranges_overlap(address, len, PCI_BRIDGE_CONTROL, 2)) {

        pci_bridge_update_mappings(s);

    }

    newctl = pci_get_word(d->config + PCI_BRIDGE_CONTROL);

    if (~oldctl & newctl & PCI_BRIDGE_CTL_BUS_RESET) {

        /* Trigger hot reset on 0->1 transition. */

        pci_bus_reset(&s->sec_bus);

    }

}


static int do_help(const char *prog)
{
  printf("%s, NPAPI plugin viewer. Version %s\n", NPW_VIEWER, NPW_VERSION);
  printf("\n");
  printf("usage: %s [GTK flags] [flags]\n", prog);
  printf("   -h --help               print this message\n");
  printf("   -t --test               check plugin is compatible\n");
  printf("   -i --info               print plugin information\n");
  printf("   -p --plugin             set plugin path\n");
  printf("   -c --connection         set connection path\n");
  return 0;
}


void WebPageProxy::reload(bool reloadFromOrigin)
{
    if (m_backForwardList->currentItem())
        setPendingAPIRequestURL(m_backForwardList->currentItem()->url());

    if (!isValid()) {
        reattachToWebProcessWithItem(m_backForwardList->currentItem());
        return;
    }

    process()->send(Messages::WebPage::Reload(reloadFromOrigin), m_pageID);
}


static int esp_input(struct xfrm_state *x, struct sk_buff *skb)
{
	struct crypto_aead *aead = x->data;
	struct aead_request *req;
	struct sk_buff *trailer;
	int ivlen = crypto_aead_ivsize(aead);
	int elen = skb->len - sizeof(struct ip_esp_hdr) - ivlen;
	int nfrags;
	int assoclen;
	int seqhilen;
	__be32 *seqhi;
	void *tmp;
	u8 *iv;
	struct scatterlist *sg;
	int err = -EINVAL;

	if (!pskb_may_pull(skb, sizeof(struct ip_esp_hdr) + ivlen))
		goto out;

	if (elen <= 0)
		goto out;

	assoclen = sizeof(struct ip_esp_hdr);
	seqhilen = 0;

	if (x->props.flags & XFRM_STATE_ESN) {
		seqhilen += sizeof(__be32);
		assoclen += seqhilen;
	}

	if (!skb_cloned(skb)) {
		if (!skb_is_nonlinear(skb)) {
			nfrags = 1;

			goto skip_cow;
		} else if (!skb_has_frag_list(skb)) {
			nfrags = skb_shinfo(skb)->nr_frags;
			nfrags++;

			goto skip_cow;
		}
	}

	err = skb_cow_data(skb, 0, &trailer);
	if (err < 0)
		goto out;

	nfrags = err;

skip_cow:
	err = -ENOMEM;
	tmp = esp_alloc_tmp(aead, nfrags, seqhilen);
	if (!tmp)
		goto out;

	ESP_SKB_CB(skb)->tmp = tmp;
	seqhi = esp_tmp_extra(tmp);
	iv = esp_tmp_iv(aead, tmp, seqhilen);
	req = esp_tmp_req(aead, iv);
	sg = esp_req_sg(aead, req);

	esp_input_set_header(skb, seqhi);

	sg_init_table(sg, nfrags);
	err = skb_to_sgvec(skb, sg, 0, skb->len);
	if (unlikely(err < 0)) {
		kfree(tmp);
		goto out;
	}

	skb->ip_summed = CHECKSUM_NONE;

	if ((x->props.flags & XFRM_STATE_ESN))
		aead_request_set_callback(req, 0, esp_input_done_esn, skb);
	else
		aead_request_set_callback(req, 0, esp_input_done, skb);

	aead_request_set_crypt(req, sg, sg, elen + ivlen, iv);
	aead_request_set_ad(req, assoclen);

	err = crypto_aead_decrypt(req);
	if (err == -EINPROGRESS)
		goto out;

	if ((x->props.flags & XFRM_STATE_ESN))
		esp_input_restore_header(skb);

	err = esp_input_done2(skb, err);

out:
	return err;
}


static inline int cris_abs(int n)

{

	int r;

	asm ("abs\t%1, %0\n" : "=r" (r) : "r" (n));

	return r;

}


void *nlmsg_data(const struct nlmsghdr *nlh)
{
	return (unsigned char *) nlh + NLMSG_HDRLEN;
}


void OSD::handle_scrub(MOSDScrub *m)
{
  dout(10) << "handle_scrub " << *m << dendl;
  if (!require_mon_or_mgr_peer(m)) {
    m->put();
    return;
  }
  if (m->fsid != monc->get_fsid()) {
    dout(0) << "handle_scrub fsid " << m->fsid << " != " << monc->get_fsid() << dendl;
    m->put();
    return;
  }

  RWLock::RLocker l(pg_map_lock);
  if (m->scrub_pgs.empty()) {
    for (ceph::unordered_map<spg_t, PG*>::iterator p = pg_map.begin();
	 p != pg_map.end();
	 ++p)
      handle_pg_scrub(m, p->second);
  } else {
    for (vector<pg_t>::iterator p = m->scrub_pgs.begin();
	 p != m->scrub_pgs.end();
	 ++p) {
      spg_t pcand;
      if (osdmap->get_primary_shard(*p, &pcand)) {
	auto pg_map_entry = pg_map.find(pcand);
	if (pg_map_entry != pg_map.end()) {
	  handle_pg_scrub(m, pg_map_entry->second);
	}
      }
    }
  }

  m->put();
}


void RenderFrameImpl::DidChangeThemeColor() {
  if (frame_->Parent())
    return;

  Send(new FrameHostMsg_DidChangeThemeColor(
      routing_id_, frame_->GetDocument().ThemeColor()));
}


  static void  Ins_MPPEM( INS_ARG )
  {
    args[0] = CURRENT_Ppem();
    DBG_PRINT1(" %d", args[0]);
  }


bool NavigatorImpl::NavigateToEntry(
    FrameTreeNode* frame_tree_node,
    const FrameNavigationEntry& frame_entry,
    const NavigationEntryImpl& entry,
    ReloadType reload_type,
    bool is_same_document_history_load,
    bool is_history_navigation_in_new_child,
    bool is_pending_entry,
    const scoped_refptr<ResourceRequestBodyImpl>& post_body) {
  TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");

  GURL dest_url = frame_entry.url();
  Referrer dest_referrer = frame_entry.referrer();
  if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
      entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
    dest_url = entry.GetOriginalRequestURL();
     dest_referrer = Referrer();
   }

  // Don't attempt to navigate if the virtual URL is non-empty and invalid.
  if (frame_tree_node->IsMainFrame()) {
    const GURL& virtual_url = entry.GetVirtualURL();
    if (!virtual_url.is_valid() && !virtual_url.is_empty()) {
      LOG(WARNING) << "Refusing to load for invalid virtual URL: "
                   << virtual_url.possibly_invalid_spec();
      return false;
    }
  }

   if (!dest_url.is_valid() && !dest_url.is_empty()) {
     LOG(WARNING) << "Refusing to load invalid URL: "
                 << dest_url.possibly_invalid_spec();
    return false;
  }

  if (dest_url.spec().size() > url::kMaxURLChars) {
    LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
                 << " characters.";
    return false;
  }

  base::TimeTicks navigation_start = base::TimeTicks::Now();
  TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
      "navigation,rail", "NavigationTiming navigationStart",
      TRACE_EVENT_SCOPE_GLOBAL, navigation_start);

  LoFiState lofi_state = LOFI_UNSPECIFIED;
  if (!frame_tree_node->IsMainFrame()) {
    lofi_state = frame_tree_node->frame_tree()
                     ->root()
                     ->current_frame_host()
                     ->last_navigation_lofi_state();
  } else if (reload_type == ReloadType::DISABLE_LOFI_MODE) {
    lofi_state = LOFI_OFF;
  }

  if (IsBrowserSideNavigationEnabled()) {
    navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
                                                     entry.restore_type()));
    RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
                      entry, reload_type, lofi_state,
                      is_same_document_history_load,
                      is_history_navigation_in_new_child, navigation_start);
    if (frame_tree_node->IsMainFrame() &&
        frame_tree_node->navigation_request()) {
      TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1(
          "navigation", "Navigation timeToNetworkStack",
          frame_tree_node->navigation_request()->navigation_handle(),
          navigation_start,
          "FrameTreeNode id", frame_tree_node->frame_tree_node_id());
    }

  } else {
    RenderFrameHostImpl* dest_render_frame_host =
        frame_tree_node->render_manager()->Navigate(
            dest_url, frame_entry, entry, reload_type != ReloadType::NONE);
    if (!dest_render_frame_host)
      return false;  // Unable to create the desired RenderFrameHost.

    if (is_pending_entry)
      CHECK_EQ(controller_->GetPendingEntry(), &entry);

    CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);

    bool is_transfer = entry.transferred_global_request_id().child_id != -1;
    if (is_transfer)
      dest_render_frame_host->set_is_loading(true);

    if (is_pending_entry && controller_->GetPendingEntryIndex() != -1)
      DCHECK(frame_entry.page_state().IsValid());

    bool is_transfer_to_same =
        is_transfer &&
        entry.transferred_global_request_id().child_id ==
            dest_render_frame_host->GetProcess()->GetID();
    if (!is_transfer_to_same) {
      navigation_data_.reset(new NavigationMetricsData(
          navigation_start, dest_url, entry.restore_type()));
      FrameMsg_Navigate_Type::Value navigation_type = GetNavigationType(
          controller_->GetBrowserContext(), entry, reload_type);
      dest_render_frame_host->Navigate(
          entry.ConstructCommonNavigationParams(
              frame_entry, post_body, dest_url, dest_referrer, navigation_type,
              lofi_state, navigation_start),
          entry.ConstructStartNavigationParams(),
          entry.ConstructRequestNavigationParams(
              frame_entry, is_same_document_history_load,
              is_history_navigation_in_new_child,
              entry.GetSubframeUniqueNames(frame_tree_node),
              frame_tree_node->has_committed_real_load(),
              controller_->GetPendingEntryIndex() == -1,
              controller_->GetIndexOfEntry(&entry),
              controller_->GetLastCommittedEntryIndex(),
              controller_->GetEntryCount()));
    }
  }

  if (is_pending_entry)
    CHECK_EQ(controller_->GetPendingEntry(), &entry);

  if (controller_->GetPendingEntryIndex() == -1 &&
      dest_url.SchemeIs(url::kJavaScriptScheme)) {
    return false;
  }

  if (delegate_ && is_pending_entry)
    delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);

  return true;
}


static void tricore_testboard_init(MachineState *machine, int board_id)

{

    TriCoreCPU *cpu;

    CPUTriCoreState *env;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ext_cram = g_new(MemoryRegion, 1);

    MemoryRegion *ext_dram = g_new(MemoryRegion, 1);

    MemoryRegion *int_cram = g_new(MemoryRegion, 1);

    MemoryRegion *int_dram = g_new(MemoryRegion, 1);

    MemoryRegion *pcp_data = g_new(MemoryRegion, 1);

    MemoryRegion *pcp_text = g_new(MemoryRegion, 1);

    if (!machine->cpu_model) {

        machine->cpu_model = "tc1796";

    }

    cpu = cpu_tricore_init(machine->cpu_model);

    env = &cpu->env;

    if (!cpu) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    memory_region_init_ram(ext_cram, NULL, "powerlink_ext_c.ram", 2*1024*1024, &error_abort);

    vmstate_register_ram_global(ext_cram);

    memory_region_init_ram(ext_dram, NULL, "powerlink_ext_d.ram", 4*1024*1024, &error_abort);

    vmstate_register_ram_global(ext_dram);

    memory_region_init_ram(int_cram, NULL, "powerlink_int_c.ram", 48*1024, &error_abort);

    vmstate_register_ram_global(int_cram);

    memory_region_init_ram(int_dram, NULL, "powerlink_int_d.ram", 48*1024, &error_abort);

    vmstate_register_ram_global(int_dram);

    memory_region_init_ram(pcp_data, NULL, "powerlink_pcp_data.ram", 16*1024, &error_abort);

    vmstate_register_ram_global(pcp_data);

    memory_region_init_ram(pcp_text, NULL, "powerlink_pcp_text.ram", 32*1024, &error_abort);

    vmstate_register_ram_global(pcp_text);

    memory_region_add_subregion(sysmem, 0x80000000, ext_cram);

    memory_region_add_subregion(sysmem, 0xa1000000, ext_dram);

    memory_region_add_subregion(sysmem, 0xd4000000, int_cram);

    memory_region_add_subregion(sysmem, 0xd0000000, int_dram);

    memory_region_add_subregion(sysmem, 0xf0050000, pcp_data);

    memory_region_add_subregion(sysmem, 0xf0060000, pcp_text);

    tricoretb_binfo.ram_size = machine->ram_size;

    tricoretb_binfo.kernel_filename = machine->kernel_filename;

    if (machine->kernel_filename) {

        tricore_load_kernel(env);

    }

}


f_setmatches(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
{
#ifdef FEAT_SEARCH_EXTRA
    list_T	*l;
    listitem_T	*li;
    dict_T	*d;
    list_T	*s = NULL;

    rettv->vval.v_number = -1;
    if (argvars[0].v_type != VAR_LIST)
    {
	emsg(_(e_listreq));
	return;
    }
    if ((l = argvars[0].vval.v_list) != NULL)
    {

	/* To some extent make sure that we are dealing with a list from
	 * "getmatches()". */
	li = l->lv_first;
	while (li != NULL)
	{
	    if (li->li_tv.v_type != VAR_DICT
		    || (d = li->li_tv.vval.v_dict) == NULL)
	    {
		emsg(_(e_invarg));
		return;
	    }
	    if (!(dict_find(d, (char_u *)"group", -1) != NULL
			&& (dict_find(d, (char_u *)"pattern", -1) != NULL
			    || dict_find(d, (char_u *)"pos1", -1) != NULL)
			&& dict_find(d, (char_u *)"priority", -1) != NULL
			&& dict_find(d, (char_u *)"id", -1) != NULL))
	    {
		emsg(_(e_invarg));
		return;
	    }
	    li = li->li_next;
	}

	clear_matches(curwin);
	li = l->lv_first;
	while (li != NULL)
	{
	    int		i = 0;
	    char_u	buf[5];
	    dictitem_T  *di;
	    char_u	*group;
	    int		priority;
	    int		id;
	    char_u	*conceal;

	    d = li->li_tv.vval.v_dict;
	    if (dict_find(d, (char_u *)"pattern", -1) == NULL)
	    {
		if (s == NULL)
		{
		    s = list_alloc();
		    if (s == NULL)
			return;
		}

		/* match from matchaddpos() */
		for (i = 1; i < 9; i++)
		{
		    sprintf((char *)buf, (char *)"pos%d", i);
		    if ((di = dict_find(d, (char_u *)buf, -1)) != NULL)
		    {
			if (di->di_tv.v_type != VAR_LIST)
			    return;

			list_append_tv(s, &di->di_tv);
			s->lv_refcount++;
		    }
		    else
			break;
		}
	    }

	    group = dict_get_string(d, (char_u *)"group", TRUE);
	    priority = (int)dict_get_number(d, (char_u *)"priority");
	    id = (int)dict_get_number(d, (char_u *)"id");
	    conceal = dict_find(d, (char_u *)"conceal", -1) != NULL
			      ? dict_get_string(d, (char_u *)"conceal", TRUE)
			      : NULL;
	    if (i == 0)
	    {
		match_add(curwin, group,
		    dict_get_string(d, (char_u *)"pattern", FALSE),
		    priority, id, NULL, conceal);
	    }
	    else
	    {
		match_add(curwin, group, NULL, priority, id, s, conceal);
		list_unref(s);
		s = NULL;
	    }
	    vim_free(group);
	    vim_free(conceal);

	    li = li->li_next;
	}
	rettv->vval.v_number = 0;
    }
#endif
}


nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
					struct nfsd_readdirargs *args)
{
	p = decode_fh(p, &args->fh);
	if (!p)
		return 0;
 	args->cookie = ntohl(*p++);
 	args->count  = ntohl(*p++);
 	args->count  = min_t(u32, args->count, PAGE_SIZE);
 	args->buffer = page_address(*(rqstp->rq_next_page++));

	return xdr_argsize_check(rqstp, p);
 }


static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,

                                    Error **errp)

{

    const char *path = qemu_opt_get(opts, "path");

    ChardevFile *file;

    if (path == NULL) {

        error_setg(errp, "chardev: file: no filename given");

        return;

    }

    file = backend->u.file = g_new0(ChardevFile, 1);

    qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));

    file->out = g_strdup(path);

    file->has_append = true;

    file->append = qemu_opt_get_bool(opts, "append", false);

}


int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
    BIGNUM *a, *b, *c, *d, *e;
    int i;

    a = BN_new();
    b = BN_new();
    c = BN_new();
    d = BN_new();
    e = BN_new();

    BN_one(a);
    BN_one(b);
    BN_zero(c);
    if (BN_mod_exp(d, a, b, c, ctx)) {
        fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
        return 0;
    }

    BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
    for (i = 0; i < num2; i++) {
        BN_bntest_rand(a, 20 + i * 5, 0, 0);
        BN_bntest_rand(b, 2 + i, 0, 0);

        if (!BN_mod_exp(d, a, b, c, ctx))
            return (0);

        if (bp != NULL) {
            if (!results) {
                BN_print(bp, a);
                BIO_puts(bp, " ^ ");
                BN_print(bp, b);
                BIO_puts(bp, " % ");
                BN_print(bp, c);
                BIO_puts(bp, " - ");
            }
            BN_print(bp, d);
            BIO_puts(bp, "\n");
        }
        BN_exp(e, a, b, ctx);
        BN_sub(e, e, d);
        BN_div(a, b, e, c, ctx);
        if (!BN_is_zero(b)) {
            fprintf(stderr, "Modulo exponentiation test failed!\n");
             return 0;
         }
     }
     BN_free(a);
     BN_free(b);
     BN_free(c);
    BN_zero(c);
    if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
        fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
                "succeeded\n");
        return 0;
    }

    BN_set_word(c, 16);
    if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
        fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
                "succeeded\n");
        return 0;
    }

    BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
    for (i = 0; i < num2; i++) {
        BN_bntest_rand(a, 20 + i * 5, 0, 0);
        BN_bntest_rand(b, 2 + i, 0, 0);

        if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
            return (00);

        if (bp != NULL) {
            if (!results) {
                BN_print(bp, a);
                BIO_puts(bp, " ^ ");
                BN_print(bp, b);
                BIO_puts(bp, " % ");
                BN_print(bp, c);
                BIO_puts(bp, " - ");
            }
            BN_print(bp, d);
            BIO_puts(bp, "\n");
        }
        BN_exp(e, a, b, ctx);
        BN_sub(e, e, d);
        BN_div(a, b, e, c, ctx);
        if (!BN_is_zero(b)) {
            fprintf(stderr, "Modulo exponentiation test failed!\n");
            return 0;
        }
    }
    BN_free(a);
    BN_free(b);
    BN_free(c);
    BN_free(d);
    BN_free(e);
    return (1);
}


inline void CalculateLstmGateFloat(
    const float* input, const float* input_to_gate_weights,
    const float* aux_input, const float* aux_input_to_gate_weights,
    const float* output_state, const float* recurrent_to_gate_weights,
    const float* cell_state, const float* cell_to_gate_weights,
    const float* layer_norm_coefficients, const float* gate_bias,
    const int n_batch, const int n_input, const int n_aux_input,
    const int n_output, const int n_cell,
    const TfLiteFusedActivation activation, float* gate,
    const bool is_input_all_zeros, const bool is_aux_input_all_zeros,
    Logger* logger, int intermediate_tensor_index,
    ErrorReporter* error_reporter) {
  const bool use_peephole = (cell_to_gate_weights != nullptr);
  const bool use_layer_norm = (layer_norm_coefficients != nullptr);

  // Initialize scratch buffers with bias for regular lstm or initialize with
  // zero for layer norm lstm.
  if (use_layer_norm) {
    std::fill_n(gate, n_cell * n_batch, 0.0f);
  } else {
    tensor_utils::VectorBatchVectorAssign(gate_bias, n_cell, n_batch, gate);
  }
  // For each batch and cell: compute input_weight * input.
  // Skip if input is all zeros.
  if (!is_input_all_zeros) {
    tensor_utils::MatrixBatchVectorMultiplyAccumulate(
        input_to_gate_weights, n_cell, n_input, input, n_batch, gate);
  }
  // For each batch and cell: compute aux_input_weight * aux_input.
  // Skip if auxiliary input is not available or all zeros.
  if (!is_aux_input_all_zeros) {
    tensor_utils::MatrixBatchVectorMultiplyAccumulate(aux_input_to_gate_weights,
                                                      n_cell, n_aux_input,
                                                      aux_input, n_batch, gate);
  }
  // For each batch and cell: compute recurrent_weight * output_state.
  tensor_utils::MatrixBatchVectorMultiplyAccumulate(
      recurrent_to_gate_weights, n_cell, n_output, output_state, n_batch, gate);
  // For each batch and cell: compute cell_weight .* cell_state (peephole LSTM)
  if (use_peephole) {
    tensor_utils::VectorBatchVectorCwiseProductAccumulate(
        cell_to_gate_weights, n_cell, cell_state, n_batch, gate);
  }
  // Do layer normalization (if layer norm LSTM)
  if (use_layer_norm) {
    logger->LogTensorValue(intermediate_tensor_index, gate, n_cell * n_batch,
                           error_reporter);

    tensor_utils::MeanStddevNormalization(gate, gate, n_cell, n_batch);
    tensor_utils::VectorBatchVectorCwiseProduct(layer_norm_coefficients, n_cell,
                                                gate, n_batch, gate);
    tensor_utils::VectorBatchVectorAdd(gate_bias, n_cell, n_batch, gate);
  }
  // Apply activation
  tensor_utils::ApplyActivationToVector(gate, n_batch * n_cell, activation,
                                        gate);
}


bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::OutputPicture(
    const scoped_refptr<H264Picture>& pic) {
  scoped_refptr<VaapiDecodeSurface> dec_surface =
      H264PictureToVaapiDecodeSurface(pic);

  vaapi_dec_->SurfaceReady(dec_surface);

  return true;
}


bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
{
    if (resolver.position() == endLineStart) {
        if (resolver.status() != endLineStatus)
            return false;
        return checkPaginationAndFloatsAtEndLine(layoutState);
    }

    static int numLines = 8; // The # of lines we're willing to match against.
    RootInlineBox* originalEndLine = layoutState.endLine();
    RootInlineBox* line = originalEndLine;
    for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
        if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
            if (line->lineBreakBidiStatus() != resolver.status())
                return false; // ...but the bidi state doesn't match.

            bool matched = false;
            RootInlineBox* result = line->nextRootBox();
            layoutState.setEndLine(result);
            if (result) {
                layoutState.setEndLineLogicalTop(line->lineBottomWithLeading());
                matched = checkPaginationAndFloatsAtEndLine(layoutState);
            }

            deleteLineRange(layoutState, originalEndLine, result);
            return matched;
        }
    }

    return false;
}


TabContents* Browser::AddTab(TabContentsWrapper* tab_contents,
                             PageTransition::Type type) {
  tab_handler_->GetTabStripModel()->AddTabContents(
      tab_contents, -1, type, TabStripModel::ADD_ACTIVE);
  return tab_contents->tab_contents();
}


void WallpaperManagerBase::OnPolicySet(const std::string& policy,
                                       const AccountId& account_id) {
  WallpaperInfo info;
  GetUserWallpaperInfo(account_id, &info);
  info.type = POLICY;
  SetUserWallpaperInfo(account_id, info, true /* is_persistent */);
}


Node * get_rightop ( const Expr * clause ) {
 const OpExpr * expr = ( const OpExpr * ) clause ;
 if ( list_length ( expr -> args ) >= 2 ) return lsecond ( expr -> args ) ;
 else return NULL ;
 }


static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev)
{
	struct inet6_dev *idev = __in6_dev_get(dev);

	if (!idev)
		return -ENODATA;

	if (inet6_fill_ifla6_attrs(skb, idev) < 0)
		return -EMSGSIZE;

	return 0;
}


R_API RList *r_bin_java_find_cp_const_by_val_utf8(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len) {
	RList *res = r_list_newf (free);
	ut32 *v = NULL;
	RListIter *iter;
	RBinJavaCPTypeObj *cp_obj;
	IFDBG eprintf("In UTF-8 Looking for %s\n", bytes);
	r_list_foreach (bin_obj->cp_list, iter, cp_obj) {
		if (cp_obj->tag == R_BIN_JAVA_CP_UTF8) {
			IFDBG eprintf("In UTF-8 Looking @ %s\n", cp_obj->info.cp_utf8.bytes);
			IFDBG eprintf("UTF-8 len = %d and memcmp = %d\n", cp_obj->info.cp_utf8.length, memcmp (bytes, cp_obj->info.cp_utf8.bytes, len));
			if (len == cp_obj->info.cp_utf8.length && !memcmp (bytes, cp_obj->info.cp_utf8.bytes, len)) {
				v = malloc (sizeof (ut32));
				if (!v) {
					r_list_free (res);
					return NULL;
				}
				*v = cp_obj->metas->ord;
				IFDBG eprintf("Found a match adding idx: %d\n", *v);
				r_list_append (res, v);
			}
		}
	}
	return res;
}


int64_t FromkLinuxStatFsFlags(int64_t input) {
  int64_t result = 0;

  if (input & kLinux_ST_NOSUID) result |= ST_NOSUID;
  if (input & kLinux_ST_RDONLY) result |= ST_RDONLY;
#if (defined(__USE_GNU) && __USE_GNU) || \
    (defined(__GNU_VISIBLE) && __GNU_VISIBLE)
  if (input & kLinux_ST_MANDLOCK) result |= ST_MANDLOCK;
  if (input & kLinux_ST_NOATIME) result |= ST_NOATIME;
  if (input & kLinux_ST_NODEV) result |= ST_NODEV;
  if (input & kLinux_ST_NODIRATIME) result |= ST_NODIRATIME;
  if (input & kLinux_ST_NOEXEC) result |= ST_NOEXEC;
  if (input & kLinux_ST_RELATIME) result |= ST_RELATIME;
  if (input & kLinux_ST_SYNCHRONOUS) result |= ST_SYNCHRONOUS;
#endif
  return result;
}


void test_lchown(const char *path)
{
	if (lchown(path, 0, 0) == 0) {
		fprintf(stderr, "leak at lchown of %s\n", path);
		exit(1);
	}
	if (errno != ENOENT && errno != ENOSYS) {
		fprintf(stderr, "leak at lchown of %s: errno was %s\n", path, strerror(errno));
		exit(1);
	}
}


bool IsPrintPreviewEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(kEnablePrintPreview);
}


void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
{
    int i, j;

    w = (x + w) / VNC_STAT_RECT;
    h = (y + h) / VNC_STAT_RECT;
    x /= VNC_STAT_RECT;
    y /= VNC_STAT_RECT;

    for (j = y; j <= h; j++) {
        for (i = x; i <= w; i++) {
            vs->lossy_rect[j][i] = 1;
        }
    }
}


int is_file_shm_hugepages(struct file *file)
{
	return file->f_op == &shm_file_operations_huge;
}


static netdev_tx_t vlan_dev_hard_start_xmit(struct sk_buff *skb,
					    struct net_device *dev)
{
	struct vlan_ethhdr *veth = (struct vlan_ethhdr *)(skb->data);
	unsigned int len;
	int ret;

	/* Handle non-VLAN frames if they are sent to us, for example by DHCP.
	 *
	 * NOTE: THIS ASSUMES DIX ETHERNET, SPECIFICALLY NOT SUPPORTING
	 * OTHER THINGS LIKE FDDI/TokenRing/802.3 SNAPs...
	 */
	if (veth->h_vlan_proto != htons(ETH_P_8021Q) ||
	    vlan_dev_info(dev)->flags & VLAN_FLAG_REORDER_HDR) {
		u16 vlan_tci;
		vlan_tci = vlan_dev_info(dev)->vlan_id;
		vlan_tci |= vlan_dev_get_egress_qos_mask(dev, skb);
		skb = __vlan_hwaccel_put_tag(skb, vlan_tci);
	}

	skb_set_dev(skb, vlan_dev_info(dev)->real_dev);
	len = skb->len;
	ret = dev_queue_xmit(skb);

	if (likely(ret == NET_XMIT_SUCCESS || ret == NET_XMIT_CN)) {
		struct vlan_pcpu_stats *stats;

		stats = this_cpu_ptr(vlan_dev_info(dev)->vlan_pcpu_stats);
		u64_stats_update_begin(&stats->syncp);
		stats->tx_packets++;
		stats->tx_bytes += len;
		u64_stats_update_end(&stats->syncp);
	} else {
		this_cpu_inc(vlan_dev_info(dev)->vlan_pcpu_stats->tx_dropped);
	}

	return ret;
}


static UINT8 btif_hl_get_app_id(int channel_id){
    UINT8 app_id =(UINT8) (channel_id >> 16);
    BTIF_TRACE_DEBUG("%s channel_id=0x%08x, app_id=0x%02x ", __FUNCTION__,channel_id, app_id);
 return app_id;
}


void V8Window::namedPropertyGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{

    DOMWindow* window = V8Window::toNative(info.Holder());
    if (!window)
        return;

    Frame* frame = window->frame();
    if (!frame)
        return;

    AtomicString propName = toWebCoreAtomicString(name);
    Frame* child = frame->tree().scopedChild(propName);
    if (child) {
        v8SetReturnValueFast(info, child->domWindow(), window);
        return;
    }

    if (!info.Holder()->GetRealNamedProperty(name).IsEmpty())
        return;

     Document* doc = frame->document();

     if (doc && doc->isHTMLDocument()) {
        if (toHTMLDocument(doc)->hasNamedItem(propName.impl()) || doc->hasElementWithId(propName.impl())) {
             RefPtr<HTMLCollection> items = doc->windowNamedItems(propName);
             if (!items->isEmpty()) {
                 if (items->hasExactlyOneItem()) {
                    v8SetReturnValueFast(info, items->item(0), window);
                    return;
                }
                v8SetReturnValueFast(info, items.release(), window);
                return;
            }
        }
    }
}


cpu_util(double pcpu[3])
{
    static struct timeval last;
    static clock_t clast;
    static struct rusage rlast;
    struct timeval temp;
    clock_t ctemp;
    struct rusage rtemp;
    double timediff;
    double userdiff;
    double systemdiff;

    if (pcpu == NULL) {
        gettimeofday(&last, NULL);
        clast = clock();
	getrusage(RUSAGE_SELF, &rlast);
        return;
    }

    gettimeofday(&temp, NULL);
    ctemp = clock();
    getrusage(RUSAGE_SELF, &rtemp);

    timediff = ((temp.tv_sec * 1000000.0 + temp.tv_usec) -
                (last.tv_sec * 1000000.0 + last.tv_usec));
    userdiff = ((rtemp.ru_utime.tv_sec * 1000000.0 + rtemp.ru_utime.tv_usec) -
                (rlast.ru_utime.tv_sec * 1000000.0 + rlast.ru_utime.tv_usec));
    systemdiff = ((rtemp.ru_stime.tv_sec * 1000000.0 + rtemp.ru_stime.tv_usec) -
                  (rlast.ru_stime.tv_sec * 1000000.0 + rlast.ru_stime.tv_usec));

    pcpu[0] = (((ctemp - clast) * 1000000.0 / CLOCKS_PER_SEC) / timediff) * 100;
    pcpu[1] = (userdiff / timediff) * 100;
    pcpu[2] = (systemdiff / timediff) * 100;
}


status_t MediaHTTP::initCheck() const {
 return mInitCheck;
}


static void dma_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    DMAState *s = opaque;

    uint32_t saddr;

    saddr = (addr & DMA_MASK) >> 2;

    DPRINTF("write dmareg " TARGET_FMT_plx ": 0x%8.8x -> 0x%8.8x\n", addr,

            s->dmaregs[saddr], val);

    switch (saddr) {

    case 0:

        if (val & DMA_INTREN) {

            if (val & DMA_INTR) {

                DPRINTF("Raise IRQ\n");

                qemu_irq_raise(s->irq);

            }

        } else {

            if (s->dmaregs[0] & (DMA_INTR | DMA_INTREN)) {

                DPRINTF("Lower IRQ\n");

                qemu_irq_lower(s->irq);

            }

        }

        if (val & DMA_RESET) {

            qemu_irq_raise(s->dev_reset);

            qemu_irq_lower(s->dev_reset);

        } else if (val & DMA_DRAIN_FIFO) {

            val &= ~DMA_DRAIN_FIFO;

        } else if (val == 0)

            val = DMA_DRAIN_FIFO;

        val &= 0x0fffffff;

        val |= DMA_VER;

        break;

    case 1:

        s->dmaregs[0] |= DMA_LOADED;

        break;

    default:

        break;

    }

    s->dmaregs[saddr] = val;

}


static int __init unittest_data_add(void)
{
	void *unittest_data;
	struct device_node *unittest_data_node, *np;
	/*
	 * __dtb_testcases_begin[] and __dtb_testcases_end[] are magically
	 * created by cmd_dt_S_dtb in scripts/Makefile.lib
	 */
	extern uint8_t __dtb_testcases_begin[];
	extern uint8_t __dtb_testcases_end[];
	const int size = __dtb_testcases_end - __dtb_testcases_begin;
	int rc;

	if (!size) {
		pr_warn("%s: No testcase data to attach; not running tests\n",
			__func__);
		return -ENODATA;
	}

	/* creating copy */
	unittest_data = kmemdup(__dtb_testcases_begin, size, GFP_KERNEL);
	if (!unittest_data)
		return -ENOMEM;

	of_fdt_unflatten_tree(unittest_data, NULL, &unittest_data_node);
	if (!unittest_data_node) {
		pr_warn("%s: No tree to attach; not running tests\n", __func__);
		kfree(unittest_data);
		return -ENODATA;
	}

	/*
	 * This lock normally encloses of_resolve_phandles()
	 */
	of_overlay_mutex_lock();

	rc = of_resolve_phandles(unittest_data_node);
	if (rc) {
		pr_err("%s: Failed to resolve phandles (rc=%i)\n", __func__, rc);
		of_overlay_mutex_unlock();
		return -EINVAL;
	}

	if (!of_root) {
		of_root = unittest_data_node;
		for_each_of_allnodes(np)
			__of_attach_node_sysfs(np);
		of_aliases = of_find_node_by_path("/aliases");
		of_chosen = of_find_node_by_path("/chosen");
		of_overlay_mutex_unlock();
		return 0;
	}

	/* attach the sub-tree to live tree */
	np = unittest_data_node->child;
	while (np) {
		struct device_node *next = np->sibling;

		np->parent = of_root;
		attach_node_and_children(np);
		np = next;
	}

	of_overlay_mutex_unlock();

	return 0;
}


uint32_t Context::getHeaderMapSize(HeaderMapType type) {
  auto map = getMap(type);
  if (!map) {
    return 0;
  }
  return map->refreshByteSize();
}


void IOBuf::reserveSlow(std::size_t minHeadroom, std::size_t minTailroom) {
  size_t newCapacity = (size_t)length_ + minHeadroom + minTailroom;
  DCHECK_LT(newCapacity, UINT32_MAX);

  // reserveSlow() is dangerous if anyone else is sharing the buffer, as we may
  // reallocate and free the original buffer.  It should only ever be called if
  // we are the only user of the buffer.
  DCHECK(!isSharedOne());

  // We'll need to reallocate the buffer.
  // There are a few options.
  // - If we have enough total room, move the data around in the buffer
  //   and adjust the data_ pointer.
  // - If we're using an internal buffer, we'll switch to an external
  //   buffer with enough headroom and tailroom.
  // - If we have enough headroom (headroom() >= minHeadroom) but not too much
  //   (so we don't waste memory), we can try one of two things, depending on
  //   whether we use jemalloc or not:
  //   - If using jemalloc, we can try to expand in place, avoiding a memcpy()
  //   - If not using jemalloc and we don't have too much to copy,
  //     we'll use realloc() (note that realloc might have to copy
  //     headroom + data + tailroom, see smartRealloc in folly/memory/Malloc.h)
  // - Otherwise, bite the bullet and reallocate.
  if (headroom() + tailroom() >= minHeadroom + minTailroom) {
    uint8_t* newData = writableBuffer() + minHeadroom;
    memmove(newData, data_, length_);
    data_ = newData;
    return;
  }

  size_t newAllocatedCapacity = 0;
  uint8_t* newBuffer = nullptr;
  std::size_t newHeadroom = 0;
  std::size_t oldHeadroom = headroom();

  // If we have a buffer allocated with malloc and we just need more tailroom,
  // try to use realloc()/xallocx() to grow the buffer in place.
  SharedInfo* info = sharedInfo();
  bool useHeapFullStorage = info && info->useHeapFullStorage;
  if (info && (info->freeFn == nullptr) && length_ != 0 &&
      oldHeadroom >= minHeadroom) {
    size_t headSlack = oldHeadroom - minHeadroom;
    newAllocatedCapacity = goodExtBufferSize(newCapacity + headSlack);
    if (usingJEMalloc()) {
      // We assume that tailroom is more useful and more important than
      // headroom (not least because realloc / xallocx allow us to grow the
      // buffer at the tail, but not at the head)  So, if we have more headroom
      // than we need, we consider that "wasted".  We arbitrarily define "too
      // much" headroom to be 25% of the capacity.
      if (headSlack * 4 <= newCapacity) {
        size_t allocatedCapacity = capacity() + sizeof(SharedInfo);
        void* p = buf_;
        if (allocatedCapacity >= jemallocMinInPlaceExpandable) {
          if (xallocx(p, newAllocatedCapacity, 0, 0) == newAllocatedCapacity) {
            if (io_buf_free_cb) {
              io_buf_free_cb(p, reinterpret_cast<size_t>(info->userData));
            }
            newBuffer = static_cast<uint8_t*>(p);
            newHeadroom = oldHeadroom;
            // update the userData
            info->userData = reinterpret_cast<void*>(newAllocatedCapacity);
            if (io_buf_alloc_cb) {
              io_buf_alloc_cb(newBuffer, newAllocatedCapacity);
            }
          }
          // if xallocx failed, do nothing, fall back to malloc/memcpy/free
        }
      }
    } else { // Not using jemalloc
      size_t copySlack = capacity() - length_;
      if (copySlack * 2 <= length_) {
        void* p = realloc(buf_, newAllocatedCapacity);
        if (UNLIKELY(p == nullptr)) {
          throw_exception<std::bad_alloc>();
        }
        newBuffer = static_cast<uint8_t*>(p);
        newHeadroom = oldHeadroom;
      }
    }
  }

  // None of the previous reallocation strategies worked (or we're using
  // an internal buffer).  malloc/copy/free.
  if (newBuffer == nullptr) {
    newAllocatedCapacity = goodExtBufferSize(newCapacity);
    newBuffer = static_cast<uint8_t*>(checkedMalloc(newAllocatedCapacity));
    if (length_ > 0) {
      assert(data_ != nullptr);
      memcpy(newBuffer + minHeadroom, data_, length_);
    }
    if (sharedInfo()) {
      freeExtBuffer();
    }
    newHeadroom = minHeadroom;
  }

  std::size_t cap;
  initExtBuffer(newBuffer, newAllocatedCapacity, &info, &cap);

  if (flags() & kFlagFreeSharedInfo) {
    delete sharedInfo();
  } else {
    if (useHeapFullStorage) {
      SharedInfo::releaseStorage(sharedInfo());
    }
  }

  setFlagsAndSharedInfo(0, info);
  capacity_ = cap;
  buf_ = newBuffer;
  data_ = newBuffer + newHeadroom;
  // length_ is unchanged
}


wv_csp12_opaque_literal_tag(tvbuff_t *tvb, guint32 offset,
			    const char *token, guint8 codepage _U_, guint32 *length)
{
	guint32 data_len = tvb_get_guintvar(tvb, offset, length);
	char *str = NULL;

	if ( token && ( (strcmp(token, "Code") == 0)
			|| (strcmp(token, "ContentSize") == 0)
			|| (strcmp(token, "MessageCount") == 0)
			|| (strcmp(token, "Validity") == 0)
			|| (strcmp(token, "KeepAliveTime") == 0)
			|| (strcmp(token, "TimeToLive") == 0)
			|| (strcmp(token, "AcceptedContentLength") == 0)
			|| (strcmp(token, "MultiTrans") == 0)
			|| (strcmp(token, "ParserSize") == 0)
			|| (strcmp(token, "ServerPollMin") == 0)
			|| (strcmp(token, "TCPPort") == 0)
			|| (strcmp(token, "UDPPort") == 0)
			|| (strcmp(token, "HistoryPeriod") == 0)
			|| (strcmp(token, "MaxWatcherList") == 0) ) )
		{
			str = wv_integer_from_opaque(tvb, offset + *length, data_len);
		}
	else
		if ( token && ( (strcmp(token, "DateTime") == 0)
				|| (strcmp(token, "DeliveryTime") == 0) ) )
			{
				str = wv_datetime_from_opaque(tvb, offset + *length, data_len);
			}

	if (str == NULL) { /* Error, or not parsed */
		str = wmem_strdup_printf(wmem_packet_scope(), "(%d bytes of unparsed opaque data)", data_len);
	}
	*length += data_len;
	return str;
}


static double mxEndianDouble_Swap(double a)
{
#if defined(__GNUC__) || defined(__llvm__)
	uint64_t result = __builtin_bswap64(*(uint64_t *)&a);
	return *(double *)&result;
#else
	double b;
	txU1 *p1 = (txU1 *) &a, *p2 = (txU1 *) &b;
	int i;
	for (i = 0; i < 8; i++)
		p2[i] = p1[7 - i];
	return b;
#endif
}


    void _process(
      const list<PG *> &pgs,
      ThreadPool::TPHandle &handle) override {
      assert(!pgs.empty());
      osd->process_peering_events(pgs, handle);
      for (list<PG *>::const_iterator i = pgs.begin();
	   i != pgs.end();
	   ++i) {
	(*i)->put("PeeringWQ");
      }
    }


QPCIBus *qpci_init_spapr(QGuestAllocator *alloc)

{

    QPCIBusSPAPR *ret;

    ret = g_malloc(sizeof(*ret));

    ret->alloc = alloc;

    ret->bus.io_readb = qpci_spapr_io_readb;

    ret->bus.io_readw = qpci_spapr_io_readw;

    ret->bus.io_readl = qpci_spapr_io_readl;

    ret->bus.io_writeb = qpci_spapr_io_writeb;

    ret->bus.io_writew = qpci_spapr_io_writew;

    ret->bus.io_writel = qpci_spapr_io_writel;

    ret->bus.config_readb = qpci_spapr_config_readb;

    ret->bus.config_readw = qpci_spapr_config_readw;

    ret->bus.config_readl = qpci_spapr_config_readl;

    ret->bus.config_writeb = qpci_spapr_config_writeb;

    ret->bus.config_writew = qpci_spapr_config_writew;

    ret->bus.config_writel = qpci_spapr_config_writel;

    ret->bus.iomap = qpci_spapr_iomap;

    ret->bus.iounmap = qpci_spapr_iounmap;

    /* FIXME: We assume the default location of the PHB for now.

     * Ideally we'd parse the device tree deposited in the guest to

     * get the window locations */

    ret->buid = 0x800000020000000ULL;

    ret->pio_cpu_base = SPAPR_PCI_WINDOW_BASE + SPAPR_PCI_IO_WIN_OFF;

    ret->pio.pci_base = 0;

    ret->pio.size = SPAPR_PCI_IO_WIN_SIZE;

    ret->mmio_cpu_base = SPAPR_PCI_WINDOW_BASE + SPAPR_PCI_MMIO_WIN_OFF;

    ret->mmio.pci_base = SPAPR_PCI_MEM_WIN_BUS_OFFSET;

    ret->mmio.size = SPAPR_PCI_MMIO_WIN_SIZE;

    ret->pci_hole_start = 0xC0000000;

    ret->pci_hole_size =

        ret->mmio.pci_base + ret->mmio.size - ret->pci_hole_start;

    ret->pci_hole_alloc = 0;

    ret->pci_iohole_start = 0xc000;

    ret->pci_iohole_size =

        ret->pio.pci_base + ret->pio.size - ret->pci_iohole_start;

    ret->pci_iohole_alloc = 0;

    return &ret->bus;

}


static ssize_t cdc_ncm_store_rx_max(struct device *d,  struct device_attribute *attr, const char *buf, size_t len)
{
	struct usbnet *dev = netdev_priv(to_net_dev(d));
	struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
	unsigned long val;

	if (kstrtoul(buf, 0, &val) || cdc_ncm_check_rx_max(dev, val) != val)
		return -EINVAL;

	cdc_ncm_update_rxtx_max(dev, val, ctx->tx_max);
	return len;
}


cgi_interpose_output( httpd_conn* hc, int rfd )
    {
    int r;
    char buf[1024];
    size_t headers_size, headers_len;
    char* headers;
    char* br;
    int status;
    char* title;
    char* cp;

    /* Make sure the connection is in blocking mode.  It should already
    ** be blocking, but we might as well be sure.
    */
    httpd_clear_ndelay( hc->conn_fd );

    /* Slurp in all headers. */
    headers_size = 0;
    httpd_realloc_str( &headers, &headers_size, 500 );
    headers_len = 0;
    for (;;)
	{
	r = read( rfd, buf, sizeof(buf) );
	if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) )
	    {
	    sleep( 1 );
	    continue;
	    }
	if ( r <= 0 )
	    {
	    br = &(headers[headers_len]);
	    break;
	    }
	httpd_realloc_str( &headers, &headers_size, headers_len + r );
	(void) memmove( &(headers[headers_len]), buf, r );
	headers_len += r;
	headers[headers_len] = '\0';
	if ( ( br = strstr( headers, "\015\012\015\012" ) ) != (char*) 0 ||
	     ( br = strstr( headers, "\012\012" ) ) != (char*) 0 )
	    break;
	}

    /* If there were no headers, bail. */
    if ( headers[0] == '\0' )
	return;

    /* Figure out the status.  Look for a Status: or Location: header;
    ** else if there's an HTTP header line, get it from there; else
    ** default to 200.
    */
    status = 200;
    if ( strncmp( headers, "HTTP/", 5 ) == 0 )
	{
	cp = headers;
	cp += strcspn( cp, " \t" );
	status = atoi( cp );
	}
    if ( ( cp = strstr( headers, "Status:" ) ) != (char*) 0 &&
	 cp < br &&
	 ( cp == headers || *(cp-1) == '\012' ) )
	{
	cp += 7;
	cp += strspn( cp, " \t" );
	status = atoi( cp );
	}
    else if ( ( cp = strstr( headers, "Location:" ) ) != (char*) 0 &&
	 cp < br &&
	 ( cp == headers || *(cp-1) == '\012' ) )
	status = 302;

    /* Write the status line. */
    switch ( status )
	{
	case 200: title = ok200title; break;
	case 302: title = err302title; break;
	case 304: title = err304title; break;
	case 400: title = httpd_err400title; break;
#ifdef AUTH_FILE
	case 401: title = err401title; break;
#endif /* AUTH_FILE */
	case 403: title = err403title; break;
	case 404: title = err404title; break;
	case 408: title = httpd_err408title; break;
	case 500: title = err500title; break;
	case 501: title = err501title; break;
	case 503: title = httpd_err503title; break;
	default: title = "Something"; break;
	}
    (void) my_snprintf( buf, sizeof(buf), "HTTP/1.0 %d %s\015\012", status, title );
    (void) httpd_write_fully( hc->conn_fd, buf, strlen( buf ) );

    /* Write the saved headers. */
    (void) httpd_write_fully( hc->conn_fd, headers, headers_len );

    /* Echo the rest of the output. */
    for (;;)
	{
	r = read( rfd, buf, sizeof(buf) );
	if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) )
	    {
	    sleep( 1 );
	    continue;
	    }
	if ( r <= 0 )
	    break;
	if ( httpd_write_fully( hc->conn_fd, buf, r ) != r )
	    break;
	}
    shutdown( hc->conn_fd, SHUT_WR );
    }


MagickExport const Quantum *GetVirtualPixelQueue(const Image *image)
{
  CacheInfo
    *magick_restrict cache_info;

  const int
    id = GetOpenMPThreadId();

  assert(image != (const Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  assert(image->cache != (Cache) NULL);
  cache_info=(CacheInfo *) image->cache;
  assert(cache_info->signature == MagickCoreSignature);
  if (cache_info->methods.get_virtual_pixels_handler !=
       (GetVirtualPixelsHandler) NULL)
    return(cache_info->methods.get_virtual_pixels_handler(image));
  assert(id < (int) cache_info->number_threads);
  return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id]));
}


decode_fh(__be32 *p, struct svc_fh *fhp)
{
	fh_init(fhp, NFS_FHSIZE);
	memcpy(&fhp->fh_handle.fh_base, p, NFS_FHSIZE);
	fhp->fh_handle.fh_size = NFS_FHSIZE;

	/* FIXME: Look up export pointer here and verify
	 * Sun Secure RPC if requested */
	return p + (NFS_FHSIZE >> 2);
}


  static NudgeDelayStrategy GetNudgeDelayStrategy(const ModelType& type) {
    switch (type) {
     case syncable::AUTOFILL:
       return ACCOMPANY_ONLY;
     case syncable::PREFERENCES:
     case syncable::SESSIONS:
       return CUSTOM;
     default:
       return IMMEDIATE;
    }
  }


 void send_stream_error(h2o_http2_conn_t *conn, uint32_t stream_id, int errnum)
{
    assert(stream_id != 0);
    assert(conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING);

    h2o_http2_encode_rst_stream_frame(&conn->_write.buf, stream_id, -errnum);
    h2o_http2_conn_request_write(conn);
}


bool GLES2DecoderImpl::CheckCurrentProgram(const char* function_name) {
  if (!state_.current_program.get()) {
    LOCAL_SET_GL_ERROR(
        GL_INVALID_OPERATION, function_name, "no program in use");
    return false;
  }
  if (!state_.current_program->InUse()) {
    LOCAL_SET_GL_ERROR(
        GL_INVALID_OPERATION, function_name, "program not linked");
    return false;
  }
  return true;
}


int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
				 const char *objname, u32 *out_sid)
{
	return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
				    objname, out_sid, false);
}


void RenderViewImpl::OnResize(const ResizeParams& params) {
  TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");

  if (webview()) {
    webview()->HidePopups();
    if (send_preferred_size_changes_ &&
        webview()->MainFrame()->IsWebLocalFrame()) {
      webview()->MainFrame()->ToWebLocalFrame()->SetCanHaveScrollbars(
          ShouldDisplayScrollbars(params.new_size.width(),
                                  params.new_size.height()));
    }
    if (display_mode_ != params.display_mode) {
      display_mode_ = params.display_mode;
      webview()->SetDisplayMode(display_mode_);
    }
  }

  browser_controls_shrink_blink_size_ =
      params.browser_controls_shrink_blink_size;
  top_controls_height_ = params.top_controls_height;
  bottom_controls_height_ = params.bottom_controls_height;

  if (device_scale_factor_for_testing_) {
    ResizeParams p(params);
    p.screen_info.device_scale_factor = *device_scale_factor_for_testing_;
    p.physical_backing_size =
        gfx::ScaleToCeiledSize(p.new_size, p.screen_info.device_scale_factor);
    RenderWidget::OnResize(p);
  } else {
    RenderWidget::OnResize(params);
  }

  if (params.scroll_focused_node_into_view)
    webview()->ScrollFocusedEditableElementIntoView();
}


void CLASS parse_kodak_ifd (int base)
{
  unsigned entries, tag, type, len, save;
  int i, c, wbi=-2;
  float mul[3]={1,1,1}, num;
  static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };

  entries = get2();
  if (entries > 1024) return;
  INT64 fsize = ifp->size();
  while (entries--) {
    tiff_get (base, &tag, &type, &len, &save);
    INT64 savepos = ftell(ifp);
    if(len > 8 && len + savepos > 2*fsize) continue;
    if(callbacks.exif_cb)
      {
        callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp);
        fseek(ifp,savepos,SEEK_SET);
      }
    if (tag == 1011) imgdata.other.FlashEC = getreal(type);
    if (tag == 1020) wbi = getint(type);
    if (tag == 1021 && len == 72) {		/* WB set in software */
      fseek (ifp, 40, SEEK_CUR);
      FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2());
      wbi = -2;
    }

    if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
    if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
    if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
    if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
    if (tag == 0x0e93) imgdata.color.linear_max[0] =
                         imgdata.color.linear_max[1] =
                         imgdata.color.linear_max[2] =
                         imgdata.color.linear_max[3] = get2();
        if (tag == 0x09ce)
		stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp);
        if (tag == 0xfa00)
		stmread(imgdata.shootinginfo.BodySerial, len, ifp);
	if (tag == 0xfa27)
	  {
                FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
                imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
	  }
	if (tag == 0xfa28)
	  {
                FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
                imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
	  }
	if (tag == 0xfa29)
	  {
                FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
                imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
	  }
	if (tag == 0xfa2a)
	  {
            FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
            imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
	  }

    if (tag == 2120 + wbi ||
        (wbi<0 && tag == 2125))  /* use Auto WB if illuminant index is not set */
      {
        FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num;
        FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */
      }
    if (tag == 2317) linear_table (len);
    if (tag == 0x903) iso_speed = getreal(type);
    //if (tag == 6020) iso_speed = getint(type);
    if (tag == 64013) wbi = fgetc(ifp);
    if ((unsigned) wbi < 7 && tag == wbtag[wbi])
      FORC3 cam_mul[c] = get4();
    if (tag == 64019) width = getint(type);
    if (tag == 64020) height = (getint(type)+1) & -2;
    fseek (ifp, save, SEEK_SET);
  }
}


static int _get_transform_coeffs(uint8_t *exps, uint8_t *bap, float chcoeff,

        float *samples, int start, int end, int dith_flag, GetBitContext *gb,

        dither_state *state)

{

    int16_t mantissa;

    int i;

    int gcode;

    mant_group l3_grp, l5_grp, l11_grp;

    for (i = 0; i < 3; i++)

        l3_grp.gcodes[i] = l5_grp.gcodes[i] = l11_grp.gcodes[i] = -1;

    l3_grp.gcptr = l5_grp.gcptr = 3;

    l11_grp.gcptr = 2;

    i = 0;

    while (i < start)

        samples[i++] = 0;

    for (i = start; i < end; i++) {

        switch (bap[i]) {

            case 0:

                if (!dith_flag)

                    mantissa = 0;

                else

                    mantissa = dither_int16(state);

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 1:

                if (l3_grp.gcptr > 2) {

                    gcode = get_bits(gb, qntztab[1]);

                    if (gcode > 26)

                        return -1;

                    l3_grp.gcodes[0] = gcode / 9;

                    l3_grp.gcodes[1] = (gcode % 9) / 3;

                    l3_grp.gcodes[2] = (gcode % 9) % 3;

                    l3_grp.gcptr = 0;

                }

                mantissa = l3_q_tab[l3_grp.gcodes[l3_grp.gcptr++]];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 2:

                if (l5_grp.gcptr > 2) {

                    gcode = get_bits(gb, qntztab[2]);

                    if (gcode > 124)

                        return -1;

                    l5_grp.gcodes[0] = gcode / 25;

                    l5_grp.gcodes[1] = (gcode % 25) / 5;

                    l5_grp.gcodes[2] = (gcode % 25) % 5;

                    l5_grp.gcptr = 0;

                }

                mantissa = l5_q_tab[l5_grp.gcodes[l5_grp.gcptr++]];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 3:

                mantissa = get_bits(gb, qntztab[3]);

                if (mantissa > 6)

                    return -1;

                mantissa = l7_q_tab[mantissa];

                samples[i] = to_float(exps[i], mantissa);

                break;

            case 4:

                if (l11_grp.gcptr > 1) {

                    gcode = get_bits(gb, qntztab[4]);

                    if (gcode > 120)

                        return -1;

                    l11_grp.gcodes[0] = gcode / 11;

                    l11_grp.gcodes[1] = gcode % 11;

                }

                mantissa = l11_q_tab[l11_grp.gcodes[l11_grp.gcptr++]];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 5:

                mantissa = get_bits(gb, qntztab[5]);

                if (mantissa > 14)

                    return -1;

                mantissa = l15_q_tab[mantissa];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            default:

                mantissa = get_bits(gb, qntztab[bap[i]]) << (16 - qntztab[bap[i]]);

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

        }

    }

    i = end;

    while (i < 256)

        samples[i++] = 0;

    return 0;

}


MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
{
#define EnhanceImageTag  "Enhance/Image"
#define EnhancePixel(weight) \
  mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
  distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
  distance_squared=(4.0+mean)*distance*distance; \
  mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
  distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
  distance_squared+=(7.0-mean)*distance*distance; \
  mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
  distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
  distance_squared+=(5.0-mean)*distance*distance; \
  mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
  distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
  distance_squared+=(5.0-mean)*distance*distance; \
  mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
  distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
  distance_squared+=(5.0-mean)*distance*distance; \
  if (distance_squared < 0.069) \
    { \
      aggregate.red+=(weight)*GetPixelRed(image,r); \
      aggregate.green+=(weight)*GetPixelGreen(image,r); \
      aggregate.blue+=(weight)*GetPixelBlue(image,r); \
      aggregate.black+=(weight)*GetPixelBlack(image,r); \
      aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \
      total_weight+=(weight); \
    } \
  r+=GetPixelChannels(image);

  CacheView
    *enhance_view,
    *image_view;

  Image
    *enhance_image;

  MagickBooleanType
    status;

  MagickOffsetType
    progress;

  ssize_t
    y;

  /*
    Initialize enhanced image attributes.
  */
  assert(image != (const Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  enhance_image=CloneImage(image,0,0,MagickTrue,
    exception);
  if (enhance_image == (Image *) NULL)
    return((Image *) NULL);
  if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
    {
      enhance_image=DestroyImage(enhance_image);
      return((Image *) NULL);
    }
  /*
    Enhance image.
  */
  status=MagickTrue;
  progress=0;
  image_view=AcquireVirtualCacheView(image,exception);
  enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static) shared(progress,status) \
    magick_number_threads(image,enhance_image,image->rows,1)
#endif
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    PixelInfo
      pixel;

    register const Quantum
      *magick_restrict p;

    register Quantum
      *magick_restrict q;

    register ssize_t
      x;

    ssize_t
      center;

    if (status == MagickFalse)
      continue;
    p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
    q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
      exception);
    if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
      {
        status=MagickFalse;
        continue;
      }
    center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2);
    GetPixelInfo(image,&pixel);
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      double
        distance,
        distance_squared,
        mean,
        total_weight;

      PixelInfo
        aggregate;

      register const Quantum
        *magick_restrict r;

      GetPixelInfo(image,&aggregate);
      total_weight=0.0;
      GetPixelInfoPixel(image,p+center,&pixel);
      r=p;
      EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
        EnhancePixel(8.0); EnhancePixel(5.0);
      r=p+GetPixelChannels(image)*(image->columns+4);
      EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
        EnhancePixel(20.0); EnhancePixel(8.0);
      r=p+2*GetPixelChannels(image)*(image->columns+4);
      EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
        EnhancePixel(40.0); EnhancePixel(10.0);
      r=p+3*GetPixelChannels(image)*(image->columns+4);
      EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
        EnhancePixel(20.0); EnhancePixel(8.0);
      r=p+4*GetPixelChannels(image)*(image->columns+4);
      EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
        EnhancePixel(8.0); EnhancePixel(5.0);
      if (total_weight > MagickEpsilon)
        {
          pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
          pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
          pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
          pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
          pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
        }
      SetPixelViaPixelInfo(enhance_image,&pixel,q);
      p+=GetPixelChannels(image);
      q+=GetPixelChannels(enhance_image);
    }
    if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
      status=MagickFalse;
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
      {
        MagickBooleanType
          proceed;

#if defined(MAGICKCORE_OPENMP_SUPPORT)
        #pragma omp atomic
#endif
        progress++;
        proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows);
        if (proceed == MagickFalse)
          status=MagickFalse;
      }
  }
  enhance_view=DestroyCacheView(enhance_view);
  image_view=DestroyCacheView(image_view);
  if (status == MagickFalse)
    enhance_image=DestroyImage(enhance_image);
  return(enhance_image);
}


static void convert_path_to_forward_slashes(char *fname)
{
  while (*fname)
  {
    if (*fname == '\\')
      *fname= '/';
    fname++;
  }
}


ClientUsageTracker::~ClientUsageTracker() {
  if (special_storage_policy_)
    special_storage_policy_->RemoveObserver(this);
}


size_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)

{

    size_t offset = 0;

    if (qemu_in_coroutine()) {

        if (do_read) {

            return qemu_co_recv(fd, buffer, size);

        } else {

            return qemu_co_send(fd, buffer, size);

        }

    }

    while (offset < size) {

        ssize_t len;

        if (do_read) {

            len = qemu_recv(fd, buffer + offset, size - offset, 0);

        } else {

            len = send(fd, buffer + offset, size - offset, 0);

        }

        if (len == -1)

            errno = socket_error();

        /* recoverable error */

        if (len == -1 && (errno == EAGAIN || errno == EINTR)) {

            continue;

        }

        /* eof */

        if (len == 0) {

            break;

        }

        /* unrecoverable error */

        if (len == -1) {

            return 0;

        }

        offset += len;

    }

    return offset;

}


  void write(bool value) {
    const char *str_value = value ? "true" : "false";
    Arg::StringValue<char> str = { str_value, std::strlen(str_value) };
    writer_.write_str(str, spec_);
  }


static int __init tcp_illinois_register(void)
{
	BUILD_BUG_ON(sizeof(struct illinois) > ICSK_CA_PRIV_SIZE);
	return tcp_register_congestion_control(&tcp_illinois);
}


__ip_vs_get_timeouts(struct net *net, struct ip_vs_timeout_user *u)
{
#if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
	struct ip_vs_proto_data *pd;
#endif

#ifdef CONFIG_IP_VS_PROTO_TCP
	pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
	u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ;
	u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ;
#endif
#ifdef CONFIG_IP_VS_PROTO_UDP
	pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
	u->udp_timeout =
			pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ;
#endif
}


static int show_slave_received_heartbeats(THD *thd, SHOW_VAR *var, char *buff)
{
  if (active_mi)
  {
    var->type= SHOW_LONGLONG;
    var->value= buff;
    *((longlong *)buff)= active_mi->received_heartbeats;
  }
  else
    var->type= SHOW_UNDEF;
  return 0;
}


int do_ssl3_write ( SSL * s , int type , const unsigned char * buf , unsigned int * pipelens , unsigned int numpipes , int create_empty_fragment ) {
 unsigned char * outbuf [ SSL_MAX_PIPELINES ] , * plen [ SSL_MAX_PIPELINES ] ;
 SSL3_RECORD wr [ SSL_MAX_PIPELINES ] ;
 int i , mac_size , clear = 0 ;
 int prefix_len = 0 ;
 int eivlen ;
 size_t align = 0 ;
 SSL3_BUFFER * wb ;
 SSL_SESSION * sess ;
 unsigned int totlen = 0 ;
 unsigned int j ;
 for ( j = 0 ;
 j < numpipes ;
 j ++ ) totlen += pipelens [ j ] ;
 if ( RECORD_LAYER_write_pending ( & s -> rlayer ) ) return ( ssl3_write_pending ( s , type , buf , totlen ) ) ;
 if ( s -> s3 -> alert_dispatch ) {
 i = s -> method -> ssl_dispatch_alert ( s ) ;
 if ( i <= 0 ) return ( i ) ;
 }
 if ( s -> rlayer . numwpipes < numpipes ) if ( ! ssl3_setup_write_buffer ( s , numpipes , 0 ) ) return - 1 ;
 if ( totlen == 0 && ! create_empty_fragment ) return 0 ;
 sess = s -> session ;
 if ( ( sess == NULL ) || ( s -> enc_write_ctx == NULL ) || ( EVP_MD_CTX_md ( s -> write_hash ) == NULL ) ) {
 clear = s -> enc_write_ctx ? 0 : 1 ;
 mac_size = 0 ;
 }
 else {
 mac_size = EVP_MD_CTX_size ( s -> write_hash ) ;
 if ( mac_size < 0 ) goto err ;
 }
 if ( ! clear && ! create_empty_fragment && ! s -> s3 -> empty_fragment_done ) {
 if ( s -> s3 -> need_empty_fragments && type == SSL3_RT_APPLICATION_DATA ) {
 unsigned int tmppipelen = 0 ;
 prefix_len = do_ssl3_write ( s , type , buf , & tmppipelen , 1 , 1 ) ;
 if ( prefix_len <= 0 ) goto err ;
 if ( prefix_len > ( SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD ) ) {
 SSLerr ( SSL_F_DO_SSL3_WRITE , ERR_R_INTERNAL_ERROR ) ;
 goto err ;
 }
 }
 s -> s3 -> empty_fragment_done = 1 ;
 }
 if ( create_empty_fragment ) {
 wb = & s -> rlayer . wbuf [ 0 ] ;
 # if defined ( SSL3_ALIGN_PAYLOAD ) && SSL3_ALIGN_PAYLOAD != 0 align = ( size_t ) SSL3_BUFFER_get_buf ( wb ) + 2 * SSL3_RT_HEADER_LENGTH ;
 align = SSL3_ALIGN_PAYLOAD - 1 - ( ( align - 1 ) % SSL3_ALIGN_PAYLOAD ) ;
 # endif outbuf [ 0 ] = SSL3_BUFFER_get_buf ( wb ) + align ;
 SSL3_BUFFER_set_offset ( wb , align ) ;
 }
 else if ( prefix_len ) {
 wb = & s -> rlayer . wbuf [ 0 ] ;
 outbuf [ 0 ] = SSL3_BUFFER_get_buf ( wb ) + SSL3_BUFFER_get_offset ( wb ) + prefix_len ;
 }
 else {
 for ( j = 0 ;
 j < numpipes ;
 j ++ ) {
 wb = & s -> rlayer . wbuf [ j ] ;
 # if defined ( SSL3_ALIGN_PAYLOAD ) && SSL3_ALIGN_PAYLOAD != 0 align = ( size_t ) SSL3_BUFFER_get_buf ( wb ) + SSL3_RT_HEADER_LENGTH ;
 align = SSL3_ALIGN_PAYLOAD - 1 - ( ( align - 1 ) % SSL3_ALIGN_PAYLOAD ) ;
 # endif outbuf [ j ] = SSL3_BUFFER_get_buf ( wb ) + align ;
 SSL3_BUFFER_set_offset ( wb , align ) ;
 }
 }
 if ( s -> enc_write_ctx && SSL_USE_EXPLICIT_IV ( s ) ) {
 int mode = EVP_CIPHER_CTX_mode ( s -> enc_write_ctx ) ;
 if ( mode == EVP_CIPH_CBC_MODE ) {
 eivlen = EVP_CIPHER_CTX_iv_length ( s -> enc_write_ctx ) ;
 if ( eivlen <= 1 ) eivlen = 0 ;
 }
 else if ( mode == EVP_CIPH_GCM_MODE ) eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN ;
 else if ( mode == EVP_CIPH_CCM_MODE ) eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN ;
 else eivlen = 0 ;
 }
 else eivlen = 0 ;
 totlen = 0 ;
 memset ( wr , 0 , sizeof wr ) ;
 for ( j = 0 ;
 j < numpipes ;
 j ++ ) {
 * ( outbuf [ j ] ++ ) = type & 0xff ;
 SSL3_RECORD_set_type ( & wr [ j ] , type ) ;
 * ( outbuf [ j ] ++ ) = ( s -> version >> 8 ) ;
 if ( SSL_get_state ( s ) == TLS_ST_CW_CLNT_HELLO && ! s -> renegotiate && TLS1_get_version ( s ) > TLS1_VERSION ) * ( outbuf [ j ] ++ ) = 0x1 ;
 else * ( outbuf [ j ] ++ ) = s -> version & 0xff ;
 plen [ j ] = outbuf [ j ] ;
 outbuf [ j ] += 2 ;
 SSL3_RECORD_set_data ( & wr [ j ] , outbuf [ j ] + eivlen ) ;
 SSL3_RECORD_set_length ( & wr [ j ] , ( int ) pipelens [ j ] ) ;
 SSL3_RECORD_set_input ( & wr [ j ] , ( unsigned char * ) & buf [ totlen ] ) ;
 totlen += pipelens [ j ] ;
 if ( s -> compress != NULL ) {
 if ( ! ssl3_do_compress ( s , & wr [ j ] ) ) {
 SSLerr ( SSL_F_DO_SSL3_WRITE , SSL_R_COMPRESSION_FAILURE ) ;
 goto err ;
 }
 }
 else {
 memcpy ( wr [ j ] . data , wr [ j ] . input , wr [ j ] . length ) ;
 SSL3_RECORD_reset_input ( & wr [ j ] ) ;
 }
 if ( ! SSL_USE_ETM ( s ) && mac_size != 0 ) {
 if ( s -> method -> ssl3_enc -> mac ( s , & wr [ j ] , & ( outbuf [ j ] [ wr [ j ] . length + eivlen ] ) , 1 ) < 0 ) goto err ;
 SSL3_RECORD_add_length ( & wr [ j ] , mac_size ) ;
 }
 SSL3_RECORD_set_data ( & wr [ j ] , outbuf [ j ] ) ;
 SSL3_RECORD_reset_input ( & wr [ j ] ) ;
 if ( eivlen ) {
 SSL3_RECORD_add_length ( & wr [ j ] , eivlen ) ;
 }
 }
 if ( s -> method -> ssl3_enc -> enc ( s , wr , numpipes , 1 ) < 1 ) goto err ;
 for ( j = 0 ;
 j < numpipes ;
 j ++ ) {
 if ( SSL_USE_ETM ( s ) && mac_size != 0 ) {
 if ( s -> method -> ssl3_enc -> mac ( s , & wr [ j ] , outbuf [ j ] + wr [ j ] . length , 1 ) < 0 ) goto err ;
 SSL3_RECORD_add_length ( & wr [ j ] , mac_size ) ;
 }
 s2n ( SSL3_RECORD_get_length ( & wr [ j ] ) , plen [ j ] ) ;
 if ( s -> msg_callback ) s -> msg_callback ( 1 , 0 , SSL3_RT_HEADER , plen [ j ] - 5 , 5 , s , s -> msg_callback_arg ) ;
 SSL3_RECORD_set_type ( & wr [ j ] , type ) ;
 SSL3_RECORD_add_length ( & wr [ j ] , SSL3_RT_HEADER_LENGTH ) ;
 if ( create_empty_fragment ) {
 if ( j > 0 ) {
 SSLerr ( SSL_F_DO_SSL3_WRITE , ERR_R_INTERNAL_ERROR ) ;
 goto err ;
 }
 return SSL3_RECORD_get_length ( wr ) ;
 }
 SSL3_BUFFER_set_left ( & s -> rlayer . wbuf [ j ] , prefix_len + SSL3_RECORD_get_length ( & wr [ j ] ) ) ;
 }
 s -> rlayer . wpend_tot = totlen ;
 s -> rlayer . wpend_buf = buf ;
 s -> rlayer . wpend_type = type ;
 s -> rlayer . wpend_ret = totlen ;
 return ssl3_write_pending ( s , type , buf , totlen ) ;
 err : return - 1 ;
 }


void PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length )
{

	static const size_t kMinPSIRSize = 12;	// 4+2+1+1+4

	this->DeleteExistingInfo();
	this->fileParsed = true;
	if ( length == 0 ) return;

	XMP_Int64 psirOrigin = fileRef->Offset();	// Need this to determine the resource data offsets.
	XMP_Int64 fileEnd = psirOrigin + length;

	char nameBuffer [260];	// The name is a PString, at 1+255+1 including length and pad.

	while ( fileRef->Offset() < fileEnd ) {

		if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break;	// Bad image resource.

		XMP_Int64 thisRsrcPos = fileRef->Offset();

		XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef );
		XMP_Uns16 id   = XIO::ReadUns16_BE ( fileRef );

		XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef );	// ! The length for the Pascal string.
		XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE;	// ! Round up to an even total. Yes, +2!
		if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break;	// Bad image resource.

		nameBuffer[0] = nameLen;
		fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 );	// Include the pad byte, present for zero nameLen.

 		XMP_Uns32 dataLen   = XIO::ReadUns32_BE ( fileRef );
 		XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL);	// Round up to an even total.
 		if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break;	// Bad image resource.

 		XMP_Int64 thisDataPos = fileRef->Offset();
			continue;
		}

		InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased );
		InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id );
		if ( rsrcPos == this->imgRsrcs.end() ) {
			rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) );
		} else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) {
			rsrcPos->second = newInfo;
		} else {
			fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
			continue;
		}
		InternalRsrcInfo* rsrcPtr = &rsrcPos->second;

		rsrcPtr->origOffset = (XMP_Uns32)thisDataPos;

		if ( nameLen > 0 ) {
			rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen );
			if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
			memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen );	// AUDIT: Safe, allocated enough bytes above.
		}

		if ( ! IsMetadataImgRsrc ( id ) ) {
			fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart );
			continue;
		}

		rsrcPtr->dataPtr = malloc ( dataTotal );	// ! Allocate after the IsMetadataImgRsrc check.
		if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory );
		fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal );

	}


static my_bool get_pidfile(MYSQL *mysql, char *pidfile)
{
  MYSQL_RES* result;

  if (mysql_query(mysql, "SHOW VARIABLES LIKE 'pid_file'"))
  {
    my_printf_error(0, "query failed; error: '%s'", error_flags,
		    mysql_error(mysql));
  }
  result = mysql_store_result(mysql);
  if (result)
  {
    MYSQL_ROW row=mysql_fetch_row(result);
    if (row)
      my_stpcpy(pidfile, row[1]);
    mysql_free_result(result);
    return row == 0;				/* Error if row = 0 */
  }
  return 1;					/* Error */
}


void V8DOMWrapper::setJSWrapperForDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
{
    ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
#ifndef NDEBUG
    V8ClassIndex::V8WrapperType type = V8DOMWrapper::domWrapperType(wrapper);
    switch (type) {
#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
        ACTIVE_DOM_OBJECT_TYPES(MAKE_CASE)
        ASSERT_NOT_REACHED();
#undef MAKE_CASE
    default:
        break;
    }
#endif
    getDOMObjectMap().set(object, wrapper);
}


static void ReflectReflectedNameAttributeTestAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Local<v8::Object> holder = info.Holder();

  TestObject* impl = V8TestObject::ToImpl(holder);

  V8SetReturnValueFast(info, impl->FastGetAttribute(html_names::kReflectedNameAttributeAttr), impl);
}


static int vti_init_vpd(struct kvm_vcpu *vcpu)
{
	int i;
	union cpuid3_t cpuid3;
	struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd);

	if (IS_ERR(vpd))
		return PTR_ERR(vpd);

	/* CPUID init */
	for (i = 0; i < 5; i++)
		vpd->vcpuid[i] = ia64_get_cpuid(i);

	/* Limit the CPUID number to 5 */
	cpuid3.value = vpd->vcpuid[3];
	cpuid3.number = 4;	/* 5 - 1 */
	vpd->vcpuid[3] = cpuid3.value;

	/*Set vac and vdc fields*/
	vpd->vac.a_from_int_cr = 1;
	vpd->vac.a_to_int_cr = 1;
	vpd->vac.a_from_psr = 1;
	vpd->vac.a_from_cpuid = 1;
	vpd->vac.a_cover = 1;
	vpd->vac.a_bsw = 1;
	vpd->vac.a_int = 1;
	vpd->vdc.d_vmsw = 1;

	/*Set virtual buffer*/
	vpd->virt_env_vaddr = KVM_VM_BUFFER_BASE;

	return 0;
}


static void x86_cpu_apic_create(X86CPU *cpu, Error **errp)

{

    DeviceState *dev = DEVICE(cpu);

    APICCommonState *apic;

    const char *apic_type = "apic";

    if (kvm_irqchip_in_kernel()) {

        apic_type = "kvm-apic";

    } else if (xen_enabled()) {

        apic_type = "xen-apic";

    }

    cpu->apic_state = qdev_try_create(qdev_get_parent_bus(dev), apic_type);

    if (cpu->apic_state == NULL) {

        error_setg(errp, "APIC device '%s' could not be created", apic_type);

        return;

    }

    object_property_add_child(OBJECT(cpu), "apic",

                              OBJECT(cpu->apic_state), NULL);

    qdev_prop_set_uint8(cpu->apic_state, "id", cpu->apic_id);

    /* TODO: convert to link<> */

    apic = APIC_COMMON(cpu->apic_state);

    apic->cpu = cpu;

    apic->apicbase = APIC_DEFAULT_ADDRESS | MSR_IA32_APICBASE_ENABLE;

}


isonsap_string(netdissect_options *ndo, const u_char *nsap,
	       register u_int nsap_length)
{
	register u_int nsap_idx;
	register char *cp;
	register struct enamemem *tp;

	if (nsap_length < 1 || nsap_length > ISONSAP_MAX_LENGTH)
		return ("isonsap_string: illegal length");

	tp = lookup_nsap(ndo, nsap, nsap_length);
	if (tp->e_name)
		return tp->e_name;

	tp->e_name = cp = (char *)malloc(sizeof("xx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xx"));
	if (cp == NULL)
		(*ndo->ndo_error)(ndo, "isonsap_string: malloc");

	for (nsap_idx = 0; nsap_idx < nsap_length; nsap_idx++) {
		*cp++ = hex[*nsap >> 4];
		*cp++ = hex[*nsap++ & 0xf];
		if (((nsap_idx & 1) == 0) &&
		     (nsap_idx + 1 < nsap_length)) {
		     	*cp++ = '.';
		}
	}
	*cp = '\0';
	return (tp->e_name);
}


 void SaveCCInfoConfirmInfoBar::ViewHierarchyChanged(bool is_add,
                                                     views::View* parent,
                                                     views::View* child) {
  InfoBarView::ViewHierarchyChanged(is_add, parent, child);
   if (is_add && child == this && !initialized_) {
     Init();
     initialized_ = true;
  }
}


static int show_traces_open(struct inode *inode, struct file *file)
{
	struct trace_array *tr = inode->i_private;
	struct seq_file *m;
	int ret;

	if (tracing_disabled)
		return -ENODEV;

	ret = seq_open(file, &show_traces_seq_ops);
	if (ret)
		return ret;

	m = file->private_data;
	m->private = tr;

	return 0;
}


ast2obj_slice(void* _o)
{
    slice_ty o = (slice_ty)_o;
    PyObject *result = NULL, *value = NULL;
    if (!o) {
        Py_RETURN_NONE;
    }

    switch (o->kind) {
    case Slice_kind:
        result = PyType_GenericNew(Slice_type, NULL, NULL);
        if (!result) goto failed;
        value = ast2obj_expr(o->v.Slice.lower);
        if (!value) goto failed;
        if (_PyObject_SetAttrId(result, &PyId_lower, value) == -1)
            goto failed;
        Py_DECREF(value);
        value = ast2obj_expr(o->v.Slice.upper);
        if (!value) goto failed;
        if (_PyObject_SetAttrId(result, &PyId_upper, value) == -1)
            goto failed;
        Py_DECREF(value);
        value = ast2obj_expr(o->v.Slice.step);
        if (!value) goto failed;
        if (_PyObject_SetAttrId(result, &PyId_step, value) == -1)
            goto failed;
        Py_DECREF(value);
        break;
    case ExtSlice_kind:
        result = PyType_GenericNew(ExtSlice_type, NULL, NULL);
        if (!result) goto failed;
        value = ast2obj_list(o->v.ExtSlice.dims, ast2obj_slice);
        if (!value) goto failed;
        if (_PyObject_SetAttrId(result, &PyId_dims, value) == -1)
            goto failed;
        Py_DECREF(value);
        break;
    case Index_kind:
        result = PyType_GenericNew(Index_type, NULL, NULL);
        if (!result) goto failed;
        value = ast2obj_expr(o->v.Index.value);
        if (!value) goto failed;
        if (_PyObject_SetAttrId(result, &PyId_value, value) == -1)
            goto failed;
        Py_DECREF(value);
        break;
    }
    return result;
failed:
    Py_XDECREF(value);
    Py_XDECREF(result);
    return NULL;
}


void visit_type_uint64(Visitor *v, uint64_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (v->type_uint64) {

        v->type_uint64(v, obj, name, errp);

    } else {

        value = *obj;

        v->type_int64(v, &value, name, errp);

        *obj = value;

    }

}


static inline int get_compat_mq_attr(struct mq_attr *attr,
			const struct compat_mq_attr __user *uattr)
{
	struct compat_mq_attr v;

	if (copy_from_user(&v, uattr, sizeof(*uattr)))
		return -EFAULT;

	memset(attr, 0, sizeof(*attr));
	attr->mq_flags = v.mq_flags;
	attr->mq_maxmsg = v.mq_maxmsg;
	attr->mq_msgsize = v.mq_msgsize;
	attr->mq_curmsgs = v.mq_curmsgs;
	return 0;
}


GBool DCTStream::readAdobeMarker() {
  int length, i;
  char buf[12];
  int c;

  length = read16();
  if (length < 14) {
    goto err;
  }
  for (i = 0; i < 12; ++i) {
    if ((c = str->getChar()) == EOF) {
      goto err;
    }
    buf[i] = c;
  }
  if (strncmp(buf, "Adobe", 5)) {
    goto err;
  }
  colorXform = buf[11];
  gotAdobeMarker = gTrue;
  for (i = 14; i < length; ++i) {
    if (str->getChar() == EOF) {
      goto err;
    }
  }
  return gTrue;

 err:
  error(errSyntaxError, getPos(), "Bad DCT Adobe APP14 marker");
  return gFalse;
}


uint16_t ksz9131ReadPhyReg(NetInterface *interface, uint8_t address)
{
   uint16_t data;

   //Read the specified PHY register
   if(interface->smiDriver != NULL)
   {
      data = interface->smiDriver->readPhyReg(SMI_OPCODE_READ,
         interface->phyAddr, address);
   }
   else
   {
      data = interface->nicDriver->readPhyReg(SMI_OPCODE_READ,
         interface->phyAddr, address);
   }

   //Return the value of the PHY register
   return data;
}


static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
			unsigned long addr, pte_t ptent, swp_entry_t *entry)
{
	struct page *page = NULL;
	struct inode *inode;
	struct address_space *mapping;
	pgoff_t pgoff;

	if (!vma->vm_file) /* anonymous vma */
		return NULL;
	if (!move_file())
		return NULL;

	inode = vma->vm_file->f_path.dentry->d_inode;
	mapping = vma->vm_file->f_mapping;
	if (pte_none(ptent))
		pgoff = linear_page_index(vma, addr);
	else /* pte_file(ptent) is true */
		pgoff = pte_to_pgoff(ptent);

	/* page is moved even if it's not RSS of this task(page-faulted). */
	page = find_get_page(mapping, pgoff);

#ifdef CONFIG_SWAP
	/* shmem/tmpfs may report page out on swap: account for that too. */
	if (radix_tree_exceptional_entry(page)) {
		swp_entry_t swap = radix_to_swp_entry(page);
		if (do_swap_account)
			*entry = swap;
		page = find_get_page(&swapper_space, swap.val);
	}
#endif
	return page;
}


callout_func_list_add(CalloutNameListType* s, int* rid)
{
  if (s->n >= s->alloc) {
    int new_size = s->alloc * 2;
    CalloutNameListEntry* nv = (CalloutNameListEntry* )
      xrealloc(s->v, sizeof(CalloutNameListEntry) * new_size);
    if (IS_NULL(nv)) return ONIGERR_MEMORY;

    s->alloc = new_size;
    s->v = nv;
  }

  *rid = s->n;

  xmemset(&(s->v[s->n]), 0, sizeof(*(s->v)));
  s->n++;
  return ONIG_NORMAL;
}


tBTA_HH_RPT_CACHE_ENTRY * bta_hh_le_co_cache_load (BD_ADDR remote_bda,
                                                   UINT8 *p_num_rpt, UINT8 app_id)
{
    UNUSED(app_id);

 unsigned idx = 0;

 bdstr_t bdstr;
    sprintf(bdstr, "%02x:%02x:%02x:%02x:%02x:%02x",
        remote_bda[0], remote_bda[1], remote_bda[2],
        remote_bda[3], remote_bda[4], remote_bda[5]);

 size_t len = btif_config_get_bin_length(bdstr, "HidReport");
 if (!p_num_rpt && len < sizeof(tBTA_HH_RPT_CACHE_ENTRY))
 return NULL;

 if (len > sizeof(sReportCache))
        len = sizeof(sReportCache);
    btif_config_get_bin(bdstr, "HidReport", (uint8_t *)sReportCache, &len);
 *p_num_rpt = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);

    BTIF_TRACE_DEBUG("%s() - Loaded %d reports; dev=%s", __FUNCTION__, *p_num_rpt, bdstr);

 return sReportCache;
}


xmlReadFd(int fd, const char *URL, const char *encoding, int options)
{
    xmlParserCtxtPtr ctxt;
    xmlParserInputBufferPtr input;
    xmlParserInputPtr stream;

    if (fd < 0)
        return (NULL);
    xmlInitParser();

    input = xmlParserInputBufferCreateFd(fd, XML_CHAR_ENCODING_NONE);
    if (input == NULL)
        return (NULL);
    input->closecallback = NULL;
    ctxt = xmlNewParserCtxt();
    if (ctxt == NULL) {
        xmlFreeParserInputBuffer(input);
        return (NULL);
    }
    stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
    if (stream == NULL) {
        xmlFreeParserInputBuffer(input);
	xmlFreeParserCtxt(ctxt);
        return (NULL);
    }
    inputPush(ctxt, stream);
    return (xmlDoRead(ctxt, URL, encoding, options, 0));
}