TfLiteStatus PrepareHashtableImport(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);

  const TfLiteTensor* input_resource_id_tensor =
      GetInput(context, node, kInputResourceIdTensor);
  TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);
  TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);
  TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);

  const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
  const TfLiteTensor* value_tensor = GetInput(context, node, kValueTensor);
  TF_LITE_ENSURE(context, (key_tensor->type == kTfLiteInt64 &&
                           value_tensor->type == kTfLiteString) ||
                              (key_tensor->type == kTfLiteString &&
                               value_tensor->type == kTfLiteInt64));
  // TODO(b/144731295): Tensorflow lookup ops support 1-D vector in storing
  // values.
  TF_LITE_ENSURE(context, HaveSameShapes(key_tensor, value_tensor));
  return kTfLiteOk;
}


static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSbyte(int8 value)
{
	if (value<0)
		return(TIFFReadDirEntryErrRange);
	else
		return(TIFFReadDirEntryErrOk);
}


static void __fanout_link(struct sock *sk, struct packet_sock *po)
{
	struct packet_fanout *f = po->fanout;

	spin_lock(&f->lock);
	f->arr[f->num_members] = sk;
	smp_wmb();
	f->num_members++;
	if (f->num_members == 1)
		dev_add_pack(&f->prot_hook);
	spin_unlock(&f->lock);
}


static int cp2112_hid_get(struct hid_device *hdev, unsigned char report_number,
			  u8 *data, size_t count, unsigned char report_type)
{
	u8 *buf;
	int ret;

	buf = kmalloc(count, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	ret = hid_hw_raw_request(hdev, report_number, buf, count,
				       report_type, HID_REQ_GET_REPORT);
	memcpy(data, buf, count);
	kfree(buf);
	return ret;
}


PHP_FUNCTION(openssl_random_pseudo_bytes)
{
	zend_long buffer_length;
	zend_string *buffer = NULL;
	zval *zstrong_result_returned = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|z/", &buffer_length, &zstrong_result_returned) == FAILURE) {
		return;
	}

	if (zstrong_result_returned) {
		zval_dtor(zstrong_result_returned);
		ZVAL_FALSE(zstrong_result_returned);
	}

	if (buffer_length <= 0
#ifndef PHP_WIN32
		|| ZEND_LONG_INT_OVFL(buffer_length)
#endif
			) {
		RETURN_FALSE;
	}
	buffer = zend_string_alloc(buffer_length, 0);

#ifdef PHP_WIN32
	/* random/urandom equivalent on Windows */
	if (php_win32_get_random_bytes((unsigned char*)buffer->val, (size_t) buffer_length) == FAILURE){
		zend_string_release(buffer);
		if (zstrong_result_returned) {
			ZVAL_FALSE(zstrong_result_returned);
		}
		RETURN_FALSE;
	}
#else

	PHP_OPENSSL_CHECK_LONG_TO_INT(buffer_length, length);
	PHP_OPENSSL_RAND_ADD_TIME();
	/* FIXME loop if requested size > INT_MAX */
	if (RAND_bytes((unsigned char*)ZSTR_VAL(buffer), (int)buffer_length) <= 0) {
		zend_string_release(buffer);
		if (zstrong_result_returned) {
			ZVAL_FALSE(zstrong_result_returned);
		}
		RETURN_FALSE;
	}
#endif

	ZSTR_VAL(buffer)[buffer_length] = 0;
	RETVAL_STR(buffer);

	if (zstrong_result_returned) {
		ZVAL_BOOL(zstrong_result_returned, 1);
	}
}


static void test_hba_enable(void)

{

    AHCIQState *ahci;

    ahci = ahci_boot();

    ahci_pci_enable(ahci);

    ahci_hba_enable(ahci);

    ahci_shutdown(ahci);

}


return_pkinit_kx(krb5_context context, krb5_kdc_req *request,
                 krb5_kdc_rep *reply, krb5_keyblock *encrypting_key,
                 krb5_pa_data **out_padata)
{
    krb5_error_code ret = 0;
    krb5_keyblock *session = reply->ticket->enc_part2->session;
    krb5_keyblock *new_session = NULL;
    krb5_pa_data *pa = NULL;
    krb5_enc_data enc;
    krb5_data *scratch = NULL;

    *out_padata = NULL;
    enc.ciphertext.data = NULL;
    if (!krb5_principal_compare(context, request->client,
                                krb5_anonymous_principal()))
        return 0;
    /*
     * The KDC contribution key needs to be a fresh key of an enctype supported
     * by the client and server. The existing session key meets these
     * requirements so we use it.
     */
    ret = krb5_c_fx_cf2_simple(context, session, "PKINIT",
                               encrypting_key, "KEYEXCHANGE",
                               &new_session);
    if (ret)
        goto cleanup;
    ret = encode_krb5_encryption_key( session, &scratch);
    if (ret)
        goto cleanup;
    ret = krb5_encrypt_helper(context, encrypting_key,
                              KRB5_KEYUSAGE_PA_PKINIT_KX, scratch, &enc);
    if (ret)
        goto cleanup;
    memset(scratch->data, 0, scratch->length);
    krb5_free_data(context, scratch);
    scratch = NULL;
    ret = encode_krb5_enc_data(&enc, &scratch);
    if (ret)
        goto cleanup;
    pa = malloc(sizeof(krb5_pa_data));
    if (pa == NULL) {
        ret = ENOMEM;
        goto cleanup;
    }
    pa->pa_type = KRB5_PADATA_PKINIT_KX;
    pa->length = scratch->length;
    pa->contents = (krb5_octet *) scratch->data;
    *out_padata = pa;
    scratch->data = NULL;
    memset(session->contents, 0, session->length);
    krb5_free_keyblock_contents(context, session);
    *session = *new_session;
    new_session->contents = NULL;
cleanup:
    krb5_free_data_contents(context, &enc.ciphertext);
    krb5_free_keyblock(context, new_session);
    krb5_free_data(context, scratch);
    return ret;
}


UNCURL_EXPORT void uncurl_close(struct uncurl_conn *ucc)
{
	if (!ucc) return;

	tls_close(ucc->tls);
	net_close(ucc->net);
	free(ucc->host);
	http_free_header(ucc->hin);
	free(ucc->hout);
	free(ucc->netbuf);
	free(ucc);
}


TabStripDummyDelegate() : run_unload_(false) {}


int platform_pm_freeze(struct device *dev)
{
	struct device_driver *drv = dev->driver;
	int ret = 0;

	if (!drv)
		return 0;

	if (drv->pm) {
		if (drv->pm->freeze)
			ret = drv->pm->freeze(dev);
	} else {
		ret = platform_legacy_suspend(dev, PMSG_FREEZE);
	}

	return ret;
}


PJ_DEF(pj_status_t) pjmedia_rtcp_build_rtcp_sdes(
					    pjmedia_rtcp_session *session,
					    void *buf,
					    pj_size_t *length,
					    const pjmedia_rtcp_sdes *sdes)
{
    pjmedia_rtcp_common *hdr;
    pj_uint8_t *p;
    pj_size_t len;

    PJ_ASSERT_RETURN(session && buf && length && sdes, PJ_EINVAL);

    /* Verify SDES item length */
    if (sdes->cname.slen > 255 || sdes->name.slen  > 255 ||
	sdes->email.slen > 255 || sdes->phone.slen > 255 ||
	sdes->loc.slen   > 255 || sdes->tool.slen  > 255 ||
	sdes->note.slen  > 255)
    {
	return PJ_EINVAL;
    }

    /* Verify buffer length */
    len = sizeof(*hdr);
    if (sdes->cname.slen) len += sdes->cname.slen + 2;
    if (sdes->name.slen)  len += sdes->name.slen  + 2;
    if (sdes->email.slen) len += sdes->email.slen + 2;
    if (sdes->phone.slen) len += sdes->phone.slen + 2;
    if (sdes->loc.slen)   len += sdes->loc.slen   + 2;
    if (sdes->tool.slen)  len += sdes->tool.slen  + 2;
    if (sdes->note.slen)  len += sdes->note.slen  + 2;
    len++; /* null termination */
    len = ((len+3)/4) * 4;
    if (len > *length)
	return PJ_ETOOSMALL;

    /* Build RTCP SDES header */
    hdr = (pjmedia_rtcp_common*)buf;
    pj_memcpy(hdr, &session->rtcp_sr_pkt.common,  sizeof(*hdr));
    hdr->pt = RTCP_SDES;
    hdr->length = pj_htons((pj_uint16_t)(len/4 - 1));

    /* Build RTCP SDES items */
    p = (pj_uint8_t*)hdr + sizeof(*hdr);
#define BUILD_SDES_ITEM(SDES_NAME, SDES_TYPE) \
    if (sdes->SDES_NAME.slen) { \
	*p++ = SDES_TYPE; \
	*p++ = (pj_uint8_t)sdes->SDES_NAME.slen; \
	pj_memcpy(p, sdes->SDES_NAME.ptr, sdes->SDES_NAME.slen); \
	p += sdes->SDES_NAME.slen; \
    }
    BUILD_SDES_ITEM(cname, RTCP_SDES_CNAME);
    BUILD_SDES_ITEM(name,  RTCP_SDES_NAME);
    BUILD_SDES_ITEM(email, RTCP_SDES_EMAIL);
    BUILD_SDES_ITEM(phone, RTCP_SDES_PHONE);
    BUILD_SDES_ITEM(loc,   RTCP_SDES_LOC);
    BUILD_SDES_ITEM(tool,  RTCP_SDES_TOOL);
    BUILD_SDES_ITEM(note,  RTCP_SDES_NOTE);
#undef BUILD_SDES_ITEM

    /* Null termination */
    *p++ = 0;

    /* Pad to 32bit */
    while ((p-(pj_uint8_t*)buf) % 4)
	*p++ = 0;

    /* Finally */
    pj_assert((int)len == p-(pj_uint8_t*)buf);
    *length = len;

    return PJ_SUCCESS;
}


int nlmsg_size(int payload)
{
	return NLMSG_HDRLEN + payload;
}


void TabStripModelObserver::ActiveTabChanged(TabContents* old_contents,
                                             TabContents* new_contents,
                                             int index,
                                             bool user_gesture) {
}


mml_copy(MinMaxLen* to, MinMaxLen* from)
{
  to->min = from->min;
  to->max = from->max;
}


static uint8_t arcmsr_abort_allcmd(struct AdapterControlBlock *acb)
{
	uint8_t rtnval = 0;
	switch (acb->adapter_type) {
	case ACB_ADAPTER_TYPE_A: {
		rtnval = arcmsr_hbaA_abort_allcmd(acb);
		}
		break;

	case ACB_ADAPTER_TYPE_B: {
		rtnval = arcmsr_hbaB_abort_allcmd(acb);
		}
		break;

	case ACB_ADAPTER_TYPE_C: {
		rtnval = arcmsr_hbaC_abort_allcmd(acb);
		}
		break;

	case ACB_ADAPTER_TYPE_D:
		rtnval = arcmsr_hbaD_abort_allcmd(acb);
		break;
	}
	return rtnval;
}


static void prep_write_cb(struct bt_att_chan *chan, uint8_t opcode,
					const void *pdu, uint16_t length,
					void *user_data)
{
	struct bt_gatt_server *server = user_data;
	uint16_t handle = 0;
	uint16_t offset;
	struct gatt_db_attribute *attr;
	struct prep_write_complete_data *pwcd;
	uint8_t ecode, status;

	if (length < 4) {
		ecode = BT_ATT_ERROR_INVALID_PDU;
		goto error;
	}

	if (queue_length(server->prep_queue) >= server->max_prep_queue_len) {
		ecode = BT_ATT_ERROR_PREPARE_QUEUE_FULL;
		goto error;
	}

	handle = get_le16(pdu);
	offset = get_le16(pdu + 2);

	attr = gatt_db_get_attribute(server->db, handle);
	if (!attr) {
		ecode = BT_ATT_ERROR_INVALID_HANDLE;
		goto error;
	}

	util_debug(server->debug_callback, server->debug_data,
				"Prep Write Req - handle: 0x%04x", handle);

	ecode = check_permissions(server, attr, BT_ATT_PERM_WRITE_MASK);
	if (ecode)
		goto error;

	pwcd = new0(struct prep_write_complete_data, 1);
	pwcd->chan = chan;
	pwcd->pdu = malloc(length);
	memcpy(pwcd->pdu, pdu, length);
	pwcd->length = length;
	pwcd->server = server;

	status = gatt_db_attribute_write(attr, offset, NULL, 0,
						BT_ATT_OP_PREP_WRITE_REQ,
						server->att,
						prep_write_complete_cb, pwcd);

	if (status)
		return;

	ecode = BT_ATT_ERROR_UNLIKELY;

error:
	bt_att_chan_send_error_rsp(chan, opcode, handle, ecode);
}


void V8TestObject::CeReactionsOverloadedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
  RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_ceReactionsOverloadedMethod");

  test_object_v8_internal::CeReactionsOverloadedMethodMethod(info);
}


