static int nntp_msg_open(struct Mailbox *m, struct Message *msg, int msgno)
{
  if (!m || !m->emails || (msgno >= m->msg_count) || !msg)
    return -1;

  struct NntpMboxData *mdata = m->mdata;
  struct Email *e = m->emails[msgno];
  if (!e)
    return -1;

  char article[16];

  /* try to get article from cache */
  struct NntpAcache *acache = &mdata->acache[e->index % NNTP_ACACHE_LEN];
  if (acache->path)
  {
    if (acache->index == e->index)
    {
      msg->fp = mutt_file_fopen(acache->path, "r");
      if (msg->fp)
        return 0;
    }
    /* clear previous entry */
    else
    {
      unlink(acache->path);
      FREE(&acache->path);
    }
  }
  snprintf(article, sizeof(article), ANUM, nntp_edata_get(e)->article_num);
  msg->fp = mutt_bcache_get(mdata->bcache, article);
  if (msg->fp)
  {
    if (nntp_edata_get(e)->parsed)
      return 0;
  }
  else
  {
    char buf[PATH_MAX];
    /* don't try to fetch article from removed newsgroup */
    if (mdata->deleted)
      return -1;

    /* create new cache file */
    const char *fetch_msg = _("Fetching message...");
    mutt_message(fetch_msg);
    msg->fp = mutt_bcache_put(mdata->bcache, article);
    if (!msg->fp)
    {
      mutt_mktemp(buf, sizeof(buf));
      acache->path = mutt_str_strdup(buf);
      acache->index = e->index;
      msg->fp = mutt_file_fopen(acache->path, "w+");
      if (!msg->fp)
      {
        mutt_perror(acache->path);
        unlink(acache->path);
        FREE(&acache->path);
        return -1;
      }
    }

    /* fetch message to cache file */
    snprintf(buf, sizeof(buf), "ARTICLE %s\r\n",
             nntp_edata_get(e)->article_num ? article : e->env->message_id);
    const int rc =
        nntp_fetch_lines(mdata, buf, sizeof(buf), fetch_msg, fetch_tempfile, msg->fp);
    if (rc)
    {
      mutt_file_fclose(&msg->fp);
      if (acache->path)
      {
        unlink(acache->path);
        FREE(&acache->path);
      }
      if (rc > 0)
      {
        if (mutt_str_startswith(buf, nntp_edata_get(e)->article_num ? "423" : "430", CASE_MATCH))
        {
          mutt_error(_("Article %s not found on the server"),
                     nntp_edata_get(e)->article_num ? article : e->env->message_id);
        }
        else
          mutt_error("ARTICLE: %s", buf);
      }
      return -1;
    }

    if (!acache->path)
      mutt_bcache_commit(mdata->bcache, article);
  }

  /* replace envelope with new one
   * hash elements must be updated because pointers will be changed */
  if (m->id_hash && e->env->message_id)
    mutt_hash_delete(m->id_hash, e->env->message_id, e);
  if (m->subj_hash && e->env->real_subj)
    mutt_hash_delete(m->subj_hash, e->env->real_subj, e);

  mutt_env_free(&e->env);
  e->env = mutt_rfc822_read_header(msg->fp, e, false, false);

  if (m->id_hash && e->env->message_id)
    mutt_hash_insert(m->id_hash, e->env->message_id, e);
  if (m->subj_hash && e->env->real_subj)
    mutt_hash_insert(m->subj_hash, e->env->real_subj, e);

  /* fix content length */
  fseek(msg->fp, 0, SEEK_END);
  e->content->length = ftell(msg->fp) - e->content->offset;

  /* this is called in neomutt before the open which fetches the message,
   * which is probably wrong, but we just call it again here to handle
   * the problem instead of fixing it */
  nntp_edata_get(e)->parsed = true;
  mutt_parse_mime_message(m, e);

  /* these would normally be updated in ctx_update(), but the
   * full headers aren't parsed with overview, so the information wasn't
   * available then */
  if (WithCrypto)
    e->security = crypt_query(e->content);

  rewind(msg->fp);
  mutt_clear_error();
  return 0;
}


 void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
  g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, request_id);
 }


void Buffered_logs::print()
{
  Buffered_log *log;
  List_iterator_fast<Buffered_log> it(m_list);
  while ((log= it++))
    log->print();
}


static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
        void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
{
#ifndef WOLFSSL_SMALL_STACK
    SignatureCtx  sigCtx[1];
#else
    SignatureCtx* sigCtx;
#endif
    byte          hash[KEYID_SIZE];
    Signer*       ca = NULL;
    word32        idx = 0;
    int           len;
    word32        tbsCertIdx = 0;
    word32        sigIndex   = 0;
    word32        signatureOID = 0;
    word32        oid = 0;
    word32        issuerIdx = 0;
    word32        issuerSz  = 0;
#ifndef NO_SKID
    int           extLen = 0;
    word32        extIdx = 0;
    word32        extEndIdx = 0;
    int           extAuthKeyIdSet = 0;
#endif
    int           ret = 0;
    word32        localIdx;
    byte          tag;

    if (cert == NULL) {
        return BAD_FUNC_ARG;
    }

#ifdef WOLFSSL_SMALL_STACK
    sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
    if (sigCtx == NULL)
        return MEMORY_E;
#endif
    InitSignatureCtx(sigCtx, heap, INVALID_DEVID);

    /* Certificate SEQUENCE */
    if (GetSequence(cert, &idx, &len, certSz) < 0)
        ret = ASN_PARSE_E;
    if (ret == 0) {
        tbsCertIdx = idx;

        /* TBSCertificate SEQUENCE */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        sigIndex = len + idx;

        if ((idx + 1) > certSz)
            ret = BUFFER_E;
    }
    if (ret == 0) {
        /* version - optional */
        localIdx = idx;
        if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
            if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
                idx++;
                if (GetLength(cert, &idx, &len, certSz) < 0)
                    ret = ASN_PARSE_E;
                idx += len;
            }
        }
    }

    if (ret == 0) {
        /* serialNumber */
        if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        idx += len;

        /* signature */
        if (!req &&
                GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
            ret = ASN_PARSE_E;
    }

    if (ret == 0) {
        issuerIdx = idx;
        /* issuer for cert or subject for csr */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        issuerSz = len + idx - issuerIdx;
    }
#ifndef NO_SKID
    if (!req && ret == 0) {
        idx += len;

        /* validity */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (!req && ret == 0) {
        idx += len;

        /* subject */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        idx += len;

        /* subjectPublicKeyInfo */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (req && ret == 0) {
        idx += len;

        /* attributes */
        if (GetASNHeader_ex(cert,
                ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
                &len, certSz, 1) < 0)
            ret = ASN_PARSE_E;
    }
    if (!req) {
        if (ret == 0) {
            idx += len;

            if ((idx + 1) > certSz)
                ret = BUFFER_E;
        }
        if (ret == 0) {
            /* issuerUniqueID - optional */
            localIdx = idx;
            if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
                if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
                    idx++;
                    if (GetLength(cert, &idx, &len, certSz) < 0)
                        ret = ASN_PARSE_E;
                    idx += len;
                }
            }
        }
        if (ret == 0) {
            if ((idx + 1) > certSz)
                ret = BUFFER_E;
        }
        if (ret == 0) {
            /* subjectUniqueID - optional */
            localIdx = idx;
            if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
                if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
                    idx++;
                    if (GetLength(cert, &idx, &len, certSz) < 0)
                        ret = ASN_PARSE_E;
                    idx += len;
                }
            }
        }

        if (ret == 0) {
            if ((idx + 1) > certSz)
                ret = BUFFER_E;
        }
        /* extensions - optional */
        localIdx = idx;
        if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
                tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
            idx++;
            if (GetLength(cert, &idx, &extLen, certSz) < 0)
                ret = ASN_PARSE_E;
            if (ret == 0) {
                if (GetSequence(cert, &idx, &extLen, certSz) < 0)
                    ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                extEndIdx = idx + extLen;

                /* Check each extension for the ones we want. */
                while (ret == 0 && idx < extEndIdx) {
                    if (GetSequence(cert, &idx, &len, certSz) < 0)
                        ret = ASN_PARSE_E;
                    if (ret == 0) {
                        extIdx = idx;
                        if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
                                                                      certSz) < 0) {
                            ret = ASN_PARSE_E;
                        }

                        if (ret == 0) {
                            if ((extIdx + 1) > certSz)
                                ret = BUFFER_E;
                        }
                    }

                    if (ret == 0) {
                        localIdx = extIdx;
                        if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
                                tag == ASN_BOOLEAN) {
                            if (GetBoolean(cert, &extIdx, certSz) < 0)
                                ret = ASN_PARSE_E;
                        }
                    }
                    if (ret == 0) {
                        if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
                            ret = ASN_PARSE_E;
                    }

                    if (ret == 0) {
                        switch (oid) {
                        case AUTH_KEY_OID:
                            if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
                                ret = ASN_PARSE_E;

                            if (ret == 0 && (extIdx + 1) >= certSz)
                                ret = BUFFER_E;

                            if (ret == 0 &&
                                    GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
                                    tag == (ASN_CONTEXT_SPECIFIC | 0)) {
                                if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
                                    ret = ASN_PARSE_E;
                                if (ret == 0) {
                                    extAuthKeyIdSet = 1;
                                    if (extLen == KEYID_SIZE)
                                        XMEMCPY(hash, cert + extIdx, extLen);
                                    else {
                                        ret = CalcHashId(cert + extIdx, extLen,
                                                                              hash);
                                    }
                                }
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    idx += len;
                }
            }
        }
    }
    else if (ret == 0) {
        idx += len;
    }

    if (ret == 0 && pubKey == NULL) {
        if (extAuthKeyIdSet)
            ca = GetCA(cm, hash);
        if (ca == NULL) {
            ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
            if (ret == 0)
                ca = GetCAByName(cm, hash);
        }
    }
#else
    if (ret == 0 && pubKey == NULL) {
        ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
        if (ret == 0)
            ca = GetCA(cm, hash);
    }
#endif /* !NO_SKID */
    if (ca == NULL && pubKey == NULL)
        ret = ASN_NO_SIGNER_E;

    if (ret == 0) {
        idx = sigIndex;
        /* signatureAlgorithm */
        if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
            ret = ASN_PARSE_E;
        /* In CSR signature data is not present in body */
        if (req)
            signatureOID = oid;
    }
    if (ret == 0) {
        if (oid != signatureOID)
            ret = ASN_SIG_OID_E;
    }
    if (ret == 0) {
        /* signatureValue */
        if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
            ret = ASN_PARSE_E;
    }

    if (ret == 0) {
        if (pubKey != NULL) {
            ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
                               sigIndex - tbsCertIdx,
                               pubKey, pubKeySz, pubKeyOID,
                               cert + idx, len, signatureOID, NULL);
        }
        else {
            ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
                               sigIndex - tbsCertIdx,
                               ca->publicKey, ca->pubKeySize, ca->keyOID,
                               cert + idx, len, signatureOID, NULL);
        }
        if (ret != 0) {
            WOLFSSL_MSG("Confirm signature failed");
        }
    }

    FreeSignatureCtx(sigCtx);
#ifdef WOLFSSL_SMALL_STACK
    if (sigCtx != NULL)
        XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
#endif
    return ret;
}


TEST_F ( SSLErrorAssistantTest , DynamicInterstitialListMatchBlank ) {
 ASSERT_TRUE ( embedded_test_server ( ) -> Start ( ) ) ;
 EXPECT_EQ ( 1u , ssl_info ( ) . public_key_hashes . size ( ) ) ;
 auto config_proto = std : : make_unique < chrome_browser_ssl : : SSLErrorAssistantConfig > ( ) ;
 config_proto -> set_version_id ( kLargeVersionId ) ;
 chrome_browser_ssl : : DynamicInterstitial * filter = config_proto -> add_dynamic_interstitial ( ) ;
 filter -> set_interstitial_type ( chrome_browser_ssl : : DynamicInterstitial : : INTERSTITIAL_PAGE_SSL ) ;
 error_assistant ( ) -> SetErrorAssistantProto ( std : : move ( config_proto ) ) ;
 base : : Optional < DynamicInterstitialInfo > dynamic_interstitial = error_assistant ( ) -> MatchDynamicInterstitial ( ssl_info ( ) ) ;
 ASSERT_TRUE ( dynamic_interstitial ) ;
 EXPECT_EQ ( chrome_browser_ssl : : DynamicInterstitial : : INTERSTITIAL_PAGE_SSL , dynamic_interstitial -> interstitial_type ) ;
 }


