bool DownloadManagerImpl::InterceptDownload(
    const download::DownloadCreateInfo& info) {
  WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID(
      info.render_process_id, info.render_frame_id);
  if (info.is_new_download &&
      info.result ==
          download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) {
    if (web_contents) {
      std::vector<GURL> url_chain(info.url_chain);
      GURL url = url_chain.back();
      url_chain.pop_back();
      NavigationController::LoadURLParams params(url);
      params.has_user_gesture = info.has_user_gesture;
      params.referrer = Referrer(
          info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
                                 info.referrer_policy));
      params.redirect_chain = url_chain;
      params.frame_tree_node_id =
          RenderFrameHost::GetFrameTreeNodeIdForRoutingId(
              info.render_process_id, info.render_frame_id);
      web_contents->GetController().LoadURLWithParams(params);
    }
    if (info.request_handle)
      info.request_handle->CancelRequest(false);
    return true;
  }

  std::string user_agent = "";
  for (const auto& header : info.request_headers) {
    if (header.first == net::HttpRequestHeaders::kUserAgent) {
      user_agent = header.second;
      break;
    }
  }

  if (delegate_ &&
      delegate_->InterceptDownloadIfApplicable(
          info.url(), user_agent, info.content_disposition, info.mime_type,
          info.request_origin, info.total_bytes, web_contents)) {
    if (info.request_handle)
      info.request_handle->CancelRequest(false);
    return true;
  }
  content::devtools_instrumentation::WillBeginDownload(
      info.render_process_id, info.render_frame_id, info.url());
  return false;
}


  const base::RepeatingCallback<bool(const GURL&)>& last_origin_filter() const {
    return last_origin_filter_;
  }


static void external_snapshot_prepare(BlkTransactionStates *common,

                                      Error **errp)

{

    BlockDriver *proto_drv;

    BlockDriver *drv;

    int flags, ret;

    Error *local_err = NULL;

    const char *device;

    const char *new_image_file;

    const char *format = "qcow2";

    enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    ExternalSnapshotStates *states =

                             DO_UPCAST(ExternalSnapshotStates, common, common);

    TransactionAction *action = common->action;

    /* get parameters */

    g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);

    device = action->blockdev_snapshot_sync->device;

    new_image_file = action->blockdev_snapshot_sync->snapshot_file;

    if (action->blockdev_snapshot_sync->has_format) {

        format = action->blockdev_snapshot_sync->format;

    }

    if (action->blockdev_snapshot_sync->has_mode) {

        mode = action->blockdev_snapshot_sync->mode;

    }

    /* start processing */

    drv = bdrv_find_format(format);

    if (!drv) {

        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

        return;

    }

    states->old_bs = bdrv_find(device);

    if (!states->old_bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (!bdrv_is_inserted(states->old_bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (bdrv_in_use(states->old_bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, device);

        return;

    }

    if (!bdrv_is_read_only(states->old_bs)) {

        if (bdrv_flush(states->old_bs)) {

            error_set(errp, QERR_IO_ERROR);

            return;

        }

    }

    flags = states->old_bs->open_flags;

    proto_drv = bdrv_find_protocol(new_image_file);

    if (!proto_drv) {

        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

        return;

    }

    /* create new image w/backing file */

    if (mode != NEW_IMAGE_MODE_EXISTING) {

        bdrv_img_create(new_image_file, format,

                        states->old_bs->filename,

                        states->old_bs->drv->format_name,

                        NULL, -1, flags, &local_err, false);

        if (error_is_set(&local_err)) {

            error_propagate(errp, local_err);

            return;

        }

    }

    /* We will manually add the backing_hd field to the bs later */

    states->new_bs = bdrv_new("");

    /* TODO Inherit bs->options or only take explicit options with an

     * extended QMP command? */

    ret = bdrv_open(states->new_bs, new_image_file, NULL,

                    flags | BDRV_O_NO_BACKING, drv);

    if (ret != 0) {

        error_setg_file_open(errp, -ret, new_image_file);

    }

}


Status ImmutableExecutorState::BuildControlFlowInfo(const Graph* g,
                                                    ControlFlowInfo* cf_info) {
  const int num_nodes = g->num_node_ids();
  cf_info->frame_names.resize(num_nodes);
  std::vector<Node*> parent_nodes;
  parent_nodes.resize(num_nodes);
  std::vector<bool> visited;
  visited.resize(num_nodes);

  string frame_name;
  std::deque<Node*> ready;

  // Initialize with the root nodes.
  for (Node* n : g->nodes()) {
    if (n->in_edges().empty()) {
      visited[n->id()] = true;
      cf_info->unique_frame_names.insert(frame_name);
      ready.push_back(n);
    }
  }

  while (!ready.empty()) {
    Node* curr_node = ready.front();
    int curr_id = curr_node->id();
    ready.pop_front();

    Node* parent = nullptr;
    if (IsEnter(curr_node)) {
      // Enter a child frame.
      TF_RETURN_IF_ERROR(
          GetNodeAttr(curr_node->attrs(), "frame_name", &frame_name));
      parent = curr_node;
    } else if (IsExit(curr_node)) {
      // Exit to the parent frame.
      parent = parent_nodes[curr_id];
      if (!parent) {
        return errors::InvalidArgument(
            "Invalid Exit op: Cannot find a corresponding Enter op.");
      }
      frame_name = cf_info->frame_names[parent->id()];
      parent = parent_nodes[parent->id()];
    } else {
      parent = parent_nodes[curr_id];
      frame_name = cf_info->frame_names[curr_id];
    }

    for (const Edge* out_edge : curr_node->out_edges()) {
      Node* out = out_edge->dst();
      if (IsSink(out)) continue;
      const int out_id = out->id();

      // Add to ready queue if not visited.
      bool is_visited = visited[out_id];
      if (!is_visited) {
        ready.push_back(out);
        visited[out_id] = true;

        // Process the node 'out'.
        cf_info->frame_names[out_id] = frame_name;
        parent_nodes[out_id] = parent;
        cf_info->unique_frame_names.insert(frame_name);
      }
    }
  }

  return Status::OK();
}


buflist_altfpos(win_T *win)
{
    buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, TRUE);
}


static void cmd_read_toc_pma_atip(IDEState *s, uint8_t* buf)

{

    int format, msf, start_track, len;

    uint64_t total_sectors = s->nb_sectors >> 2;

    int max_len;

    if (total_sectors == 0) {

        ide_atapi_cmd_error(s, SENSE_NOT_READY, ASC_MEDIUM_NOT_PRESENT);

        return;

    }

    max_len = ube16_to_cpu(buf + 7);

    format = buf[9] >> 6;

    msf = (buf[1] >> 1) & 1;

    start_track = buf[6];

    switch(format) {

    case 0:

        len = cdrom_read_toc(total_sectors, buf, msf, start_track);

        if (len < 0)

            goto error_cmd;

        ide_atapi_cmd_reply(s, len, max_len);

        break;

    case 1:

        /* multi session : only a single session defined */

        memset(buf, 0, 12);

        buf[1] = 0x0a;

        buf[2] = 0x01;

        buf[3] = 0x01;

        ide_atapi_cmd_reply(s, 12, max_len);

        break;

    case 2:

        len = cdrom_read_toc_raw(total_sectors, buf, msf, start_track);

        if (len < 0)

            goto error_cmd;

        ide_atapi_cmd_reply(s, len, max_len);

        break;

    default:

    error_cmd:

        ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,

                            ASC_INV_FIELD_IN_CMD_PACKET);

    }

}


static int vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index, VTDIrq *irq)

{

    VTD_IRTE irte = {};

    int ret = 0;

    ret = vtd_irte_get(iommu, index, &irte);

    if (ret) {

        return ret;

    }

    irq->trigger_mode = irte.trigger_mode;

    irq->vector = irte.vector;

    irq->delivery_mode = irte.delivery_mode;

    irq->dest = le32_to_cpu(irte.dest_id);

    if (!iommu->intr_eime) {

#define  VTD_IR_APIC_DEST_MASK         (0xff00ULL)

#define  VTD_IR_APIC_DEST_SHIFT        (8)

        irq->dest = (irq->dest & VTD_IR_APIC_DEST_MASK) >>

            VTD_IR_APIC_DEST_SHIFT;

    }

    irq->dest_mode = irte.dest_mode;

    irq->redir_hint = irte.redir_hint;

    VTD_DPRINTF(IR, "remapping interrupt index %d: trig:%u,vec:%u,"

                "deliver:%u,dest:%u,dest_mode:%u", index,

                irq->trigger_mode, irq->vector, irq->delivery_mode,

                irq->dest, irq->dest_mode);

    return 0;

}


void Cache::remove(CachedResource* resource)
{
    if (resource->inCache()) {
        m_resources.remove(resource->url());
        resource->setInCache(false);

        removeFromLRUList(resource);
        removeFromLiveDecodedResourcesList(resource);

        HashSet<DocLoader*>::iterator end = m_docLoaders.end();
        for (HashSet<DocLoader*>::iterator itr = m_docLoaders.begin(); itr != end; ++itr)
            (*itr)->removeCachedResource(resource);

        int delta = -static_cast<int>(resource->size());
        if (delta)
            adjustSize(resource->referenced(), delta);
    } else
        ASSERT(m_resources.get(resource->url()) != resource);

    if (resource->canDelete())
        delete resource;
}


TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node,
                             const TfLiteConvParams* params, int width,
                             int height, int filter_width, int filter_height,
                             int out_width, int out_height,
                             const TfLiteType data_type, OpData* data) {
  bool has_bias = node->inputs->size == 3;
  // Check number of inputs/outputs
  TF_LITE_ENSURE(context, has_bias || node->inputs->size == 2);
  TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);

  // Matching GetWindowedOutputSize in TensorFlow.
  auto padding = params->padding;
  data->padding = ComputePaddingHeightWidth(
      params->stride_height, params->stride_width,
      params->dilation_height_factor, params->dilation_width_factor, height,
      width, filter_height, filter_width, padding, &out_height, &out_width);

  // Note that quantized inference requires that all tensors have their
  // parameters set. This is usually done during quantized training.
  if (data_type != kTfLiteFloat32) {
    const TfLiteTensor* input = GetInput(context, node, kInputTensor);
    const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
    const TfLiteTensor* bias =
        GetOptionalInputTensor(context, node, kBiasTensor);
    TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
    int output_channels = filter->dims->data[kConvQuantizedDimension];

    TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(
        context, input, filter, bias, output, params->activation,
        &data->output_multiplier, &data->output_shift,
        &data->output_activation_min, &data->output_activation_max,
        data->per_channel_output_multiplier,
        reinterpret_cast<int*>(data->per_channel_output_shift),
        output_channels));
  }
  return kTfLiteOk;
}


SampleTable::~SampleTable() {
 delete[] mSampleToChunkEntries;
    mSampleToChunkEntries = NULL;

 delete[] mSyncSamples;
    mSyncSamples = NULL;

 delete mCompositionDeltaLookup;
    mCompositionDeltaLookup = NULL;

 delete[] mCompositionTimeDeltaEntries;
    mCompositionTimeDeltaEntries = NULL;

     delete[] mSampleTimeEntries;
     mSampleTimeEntries = NULL;

    delete[] mTimeToSample;
    mTimeToSample = NULL;
     delete mSampleIterator;
     mSampleIterator = NULL;
 }


static v8::Handle<v8::Value> cachedValueAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info)
{
    INC_STATS("DOM.TestSerializedScriptValueInterface.cachedValue._get");
    v8::Handle<v8::String> propertyName = v8::String::NewSymbol("cachedValue");
    v8::Handle<v8::Value> value = info.Holder()->GetHiddenValue(propertyName);
    if (!value.IsEmpty())
        return value;
    TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(info.Holder());
    SerializedScriptValue* serialized = imp->cachedValue();
    value = serialized ? serialized->deserialize() : v8::Handle<v8::Value>(v8::Null());
    info.Holder()->SetHiddenValue(propertyName, value);
    return value;
}


static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
{
#if defined(CONFIG_EPOLL)
	struct io_epoll *ie = &req->epoll;
	int ret;
	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;

	ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
	if (force_nonblock && ret == -EAGAIN)
		return -EAGAIN;

	if (ret < 0)
		req_set_fail(req);
	__io_req_complete(req, issue_flags, ret, 0);
	return 0;
#else
	return -EOPNOTSUPP;
#endif
}


LayoutBlockFlow::FlowThreadType LayoutBlockFlow::flowThreadType(const ComputedStyle& style)
{
    if (isPagedOverflow(style))
        return PagedFlowThread;
    if (style.specifiesColumns())
        return MultiColumnFlowThread;
    return NoFlowThread;
}