GF_Err gf_media_export_six(GF_MediaExporter *dumper)
{
	GF_ESD *esd;
	char szName[1000], szMedia[1000];
	FILE *media, *six;
	u32 track, i, di, count, pos, header_size;
	//u32 mtype;
#if !defined(GPAC_DISABLE_TTXT) && !defined(GPAC_DISABLE_VTT)
	u32 mstype;
#endif
	const char *szRootName;
	//Bool isText;

	if (!(track = gf_isom_get_track_by_id(dumper->file, dumper->trackID))) {
		GF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, ("Wrong track ID %d for file %s \n", dumper->trackID, gf_isom_get_filename(dumper->file)));
		return GF_BAD_PARAM;
	}
	if (!track) return gf_export_message(dumper, GF_BAD_PARAM, "Invalid track ID %d", dumper->trackID);

	if (dumper->flags & GF_EXPORT_PROBE_ONLY) {
		dumper->flags |= GF_EXPORT_NHML_FULL;
		return GF_OK;
	}
	esd = gf_isom_get_esd(dumper->file, track, 1);

	sprintf(szMedia, "%s.media", dumper->out_name);
	media = gf_fopen(szMedia, "wb");
	if (!media) {
		if (esd) gf_odf_desc_del((GF_Descriptor *) esd);
		return gf_export_message(dumper, GF_IO_ERR, "Error opening %s for writing - check disk access & permissions", szMedia);
	}

	sprintf(szName, "%s.six", dumper->out_name);
	szRootName = "stream";

	six = gf_fopen(szName, "wt");
	if (!six) {
		gf_fclose(media);
		if (esd) gf_odf_desc_del((GF_Descriptor *) esd);
		return gf_export_message(dumper, GF_IO_ERR, "Error opening %s for writing - check disk access & permissions", szName);
	}
	/*
		mtype = gf_isom_get_media_type(dumper->file, track);
		if (mtype==GF_ISOM_MEDIA_TEXT || mtype == GF_ISOM_MEDIA_SUBM || mtype == GF_ISOM_MEDIA_SUBT) {
			isText = GF_TRUE;
		} else {
			isText = GF_FALSE;
		}
	*/
#if !defined(GPAC_DISABLE_TTXT) && !defined(GPAC_DISABLE_VTT)
	mstype = gf_isom_get_media_subtype(dumper->file, track, 1);
#endif

	/*write header*/
	gf_fprintf(six, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
	gf_fprintf(six, "<%s timescale=\"%d\" ", szRootName, gf_isom_get_media_timescale(dumper->file, track) );
	gf_fprintf(six, "file=\"%s\" ", szMedia);
	gf_fprintf(six, ">\n");
	header_size = 0;
	if (esd) {
		if (esd->decoderConfig->decoderSpecificInfo  && esd->decoderConfig->decoderSpecificInfo->data) {
#if !defined(GPAC_DISABLE_TTXT) && !defined(GPAC_DISABLE_VTT)
			if (mstype == GF_ISOM_SUBTYPE_WVTT || mstype == GF_ISOM_SUBTYPE_STXT) {
				gf_webvtt_dump_header_boxed(media,
				                            esd->decoderConfig->decoderSpecificInfo->data+4,
				                            esd->decoderConfig->decoderSpecificInfo->dataLength,
				                            &header_size);
			} else
#endif
			{
				gf_fwrite(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, media);
				header_size = esd->decoderConfig->decoderSpecificInfo->dataLength;
			}
		}
		gf_odf_desc_del((GF_Descriptor *) esd);
	} else {
		GF_GenericSampleDescription *sdesc = gf_isom_get_generic_sample_description(dumper->file, track, 1);
		if (sdesc) {
			header_size = sdesc->extension_buf_size;
			gf_free(sdesc);
		}
	}
	gf_fprintf(six, "<header range-begin=\"0\" range-end=\"%d\"/>\n", header_size-1);

	pos = header_size;
	count = gf_isom_get_sample_count(dumper->file, track);
	for (i=0; i<count; i++) {
		GF_ISOSample *samp = gf_isom_get_sample(dumper->file, track, i+1, &di);
		if (!samp) break;

		if (media) {
			gf_fwrite(samp->data, samp->dataLength, media);
		}

		gf_fprintf(six, "<unit time=\""LLU"\" ", samp->DTS);
		if (samp->IsRAP==RAP) gf_fprintf(six, "rap=\"1\" ");
		else if (samp->IsRAP==RAP_NO) gf_fprintf(six, "rap=\"0\" ");
		gf_fprintf(six, "range-begin=\"%d\" ", pos);
		gf_fprintf(six, "range-end=\"%d\" ", pos+samp->dataLength-1);
		gf_fprintf(six, "/>\n");

		pos += samp->dataLength;
		gf_isom_sample_del(&samp);
		gf_set_progress("SIX Export", i+1, count);
		if (dumper->flags & GF_EXPORT_DO_ABORT) break;
	}
	gf_fprintf(six, "</%s>\n", szRootName);
	if (media) gf_fclose(media);
	gf_fclose(six);
	return GF_OK;

}


static int dissect_h245_MiscellaneousIndication ( 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_MiscellaneousIndication , MiscellaneousIndication_sequence ) ;
 return offset ;
 }


int	FS_GetModList( char *listbuf, int bufsize ) {
	int		nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen;
	char **pFiles = NULL;
	char **pPaks = NULL;
	char *name, *path;
	char description[MAX_OSPATH];

	int dummy;
	char **pFiles0 = NULL;
	char **pFiles1 = NULL;
#ifndef STANDALONE
	char **pFiles2 = NULL;
	char **pFiles3 = NULL;
#endif
	qboolean bDrop = qfalse;

	*listbuf = 0;
	nMods = nTotal = 0;

	pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue );
	pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue );
#ifndef STANDALONE
	pFiles2 = Sys_ListFiles( fs_steampath->string, NULL, NULL, &dummy, qtrue );
#endif
#ifndef STANDALONE
	pFiles3 = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
	pFiles = Sys_ConcatenateFileLists( pFiles2, pFiles3 );
#else
	pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1 );
#endif

	nPotential = Sys_CountFileList(pFiles);

	for ( i = 0 ; i < nPotential ; i++ ) {
		name = pFiles[i];
		if (i!=0) {
			bDrop = qfalse;
			for(j=0; j<i; j++)
			{
				if (Q_stricmp(pFiles[j],name)==0) {
					bDrop = qtrue;
					break;
				}
			}
		}
		if (bDrop) {
			continue;
		}
		if (Q_stricmp(name, com_basegame->string) && Q_stricmpn(name, ".", 1)) {
			path = FS_BuildOSPath( fs_basepath->string, name, "" );
			nPaks = 0;
			pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
			Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present

			/* try on home path */
			if ( nPaks <= 0 )
			{
				path = FS_BuildOSPath( fs_homepath->string, name, "" );
				nPaks = 0;
				pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
				Sys_FreeFileList( pPaks );
			}

#ifndef STANDALONE
			/* try on steam path */
			if ( nPaks <= 0 )
			{
				path = FS_BuildOSPath( fs_steampath->string, name, "" );
				nPaks = 0;
				pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse );
				Sys_FreeFileList( pPaks );
			}
#endif

			if (nPaks > 0) {
				nLen = strlen(name) + 1;
				FS_GetModDescription( name, description, sizeof( description ) );
				nDescLen = strlen(description) + 1;

				if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
					strcpy(listbuf, name);
					listbuf += nLen;
					strcpy(listbuf, description);
					listbuf += nDescLen;
					nTotal += nLen + nDescLen;
					nMods++;
				}
				else {
					break;
				}
			}
		}
	}
	Sys_FreeFileList( pFiles );

	return nMods;
}


void shm_init_ns(struct ipc_namespace *ns)
{
	ns->shm_ctlmax = SHMMAX;
	ns->shm_ctlall = SHMALL;
	ns->shm_ctlmni = SHMMNI;
	ns->shm_rmid_forced = 0;
	ns->shm_tot = 0;
	ipc_init_ids(&shm_ids(ns));
}


static void final(const short *i1, const short *i2,

                  void *out, int *statbuf, int len)

{

    int x, i;

    unsigned short int work[50];

    short *ptr = work;

    memcpy(work, statbuf,20);

    memcpy(work + 10, i2, len * 2);

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

        int sum = 0;

        for(x=0; x<10; x++)

            sum += i1[9-x] * ptr[x];

        sum >>= 12;

        if (ptr[10] - sum < -32768 || ptr[10] - sum > 32767) {

            memset(out, 0, len * 2);

            memset(statbuf, 0, 20);

            return;

        }

        ptr[10] -= sum;

        ptr++;

    }

    memcpy(out, work+10, len * 2);

    memcpy(statbuf, work + 40, 20);

}


void BpMemoryHeap::assertMapped() const
{
 if (mHeapId == -1) {
        sp<IBinder> binder(const_cast<BpMemoryHeap*>(this)->asBinder());
        sp<BpMemoryHeap> heap(static_cast<BpMemoryHeap*>(find_heap(binder).get()));
        heap->assertReallyMapped();
 if (heap->mBase != MAP_FAILED) {
 Mutex::Autolock _l(mLock);
 if (mHeapId == -1) {
                mBase   = heap->mBase;
                mSize   = heap->mSize;
                mOffset = heap->mOffset;
                android_atomic_write( dup( heap->mHeapId ), &mHeapId );
 }
 } else {
            free_heap(binder);
 }
 }
}


static void xilinx_axidma_realize(DeviceState *dev, Error **errp)

{

    XilinxAXIDMA *s = XILINX_AXI_DMA(dev);

    XilinxAXIDMAStreamSlave *ds = XILINX_AXI_DMA_DATA_STREAM(&s->rx_data_dev);

    XilinxAXIDMAStreamSlave *cs = XILINX_AXI_DMA_CONTROL_STREAM(

                                                            &s->rx_control_dev);

    Error *local_err = NULL;

    object_property_add_link(OBJECT(ds), "dma", TYPE_XILINX_AXI_DMA,

                             (Object **)&ds->dma,

                             object_property_allow_set_link,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &local_err);

    object_property_add_link(OBJECT(cs), "dma", TYPE_XILINX_AXI_DMA,

                             (Object **)&cs->dma,

                             object_property_allow_set_link,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &local_err);

    if (local_err) {

        goto xilinx_axidma_realize_fail;

    }

    object_property_set_link(OBJECT(ds), OBJECT(s), "dma", &local_err);

    object_property_set_link(OBJECT(cs), OBJECT(s), "dma", &local_err);

    if (local_err) {

        goto xilinx_axidma_realize_fail;

    }

    int i;

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

        struct Stream *st = &s->streams[i];

        st->nr = i;

        st->bh = qemu_bh_new(timer_hit, st);

        st->ptimer = ptimer_init(st->bh, PTIMER_POLICY_DEFAULT);

        ptimer_set_freq(st->ptimer, s->freqhz);

    }

    return;

xilinx_axidma_realize_fail:

    if (!*errp) {

        *errp = local_err;

    }

}


void GDataDirectory::RemoveChildDirectories() {
  for (GDataDirectoryCollection::iterator iter = child_directories_.begin();
       iter != child_directories_.end(); ++iter) {
    GDataDirectory* dir = iter->second;
    dir->RemoveChildren();
    if (directory_service_)
      directory_service_->RemoveEntryFromResourceMap(dir);
  }
  STLDeleteValues(&child_directories_);
  child_directories_.clear();
}


vrrp_print_json(void)
{
	FILE *file;
	element e;
	struct json_object *array;

	if (LIST_ISEMPTY(vrrp_data->vrrp))
		return;

	file = fopen_safe("/tmp/keepalived.json", "w");
	if (!file) {
		log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)",
			errno, strerror(errno));
		return;
	}

	array = json_object_new_array();

	for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) {
		struct json_object *instance_json, *json_stats, *json_data,
			*vips, *evips, *track_ifp, *track_script;
#ifdef _HAVE_FIB_ROUTING_
		struct json_object *vroutes, *vrules;
#endif
		element f;

		vrrp_t *vrrp = ELEMENT_DATA(e);
		instance_json = json_object_new_object();
		json_stats = json_object_new_object();
		json_data = json_object_new_object();
		vips = json_object_new_array();
		evips = json_object_new_array();
		track_ifp = json_object_new_array();
		track_script = json_object_new_array();
#ifdef _HAVE_FIB_ROUTING_
		vroutes = json_object_new_array();
		vrules = json_object_new_array();
#endif

		// Dump data to json
		json_object_object_add(json_data, "iname",
			json_object_new_string(vrrp->iname));
		json_object_object_add(json_data, "dont_track_primary",
			json_object_new_int(vrrp->dont_track_primary));
		json_object_object_add(json_data, "skip_check_adv_addr",
			json_object_new_int(vrrp->skip_check_adv_addr));
		json_object_object_add(json_data, "strict_mode",
			json_object_new_int((int)vrrp->strict_mode));
#ifdef _HAVE_VRRP_VMAC_
		json_object_object_add(json_data, "vmac_ifname",
			json_object_new_string(vrrp->vmac_ifname));
#endif
		// Tracked interfaces are stored in a list
		if (!LIST_ISEMPTY(vrrp->track_ifp)) {
			for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) {
				interface_t *ifp = ELEMENT_DATA(f);
				json_object_array_add(track_ifp,
					json_object_new_string(ifp->ifname));
			}
		}
		json_object_object_add(json_data, "track_ifp", track_ifp);

		// Tracked scripts also
		if (!LIST_ISEMPTY(vrrp->track_script)) {
			for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) {
				tracked_sc_t *tsc = ELEMENT_DATA(f);
				vrrp_script_t *vscript = tsc->scr;
				json_object_array_add(track_script,
					json_object_new_string(cmd_str(&vscript->script)));
			}
		}
		json_object_object_add(json_data, "track_script", track_script);

		json_object_object_add(json_data, "ifp_ifname",
			json_object_new_string(vrrp->ifp->ifname));
		json_object_object_add(json_data, "master_priority",
			json_object_new_int(vrrp->master_priority));
		json_object_object_add(json_data, "last_transition",
			json_object_new_double(timeval_to_double(&vrrp->last_transition)));
		json_object_object_add(json_data, "garp_delay",
			json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT));
		json_object_object_add(json_data, "garp_refresh",
			json_object_new_int((int)vrrp->garp_refresh.tv_sec));
		json_object_object_add(json_data, "garp_rep",
			json_object_new_int((int)vrrp->garp_rep));
		json_object_object_add(json_data, "garp_refresh_rep",
			json_object_new_int((int)vrrp->garp_refresh_rep));
		json_object_object_add(json_data, "garp_lower_prio_delay",
			json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ)));
		json_object_object_add(json_data, "garp_lower_prio_rep",
			json_object_new_int((int)vrrp->garp_lower_prio_rep));
		json_object_object_add(json_data, "lower_prio_no_advert",
			json_object_new_int((int)vrrp->lower_prio_no_advert));
		json_object_object_add(json_data, "higher_prio_send_advert",
			json_object_new_int((int)vrrp->higher_prio_send_advert));
		json_object_object_add(json_data, "vrid",
			json_object_new_int(vrrp->vrid));
		json_object_object_add(json_data, "base_priority",
			json_object_new_int(vrrp->base_priority));
		json_object_object_add(json_data, "effective_priority",
			json_object_new_int(vrrp->effective_priority));
		json_object_object_add(json_data, "vipset",
			json_object_new_boolean(vrrp->vipset));

		//Virtual IPs are stored in a list
		if (!LIST_ISEMPTY(vrrp->vip)) {
			for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) {
				ip_address_t *vip = ELEMENT_DATA(f);
				char ipaddr[INET6_ADDRSTRLEN];
				inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr),
					ipaddr, INET6_ADDRSTRLEN);
				json_object_array_add(vips,
					json_object_new_string(ipaddr));
			}
		}
		json_object_object_add(json_data, "vips", vips);

		//External VIPs are also stored in a list
		if (!LIST_ISEMPTY(vrrp->evip)) {
			for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) {
				ip_address_t *evip = ELEMENT_DATA(f);
				char ipaddr[INET6_ADDRSTRLEN];
				inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr),
					ipaddr, INET6_ADDRSTRLEN);
				json_object_array_add(evips,
					json_object_new_string(ipaddr));
			}
		}
		json_object_object_add(json_data, "evips", evips);

		json_object_object_add(json_data, "promote_secondaries",
			json_object_new_boolean(vrrp->promote_secondaries));