bool IsAutoplayAllowedByPolicy(content::WebContents* contents,
                               PrefService* prefs) {
  DCHECK(prefs);

  if (prefs->GetBoolean(prefs::kAutoplayAllowed) &&
      prefs->IsManagedPreference(prefs::kAutoplayAllowed)) {
    return true;
  }

  if (!contents)
    return false;

  const base::ListValue* autoplay_whitelist =
      prefs->GetList(prefs::kAutoplayWhitelist);
  return autoplay_whitelist &&
         prefs->IsManagedPreference(prefs::kAutoplayWhitelist) &&
         IsURLWhitelisted(contents->GetURL(), autoplay_whitelist->GetList());
}


lambda_function_body(
	char_u	    **arg,
	typval_T    *rettv,
	evalarg_T   *evalarg,
	garray_T    *newargs,
	garray_T    *argtypes,
	int	    varargs,
	garray_T    *default_args,
	char_u	    *ret_type)
{
    int		evaluate = (evalarg->eval_flags & EVAL_EVALUATE);
    garray_T	*gap = &evalarg->eval_ga;
    garray_T	*freegap = &evalarg->eval_freega;
    ufunc_T	*ufunc = NULL;
    exarg_T	eap;
    garray_T	newlines;
    char_u	*cmdline = NULL;
    int		ret = FAIL;
    partial_T	*pt;
    char_u	*name;
    int		lnum_save = -1;
    linenr_T	sourcing_lnum_top = SOURCING_LNUM;

    if (!ends_excmd2(*arg, skipwhite(*arg + 1)))
    {
	semsg(_(e_trailing_characters_str), *arg + 1);
	return FAIL;
    }

    CLEAR_FIELD(eap);
    eap.cmdidx = CMD_block;
    eap.forceit = FALSE;
    eap.cmdlinep = &cmdline;
    eap.skip = !evaluate;
    if (evalarg->eval_cctx != NULL)
	fill_exarg_from_cctx(&eap, evalarg->eval_cctx);
    else
    {
	eap.getline = evalarg->eval_getline;
	eap.cookie = evalarg->eval_cookie;
    }

    ga_init2(&newlines, sizeof(char_u *), 10);
    if (get_function_body(&eap, &newlines, NULL,
					     &evalarg->eval_tofree_ga) == FAIL)
	goto erret;

    // When inside a lambda must add the function lines to evalarg.eval_ga.
    evalarg->eval_break_count += newlines.ga_len;
    if (gap->ga_itemsize > 0)
    {
	int	idx;
	char_u	*last;
	size_t  plen;
	char_u  *pnl;

	for (idx = 0; idx < newlines.ga_len; ++idx)
	{
	    char_u  *p = skipwhite(((char_u **)newlines.ga_data)[idx]);

	    if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL)
		goto erret;

	    // Going to concatenate the lines after parsing.  For an empty or
	    // comment line use an empty string.
	    // Insert NL characters at the start of each line, the string will
	    // be split again later in .get_lambda_tv().
	    if (*p == NUL || vim9_comment_start(p))
		p = (char_u *)"";
	    plen = STRLEN(p);
	    pnl = vim_strnsave((char_u *)"\n", plen + 1);
	    if (pnl != NULL)
		mch_memmove(pnl + 1, p, plen + 1);
	    ((char_u **)gap->ga_data)[gap->ga_len++] = pnl;
	    ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl;
	}
	if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL)
	    goto erret;
	if (eap.nextcmd != NULL)
	    // more is following after the "}", which was skipped
	    last = cmdline;
	else
	    // nothing is following the "}"
	    last = (char_u *)"}";
	plen = STRLEN(last);
	pnl = vim_strnsave((char_u *)"\n", plen + 1);
	if (pnl != NULL)
	    mch_memmove(pnl + 1, last, plen + 1);
	((char_u **)gap->ga_data)[gap->ga_len++] = pnl;
	((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl;
    }

    if (eap.nextcmd != NULL)
    {
	garray_T *tfgap = &evalarg->eval_tofree_ga;

	// Something comes after the "}".
	*arg = eap.nextcmd;

	// "arg" points into cmdline, need to keep the line and free it later.
	if (ga_grow(tfgap, 1) == OK)
	{
	    ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline;
	    evalarg->eval_using_cmdline = TRUE;
	}
    }
    else
	*arg = (char_u *)"";

    if (!evaluate)
    {
	ret = OK;
	goto erret;
    }

    name = get_lambda_name();
    ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1);
    if (ufunc == NULL)
	goto erret;
    set_ufunc_name(ufunc, name);
    if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL)
	goto erret;
    ufunc->uf_flags = FC_LAMBDA;
    ufunc->uf_refcount = 1;
    ufunc->uf_args = *newargs;
    newargs->ga_data = NULL;
    ufunc->uf_def_args = *default_args;
    default_args->ga_data = NULL;
    ufunc->uf_func_type = &t_func_any;

    // error messages are for the first function line
    lnum_save = SOURCING_LNUM;
    SOURCING_LNUM = sourcing_lnum_top;

    // parse argument types
    if (parse_argument_types(ufunc, argtypes, varargs) == FAIL)
    {
	SOURCING_LNUM = lnum_save;
	goto erret;
    }

    // parse the return type, if any
    if (parse_return_type(ufunc, ret_type) == FAIL)
	goto erret;

    pt = ALLOC_CLEAR_ONE(partial_T);
    if (pt == NULL)
	goto erret;
    pt->pt_func = ufunc;
    pt->pt_refcount = 1;

    ufunc->uf_lines = newlines;
    newlines.ga_data = NULL;
    if (sandbox)
	ufunc->uf_flags |= FC_SANDBOX;
    if (!ASCII_ISUPPER(*ufunc->uf_name))
	ufunc->uf_flags |= FC_VIM9;
    ufunc->uf_script_ctx = current_sctx;
    ufunc->uf_script_ctx_version = current_sctx.sc_version;
    ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top;
    set_function_type(ufunc);

    function_using_block_scopes(ufunc, evalarg->eval_cstack);

    rettv->vval.v_partial = pt;
    rettv->v_type = VAR_PARTIAL;
    ufunc = NULL;
    ret = OK;

erret:
    if (lnum_save >= 0)
	SOURCING_LNUM = lnum_save;
    ga_clear_strings(&newlines);
    if (newargs != NULL)
	ga_clear_strings(newargs);
    ga_clear_strings(default_args);
    if (ufunc != NULL)
    {
	func_clear(ufunc, TRUE);
	func_free(ufunc, TRUE);
    }
    return ret;
}


static int check_a2dp_ready(struct a2dp_stream_common *common)
{
 if (a2dp_command(common, A2DP_CTRL_CMD_CHECK_READY) < 0)
 {
        ERROR("check a2dp ready failed");
 return -1;
 }
 return 0;
}


Jsi_RC Jsi_MapConf(Jsi_Map *mapPtr, Jsi_MapOpts *opts, bool set)
{
    switch (mapPtr->typ) {
        case JSI_MAP_HASH: return Jsi_HashConf(mapPtr->v.hash, opts, set);
        case JSI_MAP_TREE: return Jsi_TreeConf(mapPtr->v.tree, opts, set);
        case JSI_MAP_LIST: return Jsi_ListConf(mapPtr->v.list, opts, set);
        case JSI_MAP_NONE: break;
    }
    return JSI_ERROR;
}


static void yam_tx_byte(struct net_device *dev, struct yam_port *yp)
{
	struct sk_buff *skb;
	unsigned char b, temp;

	switch (yp->tx_state) {
	case TX_OFF:
		break;
	case TX_HEAD:
		if (--yp->tx_count <= 0) {
			if (!(skb = skb_dequeue(&yp->send_queue))) {
				ptt_off(dev);
				yp->tx_state = TX_OFF;
				break;
			}
			yp->tx_state = TX_DATA;
			if (skb->data[0] != 0) {
/*                              do_kiss_params(s, skb->data, skb->len); */
				dev_kfree_skb_any(skb);
				break;
			}
			yp->tx_len = skb->len - 1;	/* strip KISS byte */
			if (yp->tx_len >= YAM_MAX_FRAME || yp->tx_len < 2) {
        			dev_kfree_skb_any(skb);
				break;
			}
			skb_copy_from_linear_data_offset(skb, 1,
							 yp->tx_buf,
							 yp->tx_len);
			dev_kfree_skb_any(skb);
			yp->tx_count = 0;
			yp->tx_crcl = 0x21;
			yp->tx_crch = 0xf3;
			yp->tx_state = TX_DATA;
		}
		break;
	case TX_DATA:
		b = yp->tx_buf[yp->tx_count++];
		outb(b, THR(dev->base_addr));
		temp = yp->tx_crcl;
		yp->tx_crcl = chktabl[temp] ^ yp->tx_crch;
		yp->tx_crch = chktabh[temp] ^ b;
		if (yp->tx_count >= yp->tx_len) {
			yp->tx_state = TX_CRC1;
		}
		break;
	case TX_CRC1:
		yp->tx_crch = chktabl[yp->tx_crcl] ^ yp->tx_crch;
		yp->tx_crcl = chktabh[yp->tx_crcl] ^ chktabl[yp->tx_crch] ^ 0xff;
		outb(yp->tx_crcl, THR(dev->base_addr));
		yp->tx_state = TX_CRC2;
		break;
	case TX_CRC2:
		outb(chktabh[yp->tx_crch] ^ 0xFF, THR(dev->base_addr));
		if (skb_queue_empty(&yp->send_queue)) {
			yp->tx_count = (yp->bitrate * yp->txtail) / 8000;
			if (yp->dupmode == 2)
				yp->tx_count += (yp->bitrate * yp->holdd) / 8;
			if (yp->tx_count == 0)
				yp->tx_count = 1;
			yp->tx_state = TX_TAIL;
		} else {
			yp->tx_count = 1;
			yp->tx_state = TX_HEAD;
		}
		++dev->stats.tx_packets;
		break;
	case TX_TAIL:
		if (--yp->tx_count <= 0) {
			yp->tx_state = TX_OFF;
			ptt_off(dev);
		}
		break;
	}
}


ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
                             struct ofp11_queue_stats *qs11)
{
    qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
    qs11->queue_id = htonl(oqs->queue_id);
    qs11->tx_bytes = htonll(oqs->tx_bytes);
    qs11->tx_packets = htonll(oqs->tx_packets);
    qs11->tx_errors = htonll(oqs->tx_errors);
}


Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
{
    PERL_ARGS_ASSERT_CK_WARNER_D;

    if (Perl_ckwarn_d(aTHX_ err)) {
	va_list args;
	va_start(args, pat);
	vwarner(err, pat, &args);
	va_end(args);
    }
}


altivec_yuv2packedX (SwsContext *c,

		       int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

		       int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

		       uint8_t *dest, int dstW, int dstY)