activate_desktop_file (ActivateParameters *parameters,
                       NautilusFile       *file)
{
    ActivateParametersDesktop *parameters_desktop;
    char *primary, *secondary, *display_name;
    GtkWidget *dialog;
    GdkScreen *screen;
    char *uri;

    screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));

    if (!nautilus_file_is_trusted_link (file))
    {
        /* copy the parts of parameters we are interested in as the orignal will be freed */
        parameters_desktop = g_new0 (ActivateParametersDesktop, 1);
        if (parameters->parent_window)
        {
            parameters_desktop->parent_window = parameters->parent_window;
            g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) &parameters_desktop->parent_window);
        }
        parameters_desktop->file = nautilus_file_ref (file);

        primary = _("Untrusted application launcher");
        display_name = nautilus_file_get_display_name (file);
        secondary =
            g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. "
                               "If you do not know the source of this file, launching it may be unsafe."
                               ),
                             display_name);

        dialog = gtk_message_dialog_new (parameters->parent_window,
                                         0,
                                         GTK_MESSAGE_WARNING,
                                         GTK_BUTTONS_NONE,
                                         NULL);
        g_object_set (dialog,
                      "text", primary,
                      "secondary-text", secondary,
                      NULL);
        gtk_dialog_add_button (GTK_DIALOG (dialog),
                               _("_Launch Anyway"), RESPONSE_RUN);
        if (nautilus_file_can_set_permissions (file))
        {
            gtk_dialog_add_button (GTK_DIALOG (dialog),
                                   _("Mark as _Trusted"), RESPONSE_MARK_TRUSTED);
        }
        gtk_dialog_add_button (GTK_DIALOG (dialog),
                               _("_Cancel"), GTK_RESPONSE_CANCEL);
        gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);

        g_signal_connect (dialog, "response",
                          G_CALLBACK (untrusted_launcher_response_callback),
                          parameters_desktop);
        gtk_widget_show (dialog);

        g_free (display_name);
        g_free (secondary);
        return;
    }

    uri = nautilus_file_get_uri (file);
    DEBUG ("Launching trusted launcher %s", uri);
    nautilus_launch_desktop_file (screen, uri, NULL,
                                  parameters->parent_window);
    g_free (uri);
}


void PPB_URLLoader_Impl::RunCallback(int32_t result) {
  if (!pending_callback_.get()) {
     CHECK(main_document_loader_);
     return;
   }

  // If |user_buffer_| was set as part of registering the callback, ensure
  // it got cleared since the callback is now free to delete it.
  DCHECK(!user_buffer_);
   TrackedCallback::ClearAndRun(&pending_callback_, result);
 }


QQuickWebView::QQuickWebView(QQuickItem* parent)
    : QQuickItem(parent)
    , d_ptr(createPrivateObject(this))
    , m_experimental(new QQuickWebViewExperimental(this))
{
    Q_D(QQuickWebView);
    d->initialize();
}


static void dv_decode_ac(GetBitContext *gb, BlockInfo *mb, DCTELEM *block)

{

    int last_index = gb->size_in_bits;

    const uint8_t  *scan_table   = mb->scan_table;

    const uint32_t *factor_table = mb->factor_table;

    int pos               = mb->pos;

    int partial_bit_count = mb->partial_bit_count;

    int level, run, vlc_len, index;

    OPEN_READER(re, gb);

    UPDATE_CACHE(re, gb);

    /* if we must parse a partial VLC, we do it here */

    if (partial_bit_count > 0) {

        re_cache = ((unsigned)re_cache >> partial_bit_count) |

                   (mb->partial_bit_buffer << (sizeof(re_cache) * 8 - partial_bit_count));

        re_index -= partial_bit_count;

        mb->partial_bit_count = 0;

    }

    /* get the AC coefficients until last_index is reached */

    for (;;) {

        av_dlog(NULL, "%2d: bits=%04x index=%d\n", pos, SHOW_UBITS(re, gb, 16),

                re_index);

        /* our own optimized GET_RL_VLC */

        index   = NEG_USR32(re_cache, TEX_VLC_BITS);

        vlc_len = dv_rl_vlc[index].len;

        if (vlc_len < 0) {

            index = NEG_USR32((unsigned)re_cache << TEX_VLC_BITS, -vlc_len) + dv_rl_vlc[index].level;

            vlc_len = TEX_VLC_BITS - vlc_len;

        }

        level = dv_rl_vlc[index].level;

        run   = dv_rl_vlc[index].run;

        /* gotta check if we're still within gb boundaries */

        if (re_index + vlc_len > last_index) {

            /* should be < 16 bits otherwise a codeword could have been parsed */

            mb->partial_bit_count = last_index - re_index;

            mb->partial_bit_buffer = NEG_USR32(re_cache, mb->partial_bit_count);

            re_index = last_index;

            break;

        }

        re_index += vlc_len;

        av_dlog(NULL, "run=%d level=%d\n", run, level);

        pos += run;

        if (pos >= 64)

            break;

        level = (level * factor_table[pos] + (1 << (dv_iweight_bits - 1))) >> dv_iweight_bits;

        block[scan_table[pos]] = level;

        UPDATE_CACHE(re, gb);

    }

    CLOSE_READER(re, gb);

    mb->pos = pos;

}


void *Type_ProfileSequenceDesc_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
    cmsSEQ* OutSeq;
    cmsUInt32Number i, Count;

    *nItems = 0;

    if (!_cmsReadUInt32Number(io, &Count)) return NULL;

    if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL;
    SizeOfTag -= sizeof(cmsUInt32Number);

    OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count);
    if (OutSeq == NULL) return NULL;

    OutSeq ->n = Count;

    // Get structures as well

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

        cmsPSEQDESC* sec = &OutSeq -> seq[i];

        if (!_cmsReadUInt32Number(io, &sec ->deviceMfg)) goto Error;
        if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
        SizeOfTag -= sizeof(cmsUInt32Number);

        if (!_cmsReadUInt32Number(io, &sec ->deviceModel)) goto Error;
        if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
        SizeOfTag -= sizeof(cmsUInt32Number);

        if (!_cmsReadUInt64Number(io, &sec ->attributes)) goto Error;
        if (SizeOfTag < sizeof(cmsUInt64Number)) goto Error;
        SizeOfTag -= sizeof(cmsUInt64Number);

        if (!_cmsReadUInt32Number(io, (cmsUInt32Number *)&sec ->technology)) goto Error;
        if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
        SizeOfTag -= sizeof(cmsUInt32Number);

        if (!ReadEmbeddedText(self, io, &sec ->Manufacturer, SizeOfTag)) goto Error;
        if (!ReadEmbeddedText(self, io, &sec ->Model, SizeOfTag)) goto Error;
    }

    *nItems = 1;
    return OutSeq;

Error:
    cmsFreeProfileSequenceDescription(OutSeq);
    return NULL;
}


void flush_spe_to_thread(struct task_struct *tsk)
{
	if (tsk->thread.regs) {
		preempt_disable();
		if (tsk->thread.regs->msr & MSR_SPE) {
#ifdef CONFIG_SMP
			BUG_ON(tsk != current);
#endif
			tsk->thread.spefscr = mfspr(SPRN_SPEFSCR);
			giveup_spe(tsk);
		}
		preempt_enable();
	}
}


void WebPagePrivate::toggleTextReflowIfEnabledForBlockZoomOnly(bool shouldEnableTextReflow)
{
    if (m_webPage->settings()->textReflowMode() == WebSettings::TextReflowEnabledOnlyForBlockZoom)
        m_page->settings()->setTextReflowEnabled(shouldEnableTextReflow);
}


static void SVGExternalSubset(void *context,const xmlChar *name,
  const xmlChar *external_id,const xmlChar *system_id)
{
  SVGInfo
    *svg_info;

  xmlParserCtxt
    parser_context;

  xmlParserCtxtPtr
    parser;

  xmlParserInputPtr
    input;

  /*
    Does this document has an external subset?
  */
  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
    "  SAX.externalSubset(%s, %s, %s)",name,
    (external_id != (const xmlChar *) NULL ? (const char *) external_id : "none"),
    (system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"));
  svg_info=(SVGInfo *) context;
  parser=svg_info->parser;
  if (((external_id == NULL) && (system_id == NULL)) ||
      ((parser->validate == 0) || (parser->wellFormed == 0) ||
      (svg_info->document == 0)))
    return;
  input=SVGResolveEntity(context,external_id,system_id);
  if (input == NULL)
    return;
  (void) xmlNewDtd(svg_info->document,name,external_id,system_id);
  parser_context=(*parser);
  parser->inputTab=(xmlParserInputPtr *) xmlMalloc(5*sizeof(*parser->inputTab));
  if (parser->inputTab == (xmlParserInputPtr *) NULL)
    {
      parser->errNo=XML_ERR_NO_MEMORY;
      parser->input=parser_context.input;
      parser->inputNr=parser_context.inputNr;
      parser->inputMax=parser_context.inputMax;
      parser->inputTab=parser_context.inputTab;
      return;
  }
  parser->inputNr=0;
  parser->inputMax=5;
  parser->input=NULL;
  xmlPushInput(parser,input);
  (void) xmlSwitchEncoding(parser,xmlDetectCharEncoding(parser->input->cur,4));
  if (input->filename == (char *) NULL)
    input->filename=(char *) xmlStrdup(system_id);
  input->line=1;
  input->col=1;
  input->base=parser->input->cur;
  input->cur=parser->input->cur;
  input->free=NULL;
  xmlParseExternalSubset(parser,external_id,system_id);
  while (parser->inputNr > 1)
    (void) xmlPopInput(parser);
  xmlFreeInputStream(parser->input);
  xmlFree(parser->inputTab);
  parser->input=parser_context.input;
  parser->inputNr=parser_context.inputNr;
  parser->inputMax=parser_context.inputMax;
  parser->inputTab=parser_context.inputTab;
}


static void addWhereTerm(
  Parse *pParse,                  /* Parsing context */
  SrcList *pSrc,                  /* List of tables in FROM clause */
  int iLeft,                      /* Index of first table to join in pSrc */
  int iColLeft,                   /* Index of column in first table */
  int iRight,                     /* Index of second table in pSrc */
  int iColRight,                  /* Index of column in second table */
  int isOuterJoin,                /* True if this is an OUTER join */
  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
){
  sqlite3 *db = pParse->db;
  Expr *pE1;
  Expr *pE2;
  Expr *pEq;

  assert( iLeft<iRight );
  assert( pSrc->nSrc>iRight );
  assert( pSrc->a[iLeft].pTab );
  assert( pSrc->a[iRight].pTab );

  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);

  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  if( pEq && isOuterJoin ){
    ExprSetProperty(pEq, EP_FromJoin);
    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
    ExprSetVVAProperty(pEq, EP_NoReduce);
    pEq->iRightJoinTable = (i16)pE2->iTable;
  }
  *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
}


iasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
	struct sc_context *ctx = card->ctx;
	struct iasecc_sdo_update update;
	struct iasecc_sdo sdo;
	unsigned scb;
	int rv;

	LOG_FUNC_CALLED(ctx);
	sc_log(ctx, "Change keyset(ref:%i,lengths:%i)", data->pin_reference, data->pin2.len);
	if (!data->pin2.data || data->pin2.len < 32)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Needs at least 32 bytes for a new keyset value");

	memset(&sdo, 0, sizeof(sdo));
	sdo.sdo_class = IASECC_SDO_CLASS_KEYSET;
	sdo.sdo_ref  = data->pin_reference;

	rv = iasecc_sdo_get_data(card, &sdo);
	LOG_TEST_RET(ctx, rv, "Cannot get keyset data");

	if (sdo.docp.acls_contact.size == 0)
		LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs");
	scb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA];
	iasecc_sdo_free_fields(card, &sdo);

	sc_log(ctx, "SCB:0x%X", scb);
	if (!(scb & IASECC_SCB_METHOD_SM))
		LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Other then protected by SM, the keyset change is not supported");

	memset(&update, 0, sizeof(update));
	update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
	update.sdo_class = sdo.sdo_class;
	update.sdo_ref = sdo.sdo_ref;

	update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;
	update.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC;
	/* FIXME is it safe to modify the const value here? */
	update.fields[0].value = (unsigned char *) data->pin2.data;
	update.fields[0].size = 16;

	update.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG;
	update.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC;
	/* FIXME is it safe to modify the const value here? */
	update.fields[1].value = (unsigned char *) data->pin2.data + 16;
	update.fields[1].size = 16;

	rv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update);
	LOG_FUNC_RETURN(ctx, rv);
}


static void cma_cancel_listens(struct rdma_id_private *id_priv)
{
	struct rdma_id_private *dev_id_priv;

	/*
	 * Remove from listen_any_list to prevent added devices from spawning
	 * additional listen requests.
	 */
	mutex_lock(&lock);
	list_del(&id_priv->list);

	while (!list_empty(&id_priv->listen_list)) {
		dev_id_priv = list_entry(id_priv->listen_list.next,
					 struct rdma_id_private, listen_list);
		/* sync with device removal to avoid duplicate destruction */
		list_del_init(&dev_id_priv->list);
		list_del(&dev_id_priv->listen_list);
		mutex_unlock(&lock);

		rdma_destroy_id(&dev_id_priv->id);
		mutex_lock(&lock);
	}
	mutex_unlock(&lock);
}