#ifdef _HAVE_FIB_ROUTING_
		// Dump vroutes
		if (!LIST_ISEMPTY(vrrp->vroutes)) {
			for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) {
				ip_route_t *route = ELEMENT_DATA(f);
				char *buf = MALLOC(ROUTE_BUF_SIZE);
				format_iproute(route, buf, ROUTE_BUF_SIZE);
				json_object_array_add(vroutes,
					json_object_new_string(buf));
			}
		}
		json_object_object_add(json_data, "vroutes", vroutes);

		// Dump vrules
		if (!LIST_ISEMPTY(vrrp->vrules)) {
			for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) {
				ip_rule_t *rule = ELEMENT_DATA(f);
				char *buf = MALLOC(RULE_BUF_SIZE);
				format_iprule(rule, buf, RULE_BUF_SIZE);
				json_object_array_add(vrules,
					json_object_new_string(buf));
			}
		}
		json_object_object_add(json_data, "vrules", vrules);
#endif

		json_object_object_add(json_data, "adver_int",
			json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT));
		json_object_object_add(json_data, "master_adver_int",
			json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT));
		json_object_object_add(json_data, "accept",
			json_object_new_int((int)vrrp->accept));
		json_object_object_add(json_data, "nopreempt",
			json_object_new_boolean(vrrp->nopreempt));
		json_object_object_add(json_data, "preempt_delay",
			json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ)));
		json_object_object_add(json_data, "state",
			json_object_new_int(vrrp->state));
		json_object_object_add(json_data, "wantstate",
			json_object_new_int(vrrp->wantstate));
		json_object_object_add(json_data, "version",
			json_object_new_int(vrrp->version));
		if (vrrp->script_backup)
			json_object_object_add(json_data, "script_backup",
				json_object_new_string(cmd_str(vrrp->script_backup)));
		if (vrrp->script_master)
			json_object_object_add(json_data, "script_master",
				json_object_new_string(cmd_str(vrrp->script_master)));
		if (vrrp->script_fault)
			json_object_object_add(json_data, "script_fault",
				json_object_new_string(cmd_str(vrrp->script_fault)));
		if (vrrp->script_stop)
			json_object_object_add(json_data, "script_stop",
				json_object_new_string(cmd_str(vrrp->script_stop)));
		if (vrrp->script)
			json_object_object_add(json_data, "script",
				json_object_new_string(cmd_str(vrrp->script)));
		if (vrrp->script_master_rx_lower_pri)
			json_object_object_add(json_data, "script_master_rx_lower_pri",
				json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri)));
		json_object_object_add(json_data, "smtp_alert",
			json_object_new_boolean(vrrp->smtp_alert));
#ifdef _WITH_VRRP_AUTH_
		if (vrrp->auth_type) {
			json_object_object_add(json_data, "auth_type",
				json_object_new_int(vrrp->auth_type));

			if (vrrp->auth_type != VRRP_AUTH_AH) {
				char auth_data[sizeof(vrrp->auth_data) + 1];
				memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data));
				auth_data[sizeof(vrrp->auth_data)] = '\0';
				json_object_object_add(json_data, "auth_data",
					json_object_new_string(auth_data));
			}
		}
		else
			json_object_object_add(json_data, "auth_type",
				json_object_new_int(0));
#endif

		// Dump stats to json
		json_object_object_add(json_stats, "advert_rcvd",
			json_object_new_int64((int64_t)vrrp->stats->advert_rcvd));
		json_object_object_add(json_stats, "advert_sent",
			json_object_new_int64(vrrp->stats->advert_sent));
		json_object_object_add(json_stats, "become_master",
			json_object_new_int64(vrrp->stats->become_master));
		json_object_object_add(json_stats, "release_master",
			json_object_new_int64(vrrp->stats->release_master));
		json_object_object_add(json_stats, "packet_len_err",
			json_object_new_int64((int64_t)vrrp->stats->packet_len_err));
		json_object_object_add(json_stats, "advert_interval_err",
			json_object_new_int64((int64_t)vrrp->stats->advert_interval_err));
		json_object_object_add(json_stats, "ip_ttl_err",
			json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err));
		json_object_object_add(json_stats, "invalid_type_rcvd",
			json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd));
		json_object_object_add(json_stats, "addr_list_err",
			json_object_new_int64((int64_t)vrrp->stats->addr_list_err));
		json_object_object_add(json_stats, "invalid_authtype",
			json_object_new_int64(vrrp->stats->invalid_authtype));
#ifdef _WITH_VRRP_AUTH_
		json_object_object_add(json_stats, "authtype_mismatch",
			json_object_new_int64(vrrp->stats->authtype_mismatch));
		json_object_object_add(json_stats, "auth_failure",
			json_object_new_int64(vrrp->stats->auth_failure));
#endif
		json_object_object_add(json_stats, "pri_zero_rcvd",
			json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd));
		json_object_object_add(json_stats, "pri_zero_sent",
			json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent));

		// Add both json_data and json_stats to main instance_json
		json_object_object_add(instance_json, "data", json_data);
		json_object_object_add(instance_json, "stats", json_stats);

		// Add instance_json to main array
		json_object_array_add(array, instance_json);

	}
	fprintf(file, "%s", json_object_to_json_string(array));
	fclose(file);
}


pfkey_proto2satype(uint16_t proto)
{
	switch (proto) {
	case IPPROTO_AH:
		return SADB_SATYPE_AH;
	case IPPROTO_ESP:
		return SADB_SATYPE_ESP;
	case IPPROTO_COMP:
		return SADB_X_SATYPE_IPCOMP;
	default:
		return 0;
	}
	/* NOTREACHED */
}


WebKit::WebSpeechInputController* RenderViewImpl::speechInputController(
    WebKit::WebSpeechInputListener* listener) {
#if defined(ENABLE_INPUT_SPEECH)
  if (!input_tag_speech_dispatcher_)
    input_tag_speech_dispatcher_ =
        new InputTagSpeechDispatcher(this, listener);
#endif
  return input_tag_speech_dispatcher_;
}


static void gen_mfsrin_64b(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    t0 = tcg_temp_new();

    tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);

    tcg_gen_andi_tl(t0, t0, 0xF);

    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

#endif

}


char VariableUnserializer::readChar() {
  check();
  return *(m_buf++);
}


void RenderViewImpl::DidHandleMouseEvent(const WebKit::WebMouseEvent& event) {
  FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
}


png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
    png_alloc_size_t avail_out)
{
   /* Loop reading IDATs and decompressing the result into output[avail_out] */
   png_ptr->zstream.next_out = output;
   png_ptr->zstream.avail_out = 0; /* safety: set below */

   if (output == NULL)
      avail_out = 0;

   do
   {
      int ret;
      png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];

      if (png_ptr->zstream.avail_in == 0)
      {
         uInt avail_in;
         png_bytep buffer;

         while (png_ptr->idat_size == 0)
         {
            png_crc_finish(png_ptr, 0);

            png_ptr->idat_size = png_read_chunk_header(png_ptr);
            /* This is an error even in the 'check' case because the code just
             * consumed a non-IDAT header.
             */
            if (png_ptr->chunk_name != png_IDAT)
               png_error(png_ptr, "Not enough image data");
         }

         avail_in = png_ptr->IDAT_read_size;

         if (avail_in > png_ptr->idat_size)
            avail_in = (uInt)png_ptr->idat_size;

         /* A PNG with a gradually increasing IDAT size will defeat this attempt
          * to minimize memory usage by causing lots of re-allocs, but
          * realistically doing IDAT_read_size re-allocs is not likely to be a
          * big problem.
          */
         buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/);

         png_crc_read(png_ptr, buffer, avail_in);
         png_ptr->idat_size -= avail_in;

         png_ptr->zstream.next_in = buffer;
         png_ptr->zstream.avail_in = avail_in;
      }

      /* And set up the output side. */
      if (output != NULL) /* standard read */
      {
         uInt out = ZLIB_IO_MAX;

         if (out > avail_out)
            out = (uInt)avail_out;

         avail_out -= out;
         png_ptr->zstream.avail_out = out;
      }

      else /* after last row, checking for end */
      {
         png_ptr->zstream.next_out = tmpbuf;
         png_ptr->zstream.avail_out = (sizeof tmpbuf);
      }

      /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
       * process.  If the LZ stream is truncated the sequential reader will
       * terminally damage the stream, above, by reading the chunk header of the
       * following chunk (it then exits with png_error).
       *
       * TODO: deal more elegantly with truncated IDAT lists.
       */
      ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH);

      /* Take the unconsumed output back. */
      if (output != NULL)
         avail_out += png_ptr->zstream.avail_out;

      else /* avail_out counts the extra bytes */
         avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;

      png_ptr->zstream.avail_out = 0;

      if (ret == Z_STREAM_END)
      {
         /* Do this for safety; we won't read any more into this row. */
         png_ptr->zstream.next_out = NULL;

         png_ptr->mode |= PNG_AFTER_IDAT;
         png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;

         if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
            png_chunk_benign_error(png_ptr, "Extra compressed data");
         break;
      }

      if (ret != Z_OK)
      {
         png_zstream_error(png_ptr, ret);

         if (output != NULL)
            png_chunk_error(png_ptr, png_ptr->zstream.msg);

         else /* checking */
         {
            png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
            return;
         }
      }
   } while (avail_out > 0);

   if (avail_out > 0)
   {
      /* The stream ended before the image; this is the same as too few IDATs so
       * should be handled the same way.
       */
      if (output != NULL)
         png_error(png_ptr, "Not enough image data");

      else /* the deflate stream contained extra data */
         png_chunk_benign_error(png_ptr, "Too much image data");
   }
}


xsltCompilerVarInfoPush(xsltCompilerCtxtPtr cctxt,
				  xmlNodePtr inst,
				  const xmlChar *name,
				  const xmlChar *nsName)
{
    xsltVarInfoPtr ivar;

    if ((cctxt->ivar != NULL) && (cctxt->ivar->next != NULL)) {
	ivar = cctxt->ivar->next;
    } else if ((cctxt->ivar == NULL) && (cctxt->ivars != NULL)) {
	ivar = cctxt->ivars;
    } else {
	ivar = (xsltVarInfoPtr) xmlMalloc(sizeof(xsltVarInfo));
	if (ivar == NULL) {
	    xsltTransformError(NULL, cctxt->style, inst,
		"xsltParseInScopeVarPush: xmlMalloc() failed!\n");
	    cctxt->style->errors++;
	    return(NULL);
	}
	/* memset(retVar, 0, sizeof(xsltInScopeVar)); */
	if (cctxt->ivars == NULL) {
	    cctxt->ivars = ivar;
	    ivar->prev = NULL;
	} else {
	    cctxt->ivar->next = ivar;
	    ivar->prev = cctxt->ivar;
	}
	cctxt->ivar = ivar;
	ivar->next = NULL;
    }
    ivar->depth = cctxt->depth;
    ivar->name = name;
    ivar->nsName = nsName;
    return(ivar);
}


static void btpan_close_conn(btpan_conn_t* conn)
{
    BTIF_TRACE_API("btpan_close_conn: %p",conn);

 if (conn && conn->state == PAN_STATE_OPEN)
 {
        BTIF_TRACE_DEBUG("btpan_close_conn: PAN_STATE_OPEN");

        conn->state = PAN_STATE_CLOSE;
        btpan_cb.open_count--;

 if (btpan_cb.open_count == 0)
 {
            destroy_tap_read_thread();
 if (btpan_cb.tap_fd != INVALID_FD)
 {
                btpan_tap_close(btpan_cb.tap_fd);
                btpan_cb.tap_fd = INVALID_FD;
 }
 }
 }
}