{

  int i,j;

  vector signed short X,X0,X1,Y0,U0,V0,Y1,U1,V1,U,V;

  vector signed short R0,G0,B0,R1,G1,B1;

  vector unsigned char R,G,B;

  vector unsigned char *out,*nout;

  vector signed short   RND = vec_splat_s16(1<<3);

  vector unsigned short SCL = vec_splat_u16(4);

  unsigned long scratch[16] __attribute__ ((aligned (16)));

  vector signed short *YCoeffs, *CCoeffs;

  YCoeffs = c->vYCoeffsBank+dstY*lumFilterSize;

  CCoeffs = c->vCCoeffsBank+dstY*chrFilterSize;

  out = (vector unsigned char *)dest;

  for(i=0; i<dstW; i+=16){

    Y0 = RND;

    Y1 = RND;

    /* extract 16 coeffs from lumSrc */

    for(j=0; j<lumFilterSize; j++) {

      X0 = vec_ld (0,  &lumSrc[j][i]);

      X1 = vec_ld (16, &lumSrc[j][i]);

      Y0 = vec_mradds (X0, YCoeffs[j], Y0);

      Y1 = vec_mradds (X1, YCoeffs[j], Y1);

    }

    U = RND;

    V = RND;

    /* extract 8 coeffs from U,V */

    for(j=0; j<chrFilterSize; j++) {

      X  = vec_ld (0, &chrSrc[j][i/2]);

      U  = vec_mradds (X, CCoeffs[j], U);

      X  = vec_ld (0, &chrSrc[j][i/2+2048]);

      V  = vec_mradds (X, CCoeffs[j], V);

    }

    /* scale and clip signals */

    Y0 = vec_sra (Y0, SCL);

    Y1 = vec_sra (Y1, SCL);

    U  = vec_sra (U,  SCL);

    V  = vec_sra (V,  SCL);

    Y0 = vec_clip_s16 (Y0);

    Y1 = vec_clip_s16 (Y1);

    U  = vec_clip_s16 (U);

    V  = vec_clip_s16 (V);

    /* now we have

      Y0= y0 y1 y2 y3 y4 y5 y6 y7     Y1= y8 y9 y10 y11 y12 y13 y14 y15

      U= u0 u1 u2 u3 u4 u5 u6 u7      V= v0 v1 v2 v3 v4 v5 v6 v7

      Y0= y0 y1 y2 y3 y4 y5 y6 y7    Y1= y8 y9 y10 y11 y12 y13 y14 y15

      U0= u0 u0 u1 u1 u2 u2 u3 u3    U1= u4 u4 u5 u5 u6 u6 u7 u7

      V0= v0 v0 v1 v1 v2 v2 v3 v3    V1= v4 v4 v5 v5 v6 v6 v7 v7

    */

    U0 = vec_mergeh (U,U);

    V0 = vec_mergeh (V,V);

    U1 = vec_mergel (U,U);

    V1 = vec_mergel (V,V);

    cvtyuvtoRGB (c, Y0,U0,V0,&R0,&G0,&B0);

    cvtyuvtoRGB (c, Y1,U1,V1,&R1,&G1,&B1);

    R  = vec_packclp (R0,R1);

    G  = vec_packclp (G0,G1);

    B  = vec_packclp (B0,B1);

    switch(c->dstFormat) {

      case PIX_FMT_ABGR: out_abgr (R,G,B,out); break;

      case PIX_FMT_BGRA: out_bgra (R,G,B,out); break;

      case PIX_FMT_RGBA: out_rgba (R,G,B,out); break;

      case PIX_FMT_ARGB: out_argb (R,G,B,out); break;

      case PIX_FMT_RGB24: out_rgb24 (R,G,B,out); break;

      case PIX_FMT_BGR24: out_bgr24 (R,G,B,out); break;

      default:

        {

          /* If this is reached, the caller should have called yuv2packedXinC

             instead. */

          static int printed_error_message;

          if(!printed_error_message) {

            av_log(c, AV_LOG_ERROR, "altivec_yuv2packedX doesn't support %s output\n",

                    sws_format_name(c->dstFormat));

            printed_error_message=1;

          }

          return;

        }

    }

  }

  if (i < dstW) {

    i -= 16;

    Y0 = RND;

    Y1 = RND;

    /* extract 16 coeffs from lumSrc */

    for(j=0; j<lumFilterSize; j++) {

      X0 = vec_ld (0,  &lumSrc[j][i]);

      X1 = vec_ld (16, &lumSrc[j][i]);

      Y0 = vec_mradds (X0, YCoeffs[j], Y0);

      Y1 = vec_mradds (X1, YCoeffs[j], Y1);

    }

    U = RND;

    V = RND;

    /* extract 8 coeffs from U,V */

    for(j=0; j<chrFilterSize; j++) {

      X  = vec_ld (0, &chrSrc[j][i/2]);

      U  = vec_mradds (X, CCoeffs[j], U);

      X  = vec_ld (0, &chrSrc[j][i/2+2048]);

      V  = vec_mradds (X, CCoeffs[j], V);

    }

    /* scale and clip signals */

    Y0 = vec_sra (Y0, SCL);

    Y1 = vec_sra (Y1, SCL);

    U  = vec_sra (U,  SCL);

    V  = vec_sra (V,  SCL);

    Y0 = vec_clip_s16 (Y0);

    Y1 = vec_clip_s16 (Y1);

    U  = vec_clip_s16 (U);

    V  = vec_clip_s16 (V);

    /* now we have

       Y0= y0 y1 y2 y3 y4 y5 y6 y7     Y1= y8 y9 y10 y11 y12 y13 y14 y15

       U= u0 u1 u2 u3 u4 u5 u6 u7      V= v0 v1 v2 v3 v4 v5 v6 v7

       Y0= y0 y1 y2 y3 y4 y5 y6 y7    Y1= y8 y9 y10 y11 y12 y13 y14 y15

       U0= u0 u0 u1 u1 u2 u2 u3 u3    U1= u4 u4 u5 u5 u6 u6 u7 u7

       V0= v0 v0 v1 v1 v2 v2 v3 v3    V1= v4 v4 v5 v5 v6 v6 v7 v7

    */

    U0 = vec_mergeh (U,U);

    V0 = vec_mergeh (V,V);

    U1 = vec_mergel (U,U);

    V1 = vec_mergel (V,V);

    cvtyuvtoRGB (c, Y0,U0,V0,&R0,&G0,&B0);

    cvtyuvtoRGB (c, Y1,U1,V1,&R1,&G1,&B1);

    R  = vec_packclp (R0,R1);

    G  = vec_packclp (G0,G1);

    B  = vec_packclp (B0,B1);

    nout = (vector unsigned char *)scratch;

    switch(c->dstFormat) {

      case PIX_FMT_ABGR: out_abgr (R,G,B,nout); break;

      case PIX_FMT_BGRA: out_bgra (R,G,B,nout); break;

      case PIX_FMT_RGBA: out_rgba (R,G,B,nout); break;

      case PIX_FMT_ARGB: out_argb (R,G,B,nout); break;

      case PIX_FMT_RGB24: out_rgb24 (R,G,B,nout); break;

      case PIX_FMT_BGR24: out_bgr24 (R,G,B,nout); break;

      default:

        /* Unreachable, I think. */

        av_log(c, AV_LOG_ERROR, "altivec_yuv2packedX doesn't support %s output\n",

                sws_format_name(c->dstFormat));

        return;

    }

    memcpy (&((uint32_t*)dest)[i], scratch, (dstW-i)/4);

  }

}


static int decode_frame(AVCodecContext *avctx,

                        void *data,

                        int *got_frame,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    DPXContext *const s = avctx->priv_data;

    AVFrame *picture  = data;

    AVFrame *const p = &s->picture;

    uint8_t *ptr[AV_NUM_DATA_POINTERS];

    unsigned int offset;

    int magic_num, endian;

    int x, y, i, ret;

    int w, h, bits_per_color, descriptor, elements, packing, total_size;

    unsigned int rgbBuffer = 0;

    int n_datum = 0;

    if (avpkt->size <= 1634) {

        av_log(avctx, AV_LOG_ERROR, "Packet too small for DPX header\n");

        return AVERROR_INVALIDDATA;

    }

    magic_num = AV_RB32(buf);

    buf += 4;

    /* Check if the files "magic number" is "SDPX" which means it uses

     * big-endian or XPDS which is for little-endian files */

    if (magic_num == AV_RL32("SDPX")) {

        endian = 0;

    } else if (magic_num == AV_RB32("SDPX")) {

        endian = 1;

    } else {

        av_log(avctx, AV_LOG_ERROR, "DPX marker not found\n");

        return AVERROR_INVALIDDATA;

    }

    offset = read32(&buf, endian);

    if (avpkt->size <= offset) {

        av_log(avctx, AV_LOG_ERROR, "Invalid data start offset\n");

        return AVERROR_INVALIDDATA;

    }

    // Need to end in 0x304 offset from start of file

    buf = avpkt->data + 0x304;

    w = read32(&buf, endian);

    h = read32(&buf, endian);

    if ((ret = av_image_check_size(w, h, 0, avctx)) < 0)

        return ret;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    // Need to end in 0x320 to read the descriptor

    buf += 20;

    descriptor = buf[0];

    // Need to end in 0x323 to read the bits per color

    buf += 3;

    avctx->bits_per_raw_sample =

    bits_per_color = buf[0];

    buf++;

    packing = *((uint16_t*)buf);

    buf += 824;

    avctx->sample_aspect_ratio.num = read32(&buf, endian);

    avctx->sample_aspect_ratio.den = read32(&buf, endian);

    if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0)

        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,

                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den,

                  0x10000);

    else

        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };

    switch (descriptor) {

        case 51: // RGBA

            elements = 4;

            break;

        case 50: // RGB

            elements = 3;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported descriptor %d\n", descriptor);

            return AVERROR_INVALIDDATA;

    }

    switch (bits_per_color) {

        case 8:

            if (elements == 4) {

                avctx->pix_fmt = AV_PIX_FMT_RGBA;

            } else {

                avctx->pix_fmt = AV_PIX_FMT_RGB24;

            }

            total_size = avctx->width * avctx->height * elements;

            break;

        case 10:

            if (!packing) {

                av_log(avctx, AV_LOG_ERROR, "Packing to 32bit required\n");

                return -1;

            }

            avctx->pix_fmt = AV_PIX_FMT_GBRP10;

            total_size = (avctx->width * avctx->height * elements + 2) / 3 * 4;

            break;

        case 12:

            if (!packing) {

                av_log(avctx, AV_LOG_ERROR, "Packing to 16bit required\n");

                return -1;

            }

            if (endian) {

                avctx->pix_fmt = AV_PIX_FMT_GBRP12BE;

            } else {

                avctx->pix_fmt = AV_PIX_FMT_GBRP12LE;

            }

            total_size = 2 * avctx->width * avctx->height * elements;

            break;

        case 16:

            if (endian) {

                avctx->pix_fmt = elements == 4 ? AV_PIX_FMT_RGBA64BE : AV_PIX_FMT_RGB48BE;

            } else {

                avctx->pix_fmt = elements == 4 ? AV_PIX_FMT_RGBA64LE : AV_PIX_FMT_RGB48LE;

            }

            total_size = 2 * avctx->width * avctx->height * elements;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported color depth : %d\n", bits_per_color);

            return AVERROR_INVALIDDATA;

    }

    if (s->picture.data[0])

        avctx->release_buffer(avctx, &s->picture);

    if ((ret = ff_get_buffer(avctx, p)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    // Move pointer to offset from start of file

    buf =  avpkt->data + offset;

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

        ptr[i] = p->data[i];

    if (total_size > avpkt->size) {

        av_log(avctx, AV_LOG_ERROR, "Overread buffer. Invalid header?\n");

        return AVERROR_INVALIDDATA;

    }

    switch (bits_per_color) {

    case 10:

        for (x = 0; x < avctx->height; x++) {

            uint16_t *dst[3] = {(uint16_t*)ptr[0],

                                (uint16_t*)ptr[1],

                                (uint16_t*)ptr[2]};

            for (y = 0; y < avctx->width; y++) {

                *dst[2]++ = read10in32(&buf, &rgbBuffer,

                                       &n_datum, endian);

                *dst[0]++ = read10in32(&buf, &rgbBuffer,

                                       &n_datum, endian);

                *dst[1]++ = read10in32(&buf, &rgbBuffer,

                                       &n_datum, endian);

                // For 10 bit, ignore alpha

                if (elements == 4)

                    read10in32(&buf, &rgbBuffer,

                               &n_datum, endian);

            }

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

                ptr[i] += p->linesize[i];

        }

        break;

    case 12:

        for (x = 0; x < avctx->height; x++) {

            uint16_t *dst[3] = {(uint16_t*)ptr[0],

                                (uint16_t*)ptr[1],

                                (uint16_t*)ptr[2]};

            for (y = 0; y < avctx->width; y++) {

                *dst[2] = *((uint16_t*)buf);

                *dst[2] = (*dst[2] >> 4) | (*dst[2] << 12);

                dst[2]++;

                buf += 2;

                *dst[0] = *((uint16_t*)buf);

                *dst[0] = (*dst[0] >> 4) | (*dst[0] << 12);

                dst[0]++;

                buf += 2;

                *dst[1] = *((uint16_t*)buf);

                *dst[1] = (*dst[1] >> 4) | (*dst[1] << 12);

                dst[1]++;

                buf += 2;

                // For 12 bit, ignore alpha

                if (elements == 4)

                    buf += 2;

            }

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

                ptr[i] += p->linesize[i];

        }

        break;

    case 16:

        elements *= 2;

    case 8:

        for (x = 0; x < avctx->height; x++) {

            memcpy(ptr[0], buf, elements*avctx->width);

            ptr[0] += p->linesize[0];

            buf += elements*avctx->width;

        }

        break;

    }

    *picture   = s->picture;

    *got_frame = 1;

    return buf_size;

}


static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
			   const unsigned char *buf, size_t nr)
{
	const unsigned char *b = buf;
	DECLARE_WAITQUEUE(wait, current);
	int c;
	ssize_t retval = 0;

	/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
	if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) {
		retval = tty_check_change(tty);
		if (retval)
			return retval;
	}

	down_read(&tty->termios_rwsem);

	/* Write out any echoed characters that are still pending */
	process_echoes(tty);

	add_wait_queue(&tty->write_wait, &wait);
	while (1) {
		set_current_state(TASK_INTERRUPTIBLE);
		if (signal_pending(current)) {
			retval = -ERESTARTSYS;
			break;
		}
		if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
			retval = -EIO;
			break;
		}
		if (O_OPOST(tty)) {
			while (nr > 0) {
				ssize_t num = process_output_block(tty, b, nr);
				if (num < 0) {
					if (num == -EAGAIN)
						break;
					retval = num;
					goto break_out;
				}
				b += num;
				nr -= num;
				if (nr == 0)
					break;
				c = *b;
				if (process_output(c, tty) < 0)
					break;
				b++; nr--;
			}
			if (tty->ops->flush_chars)
				tty->ops->flush_chars(tty);
		} else {
			while (nr > 0) {
				c = tty->ops->write(tty, b, nr);
				if (c < 0) {
					retval = c;
					goto break_out;
				}
				if (!c)
					break;
				b += c;
				nr -= c;
			}
		}
		if (!nr)
			break;
		if (file->f_flags & O_NONBLOCK) {
			retval = -EAGAIN;
			break;
		}
		up_read(&tty->termios_rwsem);

		schedule();

		down_read(&tty->termios_rwsem);
	}