vpc_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

               QEMUIOVector *qiov, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int64_t image_offset;

    int64_t n_bytes;

    int64_t bytes_done = 0;

    int ret;

    VHDFooter *footer =  (VHDFooter *) s->footer_buf;

    QEMUIOVector local_qiov;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        return bdrv_co_pwritev(bs->file->bs, offset, bytes, qiov, 0);

    }

    qemu_co_mutex_lock(&s->lock);

    qemu_iovec_init(&local_qiov, qiov->niov);

    while (bytes > 0) {

        image_offset = get_image_offset(bs, offset, true);

        n_bytes = MIN(bytes, s->block_size - (offset % s->block_size));

        if (image_offset == -1) {

            image_offset = alloc_block(bs, offset);

            if (image_offset < 0) {

                ret = image_offset;

                goto fail;

            }

        }

        qemu_iovec_reset(&local_qiov);

        qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);

        ret = bdrv_co_pwritev(bs->file->bs, image_offset, n_bytes,

                              &local_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        bytes -= n_bytes;

        offset += n_bytes;

        bytes_done += n_bytes;

    }

    ret = 0;

fail:

    qemu_iovec_destroy(&local_qiov);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


int dmarc_store_data(header_line *hdr) {
  /* No debug output because would change every test debug output */
  if (dmarc_disable_verify != TRUE)
    from_header = hdr;
  return OK;
}


static void free_todo_entries(TodoEntry **todos) {
        for (TodoEntry *x = *todos; x && x->dir; x++) {
                closedir(x->dir);
                free(x->dirname);
        }

        freep(todos);
}