int bt_sock_wait_state(struct sock *sk, int state, unsigned long timeo)
{
	DECLARE_WAITQUEUE(wait, current);
	int err = 0;

	BT_DBG("sk %p", sk);

	add_wait_queue(sk_sleep(sk), &wait);
	set_current_state(TASK_INTERRUPTIBLE);
	while (sk->sk_state != state) {
		if (!timeo) {
			err = -EINPROGRESS;
			break;
		}

		if (signal_pending(current)) {
			err = sock_intr_errno(timeo);
			break;
		}

		release_sock(sk);
		timeo = schedule_timeout(timeo);
		lock_sock(sk);
		set_current_state(TASK_INTERRUPTIBLE);

		err = sock_error(sk);
		if (err)
			break;
	}
	__set_current_state(TASK_RUNNING);
	remove_wait_queue(sk_sleep(sk), &wait);
	return err;
}


static bool parseCoreNode(QSvgNode *node,
                          const QXmlStreamAttributes &attributes)
{
    QStringList features;
    QStringList extensions;
    QStringList languages;
    QStringList formats;
    QStringList fonts;
    QString xmlClassStr;

    for (int i = 0; i < attributes.count(); ++i) {
        const QXmlStreamAttribute &attribute = attributes.at(i);
        QStringView name = attribute.qualifiedName();
        if (name.isEmpty())
            continue;
        QStringView value = attribute.value();
        switch (name.at(0).unicode()) {
        case 'c':
            if (name == QLatin1String("class"))
                xmlClassStr = value.toString();
            break;
        case 'r':
            if (name == QLatin1String("requiredFeatures"))
                features = stringToList(value.toString());
            else if (name == QLatin1String("requiredExtensions"))
                extensions = stringToList(value.toString());
            else if (name == QLatin1String("requiredFormats"))
                formats = stringToList(value.toString());
            else if (name == QLatin1String("requiredFonts"))
                fonts = stringToList(value.toString());
            break;
        case 's':
            if (name == QLatin1String("systemLanguage"))
                languages = stringToList(value.toString());
            break;
        default:
            break;
        }
    }

    node->setRequiredFeatures(features);
    node->setRequiredExtensions(extensions);
    node->setRequiredLanguages(languages);
    node->setRequiredFormats(formats);
    node->setRequiredFonts(fonts);
    node->setNodeId(someId(attributes));
    node->setXmlClass(xmlClassStr);

    return true;
}


int path_pts(struct path *path)
{
	/* Find something mounted on "pts" in the same directory as
	 * the input path.
	 */
	struct dentry *child, *parent;
	struct qstr this;
	int ret;

	ret = path_parent_directory(path);
	if (ret)
		return ret;

	parent = path->dentry;
	this.name = "pts";
	this.len = 3;
	child = d_hash_and_lookup(parent, &this);
	if (!child)
		return -ENOENT;

	path->dentry = child;
	dput(parent);
	follow_mount(path);
	return 0;
}


int jpc_tsfb_analyze2(jpc_tsfb_t *tsfb, int *a, int xstart, int ystart,
  int width, int height, int stride, int numlvls)
{
	if (width > 0 && height > 0) {
		if ((*tsfb->qmfb->analyze)(a, xstart, ystart, width, height, stride))
			return -1;
		if (numlvls > 0) {
			if (jpc_tsfb_analyze2(tsfb, a, JPC_CEILDIVPOW2(xstart,
			  1), JPC_CEILDIVPOW2(ystart, 1), JPC_CEILDIVPOW2(
			  xstart + width, 1) - JPC_CEILDIVPOW2(xstart, 1),
			  JPC_CEILDIVPOW2(ystart + height, 1) -
			  JPC_CEILDIVPOW2(ystart, 1), stride, numlvls - 1)) {
				return -1;
			}
		}
	}
	return 0;
}


static ossl_inline LHASH_OF ( type ) * lh_ ## type ## _new ( unsigned long ( * hfn ) ( const type * ) , int ( * cfn ) ( const type * , const type * ) ) {
 return ( LHASH_OF ( type ) * ) OPENSSL_LH_new ( ( OPENSSL_LH_HASHFUNC ) hfn , ( OPENSSL_LH_COMPFUNC ) cfn ) ;
 }
 static ossl_inline void lh_ ## type ## _free ( LHASH_OF ( type ) * lh ) {
 OPENSSL_LH_free ( ( OPENSSL_LHASH * ) lh ) ;
 }
 static ossl_inline type * lh_ ## type ## _insert ( LHASH_OF ( type ) * lh , type * d ) {
 return ( type * ) OPENSSL_LH_insert ( ( OPENSSL_LHASH * ) lh , d ) ;
 }
 static ossl_inline type * lh_ ## type ## _delete ( LHASH_OF ( type ) * lh , const type * d ) {
 return ( type * ) OPENSSL_LH_delete ( ( OPENSSL_LHASH * ) lh , d ) ;
 }
 static ossl_inline type * lh_ ## type ## _retrieve ( LHASH_OF ( type ) * lh , const type * d ) {
 return ( type * ) OPENSSL_LH_retrieve ( ( OPENSSL_LHASH * ) lh , d ) ;
 }
 static ossl_inline int lh_ ## type ## _error ( LHASH_OF ( type ) * lh ) {
 return OPENSSL_LH_error ( ( OPENSSL_LHASH * ) lh ) ;
 }
 static ossl_inline unsigned long lh_ ## type ## _num_items ( LHASH_OF ( type ) * lh ) {
 return OPENSSL_LH_num_items ( ( OPENSSL_LHASH * ) lh ) ;
 }
 static ossl_inline void lh_ ## type ## _node_stats_bio ( const LHASH_OF ( type ) * lh , BIO * out ) {
 OPENSSL_LH_node_stats_bio ( ( const OPENSSL_LHASH * ) lh , out ) ;
 }
 static ossl_inline void lh_ ## type ## _node_usage_stats_bio ( const LHASH_OF ( type ) * lh , BIO * out ) {
 OPENSSL_LH_node_usage_stats_bio ( ( const OPENSSL_LHASH * ) lh , out ) ;
 }
 static ossl_inline void lh_ ## type ## _stats_bio ( const LHASH_OF ( type ) * lh , BIO * out ) {
 OPENSSL_LH_stats_bio ( ( const OPENSSL_LHASH * ) lh , out ) ;
 }
 static ossl_inline unsigned long lh_ ## type ## _get_down_load ( LHASH_OF ( type ) * lh ) {
 return OPENSSL_LH_get_down_load ( ( OPENSSL_LHASH * ) lh ) ;
 }
 static ossl_inline void lh_ ## type ## _set_down_load ( LHASH_OF ( type ) * lh , unsigned long dl ) {
 OPENSSL_LH_set_down_load ( ( OPENSSL_LHASH * ) lh , dl ) ;
 }
 static ossl_inline void lh_ ## type ## _doall ( LHASH_OF ( type ) * lh , void ( * doall ) ( type * ) ) {
 OPENSSL_LH_doall ( ( OPENSSL_LHASH * ) lh , ( OPENSSL_LH_DOALL_FUNC ) doall ) ;
 }
 LHASH_OF ( type ) # define IMPLEMENT_LHASH_DOALL_ARG_CONST ( type , argtype ) int_implement_lhash_doall ( type , argtype , const type ) # define IMPLEMENT_LHASH_DOALL_ARG ( type , argtype ) int_implement_lhash_doall ( type , argtype , type ) # define int_implement_lhash_doall ( type , argtype , cbargtype ) static ossl_inline void lh_ ## type ## _doall_ ## argtype ( LHASH_OF ( type ) * lh , void ( * fn ) ( cbargtype * , argtype * ) , argtype * arg ) {
 OPENSSL_LH_doall_arg ( ( OPENSSL_LHASH * ) lh , ( OPENSSL_LH_DOALL_FUNCARG ) fn , ( void * ) arg ) ;
 }
 LHASH_OF ( type ) DEFINE_LHASH_OF ( OPENSSL_STRING ) ;
 # ifdef _MSC_VER # pragma warning ( push ) # pragma warning ( disable : 4090 ) # endif DEFINE_LHASH_OF ( OPENSSL_CSTRING )


static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,

                                  int *got_frame, uint8_t *data_start,

                                  unsigned int data_size)

{

    WebPContext *s = avctx->priv_data;

    AVPacket pkt;

    int ret;

    if (!s->initialized) {

        ff_vp8_decode_init(avctx);

        s->initialized = 1;

        if (s->has_alpha)

            avctx->pix_fmt = AV_PIX_FMT_YUVA420P;

    }

    s->lossless = 0;

    if (data_size > INT_MAX) {

        av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");

        return AVERROR_PATCHWELCOME;

    }

    av_init_packet(&pkt);

    pkt.data = data_start;

    pkt.size = data_size;

    ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);

    if (s->has_alpha) {

        ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,

                                     s->alpha_data_size);

    }

}


void SimulateMouseWheelCtrlZoomEvent(WebContents* web_contents,
                                     const gfx::Point& point,
                                     bool zoom_in,
                                     blink::WebMouseWheelEvent::Phase phase) {
  blink::WebMouseWheelEvent wheel_event(blink::WebInputEvent::kMouseWheel,
                                        blink::WebInputEvent::kControlKey,
                                        ui::EventTimeForNow());

  wheel_event.SetPositionInWidget(point.x(), point.y());
  wheel_event.delta_y =
      (zoom_in ? 1.0 : -1.0) * ui::MouseWheelEvent::kWheelDelta;
  wheel_event.wheel_ticks_y = (zoom_in ? 1.0 : -1.0);
  wheel_event.has_precise_scrolling_deltas = false;
  wheel_event.phase = phase;
  RenderWidgetHostImpl* widget_host = RenderWidgetHostImpl::From(
      web_contents->GetRenderViewHost()->GetWidget());
  widget_host->ForwardWheelEvent(wheel_event);
}


static int mpl2_probe(AVProbeData *p)

{

    int i;

    char c;

    int64_t start, end;

    const unsigned char *ptr = p->buf;

    const unsigned char *ptr_end = ptr + p->buf_size;

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

        if (sscanf(ptr, "[%"SCNd64"][%"SCNd64"]%c", &start, &end, &c) != 3 &&

            sscanf(ptr, "[%"SCNd64"][]%c",          &start,       &c) != 2)

            return 0;

        ptr += strcspn(ptr, "\n") + 1;

        if (ptr >= ptr_end)

            return 0;

    }

    return AVPROBE_SCORE_MAX;

}


static void bitplanar2chunky(CDXLVideoContext *c, int linesize, uint8_t *out)
{
    GetBitContext gb;
    int x, y, plane;

    if (init_get_bits8(&gb, c->video, c->video_size) < 0)
        return;
    for (plane = 0; plane < c->bpp; plane++) {
        for (y = 0; y < c->avctx->height; y++) {
            for (x = 0; x < c->avctx->width; x++)
                out[linesize * y + x] |= get_bits1(&gb) << plane;
            skip_bits(&gb, c->padded_bits);
        }
    }
}


static int cit_write_reg(struct gspca_dev *gspca_dev, u16 value, u16 index)
{
	struct usb_device *udev = gspca_dev->dev;
	int err;

	err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00,
			USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
			value, index, NULL, 0, 1000);
	if (err < 0)
		pr_err("Failed to write a register (index 0x%04X, value 0x%02X, error %d)\n",
		       index, value, err);

	return 0;
}


static int bin_main(RCore *r, int mode, int va) {
	RBinAddr *binmain = r_bin_get_sym (r->bin, R_BIN_SYM_MAIN);
	ut64 addr;
	if (!binmain) {
		return false;
	}
	addr = va ? r_bin_a2b (r->bin, binmain->vaddr) : binmain->paddr;

	if (IS_MODE_SET (mode)) {
		r_flag_space_set (r->flags, "symbols");
		r_flag_set (r->flags, "main", addr, r->blocksize);
	} else if (IS_MODE_SIMPLE (mode)) {
		r_cons_printf ("%"PFMT64d, addr);
	} else if (IS_MODE_RAD (mode)) {
		r_cons_printf ("fs symbols\n");
		r_cons_printf ("f main @ 0x%08"PFMT64x"\n", addr);
	} else if (IS_MODE_JSON (mode)) {
		r_cons_printf ("{\"vaddr\":%" PFMT64d
			",\"paddr\":%" PFMT64d "}", addr, binmain->paddr);
	} else {
		r_cons_printf ("[Main]\n");
		r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x"\n",
			addr, binmain->paddr);
	}
	return true;
}


R_API bool r_buf_resize(RBuffer *b, ut64 newsize) {
	r_return_val_if_fail (b, false);
	return buf_resize (b, newsize);
}