break_out:
	__set_current_state(TASK_RUNNING);
	remove_wait_queue(&tty->write_wait, &wait);
	if (b - buf != nr && tty->fasync)
		set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
	up_read(&tty->termios_rwsem);
	return (b - buf) ? b - buf : retval;
}


bool test_r_str_trim(void) {
	//  1
	const char* one = r_str_trim_head_ro ("  hello  ");
	mu_assert_streq (one, "hello  ", "one");
	//  2
	char* two = strdup ("  hello  ");
	r_str_trim_head (two);
	mu_assert_streq (two, "hello  ", "two");
	r_str_trim (two);
	//  2
	mu_assert_streq (two, "hello", "three");
	free (two);
	mu_end;
}


void __invalid_creds(const struct cred *cred, const char *file, unsigned line)
{
	printk(KERN_ERR "CRED: Invalid credentials\n");
	printk(KERN_ERR "CRED: At %s:%u\n", file, line);
	dump_invalid_creds(cred, "Specified", current);
	BUG();
}


_tiffReadProc(thandle_t fd, void* buf, tmsize_t size)
{
	size_t size_io = (size_t) size;
	if ((tmsize_t) size_io != size)
	{
		errno=EINVAL;
		return (tmsize_t) -1;
	}
	return ((tmsize_t) read((int) fd, buf, size_io));
}


static void nbd_accept(void *opaque)

{

    int server_fd = (uintptr_t) opaque;

    struct sockaddr_in addr;

    socklen_t addr_len = sizeof(addr);

    int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);

    nbd_started = true;

    if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {

        nb_fds++;

    }

}


static int error_type_get(void *data, u64 *val)
{
	*val = error_type;

	return 0;
}


void RenderFrameImpl::LoadNavigationErrorPageForHttpStatusError(
    const WebURLRequest& failed_request,
    const GURL& unreachable_url,
    int http_status,
    bool replace,
    HistoryEntry* entry) {
  blink::WebFrameLoadType frame_load_type =
      entry ? blink::WebFrameLoadType::kBackForward
            : blink::WebFrameLoadType::kStandard;
  const blink::WebHistoryItem& history_item =
      entry ? entry->root() : blink::WebHistoryItem();

  std::string error_html;
  GetContentClient()->renderer()->PrepareErrorPageForHttpStatusError(
      this, failed_request, unreachable_url, http_status, &error_html, nullptr);
  LoadNavigationErrorPageInternal(error_html, GURL(kUnreachableWebDataURL),
                                  unreachable_url, replace, frame_load_type,
                                  history_item);
}


  static std::shared_ptr<Repetition> opt(const std::shared_ptr<Ope> &ope) {
    return std::make_shared<Repetition>(ope, 0, 1);
  }


static int dissect_h245_H223AL2MParameters ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_H223AL2MParameters , H223AL2MParameters_sequence ) ;
 return offset ;
 }


static int kvm_get_vcpu_events ( X86CPU * cpu ) {
 CPUX86State * env = & cpu -> env ;
 struct kvm_vcpu_events events ;
 int ret ;
 if ( ! kvm_has_vcpu_events ( ) ) {
 return 0 ;
 }
 memset ( & events , 0 , sizeof ( events ) ) ;
 ret = kvm_vcpu_ioctl ( CPU ( cpu ) , KVM_GET_VCPU_EVENTS , & events ) ;
 if ( ret < 0 ) {
 return ret ;
 }
 env -> exception_injected = events . exception . injected ? events . exception . nr : - 1 ;
 env -> has_error_code = events . exception . has_error_code ;
 env -> error_code = events . exception . error_code ;
 env -> interrupt_injected = events . interrupt . injected ? events . interrupt . nr : - 1 ;
 env -> soft_interrupt = events . interrupt . soft ;
 env -> nmi_injected = events . nmi . injected ;
 env -> nmi_pending = events . nmi . pending ;
 if ( events . nmi . masked ) {
 env -> hflags2 |= HF2_NMI_MASK ;
 }
 else {
 env -> hflags2 &= ~ HF2_NMI_MASK ;
 }
 if ( events . flags & KVM_VCPUEVENT_VALID_SMM ) {
 if ( events . smi . smm ) {
 env -> hflags |= HF_SMM_MASK ;
 }
 else {
 env -> hflags &= ~ HF_SMM_MASK ;
 }
 if ( events . smi . pending ) {
 cpu_interrupt ( CPU ( cpu ) , CPU_INTERRUPT_SMI ) ;
 }
 else {
 cpu_reset_interrupt ( CPU ( cpu ) , CPU_INTERRUPT_SMI ) ;
 }
 if ( events . smi . smm_inside_nmi ) {
 env -> hflags2 |= HF2_SMM_INSIDE_NMI_MASK ;
 }
 else {
 env -> hflags2 &= ~ HF2_SMM_INSIDE_NMI_MASK ;
 }
 if ( events . smi . latched_init ) {
 cpu_interrupt ( CPU ( cpu ) , CPU_INTERRUPT_INIT ) ;
 }
 else {
 cpu_reset_interrupt ( CPU ( cpu ) , CPU_INTERRUPT_INIT ) ;
 }
 }
 env -> sipi_vector = events . sipi_vector ;
 return 0 ;
 }


qf_getprop_keys2flags(dict_T *what, int loclist)
{
    int		flags = QF_GETLIST_NONE;

    if (dict_has_key(what, "all"))
    {
	flags |= QF_GETLIST_ALL;
	if (!loclist)
	    // File window ID is applicable only to location list windows
	    flags &= ~ QF_GETLIST_FILEWINID;
    }

    if (dict_has_key(what, "title"))
	flags |= QF_GETLIST_TITLE;

    if (dict_has_key(what, "nr"))
	flags |= QF_GETLIST_NR;

    if (dict_has_key(what, "winid"))
	flags |= QF_GETLIST_WINID;

    if (dict_has_key(what, "context"))
	flags |= QF_GETLIST_CONTEXT;

    if (dict_has_key(what, "id"))
	flags |= QF_GETLIST_ID;

    if (dict_has_key(what, "items"))
	flags |= QF_GETLIST_ITEMS;

    if (dict_has_key(what, "idx"))
	flags |= QF_GETLIST_IDX;

    if (dict_has_key(what, "size"))
	flags |= QF_GETLIST_SIZE;

    if (dict_has_key(what, "changedtick"))
	flags |= QF_GETLIST_TICK;

    if (loclist && dict_has_key(what, "filewinid"))
	flags |= QF_GETLIST_FILEWINID;

    if (dict_has_key(what, "qfbufnr"))
	flags |= QF_GETLIST_QFBUFNR;

    if (dict_has_key(what, "quickfixtextfunc"))
	flags |= QF_GETLIST_QFTF;

    return flags;
}


void WebGLRenderingContextBase::ForceRestoreContext() {
  if (!isContextLost()) {
    SynthesizeGLError(GL_INVALID_OPERATION, "restoreContext",
                      "context not lost");
    return;
  }

  if (!restore_allowed_) {
    if (context_lost_mode_ == kWebGLLoseContextLostContext)
      SynthesizeGLError(GL_INVALID_OPERATION, "restoreContext",
                        "context restoration not allowed");
    return;
  }

  if (!restore_timer_.IsActive())
    restore_timer_.StartOneShot(TimeDelta(), FROM_HERE);
}


static int out_dump(const struct audio_stream *stream, int fd)
{
    UNUSED(fd);
 struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream;
    FNLOG();
 return 0;
}


TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  TFLITE_DCHECK(node->builtin_data != nullptr);

  const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
  const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);

  OpData* data = static_cast<OpData*>(node->user_data);
  auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data);

  TF_LITE_ENSURE_STATUS(
      CalculateOpData(context, params, input1, input2, output, data));

  return kTfLiteOk;
}


GpuChannelHost* RenderThread::GetGpuChannel() {
  if (!gpu_channel_.get())
    return NULL;

  if (gpu_channel_->state() != GpuChannelHost::kConnected)
    return NULL;

  return gpu_channel_.get();
}


    void ListCTCP(const CString& sLine) {
        CString sUserName = sLine.Token(1, true);

        if (sUserName.empty()) {
            sUserName = GetUser()->GetUserName();
        }
        CUser* pUser = FindUser(sUserName);
        if (!pUser) return;

        const MCString& msCTCPReplies = pUser->GetCTCPReplies();
        CTable Table;
        Table.AddColumn(t_s("Request", "listctcp"));
        Table.AddColumn(t_s("Reply", "listctcp"));
        for (const auto& it : msCTCPReplies) {
            Table.AddRow();
            Table.SetCell(t_s("Request", "listctcp"), it.first);
            Table.SetCell(t_s("Reply", "listctcp"), it.second);
        }

        if (Table.empty()) {
            PutModule(t_f("No CTCP replies for user {1} are configured")(
                pUser->GetUserName()));
        } else {
            PutModule(t_f("CTCP replies for user {1}:")(pUser->GetUserName()));
            PutModule(Table);
        }
    }


void MoveTo(double x1,double y1) {
    sprintf(outputbuffer,"\n %12.3f %12.3f m",x1,y1);
    sendClean(outputbuffer);
}


gint proto_registrar_get_length ( const int n ) {
 header_field_info * hfinfo ;
 PROTO_REGISTRAR_GET_NTH ( n , hfinfo ) ;
 return ftype_length ( hfinfo -> type ) ;
 }


void TestingAutomationProvider::BringBrowserToFront(int browser_handle,
                                                    bool* success) {
  *success = false;
  if (browser_tracker_->ContainsHandle(browser_handle)) {
    Browser* browser = browser_tracker_->GetResource(browser_handle);
    browser->window()->Activate();
    *success = true;
  }
}


static int ogg_read_seek ( AVFormatContext * s , int stream_index , int64_t timestamp , int flags ) {
 struct ogg * ogg = s -> priv_data ;
 struct ogg_stream * os = ogg -> streams + stream_index ;
 int ret ;
 av_assert0 ( stream_index < ogg -> nstreams ) ;
 ogg_reset ( s ) ;
 if ( s -> streams [ stream_index ] -> codec -> codec_type == AVMEDIA_TYPE_VIDEO && ! ( flags & AVSEEK_FLAG_ANY ) ) os -> keyframe_seek = 1 ;
 ret = ff_seek_frame_binary ( s , stream_index , timestamp , flags ) ;
 ogg_reset ( s ) ;
 os = ogg -> streams + stream_index ;
 if ( ret < 0 ) os -> keyframe_seek = 0 ;
 return ret ;
 }


static always_inline int _pte_check (mmu_ctx_t *ctx, int is_64b,

                                     target_ulong pte0, target_ulong pte1,

                                     int h, int rw, int type)