static inline u32 task_sid ( const struct task_struct * task ) {
 u32 sid ;
 rcu_read_lock ( ) ;
 sid = cred_sid ( __task_cred ( task ) ) ;
 rcu_read_unlock ( ) ;
 return sid ;
 }


    struct Magick_info {
      Magick_info() {
        Magick::InitializeMagick("");


  bool InitSkBitmapFromData(SkBitmap* bitmap,
bool ParamTraits<SkImageInfo>::Read(const base::Pickle* m,
                                    base::PickleIterator* iter,
                                    SkImageInfo* r) {
  SkColorType color_type;
  SkAlphaType alpha_type;
  uint32_t width;
  uint32_t height;
  if (!ReadParam(m, iter, &color_type) || !ReadParam(m, iter, &alpha_type) ||
      !ReadParam(m, iter, &width) || !ReadParam(m, iter, &height)) {
    return false;
   }


int ssl3_send_server_certificate(SSL *s)
	{
	CERT_PKEY *cpk;

	if (s->state == SSL3_ST_SW_CERT_A)
		{
		cpk=ssl_get_server_send_pkey(s);
		if (cpk == NULL)
			{
			/* VRS: allow null cert if auth == KRB5 */
			if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
			    (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
				{
				SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
				return(0);
				}
			}

		if (!ssl3_output_cert_chain(s,cpk))
			{
			SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
			return(0);
			}
		s->state=SSL3_ST_SW_CERT_B;
		}

	/* SSL3_ST_SW_CERT_B */
	return ssl_do_write(s);
	}


RTCPeerConnectionHandler::CurrentRemoteDescription() {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::currentRemoteDescription");
  base::OnceCallback<const webrtc::SessionDescriptionInterface*()>
      description_cb = base::BindOnce(
          &webrtc::PeerConnectionInterface::current_remote_description,
          native_peer_connection_);
  return GetWebRTCSessionDescriptionOnSignalingThread(
      std::move(description_cb), "currentRemoteDescription");
}


void WebContentsImpl::RequestOpenURL(RenderViewHost* rvh,
                                     const GURL& url,
                                     const Referrer& referrer,
                                     WindowOpenDisposition disposition,
                                     int64 source_frame_id,
                                     bool should_replace_current_entry,
                                     bool user_gesture) {
  if (static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() &&
      !rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance())) {
    return;
  }

  std::vector<GURL> redirect_chain;
  RequestTransferURL(url, redirect_chain, referrer, PAGE_TRANSITION_LINK,
                     disposition, source_frame_id, GlobalRequestID(),
                     should_replace_current_entry, user_gesture);
}


ProcScreenSaverUnsetAttributes(ClientPtr client)
{
#ifdef PANORAMIX
    if (!noPanoramiXExtension) {
        REQUEST(xScreenSaverUnsetAttributesReq);
         PanoramiXRes *draw;
         int rc, i;

         rc = dixLookupResourceByClass((void **) &draw, stuff->drawable,
                                       XRC_DRAWABLE, client, DixWriteAccess);
         if (rc != Success)
        for (i = PanoramiXNumScreens - 1; i > 0; i--) {
            stuff->drawable = draw->info[i].id;
            ScreenSaverUnsetAttributes(client);
        }

        stuff->drawable = draw->info[0].id;
    }
#endif

    return ScreenSaverUnsetAttributes(client);
}


static void cfg_resp_handler(int err, const struct http_msg *msg,
			     struct mbuf *mb, struct json_object *jobj,
			     void *arg)
{
	char *json_str = NULL;
	struct zapi_ice_server *servers;
	size_t nservers = 0;
	size_t i;

	re_printf("config ready! err=%d\n");
	if (err == ECONNABORTED)
		goto out;

	if (!err && jobj) {
		err = jzon_encode(&json_str, jobj);
		if (err)
			goto out;
	}

	re_printf("CONFIG: %s\n", json_str);

	config_update(g_config, err, json_str, str_len(json_str));
	mem_deref(json_str);

	servers = config_get_iceservers(g_config, &nservers);
	re_printf("Probing: %d servers\n", nservers);

	for (i = 0; i < nservers; ++i) {
		struct zapi_ice_server *turn = &servers[i];
		struct stun_uri uri;

		err = stun_uri_decode(&uri, turn->url);
		if (err)
			err = turn_dns_lookup(turn, &uri);
		else {
			start_netprobe(&uri.addr, uri.proto, uri.secure,
				       turn->username, turn->credential);
		}
	}

 out:
	if (err)
		error("config request failed: %m\n", err);
}


GF_Box *trgr_box_new()
{
	ISOM_DECL_BOX_ALLOC(GF_TrackGroupBox, GF_ISOM_BOX_TYPE_TRGR);
	tmp->groups = gf_list_new();
	if (!tmp->groups) {
		gf_free(tmp);
		return NULL;
	}
	return (GF_Box *)tmp;


bool OSDService::_get_map_bl(epoch_t e, bufferlist& bl)
{
  bool found = map_bl_cache.lookup(e, &bl);
  if (found) {
    if (logger)
      logger->inc(l_osd_map_bl_cache_hit);
    return true;
  }
  if (logger)
    logger->inc(l_osd_map_bl_cache_miss);
  found = store->read(coll_t::meta(),
		      OSD::get_osdmap_pobject_name(e), 0, 0, bl,
		      CEPH_OSD_OP_FLAG_FADVISE_WILLNEED) >= 0;
  if (found) {
    _add_map_bl(e, bl);
  }
  return found;
}


static int fuse_check_page(struct page *page)
{
	if (page_mapcount(page) ||
	    page->mapping != NULL ||
	    page_count(page) != 1 ||
	    (page->flags & PAGE_FLAGS_CHECK_AT_PREP &
	     ~(1 << PG_locked |
	       1 << PG_referenced |
	       1 << PG_uptodate |
	       1 << PG_lru |
	       1 << PG_active |
	       1 << PG_reclaim))) {
		printk(KERN_WARNING "fuse: trying to steal weird page\n");
		printk(KERN_WARNING "  page=%p index=%li flags=%08lx, count=%i, mapcount=%i, mapping=%p\n", page, page->index, page->flags, page_count(page), page_mapcount(page), page->mapping);
		return 1;
	}
	return 0;
}


int dtls1_dispatch_alert(SSL *s)
	{
	int i,j;
	void (*cb)(const SSL *ssl,int type,int val)=NULL;
	unsigned char buf[DTLS1_AL_HEADER_LENGTH];
	unsigned char *ptr = &buf[0];

	s->s3->alert_dispatch=0;

	memset(buf, 0x00, sizeof(buf));
	*ptr++ = s->s3->send_alert[0];
	*ptr++ = s->s3->send_alert[1];

#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
	if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
		{
		s2n(s->d1->handshake_read_seq, ptr);
#if 0
		if ( s->d1->r_msg_hdr.frag_off == 0)  /* waiting for a new msg */

		else
			s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
#endif

#if 0
		fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
#endif
		l2n3(s->d1->r_msg_hdr.frag_off, ptr);
		}
#endif

	i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
	if (i <= 0)
		{
		s->s3->alert_dispatch=1;
		/* fprintf( stderr, "not done with alert\n" ); */
		}
	else
		{
		if (s->s3->send_alert[0] == SSL3_AL_FATAL
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
		    || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
#endif
		    )
			(void)BIO_flush(s->wbio);

		if (s->msg_callback)
			s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
				2, s, s->msg_callback_arg);

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

		if (cb != NULL)
			{
			j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
			cb(s,SSL_CB_WRITE_ALERT,j);
			}
		}
	return(i);
	}


void CarbonProtocolReader::skipLinearContainer() {
  const auto pr = readLinearContainerFieldSizeAndInnerType();
  skipLinearContainerItems(pr);
}


static int usb_msd_handle_data(USBDevice *dev, USBPacket *p)

{

    MSDState *s = (MSDState *)dev;

    int ret = 0;

    struct usb_msd_cbw cbw;

    uint8_t devep = p->devep;

    uint8_t *data = p->data;

    int len = p->len;

    switch (p->pid) {

    case USB_TOKEN_OUT:

        if (devep != 2)

            goto fail;

        switch (s->mode) {

        case USB_MSDM_CBW:

            if (len != 31) {

                fprintf(stderr, "usb-msd: Bad CBW size");

                goto fail;

            }

            memcpy(&cbw, data, 31);

            if (le32_to_cpu(cbw.sig) != 0x43425355) {

                fprintf(stderr, "usb-msd: Bad signature %08x\n",

                        le32_to_cpu(cbw.sig));

                goto fail;

            }

            DPRINTF("Command on LUN %d\n", cbw.lun);

            if (cbw.lun != 0) {

                fprintf(stderr, "usb-msd: Bad LUN %d\n", cbw.lun);

                goto fail;

            }

            s->tag = le32_to_cpu(cbw.tag);

            s->data_len = le32_to_cpu(cbw.data_len);

            if (s->data_len == 0) {

                s->mode = USB_MSDM_CSW;

            } else if (cbw.flags & 0x80) {

                s->mode = USB_MSDM_DATAIN;

            } else {

                s->mode = USB_MSDM_DATAOUT;

            }

            DPRINTF("Command tag 0x%x flags %08x len %d data %d\n",

                    s->tag, cbw.flags, cbw.cmd_len, s->data_len);

            s->residue = 0;

            s->scsi_len = 0;

            s->req = scsi_req_new(s->scsi_dev, s->tag, 0, NULL);

            scsi_req_enqueue(s->req, cbw.cmd);

            /* ??? Should check that USB and SCSI data transfer

               directions match.  */

            if (s->mode != USB_MSDM_CSW && s->residue == 0) {

                scsi_req_continue(s->req);

            }

            ret = len;

            break;

        case USB_MSDM_DATAOUT:

            DPRINTF("Data out %d/%d\n", len, s->data_len);

            if (len > s->data_len)

                goto fail;

            s->usb_buf = data;

            s->usb_len = len;

            if (s->scsi_len) {

                usb_msd_copy_data(s);

            }

            if (s->residue && s->usb_len) {

                s->data_len -= s->usb_len;

                if (s->data_len == 0)

                    s->mode = USB_MSDM_CSW;

                s->usb_len = 0;

            }

            if (s->usb_len) {

                DPRINTF("Deferring packet %p\n", p);

                s->packet = p;

                ret = USB_RET_ASYNC;

            } else {

                ret = len;

            }

            break;

        default:

            DPRINTF("Unexpected write (len %d)\n", len);

            goto fail;

        }

        break;

    case USB_TOKEN_IN:

        if (devep != 1)

            goto fail;

        switch (s->mode) {

        case USB_MSDM_DATAOUT:

            if (s->data_len != 0 || len < 13)

                goto fail;

            /* Waiting for SCSI write to complete.  */

            s->packet = p;

            ret = USB_RET_ASYNC;

            break;

        case USB_MSDM_CSW:

            DPRINTF("Command status %d tag 0x%x, len %d\n",

                    s->result, s->tag, len);

            if (len < 13)

                goto fail;

            usb_msd_send_status(s, p);

            s->mode = USB_MSDM_CBW;

            ret = 13;

            break;

        case USB_MSDM_DATAIN:

            DPRINTF("Data in %d/%d, scsi_len %d\n", len, s->data_len, s->scsi_len);

            if (len > s->data_len)

                len = s->data_len;

            s->usb_buf = data;

            s->usb_len = len;

            if (s->scsi_len) {

                usb_msd_copy_data(s);

            }

            if (s->residue && s->usb_len) {

                s->data_len -= s->usb_len;

                memset(s->usb_buf, 0, s->usb_len);

                if (s->data_len == 0)

                    s->mode = USB_MSDM_CSW;

                s->usb_len = 0;

            }

            if (s->usb_len) {

                DPRINTF("Deferring packet %p\n", p);

                s->packet = p;

                ret = USB_RET_ASYNC;

            } else {

                ret = len;

            }

            break;

        default:

            DPRINTF("Unexpected read (len %d)\n", len);

            goto fail;

        }

        break;

    default:

        DPRINTF("Bad token\n");

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static int ovl_dir_getattr(struct vfsmount *mnt, struct dentry *dentry,
			 struct kstat *stat)
{
	int err;
	enum ovl_path_type type;
	struct path realpath;

	type = ovl_path_real(dentry, &realpath);
	err = vfs_getattr(&realpath, stat);
	if (err)
		return err;

	stat->dev = dentry->d_sb->s_dev;
	stat->ino = dentry->d_inode->i_ino;

	/*
	 * It's probably not worth it to count subdirs to get the
	 * correct link count.  nlink=1 seems to pacify 'find' and
	 * other utilities.
	 */
	if (OVL_TYPE_MERGE(type))
		stat->nlink = 1;

	return 0;
}


Formattable::setArray(const Formattable* array, int32_t count)
{
    dispose();
    fType = kArray;
    fValue.fArrayAndCount.fArray = createArrayCopy(array, count);
    fValue.fArrayAndCount.fCount = count;
}


void RenderFrameDevToolsAgentHost::GrantPolicy() {
  if (!frame_host_)
    return;
  uint32_t process_id = frame_host_->GetProcess()->GetID();
  if (base::FeatureList::IsEnabled(network::features::kNetworkService))
    GetNetworkService()->SetRawHeadersAccess(process_id, true);
  ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadRawCookies(
      process_id);
}


static GF_Err isom_create_init_from_mem(const char *fileName, GF_ISOFile *file)
{
	u32 sample_rate=0;
	u32 nb_channels=0;
	u32 bps=0;
	//u32 atag=0;
	u32 nal_len=4;
	u32 width = 0;
	u32 height = 0;
	u32 timescale = 10000000;
	u64 tfdt = 0;
	char sz4cc[5];
	char CodecParams[2048];
	u32 CodecParamLen=0;
	char *sep, *val;
	GF_TrackBox *trak;
	GF_TrackExtendsBox *trex;
	GF_SampleTableBox *stbl;

	sz4cc[0] = 0;

	val = (char*) ( fileName + strlen("isobmff://") );
	while (1)  {
		sep = strchr(val, ' ');
		if (sep) sep[0] = 0;

		if (!strncmp(val, "4cc=", 4)) strcpy(sz4cc, val+4);
		else if (!strncmp(val, "init=", 5)) {
			char szH[3], *data = val+5;
			u32 i, len = (u32) strlen(data);
			for (i=0; i<len; i+=2) {
				u32 v;
				//init is hex-encoded so 2 input bytes for one output char
				szH[0] = data[i];
				szH[1] = data[i+1];
				szH[2] = 0;
				sscanf(szH, "%X", &v);
				CodecParams[CodecParamLen] = (char) v;
				CodecParamLen++;
			}
		}
		else if (!strncmp(val, "nal=", 4)) nal_len = atoi(val+4);
		else if (!strncmp(val, "bps=", 4)) bps = atoi(val+4);
		//else if (!strncmp(val, "atag=", 5)) atag = atoi(val+5);
		else if (!strncmp(val, "ch=", 3)) nb_channels = atoi(val+3);
		else if (!strncmp(val, "srate=", 6)) sample_rate = atoi(val+6);
		else if (!strncmp(val, "w=", 2)) width = atoi(val+2);
		else if (!strncmp(val, "h=", 2)) height = atoi(val+2);
		else if (!strncmp(val, "scale=", 6)) timescale = atoi(val+6);
		else if (!strncmp(val, "tfdt=", 5)) {
			sscanf(val+5, LLX, &tfdt);
		}
		if (!sep) break;
		sep[0] = ' ';
		val = sep+1;
	}
	if (!stricmp(sz4cc, "H264") || !stricmp(sz4cc, "AVC1")) {
	}
	else if (!stricmp(sz4cc, "AACL")) {
	}
	else {
		GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Cannot convert smooth media type %s to ISO init segment\n", sz4cc));
		return GF_NOT_SUPPORTED;
	}

	file->moov = (GF_MovieBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MOOV);
	if (!file->moov) return GF_OUT_OF_MEM;
	gf_list_add(file->TopBoxes, file->moov);
	file->moov->mov = file;
	file->is_smooth = GF_TRUE;
	file->moov->mvhd = (GF_MovieHeaderBox *) gf_isom_box_new_parent(&file->moov->child_boxes, GF_ISOM_BOX_TYPE_MVHD);
	if (!file->moov->mvhd) return GF_OUT_OF_MEM;
	file->moov->mvhd->timeScale = timescale;
	file->moov->mvex = (GF_MovieExtendsBox *) gf_isom_box_new_parent(&file->moov->child_boxes, GF_ISOM_BOX_TYPE_MVEX);
	if (!file->moov->mvex) return GF_OUT_OF_MEM;
	trex = (GF_TrackExtendsBox *) gf_isom_box_new_parent(&file->moov->mvex->child_boxes, GF_ISOM_BOX_TYPE_TREX);
	if (!trex) return GF_OUT_OF_MEM;

	trex->def_sample_desc_index = 1;
	trex->trackID = 1;
	gf_list_add(file->moov->mvex->TrackExList, trex);

	trak = (GF_TrackBox *) gf_isom_box_new_parent(&file->moov->child_boxes, GF_ISOM_BOX_TYPE_TRAK);
	if (!trak) return GF_OUT_OF_MEM;
	trak->moov = file->moov;
	gf_list_add(file->moov->trackList, trak);

	trak->Header = (GF_TrackHeaderBox *) gf_isom_box_new_parent(&trak->child_boxes, GF_ISOM_BOX_TYPE_TKHD);
	if (!trak->Header) return GF_OUT_OF_MEM;
	trak->Header->trackID = 1;
	trak->Header->flags |= 1;
	trak->Header->width = width;
	trak->Header->height = height;

	trak->Media = (GF_MediaBox *) gf_isom_box_new_parent(&trak->child_boxes, GF_ISOM_BOX_TYPE_MDIA);
	if (!trak->Media) return GF_OUT_OF_MEM;
	trak->Media->mediaTrack = trak;
	trak->Media->mediaHeader = (GF_MediaHeaderBox *) gf_isom_box_new_parent(&trak->Media->child_boxes, GF_ISOM_BOX_TYPE_MDHD);
	if (!trak->Media->mediaHeader) return GF_OUT_OF_MEM;
	trak->Media->mediaHeader->timeScale = timescale;

	trak->Media->handler = (GF_HandlerBox *) gf_isom_box_new_parent(&trak->Media->child_boxes,GF_ISOM_BOX_TYPE_HDLR);
	if (!trak->Media->handler) return GF_OUT_OF_MEM;
    //we assume by default vide for handler type (only used for smooth streaming)
	trak->Media->handler->handlerType = width ? GF_ISOM_MEDIA_VISUAL : GF_ISOM_MEDIA_AUDIO;

	trak->Media->information = (GF_MediaInformationBox *) gf_isom_box_new_parent(&trak->Media->child_boxes, GF_ISOM_BOX_TYPE_MINF);
	if (!trak->Media->information) return GF_OUT_OF_MEM;
	trak->Media->information->sampleTable = (GF_SampleTableBox *) gf_isom_box_new_parent(&trak->Media->information->child_boxes, GF_ISOM_BOX_TYPE_STBL);
	if (!trak->Media->information->sampleTable) return GF_OUT_OF_MEM;

	stbl = trak->Media->information->sampleTable;
	stbl->SampleSize = (GF_SampleSizeBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_STSZ);
	if (!stbl->SampleSize) return GF_OUT_OF_MEM;
	stbl->TimeToSample = (GF_TimeToSampleBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_STTS);
	if (!stbl->TimeToSample) return GF_OUT_OF_MEM;
	stbl->ChunkOffset = (GF_Box *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_STCO);
	if (!stbl->ChunkOffset) return GF_OUT_OF_MEM;
	stbl->SampleToChunk = (GF_SampleToChunkBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_STSC);
	if (!stbl->SampleToChunk) return GF_OUT_OF_MEM;
	stbl->SyncSample = (GF_SyncSampleBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_STSS);
	if (!stbl->SyncSample) return GF_OUT_OF_MEM;
	stbl->SampleDescription = (GF_SampleDescriptionBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_STSD);
	if (!stbl->SampleDescription) return GF_OUT_OF_MEM;

	trak->dts_at_seg_start = tfdt;
	trak->dts_at_next_seg_start = tfdt;

	if (!stricmp(sz4cc, "H264") || !stricmp(sz4cc, "AVC1")) {
#ifndef GPAC_DISABLE_AV_PARSERS
		u32 pos = 0;
		u32 end, sc_size=0;
#endif
		GF_MPEGVisualSampleEntryBox *avc =  (GF_MPEGVisualSampleEntryBox *) gf_isom_box_new_parent(&stbl->SampleDescription->child_boxes, GF_ISOM_BOX_TYPE_AVC1);
		if (!avc) return GF_OUT_OF_MEM;
		avc->avc_config =  (GF_AVCConfigurationBox *) gf_isom_box_new_parent(&avc->child_boxes, GF_ISOM_BOX_TYPE_AVCC);
		if (!avc->avc_config) return GF_OUT_OF_MEM;

		avc->Width = width;
		avc->Height = height;

		avc->avc_config->config = gf_odf_avc_cfg_new();
		avc->avc_config->config->nal_unit_size = nal_len;
		avc->avc_config->config->configurationVersion = 1;

#ifndef GPAC_DISABLE_AV_PARSERS
		//locate pps and sps
		gf_media_nalu_next_start_code((u8 *) CodecParams, CodecParamLen, &sc_size);
		pos += sc_size;
		while (pos<CodecParamLen) {
			GF_NALUFFParam *slc;
			u8 nal_type;
			char *nal = &CodecParams[pos];
			end = gf_media_nalu_next_start_code(nal, CodecParamLen-pos, &sc_size);
			if (!end) end = CodecParamLen;

			GF_SAFEALLOC(slc, GF_NALUFFParam);
			if (!slc) break;
			slc->size = end;
			slc->data = gf_malloc(sizeof(char)*slc->size);
			if (!slc->data) return GF_OUT_OF_MEM;
			memcpy(slc->data, nal, sizeof(char)*slc->size);

			nal_type = nal[0] & 0x1F;
			if (nal_type == GF_AVC_NALU_SEQ_PARAM) {
/*				AVCState avcc;
				u32 idx = gf_avc_read_sps(slc->data, slc->size, &avcc, 0, NULL);
				avc->avc_config->config->profile_compatibility = avcc.sps[idx].prof_compat;
				avc->avc_config->config->AVCProfileIndication = avcc.sps[idx].profile_idc;
				avc->avc_config->config->AVCLevelIndication = avcc.sps[idx].level_idc;
				avc->avc_config->config->chroma_format = avcc.sps[idx].chroma_format;
				avc->avc_config->config->luma_bit_depth = 8 + avcc.sps[idx].luma_bit_depth_m8;
				avc->avc_config->config->chroma_bit_depth = 8 + avcc.sps[idx].chroma_bit_depth_m8;
*/

				gf_list_add(avc->avc_config->config->sequenceParameterSets, slc);
			} else {
				gf_list_add(avc->avc_config->config->pictureParameterSets, slc);
			}
			pos += slc->size + sc_size;
		}
#endif

		AVC_RewriteESDescriptor(avc);
	}
	else if (!stricmp(sz4cc, "AACL")) {
#ifndef GPAC_DISABLE_AV_PARSERS
		GF_M4ADecSpecInfo aacinfo;
#endif

		GF_MPEGAudioSampleEntryBox *aac =  (GF_MPEGAudioSampleEntryBox *) gf_isom_box_new_parent(&stbl->SampleDescription->child_boxes, GF_ISOM_BOX_TYPE_MP4A);
		if (!aac) return GF_OUT_OF_MEM;
		aac->esd = (GF_ESDBox *) gf_isom_box_new_parent(&aac->child_boxes, GF_ISOM_BOX_TYPE_ESDS);
		if (!aac->esd) return GF_OUT_OF_MEM;
		aac->esd->desc = gf_odf_desc_esd_new(2);
		if (!aac->esd->desc) return GF_OUT_OF_MEM;
#ifndef GPAC_DISABLE_AV_PARSERS
		memset(&aacinfo, 0, sizeof(GF_M4ADecSpecInfo));
		aacinfo.nb_chan = nb_channels;
		aacinfo.base_object_type = GF_M4A_AAC_LC;
		aacinfo.base_sr = sample_rate;
		gf_m4a_write_config(&aacinfo, &aac->esd->desc->decoderConfig->decoderSpecificInfo->data, &aac->esd->desc->decoderConfig->decoderSpecificInfo->dataLength);
#endif
		aac->esd->desc->decoderConfig->streamType = GF_STREAM_AUDIO;
		aac->esd->desc->decoderConfig->objectTypeIndication = GF_CODECID_AAC_MPEG4;
		aac->bitspersample = bps;
		aac->samplerate_hi = sample_rate;
		aac->channel_count = nb_channels;
	}

	return GF_OK;
}


static void pdo_stmt_iter_get_key ( zend_object_iterator * iter , zval * key TSRMLS_DC ) {
 struct php_pdo_iterator * I = ( struct php_pdo_iterator * ) iter -> data ;
 if ( I -> key == ( ulong ) - 1 ) {
 ZVAL_NULL ( key ) ;
 }
 else {
 ZVAL_LONG ( key , I -> key ) ;
 }
 }


scoped_refptr<StaticBitmapImage> HTMLCanvasElement::Snapshot(
    SourceDrawingBuffer source_buffer,
    AccelerationHint hint) const {
  if (size_.IsEmpty())
    return nullptr;

  scoped_refptr<StaticBitmapImage> image_bitmap = nullptr;
  if (PlaceholderFrame()) {  // Offscreen Canvas
    DCHECK(PlaceholderFrame()->OriginClean());
    image_bitmap = PlaceholderFrame()->Bitmap();
  } else if (Is3d()) {  // WebGL or WebGL2 canvas
    if (context_->CreationAttributes().premultiplied_alpha) {
      context_->PaintRenderingResultsToCanvas(source_buffer);
      if (ResourceProvider())
        image_bitmap = ResourceProvider()->Snapshot();
    } else {
      scoped_refptr<Uint8Array> data_array =
          context_->PaintRenderingResultsToDataArray(source_buffer);
      if (data_array) {
        IntSize adjusted_size = context_->DrawingBufferSize();
        SkImageInfo info =
            SkImageInfo::Make(adjusted_size.Width(), adjusted_size.Height(),
                              kRGBA_8888_SkColorType, kUnpremul_SkAlphaType);
        info = info.makeColorSpace(ColorParams().GetSkColorSpace());
        if (ColorParams().GetSkColorType() != kN32_SkColorType)
          info = info.makeColorType(kRGBA_F16_SkColorType);
        image_bitmap = StaticBitmapImage::Create(std::move(data_array), info);
      }
    }
  } else if (canvas2d_bridge_) {  // 2D Canvas
    DCHECK(Is2d());
    image_bitmap = canvas2d_bridge_->NewImageSnapshot(hint);
  } else if (context_) {  // Bitmap renderer canvas
    image_bitmap = context_->GetImage(hint);
  }

  if (!image_bitmap)
    image_bitmap = CreateTransparentImage(size_);
  return image_bitmap;
}


RendererSchedulerImpl::AsValueLocked(base::TimeTicks optional_now) const {
  helper_.CheckOnValidThread();
  any_thread_lock_.AssertAcquired();

  if (optional_now.is_null())
    optional_now = helper_.NowTicks();
  std::unique_ptr<base::trace_event::TracedValue> state(
      new base::trace_event::TracedValue());
  state->SetBoolean(
      "has_visible_render_widget_with_touch_handler",
      main_thread_only().has_visible_render_widget_with_touch_handler);
  state->SetString("current_use_case",
                   UseCaseToString(main_thread_only().current_use_case));
  state->SetBoolean("loading_tasks_seem_expensive",
                    main_thread_only().loading_tasks_seem_expensive);
  state->SetBoolean("timer_tasks_seem_expensive",
                    main_thread_only().timer_tasks_seem_expensive);
  state->SetBoolean("begin_frame_not_expected_soon",
                    main_thread_only().begin_frame_not_expected_soon);
  state->SetBoolean(
      "compositor_will_send_main_frame_not_expected",
      main_thread_only().compositor_will_send_main_frame_not_expected);
  state->SetBoolean("touchstart_expected_soon",
                    main_thread_only().touchstart_expected_soon);
  state->SetString("idle_period_state",
                   IdleHelper::IdlePeriodStateToString(
                       idle_helper_.SchedulerIdlePeriodState()));
  state->SetBoolean("renderer_hidden", main_thread_only().renderer_hidden);
  state->SetBoolean("have_seen_a_begin_main_frame",
                    main_thread_only().have_seen_a_begin_main_frame);
  state->SetBoolean("waiting_for_meaningful_paint",
                    any_thread().waiting_for_meaningful_paint);
  state->SetBoolean("have_seen_input_since_navigation",
                    any_thread().have_seen_input_since_navigation);
  state->SetBoolean(
      "have_reported_blocking_intervention_in_current_policy",
      main_thread_only().have_reported_blocking_intervention_in_current_policy);
  state->SetBoolean(
      "have_reported_blocking_intervention_since_navigation",
      main_thread_only().have_reported_blocking_intervention_since_navigation);
  state->SetBoolean("renderer_backgrounded",
                    main_thread_only().renderer_backgrounded);
  state->SetBoolean("stopped_when_backgrounded",
                    main_thread_only().stopped_when_backgrounded);
  state->SetDouble("now", (optional_now - base::TimeTicks()).InMillisecondsF());
  state->SetDouble(
      "fling_compositor_escalation_deadline",
      (any_thread().fling_compositor_escalation_deadline - base::TimeTicks())
          .InMillisecondsF());
  state->SetInteger("navigation_task_expected_count",
                    main_thread_only().navigation_task_expected_count);
  state->SetDouble("last_idle_period_end_time",
                   (any_thread().last_idle_period_end_time - base::TimeTicks())
                       .InMillisecondsF());
  state->SetBoolean("awaiting_touch_start_response",
                    any_thread().awaiting_touch_start_response);
  state->SetBoolean("begin_main_frame_on_critical_path",
                    any_thread().begin_main_frame_on_critical_path);
  state->SetBoolean("last_gesture_was_compositor_driven",
                    any_thread().last_gesture_was_compositor_driven);
  state->SetBoolean("default_gesture_prevented",
                    any_thread().default_gesture_prevented);
  state->SetDouble("expected_loading_task_duration",
                   main_thread_only()
                       .loading_task_cost_estimator.expected_task_duration()
                       .InMillisecondsF());
  state->SetDouble("expected_timer_task_duration",
                   main_thread_only()
                       .timer_task_cost_estimator.expected_task_duration()
                       .InMillisecondsF());
  state->SetBoolean("is_audio_playing", main_thread_only().is_audio_playing);
  state->SetBoolean("virtual_time_stopped",
                    main_thread_only().virtual_time_stopped);
  state->SetDouble("virtual_time_pause_count",
                   main_thread_only().virtual_time_pause_count);
  state->SetString(
      "virtual_time_policy",
      VirtualTimePolicyToString(main_thread_only().virtual_time_policy));
  state->SetBoolean("virtual_time", main_thread_only().use_virtual_time);

  state->BeginDictionary("web_view_schedulers");
  for (WebViewSchedulerImpl* web_view_scheduler :
       main_thread_only().web_view_schedulers) {
    state->BeginDictionaryWithCopiedName(PointerToString(web_view_scheduler));
    web_view_scheduler->AsValueInto(state.get());
    state->EndDictionary();
  }
  state->EndDictionary();

  state->BeginDictionary("policy");
  main_thread_only().current_policy.AsValueInto(state.get());
  state->EndDictionary();

  state->SetDouble(
      "longest_jank_free_task_duration",
      main_thread_only().longest_jank_free_task_duration->InMillisecondsF());
  state->SetDouble(
      "compositor_frame_interval",
      main_thread_only().compositor_frame_interval.InMillisecondsF());
  state->SetDouble(
      "estimated_next_frame_begin",
      (main_thread_only().estimated_next_frame_begin - base::TimeTicks())
          .InMillisecondsF());
  state->SetBoolean("in_idle_period", any_thread().in_idle_period);

  state->SetString(
      "expensive_task_policy",
      ExpensiveTaskPolicyToString(main_thread_only().expensive_task_policy));

  any_thread().user_model.AsValueInto(state.get());
  render_widget_scheduler_signals_.AsValueInto(state.get());

  state->BeginDictionary("task_queue_throttler");
  task_queue_throttler_->AsValueInto(state.get(), optional_now);
  state->EndDictionary();

  return std::move(state);
}


static struct sock *udp6_lib_lookup2(struct net *net,
		const struct in6_addr *saddr, __be16 sport,
		const struct in6_addr *daddr, unsigned int hnum, int dif,
		struct udp_hslot *hslot2, unsigned int slot2)
{
	struct sock *sk, *result;
	struct hlist_nulls_node *node;
	int score, badness, matches = 0, reuseport = 0;
	u32 hash = 0;

begin:
	result = NULL;
	badness = -1;
	udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) {
		score = compute_score2(sk, net, saddr, sport,
				      daddr, hnum, dif);
		if (score > badness) {
			result = sk;
			badness = score;
			reuseport = sk->sk_reuseport;
			if (reuseport) {
				hash = udp6_ehashfn(net, daddr, hnum,
						    saddr, sport);
				matches = 1;
			}
		} else if (score == badness && reuseport) {
			matches++;
			if (reciprocal_scale(hash, matches) == 0)
				result = sk;
			hash = next_pseudo_random32(hash);
		}
	}
	/*
	 * if the nulls value we got at the end of this lookup is
	 * not the expected one, we must restart lookup.
	 * We probably met an item that was moved to another chain.
	 */
	if (get_nulls_value(node) != slot2)
		goto begin;

	if (result) {
		if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
			result = NULL;
		else if (unlikely(compute_score2(result, net, saddr, sport,
				  daddr, hnum, dif) < badness)) {
			sock_put(result);
			goto begin;
		}
	}
	return result;
}


static void __exit cleanup_ipmi(void)
{
	int count;

	if (!initialized)
		return;

	atomic_notifier_chain_unregister(&panic_notifier_list, &panic_block);

	/*
	 * This can't be called if any interfaces exist, so no worry
	 * about shutting down the interfaces.
	 */

	/*
	 * Tell the timer to stop, then wait for it to stop.  This
	 * avoids problems with race conditions removing the timer
	 * here.
	 */
	atomic_inc(&stop_operation);
	del_timer_sync(&ipmi_timer);

	driver_unregister(&ipmidriver.driver);

	initialized = 0;

	/* Check for buffer leaks. */
	count = atomic_read(&smi_msg_inuse_count);
	if (count != 0)
		pr_warn("SMI message count %d at exit\n", count);
	count = atomic_read(&recv_msg_inuse_count);
	if (count != 0)
		pr_warn("recv message count %d at exit\n", count);
}


void GfxImageColorMap::getCMYK(Guchar *x, GfxCMYK *cmyk) {
  GfxColor color;
  int i;

  if (colorSpace2) {
    for (i = 0; i < nComps2; ++i) {
      color.c[i] = lookup[i][x[0]];
    }
    colorSpace2->getCMYK(&color, cmyk);
  } else {
    for (i = 0; i < nComps; ++i) {
      color.c[i] = lookup[i][x[i]];
    }
    colorSpace->getCMYK(&color, cmyk);
  }
}


unsigned long bebytes2ulong(const u8 *buf)
{
	if (buf == NULL)
		return 0UL;
	return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}


static int inet_sk_reselect_saddr(struct sock *sk)
{
	struct inet_sock *inet = inet_sk(sk);
	__be32 old_saddr = inet->inet_saddr;
	__be32 daddr = inet->inet_daddr;
	struct flowi4 fl4;
	struct rtable *rt;
	__be32 new_saddr;

	if (inet->opt && inet->opt->srr)
		daddr = inet->opt->faddr;

	/* Query new route. */
	rt = ip_route_connect(&fl4, daddr, 0, RT_CONN_FLAGS(sk),
			      sk->sk_bound_dev_if, sk->sk_protocol,
			      inet->inet_sport, inet->inet_dport, sk, false);
	if (IS_ERR(rt))
		return PTR_ERR(rt);

	sk_setup_caps(sk, &rt->dst);

	new_saddr = rt->rt_src;

	if (new_saddr == old_saddr)
		return 0;

	if (sysctl_ip_dynaddr > 1) {
		printk(KERN_INFO "%s(): shifting inet->saddr from %pI4 to %pI4\n",
		       __func__, &old_saddr, &new_saddr);
	}

	inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;

	/*
	 * XXX The only one ugly spot where we need to
	 * XXX really change the sockets identity after
	 * XXX it has entered the hashes. -DaveM
	 *
	 * Besides that, it does not check for connection
	 * uniqueness. Wait for troubles.
	 */
	__sk_prot_rehash(sk);
	return 0;
}


bool ContentSecurityPolicy::AllowBaseURI(
    const KURL& url,
    RedirectStatus redirect_status,
    SecurityViolationReportingPolicy reporting_policy) const {
  if (ShouldBypassContentSecurityPolicy(url, execution_context_))
    return true;

  bool is_allowed = true;
  for (const auto& policy : policies_) {
    if (!CheckHeaderTypeMatches(CheckHeaderType::kCheckAll,
                                policy->HeaderType()))
      continue;
    is_allowed &= policy->AllowBaseURI(url, redirect_status, reporting_policy);
  }

  return is_allowed;
}


String AXLayoutObject::text() const {
  if (isPasswordFieldAndShouldHideValue()) {
    if (!getLayoutObject())
      return String();

    const ComputedStyle* style = getLayoutObject()->style();
    if (!style)
      return String();

    unsigned unmaskedTextLength = AXNodeObject::text().length();
    if (!unmaskedTextLength)
      return String();

    UChar maskCharacter = 0;
    switch (style->textSecurity()) {
      case TSNONE:
        break;  // Fall through to the non-password branch.
      case TSDISC:
        maskCharacter = bulletCharacter;
        break;
      case TSCIRCLE:
        maskCharacter = whiteBulletCharacter;
        break;
      case TSSQUARE:
        maskCharacter = blackSquareCharacter;
        break;
    }
    if (maskCharacter) {
      StringBuilder maskedText;
      maskedText.reserveCapacity(unmaskedTextLength);
      for (unsigned i = 0; i < unmaskedTextLength; ++i)
        maskedText.append(maskCharacter);
      return maskedText.toString();
    }
  }

  return AXNodeObject::text();
}


static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
                                        unsigned len, const char *key)
{
    c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
    av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);

    return 0;
}


static void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase,
 unsigned ExifLength, int NestingLevel)
{
 int de;
 int a;
 int NumDirEntries;
 unsigned ThumbnailOffset = 0;
 unsigned ThumbnailSize = 0;
 char IndentString[25];

    printf("ProcessExifDir");
 if (NestingLevel > 4){
 ErrNonfatal("Maximum directory nesting exceeded (corrupt exif header)", 0,0);
 return;
 }

    memset(IndentString, ' ', 25);
 IndentString[NestingLevel * 4] = '\0';

 NumDirEntries = Get16u(DirStart);
 #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))

 {
 unsigned char * DirEnd;
 DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries);
 if (DirEnd+4 > (OffsetBase+ExifLength)){
 if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){
 }else{
 ErrNonfatal("Illegally sized exif subdirectory (%d entries)",NumDirEntries,0);
 return;
 }
 }
 if (DumpExifMap){
            printf("Map: %05d-%05d: Directory\n",(int)(DirStart-OffsetBase), (int)(DirEnd+4-OffsetBase));
 }

 }

 if (ShowTags){
        printf("(dir has %d entries)\n",NumDirEntries);
 }

 for (de=0;de<NumDirEntries;de++){
 int Tag, Format, Components;
 unsigned char * ValuePtr;
 int ByteCount;
 unsigned char * DirEntry;
 DirEntry = DIR_ENTRY_ADDR(DirStart, de);

 Tag = Get16u(DirEntry);
 Format = Get16u(DirEntry+2);
 Components = Get32u(DirEntry+4);

 if ((Format-1) >= NUM_FORMATS) {
 ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
 continue;
 }

 if ((unsigned)Components > 0x10000){
 ErrNonfatal("Illegal number of components %d for tag %04x", Components, Tag);
 continue;
 }

 ByteCount = Components * BytesPerFormat[Format];

 if (ByteCount > 4){

             unsigned OffsetVal;
             OffsetVal = Get32u(DirEntry+8);
            if (OffsetVal > UINT32_MAX - ByteCount || OffsetVal+ByteCount > ExifLength){
                 ErrNonfatal("Illegal value pointer for tag %04x", Tag,0);
                 continue;
 }
 ValuePtr = OffsetBase+OffsetVal;

 if (OffsetVal > ImageInfo.LargestExifOffset){
 ImageInfo.LargestExifOffset = OffsetVal;
 }

 if (DumpExifMap){
                printf("Map: %05d-%05d:   Data for tag %04x\n",OffsetVal, OffsetVal+ByteCount, Tag);
 }
 }else{
 ValuePtr = DirEntry+8;
 }

 if (Tag == TAG_MAKER_NOTE){
 if (ShowTags){
                printf("%s    Maker note: ",IndentString);
 }
 ProcessMakerNote(ValuePtr, ByteCount, OffsetBase, ExifLength);
 continue;
 }

 if (ShowTags){
 for (a=0;;a++){
 if (a >= (int)TAG_TABLE_SIZE){
                    printf("%s", IndentString);
                    printf("    Unknown Tag %04x Value = ", Tag);
 break;
 }
 if (TagTable[a].Tag == Tag){
                    printf("%s", IndentString);
                    printf("    %s = ",TagTable[a].Desc);
 break;
 }
 }

 switch(Format){
 case FMT_BYTE:
 if(ByteCount>1){
                        printf("%.*ls\n", ByteCount/2, (wchar_t *)ValuePtr);
 }else{
 PrintFormatNumber(ValuePtr, Format, ByteCount);
                        printf("\n");
 }
 break;

 case FMT_UNDEFINED:

 case FMT_STRING:
 {
                          printf("\"%s\"", ValuePtr);
 }
 break;

 default:
 PrintFormatNumber(ValuePtr, Format, ByteCount);
                    printf("\n");
 }
 }

 switch(Tag){

 case TAG_MAKE:
                strncpy(ImageInfo.CameraMake, (char *)ValuePtr, ByteCount < 31 ? ByteCount : 31);
 break;

 case TAG_MODEL:
                strncpy(ImageInfo.CameraModel, (char *)ValuePtr, ByteCount < 39 ? ByteCount : 39);
 break;

 case TAG_SUBSEC_TIME:
                strlcpy(ImageInfo.SubSecTime, (char *)ValuePtr, sizeof(ImageInfo.SubSecTime));
 break;

 case TAG_SUBSEC_TIME_ORIG:
                strlcpy(ImageInfo.SubSecTimeOrig, (char *)ValuePtr,
 sizeof(ImageInfo.SubSecTimeOrig));
 break;

 case TAG_SUBSEC_TIME_DIG:
                strlcpy(ImageInfo.SubSecTimeDig, (char *)ValuePtr,
 sizeof(ImageInfo.SubSecTimeDig));
 break;

 case TAG_DATETIME_DIGITIZED:
                strlcpy(ImageInfo.DigitizedTime, (char *)ValuePtr,
 sizeof(ImageInfo.DigitizedTime));

 if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
 ErrNonfatal("More than %d date fields!  This is nuts", MAX_DATE_COPIES, 0);
 break;
 }
 ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
 (char *)ValuePtr - (char *)OffsetBase;
 break;

 case TAG_DATETIME_ORIGINAL:
                strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);

 case TAG_DATETIME:
 if (!isdigit(ImageInfo.DateTime[0])){
                    strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
 }

 if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
 ErrNonfatal("More than %d date fields!  This is nuts", MAX_DATE_COPIES, 0);
 break;
 }
 ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
 (char *)ValuePtr - (char *)OffsetBase;
 break;

 case TAG_WINXP_COMMENT:
 if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
 if (ShowTags) printf("Windows XP commend and other comment in header\n");
 break; // Already have a windows comment, skip this one.
 }

 if (ByteCount > 1){
 if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE;
                    memcpy(ImageInfo.Comments, ValuePtr, ByteCount);
 ImageInfo.CommentWidchars = ByteCount/2;
 }
 break;

 case TAG_USERCOMMENT:
 if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
 if (ShowTags) printf("Multiple comments in exif header\n");
 break; // Already have a windows comment, skip this one.
 }

 for (a=ByteCount;;){
                    a--;
 if ((ValuePtr)[a] == ' '){
 (ValuePtr)[a] = '\0';
 }else{
 break;
 }
 if (a == 0) break;
 }

 {
 int msiz = ExifLength - (ValuePtr-OffsetBase);
 if (msiz > ByteCount) msiz = ByteCount;
 if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1;
 if (msiz > 5 && memcmp(ValuePtr, "ASCII", 5) == 0) {
 for (a = 5; a < 10 && a < msiz; a++) {
 int c = (ValuePtr)[a];
 if (c != '\0' && c != ' ') {
                                strncpy(ImageInfo.Comments,
 (char *)ValuePtr + a, msiz - a);
 break;
 }
 }
 } else {
                        strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz);
 }
 }
 break;

 case TAG_FNUMBER:
 ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_APERTURE:
 case TAG_MAXAPERTURE:
 if (ImageInfo.ApertureFNumber == 0){
 ImageInfo.ApertureFNumber
 = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5);
 }
 break;

 case TAG_FOCALLENGTH:
 ImageInfo.FocalLength.num = Get32u(ValuePtr);
 ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr);
 break;

 case TAG_SUBJECT_DISTANCE:
 ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_EXPOSURETIME:
 ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_SHUTTERSPEED:
 if (ImageInfo.ExposureTime == 0){
 ImageInfo.ExposureTime
 = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2)));
 }
 break;

 case TAG_FLASH:
 ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_ORIENTATION:
 if (NumOrientations >= 2){
 ErrNonfatal("More than two orientation tags!",0,0);
 break;
 }
 OrientationPtr[NumOrientations] = ValuePtr;
 OrientationNumFormat[NumOrientations] = Format;
 if (NumOrientations == 0){
 ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
 }
 if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){
 ErrNonfatal("Undefined rotation value %d", ImageInfo.Orientation, 0);
 ImageInfo.Orientation = 0;
 }
 NumOrientations += 1;
 break;

 case TAG_EXIF_IMAGELENGTH:
 case TAG_EXIF_IMAGEWIDTH:
                a = (int)ConvertAnyFormat(ValuePtr, Format);
 if (ExifImageWidth < a) ExifImageWidth = a;
 break;

 case TAG_FOCAL_PLANE_XRES:
 FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_FOCAL_PLANE_UNITS:
 switch((int)ConvertAnyFormat(ValuePtr, Format)){
 case 1: FocalplaneUnits = 25.4; break; // inch
 case 2:
 FocalplaneUnits = 25.4;
 break;

 case 3: FocalplaneUnits = 10; break; // centimeter
 case 4: FocalplaneUnits = 1; break; // millimeter
 case 5: FocalplaneUnits = .001; break; // micrometer
 }
 break;

 case TAG_EXPOSURE_BIAS:
 ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_WHITEBALANCE:
 ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_LIGHT_SOURCE:
 ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_METERING_MODE:
 ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_EXPOSURE_PROGRAM:
 ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_EXPOSURE_INDEX:
 if (ImageInfo.ISOequivalent == 0){
 ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
 }
 break;

 case TAG_EXPOSURE_MODE:
 ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_ISO_EQUIVALENT:
 ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_DIGITALZOOMRATIO:
 ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_THUMBNAIL_OFFSET:
 ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
 DirWithThumbnailPtrs = DirStart;
 break;

 case TAG_THUMBNAIL_LENGTH:
 ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
 ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase;
 break;

 case TAG_EXIF_OFFSET:
 if (ShowTags) printf("%s    Exif Dir:",IndentString);

 case TAG_INTEROP_OFFSET:
 if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf("%s    Interop Dir:",IndentString);
 {
 unsigned char * SubdirStart;
 SubdirStart = OffsetBase + Get32u(ValuePtr);
 if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
 ErrNonfatal("Illegal exif or interop ofset directory link",0,0);
 }else{
 ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
 }
 continue;
 }
 break;

 case TAG_GPSINFO:
 if (ShowTags) printf("%s    GPS info dir:",IndentString);
 {
 unsigned char * SubdirStart;
 SubdirStart = OffsetBase + Get32u(ValuePtr);
 if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
 ErrNonfatal("Illegal GPS directory link",0,0);
 }else{
 ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength);
 }
 continue;
 }
 break;

 case TAG_FOCALLENGTH_35MM:
 ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format);
 break;

 case TAG_DISTANCE_RANGE:
 ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format);
 break;
 }
 }

 {
 unsigned char * SubdirStart;
 unsigned Offset;

 if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
            printf("DirStart %p offset from dirstart %d", DirStart, 2+12*NumDirEntries);
 Offset = Get32u(DirStart+2+12*NumDirEntries);
 if (Offset){
 SubdirStart = OffsetBase + Offset;
 if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){
                    printf("SubdirStart %p OffsetBase %p ExifLength %d Offset %d",
 SubdirStart, OffsetBase, ExifLength, Offset);
 if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){
 if (ShowTags) printf("Thumbnail removed with Jhead 1.3 or earlier\n");
 }else{
 ErrNonfatal("Illegal subdirectory link",0,0);
 }
 }else{
 if (SubdirStart <= OffsetBase+ExifLength){
 if (ShowTags) printf("%s    Continued directory ",IndentString);
 ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
 }
 }
 if (Offset > ImageInfo.LargestExifOffset){
 ImageInfo.LargestExifOffset = Offset;
 }
 }
 }else{
 }
 }

 if (ThumbnailOffset){
 ImageInfo.ThumbnailAtEnd = FALSE;

 if (DumpExifMap){
            printf("Map: %05d-%05d: Thumbnail\n",ThumbnailOffset, ThumbnailOffset+ThumbnailSize);
 }

 if (ThumbnailOffset <= ExifLength){
 if (ThumbnailSize > ExifLength-ThumbnailOffset){
 ThumbnailSize = ExifLength-ThumbnailOffset;
 if (ShowTags) printf("Thumbnail incorrectly placed in header\n");

 }
 ImageInfo.ThumbnailOffset = ThumbnailOffset;
 ImageInfo.ThumbnailSize = ThumbnailSize;

 if (ShowTags){
                printf("Thumbnail size: %d bytes\n",ThumbnailSize);
 }
 }
 }
    printf("returning from ProcessExifDir");
}