parse_instruction(
   struct translate_ctx *ctx,
   boolean has_label )
{
   uint i;
   uint saturate = 0;
   const struct tgsi_opcode_info *info;
   struct tgsi_full_instruction inst;
   const char *cur;
   uint advance;

   inst = tgsi_default_full_instruction();

   /* Parse predicate.
    */
   eat_opt_white( &ctx->cur );
   if (*ctx->cur == '(') {
      uint file;
      int index;
      uint swizzle[4];
      boolean parsed_swizzle;

      inst.Instruction.Predicate = 1;

      ctx->cur++;
      if (*ctx->cur == '!') {
         ctx->cur++;
         inst.Predicate.Negate = 1;
      }

      if (!parse_register_1d( ctx, &file, &index ))
         return FALSE;

      if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
         if (parsed_swizzle) {
            inst.Predicate.SwizzleX = swizzle[0];
            inst.Predicate.SwizzleY = swizzle[1];
            inst.Predicate.SwizzleZ = swizzle[2];
            inst.Predicate.SwizzleW = swizzle[3];
         }
      }

      if (*ctx->cur != ')') {
         report_error( ctx, "Expected `)'" );
         return FALSE;
      }

      ctx->cur++;
   }

   /* Parse instruction name.
    */
   eat_opt_white( &ctx->cur );
   for (i = 0; i < TGSI_OPCODE_LAST; i++) {
      cur = ctx->cur;

      info = tgsi_get_opcode_info( i );
      if (match_inst(&cur, &saturate, info)) {
         if (info->num_dst + info->num_src + info->is_tex == 0) {
            ctx->cur = cur;
            break;
         }
         else if (*cur == '\0' || eat_white( &cur )) {
            ctx->cur = cur;
            break;
         }
      }
   }
   if (i == TGSI_OPCODE_LAST) {
      if (has_label)
         report_error( ctx, "Unknown opcode" );
      else
         report_error( ctx, "Expected `DCL', `IMM' or a label" );
      return FALSE;
   }

   inst.Instruction.Opcode = i;
   inst.Instruction.Saturate = saturate;
   inst.Instruction.NumDstRegs = info->num_dst;
   inst.Instruction.NumSrcRegs = info->num_src;

   if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) {
      /*
       * These are not considered tex opcodes here (no additional
       * target argument) however we're required to set the Texture
       * bit so we can set the number of tex offsets.
       */
      inst.Instruction.Texture = 1;
      inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN;
   }

   /* Parse instruction operands.
    */
   for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) {
      if (i > 0) {
         eat_opt_white( &ctx->cur );
         if (*ctx->cur != ',') {
            report_error( ctx, "Expected `,'" );
            return FALSE;
         }
         ctx->cur++;
         eat_opt_white( &ctx->cur );
      }

      if (i < info->num_dst) {
         if (!parse_dst_operand( ctx, &inst.Dst[i] ))
            return FALSE;
      }
      else if (i < info->num_dst + info->num_src) {
         if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] ))
            return FALSE;
      }
      else {
         uint j;

         for (j = 0; j < TGSI_TEXTURE_COUNT; j++) {
            if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) {
               inst.Instruction.Texture = 1;
               inst.Texture.Texture = j;
               break;
            }
         }
         if (j == TGSI_TEXTURE_COUNT) {
            report_error( ctx, "Expected texture target" );
            return FALSE;
         }
      }
   }

    cur = ctx->cur;
    eat_opt_white( &cur );
   for (i = 0; inst.Instruction.Texture && *cur == ','; i++) {
          cur++;
          eat_opt_white( &cur );
          ctx->cur = cur;
         if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] ))
            return FALSE;
         cur = ctx->cur;
         eat_opt_white( &cur );
   }
   inst.Texture.NumOffsets = i;

   cur = ctx->cur;
   eat_opt_white( &cur );
   if (info->is_branch && *cur == ':') {
      uint target;

      cur++;
      eat_opt_white( &cur );
      if (!parse_uint( &cur, &target )) {
         report_error( ctx, "Expected a label" );
         return FALSE;
      }
      inst.Instruction.Label = 1;
      inst.Label.Label = target;
      ctx->cur = cur;
   }

   advance = tgsi_build_full_instruction(
      &inst,
      ctx->tokens_cur,
      ctx->header,
      (uint) (ctx->tokens_end - ctx->tokens_cur) );
   if (advance == 0)
      return FALSE;
   ctx->tokens_cur += advance;

   return TRUE;
}


pdf_new_processor(fz_context *ctx, int size)
{
	return Memento_label(fz_calloc(ctx, 1, size), "pdf_processor");
}


void RenderProcessHostImpl::CreateMessageFilters() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  AddFilter(new ResourceSchedulerFilter(GetID()));
  MediaInternals* media_internals = MediaInternals::GetInstance();
  scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
      new BrowserPluginMessageFilter(GetID()));
  AddFilter(bp_message_filter.get());

  scoped_refptr<net::URLRequestContextGetter> request_context(
      storage_partition_impl_->GetURLRequestContext());
  scoped_refptr<RenderMessageFilter> render_message_filter(
      new RenderMessageFilter(
          GetID(), GetBrowserContext(), request_context.get(),
          widget_helper_.get(), media_internals,
          storage_partition_impl_->GetDOMStorageContext(),
          storage_partition_impl_->GetCacheStorageContext()));
  AddFilter(render_message_filter.get());

  render_frame_message_filter_ = new RenderFrameMessageFilter(
      GetID(),
#if BUILDFLAG(ENABLE_PLUGINS)
      PluginServiceImpl::GetInstance(),
#else
      nullptr,
#endif
      GetBrowserContext(),
      request_context.get(),
      widget_helper_.get());
  AddFilter(render_frame_message_filter_.get());

  BrowserContext* browser_context = GetBrowserContext();
  ResourceContext* resource_context = browser_context->GetResourceContext();

  scoped_refptr<net::URLRequestContextGetter> media_request_context(
      GetStoragePartition()->GetMediaURLRequestContext());

  ResourceMessageFilter::GetContextsCallback get_contexts_callback(
      base::Bind(&GetContexts, browser_context->GetResourceContext(),
                 request_context, media_request_context));

  scoped_refptr<ChromeBlobStorageContext> blob_storage_context =
      ChromeBlobStorageContext::GetFor(browser_context);

  resource_message_filter_ = new ResourceMessageFilter(
      GetID(), storage_partition_impl_->GetAppCacheService(),
      blob_storage_context.get(),
      storage_partition_impl_->GetFileSystemContext(),
      storage_partition_impl_->GetServiceWorkerContext(),
      get_contexts_callback);

  AddFilter(resource_message_filter_.get());

  media::AudioManager* audio_manager =
      BrowserMainLoop::GetInstance()->audio_manager();
  MediaStreamManager* media_stream_manager =
      BrowserMainLoop::GetInstance()->media_stream_manager();
  audio_input_renderer_host_ = new AudioInputRendererHost(
      GetID(), base::GetProcId(GetHandle()), audio_manager,
      media_stream_manager, AudioMirroringManager::GetInstance(),
       BrowserMainLoop::GetInstance()->user_input_monitor());
   AddFilter(audio_input_renderer_host_.get());
   audio_renderer_host_ = new AudioRendererHost(
      GetID(), audio_manager, AudioMirroringManager::GetInstance(),
      media_stream_manager,
       browser_context->GetResourceContext()->GetMediaDeviceIDSalt());
   AddFilter(audio_renderer_host_.get());
   AddFilter(
      new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service()));
  AddFilter(new AppCacheDispatcherHost(
      storage_partition_impl_->GetAppCacheService(), GetID()));
  AddFilter(new ClipboardMessageFilter(blob_storage_context));
  AddFilter(new DOMStorageMessageFilter(
      storage_partition_impl_->GetDOMStorageContext()));

#if BUILDFLAG(ENABLE_WEBRTC)
  peer_connection_tracker_host_ = new PeerConnectionTrackerHost(
      GetID(), webrtc_eventlog_host_.GetWeakPtr());
  AddFilter(peer_connection_tracker_host_.get());
  AddFilter(new MediaStreamDispatcherHost(
      GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
      media_stream_manager));
  AddFilter(new MediaStreamTrackMetricsHost());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
  AddFilter(new PepperRendererConnection(GetID()));
#endif
  AddFilter(new SpeechRecognitionDispatcherHost(
      GetID(), storage_partition_impl_->GetURLRequestContext()));
  AddFilter(new FileAPIMessageFilter(
      GetID(), storage_partition_impl_->GetURLRequestContext(),
      storage_partition_impl_->GetFileSystemContext(),
      blob_storage_context.get(), StreamContext::GetFor(browser_context)));
  AddFilter(new BlobDispatcherHost(
      GetID(), blob_storage_context,
      make_scoped_refptr(storage_partition_impl_->GetFileSystemContext())));
  AddFilter(new FileUtilitiesMessageFilter(GetID()));
  AddFilter(
      new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker()));
#if defined(OS_MACOSX)
  AddFilter(new TextInputClientMessageFilter());
#elif defined(OS_WIN)
  AddFilter(new DWriteFontProxyMessageFilter());

  channel_->AddFilter(new FontCacheDispatcher());
#endif

  message_port_message_filter_ = new MessagePortMessageFilter(
      base::Bind(&RenderWidgetHelper::GetNextRoutingID,
                 base::Unretained(widget_helper_.get())));
  AddFilter(message_port_message_filter_.get());

  scoped_refptr<CacheStorageDispatcherHost> cache_storage_filter =
      new CacheStorageDispatcherHost();
  cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext());
  AddFilter(cache_storage_filter.get());

  scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
      new ServiceWorkerDispatcherHost(
          GetID(), message_port_message_filter_.get(), resource_context);
  service_worker_filter->Init(
      storage_partition_impl_->GetServiceWorkerContext());
  AddFilter(service_worker_filter.get());

  AddFilter(new SharedWorkerMessageFilter(
      GetID(), resource_context,
      WorkerStoragePartition(
          storage_partition_impl_->GetURLRequestContext(),
          storage_partition_impl_->GetMediaURLRequestContext(),
          storage_partition_impl_->GetAppCacheService(),
          storage_partition_impl_->GetQuotaManager(),
          storage_partition_impl_->GetFileSystemContext(),
          storage_partition_impl_->GetDatabaseTracker(),
          storage_partition_impl_->GetIndexedDBContext(),
          storage_partition_impl_->GetServiceWorkerContext()),
      message_port_message_filter_.get()));

#if BUILDFLAG(ENABLE_WEBRTC)
  p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
      resource_context, request_context.get());
  AddFilter(p2p_socket_dispatcher_host_.get());
#endif

  AddFilter(new TraceMessageFilter(GetID()));
  AddFilter(new ResolveProxyMsgHelper(request_context.get()));
  AddFilter(new QuotaDispatcherHost(
      GetID(), storage_partition_impl_->GetQuotaManager(),
      GetContentClient()->browser()->CreateQuotaPermissionContext()));

  scoped_refptr<ServiceWorkerContextWrapper> service_worker_context(
      static_cast<ServiceWorkerContextWrapper*>(
          storage_partition_impl_->GetServiceWorkerContext()));
  notification_message_filter_ = new NotificationMessageFilter(
      GetID(), storage_partition_impl_->GetPlatformNotificationContext(),
      resource_context, service_worker_context, browser_context);
  AddFilter(notification_message_filter_.get());

  AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
  AddFilter(new HistogramMessageFilter());
  AddFilter(new MemoryMessageFilter(this));
  AddFilter(new PushMessagingMessageFilter(
      GetID(), storage_partition_impl_->GetServiceWorkerContext()));
#if defined(OS_ANDROID)
  AddFilter(new ScreenOrientationListenerAndroid());
  synchronous_compositor_filter_ =
      new SynchronousCompositorBrowserFilter(GetID());
  AddFilter(synchronous_compositor_filter_.get());
#endif
}


static void ati_remote2_input_key(struct ati_remote2 *ar2)
{
	struct input_dev *idev = ar2->idev;
	u8 *data = ar2->buf[1];
	int channel, mode, hw_code, index;

	channel = data[0] >> 4;

	if (!((1 << channel) & ar2->channel_mask))
		return;

	mode = data[0] & 0x0F;

	if (mode > ATI_REMOTE2_PC) {
		dev_err(&ar2->intf[1]->dev,
			"Unknown mode byte (%02x %02x %02x %02x)\n",
			data[3], data[2], data[1], data[0]);
		return;
	}

	hw_code = data[2];
	if (hw_code == 0x3f) {
		/*
		 * For some incomprehensible reason the mouse pad generates
		 * events which look identical to the events from the last
		 * pressed mode key. Naturally we don't want to generate key
		 * events for the mouse pad so we filter out any subsequent
		 * events from the same mode key.
		 */
		if (ar2->mode == mode)
			return;

		if (data[1] == 0)
			ar2->mode = mode;
	}

	if (!((1 << mode) & ar2->mode_mask))
		return;

	index = ati_remote2_lookup(hw_code);
	if (index < 0) {
		dev_err(&ar2->intf[1]->dev,
			"Unknown code byte (%02x %02x %02x %02x)\n",
			data[3], data[2], data[1], data[0]);
		return;
	}

	switch (data[1]) {
	case 0:	/* release */
		break;
	case 1:	/* press */
		ar2->jiffies = jiffies + msecs_to_jiffies(idev->rep[REP_DELAY]);
		break;
	case 2:	/* repeat */

		/* No repeat for mouse buttons. */
		if (ar2->keycode[mode][index] == BTN_LEFT ||
		    ar2->keycode[mode][index] == BTN_RIGHT)
			return;

		if (!time_after_eq(jiffies, ar2->jiffies))
			return;

		ar2->jiffies = jiffies + msecs_to_jiffies(idev->rep[REP_PERIOD]);
		break;
	default:
		dev_err(&ar2->intf[1]->dev,
			"Unknown state byte (%02x %02x %02x %02x)\n",
			data[3], data[2], data[1], data[0]);
		return;
	}

	input_event(idev, EV_KEY, ar2->keycode[mode][index], data[1]);
	input_sync(idev);
}


jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size)
{
    Jbig2Segment *result;
     uint8_t rtscarf;
     uint32_t rtscarf_long;
     uint32_t *referred_to_segments;
    uint32_t referred_to_segment_count;
    uint32_t referred_to_segment_size;
    uint32_t pa_size;
    uint32_t offset;

     /* minimum possible size of a jbig2 segment header */
     if (buf_size < 11)
        return NULL;

    result = jbig2_new(ctx, Jbig2Segment, 1);
    if (result == NULL) {
        jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate segment in jbig2_parse_segment_header");
        return result;
    }

    /* 7.2.2 */
    result->number = jbig2_get_uint32(buf);

    /* 7.2.3 */
    result->flags = buf[4];

    /* 7.2.4 referred-to segments */
    rtscarf = buf[5];
    if ((rtscarf & 0xe0) == 0xe0) {
        rtscarf_long = jbig2_get_uint32(buf + 5);
        referred_to_segment_count = rtscarf_long & 0x1fffffff;
        offset = 5 + 4 + (referred_to_segment_count + 1) / 8;
    } else {
        referred_to_segment_count = (rtscarf >> 5);
        offset = 5 + 1;
    }
    result->referred_to_segment_count = referred_to_segment_count;

    /* we now have enough information to compute the full header length */
    referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4;     /* 7.2.5 */
    pa_size = result->flags & 0x40 ? 4 : 1;     /* 7.2.6 */
    if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) {
        jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "jbig2_parse_segment_header() called with insufficient data", -1);
        jbig2_free(ctx->allocator, result);
        return NULL;
    }

     /* 7.2.5 */
     if (referred_to_segment_count) {
        uint32_t i;

         referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size);
         if (referred_to_segments == NULL) {
            jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate referred_to_segments " "in jbig2_parse_segment_header");
            return NULL;
        }

        for (i = 0; i < referred_to_segment_count; i++) {
            referred_to_segments[i] =
                (referred_to_segment_size == 1) ? buf[offset] :
                (referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset);
            offset += referred_to_segment_size;
            jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d refers to segment %d", result->number, referred_to_segments[i]);
        }
        result->referred_to_segments = referred_to_segments;
    } else {                    /* no referred-to segments */

        result->referred_to_segments = NULL;
    }

    /* 7.2.6 */
    if (result->flags & 0x40) {
        result->page_association = jbig2_get_uint32(buf + offset);
        offset += 4;
    } else {
        result->page_association = buf[offset++];
    }
    jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d is associated with page %d", result->number, result->page_association);

    /* 7.2.7 */
    result->data_length = jbig2_get_uint32(buf + offset);
    *p_header_size = offset + 4;

    /* no body parsing results yet */
    result->result = NULL;

    return result;
}


Event* Document::createEvent(ScriptState* script_state,
                             const String& event_type,
                             ExceptionState& exception_state) {
  Event* event = nullptr;
  ExecutionContext* execution_context = ExecutionContext::From(script_state);
  for (const auto& factory : EventFactories()) {
    event = factory->Create(execution_context, event_type);
    if (event) {
      if (DeprecatedEqualIgnoringCase(event_type, "TouchEvent") &&
          !OriginTrials::touchEventFeatureDetectionEnabled(execution_context))
        break;
      return event;
    }
  }
  exception_state.ThrowDOMException(
      kNotSupportedError,
      "The provided event type ('" + event_type + "') is invalid.");
  return nullptr;
}


static int check_ref(const char *name, unsigned int flags)
{
	if (!flags)
		return 1;

	if (!skip_prefix(name, "refs/", &name))
		return 0;

	/* REF_NORMAL means that we don't want the magic fake tag refs */
	if ((flags & REF_NORMAL) && check_refname_format(name, 0))
		return 0;

	/* REF_HEADS means that we want regular branch heads */
	if ((flags & REF_HEADS) && starts_with(name, "heads/"))
		return 1;

	/* REF_TAGS means that we want tags */
	if ((flags & REF_TAGS) && starts_with(name, "tags/"))
		return 1;

	/* All type bits clear means that we are ok with anything */
	return !(flags & ~REF_NORMAL);
}


TEST(BasicFlatBufferModel, TestNonExistentFiles) {
  ASSERT_TRUE(!FlatBufferModel::BuildFromFile("/tmp/tflite_model_1234"));
}


static int tcp_v4_send_synack(struct sock *sk, struct dst_entry *dst,
			      struct request_sock *req,
			      struct request_values *rvp)
{
	const struct inet_request_sock *ireq = inet_rsk(req);
	int err = -1;
	struct sk_buff * skb;

	/* First, grab a route. */
	if (!dst && (dst = inet_csk_route_req(sk, req)) == NULL)
		return -1;

	skb = tcp_make_synack(sk, dst, req, rvp);

	if (skb) {
		__tcp_v4_send_check(skb, ireq->loc_addr, ireq->rmt_addr);

		err = ip_build_and_send_pkt(skb, sk, ireq->loc_addr,
					    ireq->rmt_addr,
					    ireq->opt);
		err = net_xmit_eval(err);
	}

	dst_release(dst);
	return err;
}


static int decode_attr_space_avail(struct xdr_stream *xdr, uint32_t *bitmap, uint64_t *res)
{
	__be32 *p;
	int status = 0;

	*res = 0;
	if (unlikely(bitmap[1] & (FATTR4_WORD1_SPACE_AVAIL - 1U)))
		return -EIO;
	if (likely(bitmap[1] & FATTR4_WORD1_SPACE_AVAIL)) {
		p = xdr_inline_decode(xdr, 8);
		if (unlikely(!p))
			goto out_overflow;
		xdr_decode_hyper(p, res);
		bitmap[1] &= ~FATTR4_WORD1_SPACE_AVAIL;
	}
	dprintk("%s: space avail=%Lu\n", __func__, (unsigned long long)*res);
	return status;
out_overflow:
	print_overflow_msg(__func__, xdr);
	return -EIO;
}


static int wc_EncodeName_ex(EncodedName* name, const char* nameStr, char nameType,
                  byte type, byte emailType)
{
    word32 idx = 0;
    /* bottom up */
    byte firstLen[1 + MAX_LENGTH_SZ];
    byte secondLen[MAX_LENGTH_SZ];
    byte sequence[MAX_SEQ_SZ];
    byte set[MAX_SET_SZ];

    int strLen;
    int thisLen;
    int firstSz, secondSz, seqSz, setSz;

    if (nameStr == NULL) {
        name->used = 0;
        return 0;
    }
    thisLen = strLen = (int)XSTRLEN(nameStr);
    if (strLen == 0) { /* no user data for this item */
        name->used = 0;
        return 0;
    }

    /* Restrict country code size */
    if (ASN_COUNTRY_NAME == type && strLen != CTC_COUNTRY_SIZE) {
        WOLFSSL_MSG("Country code size error");
        return ASN_COUNTRY_SIZE_E;
    }

    secondSz = SetLength(strLen, secondLen);
    thisLen += secondSz;
    switch (type) {
        case ASN_EMAIL_NAME: /* email */
            thisLen += EMAIL_JOINT_LEN;
            firstSz  = EMAIL_JOINT_LEN;
            break;

        case ASN_DOMAIN_COMPONENT:
            thisLen += PILOT_JOINT_LEN;
            firstSz  = PILOT_JOINT_LEN;
            break;

        default:
            thisLen++;                                 /* str type */
            thisLen += JOINT_LEN;
            firstSz  = JOINT_LEN + 1;
    }
    thisLen++; /* id  type */
    firstSz  = SetObjectId(firstSz, firstLen);
    thisLen += firstSz;

    seqSz = SetSequence(thisLen, sequence);
    thisLen += seqSz;
    setSz = SetSet(thisLen, set);
    thisLen += setSz;

    if (thisLen > (int)sizeof(name->encoded)) {
        return BUFFER_E;
    }

    /* store it */
    idx = 0;
    /* set */
    XMEMCPY(name->encoded, set, setSz);
    idx += setSz;
    /* seq */
    XMEMCPY(name->encoded + idx, sequence, seqSz);
    idx += seqSz;
    /* asn object id */
    XMEMCPY(name->encoded + idx, firstLen, firstSz);
    idx += firstSz;
    switch (type) {
        case ASN_EMAIL_NAME:
        {
            const byte EMAIL_OID[] = {
                0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01
            };
            /* email joint id */
            XMEMCPY(name->encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
            idx += (int)sizeof(EMAIL_OID);
            name->encoded[idx++] = emailType;
            break;
        }

        case ASN_DOMAIN_COMPONENT:
        {
            const byte PILOT_OID[] = {
                0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01
            };

            XMEMCPY(name->encoded + idx, PILOT_OID, sizeof(PILOT_OID));
            idx += (int)sizeof(PILOT_OID);
            /* id type */
            name->encoded[idx++] = type;
            /* str type */
            name->encoded[idx++] = nameType;
            break;
        }

        default:
            name->encoded[idx++] = 0x55;
            name->encoded[idx++] = 0x04;
            /* id type */
            name->encoded[idx++] = type;
            /* str type */
            name->encoded[idx++] = nameType;
    }
    /* second length */
    XMEMCPY(name->encoded + idx, secondLen, secondSz);
    idx += secondSz;
    /* str value */
    XMEMCPY(name->encoded + idx, nameStr, strLen);
    idx += strLen;

    name->type = type;
    name->totalLen = idx;
    name->used = 1;

    return idx;
}


memen(struct pci_vdev *dev)
{
	uint16_t cmd;

	cmd = pci_get_cfgdata16(dev, PCIR_COMMAND);

	return (cmd & PCIM_CMD_MEMEN) != 0;
}


DDWORD SwapDDWord(BYTE *p, int size) {
  union BYTES2DDWORD
  {
      DDWORD ddword;
      BYTE   bytes[sizeof(DDWORD)];
  };

  union BYTES2DDWORD converter;
  converter.ddword = 0;
  int i = 0;
  int correct = size > sizeof(DDWORD) ? sizeof(DDWORD) : size;

#ifdef WORDS_BIGENDIAN
  for (i = 0; i < correct; ++i)
  {
      converter.bytes[i] = p[correct - i];
  }
#else
  for (i = 0; i < correct; ++i)
  {
      converter.bytes[i] = p[i];
  }
#endif

  return converter.ddword;
}


BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)

{

    return is_read ? bs->on_read_error : bs->on_write_error;

}


void Database::setPassword(const QString &hostname, unsigned short port, const QString &uname, const QString &pw) {
	QSqlQuery query;
	query.prepare(QLatin1String("UPDATE `servers` SET `password` = ? WHERE `hostname` = ? AND `port` = ? AND `username` = ?"));
	query.addBindValue(pw);
	query.addBindValue(hostname);
	query.addBindValue(port);
	query.addBindValue(uname);
	query.exec();
}


ofputil_destroy_requestforward(struct ofputil_requestforward *rf)
{
    if (!rf) {
        return;
    }

    switch (rf->reason) {
    case OFPRFR_GROUP_MOD:
        ofputil_uninit_group_mod(rf->group_mod);
        free(rf->group_mod);
        break;

    case OFPRFR_METER_MOD:
        ofpbuf_uninit(&rf->bands);
        free(rf->meter_mod);
        break;

    case OFPRFR_N_REASONS:
        OVS_NOT_REACHED();
    }
}


static int ath10k_usb_hif_start(struct ath10k *ar)
{
	int i;
	struct ath10k_usb *ar_usb = ath10k_usb_priv(ar);

	ath10k_usb_start_recv_pipes(ar);

	/* set the TX resource avail threshold for each TX pipe */
	for (i = ATH10K_USB_PIPE_TX_CTRL;
	     i <= ATH10K_USB_PIPE_TX_DATA_HP; i++) {
		ar_usb->pipes[i].urb_cnt_thresh =
		    ar_usb->pipes[i].urb_alloc / 2;
	}

	return 0;
}


bool SSLClientSocketOpenSSL::DoTransportIO() {
  bool network_moved = false;
  int rv;
  do {
    rv = BufferSend();
    if (rv != ERR_IO_PENDING && rv != 0)
      network_moved = true;
  } while (rv > 0);
  if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
    network_moved = true;
  return network_moved;
}


GF_Err tsel_box_read(GF_Box *s,GF_BitStream *bs)
{
	u32 i;
	GF_TrackSelectionBox *ptr = (GF_TrackSelectionBox *) s;

	ISOM_DECREASE_SIZE(ptr, 4);
	ptr->switchGroup = gf_bs_read_u32(bs);

	if (ptr->size % 4) return GF_ISOM_INVALID_FILE;
	ptr->attributeListCount = (u32)ptr->size/4;
	ptr->attributeList = gf_malloc(ptr->attributeListCount*sizeof(u32));
	if (ptr->attributeList == NULL) return GF_OUT_OF_MEM;

	for (i=0; i< ptr->attributeListCount; i++) {
		ptr->attributeList[i] = gf_bs_read_u32(bs);
	}
	return GF_OK;
}


  void Verify_StoreNewGroup() {
    EXPECT_TRUE(delegate()->stored_group_success_);
    EXPECT_EQ(group_.get(), delegate()->stored_group_.get());
    EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
    EXPECT_TRUE(cache_->is_complete());

    AppCacheDatabase::GroupRecord group_record;
    AppCacheDatabase::CacheRecord cache_record;
    EXPECT_TRUE(database()->FindGroup(group_->group_id(), &group_record));
    EXPECT_TRUE(database()->FindCache(cache_->cache_id(), &cache_record));

    EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
    EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
    EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
    EXPECT_EQ(kDefaultEntrySize, mock_quota_manager_proxy_->last_delta_);

    TestFinished();
  }