{

    target_ulong ptem, mmask;

    int access, ret, pteh, ptev, pp;

    access = 0;

    ret = -1;

    /* Check validity and table match */

#if defined(TARGET_PPC64)

    if (is_64b) {

        ptev = pte64_is_valid(pte0);

        pteh = (pte0 >> 1) & 1;

    } else

#endif

    {

        ptev = pte_is_valid(pte0);

        pteh = (pte0 >> 6) & 1;

    }

    if (ptev && h == pteh) {

        /* Check vsid & api */

#if defined(TARGET_PPC64)

        if (is_64b) {

            ptem = pte0 & PTE64_PTEM_MASK;

            mmask = PTE64_CHECK_MASK;

            pp = (pte1 & 0x00000003) | ((pte1 >> 61) & 0x00000004);

            ctx->nx |= (pte1 >> 2) & 1; /* No execute bit */

            ctx->nx |= (pte1 >> 3) & 1; /* Guarded bit    */

        } else

#endif

        {

            ptem = pte0 & PTE_PTEM_MASK;

            mmask = PTE_CHECK_MASK;

            pp = pte1 & 0x00000003;

        }

        if (ptem == ctx->ptem) {

            if (ctx->raddr != (target_ulong)-1) {

                /* all matches should have equal RPN, WIMG & PP */

                if ((ctx->raddr & mmask) != (pte1 & mmask)) {

                    if (loglevel != 0)

                        fprintf(logfile, "Bad RPN/WIMG/PP\n");

                    return -3;

                }

            }

            /* Compute access rights */

            access = pp_check(ctx->key, pp, ctx->nx);

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = check_prot(ctx->prot, rw, type);

            if (ret == 0) {

                /* Access granted */

#if defined (DEBUG_MMU)

                if (loglevel != 0)

                    fprintf(logfile, "PTE access granted !\n");

#endif

            } else {

                /* Access right violation */

#if defined (DEBUG_MMU)

                if (loglevel != 0)

                    fprintf(logfile, "PTE access rejected\n");

#endif

            }

        }

    }

    return ret;

}


vips_tracked_free( void *s )
{
	/* Keep the size of the alloc in the previous 16 bytes. Ensures
	 * alignment rules are kept.
	 */
	void *start = (void *) ((char *) s - 16);
	size_t size = *((size_t *) start);

	g_mutex_lock( vips_tracked_mutex );

#ifdef DEBUG_VERBOSE
	printf( "vips_tracked_free: %p, %zd bytes\n", s, size );
#endif /*DEBUG_VERBOSE*/

	if( vips_tracked_allocs <= 0 )
		g_warning( "%s", _( "vips_free: too many frees" ) );
	if( vips_tracked_mem < size )
		g_warning( "%s", _( "vips_free: too much free" ) );

	vips_tracked_mem -= size;
	vips_tracked_allocs -= 1;

	g_mutex_unlock( vips_tracked_mutex );

	g_free( start );

	VIPS_GATE_FREE( size );
}


venc_dev::venc_dev(class omx_venc *venc_class)
{
 int i = 0;
    venc_handle = venc_class;
    etb = ebd = ftb = fbd = 0;

 for (i = 0; i < MAX_PORT; i++)
        streaming[i] = false;

    stopped = 1;
    paused = false;
    async_thread_created = false;
    color_format = 0;
    hw_overload = false;
    pthread_mutex_init(&pause_resume_mlock, NULL);
    pthread_cond_init(&pause_resume_cond, NULL);
    memset(&extradata_info, 0, sizeof(extradata_info));
    memset(&idrperiod, 0, sizeof(idrperiod));
    memset(&multislice, 0, sizeof(multislice));
    memset (&slice_mode, 0 , sizeof(slice_mode));
    memset(&m_sVenc_cfg, 0, sizeof(m_sVenc_cfg));
    memset(&rate_ctrl, 0, sizeof(rate_ctrl));
    memset(&bitrate, 0, sizeof(bitrate));
    memset(&intra_period, 0, sizeof(intra_period));
    memset(&codec_profile, 0, sizeof(codec_profile));
    memset(&set_param, 0, sizeof(set_param));
    memset(&time_inc, 0, sizeof(time_inc));
    memset(&m_sInput_buff_property, 0, sizeof(m_sInput_buff_property));
    memset(&m_sOutput_buff_property, 0, sizeof(m_sOutput_buff_property));
    memset(&session_qp, 0, sizeof(session_qp));
    memset(&entropy, 0, sizeof(entropy));
    memset(&dbkfilter, 0, sizeof(dbkfilter));
    memset(&intra_refresh, 0, sizeof(intra_refresh));
    memset(&hec, 0, sizeof(hec));
    memset(&voptimecfg, 0, sizeof(voptimecfg));
    memset(&capability, 0, sizeof(capability));
    memset(&m_debug,0,sizeof(m_debug));
    memset(&hier_layers,0,sizeof(hier_layers));
    is_searchrange_set = false;
    enable_mv_narrow_searchrange = false;
    supported_rc_modes = RC_ALL;
    camera_mode_enabled = false;
    memset(&ltrinfo, 0, sizeof(ltrinfo));
    sess_priority.priority = 1;
    operating_rate = 0;

 char property_value[PROPERTY_VALUE_MAX] = {0};
    property_get("vidc.enc.log.in", property_value, "0");
    m_debug.in_buffer_log = atoi(property_value);

    property_get("vidc.enc.log.out", property_value, "0");
    m_debug.out_buffer_log = atoi(property_value);

    property_get("vidc.enc.log.extradata", property_value, "0");
    m_debug.extradata_log = atoi(property_value);

    snprintf(m_debug.log_loc, PROPERTY_VALUE_MAX,
 "%s", BUFFER_LOG_LOC);
}


DownloadResourceHandler::DownloadResourceHandler(
    net::URLRequest* request,
    const std::string& request_origin,
    download::DownloadSource download_source,
    bool follow_cross_origin_redirects)
    : ResourceHandler(request),
      tab_info_(new DownloadTabInfo()),
      follow_cross_origin_redirects_(follow_cross_origin_redirects),
      first_origin_(url::Origin::Create(request->url())),
      core_(request, this, false, request_origin, download_source) {
  const ResourceRequestInfoImpl* request_info = GetRequestInfo();
  base::PostTaskWithTraits(
      FROM_HERE, {BrowserThread::UI},
      base::BindOnce(
          &InitializeDownloadTabInfoOnUIThread,
          DownloadRequestHandle(AsWeakPtr(),
                                request_info->GetWebContentsGetterForRequest()),
          tab_info_.get()));
}


    void writeBooleanObject(v8::Handle<v8::Value> value)
    {
        v8::Handle<v8::BooleanObject> booleanObject = value.As<v8::BooleanObject>();
        m_writer.writeBooleanObject(booleanObject->ValueOf());
    }


void GLES2DecoderImpl::DeleteTexturesHelper(
    GLsizei n, const GLuint* client_ids) {
  for (GLsizei ii = 0; ii < n; ++ii) {
    TextureManager::TextureInfo* info = GetTextureInfo(client_ids[ii]);
    if (info) {
      GLuint service_id = info->service_id();
      glDeleteTextures(1, &service_id);
      RemoveTextureInfo(client_ids[ii]);
    }
  }
}


	__releases(rcu)
{
	struct igmp_mcf_iter_state *state = igmp_mcf_seq_private(seq);
	if (likely(state->im != NULL)) {
		spin_unlock_bh(&state->im->lock);
		state->im = NULL;
	}
	state->idev = NULL;
	state->dev = NULL;
	rcu_read_unlock();
}


static int __net_init ip6mr_rules_init(struct net *net)
{
	struct fib_rules_ops *ops;
	struct mr6_table *mrt;
	int err;

	ops = fib_rules_register(&ip6mr_rules_ops_template, net);
	if (IS_ERR(ops))
		return PTR_ERR(ops);

	INIT_LIST_HEAD(&net->ipv6.mr6_tables);

	mrt = ip6mr_new_table(net, RT6_TABLE_DFLT);
	if (!mrt) {
		err = -ENOMEM;
		goto err1;
	}

	err = fib_default_rule_add(ops, 0x7fff, RT6_TABLE_DFLT, 0);
	if (err < 0)
		goto err2;

	net->ipv6.mr6_rules_ops = ops;
	return 0;

err2:
	ip6mr_free_table(mrt);
err1:
	fib_rules_unregister(ops);
	return err;
}


void GLES2Implementation::CoverFillPathInstancedCHROMIUM(
    GLsizei num_paths,
    GLenum path_name_type,
    const GLvoid* paths,
    GLuint path_base,
    GLenum cover_mode,
    GLenum transform_type,
    const GLfloat* transform_values) {
  GPU_CLIENT_SINGLE_THREAD_CHECK();
  GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glCoverFillPathInstancedCHROMIUM("
                     << num_paths << ", " << path_name_type << ", " << paths
                     << ", " << path_base << ", " << cover_mode << ", "
                     << transform_type << ", " << transform_values << ")");

  ScopedTransferBufferPtr buffer(helper_, transfer_buffer_);
  uint32_t paths_shm_id = 0;
  uint32_t paths_offset = 0;
  uint32_t transforms_shm_id = 0;
  uint32_t transforms_offset = 0;
  if (!PrepareInstancedPathCommand(
          "glCoverFillPathInstancedCHROMIUM", num_paths, path_name_type, paths,
          transform_type, transform_values, &buffer, &paths_shm_id,
          &paths_offset, &transforms_shm_id, &transforms_offset)) {
    return;
  }

  helper_->CoverFillPathInstancedCHROMIUM(
      num_paths, path_name_type, paths_shm_id, paths_offset, path_base,
      cover_mode, transform_type, transforms_shm_id, transforms_offset);

  CheckGLError();
}


static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    KLVPacket klv;
    MXFContext *mxf = s->priv_data;
    int ret;

    while (1) {
        int64_t max_data_size;
        int64_t pos = avio_tell(s->pb);

        if (pos < mxf->current_klv_data.next_klv - mxf->current_klv_data.length || pos >= mxf->current_klv_data.next_klv) {
            mxf->current_klv_data = (KLVPacket){{0}};
            ret = klv_read_packet(&klv, s->pb);
            if (ret < 0)
                break;
            max_data_size = klv.length;
            pos = klv.next_klv - klv.length;
            PRINT_KEY(s, "read packet", klv.key);
            av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
            if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
                ret = mxf_decrypt_triplet(s, pkt, &klv);
                if (ret < 0) {
                    av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
                    return ret;
                }
                return 0;
            }
        } else {
            klv = mxf->current_klv_data;
            max_data_size = klv.next_klv - pos;
        }
        if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
            IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) ||
            IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
            int body_sid = find_body_sid_by_offset(mxf, klv.offset);
            int index = mxf_get_stream_index(s, &klv, body_sid);
            int64_t next_ofs;
            AVStream *st;
            MXFTrack *track;

            if (index < 0) {
                av_log(s, AV_LOG_ERROR,
                       "error getting stream index %"PRIu32"\n",
                       AV_RB32(klv.key + 12));
                goto skip;
            }

            st = s->streams[index];
            track = st->priv_data;

            if (s->streams[index]->discard == AVDISCARD_ALL)
                goto skip;

            next_ofs = mxf_set_current_edit_unit(mxf, st, pos, 1);

            if (track->wrapping != FrameWrapped) {
                int64_t size;

                if (next_ofs <= 0) {
                    // If we have no way to packetize the data, then return it in chunks...
                    if (klv.next_klv - klv.length == pos && max_data_size > MXF_MAX_CHUNK_SIZE) {
                        st->need_parsing = AVSTREAM_PARSE_FULL;
                        avpriv_request_sample(s, "Huge KLV without proper index in non-frame wrapped essence");
                    }
                    size = FFMIN(max_data_size, MXF_MAX_CHUNK_SIZE);
                } else {
                    if ((size = next_ofs - pos) <= 0) {
                        av_log(s, AV_LOG_ERROR, "bad size: %"PRId64"\n", size);
                        ret = AVERROR_INVALIDDATA;
                        goto skip;
                    }
                    // We must not overread, because the next edit unit might be in another KLV
                    if (size > max_data_size)
                        size = max_data_size;
                }

                mxf->current_klv_data = klv;
                klv.offset = pos;
                klv.length = size;
                klv.next_klv = klv.offset + klv.length;
            }

            /* check for 8 channels AES3 element */
            if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
                ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
                                              pkt, klv.length);
                if (ret < 0) {
                    av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
                    mxf->current_klv_data = (KLVPacket){{0}};
                    return ret;
                }
            } else {
                ret = av_get_packet(s->pb, pkt, klv.length);
                if (ret < 0) {
                    mxf->current_klv_data = (KLVPacket){{0}};
                    return ret;
                }
            }
            pkt->stream_index = index;
            pkt->pos = klv.offset;

            ret = mxf_set_pts(mxf, st, pkt);
            if (ret < 0) {
                mxf->current_klv_data = (KLVPacket){{0}};
                return ret;
            }

            /* seek for truncated packets */
            avio_seek(s->pb, klv.next_klv, SEEK_SET);

            return 0;
        } else {
        skip:
            avio_skip(s->pb, max_data_size);
            mxf->current_klv_data = (KLVPacket){{0}};
        }
    }
    return avio_feof(s->pb) ? AVERROR_EOF : ret;
}