bool WindowsServiceControl::isRegistered()
{
	return m_serviceHandle != nullptr;
}


static void hns_xgmac_get_stats(void *mac_drv, u64 *data)
{
	u32 i;
	u64 *buf = data;
	struct mac_driver *drv = (struct mac_driver *)mac_drv;
	struct mac_hw_stats *hw_stats = NULL;

	hw_stats = &drv->mac_cb->hw_stats;

	for (i = 0; i < ARRAY_SIZE(g_xgmac_stats_string); i++) {
		buf[i] = DSAF_STATS_READ(hw_stats,
			g_xgmac_stats_string[i].offset);
	}
}


void RenderWidgetHostImpl::LostCapture() {
  if (touch_emulator_)
    touch_emulator_->CancelTouch();

  Send(new InputMsg_MouseCaptureLost(routing_id_));

  if (delegate_)
    delegate_->LostCapture(this);
}


int pgpPubkeyFingerprint(const uint8_t *h, size_t hlen,
			  uint8_t **fp, size_t *fplen)
{
    int rc = -1; /* assume failure */
    const uint8_t *se;
    const uint8_t *pend = h + hlen;
    uint8_t version = 0;

    if (pgpVersion(h, hlen, &version))
	return rc;

    /* We only permit V4 keys, V3 keys are long long since deprecated */
    switch (version) {
    case 4:
      {	pgpPktKeyV4 v = (pgpPktKeyV4) (h);
	int mpis = -1;

	/* Packet must be larger than v to have room for the required MPIs */
	if (hlen > sizeof(*v)) {
	    switch (v->pubkey_algo) {
	    case PGPPUBKEYALGO_RSA:
		mpis = 2;
		break;
	    case PGPPUBKEYALGO_DSA:
		mpis = 4;
		break;
	    case PGPPUBKEYALGO_EDDSA:
		mpis = 1;
		break;
	    }
	}

	se = (uint8_t *)(v + 1);
	/* EdDSA has a curve id before the MPIs */
	if (v->pubkey_algo == PGPPUBKEYALGO_EDDSA) {
	    if (se < pend && se[0] != 0x00 && se[0] != 0xff)
		se += 1 + se[0];
	    else
		se = pend;      /* error out when reading the MPI */
	}
	while (se < pend && mpis-- > 0)
	    se += pgpMpiLen(se);

	/* Does the size and number of MPI's match our expectations? */
	if (se == pend && mpis == 0) {
	    DIGEST_CTX ctx = rpmDigestInit(PGPHASHALGO_SHA1, RPMDIGEST_NONE);
	    uint8_t *d = NULL;
	    size_t dlen = 0;
	    int i = se - h;
	    uint8_t in[3] = { 0x99, (i >> 8), i };

	    (void) rpmDigestUpdate(ctx, in, 3);
	    (void) rpmDigestUpdate(ctx, h, i);
	    (void) rpmDigestFinal(ctx, (void **)&d, &dlen, 0);

	    if (dlen == 20) {
		rc = 0;
		*fp = d;
		*fplen = dlen;
	    } else {
		free(d);
	    }
	}

      }	break;
    default:
	rpmlog(RPMLOG_WARNING, _("Unsupported version of key: V%d\n"), version);
    }
    return rc;
}