parse_schema_nodeid(const char *id, const char **mod_name, int *mod_name_len, const char **name, int *nam_len,
                    int *is_relative, int *has_predicate, int *all_desc, int extended)
{
    int parsed = 0, ret;

    assert(id);
    assert(is_relative);

    if (has_predicate) {
        *has_predicate = 0;
    }

    if (id[0] != '/') {
        if (*is_relative != -1) {
            return -parsed;
        } else {
            *is_relative = 1;
        }
        if (!strncmp(id, "./", 2)) {
            parsed += 2;
            id += 2;
        }
    } else {
        if (*is_relative == -1) {
            *is_relative = 0;
        }
        ++parsed;
        ++id;
    }

    if ((ret = parse_node_identifier(id, mod_name, mod_name_len, name, nam_len, all_desc, extended)) < 1) {
        return -parsed + ret;
    }

    parsed += ret;
    id += ret;

    if ((id[0] == '[') && has_predicate) {
        *has_predicate = 1;
    }

    return parsed;
}


static void ntlm_compute_channel_bindings(NTLM_CONTEXT* context)
{
	WINPR_DIGEST_CTX* md5;
	BYTE* ChannelBindingToken;
	UINT32 ChannelBindingTokenLength;
	SEC_CHANNEL_BINDINGS* ChannelBindings;
	ZeroMemory(context->ChannelBindingsHash, WINPR_MD5_DIGEST_LENGTH);
	ChannelBindings = context->Bindings.Bindings;

	if (!ChannelBindings)
		return;

	if (!(md5 = winpr_Digest_New()))
		return;

	if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
		goto out;

	ChannelBindingTokenLength = context->Bindings.BindingsLength - sizeof(SEC_CHANNEL_BINDINGS);
	ChannelBindingToken = &((BYTE*)ChannelBindings)[ChannelBindings->dwApplicationDataOffset];

	if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->dwInitiatorAddrType))
		goto out;

	if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbInitiatorLength))
		goto out;

	if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->dwAcceptorAddrType))
		goto out;

	if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbAcceptorLength))
		goto out;

	if (!ntlm_md5_update_uint32_be(md5, ChannelBindings->cbApplicationDataLength))
		goto out;

	if (!winpr_Digest_Update(md5, (void*)ChannelBindingToken, ChannelBindingTokenLength))
		goto out;

	if (!winpr_Digest_Final(md5, context->ChannelBindingsHash, WINPR_MD5_DIGEST_LENGTH))
		goto out;

out:
	winpr_Digest_Free(md5);
}


void RequestContext::FillOperationInfo(service_control::OperationInfo *info) {
  if (method()) {
    info->operation_name = method()->selector();
  } else {
    info->operation_name = kUnrecognizedOperation;
  }
  info->operation_id = operation_id_;
  if (check_response_info_.is_api_key_valid &&
      check_response_info_.service_is_activated) {
    info->api_key = api_key_;
  }
  info->producer_project_id = service_context()->project_id();
  info->referer = http_referer_;
  info->request_start_time = start_time_;
  info->client_ip = FindClientIPAddress();
  info->client_host = request_->GetClientHost();
}


hb_set_union (hb_set_t       *set,
	      const hb_set_t *other)
{
  if (unlikely (hb_object_is_immutable (set)))
    return;

  set->union_ (*other);
}


static int handle_pte_fault(struct mm_struct *mm,
		     struct vm_area_struct *vma, unsigned long address,
		     pte_t *pte, pmd_t *pmd, unsigned int flags)
{
	pte_t entry;
	spinlock_t *ptl;

	/*
	 * some architectures can have larger ptes than wordsize,
	 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and CONFIG_32BIT=y,
	 * so READ_ONCE or ACCESS_ONCE cannot guarantee atomic accesses.
	 * The code below just needs a consistent view for the ifs and
	 * we later double check anyway with the ptl lock held. So here
	 * a barrier will do.
	 */
	entry = *pte;
	barrier();
	if (!pte_present(entry)) {
		if (pte_none(entry)) {
			if (vma->vm_ops) {
				if (likely(vma->vm_ops->fault))
					return do_fault(mm, vma, address, pte,
							pmd, flags, entry);
			}
			return do_anonymous_page(mm, vma, address,
						 pte, pmd, flags);
		}
		return do_swap_page(mm, vma, address,
					pte, pmd, flags, entry);
	}

	if (pte_protnone(entry))
		return do_numa_page(mm, vma, address, entry, pte, pmd);

	ptl = pte_lockptr(mm, pmd);
	spin_lock(ptl);
	if (unlikely(!pte_same(*pte, entry)))
		goto unlock;
	if (flags & FAULT_FLAG_WRITE) {
		if (!pte_write(entry))
			return do_wp_page(mm, vma, address,
					pte, pmd, ptl, entry);
		entry = pte_mkdirty(entry);
	}
	entry = pte_mkyoung(entry);
	if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {
		update_mmu_cache(vma, address, pte);
	} else {
		/*
		 * This is needed only for protection faults but the arch code
		 * is not yet telling us if this is a protection fault or not.
		 * This still avoids useless tlb flushes for .text page faults
		 * with threads.
		 */
		if (flags & FAULT_FLAG_WRITE)
			flush_tlb_fix_spurious_fault(vma, address);
	}
unlock:
	pte_unmap_unlock(pte, ptl);
	return 0;
}


static void qdm2_decode_fft_packets (QDM2Context *q)

{

    int i, j, min, max, value, type, unknown_flag;

    GetBitContext gb;

    if (q->sub_packet_list_B[0].packet == NULL)

        return;

    /* reset minimum indices for FFT coefficients */

    q->fft_coefs_index = 0;

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

        q->fft_coefs_min_index[i] = -1;

    /* process subpackets ordered by type, largest type first */

    for (i = 0, max = 256; i < q->sub_packets_B; i++) {

        QDM2SubPacket *packet;

        /* find subpacket with largest type less than max */

        for (j = 0, min = 0, packet = NULL; j < q->sub_packets_B; j++) {

            value = q->sub_packet_list_B[j].packet->type;

            if (value > min && value < max) {

                min = value;

                packet = q->sub_packet_list_B[j].packet;

            }

        }

        max = min;

        /* check for errors (?) */

        if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))

            return;

        /* decode FFT tones */

        init_get_bits (&gb, packet->data, packet->size*8);

        if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])

            unknown_flag = 1;

        else

            unknown_flag = 0;

        type = packet->type;

        if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {

            int duration = q->sub_sampling + 5 - (type & 15);

            if (duration >= 0 && duration < 4)

                qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);

        } else if (type == 31) {

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

                qdm2_fft_decode_tones(q, i, &gb, unknown_flag);

        } else if (type == 46) {

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

                q->fft_level_exp[i] = get_bits(&gb, 6);

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

            qdm2_fft_decode_tones(q, i, &gb, unknown_flag);

        }

    } // Loop on B packets

    /* calculate maximum indices for FFT coefficients */

    for (i = 0, j = -1; i < 5; i++)

        if (q->fft_coefs_min_index[i] >= 0) {

            if (j >= 0)

                q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];

            j = i;

        }

    if (j >= 0)

        q->fft_coefs_max_index[j] = q->fft_coefs_index;

}


static void vtd_address_space_unmap(VTDAddressSpace *as, IOMMUNotifier *n)

{

    IOMMUTLBEntry entry;

    hwaddr size;

    hwaddr start = n->start;

    hwaddr end = n->end;

    /*

     * Note: all the codes in this function has a assumption that IOVA

     * bits are no more than VTD_MGAW bits (which is restricted by

     * VT-d spec), otherwise we need to consider overflow of 64 bits.

     */

    if (end > VTD_ADDRESS_SIZE(VTD_HOST_ADDRESS_WIDTH)) {

        /*

         * Don't need to unmap regions that is bigger than the whole

         * VT-d supported address space size

         */

        end = VTD_ADDRESS_SIZE(VTD_HOST_ADDRESS_WIDTH);

    }

    assert(start <= end);

    size = end - start;

    if (ctpop64(size) != 1) {

        /*

         * This size cannot format a correct mask. Let's enlarge it to

         * suite the minimum available mask.

         */

        int n = 64 - clz64(size);

        if (n > VTD_MGAW) {

            /* should not happen, but in case it happens, limit it */

            n = VTD_MGAW;

        }

        size = 1ULL << n;

    }

    entry.target_as = &address_space_memory;

    /* Adjust iova for the size */

    entry.iova = n->start & ~(size - 1);

    /* This field is meaningless for unmap */

    entry.translated_addr = 0;

    entry.perm = IOMMU_NONE;

    entry.addr_mask = size - 1;

    trace_vtd_as_unmap_whole(pci_bus_num(as->bus),

                             VTD_PCI_SLOT(as->devfn),

                             VTD_PCI_FUNC(as->devfn),

                             entry.iova, size);

    memory_region_notify_one(n, &entry);

}


set_optimize_exact(regex_t* reg, OptStr* e)
{
  int r;

  if (e->len == 0) return 0;

  reg->exact = (UChar* )xmalloc(e->len);
  CHECK_NULL_RETURN_MEMERR(reg->exact);
  xmemcpy(reg->exact, e->s, e->len);
  reg->exact_end = reg->exact + e->len;

  if (e->case_fold) {
    reg->optimize = OPTIMIZE_STR_CASE_FOLD;
    if (e->good_case_fold != 0) {
      if (e->len >= 2) {
        r = set_sunday_quick_search_or_bmh_skip_table(reg, 1,
                             reg->exact, reg->exact_end,
                             reg->map, &(reg->map_offset));
        if (r != 0) return r;
        reg->optimize = OPTIMIZE_STR_CASE_FOLD_FAST;
      }
    }
  }
  else {
    int allow_reverse;

    allow_reverse =
      ONIGENC_IS_ALLOWED_REVERSE_MATCH(reg->enc, reg->exact, reg->exact_end);

    if (e->len >= 2 || (e->len >= 1 && allow_reverse)) {
      r = set_sunday_quick_search_or_bmh_skip_table(reg, 0,
                                         reg->exact, reg->exact_end,
                                         reg->map, &(reg->map_offset));
      if (r != 0) return r;

      reg->optimize = (allow_reverse != 0
                       ? OPTIMIZE_STR_FAST
                       : OPTIMIZE_STR_FAST_STEP_FORWARD);
    }
    else {
      reg->optimize = OPTIMIZE_STR;
    }
  }

  reg->dmin = e->mmd.min;
  reg->dmax = e->mmd.max;

  if (reg->dmin != INFINITE_LEN) {
    reg->threshold_len = reg->dmin + (int )(reg->exact_end - reg->exact);
  }

  return 0;
}


static inline int mm_counter_file(struct page *page)
{
	if (PageSwapBacked(page))
		return MM_SHMEMPAGES;
	return MM_FILEPAGES;
}


void RenderViewImpl::ProcessAcceleratedPinchZoomFlags(
    const CommandLine& command_line) {
  if (!webview()->isAcceleratedCompositingActive())
    return;

  bool enable_viewport = command_line.HasSwitch(switches::kEnableViewport);
  bool enable_pinch = command_line.HasSwitch(switches::kEnablePinch)
      || command_line.HasSwitch(switches::kEnableCssTransformPinch);

  if (enable_viewport)
    return;

  if (enable_pinch)
    webview()->setPageScaleFactorLimits(1, 4);
  else
    webview()->setPageScaleFactorLimits(1, 1);
}


void avcc_del(GF_Box *s)
{
	GF_AVCConfigurationBox *ptr = (GF_AVCConfigurationBox *)s;
	if (ptr->config) gf_odf_avc_cfg_del(ptr->config);
	gf_free(ptr);
}


struct zip_cdir * _zip_cdir_new ( int nentry , struct zip_error * error ) {
 struct zip_cdir * cd ;
 if ( ( cd = ( struct zip_cdir * ) malloc ( sizeof ( * cd ) ) ) == NULL ) {
 _zip_error_set ( error , ZIP_ER_MEMORY , 0 ) ;
 return NULL ;
 }
 if ( ( cd -> entry = ( struct zip_dirent * ) malloc ( sizeof ( * ( cd -> entry ) ) * nentry ) ) == NULL ) {
 _zip_error_set ( error , ZIP_ER_MEMORY , 0 ) ;
 free ( cd ) ;
 return NULL ;
 }
 cd -> nentry = nentry ;
 cd -> size = cd -> offset = 0 ;
 cd -> comment = NULL ;
 cd -> comment_len = 0 ;
 return cd ;
 }


static struct hlist_nulls_node *ct_get_idx(struct seq_file *seq, loff_t pos)
{
	struct hlist_nulls_node *head = ct_get_first(seq);

	if (head)
		while (pos && (head = ct_get_next(seq, head)))
			pos--;
	return pos ? NULL : head;
}


static uint8_t check_length(uint16_t length, uint16_t offset)
{
	if (length > BT_ATT_MAX_VALUE_LEN)
		return BT_ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LEN;

	if (offset > BT_ATT_MAX_VALUE_LEN)
		return BT_ATT_ERROR_INVALID_OFFSET;

	if (length + offset > BT_ATT_MAX_VALUE_LEN)
		return BT_ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LEN;

	return 0;
}


static bool HHVM_METHOD(ZipArchive, addGlob, const String& pattern,
                        int64_t flags, const Array& options) {
  auto zipDir = getResource<ZipDirectory>(this_, "zipDir");

  FAIL_IF_INVALID_ZIPARCHIVE(addGlob, zipDir);
  FAIL_IF_EMPTY_STRING_ZIPARCHIVE(addGlob, pattern);

  return addPattern(zipDir->getZip(), pattern, options, "", flags, true);
}