Pattern_Prefix_Status pattern_fixed_prefix ( Const * patt , Pattern_Type ptype , Oid collation , Const * * prefix , Selectivity * rest_selec ) {
 Pattern_Prefix_Status result ;
 switch ( ptype ) {
 case Pattern_Type_Like : result = like_fixed_prefix ( patt , false , collation , prefix , rest_selec ) ;
 break ;
 case Pattern_Type_Like_IC : result = like_fixed_prefix ( patt , true , collation , prefix , rest_selec ) ;
 break ;
 case Pattern_Type_Regex : result = regex_fixed_prefix ( patt , false , collation , prefix , rest_selec ) ;
 break ;
 case Pattern_Type_Regex_IC : result = regex_fixed_prefix ( patt , true , collation , prefix , rest_selec ) ;
 break ;
 default : elog ( ERROR , "unrecognized ptype: %d" , ( int ) ptype ) ;
 result = Pattern_Prefix_None ;
 break ;
 }
 return result ;
 }


static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)

{

        MOVMuxContext *mov = s->priv_data;

        MOVTrack *trk = &mov->tracks[pkt->stream_index];

        AVCodecParameters *par = trk->par;

        int64_t frag_duration = 0;

        int size = pkt->size;

        int ret = check_pkt(s, pkt);

        if (ret < 0)

            return ret;

        if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {

            int i;

            for (i = 0; i < s->nb_streams; i++)

                mov->tracks[i].frag_discont = 1;

            mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;

        }

        if (!pkt->size) {

            if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {

                trk->start_dts = pkt->dts;

                if (pkt->pts != AV_NOPTS_VALUE)

                    trk->start_cts = pkt->pts - pkt->dts;

                else

                    trk->start_cts = 0;

            }

            if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||

                trk->par->codec_id == AV_CODEC_ID_FLAC) {

                int side_size = 0;

                uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);

                if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {

                    void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);

                    if (!newextra)

                        return AVERROR(ENOMEM);

                    av_free(par->extradata);

                    par->extradata = newextra;

                    memcpy(par->extradata, side, side_size);

                    par->extradata_size = side_size;

                    mov->need_rewrite_extradata = 1;

                }

            }

            return 0;             /* Discard 0 sized packets */

        }

        if (trk->entry && pkt->stream_index < s->nb_streams)

            frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,

                                         s->streams[pkt->stream_index]->time_base,

                                         AV_TIME_BASE_Q);

        if ((mov->max_fragment_duration &&

             frag_duration >= mov->max_fragment_duration) ||

             (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||

             (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&

              par->codec_type == AVMEDIA_TYPE_VIDEO &&

              trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {

            if (frag_duration >= mov->min_fragment_duration) {

                // Set the duration of this track to line up with the next

                // sample in this track. This avoids relying on AVPacket

                // duration, but only helps for this particular track, not

                // for the other ones that are flushed at the same time.

                trk->track_duration = pkt->dts - trk->start_dts;

                if (pkt->pts != AV_NOPTS_VALUE)

                    trk->end_pts = pkt->pts;

                else

                    trk->end_pts = pkt->dts;

                trk->end_reliable = 1;

                mov_auto_flush_fragment(s, 0);

            }

        }

        return ff_mov_write_packet(s, pkt);

}


test_bson_append_binary_deprecated (void)
{
   const static uint8_t binary[] = {'1', '2', '3', '4'};
   bson_t *b;
   bson_t *b2;

   b = bson_new ();
   BSON_ASSERT (bson_append_binary (
      b, "binary", -1, BSON_SUBTYPE_BINARY_DEPRECATED, binary, 4));
   b2 = get_bson ("binary_deprecated.bson");
   BSON_ASSERT_BSON_EQUAL (b, b2);
   bson_destroy (b);
   bson_destroy (b2);
}


void DevToolsWindow::IndexingTotalWorkCalculated(
    int request_id,
    const std::string& file_system_path,
    int total_work) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::FundamentalValue request_id_value(request_id);
  StringValue file_system_path_value(file_system_path);
  base::FundamentalValue total_work_value(total_work);
  CallClientFunction("InspectorFrontendAPI.indexingTotalWorkCalculated",
                     &request_id_value, &file_system_path_value,
                     &total_work_value);
}


QPDF::read_xrefTable(qpdf_offset_t xref_offset)
{
    PCRE xref_first_re("^\\s*(\\d+)\\s+(\\d+)\\s*");
    PCRE xref_entry_re("(?s:(^\\d{10}) (\\d{5}) ([fn])\\s*$)");

    std::vector<QPDFObjGen> deleted_items;

    this->file->seek(xref_offset, SEEK_SET);
    bool done = false;
    while (! done)
    {
        char linebuf[51];
        memset(linebuf, 0, sizeof(linebuf));
        this->file->read(linebuf, sizeof(linebuf) - 1);
	std::string line = linebuf;
	PCRE::Match m1 = xref_first_re.match(line.c_str());
	if (! m1)
	{
	    QTC::TC("qpdf", "QPDF invalid xref");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
			  "xref table", this->file->getLastOffset(),
			  "xref syntax invalid");
	}
        file->seek(this->file->getLastOffset() + m1.getMatch(0).length(),
                   SEEK_SET);
	int obj = atoi(m1.getMatch(1).c_str());
	int num = atoi(m1.getMatch(2).c_str());
	for (int i = obj; i < obj + num; ++i)
	{
	    if (i == 0)
	    {
		// This is needed by checkLinearization()
		this->first_xref_item_offset = this->file->tell();
	    }
	    std::string xref_entry = this->file->readLine(30);
	    PCRE::Match m2 = xref_entry_re.match(xref_entry.c_str());
	    if (! m2)
	    {
		QTC::TC("qpdf", "QPDF invalid xref entry");
		throw QPDFExc(
		    qpdf_e_damaged_pdf, this->file->getName(),
		    "xref table", this->file->getLastOffset(),
		    "invalid xref entry (obj=" +
		    QUtil::int_to_string(i) + ")");
	    }

            // For xref_table, these will always be small enough to be ints
	    qpdf_offset_t f1 = QUtil::string_to_ll(m2.getMatch(1).c_str());
	    int f2 = atoi(m2.getMatch(2).c_str());
	    char type = m2.getMatch(3).at(0);
	    if (type == 'f')
	    {
		// Save deleted items until after we've checked the
		// XRefStm, if any.
		deleted_items.push_back(QPDFObjGen(i, f2));
	    }
	    else
	    {
		insertXrefEntry(i, 1, f1, f2);
	    }
	}
	qpdf_offset_t pos = this->file->tell();
	QPDFTokenizer::Token t = readToken(this->file);
	if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer"))
	{
	    done = true;
	}
	else
	{
	    this->file->seek(pos, SEEK_SET);
	}
    }

    // Set offset to previous xref table if any
    QPDFObjectHandle cur_trailer =
	readObject(this->file, "trailer", 0, 0, false);
    if (! cur_trailer.isDictionary())
    {
	QTC::TC("qpdf", "QPDF missing trailer");
	throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
		      "", this->file->getLastOffset(),
		      "expected trailer dictionary");
    }

    if (! this->trailer.isInitialized())
    {
	setTrailer(cur_trailer);

	if (! this->trailer.hasKey("/Size"))
	{
	    QTC::TC("qpdf", "QPDF trailer lacks size");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
			  "trailer", this->file->getLastOffset(),
			  "trailer dictionary lacks /Size key");
	}
	if (! this->trailer.getKey("/Size").isInteger())
	{
	    QTC::TC("qpdf", "QPDF trailer size not integer");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
			  "trailer", this->file->getLastOffset(),
			  "/Size key in trailer dictionary is not "
			  "an integer");
	}
    }

    if (cur_trailer.hasKey("/XRefStm"))
    {
	if (this->ignore_xref_streams)
	{
	    QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer");
	}
	else
	{
	    if (cur_trailer.getKey("/XRefStm").isInteger())
	    {
		// Read the xref stream but disregard any return value
		// -- we'll use our trailer's /Prev key instead of the
		// xref stream's.
		(void) read_xrefStream(
		    cur_trailer.getKey("/XRefStm").getIntValue());
	    }
	    else
	    {
		throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
			      "xref stream", xref_offset,
			      "invalid /XRefStm");
	    }
	}
    }

    // Handle any deleted items now that we've read the /XRefStm.
    for (std::vector<QPDFObjGen>::iterator iter = deleted_items.begin();
	 iter != deleted_items.end(); ++iter)
    {
	QPDFObjGen& og = *iter;
	insertXrefEntry(og.getObj(), 0, 0, og.getGen());
    }

    if (cur_trailer.hasKey("/Prev"))
    {
	if (! cur_trailer.getKey("/Prev").isInteger())
	{
	    QTC::TC("qpdf", "QPDF trailer prev not integer");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
			  "trailer", this->file->getLastOffset(),
			  "/Prev key in trailer dictionary is not "
			  "an integer");
	}
	QTC::TC("qpdf", "QPDF prev key in trailer dictionary");
	xref_offset = cur_trailer.getKey("/Prev").getIntValue();
    }
    else
    {
	xref_offset = 0;
    }

    return xref_offset;
}


static void monitor_event(void *opaque, int event)

{

    Monitor *mon = opaque;

    switch (event) {

    case CHR_EVENT_MUX_IN:

        qemu_mutex_lock(&mon->out_lock);

        mon->mux_out = 0;

        qemu_mutex_unlock(&mon->out_lock);

        if (mon->reset_seen) {

            monitor_resume(mon);

            monitor_flush(mon);

        } else {

            mon->suspend_cnt = 0;

        }

        break;

    case CHR_EVENT_MUX_OUT:

        if (mon->reset_seen) {

            if (mon->suspend_cnt == 0) {

                monitor_printf(mon, "\n");

            }

            monitor_flush(mon);

            monitor_suspend(mon);

        } else {

            mon->suspend_cnt++;

        }

        qemu_mutex_lock(&mon->out_lock);

        mon->mux_out = 1;

        qemu_mutex_unlock(&mon->out_lock);

        break;

    case CHR_EVENT_OPENED:

        monitor_printf(mon, "QEMU %s monitor - type 'help' for more "

                       "information\n", QEMU_VERSION);

        if (!mon->mux_out) {

            readline_show_prompt(mon->rs);

        }

        mon->reset_seen = 1;

        mon_refcount++;

        break;

    case CHR_EVENT_CLOSED:

        mon_refcount--;

        monitor_fdsets_cleanup();

        break;

    }

}


TIFFReadRawStripOrTile2(TIFF* tif, uint32 strip_or_tile, int is_strip,
                        tmsize_t size, const char* module)
{
        TIFFDirectory *td = &tif->tif_dir;

        assert( !isMapped(tif) );
        assert((tif->tif_flags&TIFF_NOREADRAW)==0);

        if (!SeekOK(tif, td->td_stripoffset[strip_or_tile])) {
            if( is_strip )
            {
                TIFFErrorExt(tif->tif_clientdata, module,
                    "Seek error at scanline %lu, strip %lu",
                    (unsigned long) tif->tif_row,
                    (unsigned long) strip_or_tile);
            }
            else
            {
                TIFFErrorExt(tif->tif_clientdata, module,
                    "Seek error at row %lu, col %lu, tile %lu",
                    (unsigned long) tif->tif_row,
                    (unsigned long) tif->tif_col,
                    (unsigned long) strip_or_tile);
            }
            return ((tmsize_t)(-1));
        }

        if( !TIFFReadAndRealloc( tif, size, 0, is_strip,
                                 strip_or_tile, module ) )
        {
            return ((tmsize_t)(-1));
        }

        return (size);
}