float SVGLayoutSupport::calculateScreenFontSizeScalingFactor(const LayoutObject* layoutObject)
{
    ASSERT(layoutObject);

     AffineTransform ctm = deprecatedCalculateTransformToLayer(layoutObject) * SubtreeContentTransformScope::currentContentTransformation();
     ctm.scale(layoutObject->document().frameHost()->deviceScaleFactorDeprecated());

    return narrowPrecisionToFloat(sqrt((ctm.xScaleSquared() + ctm.yScaleSquared()) / 2));
 }


int follow_down(struct path *path)
{
	struct vfsmount *mounted;

	mounted = lookup_mnt(path);
	if (mounted) {
		dput(path->dentry);
		mntput(path->mnt);
		path->mnt = mounted;
		path->dentry = dget(mounted->mnt_root);
		return 1;
	}
	return 0;
}


static void release_unused_pictures(H264Context *h, int remove_current)
{
    int i;

    /* release non reference frames */
    for (i = 0; i < MAX_PICTURE_COUNT; i++) {
        if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
            (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
            unref_picture(h, &h->DPB[i]);
        }
    }
}


void GLES2DecoderImpl::DoGenerateMipmap(GLenum target) {
  TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget(
      &state_, target);
  if (!texture_ref ||
      !texture_manager()->CanGenerateMipmaps(texture_ref)) {
    LOCAL_SET_GL_ERROR(
        GL_INVALID_OPERATION, "glGenerateMipmap", "Can not generate mips");
    return;
  }
  Texture* tex = texture_ref->texture();
  GLint base_level = tex->base_level();

  if (target == GL_TEXTURE_CUBE_MAP) {
    for (int i = 0; i < 6; ++i) {
      GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X + i;
      if (!texture_manager()->ClearTextureLevel(this, texture_ref, face,
                                                base_level)) {
        LOCAL_SET_GL_ERROR(
            GL_OUT_OF_MEMORY, "glGenerateMipmap", "dimensions too big");
        return;
      }
    }
  } else {
    if (!texture_manager()->ClearTextureLevel(this, texture_ref, target,
                                              base_level)) {
      LOCAL_SET_GL_ERROR(
          GL_OUT_OF_MEMORY, "glGenerateMipmap", "dimensions too big");
      return;
    }
  }

  LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("glGenerateMipmap");
  bool texture_zero_level_set = false;
  GLenum type = 0;
  GLenum internal_format = 0;
  GLenum format = 0;
  if (workarounds().set_zero_level_before_generating_mipmap &&
      target == GL_TEXTURE_2D) {
    if (base_level != 0 &&
        !tex->GetLevelType(target, 0, &type, &internal_format) &&
        tex->GetLevelType(target, tex->base_level(), &type, &internal_format)) {
      format = TextureManager::ExtractFormatFromStorageFormat(internal_format);
      ScopedPixelUnpackState reset_restore(&state_);
      api()->glTexImage2DFn(target, 0, internal_format, 1, 1, 0, format, type,
                            nullptr);
      texture_zero_level_set = true;
    }
  }

  bool enable_srgb = 0;
  if (target == GL_TEXTURE_2D) {
    tex->GetLevelType(target, tex->base_level(), &type, &internal_format);
    enable_srgb = GLES2Util::GetColorEncodingFromInternalFormat(
                      internal_format) == GL_SRGB;
  }
  if (enable_srgb && feature_info_->feature_flags().desktop_srgb_support) {
    state_.EnableDisableFramebufferSRGB(enable_srgb);
  }
  if (enable_srgb && workarounds().decode_encode_srgb_for_generatemipmap) {
    if (target == GL_TEXTURE_2D) {
      if (!InitializeSRGBConverter("generateMipmap")) {
        return;
      }
      srgb_converter_->GenerateMipmap(this, tex, target);
    } else {
      api()->glGenerateMipmapEXTFn(target);
    }
  } else {
    api()->glGenerateMipmapEXTFn(target);
  }

  if (texture_zero_level_set) {
    ScopedPixelUnpackState reset_restore(&state_);
    api()->glTexImage2DFn(target, 0, internal_format, 0, 0, 0, format, type,
                          nullptr);
  }

  GLenum error = LOCAL_PEEK_GL_ERROR("glGenerateMipmap");
  if (error == GL_NO_ERROR) {
    texture_manager()->MarkMipmapsGenerated(texture_ref);
  }
}