static int MP4_ReadBox_mvhd(  stream_t *p_stream, MP4_Box_t *p_box )
{
#ifdef MP4_VERBOSE
    char s_creation_time[128];
    char s_modification_time[128];
    char s_duration[128];
#endif
    MP4_READBOX_ENTER( MP4_Box_data_mvhd_t );

    MP4_GETVERSIONFLAGS( p_box->data.p_mvhd );

    if( p_box->data.p_mvhd->i_version )
    {
        MP4_GET8BYTES( p_box->data.p_mvhd->i_creation_time );
        MP4_GET8BYTES( p_box->data.p_mvhd->i_modification_time );
        MP4_GET4BYTES( p_box->data.p_mvhd->i_timescale );
        MP4_GET8BYTES( p_box->data.p_mvhd->i_duration );
    }
    else
    {
        MP4_GET4BYTES( p_box->data.p_mvhd->i_creation_time );
        MP4_GET4BYTES( p_box->data.p_mvhd->i_modification_time );
        MP4_GET4BYTES( p_box->data.p_mvhd->i_timescale );
        MP4_GET4BYTES( p_box->data.p_mvhd->i_duration );
    }
    MP4_GET4BYTES( p_box->data.p_mvhd->i_rate );
    MP4_GET2BYTES( p_box->data.p_mvhd->i_volume );
    MP4_GET2BYTES( p_box->data.p_mvhd->i_reserved1 );

    for( unsigned i = 0; i < 2; i++ )
    {
        MP4_GET4BYTES( p_box->data.p_mvhd->i_reserved2[i] );
    }
    for( unsigned i = 0; i < 9; i++ )
    {
        MP4_GET4BYTES( p_box->data.p_mvhd->i_matrix[i] );
    }
    for( unsigned i = 0; i < 6; i++ )
    {
        MP4_GET4BYTES( p_box->data.p_mvhd->i_predefined[i] );
    }

    MP4_GET4BYTES( p_box->data.p_mvhd->i_next_track_id );

#ifdef MP4_VERBOSE
    MP4_ConvertDate2Str( s_creation_time, p_box->data.p_mvhd->i_creation_time, false );
    MP4_ConvertDate2Str( s_modification_time,
                         p_box->data.p_mvhd->i_modification_time, false );
    if( p_box->data.p_mvhd->i_rate )
    {
        MP4_ConvertDate2Str( s_duration,
                 p_box->data.p_mvhd->i_duration / p_box->data.p_mvhd->i_rate, true );
    }
    else
    {
        s_duration[0] = 0;
    }
    msg_Dbg( p_stream, "read box: \"mvhd\" creation %s modification %s time scale %d duration %s rate %f volume %f next track id %d",
                  s_creation_time,
                  s_modification_time,
                  (uint32_t)p_box->data.p_mvhd->i_timescale,
                  s_duration,
                  (float)p_box->data.p_mvhd->i_rate / (1<<16 ),
                  (float)p_box->data.p_mvhd->i_volume / 256 ,
                  (uint32_t)p_box->data.p_mvhd->i_next_track_id );
#endif
    MP4_READBOX_EXIT( 1 );
}


void ChromeExtensionWebContentsObserver::RenderViewCreated(
     content::RenderViewHost* render_view_host) {
   ReloadIfTerminated(render_view_host);
   ExtensionWebContentsObserver::RenderViewCreated(render_view_host);
 }


static char * default_opaque_binary_tag ( tvbuff_t * tvb , guint32 offset , guint8 token _U_ , guint8 codepage _U_ , guint32 * length ) {
 guint32 data_len = tvb_get_guintvar ( tvb , offset , length ) ;
 char * str = wmem_strdup_printf ( wmem_packet_scope ( ) , "(%d bytes of opaque data)" , data_len ) ;
 * length += data_len ;
 return str ;
 }


png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
{
   unsigned int i;

   png_debug(1, "in png_handle_eXIf");

   if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
      png_chunk_error(png_ptr, "missing IHDR");

   if (length < 2)
   {
      png_crc_finish(png_ptr, length);
      png_chunk_benign_error(png_ptr, "too short");
      return;
   }

   else if (info_ptr == NULL || (info_ptr->valid & PNG_INFO_eXIf) != 0)
   {
      png_crc_finish(png_ptr, length);
      png_chunk_benign_error(png_ptr, "duplicate");
      return;
   }

   info_ptr->free_me |= PNG_FREE_EXIF;

   info_ptr->eXIf_buf = png_voidcast(png_bytep,
             png_malloc_warn(png_ptr, length));

   if (info_ptr->eXIf_buf == NULL)
   {
      png_crc_finish(png_ptr, length);
      png_chunk_benign_error(png_ptr, "out of memory");
      return;
   }

   for (i = 0; i < length; i++)
   {
      png_byte buf[1];
      png_crc_read(png_ptr, buf, 1);
      info_ptr->eXIf_buf[i] = buf[0];
      if (i == 1 && buf[0] != 'M' && buf[0] != 'I'
                 && info_ptr->eXIf_buf[0] != buf[0])
      {
         png_crc_finish(png_ptr, length);
         png_chunk_benign_error(png_ptr, "incorrect byte-order specifier");
         png_free(png_ptr, info_ptr->eXIf_buf);
         info_ptr->eXIf_buf = NULL;
         return;
      }
   }

   if (png_crc_finish(png_ptr, 0) != 0)
      return;

   png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf);

   png_free(png_ptr, info_ptr->eXIf_buf);
   info_ptr->eXIf_buf = NULL;
}


void RenderView::OnRedo() {
  if (!webview())
    return;

  webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Redo"));
}


static GF_Err flac_dmx_initialize(GF_Filter *filter)
{
	GF_FLACDmxCtx *ctx = gf_filter_get_udta(filter);
	ctx->bs = gf_bs_new((u8 *)ctx, 1, GF_BITSTREAM_READ);
	return GF_OK;
}


LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentTempo(ModPlugFile* file)
{
	if(!file) return 0;
	return openmpt_module_get_current_tempo(file->mod);
}


void WebFrameLoaderClient::download(ResourceHandle* handle,
                                    const ResourceRequest& request,
                                    const ResourceRequest& initialRequest,
                                    const ResourceResponse& response) {
  NOTREACHED();
}


TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  TfLiteTensor* output_values;
  TF_LITE_ENSURE_OK(
      context, GetOutputSafe(context, node, kOutputValues, &output_values));
  TfLiteTensor* output_indexes;
  TF_LITE_ENSURE_OK(
      context, GetOutputSafe(context, node, kOutputIndexes, &output_indexes));
  if (IsDynamicTensor(output_values)) {
    TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
  }
  const TfLiteTensor* top_k;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTopK, &top_k));
  const int32 k = top_k->data.i32[0];
  // The tensor can have more than 2 dimensions or even be a vector, the code
  // anyway calls the internal dimension as row;
  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  const int32 row_size = input->dims->data[input->dims->size - 1];
  int32 num_rows = 1;
  for (int i = 0; i < input->dims->size - 1; ++i) {
    num_rows *= input->dims->data[i];
  }
  switch (output_values->type) {
    case kTfLiteFloat32:
      TopK(row_size, num_rows, GetTensorData<float>(input), k,
           output_indexes->data.i32, GetTensorData<float>(output_values));
      break;
    case kTfLiteUInt8:
      TopK(row_size, num_rows, input->data.uint8, k, output_indexes->data.i32,
           output_values->data.uint8);
      break;
    case kTfLiteInt8:
      TopK(row_size, num_rows, input->data.int8, k, output_indexes->data.i32,
           output_values->data.int8);
      break;
    case kTfLiteInt32:
      TopK(row_size, num_rows, input->data.i32, k, output_indexes->data.i32,
           output_values->data.i32);
      break;
    case kTfLiteInt64:
      TopK(row_size, num_rows, input->data.i64, k, output_indexes->data.i32,
           output_values->data.i64);
      break;
    default:
      TF_LITE_KERNEL_LOG(context, "Type %s is currently not supported by TopK.",
                         TfLiteTypeGetName(output_values->type));
      return kTfLiteError;
  }

  return kTfLiteOk;
}


static void copy_out_param(struct tee_ta_param *ta_param, uint32_t num_params,
			   struct optee_msg_param *params, uint64_t *saved_attr)
{
	size_t n;

	for (n = 0; n < num_params; n++) {
		switch (TEE_PARAM_TYPE_GET(ta_param->types, n)) {
		case TEE_PARAM_TYPE_MEMREF_OUTPUT:
		case TEE_PARAM_TYPE_MEMREF_INOUT:
			switch (saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK) {
			case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
			case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
				params[n].u.tmem.size = ta_param->u[n].mem.size;
				break;
			case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
			case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
				params[n].u.rmem.size = ta_param->u[n].mem.size;
				break;
			default:
				break;
			}
			break;
		case TEE_PARAM_TYPE_VALUE_OUTPUT:
		case TEE_PARAM_TYPE_VALUE_INOUT:
			params[n].u.value.a = ta_param->u[n].val.a;
			params[n].u.value.b = ta_param->u[n].val.b;
			break;
		default:
			break;
		}
	}
}


static void get_tile_buffer ( const uint8_t * const data_end , int is_last , struct vpx_internal_error_info * error_info , const uint8_t * * data , vpx_decrypt_cb decrypt_cb , void * decrypt_state , TileBuffer * buf ) {
 size_t size ;
 if ( ! is_last ) {
 if ( ! read_is_valid ( * data , 4 , data_end ) ) vpx_internal_error ( error_info , VPX_CODEC_CORRUPT_FRAME , "Truncated packet or corrupt tile length" ) ;
 if ( decrypt_cb ) {
 uint8_t be_data [ 4 ] ;
 decrypt_cb ( decrypt_state , * data , be_data , 4 ) ;
 size = mem_get_be32 ( be_data ) ;
 }
 else {
 size = mem_get_be32 ( * data ) ;
 }
 * data += 4 ;
 if ( size > ( size_t ) ( data_end - * data ) ) vpx_internal_error ( error_info , VPX_CODEC_CORRUPT_FRAME , "Truncated packet or corrupt tile size" ) ;
 }
 else {
 size = data_end - * data ;
 }
 buf -> data = * data ;
 buf -> size = size ;
 * data += size ;
 }


CImgException() { _message = new char[1]; *_message = 0; }


static void JS_DefineAction(v8::FunctionCallbackInfo<v8::Value> const& args) {
  TRI_V8_TRY_CATCH_BEGIN(isolate);
  v8::HandleScope scope(isolate);
  TRI_GET_GLOBALS();

  if (args.Length() != 3) {
    TRI_V8_THROW_EXCEPTION_USAGE(
        "defineAction(<name>, <callback>, <parameter>)");
  }

  V8SecurityFeature& v8security = v8g->_server.getFeature<V8SecurityFeature>();

  if (!v8security.isAllowedToDefineHttpAction(isolate)) {
    TRI_V8_THROW_EXCEPTION_MESSAGE(TRI_ERROR_FORBIDDEN, "operation only allowed for internal scripts");
  }

  // extract the action name
  TRI_Utf8ValueNFC utf8name(isolate, args[0]);

  if (*utf8name == nullptr) {
    TRI_V8_THROW_TYPE_ERROR("<name> must be an UTF-8 string");
  }

  std::string name = *utf8name;

  // extract the action callback
  if (!args[1]->IsFunction()) {
    TRI_V8_THROW_TYPE_ERROR("<callback> must be a function");
  }

  v8::Handle<v8::Function> callback = v8::Handle<v8::Function>::Cast(args[1]);

  // extract the options
  v8::Handle<v8::Object> options;

  if (args[2]->IsObject()) {
    options = args[2]->ToObject(TRI_IGETC).FromMaybe(v8::Local<v8::Object>());
  } else {
    options = v8::Object::New(isolate);
  }

  // create an action with the given options
  auto action = std::make_shared<v8_action_t>(v8g->_server.getFeature<ActionFeature>());
  ParseActionOptions(isolate, v8g, action.get(), options);

  // store an action with the given name
  // note: this may return a previous action for the same name
  std::shared_ptr<TRI_action_t> actionForName = TRI_DefineActionVocBase(name, action);

  v8_action_t* v8ActionForName = dynamic_cast<v8_action_t*>(actionForName.get());

  if (v8ActionForName != nullptr) {
    v8ActionForName->createCallback(isolate, callback);
  } else {
    LOG_TOPIC("43be9", WARN, arangodb::Logger::FIXME)
        << "cannot create callback for V8 action";
  }

  TRI_V8_RETURN_UNDEFINED();
  TRI_V8_TRY_CATCH_END
}


static int ebb_event_check(struct perf_event *event) { return 0; }


static void perf_pending_event(struct irq_work *entry)
{
	struct perf_event *event = container_of(entry,
			struct perf_event, pending);
	int rctx;

	rctx = perf_swevent_get_recursion_context();
	/*
	 * If we 'fail' here, that's OK, it means recursion is already disabled
	 * and we won't recurse 'further'.
	 */

	if (event->pending_disable) {
		event->pending_disable = 0;
		perf_event_disable_local(event);
	}

	if (event->pending_wakeup) {
		event->pending_wakeup = 0;
		perf_event_wakeup(event);
	}

	if (rctx >= 0)
		perf_swevent_put_recursion_context(rctx);
}


static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx)
{
	return proc_pident_readdir(file, ctx,
				   tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
}


static int unin_main_pci_host_init(PCIDevice *d)

{

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_APPLE);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_APPLE_UNI_N_PCI);

    d->config[0x08] = 0x00; // revision

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);

    d->config[0x0C] = 0x08; // cache_line_size

    d->config[0x0D] = 0x10; // latency_timer

    d->config[0x34] = 0x00; // capabilities_pointer

    return 0;

}