read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
{
  uint8_t cipher_length;
  uint8_t hmac_length;

  CLEAR (*key);
  if (!buf_read (buf, &cipher_length, 1))
    goto read_err;
  if (!buf_read (buf, &hmac_length, 1))
    goto read_err;

  if (!buf_read (buf, key->cipher, cipher_length))
    goto read_err;
  if (!buf_read (buf, key->hmac, hmac_length))
    goto read_err;

  if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
    goto key_len_err;

  return 1;

read_err:
  msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
  return -1;

key_len_err:
  msg (D_TLS_ERRORS,
       "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
       kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
  return 0;
}


CatalogueResetFPE (FontPathElementPtr fpe)
{
    /* Always just tell the caller to close and re-open */
    return FPEResetFailed;
}


void CLASS subtract(const char *fname)
{
  FILE *fp;
  int dim[3] = {0, 0, 0}, comment = 0, number = 0, error = 0, nd = 0, c, row, col;
  ushort *pixel;
#ifdef LIBRAW_LIBRARY_BUILD
  RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 0, 2);
#endif

  if (!(fp = fopen(fname, "rb")))
  {
#ifdef DCRAW_VERBOSE
    perror(fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
    imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE;
#endif
    return;
  }
  if (fgetc(fp) != 'P' || fgetc(fp) != '5')
    error = 1;
  while (!error && nd < 3 && (c = fgetc(fp)) != EOF)
  {
    if (c == '#')
      comment = 1;
    if (c == '\n')
      comment = 0;
    if (comment)
      continue;
    if (isdigit(c))
      number = 1;
    if (number)
    {
      if (isdigit(c))
        dim[nd] = dim[nd] * 10 + c - '0';
      else if (isspace(c))
      {
        number = 0;
        nd++;
      }
      else
        error = 1;
    }
  }
  if (error || nd < 3)
  {
#ifdef DCRAW_VERBOSE
    fprintf(stderr, _("%s is not a valid PGM file!\n"), fname);
#endif
    fclose(fp);
    return;
  }
  else if (dim[0] != width || dim[1] != height || dim[2] != 65535)
  {
#ifdef DCRAW_VERBOSE
    fprintf(stderr, _("%s has the wrong dimensions!\n"), fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
    imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM;
#endif
    fclose(fp);
    return;
  }
  pixel = (ushort *)calloc(width, sizeof *pixel);
  merror(pixel, "subtract()");
  for (row = 0; row < height; row++)
  {
    fread(pixel, 2, width, fp);
    for (col = 0; col < width; col++)
      BAYER(row, col) = MAX(BAYER(row, col) - ntohs(pixel[col]), 0);
  }
  free(pixel);
  fclose(fp);
  memset(cblack, 0, sizeof cblack);
  black = 0;
#ifdef LIBRAW_LIBRARY_BUILD
  RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 1, 2);
#endif
}


BGD_DECLARE(void *) gdImageGifAnimEndPtr(int *size)
{
	char *rv = (char *) gdMalloc(1);
	if(!rv) {
		return 0;
	}
	*rv = ';';
	*size = 1;
	return (void *)rv;
}


void usb_desc_create_serial(USBDevice *dev)

{

    DeviceState *hcd = dev->qdev.parent_bus->parent;

    const USBDesc *desc = usb_device_get_usb_desc(dev);

    int index = desc->id.iSerialNumber;

    char serial[64];

    char *path;

    int dst;

    if (dev->serial) {

        /* 'serial' usb bus property has priority if present */

        usb_desc_set_string(dev, index, dev->serial);

        return;

    }

    assert(index != 0 && desc->str[index] != NULL);

    dst = snprintf(serial, sizeof(serial), "%s", desc->str[index]);

    path = qdev_get_dev_path(hcd);

    if (path) {

        dst += snprintf(serial+dst, sizeof(serial)-dst, "-%s", path);

    }

    dst += snprintf(serial+dst, sizeof(serial)-dst, "-%s", dev->port->path);

    usb_desc_set_string(dev, index, serial);

    g_free(path);

}


static void get_random_vector(unsigned char *vector)
{
#ifdef linux
	int fd = open("/dev/urandom",O_RDONLY); /* Linux: get *real* random numbers */
	int total = 0;
	if (fd >= 0) {
		while (total < AUTH_VECTOR_LEN) {
			int bytes = read(fd, vector + total, AUTH_VECTOR_LEN - total);
			if (bytes <= 0)
				break;			/* oops! Error */
			total += bytes;
		}
		close(fd);
	}

	if (total != AUTH_VECTOR_LEN)
#endif
	{				/* do this *always* on other platforms */
		MD5_CTX my_md5;
		struct timeval tv;
		struct timezone tz;
		static unsigned int session = 0; /* make the number harder to guess */

		/* Use the time of day with the best resolution the system can
	 	   give us -- often close to microsecond accuracy. */
		gettimeofday(&tv,&tz);

		if (session == 0) {
			session = getppid();	/* (possibly) hard to guess information */
		}

		tv.tv_sec ^= getpid() * session++;

		/* Hash things to get maybe cryptographically strong pseudo-random numbers */
		MD5Init(&my_md5);
		MD5Update(&my_md5, (unsigned char *) &tv, sizeof(tv));
		MD5Update(&my_md5, (unsigned char *) &tz, sizeof(tz));
		MD5Final(vector, &my_md5);				/* set the final vector */
	}
}


static int index_error_invalid(const char *message)
{
	giterr_set(GITERR_INDEX, "invalid data in index - %s", message);
	return -1;
}


int kvm_vcpu_ioctl_get_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg)
{
	int r = 0;
	union kvmppc_one_reg val;
	int size;

	size = one_reg_size(reg->id);
	if (size > sizeof(val))
		return -EINVAL;

	r = kvmppc_get_one_reg(vcpu, reg->id, &val);
	if (r == -EINVAL) {
		r = 0;
		switch (reg->id) {
#ifdef CONFIG_ALTIVEC
		case KVM_REG_PPC_VR0 ... KVM_REG_PPC_VR31:
			if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
				r = -ENXIO;
				break;
			}
			val.vval = vcpu->arch.vr.vr[reg->id - KVM_REG_PPC_VR0];
			break;
		case KVM_REG_PPC_VSCR:
			if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
				r = -ENXIO;
				break;
			}
			val = get_reg_val(reg->id, vcpu->arch.vr.vscr.u[3]);
			break;
		case KVM_REG_PPC_VRSAVE:
			val = get_reg_val(reg->id, vcpu->arch.vrsave);
			break;
#endif /* CONFIG_ALTIVEC */
		default:
			r = -EINVAL;
			break;
		}
	}

	if (r)
		return r;

	if (copy_to_user((char __user *)(unsigned long)reg->addr, &val, size))
		r = -EFAULT;

	return r;
}


pktap_if_print(netdissect_options *ndo,
               const struct pcap_pkthdr *h, const u_char *p)
{
	uint32_t dlt, hdrlen, rectype;
	u_int caplen = h->caplen;
	u_int length = h->len;
	if_printer printer;
	const pktap_header_t *hdr;

	if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
		ND_PRINT((ndo, "[|pktap]"));
		return (0);
	}
	hdr = (const pktap_header_t *)p;
	dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
	hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
	if (hdrlen < sizeof(pktap_header_t)) {
		/*
		 * Claimed header length < structure length.
		 * XXX - does this just mean some fields aren't
		 * being supplied, or is it truly an error (i.e.,
		 * is the length supplied so that the header can
		 * be expanded in the future)?
		 */
		ND_PRINT((ndo, "[|pktap]"));
		return (0);
	}
	if (caplen < hdrlen || length < hdrlen) {
		ND_PRINT((ndo, "[|pktap]"));
		return (hdrlen);
	}

	if (ndo->ndo_eflag)
		pktap_header_print(ndo, p, length);

	length -= hdrlen;
	caplen -= hdrlen;
	p += hdrlen;

	rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
	switch (rectype) {

	case PKT_REC_NONE:
		ND_PRINT((ndo, "no data"));
		break;

	case PKT_REC_PACKET:
		if ((printer = lookup_printer(dlt)) != NULL) {
			hdrlen += printer(ndo, h, p);
		} else {
			if (!ndo->ndo_eflag)
				pktap_header_print(ndo, (const u_char *)hdr,
						length + hdrlen);

			if (!ndo->ndo_suppress_default_print)
				ND_DEFAULTPRINT(p, caplen);
		}
		break;
	}

	return (hdrlen);
}


translate_ring_addresses(struct virtio_net *dev, int vq_index)
{
	struct vhost_virtqueue *vq = dev->virtqueue[vq_index];
	struct vhost_vring_addr *addr = &vq->ring_addrs;
	uint64_t len, expected_len;

	if (addr->flags & (1 << VHOST_VRING_F_LOG)) {
		vq->log_guest_addr =
			log_addr_to_gpa(dev, vq);
		if (vq->log_guest_addr == 0) {
			VHOST_LOG_CONFIG(DEBUG, "(%s) failed to map log_guest_addr.\n",
				dev->ifname);
			return dev;
		}
	}

	if (vq_is_packed(dev)) {
		len = sizeof(struct vring_packed_desc) * vq->size;
		vq->desc_packed = (struct vring_packed_desc *)(uintptr_t)
			ring_addr_to_vva(dev, vq, addr->desc_user_addr, &len);
		if (vq->desc_packed == NULL ||
				len != sizeof(struct vring_packed_desc) *
				vq->size) {
			VHOST_LOG_CONFIG(DEBUG, "(%s) failed to map desc_packed ring.\n",
				dev->ifname);
			return dev;
		}

		dev = numa_realloc(dev, vq_index);
		vq = dev->virtqueue[vq_index];
		addr = &vq->ring_addrs;

		len = sizeof(struct vring_packed_desc_event);
		vq->driver_event = (struct vring_packed_desc_event *)
					(uintptr_t)ring_addr_to_vva(dev,
					vq, addr->avail_user_addr, &len);
		if (vq->driver_event == NULL ||
				len != sizeof(struct vring_packed_desc_event)) {
			VHOST_LOG_CONFIG(DEBUG, "(%s) failed to find driver area address.\n",
				dev->ifname);
			return dev;
		}

		len = sizeof(struct vring_packed_desc_event);
		vq->device_event = (struct vring_packed_desc_event *)
					(uintptr_t)ring_addr_to_vva(dev,
					vq, addr->used_user_addr, &len);
		if (vq->device_event == NULL ||
				len != sizeof(struct vring_packed_desc_event)) {
			VHOST_LOG_CONFIG(DEBUG, "(%s) failed to find device area address.\n",
				dev->ifname);
			return dev;
		}

		vq->access_ok = true;
		return dev;
	}

	/* The addresses are converted from QEMU virtual to Vhost virtual. */
	if (vq->desc && vq->avail && vq->used)
		return dev;

	len = sizeof(struct vring_desc) * vq->size;
	vq->desc = (struct vring_desc *)(uintptr_t)ring_addr_to_vva(dev,
			vq, addr->desc_user_addr, &len);
	if (vq->desc == 0 || len != sizeof(struct vring_desc) * vq->size) {
		VHOST_LOG_CONFIG(DEBUG, "(%s) failed to map desc ring.\n", dev->ifname);
		return dev;
	}

	dev = numa_realloc(dev, vq_index);
	vq = dev->virtqueue[vq_index];
	addr = &vq->ring_addrs;

	len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
	if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))
		len += sizeof(uint16_t);
	expected_len = len;
	vq->avail = (struct vring_avail *)(uintptr_t)ring_addr_to_vva(dev,
			vq, addr->avail_user_addr, &len);
	if (vq->avail == 0 || len != expected_len) {
		VHOST_LOG_CONFIG(DEBUG, "(%s) failed to map avail ring.\n", dev->ifname);
		return dev;
	}

	len = sizeof(struct vring_used) +
		sizeof(struct vring_used_elem) * vq->size;
	if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))
		len += sizeof(uint16_t);
	expected_len = len;
	vq->used = (struct vring_used *)(uintptr_t)ring_addr_to_vva(dev,
			vq, addr->used_user_addr, &len);
	if (vq->used == 0 || len != expected_len) {
		VHOST_LOG_CONFIG(DEBUG, "(%s) failed to map used ring.\n", dev->ifname);
		return dev;
	}

	if (vq->last_used_idx != vq->used->idx) {
		VHOST_LOG_CONFIG(WARNING, "(%s) last_used_idx (%u) and vq->used->idx (%u) mismatches;\n",
			dev->ifname,
			vq->last_used_idx, vq->used->idx);
		vq->last_used_idx  = vq->used->idx;
		vq->last_avail_idx = vq->used->idx;
		VHOST_LOG_CONFIG(WARNING, "(%s) some packets maybe resent for Tx and dropped for Rx\n",
			dev->ifname);
	}

	vq->access_ok = true;

	VHOST_LOG_CONFIG(DEBUG, "(%s) mapped address desc: %p\n", dev->ifname, vq->desc);
	VHOST_LOG_CONFIG(DEBUG, "(%s) mapped address avail: %p\n", dev->ifname, vq->avail);
	VHOST_LOG_CONFIG(DEBUG, "(%s) mapped address used: %p\n", dev->ifname, vq->used);
	VHOST_LOG_CONFIG(DEBUG, "(%s) log_guest_addr: %" PRIx64 "\n",
			dev->ifname, vq->log_guest_addr);

	return dev;
}