static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _deep_copy ( const STACK_OF ( t1 ) * sk , sk_ ## t1 ## _copyfunc copyfunc , sk_ ## t1 ## _freefunc freefunc ) {
 return ( STACK_OF ( t1 ) * ) OPENSSL_sk_deep_copy ( ( const OPENSSL_STACK * ) sk , ( OPENSSL_sk_copyfunc ) copyfunc , ( OPENSSL_sk_freefunc ) freefunc ) ;
 }
 static ossl_inline sk_ ## t1 ## _compfunc sk_ ## t1 ## _set_cmp_func ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _compfunc compare ) {
 return ( sk_ ## t1 ## _compfunc ) OPENSSL_sk_set_cmp_func ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_compfunc ) compare ) ;
 }
 # define DEFINE_SPECIAL_STACK_OF ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , t2 , t2 ) # define DEFINE_STACK_OF ( t ) SKM_DEFINE_STACK_OF ( t , t , t ) # define DEFINE_SPECIAL_STACK_OF_CONST ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , const t2 , t2 ) # define DEFINE_STACK_OF_CONST ( t ) SKM_DEFINE_STACK_OF ( t , const t , t ) typedef char * OPENSSL_STRING ;
 typedef const char * OPENSSL_CSTRING ;
 DEFINE_SPECIAL_STACK_OF ( OPENSSL_STRING , char ) DEFINE_SPECIAL_STACK_OF_CONST ( OPENSSL_CSTRING , char )


static void section_free(void *ptr) {
 if (!ptr)
 return;

 section_t *section = ptr;
  osi_free(section->name);
  list_free(section->entries);
  osi_free(section);
}


int HttpProxyClientSocket::RestartWithAuth(const CompletionCallback& callback) {
  DCHECK_EQ(STATE_NONE, next_state_);
  DCHECK(user_callback_.is_null());

  int rv = PrepareForAuthRestart();
  if (rv != OK)
    return rv;

  rv = DoLoop(OK);
  if (rv == ERR_IO_PENDING) {
    if (!callback.is_null())
      user_callback_ =  callback;
  }

  return rv;
}


  void OnTimeout() {
    LOG_IF(ERROR, is_removing_) << "Timed out";
    SignalDone();
  }


IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
 stream_t *ps_stream;
    ps_stream = &ps_dec->s_bit_stream;
    UWORD16 u2_height;
    UWORD16 u2_width;

 if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
 {
        impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
 return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;

 }
    impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);

    u2_width    = impeg2d_bit_stream_get(ps_stream,12);
    u2_height   = impeg2d_bit_stream_get(ps_stream,12);

 if ((u2_width != ps_dec->u2_horizontal_size)
 || (u2_height != ps_dec->u2_vertical_size))
 {
 if (0 == ps_dec->u2_header_done)
 {
 /* This is the first time we are reading the resolution */
            ps_dec->u2_horizontal_size = u2_width;
            ps_dec->u2_vertical_size = u2_height;
 if (0 == ps_dec->u4_frm_buf_stride)
 {
                ps_dec->u4_frm_buf_stride  = (UWORD32) ALIGN16(u2_width);
 }
 }
 else
 {
 if((u2_width > ps_dec->u2_create_max_width)
 || (u2_height > ps_dec->u2_create_max_height))
 {
                IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;

                ps_dec->u2_reinit_max_height   = u2_height;
                ps_dec->u2_reinit_max_width    = u2_width;

 return e_error;
 }
 else
 {
 /* The resolution has changed */
 return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
 }
 }
 }

 if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
 || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
 {
        IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
 return SET_IVD_FATAL_ERROR(e_error);
 }

 /*------------------------------------------------------------------------*/
 /* Flush the following as they are not being used                         */
 /* aspect_ratio_info (4 bits)                                             */
 /*------------------------------------------------------------------------*/
    ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);

 /*------------------------------------------------------------------------*/

     /* Frame rate code(4 bits)                                                */
     /*------------------------------------------------------------------------*/
     ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
     /*------------------------------------------------------------------------*/
     /* Flush the following as they are not being used                         */
     /* bit_rate_value (18 bits)                                               */
 /*------------------------------------------------------------------------*/
    impeg2d_bit_stream_flush(ps_stream,18);
    GET_MARKER_BIT(ps_dec,ps_stream);
 /*------------------------------------------------------------------------*/
 /* Flush the following as they are not being used                         */
 /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit)     */
 /*------------------------------------------------------------------------*/
    impeg2d_bit_stream_flush(ps_stream,11);

 /*------------------------------------------------------------------------*/
 /* Quantization matrix for the intra blocks                               */
 /*------------------------------------------------------------------------*/
 if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
 {
        UWORD16 i;
 for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
 {
            ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
 }

 }
 else
 {
        memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
                NUM_PELS_IN_BLOCK);
 }

 /*------------------------------------------------------------------------*/
 /* Quantization matrix for the inter blocks                               */
 /*------------------------------------------------------------------------*/
 if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
 {
        UWORD16 i;
 for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
 {
            ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
 }
 }
 else
 {
        memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
            NUM_PELS_IN_BLOCK);
 }
    impeg2d_next_start_code(ps_dec);

 return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}


 static void build_l4proto_tcp(const struct nf_conntrack *ct, struct nethdr *n)
 {
 	if (!nfct_attr_is_set(ct, ATTR_TCP_STATE))
 		return;

	ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
		      sizeof(struct nfct_attr_grp_port));
 	ct_build_u8(ct, ATTR_TCP_STATE, n, NTA_TCP_STATE);
 	if (CONFIG(sync).tcp_window_tracking) {
 		ct_build_u8(ct, ATTR_TCP_WSCALE_ORIG, n, NTA_TCP_WSCALE_ORIG);
		ct_build_u8(ct, ATTR_TCP_WSCALE_REPL, n, NTA_TCP_WSCALE_REPL);
	}
}