std::set<FilePath> Extension::GetBrowserImages() const {
  std::set<FilePath> image_paths;

  for (ExtensionIconSet::IconMap::const_iterator iter = icons().map().begin();
       iter != icons().map().end(); ++iter) {
    image_paths.insert(FilePath::FromWStringHack(UTF8ToWide(iter->second)));
  }

  DictionaryValue* theme_images = GetThemeImages();
  if (theme_images) {
    for (DictionaryValue::key_iterator it = theme_images->begin_keys();
         it != theme_images->end_keys(); ++it) {
      std::string val;
      if (theme_images->GetStringWithoutPathExpansion(*it, &val))
        image_paths.insert(FilePath::FromWStringHack(UTF8ToWide(val)));
    }
  }

  if (page_action()) {
    std::vector<std::string>* icon_paths = page_action()->icon_paths();
    for (std::vector<std::string>::iterator iter = icon_paths->begin();
         iter != icon_paths->end(); ++iter) {
      image_paths.insert(FilePath::FromWStringHack(UTF8ToWide(*iter)));
    }
  }

  if (browser_action()) {
    std::vector<std::string>* icon_paths = browser_action()->icon_paths();
    for (std::vector<std::string>::iterator iter = icon_paths->begin();
         iter != icon_paths->end(); ++iter) {
      image_paths.insert(FilePath::FromWStringHack(UTF8ToWide(*iter)));
    }
  }

  return image_paths;
}


inline void MinimumScalarBroadcast(int size, const ArithmeticParams& params,
                                   int8 input1_data, const int8* input2_data,
                                   int8* output_data) {
  ruy::profiler::ScopeLabel label("MinimumScalarBroadcastInt8/8bit");
  int i = 0;

#ifdef USE_NEON
  const int8x16_t input1_val_original = vdupq_n_s8(input1_data);
  for (; i <= size - 16; i += 16) {
    const int8x16_t input2_val_original = vld1q_s8(input2_data + i);
    const int8x16_t min_data =
        vminq_s8(input1_val_original, input2_val_original);
    vst1q_s8(output_data + i, min_data);
  }
#endif  // USE_NEON
  for (; i < size; ++i) {
    const int8 input2_val = input2_data[i];
    output_data[i] = std::min(input1_data, input2_val);
  }
}


static int blackout_line_cmpskip(int n, int x, int y, char *dst, char *src,
    int w, int pixelsize) {

	int i, x1, y1, x2, y2, b, hit = 0;
	int beg = -1, end = -1;

	if (tile_blackout[n].cover == 0) {
		return 0;	/* 0 means do not skip it. */
	} else if (tile_blackout[n].cover == 2) {
		return 1;	/* 1 means skip it. */
	}

	/* tile has partial coverage: */

	for (i=0; i < w * pixelsize; i++)  {
		if (*(dst+i) != *(src+i)) {
			beg = i/pixelsize;	/* beginning difference */
			break;
		}
	}
	for (i = w * pixelsize - 1; i >= 0; i--)  {
		if (*(dst+i) != *(src+i)) {
			end = i/pixelsize;	/* ending difference */
			break;
		}
	}
	if (beg < 0 || end < 0) {
		/* problem finding range... */
		return 0;
	}

	/* loop over blackout rectangles: */
	for (b=0; b < tile_blackout[n].count; b++) {

		/* y in full display space: */
		y1 = tile_blackout[n].bo[b].y1;
		y2 = tile_blackout[n].bo[b].y2;

		/* x relative to tile origin: */
		x1 = tile_blackout[n].bo[b].x1 - x;
		x2 = tile_blackout[n].bo[b].x2 - x;

		if (y1 > y || y >= y2) {
			continue;
		}
		if (x1 <= beg && end <= x2) {
			hit = 1;
			break;
		}
	}
	if (hit) {
		return 1;
	} else {
		return 0;
	}
}


base::FilePath ChromeContentBrowserClient::GetShaderDiskCacheDirectory() {
  base::FilePath user_data_dir;
  base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  DCHECK(!user_data_dir.empty());
  return user_data_dir.Append(FILE_PATH_LITERAL("ShaderCache"));
}


int Jsi_Close(Jsi_Interp *interp, Jsi_Channel chan) {
    if (chan->fsPtr==0 || !chan->fsPtr->closeProc) return -1;
    if (chan->flags&JSI_FS_NOCLOSE) return -1;
    int rc = chan->fsPtr->closeProc(chan);
    if (rc == 0)
        Jsi_Free(chan);
    return rc;
}


static CCIDBus *ccid_bus_new(DeviceState *dev)

{

    CCIDBus *bus;

    bus = FROM_QBUS(CCIDBus, qbus_create(&ccid_bus_info, dev, NULL));

    bus->qbus.allow_hotplug = 1;

    return bus;

}


static int read_low_coeffs(AVCodecContext *avctx, int16_t *dst, int size, int width, ptrdiff_t stride)

{

    PixletContext *ctx = avctx->priv_data;

    GetBitContext *b = &ctx->gbit;

    unsigned cnt1, nbits, k, j = 0, i = 0;

    int64_t value, state = 3;

    int rlen, escape, flag = 0;

    while (i < size) {

        nbits = FFMIN(ff_clz((state >> 8) + 3) ^ 0x1F, 14);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 < 8) {

            value = show_bits(b, nbits);

            if (value <= 1) {

                skip_bits(b, nbits - 1);

                escape = ((1 << nbits) - 1) * cnt1;

            } else {

                skip_bits(b, nbits);

                escape = value + ((1 << nbits) - 1) * cnt1 - 1;

            }

        } else {

            escape = get_bits(b, 16);

        }

        value = -((escape + flag) & 1) | 1;

        dst[j++] = value * ((escape + flag + 1) >> 1);

        i++;

        if (j == width) {

            j = 0;

            dst += stride;

        }

        state = 120 * (escape + flag) + state - (120 * state >> 8);

        flag = 0;

        if (state * 4 > 0xFF || i >= size)

            continue;

        nbits = ((state + 8) >> 5) + (state ? ff_clz(state) : 32) - 24;

        escape = av_mod_uintp2(16383, nbits);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 > 7) {

            rlen = get_bits(b, 16);

        } else {

            value = show_bits(b, nbits);

            if (value > 1) {

                skip_bits(b, nbits);

                rlen = value + escape * cnt1 - 1;

            } else {

                skip_bits(b, nbits - 1);

                rlen = escape * cnt1;

            }

        }

        if (rlen > size - i)

            return AVERROR_INVALIDDATA;

        i += rlen;

        for (k = 0; k < rlen; k++) {

            dst[j++] = 0;

            if (j == width) {

                j = 0;

                dst += stride;

            }

        }

        state = 0;

        flag = rlen < 0xFFFF ? 1 : 0;

    }

    align_get_bits(b);

    return get_bits_count(b) >> 3;

}


void GLES2Implementation::GetVertexAttribPointerv(GLuint index,
                                                  GLenum pname,
                                                  void** ptr) {
  GPU_CLIENT_SINGLE_THREAD_CHECK();
  GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glGetVertexAttribPointer(" << index
                     << ", " << GLES2Util::GetStringVertexPointer(pname) << ", "
                     << static_cast<void*>(ptr) << ")");
  GPU_CLIENT_LOG_CODE_BLOCK(int32_t num_results = 1);
  if (!vertex_array_object_manager_->GetAttribPointer(index, pname, ptr)) {
    TRACE_EVENT0("gpu", "GLES2::GetVertexAttribPointerv");
    typedef cmds::GetVertexAttribPointerv::Result Result;
    auto result = GetResultAs<Result>();
    if (!result) {
      return;
    }
    result->SetNumResults(0);
    helper_->GetVertexAttribPointerv(index, pname, GetResultShmId(),
                                     result.offset());
    WaitForCmd();
    result->CopyResult(ptr);
    GPU_CLIENT_LOG_CODE_BLOCK(num_results = result->GetNumResults());
  }
  GPU_CLIENT_LOG_CODE_BLOCK({
    for (int32_t i = 0; i < num_results; ++i) {
      GPU_CLIENT_LOG("  " << i << ": " << ptr[i]);
    }
  });
  CheckGLError();
}


static void ecdsa_restart_det_init( mbedtls_ecdsa_restart_det_ctx *ctx )
{
    mbedtls_hmac_drbg_init( &ctx->rng_ctx );
    ctx->state = ecdsa_det_init;
}


static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
                                      int64_t timestamp, int *seq_no)
{
    int i;
    int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
                  0 : c->first_timestamp;

    if (timestamp < pos) {
        *seq_no = pls->start_seq_no;
        return 0;
    }

    for (i = 0; i < pls->n_segments; i++) {
        int64_t diff = pos + pls->segments[i]->duration - timestamp;
        if (diff > 0) {
            *seq_no = pls->start_seq_no + i;
            return 1;
        }
        pos += pls->segments[i]->duration;
    }

    *seq_no = pls->start_seq_no + pls->n_segments - 1;

    return 0;
}


pdf_load_obj_stm(fz_context *ctx, pdf_document *doc, int num, pdf_lexbuf *buf, int target)
{
	fz_stream *stm = NULL;
	pdf_obj *objstm = NULL;
	int *numbuf = NULL;
	int64_t *ofsbuf = NULL;

	pdf_obj *obj;
	int64_t first;
	int count;
	int i;
	pdf_token tok;
	pdf_xref_entry *ret_entry = NULL;

	fz_var(numbuf);
	fz_var(ofsbuf);
	fz_var(objstm);
	fz_var(stm);

	fz_try(ctx)
	{
		objstm = pdf_load_object(ctx, doc, num);

		count = pdf_to_int(ctx, pdf_dict_get(ctx, objstm, PDF_NAME_N));
		first = pdf_to_int(ctx, pdf_dict_get(ctx, objstm, PDF_NAME_First));

		if (count < 0)
			fz_throw(ctx, FZ_ERROR_GENERIC, "negative number of objects in object stream");
		if (first < 0)
			fz_throw(ctx, FZ_ERROR_GENERIC, "first object in object stream resides outside stream");

		numbuf = fz_calloc(ctx, count, sizeof(*numbuf));
		ofsbuf = fz_calloc(ctx, count, sizeof(*ofsbuf));

		stm = pdf_open_stream_number(ctx, doc, num);
		for (i = 0; i < count; i++)
		{
			tok = pdf_lex(ctx, stm, buf);
			if (tok != PDF_TOK_INT)
				fz_throw(ctx, FZ_ERROR_GENERIC, "corrupt object stream (%d 0 R)", num);
			numbuf[i] = buf->i;

			tok = pdf_lex(ctx, stm, buf);
			if (tok != PDF_TOK_INT)
				fz_throw(ctx, FZ_ERROR_GENERIC, "corrupt object stream (%d 0 R)", num);
			ofsbuf[i] = buf->i;
		}

		fz_seek(ctx, stm, first, SEEK_SET);

		for (i = 0; i < count; i++)
		{
			int xref_len = pdf_xref_len(ctx, doc);
			pdf_xref_entry *entry;
			fz_seek(ctx, stm, first + ofsbuf[i], SEEK_SET);

			obj = pdf_parse_stm_obj(ctx, doc, stm, buf);

			if (numbuf[i] <= 0 || numbuf[i] >= xref_len)
			{
				pdf_drop_obj(ctx, obj);
				fz_throw(ctx, FZ_ERROR_GENERIC, "object id (%d 0 R) out of range (0..%d)", numbuf[i], xref_len - 1);
			}

			entry = pdf_get_xref_entry(ctx, doc, numbuf[i]);

			pdf_set_obj_parent(ctx, obj, numbuf[i]);

			if (entry->type == 'o' && entry->ofs == num)
			{
				/* If we already have an entry for this object,
				 * we'd like to drop it and use the new one -
				 * but this means that anyone currently holding
				 * a pointer to the old one will be left with a
				 * stale pointer. Instead, we drop the new one
				 * and trust that the old one is correct. */
				if (entry->obj)
				{
					if (pdf_objcmp(ctx, entry->obj, obj))
						fz_warn(ctx, "Encountered new definition for object %d - keeping the original one", numbuf[i]);
					pdf_drop_obj(ctx, obj);
				}
				else
				{
					entry->obj = obj;
					fz_drop_buffer(ctx, entry->stm_buf);
					entry->stm_buf = NULL;
				}
				if (numbuf[i] == target)
					ret_entry = entry;
			}
			else
			{
				pdf_drop_obj(ctx, obj);
			}
		}
	}
	fz_always(ctx)
	{
		fz_drop_stream(ctx, stm);
		fz_free(ctx, ofsbuf);
		fz_free(ctx, numbuf);
		pdf_drop_obj(ctx, objstm);
	}
	fz_catch(ctx)
	{
		fz_rethrow(ctx);
	}
	return ret_entry;
}