png_create_info_struct(png_structp png_ptr)
{
   png_infop info_ptr;

   png_debug(1, "in png_create_info_struct");

   if (png_ptr == NULL)
      return (NULL);

#ifdef PNG_USER_MEM_SUPPORTED
   info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
      png_ptr->malloc_fn, png_ptr->mem_ptr);
#else
   info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
#endif
   if (info_ptr != NULL)
      png_info_init_3(&info_ptr, png_sizeof(png_info));

   return (info_ptr);
}


static CURLcode imap_select(struct connectdata *conn)
{
  CURLcode result = CURLE_OK;
  struct imap_conn *imapc = &conn->proto.imapc;
  const char *str;

  str = getcmdid(conn);

  result = imapsendf(conn, str, "%s SELECT %s", str,
                     imapc->mailbox?imapc->mailbox:"");
  if(result)
    return result;

  state(conn, IMAP_SELECT);
  return result;
}


int ff_xvmc_field_start(MpegEncContext *s, AVCodecContext *avctx)

{

    struct xvmc_pix_fmt *last, *next, *render = (struct xvmc_pix_fmt*)s->current_picture.data[2];

    const int mb_block_count = 4 + (1 << s->chroma_format);

    assert(avctx);

    if (!render || render->xvmc_id != AV_XVMC_ID ||

        !render->data_blocks || !render->mv_blocks) {

        av_log(avctx, AV_LOG_ERROR,

               "Render token doesn't look as expected.\n");

        return -1; // make sure that this is a render packet

    }

    if (render->filled_mv_blocks_num) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface contains %i unprocessed blocks.\n",

               render->filled_mv_blocks_num);

        return -1;

    }

    if (render->allocated_mv_blocks   < 1 ||

        render->allocated_data_blocks <  render->allocated_mv_blocks*mb_block_count ||

        render->start_mv_blocks_num   >= render->allocated_mv_blocks                ||

        render->next_free_data_block_num >

                        render->allocated_data_blocks -

                        mb_block_count*(render->allocated_mv_blocks-render->start_mv_blocks_num)) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface doesn't provide enough block structures to work with.\n");

        return -1;

    }

    render->picture_structure = s->picture_structure;

    render->flags             = s->first_field ? 0 : XVMC_SECOND_FIELD;

    render->p_future_surface  = NULL;

    render->p_past_surface    = NULL;

    switch(s->pict_type) {

        case  FF_I_TYPE:

            return 0; // no prediction from other frames

        case  FF_B_TYPE:

            next = (struct xvmc_pix_fmt*)s->next_picture.data[2];

            if (!next)

                return -1;

            if (next->xvmc_id != AV_XVMC_ID)

                return -1;

            render->p_future_surface = next->p_surface;

            // no return here, going to set forward prediction

        case  FF_P_TYPE:

            last = (struct xvmc_pix_fmt*)s->last_picture.data[2];

            if (!last)

                last = render; // predict second field from the first

            if (last->xvmc_id != AV_XVMC_ID)

                return -1;

            render->p_past_surface = last->p_surface;

            return 0;

    }

return -1;

}


int mbfl_strlen ( mbfl_string * string ) {
 int len , n , m , k ;
 unsigned char * p ;
 const unsigned char * mbtab ;
 const mbfl_encoding * encoding ;
 encoding = mbfl_no2encoding ( string -> no_encoding ) ;
 if ( encoding == NULL || string == NULL ) {
 return - 1 ;
 }
 len = 0 ;
 if ( encoding -> flag & MBFL_ENCTYPE_SBCS ) {
 len = string -> len ;
 }
 else if ( encoding -> flag & ( MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE ) ) {
 len = string -> len / 2 ;
 }
 else if ( encoding -> flag & ( MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE ) ) {
 len = string -> len / 4 ;
 }
 else if ( encoding -> mblen_table != NULL ) {
 mbtab = encoding -> mblen_table ;
 n = 0 ;
 p = string -> val ;
 k = string -> len ;
 if ( p != NULL ) {
 while ( n < k ) {
 m = mbtab [ * p ] ;
 n += m ;
 p += m ;
 len ++ ;
 }
 ;
 }
 }
 else {
 mbfl_convert_filter * filter = mbfl_convert_filter_new ( string -> no_encoding , mbfl_no_encoding_wchar , filter_count_output , 0 , & len ) ;
 if ( filter == NULL ) {
 return - 1 ;
 }
 n = string -> len ;
 p = string -> val ;
 if ( p != NULL ) {
 while ( n > 0 ) {
 ( * filter -> filter_function ) ( * p ++ , filter ) ;
 n -- ;
 }
 }
 mbfl_convert_filter_delete ( filter ) ;
 }
 return len ;
 }


file_buffer(struct magic_set *ms, int fd, const char *inname __attribute__ ((unused)),
    const void *buf, size_t nb)
{
	int m = 0, rv = 0, looks_text = 0;
	int mime = ms->flags & MAGIC_MIME;
	const unsigned char *ubuf = CAST(const unsigned char *, buf);
	unichar *u8buf = NULL;
	size_t ulen;
	const char *code = NULL;
	const char *code_mime = "binary";
	const char *type = "application/octet-stream";
	const char *def = "data";
	const char *ftype = NULL;

	if (nb == 0) {
		def = "empty";
		type = "application/x-empty";
		goto simple;
	} else if (nb == 1) {
		def = "very short file (no magic)";
		goto simple;
	}

	if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
		looks_text = file_encoding(ms, ubuf, nb, &u8buf, &ulen,
		    &code, &code_mime, &ftype);
	}

#ifdef __EMX__
	if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
		switch (file_os2_apptype(ms, inname, buf, nb)) {
		case -1:
			return -1;
		case 0:
			break;
		default:
			return 1;
		}
	}
#endif
#if HAVE_FORK
	/* try compression stuff */
	if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0)
		if ((m = file_zmagic(ms, fd, inname, ubuf, nb)) != 0) {
			if ((ms->flags & MAGIC_DEBUG) != 0)
				(void)fprintf(stderr, "zmagic %d\n", m);
			goto done_encoding;
		}
#endif
	/* Check if we have a tar file */
	if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0)
		if ((m = file_is_tar(ms, ubuf, nb)) != 0) {
			if ((ms->flags & MAGIC_DEBUG) != 0)
				(void)fprintf(stderr, "tar %d\n", m);
			goto done;
		}

	/* Check if we have a CDF file */
	if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0)
		if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) {
			if ((ms->flags & MAGIC_DEBUG) != 0)
				(void)fprintf(stderr, "cdf %d\n", m);
			goto done;
		}

	/* try soft magic tests */
	if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0)
		if ((m = file_softmagic(ms, ubuf, nb, 0, BINTEST,
		    looks_text)) != 0) {
			if ((ms->flags & MAGIC_DEBUG) != 0)
				(void)fprintf(stderr, "softmagic %d\n", m);
#ifdef BUILTIN_ELF
			if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
			    nb > 5 && fd != -1) {
				/*
				 * We matched something in the file, so this
				 * *might* be an ELF file, and the file is at
				 * least 5 bytes long, so if it's an ELF file
				 * it has at least one byte past the ELF magic
				 * number - try extracting information from the
				 * ELF headers that cannot easily * be
				 * extracted with rules in the magic file.
				 */
				if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0)
					if ((ms->flags & MAGIC_DEBUG) != 0)
						(void)fprintf(stderr,
						    "elf %d\n", m);
			}
#endif
			goto done;
		}

	/* try text properties */
	if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {

		if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) {
			if ((ms->flags & MAGIC_DEBUG) != 0)
				(void)fprintf(stderr, "ascmagic %d\n", m);
			goto done;
		}
	}

simple:
	/* give up */
	m = 1;
	if ((!mime || (mime & MAGIC_MIME_TYPE)) &&
	    file_printf(ms, "%s", mime ? type : def) == -1) {
	    rv = -1;
	}
 done:
	if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
		if (ms->flags & MAGIC_MIME_TYPE)
			if (file_printf(ms, "; charset=") == -1)
				rv = -1;
		if (file_printf(ms, "%s", code_mime) == -1)
			rv = -1;
	}
#if HAVE_FORK
 done_encoding:
#endif
	free(u8buf);
	if (rv)
		return rv;

	return m;
}


png_write_sRGB(png_structp png_ptr, int srgb_intent)
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_sRGB;
#endif
   png_byte buf[1];

   png_debug(1, "in png_write_sRGB");

   if (srgb_intent >= PNG_sRGB_INTENT_LAST)
         png_warning(png_ptr,
            "Invalid sRGB rendering intent specified");
   buf[0]=(png_byte)srgb_intent;
   png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1);
}


void MessageLoop::RemoveDestructionObserver(
    DestructionObserver* destruction_observer) {
  DCHECK_EQ(this, current());
  destruction_observers_.RemoveObserver(destruction_observer);
}


RunLoop::Delegate::~Delegate() {
  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
  if (bound_)
    tls_delegate.Get().Set(nullptr);
}


void FrameLoader::updateFirstPartyForCookies()
{
    if (m_frame->tree()->parent())
        setFirstPartyForCookies(m_frame->tree()->parent()->document()->firstPartyForCookies());
    else
        setFirstPartyForCookies(m_URL);
}


static void __perf_event_exit_context(void *__info)
{
	struct perf_event_context *ctx = __info;
	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
	struct perf_event *event;

	raw_spin_lock(&ctx->lock);
	list_for_each_entry(event, &ctx->event_list, event_entry)
		__perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
	raw_spin_unlock(&ctx->lock);
}


void Plugin::GetExitStatus(NaClSrpcArg* prop_value) {
  PLUGIN_PRINTF(("GetExitStatus (this=%p)\n", reinterpret_cast<void*>(this)));
  prop_value->tag = NACL_SRPC_ARG_TYPE_INT;
  prop_value->u.ival = exit_status();
}


static void check_unshare_flags(unsigned long *flags_ptr)
{
	/*
	 * If unsharing a thread from a thread group, must also
	 * unshare vm.
	 */
	if (*flags_ptr & CLONE_THREAD)
		*flags_ptr |= CLONE_VM;

	/*
	 * If unsharing vm, must also unshare signal handlers.
	 */
	if (*flags_ptr & CLONE_VM)
		*flags_ptr |= CLONE_SIGHAND;

	/*
	 * If unsharing namespace, must also unshare filesystem information.
	 */
	if (*flags_ptr & CLONE_NEWNS)
		*flags_ptr |= CLONE_FS;
}


static dma_addr_t arm_coherent_iommu_map_page(struct device *dev, struct page *page,
	     unsigned long offset, size_t size, enum dma_data_direction dir,
	     struct dma_attrs *attrs)
{
	struct dma_iommu_mapping *mapping = dev->archdata.mapping;
	dma_addr_t dma_addr;
	int ret, prot, len = PAGE_ALIGN(size + offset);

	dma_addr = __alloc_iova(mapping, len);
	if (dma_addr == DMA_ERROR_CODE)
		return dma_addr;

	switch (dir) {
	case DMA_BIDIRECTIONAL:
		prot = IOMMU_READ | IOMMU_WRITE;
		break;
	case DMA_TO_DEVICE:
		prot = IOMMU_READ;
		break;
	case DMA_FROM_DEVICE:
		prot = IOMMU_WRITE;
		break;
	default:
		prot = 0;
	}

	ret = iommu_map(mapping->domain, dma_addr, page_to_phys(page), len, prot);
	if (ret < 0)
		goto fail;

	return dma_addr + offset;
fail:
	__free_iova(mapping, dma_addr, len);
	return DMA_ERROR_CODE;
}


int sock_map_fd(struct socket *sock, int flags)
{
	struct file *newfile;
	int fd = sock_alloc_file(sock, &newfile, flags);

	if (likely(fd >= 0))
		fd_install(fd, newfile);

	return fd;
}


WebContents* WebContents::Create(const WebContents::CreateParams& params) {
  return WebContentsImpl::CreateWithOpener(
      params, static_cast<WebContentsImpl*>(params.opener));
}