static MXFStructuralComponent* mxf_resolve_sourceclip(MXFContext *mxf, UID *strong_ref)
{
    MXFStructuralComponent *component = NULL;

    component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
    if (!component)
        return NULL;
    switch (component->type) {
        case SourceClip:
            return component;
        case EssenceGroup:
            return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component);
        default:
            break;
    }
    return NULL;
}


void RenderProcessHostImpl::CreateRendererHost(
    mojom::RendererHostAssociatedRequest request) {
  renderer_host_binding_.Bind(std::move(request));
}


static void vfio_listener_region_del(MemoryListener *listener,

                                     MemoryRegionSection *section)

{

    VFIOContainer *container = container_of(listener, VFIOContainer, listener);

    hwaddr iova, end;

    Int128 llend, llsize;

    int ret;

    if (vfio_listener_skipped_section(section)) {

        trace_vfio_listener_region_del_skip(

                section->offset_within_address_space,

                section->offset_within_address_space +

                int128_get64(int128_sub(section->size, int128_one())));

        return;

    }

    if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=

                 (section->offset_within_region & ~TARGET_PAGE_MASK))) {

        error_report("%s received unaligned region", __func__);

        return;

    }

    if (memory_region_is_iommu(section->mr)) {

        VFIOGuestIOMMU *giommu;

        QLIST_FOREACH(giommu, &container->giommu_list, giommu_next) {

            if (giommu->iommu == section->mr) {

                memory_region_unregister_iommu_notifier(giommu->iommu,

                                                        &giommu->n);

                QLIST_REMOVE(giommu, giommu_next);

                g_free(giommu);

                break;

            }

        }

        /*

         * FIXME: We assume the one big unmap below is adequate to

         * remove any individual page mappings in the IOMMU which

         * might have been copied into VFIO. This works for a page table

         * based IOMMU where a big unmap flattens a large range of IO-PTEs.

         * That may not be true for all IOMMU types.

         */

    }

    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);

    llend = int128_make64(section->offset_within_address_space);

    llend = int128_add(llend, section->size);

    llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));

    if (int128_ge(int128_make64(iova), llend)) {

        return;

    }

    end = int128_get64(int128_sub(llend, int128_one()));

    llsize = int128_sub(llend, int128_make64(iova));

    trace_vfio_listener_region_del(iova, end);

    ret = vfio_dma_unmap(container, iova, int128_get64(llsize));

    memory_region_unref(section->mr);

    if (ret) {

        error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "

                     "0x%"HWADDR_PRIx") = %d (%m)",

                     container, iova, int128_get64(llsize), ret);

    }

    if (container->iommu_type == VFIO_SPAPR_TCE_v2_IOMMU) {

        vfio_spapr_remove_window(container,

                                 section->offset_within_address_space);

        if (vfio_host_win_del(container,

                              section->offset_within_address_space,

                              section->offset_within_address_space +

                              int128_get64(section->size) - 1) < 0) {

            hw_error("%s: Cannot delete missing window at %"HWADDR_PRIx,

                     __func__, section->offset_within_address_space);

        }

    }

}


bool Helper::isDiskDevice(const QString &devicePath)
{
    const QJsonArray &blocks = getBlockDevices(devicePath);

    if (blocks.isEmpty())
        return false;

    if (!blocks.first().isObject())
        return false;

    return blocks.first().toObject().value("pkname").isNull();
}


void OfflineAudioDestinationHandler::FinishOfflineRendering() {
  DCHECK(!IsMainThread());

  PostCrossThreadTask(
      *main_thread_task_runner_, FROM_HERE,
      CrossThreadBind(&OfflineAudioDestinationHandler::NotifyComplete,
                      WrapRefCounted(this)));
}


    BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
    BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
         : mMem(mem),
          mIsBackup(is_backup),
          mPortIndex(portIndex) {
     }


struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
{
	struct qstr this;
	unsigned int c;
	int err;

	WARN_ON_ONCE(!inode_is_locked(base->d_inode));

	this.name = name;
	this.len = len;
	this.hash = full_name_hash(base, name, len);
	if (!len)
		return ERR_PTR(-EACCES);

	if (unlikely(name[0] == '.')) {
		if (len < 2 || (len == 2 && name[1] == '.'))
			return ERR_PTR(-EACCES);
	}

	while (len--) {
		c = *(const unsigned char *)name++;
		if (c == '/' || c == '\0')
			return ERR_PTR(-EACCES);
	}
	/*
	 * See if the low-level filesystem might want
	 * to use its own hash..
	 */
	if (base->d_flags & DCACHE_OP_HASH) {
		int err = base->d_op->d_hash(base, &this);
		if (err < 0)
			return ERR_PTR(err);
	}

	err = inode_permission(base->d_inode, MAY_EXEC);
	if (err)
		return ERR_PTR(err);

	return __lookup_hash(&this, base, 0);
}


void TestingAutomationProvider::GetLocalStatePrefsInfo(
    DictionaryValue* args,
    IPC::Message* reply_message) {
  DictionaryValue* items = g_browser_process->local_state()->
      GetPreferenceValues();
  scoped_ptr<DictionaryValue> return_value(new DictionaryValue);
  return_value->Set("prefs", items);  // return_value owns items.
  AutomationJSONReply(this, reply_message).SendSuccess(return_value.get());
}


void DevToolsAgent::sendMessageToInspectorFrontend(
    const WebKit::WebString& message) {
  Send(new DevToolsHostMsg_ForwardToClient(
      routing_id(),
      DevToolsClientMsg_DispatchOnInspectorFrontend(MSG_ROUTING_NONE,
                                                    message.utf8())));
}


nfsd4_decode_fallocate(struct nfsd4_compoundargs *argp,
		       struct nfsd4_fallocate *fallocate)
{
	DECODE_HEAD;

	status = nfsd4_decode_stateid(argp, &fallocate->falloc_stateid);
	if (status)
		return status;

	READ_BUF(16);
	p = xdr_decode_hyper(p, &fallocate->falloc_offset);
	xdr_decode_hyper(p, &fallocate->falloc_length);

	DECODE_TAIL;
}


CIRCNetwork* CUser::FindNetwork(const CString& sNetwork) const {
    for (CIRCNetwork* pNetwork : m_vIRCNetworks) {
        if (pNetwork->GetName().Equals(sNetwork)) {
            return pNetwork;
        }
    }

    return nullptr;
}


mrb_realloc(mrb_state *mrb, void *p, size_t len)
{
  void *p2;

  p2 = mrb_realloc_simple(mrb, p, len);
  if (len == 0) return p2;
  if (p2 == NULL) {
    mrb->gc.out_of_memory = TRUE;
    mrb_raise_nomemory(mrb);
  }
  else {
    mrb->gc.out_of_memory = FALSE;
  }

  return p2;
}


CAMLprim value caml_string_get(value str, value index)
{
  intnat idx = Long_val(index);
  if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error();
  return Val_int(Byte_u(str, idx));
}


Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena *arena)
{
    stmt_ty p;
    if (!test) {
        PyErr_SetString(PyExc_ValueError,
                        "field test is required for Assert");
        return NULL;
    }
    p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
    if (!p)
        return NULL;
    p->kind = Assert_kind;
    p->v.Assert.test = test;
    p->v.Assert.msg = msg;
    p->lineno = lineno;
    p->col_offset = col_offset;
    return p;
}


set_tctl(E1000State *s, int index, uint32_t val)
{
    s->mac_reg[index] = val;
    s->mac_reg[TDT] &= 0xffff;
    start_xmit(s);
}


int sk_chk_filter(struct sock_filter *filter, unsigned int flen)
{
	/*
	 * Valid instructions are initialized to non-0.
	 * Invalid instructions are initialized to 0.
	 */
	static const u8 codes[] = {
		[BPF_ALU|BPF_ADD|BPF_K]  = BPF_S_ALU_ADD_K,
		[BPF_ALU|BPF_ADD|BPF_X]  = BPF_S_ALU_ADD_X,
		[BPF_ALU|BPF_SUB|BPF_K]  = BPF_S_ALU_SUB_K,
		[BPF_ALU|BPF_SUB|BPF_X]  = BPF_S_ALU_SUB_X,
		[BPF_ALU|BPF_MUL|BPF_K]  = BPF_S_ALU_MUL_K,
		[BPF_ALU|BPF_MUL|BPF_X]  = BPF_S_ALU_MUL_X,
		[BPF_ALU|BPF_DIV|BPF_X]  = BPF_S_ALU_DIV_X,
		[BPF_ALU|BPF_MOD|BPF_K]  = BPF_S_ALU_MOD_K,
		[BPF_ALU|BPF_MOD|BPF_X]  = BPF_S_ALU_MOD_X,
		[BPF_ALU|BPF_AND|BPF_K]  = BPF_S_ALU_AND_K,
		[BPF_ALU|BPF_AND|BPF_X]  = BPF_S_ALU_AND_X,
		[BPF_ALU|BPF_OR|BPF_K]   = BPF_S_ALU_OR_K,
		[BPF_ALU|BPF_OR|BPF_X]   = BPF_S_ALU_OR_X,
		[BPF_ALU|BPF_XOR|BPF_K]  = BPF_S_ALU_XOR_K,
		[BPF_ALU|BPF_XOR|BPF_X]  = BPF_S_ALU_XOR_X,
		[BPF_ALU|BPF_LSH|BPF_K]  = BPF_S_ALU_LSH_K,
		[BPF_ALU|BPF_LSH|BPF_X]  = BPF_S_ALU_LSH_X,
		[BPF_ALU|BPF_RSH|BPF_K]  = BPF_S_ALU_RSH_K,
		[BPF_ALU|BPF_RSH|BPF_X]  = BPF_S_ALU_RSH_X,
		[BPF_ALU|BPF_NEG]        = BPF_S_ALU_NEG,
		[BPF_LD|BPF_W|BPF_ABS]   = BPF_S_LD_W_ABS,
		[BPF_LD|BPF_H|BPF_ABS]   = BPF_S_LD_H_ABS,
		[BPF_LD|BPF_B|BPF_ABS]   = BPF_S_LD_B_ABS,
		[BPF_LD|BPF_W|BPF_LEN]   = BPF_S_LD_W_LEN,
		[BPF_LD|BPF_W|BPF_IND]   = BPF_S_LD_W_IND,
		[BPF_LD|BPF_H|BPF_IND]   = BPF_S_LD_H_IND,
		[BPF_LD|BPF_B|BPF_IND]   = BPF_S_LD_B_IND,
		[BPF_LD|BPF_IMM]         = BPF_S_LD_IMM,
		[BPF_LDX|BPF_W|BPF_LEN]  = BPF_S_LDX_W_LEN,
		[BPF_LDX|BPF_B|BPF_MSH]  = BPF_S_LDX_B_MSH,
		[BPF_LDX|BPF_IMM]        = BPF_S_LDX_IMM,
		[BPF_MISC|BPF_TAX]       = BPF_S_MISC_TAX,
		[BPF_MISC|BPF_TXA]       = BPF_S_MISC_TXA,
		[BPF_RET|BPF_K]          = BPF_S_RET_K,
		[BPF_RET|BPF_A]          = BPF_S_RET_A,
		[BPF_ALU|BPF_DIV|BPF_K]  = BPF_S_ALU_DIV_K,
		[BPF_LD|BPF_MEM]         = BPF_S_LD_MEM,
		[BPF_LDX|BPF_MEM]        = BPF_S_LDX_MEM,
		[BPF_ST]                 = BPF_S_ST,
		[BPF_STX]                = BPF_S_STX,
		[BPF_JMP|BPF_JA]         = BPF_S_JMP_JA,
		[BPF_JMP|BPF_JEQ|BPF_K]  = BPF_S_JMP_JEQ_K,
		[BPF_JMP|BPF_JEQ|BPF_X]  = BPF_S_JMP_JEQ_X,
		[BPF_JMP|BPF_JGE|BPF_K]  = BPF_S_JMP_JGE_K,
		[BPF_JMP|BPF_JGE|BPF_X]  = BPF_S_JMP_JGE_X,
		[BPF_JMP|BPF_JGT|BPF_K]  = BPF_S_JMP_JGT_K,
		[BPF_JMP|BPF_JGT|BPF_X]  = BPF_S_JMP_JGT_X,
		[BPF_JMP|BPF_JSET|BPF_K] = BPF_S_JMP_JSET_K,
		[BPF_JMP|BPF_JSET|BPF_X] = BPF_S_JMP_JSET_X,
	};
	int pc;
	bool anc_found;

	if (flen == 0 || flen > BPF_MAXINSNS)
		return -EINVAL;

	/* check the filter code now */
	for (pc = 0; pc < flen; pc++) {
		struct sock_filter *ftest = &filter[pc];
		u16 code = ftest->code;

		if (code >= ARRAY_SIZE(codes))
			return -EINVAL;
		code = codes[code];
		if (!code)
			return -EINVAL;
		/* Some instructions need special checks */
		switch (code) {
		case BPF_S_ALU_DIV_K:
		case BPF_S_ALU_MOD_K:
			/* check for division by zero */
			if (ftest->k == 0)
				return -EINVAL;
			break;
		case BPF_S_LD_MEM:
		case BPF_S_LDX_MEM:
		case BPF_S_ST:
		case BPF_S_STX:
			/* check for invalid memory addresses */
			if (ftest->k >= BPF_MEMWORDS)
				return -EINVAL;
			break;
		case BPF_S_JMP_JA:
			/*
			 * Note, the large ftest->k might cause loops.
			 * Compare this with conditional jumps below,
			 * where offsets are limited. --ANK (981016)
			 */
			if (ftest->k >= (unsigned int)(flen-pc-1))
				return -EINVAL;
			break;
		case BPF_S_JMP_JEQ_K:
		case BPF_S_JMP_JEQ_X:
		case BPF_S_JMP_JGE_K:
		case BPF_S_JMP_JGE_X:
		case BPF_S_JMP_JGT_K:
		case BPF_S_JMP_JGT_X:
		case BPF_S_JMP_JSET_X:
		case BPF_S_JMP_JSET_K:
			/* for conditionals both must be safe */
			if (pc + ftest->jt + 1 >= flen ||
			    pc + ftest->jf + 1 >= flen)
				return -EINVAL;
			break;
		case BPF_S_LD_W_ABS:
		case BPF_S_LD_H_ABS:
		case BPF_S_LD_B_ABS:
			anc_found = false;
#define ANCILLARY(CODE) case SKF_AD_OFF + SKF_AD_##CODE:	\
				code = BPF_S_ANC_##CODE;	\
				anc_found = true;		\
				break
			switch (ftest->k) {
			ANCILLARY(PROTOCOL);
			ANCILLARY(PKTTYPE);
			ANCILLARY(IFINDEX);
			ANCILLARY(NLATTR);
			ANCILLARY(NLATTR_NEST);
			ANCILLARY(MARK);
			ANCILLARY(QUEUE);
			ANCILLARY(HATYPE);
			ANCILLARY(RXHASH);
			ANCILLARY(CPU);
			ANCILLARY(ALU_XOR_X);
			ANCILLARY(VLAN_TAG);
			ANCILLARY(VLAN_TAG_PRESENT);
			ANCILLARY(PAY_OFFSET);
			}

			/* ancillary operation unknown or unsupported */
			if (anc_found == false && ftest->k >= SKF_AD_OFF)
				return -EINVAL;
		}
		ftest->code = code;
	}

	/* last instruction must be a RET code */
	switch (filter[flen - 1].code) {
	case BPF_S_RET_K:
	case BPF_S_RET_A:
		return check_load_and_stores(filter, flen);
	}
	return -EINVAL;
}


static bool parse_signature(struct MACH0_(obj_t) *bin, ut64 off) {
	int i,len;
	ut32 data;
	bin->signature = NULL;
	struct linkedit_data_command link = {0};
	ut8 lit[sizeof (struct linkedit_data_command)] = {0};
	struct blob_index_t idx = {0};
	struct super_blob_t super = {{0}};

	if (off > bin->size || off + sizeof (struct linkedit_data_command) > bin->size) {
		return false;
	}
	len = r_buf_read_at (bin->b, off, lit, sizeof (struct linkedit_data_command));
	if (len != sizeof (struct linkedit_data_command)) {
		bprintf ("Failed to get data while parsing LC_CODE_SIGNATURE command\n");
		return false;
	}
	link.cmd = r_read_ble32 (&lit[0], bin->big_endian);
	link.cmdsize = r_read_ble32 (&lit[4], bin->big_endian);
	link.dataoff = r_read_ble32 (&lit[8], bin->big_endian);
	link.datasize = r_read_ble32 (&lit[12], bin->big_endian);

	data = link.dataoff;
	if (data > bin->size || data + sizeof (struct super_blob_t) > bin->size) {
		bin->signature = (ut8 *)strdup ("Malformed entitlement");
		return true;
	}
	super.blob.magic = r_buf_read_ble32_at (bin->b, data, mach0_endian);
	super.blob.length = r_buf_read_ble32_at (bin->b, data + 4, mach0_endian);
	super.count = r_buf_read_ble32_at (bin->b, data + 8, mach0_endian);
	char *verbose = r_sys_getenv ("RABIN2_CODESIGN_VERBOSE");
	bool isVerbose = false;
	if (verbose) {
		isVerbose = *verbose;
		free (verbose);
	}
	// to dump all certificates
	// [0x00053f75]> b 5K;/x 30800609;wtf @@ hit*
	// then do this:
	// $ openssl asn1parse -inform der -in a|less
	// $ openssl pkcs7 -inform DER -print_certs -text -in a
	for (i = 0; i < super.count; i++) {
		if (data + i > bin->size) {
			bin->signature = (ut8 *)strdup ("Malformed entitlement");
			break;
		}
		struct blob_index_t bi;
		if (r_buf_read_at (bin->b, data + 12 + (i * sizeof (struct blob_index_t)),
			(ut8*)&bi, sizeof (struct blob_index_t)) < sizeof (struct blob_index_t)) {
			break;
		}
		idx.type = r_read_ble32 (&bi.type, mach0_endian);
		idx.offset = r_read_ble32 (&bi.offset, mach0_endian);
		switch (idx.type) {
		case CSSLOT_ENTITLEMENTS:
			if (true || isVerbose) {
				ut64 off = data + idx.offset;
				if (off > bin->size || off + sizeof (struct blob_t) > bin->size) {
					bin->signature = (ut8 *)strdup ("Malformed entitlement");
					break;
				}
				struct blob_t entitlements = {0};
				entitlements.magic = r_buf_read_ble32_at (bin->b, off, mach0_endian);
				entitlements.length = r_buf_read_ble32_at (bin->b, off + 4, mach0_endian);
				len = entitlements.length - sizeof (struct blob_t);
				if (len <= bin->size && len > 1) {
					bin->signature = calloc (1, len + 1);
					if (!bin->signature) {
						break;
					}
					if (off + sizeof (struct blob_t) + len < r_buf_size (bin->b)) {
						r_buf_read_at (bin->b, off + sizeof (struct blob_t), (ut8 *)bin->signature, len);
						if (len >= 0) {
							bin->signature[len] = '\0';
						}
					} else {
						bin->signature = (ut8 *)strdup ("Malformed entitlement");
					}
				} else {
					bin->signature = (ut8 *)strdup ("Malformed entitlement");
				}
			}
			break;
		case CSSLOT_CODEDIRECTORY:
			if (isVerbose) {
				parseCodeDirectory (bin->b, data + idx.offset, link.datasize);
			}
			break;
		case 0x1000:
			// unknown
			break;
		case CSSLOT_CMS_SIGNATURE: // ASN1/DER certificate
			if (isVerbose) {
				ut8 header[8] = {0};
				r_buf_read_at (bin->b, data + idx.offset, header, sizeof (header));
				ut32 length = R_MIN (UT16_MAX, r_read_ble32 (header + 4, 1));
				ut8 *p = calloc (length, 1);
				if (p) {
					r_buf_read_at (bin->b, data + idx.offset + 0, p, length);
					ut32 *words = (ut32*)p;
					eprintf ("Magic: %x\n", words[0]);
					eprintf ("wtf DUMP @%d!%d\n",
						(int)data + idx.offset + 8, (int)length);
					eprintf ("openssl pkcs7 -print_certs -text -inform der -in DUMP\n");
					eprintf ("openssl asn1parse -offset %d -length %d -inform der -in /bin/ls\n",
						(int)data + idx.offset + 8, (int)length);
					eprintf ("pFp@%d!%d\n",
						(int)data + idx.offset + 8, (int)length);
					free (p);
				}
			}
			break;
		case CSSLOT_REQUIREMENTS: // 2
			{
				ut8 p[256];
				r_buf_read_at (bin->b, data + idx.offset + 16, p, sizeof (p));
				p[sizeof (p) - 1] = 0;
				ut32 slot_size = r_read_ble32 (p + 8, 1);
				if (slot_size < sizeof (p)) {
					ut32 ident_size = r_read_ble32 (p + 8, 1);
					if (!ident_size || ident_size > sizeof (p) - 28) {
						break;
					}
					char *ident = r_str_ndup ((const char *)p + 28, ident_size);
					if (ident) {
						sdb_set (bin->kv, "mach0.ident", ident, 0);
						free (ident);
					}
				} else {
					if (bin->verbose) {
						eprintf ("Invalid code slot size\n");
					}
				}
			}
			break;
		case CSSLOT_INFOSLOT: // 1;
		case CSSLOT_RESOURCEDIR: // 3;
		case CSSLOT_APPLICATION: // 4;
			// TODO: parse those codesign slots
			if (bin->verbose) {
				eprintf ("TODO: Some codesign slots are not yet supported\n");
			}
			break;
		default:
			if (bin->verbose) {
				eprintf ("Unknown Code signature slot %d\n", idx.type);
			}
			break;
		}
	}
	if (!bin->signature) {
		bin->signature = (ut8 *)strdup ("No entitlement found");
	}
	return true;
}


findtags_match_tag(
    findtags_state_T	*st,
    tagptrs_T		*tagpp,
    findtags_match_args_T *margs)
{
    int		match = FALSE;
    int		cmplen;

    // First try matching with the pattern literally (also when it is
    // a regexp).
    cmplen = (int)(tagpp->tagname_end - tagpp->tagname);
    if (p_tl != 0 && cmplen > p_tl)	    // adjust for 'taglength'
	cmplen = p_tl;
    // if tag length does not match, don't try comparing
    if (st->orgpat->len != cmplen)
	match = FALSE;
    else
    {
	if (st->orgpat->regmatch.rm_ic)
	{
	    match =
		(MB_STRNICMP(tagpp->tagname, st->orgpat->pat, cmplen) == 0);
	    if (match)
		margs->match_no_ic =
		    (STRNCMP(tagpp->tagname, st->orgpat->pat, cmplen) == 0);
	}
	else
	    match = (STRNCMP(tagpp->tagname, st->orgpat->pat, cmplen) == 0);
    }

    // Has a regexp: Also find tags matching regexp.
    margs->match_re = FALSE;
    if (!match && st->orgpat->regmatch.regprog != NULL)
    {
	int	cc;

	cc = *tagpp->tagname_end;
	*tagpp->tagname_end = NUL;
	match = vim_regexec(&st->orgpat->regmatch, tagpp->tagname, (colnr_T)0);
	if (match)
	{
	    margs->matchoff = (int)(st->orgpat->regmatch.startp[0] -
							tagpp->tagname);
	    if (st->orgpat->regmatch.rm_ic)
	    {
		st->orgpat->regmatch.rm_ic = FALSE;
		margs->match_no_ic = vim_regexec(&st->orgpat->regmatch,
			tagpp->tagname, (colnr_T)0);
		st->orgpat->regmatch.rm_ic = TRUE;
	    }
	}
	*tagpp->tagname_end = cc;
	margs->match_re = TRUE;
    }

    return match ? TAG_MATCH_SUCCESS : TAG_MATCH_FAIL;
}


struct nft_set *nf_tables_set_lookup(const struct nft_table *table,
				     const struct nlattr *nla)
{
	struct nft_set *set;

	if (nla == NULL)
		return ERR_PTR(-EINVAL);

	list_for_each_entry(set, &table->sets, list) {
		if (!nla_strcmp(nla, set->name))
			return set;
	}
	return ERR_PTR(-ENOENT);
}


yang_read_extcomplex_str(struct lys_module *module, struct lys_ext_instance_complex *ext, const char *arg_name,
                         const char *parent_name, char *value, int parent_stmt, LY_STMT stmt)
{
    int c;
    const char **str, ***p = NULL;
    void *reallocated;
    struct lyext_substmt *info;

    c = 0;
    if (stmt == LY_STMT_PREFIX && parent_stmt == LY_STMT_BELONGSTO) {
        /* str contains no NULL value */
        str = lys_ext_complex_get_substmt(LY_STMT_BELONGSTO, ext, &info);
        if (info->cardinality < LY_STMT_CARD_SOME) {
            str++;
        } else {
           /* get the index in the array to add new item */
            p = (const char ***)str;
            for (c = 0; p[0][c + 1]; c++);
            str = p[1];
        }
        str[c] = lydict_insert_zc(module->ctx, value);
    }  else {
        str = lys_ext_complex_get_substmt(stmt, ext, &info);
        if (!str) {
            LOGVAL(module->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, arg_name, parent_name);
            goto error;
        }
        if (info->cardinality < LY_STMT_CARD_SOME && *str) {
            LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, arg_name, parent_name);
            goto error;
        }

        if (info->cardinality >= LY_STMT_CARD_SOME) {
            /* there can be multiple instances, str is actually const char *** */
            p = (const char ***)str;
            if (!p[0]) {
                /* allocate initial array */
                p[0] = calloc(2, sizeof(const char *));
                LY_CHECK_ERR_GOTO(!p[0], LOGMEM(module->ctx), error);
                if (stmt == LY_STMT_BELONGSTO) {
                    /* allocate another array for the belongs-to's prefixes */
                    p[1] = calloc(2, sizeof(const char *));
                    LY_CHECK_ERR_GOTO(!p[1], LOGMEM(module->ctx), error);
                } else if (stmt == LY_STMT_ARGUMENT) {
                    /* allocate another array for the yin element */
                    ((uint8_t **)p)[1] = calloc(2, sizeof(uint8_t));
                    LY_CHECK_ERR_GOTO(!p[1], LOGMEM(module->ctx), error);
                    /* default value of yin element */
                    ((uint8_t *)p[1])[0] = 2;
                }
            } else {
                /* get the index in the array to add new item */
                for (c = 0; p[0][c]; c++);
            }
            str = p[0];
        }

        str[c] = lydict_insert_zc(module->ctx, value);
        value = NULL;

        if (c) {
            /* enlarge the array(s) */
            reallocated = realloc(p[0], (c + 2) * sizeof(const char *));
            if (!reallocated) {
                LOGMEM(module->ctx);
                lydict_remove(module->ctx, p[0][c]);
                p[0][c] = NULL;
                return EXIT_FAILURE;
            }
            p[0] = reallocated;
            p[0][c + 1] = NULL;

            if (stmt == LY_STMT_BELONGSTO) {
                /* enlarge the second belongs-to's array with prefixes */
                reallocated = realloc(p[1], (c + 2) * sizeof(const char *));
                if (!reallocated) {
                    LOGMEM(module->ctx);
                    lydict_remove(module->ctx, p[1][c]);
                    p[1][c] = NULL;
                    return EXIT_FAILURE;
                }
                p[1] = reallocated;
                p[1][c + 1] = NULL;
            } else if (stmt == LY_STMT_ARGUMENT) {
                /* enlarge the second argument's array with yin element */
                reallocated = realloc(p[1], (c + 2) * sizeof(uint8_t));
                if (!reallocated) {
                    LOGMEM(module->ctx);
                    ((uint8_t *)p[1])[c] = 0;
                    return EXIT_FAILURE;
                }
                p[1] = reallocated;
                ((uint8_t *)p[1])[c + 1] = 0;
            }
        }
    }

    return EXIT_SUCCESS;

error:
    free(value);
    return EXIT_FAILURE;
}


ChromeContentBrowserClient::GetOriginPolicyErrorPage(
    content::OriginPolicyErrorReason error_reason,
    const url::Origin& origin,
    const GURL& url) {
  return security_interstitials::OriginPolicyUI::GetErrorPage(error_reason,
                                                              origin, url);
}


gotchars(char_u *chars, int len)
{
    char_u		*s = chars;
    int			i;
    static char_u	buf[4];
    static int		buflen = 0;
    int			todo = len;

    while (todo--)
    {
	buf[buflen++] = *s++;

	// When receiving a special key sequence, store it until we have all
	// the bytes and we can decide what to do with it.
	if (buflen == 1 && buf[0] == K_SPECIAL)
	    continue;
	if (buflen == 2)
	    continue;
	if (buflen == 3 && buf[1] == KS_EXTRA
		       && (buf[2] == KE_FOCUSGAINED || buf[2] == KE_FOCUSLOST))
	{
	    // Drop K_FOCUSGAINED and K_FOCUSLOST, they are not useful in a
	    // recording.
	    buflen = 0;
	    continue;
	}

	// Handle one byte at a time; no translation to be done.
	for (i = 0; i < buflen; ++i)
	    updatescript(buf[i]);

	if (reg_recording != 0)
	{
	    buf[buflen] = NUL;
	    add_buff(&recordbuff, buf, (long)buflen);
	    // remember how many chars were last recorded
	    last_recorded_len += buflen;
	}
	buflen = 0;
    }
    may_sync_undo();

#ifdef FEAT_EVAL
    // output "debug mode" message next time in debug mode
    debug_did_msg = FALSE;
#endif

    // Since characters have been typed, consider the following to be in
    // another mapping.  Search string will be kept in history.
    ++maptick;
}


e1000_receive(VLANClientState *nc, const uint8_t *buf, size_t size)

{

    E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;

    struct e1000_rx_desc desc;

    target_phys_addr_t base;

    unsigned int n, rdt;

    uint32_t rdh_start;

    uint16_t vlan_special = 0;

    uint8_t vlan_status = 0, vlan_offset = 0;

    if (!(s->mac_reg[RCTL] & E1000_RCTL_EN))

        return -1;

    if (size > s->rxbuf_size) {

        DBGOUT(RX, "packet too large for buffers (%lu > %d)\n",

               (unsigned long)size, s->rxbuf_size);

        return -1;

    }

    if (!receive_filter(s, buf, size))

        return size;

    if (vlan_enabled(s) && is_vlan_packet(s, buf)) {

        vlan_special = cpu_to_le16(be16_to_cpup((uint16_t *)(buf + 14)));

        memmove((uint8_t *)buf + 4, buf, 12);

        vlan_status = E1000_RXD_STAT_VP;

        vlan_offset = 4;

        size -= 4;

    }

    rdh_start = s->mac_reg[RDH];

    size += 4; // for the header

    do {

        if (s->mac_reg[RDH] == s->mac_reg[RDT] && s->check_rxov) {

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

        base = ((uint64_t)s->mac_reg[RDBAH] << 32) + s->mac_reg[RDBAL] +

               sizeof(desc) * s->mac_reg[RDH];

        cpu_physical_memory_read(base, (void *)&desc, sizeof(desc));

        desc.special = vlan_special;

        desc.status |= (vlan_status | E1000_RXD_STAT_DD);

        if (desc.buffer_addr) {

            cpu_physical_memory_write(le64_to_cpu(desc.buffer_addr),

                                      (void *)(buf + vlan_offset), size);

            desc.length = cpu_to_le16(size);

            desc.status |= E1000_RXD_STAT_EOP|E1000_RXD_STAT_IXSM;

        } else // as per intel docs; skip descriptors with null buf addr

            DBGOUT(RX, "Null RX descriptor!!\n");

        cpu_physical_memory_write(base, (void *)&desc, sizeof(desc));

        if (++s->mac_reg[RDH] * sizeof(desc) >= s->mac_reg[RDLEN])

            s->mac_reg[RDH] = 0;

        s->check_rxov = 1;

        /* see comment in start_xmit; same here */

        if (s->mac_reg[RDH] == rdh_start) {

            DBGOUT(RXERR, "RDH wraparound @%x, RDT %x, RDLEN %x\n",

                   rdh_start, s->mac_reg[RDT], s->mac_reg[RDLEN]);

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

    } while (desc.buffer_addr == 0);

    s->mac_reg[GPRC]++;

    s->mac_reg[TPR]++;

    n = s->mac_reg[TORL];

    if ((s->mac_reg[TORL] += size) < n)

        s->mac_reg[TORH]++;

    n = E1000_ICS_RXT0;

    if ((rdt = s->mac_reg[RDT]) < s->mac_reg[RDH])

        rdt += s->mac_reg[RDLEN] / sizeof(desc);

    if (((rdt - s->mac_reg[RDH]) * sizeof(desc)) <= s->mac_reg[RDLEN] >>

        s->rxbuf_min_shift)

        n |= E1000_ICS_RXDMT0;

    set_ics(s, 0, n);

    return size;

}


void ExtensionViewGuest::CreateWebContents(
    const base::DictionaryValue& create_params,
    const WebContentsCreatedCallback& callback) {
  std::string extension_id;
  create_params.GetString(extensionview::kAttributeExtension, &extension_id);

  if (!crx_file::id_util::IdIsValid(extension_id) ||
      !IsExtensionIdWhitelisted(extension_id)) {
    callback.Run(nullptr);
    return;
  }

  extension_url_ =
      extensions::Extension::GetBaseURLFromExtensionId(extension_id);

  if (!extension_url_.is_valid()) {
    callback.Run(nullptr);
    return;
  }

  content::SiteInstance* view_site_instance =
      content::SiteInstance::CreateForURL(browser_context(),
                                          extension_url_);

  WebContents::CreateParams params(browser_context(), view_site_instance);
  params.guest_delegate = this;
  callback.Run(WebContents::Create(params));
}


static void nfs_readdir_page_init_array(struct page *page, u64 last_cookie)
{
	struct nfs_cache_array *array;

	array = kmap_atomic(page);
	nfs_readdir_array_init(array);
	array->last_cookie = last_cookie;
	array->cookies_are_ordered = 1;
	kunmap_atomic(array);
}


set_vim_var_char(int c)
{
    char_u	buf[MB_MAXBYTES + 1];

    if (has_mbyte)
	buf[(*mb_char2bytes)(c, buf)] = NUL;
    else
    {
	buf[0] = c;
	buf[1] = NUL;
    }
    set_vim_var_string(VV_CHAR, buf, -1);
}


static int cifs_ci_compare(const struct dentry *parent,
		const struct inode *pinode,
		const struct dentry *dentry, const struct inode *inode,
		unsigned int len, const char *str, const struct qstr *name)
{
	struct nls_table *codepage = CIFS_SB(pinode->i_sb)->local_nls;

	if ((name->len == len) &&
	    (nls_strnicmp(codepage, name->name, str, len) == 0))
		return 0;
	return 1;
}


int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
		       struct sctp_info *info)
{
	struct sctp_transport *prim;
	struct list_head *pos;
	int mask;

	memset(info, 0, sizeof(*info));
	if (!asoc) {
		struct sctp_sock *sp = sctp_sk(sk);

		info->sctpi_s_autoclose = sp->autoclose;
		info->sctpi_s_adaptation_ind = sp->adaptation_ind;
		info->sctpi_s_pd_point = sp->pd_point;
		info->sctpi_s_nodelay = sp->nodelay;
		info->sctpi_s_disable_fragments = sp->disable_fragments;
		info->sctpi_s_v4mapped = sp->v4mapped;
		info->sctpi_s_frag_interleave = sp->frag_interleave;
		info->sctpi_s_type = sp->type;

		return 0;
	}

	info->sctpi_tag = asoc->c.my_vtag;
	info->sctpi_state = asoc->state;
	info->sctpi_rwnd = asoc->a_rwnd;
	info->sctpi_unackdata = asoc->unack_data;
	info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
	info->sctpi_instrms = asoc->c.sinit_max_instreams;
	info->sctpi_outstrms = asoc->c.sinit_num_ostreams;
	list_for_each(pos, &asoc->base.inqueue.in_chunk_list)
		info->sctpi_inqueue++;
	list_for_each(pos, &asoc->outqueue.out_chunk_list)
		info->sctpi_outqueue++;
	info->sctpi_overall_error = asoc->overall_error_count;
	info->sctpi_max_burst = asoc->max_burst;
	info->sctpi_maxseg = asoc->frag_point;
	info->sctpi_peer_rwnd = asoc->peer.rwnd;
	info->sctpi_peer_tag = asoc->c.peer_vtag;

	mask = asoc->peer.ecn_capable << 1;
	mask = (mask | asoc->peer.ipv4_address) << 1;
	mask = (mask | asoc->peer.ipv6_address) << 1;
	mask = (mask | asoc->peer.hostname_address) << 1;
	mask = (mask | asoc->peer.asconf_capable) << 1;
	mask = (mask | asoc->peer.prsctp_capable) << 1;
	mask = (mask | asoc->peer.auth_capable);
	info->sctpi_peer_capable = mask;
	mask = asoc->peer.sack_needed << 1;
	mask = (mask | asoc->peer.sack_generation) << 1;
	mask = (mask | asoc->peer.zero_window_announced);
	info->sctpi_peer_sack = mask;

	info->sctpi_isacks = asoc->stats.isacks;
	info->sctpi_osacks = asoc->stats.osacks;
	info->sctpi_opackets = asoc->stats.opackets;
	info->sctpi_ipackets = asoc->stats.ipackets;
	info->sctpi_rtxchunks = asoc->stats.rtxchunks;
	info->sctpi_outofseqtsns = asoc->stats.outofseqtsns;
	info->sctpi_idupchunks = asoc->stats.idupchunks;
	info->sctpi_gapcnt = asoc->stats.gapcnt;
	info->sctpi_ouodchunks = asoc->stats.ouodchunks;
	info->sctpi_iuodchunks = asoc->stats.iuodchunks;
	info->sctpi_oodchunks = asoc->stats.oodchunks;
	info->sctpi_iodchunks = asoc->stats.iodchunks;
	info->sctpi_octrlchunks = asoc->stats.octrlchunks;
	info->sctpi_ictrlchunks = asoc->stats.ictrlchunks;

	prim = asoc->peer.primary_path;
	memcpy(&info->sctpi_p_address, &prim->ipaddr,
	       sizeof(struct sockaddr_storage));
	info->sctpi_p_state = prim->state;
	info->sctpi_p_cwnd = prim->cwnd;
	info->sctpi_p_srtt = prim->srtt;
	info->sctpi_p_rto = jiffies_to_msecs(prim->rto);
	info->sctpi_p_hbinterval = prim->hbinterval;
	info->sctpi_p_pathmaxrxt = prim->pathmaxrxt;
	info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay);
	info->sctpi_p_ssthresh = prim->ssthresh;
	info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked;
	info->sctpi_p_flight_size = prim->flight_size;
	info->sctpi_p_error = prim->error_count;

	return 0;
}


static int hasharray(i_ctx_t * i_ctx_p, ref *m1, gs_md5_state_t *md5)
{
    int i, code;
    ref ref1;

    for (i=0;i < r_size(m1);i++) {
        code = array_get(imemory, m1, i, &ref1);
        if (code < 0)
            return 0;

        code = r_type(&ref1);
        if (code < 0)
            return code;
        switch(r_type(&ref1)) {
            case t_null:
                break;
            case t_boolean:
                gs_md5_append(md5, (const gs_md5_byte_t *)&ref1.value.boolval, sizeof(ref1.value.boolval));
                break;
            case t_integer:
                gs_md5_append(md5, (const gs_md5_byte_t *)&ref1.value.intval, sizeof(ref1.value.intval));
                break;
            case t_real:
                gs_md5_append(md5, (const gs_md5_byte_t *)&ref1.value.realval, sizeof(ref1.value.realval));
                break;
            case t_name:
                gs_md5_append(md5, (const gs_md5_byte_t *)&ref1.value.pname, sizeof(ref1.value.pname));
                break;
            case t_string:
                gs_md5_append(md5, (const gs_md5_byte_t *)ref1.value.const_bytes, r_size(&ref1));
                break;
            case t_array:
            case t_mixedarray:
            case t_shortarray:
                if (!hasharray(i_ctx_p, &ref1, md5))
                    return 0;
                break;
            case t_oparray:
                break;
            case t_operator:
                gs_md5_append(md5, (const gs_md5_byte_t *)&ref1.value.opproc, sizeof(ref1.value.opproc));
                break;
            case t__invalid:
            case t_dictionary:
            case t_file:
            case t_unused_array_:
            case t_struct:
            case t_astruct:
            case t_fontID:
            case t_save:
            case t_mark:
            case t_device:
                return 0;
            default:
                /* Some high frequency operators are defined starting at t_next_index
                 * I think as long as the 'type' of each is the same, we are OK
                 */
                break;
        }
    }
    return 1;
}


TEST_F(EncryptedRecordTest, TestWriteSplittingCombineSmall) {
  TLSMessage msg{ContentType::application_data, IOBuf::create(500)};
  msg.fragment->append(500);
  memset(msg.fragment->writableData(), 0x1, msg.fragment->length());
  msg.fragment->prependChain(IOBuf::copyBuffer("moredata"));

  Sequence s;
  EXPECT_CALL(*writeAead_, _encrypt(_, _, _))
      .Times(1)
      .WillRepeatedly(
          Invoke([](std::unique_ptr<IOBuf>& /*buf*/, const IOBuf*, uint64_t) {
            return getBuf("aaaa");
          }));
  write_.write(std::move(msg));
}


static int mp3_header_decompress(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args,

                     uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size, int keyframe){

    uint32_t header;

    int sample_rate= avctx->sample_rate;

    int sample_rate_index=0;

    int lsf, mpeg25, bitrate_index, frame_size;

    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];

    if(ff_mpa_check_header(header) >= 0){

        *poutbuf= (uint8_t *) buf;

        *poutbuf_size= buf_size;

        return 0;

    }

    header= 0xFFE00000 | ((4-3)<<17) | (1<<16); //FIXME simplify

    lsf     = sample_rate < (24000+32000)/2;

    mpeg25  = sample_rate < (12000+16000)/2;

    header |= (!mpeg25)<<20;

    header |= (!lsf   )<<19;

    if(sample_rate<<(lsf+mpeg25) < (44100+32000)/2)

        sample_rate_index |= 2;

    else if(sample_rate<<(lsf+mpeg25) > (44100+48000)/2)

        sample_rate_index |= 1;

    header |= sample_rate_index<<10;

    sample_rate= mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25); //in case sample rate is a little off

    for(bitrate_index=2; bitrate_index<30; bitrate_index++){

        frame_size = mpa_bitrate_tab[lsf][2][bitrate_index>>1];

        frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);

        if(frame_size == buf_size + 4)

            break;

    }

    if(bitrate_index == 30){

        av_log(avctx, AV_LOG_ERROR, "couldnt find bitrate_index\n");

        return -1;

    }

    header |= (bitrate_index&1)<<9;

    header |= (bitrate_index>>1)<<12;

    header |= (avctx->channels==1 ? MPA_MONO : MPA_JSTEREO)<<6;

    *poutbuf_size= buf_size + 4;

    *poutbuf= av_malloc(buf_size + 4 + FF_INPUT_BUFFER_PADDING_SIZE);

    memcpy(*poutbuf + 4, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if(avctx->channels==2){

        if(lsf){

            FFSWAP(int, (*poutbuf)[5], (*poutbuf)[6]);

            header |= ((*poutbuf)[5] & 0xC0)>>2;

        }else{

            header |= (*poutbuf)[5] & 0x30;

        }

    }

    (*poutbuf)[0]= header>>24;

    (*poutbuf)[1]= header>>16;

    (*poutbuf)[2]= header>> 8;

    (*poutbuf)[3]= header    ;

    return 1;

}


void MenuGtk::BuildMenuFromDelegate() {
  for (int i = 1; i <= delegate_->GetItemCount(); ++i) {
    GtkWidget* menu_item = NULL;

    if (delegate_->IsItemSeparator(i)) {
      menu_item = gtk_separator_menu_item_new();
    } else if (delegate_->HasIcon(i)) {
      const SkBitmap* icon = delegate_->GetIcon(i);
      menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon);
    } else {
      menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str());
    }

    AppendMenuItem(i, menu_item);
  }
}


static inline void gen_op_mov_v_reg(int ot, TCGv t0, int reg)

{

    switch(ot) {

    case OT_BYTE:

        if (reg < 4 X86_64_DEF( || reg >= 8 || x86_64_hregs)) {

            goto std_case;

        } else {

            tcg_gen_shri_tl(t0, cpu_regs[reg - 4], 8);

            tcg_gen_ext8u_tl(t0, t0);

        }

        break;

    default:

    std_case:

        tcg_gen_mov_tl(t0, cpu_regs[reg]);

        break;

    }

}


void decodeTrailers(RequestTrailerMap& trailers) { decodeTrailers(nullptr, trailers); }


void usb_serial_console_disconnect(struct usb_serial *serial)
{
	if (serial->port[0] && serial->port[0] == usbcons_info.port) {
		usb_serial_console_exit();
		usb_serial_put(serial);
	}
}


size_t Frame::getName(char *result_buf, size_t result_len) {
  if (result_len <= 1) {
    return 0; // Insufficient result_bug. Bail!
  }

  // Add '@recurse_level' if required
  // NOTE: Dont use snprintf's return val as it is compiler dependent
  if (m_recursion) {
    snprintf(result_buf, result_len, "%s@%d", m_name, m_recursion);
  } else {
    snprintf(result_buf, result_len, "%s", m_name);
  }

  // Force null-termination at MAX
  result_buf[result_len - 1] = 0;
  return strlen(result_buf);
}


static NPError NPN_SetValueForURL(NPP instance, NPNURLVariable variable, const char* url, const char* value, uint32_t len)
{
    notImplemented();
    return NPERR_GENERIC_ERROR;
}


static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended)
{
	zval *IM, *EXT = NULL;
	gdImagePtr im=NULL;
	long col = -1, x = -1, y = -1;
	int str_len, fontname_len, i, brect[8];
	double ptsize, angle;
	char *str = NULL, *fontname = NULL;
	char *error = NULL;
	int argc = ZEND_NUM_ARGS();
	gdFTStringExtra strex = {0};

	if (mode == TTFTEXT_BBOX) {
		if (argc < 4 || argc > ((extended) ? 5 : 4)) {
			ZEND_WRONG_PARAM_COUNT();
		} else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
			RETURN_FALSE;
		}
	} else {
		if (argc < 8 || argc > ((extended) ? 9 : 8)) {
			ZEND_WRONG_PARAM_COUNT();
		} else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
			RETURN_FALSE;
		}
		ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
	}

	/* convert angle to radians */
	angle = angle * (M_PI/180);

	if (extended && EXT) {	/* parse extended info */
		HashPosition pos;

		/* walk the assoc array */
		zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos);
		do {
			zval ** item;
			char * key;
			ulong num_key;

			if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) {
				continue;
			}

			if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) {
				continue;
			}

			if (strcmp("linespacing", key) == 0) {
				convert_to_double_ex(item);
				strex.flags |= gdFTEX_LINESPACE;
				strex.linespacing = Z_DVAL_PP(item);
			}

		} while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS);
	}

#ifdef VIRTUAL_DIR
	{
		char tmp_font_path[MAXPATHLEN];

		if (!VCWD_REALPATH(fontname, tmp_font_path)) {
			fontname = NULL;
		}
	}
 #endif /* VIRTUAL_DIR */

 	PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename");

 #ifdef HAVE_GD_FREETYPE
 	if (extended) {
 		error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex);
	}
	else
		error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str);

#endif /* HAVE_GD_FREETYPE */

	if (error) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error);
		RETURN_FALSE;
	}

	array_init(return_value);

	/* return array with the text's bounding box */
	for (i = 0; i < 8; i++) {
		add_next_index_long(return_value, brect[i]);
	}
}


static int __from_ib_access_flags(int iflags)
{
	int qflags = 0;

	if (iflags & IB_ACCESS_LOCAL_WRITE)
		qflags |= BNXT_QPLIB_ACCESS_LOCAL_WRITE;
	if (iflags & IB_ACCESS_REMOTE_READ)
		qflags |= BNXT_QPLIB_ACCESS_REMOTE_READ;
	if (iflags & IB_ACCESS_REMOTE_WRITE)
		qflags |= BNXT_QPLIB_ACCESS_REMOTE_WRITE;
	if (iflags & IB_ACCESS_REMOTE_ATOMIC)
		qflags |= BNXT_QPLIB_ACCESS_REMOTE_ATOMIC;
	if (iflags & IB_ACCESS_MW_BIND)
		qflags |= BNXT_QPLIB_ACCESS_MW_BIND;
	if (iflags & IB_ZERO_BASED)
		qflags |= BNXT_QPLIB_ACCESS_ZERO_BASED;
	if (iflags & IB_ACCESS_ON_DEMAND)
		qflags |= BNXT_QPLIB_ACCESS_ON_DEMAND;
	return qflags;
};


void RenderFrameImpl::OnReload(bool bypass_cache) {
  frame_->StartReload(bypass_cache ? WebFrameLoadType::kReloadBypassingCache
                                   : WebFrameLoadType::kReload);
}


void FVDrawInfo(FontView *fv,GWindow pixmap, GEvent *event) {
    GRect old, r;
    Color bg = GDrawGetDefaultBackground(GDrawGetDisplayOfWindow(pixmap));
    Color fg = fvglyphinfocol;
    SplineChar *sc, dummy;
    SplineFont *sf = fv->b.sf;
    EncMap *map = fv->b.map;
    int gid, uni, localenc;
    GString *output = g_string_new( "" );
    gchar *uniname = NULL;

    if ( event->u.expose.rect.y+event->u.expose.rect.height<=fv->mbh ) {
        g_string_free( output, TRUE ); output = NULL;
	return;
    }

    GDrawSetFont(pixmap,fv->fontset[0]);
    GDrawPushClip(pixmap,&event->u.expose.rect,&old);

    r.x = 0; r.width = fv->width; r.y = fv->mbh; r.height = fv->infoh;
    GDrawFillRect(pixmap,&r,bg);
    if ( fv->end_pos>=map->enccount || fv->pressed_pos>=map->enccount ||
	    fv->end_pos<0 || fv->pressed_pos<0 )
	fv->end_pos = fv->pressed_pos = -1;	/* Can happen after reencoding */
    if ( fv->end_pos == -1 ) {
        g_string_free( output, TRUE ); output = NULL;
	GDrawPopClip(pixmap,&old);
	return;
    }

    localenc = fv->end_pos;
    if ( map->remap!=NULL ) {
	struct remap *remap = map->remap;
	while ( remap->infont!=-1 ) {
	    if ( localenc>=remap->infont && localenc<=remap->infont+(remap->lastenc-remap->firstenc) ) {
		localenc += remap->firstenc-remap->infont;
		break;
	    }
	    ++remap;
	}
    }
    g_string_printf( output, "%d (0x%x) ", localenc, localenc );

    sc = (gid=fv->b.map->map[fv->end_pos])!=-1 ? sf->glyphs[gid] : NULL;
    if ( fv->b.cidmaster==NULL || fv->b.normal==NULL || sc==NULL )
	SCBuildDummy(&dummy,sf,fv->b.map,fv->end_pos);
    else
	dummy = *sc;
    if ( sc==NULL ) sc = &dummy;
    uni = dummy.unicodeenc!=-1 ? dummy.unicodeenc : sc->unicodeenc;

    /* last resort at guessing unicode code point from partial name */
    if ( uni == -1 ) {
	char *pt = strchr( sc->name, '.' );
	if( pt != NULL ) {
	    gchar *buf = g_strndup( (const gchar *) sc->name, pt - sc->name );
	    uni = UniFromName( (char *) buf, fv->b.sf->uni_interp, map->enc );
	    g_free( buf );
	}
    }

    if ( uni != -1 )
	g_string_append_printf( output, "U+%04X", uni );
    else {
	output = g_string_append( output, "U+????" );
    }

    /* postscript name */
    g_string_append_printf( output, " \"%s\" ", sc->name );

    /* code point name or range name */
    if( uni != -1 ) {
	uniname = (gchar *) unicode_name( uni );
	if ( uniname == NULL ) {
	    uniname = g_strdup( UnicodeRange( uni ) );
	}
    }

    if ( uniname != NULL ) {
	output = g_string_append( output, uniname );
	g_free( uniname );
    }

    GDrawDrawText8( pixmap, 10, fv->mbh+fv->lab_as, output->str, -1, fg );
    g_string_free( output, TRUE ); output = NULL;
    GDrawPopClip( pixmap, &old );
    return;
}


void Document::NodeChildrenWillBeRemoved(ContainerNode& container) {
  EventDispatchForbiddenScope assert_no_event_dispatch;
  for (Range* range : ranges_) {
    range->NodeChildrenWillBeRemoved(container);
    if (range == sequential_focus_navigation_starting_point_)
      range->FixupRemovedChildrenAcrossShadowBoundary(container);
  }

  for (NodeIterator* ni : node_iterators_) {
    for (Node& n : NodeTraversal::ChildrenOf(container))
      ni->NodeWillBeRemoved(n);
  }

  NotifyNodeChildrenWillBeRemoved(container);

  if (ContainsV1ShadowTree()) {
    for (Node& n : NodeTraversal::ChildrenOf(container))
      n.CheckSlotChangeBeforeRemoved();
  }
}


void WebContext::setProduct(const QString& product) {
  if (IsInitialized()) {
    UserAgentSettings::Get(context_.get())->SetProduct(
        product.toStdString());
  } else {
    construct_props_->product = product.toStdString();
  }
}


static int jsi_FSTruncateProc(Jsi_Channel chan, unsigned int len) { return ftruncate(fileno(_JSI_GETFP(chan,1)), len);}


BrowserCommandController::BrowserCommandController(Browser* browser)
    : browser_(browser),
      command_updater_(nullptr) {
  browser_->tab_strip_model()->AddObserver(this);
  PrefService* local_state = g_browser_process->local_state();
  if (local_state) {
    local_pref_registrar_.Init(local_state);
    local_pref_registrar_.Add(
        prefs::kAllowFileSelectionDialogs,
        base::Bind(
            &BrowserCommandController::UpdateCommandsForFileSelectionDialogs,
            base::Unretained(this)));
  }

  profile_pref_registrar_.Init(profile()->GetPrefs());
  profile_pref_registrar_.Add(
      prefs::kDevToolsAvailability,
      base::Bind(&BrowserCommandController::UpdateCommandsForDevTools,
                 base::Unretained(this)));
  profile_pref_registrar_.Add(
      bookmarks::prefs::kEditBookmarksEnabled,
      base::Bind(&BrowserCommandController::UpdateCommandsForBookmarkEditing,
                 base::Unretained(this)));
  profile_pref_registrar_.Add(
      bookmarks::prefs::kShowBookmarkBar,
      base::Bind(&BrowserCommandController::UpdateCommandsForBookmarkBar,
                 base::Unretained(this)));
  profile_pref_registrar_.Add(
      prefs::kIncognitoModeAvailability,
      base::Bind(
          &BrowserCommandController::UpdateCommandsForIncognitoAvailability,
          base::Unretained(this)));
  profile_pref_registrar_.Add(
      prefs::kPrintingEnabled,
      base::Bind(&BrowserCommandController::UpdatePrintingState,
                 base::Unretained(this)));
#if !defined(OS_MACOSX)
  profile_pref_registrar_.Add(
      prefs::kFullscreenAllowed,
      base::Bind(&BrowserCommandController::UpdateCommandsForFullscreenMode,
                 base::Unretained(this)));
#endif
  pref_signin_allowed_.Init(
      prefs::kSigninAllowed,
      profile()->GetOriginalProfile()->GetPrefs(),
      base::Bind(&BrowserCommandController::OnSigninAllowedPrefChange,
                 base::Unretained(this)));

  InitCommandState();

  sessions::TabRestoreService* tab_restore_service =
      TabRestoreServiceFactory::GetForProfile(profile());
  if (tab_restore_service) {
    tab_restore_service->AddObserver(this);
    TabRestoreServiceChanged(tab_restore_service);
  }
}


static unsigned int read_partition_size(VP8D_COMP *pbi,
 const unsigned char *cx_size)
{
 unsigned char temp[3];
 if (pbi->decrypt_cb)
 {
        pbi->decrypt_cb(pbi->decrypt_state, cx_size, temp, 3);
        cx_size = temp;
 }
 return cx_size[0] + (cx_size[1] << 8) + (cx_size[2] << 16);
}


const OriginAccessEntry& Document::accessEntryFromURL()
{
    if (!m_accessEntryFromURL) {
        m_accessEntryFromURL = adoptPtr(new OriginAccessEntry(url().protocol(), url().host(), OriginAccessEntry::AllowRegisterableDomains));
    }
    return *m_accessEntryFromURL;
}


scanner_scan_primary_expression (parser_context_t *context_p, /**< context */
                                 scanner_context_t *scanner_context_p, /* scanner context */
                                 lexer_token_type_t type, /**< current token type */
                                 scan_stack_modes_t stack_top) /**< current stack top */
{
  switch (type)
  {
    case LEXER_KEYW_NEW:
    {
      scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW;

#if ENABLED (JERRY_ES2015)
      if (scanner_try_scan_new_target (context_p))
      {
        scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
      }
#endif /* ENABLED (JERRY_ES2015) */
      break;
    }
    case LEXER_DIVIDE:
    case LEXER_ASSIGN_DIVIDE:
    {
      lexer_construct_regexp_object (context_p, true);
      scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
      break;
    }
    case LEXER_KEYW_FUNCTION:
    {
      uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;

#if ENABLED (JERRY_ES2015)
      if (scanner_context_p->async_source_p != NULL)
      {
        status_flags |= SCANNER_LITERAL_POOL_ASYNC;
      }

      if (lexer_consume_generator (context_p))
      {
        status_flags |= SCANNER_LITERAL_POOL_GENERATOR;
      }
#endif /* ENABLED (JERRY_ES2015) */

      scanner_push_literal_pool (context_p, scanner_context_p, status_flags);

      lexer_next_token (context_p);

      if (context_p->token.type == LEXER_LITERAL
          && context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
      {
        lexer_next_token (context_p);
      }

      parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_EXPRESSION);
      scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
      return SCAN_KEEP_TOKEN;
    }
    case LEXER_LEFT_PAREN:
    {
      scanner_scan_bracket (context_p, scanner_context_p);
      return SCAN_KEEP_TOKEN;
    }
    case LEXER_LEFT_SQUARE:
    {
#if ENABLED (JERRY_ES2015)
      scanner_push_destructuring_pattern (context_p, scanner_context_p, SCANNER_BINDING_NONE, false);
#endif /* ENABLED (JERRY_ES2015) */

      parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);
      scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
      break;
    }
    case LEXER_LEFT_BRACE:
    {
#if ENABLED (JERRY_ES2015)
      scanner_push_destructuring_pattern (context_p, scanner_context_p, SCANNER_BINDING_NONE, false);
#endif /* ENABLED (JERRY_ES2015) */

      parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);
      scanner_context_p->mode = SCAN_MODE_PROPERTY_NAME;
      return SCAN_KEEP_TOKEN;
    }
#if ENABLED (JERRY_ES2015)
    case LEXER_TEMPLATE_LITERAL:
    {
      if (context_p->source_p[-1] != LIT_CHAR_GRAVE_ACCENT)
      {
        parser_stack_push_uint8 (context_p, SCAN_STACK_TEMPLATE_STRING);
        scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
        break;
      }

      /* The string is a normal string literal. */
      /* FALLTHRU */
    }
#endif /* ENABLED (JERRY_ES2015) */
    case LEXER_LITERAL:
    {
#if ENABLED (JERRY_ES2015)
      const uint8_t *source_p = context_p->source_p;

      if (context_p->token.lit_location.type == LEXER_IDENT_LITERAL
          && lexer_check_arrow (context_p))
      {
        scanner_scan_simple_arrow (context_p, scanner_context_p, source_p);
        return SCAN_KEEP_TOKEN;
      }
      else if (JERRY_UNLIKELY (lexer_token_is_async (context_p)))
      {
        scanner_context_p->async_source_p = source_p;
        scanner_check_async_function (context_p, scanner_context_p);
        return SCAN_KEEP_TOKEN;
      }
#endif /* ENABLED (JERRY_ES2015) */

      if (context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
      {
        scanner_add_reference (context_p, scanner_context_p);
      }
      /* FALLTHRU */
    }
    case LEXER_KEYW_THIS:
    case LEXER_KEYW_SUPER:
    case LEXER_LIT_TRUE:
    case LEXER_LIT_FALSE:
    case LEXER_LIT_NULL:
    {
      scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
      break;
    }
#if ENABLED (JERRY_ES2015)
    case LEXER_KEYW_CLASS:
    {
      scanner_push_class_declaration (context_p, scanner_context_p, SCAN_STACK_CLASS_EXPRESSION);

      if (context_p->token.type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
      {
        return SCAN_KEEP_TOKEN;
      }
      break;
    }
#endif /* ENABLED (JERRY_ES2015) */
    case LEXER_RIGHT_SQUARE:
    {
      if (stack_top != SCAN_STACK_ARRAY_LITERAL)
      {
        scanner_raise_error (context_p);
      }

      scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
      return SCAN_KEEP_TOKEN;
    }
#if ENABLED (JERRY_ES2015)
    case LEXER_THREE_DOTS:
    {
      /* Elision or spread arguments */
      if (stack_top != SCAN_STACK_PAREN_EXPRESSION && stack_top != SCAN_STACK_ARRAY_LITERAL)
      {
        scanner_raise_error (context_p);
      }
      scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
      break;
    }
#endif /* ENABLED (JERRY_ES2015) */
    case LEXER_COMMA:
    {
      if (stack_top != SCAN_STACK_ARRAY_LITERAL)
      {
        scanner_raise_error (context_p);
      }
      scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;

#if ENABLED (JERRY_ES2015)
      if (scanner_context_p->binding_type != SCANNER_BINDING_NONE)
      {
        scanner_context_p->mode = SCAN_MODE_BINDING;
      }
#endif /* ENABLED (JERRY_ES2015) */
      break;
    }
#if ENABLED (JERRY_ES2015)
    case LEXER_KEYW_YIELD:
    {
      lexer_next_token (context_p);

      if (lexer_check_yield_no_arg (context_p))
      {
        scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
      }

      if (context_p->token.type == LEXER_MULTIPLY)
      {
        return SCAN_NEXT_TOKEN;
      }
      return SCAN_KEEP_TOKEN;
    }
#endif /* ENABLED (JERRY_ES2015) */
    case LEXER_RIGHT_PAREN:
    {
      if (stack_top == SCAN_STACK_PAREN_EXPRESSION)
      {
        scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
        parser_stack_pop_uint8 (context_p);
        break;
      }
      /* FALLTHRU */
    }
    default:
    {
      scanner_raise_error (context_p);
    }
  }
  return SCAN_NEXT_TOKEN;
} /* scanner_scan_primary_expression */


views::View* PageInfoWindowView::GetExtraView() {
  if (!cert_id_)
    return NULL;
  scoped_refptr<net::X509Certificate> cert;
  CertStore::GetSharedInstance()->RetrieveCert(cert_id_, &cert);
  if (!cert.get() || !cert->os_cert_handle())
    return NULL;

  views::View* button_container = new views::View();
  views::GridLayout* layout = new views::GridLayout(button_container);
  button_container->SetLayoutManager(layout);

  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddPaddingColumn(0, kHorizontalPadding);
  column_set->AddColumn(views::GridLayout::LEADING,
                        views::GridLayout::LEADING, 0,
                        views::GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, 0);
  layout->AddView(new views::NativeButton(this,
      l10n_util::GetString(IDS_PAGEINFO_CERT_INFO_BUTTON)));

  return button_container;
}


  t42_parser_init( T42_Parser     parser,
                   FT_Stream      stream,
                   FT_Memory      memory,
                   PSAux_Service  psaux )
  {
    FT_Error  error = FT_Err_Ok;
    FT_Long   size;

    psaux->ps_parser_funcs->init( &parser->root, 0, 0, memory );

    parser->stream    = stream;
    parser->base_len  = 0;
    parser->base_dict = 0;
    parser->in_memory = 0;

    /*******************************************************************/
    /*                                                                 */
    /* Here a short summary of what is going on:                       */
    /*                                                                 */
    /*   When creating a new Type 42 parser, we try to locate and load */
    /*   the base dictionary, loading the whole font into memory.      */
    /*                                                                 */
    /*   When `loading' the base dictionary, we only set up pointers   */
    /*   in the case of a memory-based stream.  Otherwise, we allocate */
    /*   and load the base dictionary in it.                           */
    /*                                                                 */
    /*   parser->in_memory is set if we have a memory stream.          */
    /*                                                                 */

    if ( FT_STREAM_SEEK( 0L ) ||
         FT_FRAME_ENTER( 17 ) )
      goto Exit;

    if ( ft_memcmp( stream->cursor, "%!PS-TrueTypeFont", 17 ) != 0 )
    {
      FT_TRACE2(( "  not a Type42 font\n" ));
      error = FT_THROW( Unknown_File_Format );
    }

    FT_FRAME_EXIT();

    if ( error || FT_STREAM_SEEK( 0 ) )
      goto Exit;

    size = stream->size;

    /* now, try to load `size' bytes of the `base' dictionary we */
    /* found previously                                          */

    /* if it is a memory-based resource, set up pointers */
    if ( !stream->read )
    {
      parser->base_dict = (FT_Byte*)stream->base + stream->pos;
      parser->base_len  = size;
      parser->in_memory = 1;

      /* check that the `size' field is valid */
      if ( FT_STREAM_SKIP( size ) )
        goto Exit;
    }
    else
    {
      /* read segment in memory */
      if ( FT_ALLOC( parser->base_dict, size )       ||
           FT_STREAM_READ( parser->base_dict, size ) )
        goto Exit;

      parser->base_len = size;
    }

    parser->root.base   = parser->base_dict;
    parser->root.cursor = parser->base_dict;
    parser->root.limit  = parser->root.cursor + parser->base_len;

  Exit:
    if ( error && !parser->in_memory )
      FT_FREE( parser->base_dict );

    return error;
  }


void RenderFrameHostImpl::DispatchBeforeUnload(BeforeUnloadType type,
                                               bool is_reload) {
  bool for_navigation =
      type == BeforeUnloadType::BROWSER_INITIATED_NAVIGATION ||
      type == BeforeUnloadType::RENDERER_INITIATED_NAVIGATION;
  bool for_inner_delegate_attach =
      type == BeforeUnloadType::INNER_DELEGATE_ATTACH;
  DCHECK(for_navigation || for_inner_delegate_attach || !is_reload);

  DCHECK(type == BeforeUnloadType::BROWSER_INITIATED_NAVIGATION ||
         type == BeforeUnloadType::RENDERER_INITIATED_NAVIGATION ||
         type == BeforeUnloadType::INNER_DELEGATE_ATTACH ||
         frame_tree_node_->IsMainFrame());

  if (!for_navigation) {
    if (frame_tree_node_->navigation_request() &&
        frame_tree_node_->navigation_request()->navigation_handle()) {
      frame_tree_node_->navigation_request()
          ->navigation_handle()
          ->set_net_error_code(net::ERR_ABORTED);
    }
    frame_tree_node_->ResetNavigationRequest(false, true);
  }

  bool check_subframes_only =
      type == BeforeUnloadType::RENDERER_INITIATED_NAVIGATION;
  if (!ShouldDispatchBeforeUnload(check_subframes_only)) {
    DCHECK(!for_navigation);

    base::OnceClosure task = base::BindOnce(
        [](base::WeakPtr<RenderFrameHostImpl> self) {
          if (!self)
            return;
          self->frame_tree_node_->render_manager()->OnBeforeUnloadACK(
              true, base::TimeTicks::Now());
        },
        weak_ptr_factory_.GetWeakPtr());
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(task));
    return;
  }
  TRACE_EVENT_ASYNC_BEGIN1("navigation", "RenderFrameHostImpl BeforeUnload",
                           this, "&RenderFrameHostImpl", (void*)this);

  if (is_waiting_for_beforeunload_ack_) {
    unload_ack_is_for_navigation_ =
        unload_ack_is_for_navigation_ && for_navigation;
  } else {
    is_waiting_for_beforeunload_ack_ = true;
    beforeunload_dialog_request_cancels_unload_ = false;
    unload_ack_is_for_navigation_ = for_navigation;
    send_before_unload_start_time_ = base::TimeTicks::Now();
    if (render_view_host_->GetDelegate()->IsJavaScriptDialogShowing()) {
      SimulateBeforeUnloadAck(type != BeforeUnloadType::DISCARD);
    } else {
      if (beforeunload_timeout_)
        beforeunload_timeout_->Start(beforeunload_timeout_delay_);

      beforeunload_pending_replies_.clear();
      beforeunload_dialog_request_cancels_unload_ =
          (type == BeforeUnloadType::DISCARD);

      CheckOrDispatchBeforeUnloadForSubtree(check_subframes_only,
                                            true /* send_ipc */, is_reload);
    }
  }
}


static int addFillStyle(SWFShape shape, SWFFillStyle fill)
{
	int i;

	for ( i=0; i<shape->nFills; ++i )
	{
		if ( SWFFillStyle_equals(fill, shape->fills[i]) )
			return i;
	}

	if ( shape->isEnded )
		return -1;

	if ( shape->nFills%STYLE_INCREMENT == 0 )
	{
		int size = (shape->nFills+STYLE_INCREMENT) * sizeof(SWFFillStyle);
		shape->fills = (SWFFillStyle*)realloc(shape->fills, size);
	}

	shape->fills[shape->nFills] = fill;
	++shape->nFills;
	return shape->nFills;
}


void JBIG2Stream::readGenericRegionSeg(Guint segNum, GBool imm,
				       GBool lossless, Guint length) {
  JBIG2Bitmap *bitmap;
  Guint w, h, x, y, segInfoFlags, extCombOp, rowCount;
  Guint flags, mmr, templ, tpgdOn;
  int atx[4], aty[4];

  if (!readULong(&w) || !readULong(&h) ||
      !readULong(&x) || !readULong(&y) ||
      !readUByte(&segInfoFlags)) {
    goto eofError;
  }
  extCombOp = segInfoFlags & 7;

  if (!readUByte(&flags)) {
    goto eofError;
  }
  mmr = flags & 1;
  templ = (flags >> 1) & 3;
  tpgdOn = (flags >> 3) & 1;

  if (!mmr) {
    if (templ == 0) {
      if (!readByte(&atx[0]) ||
	  !readByte(&aty[0]) ||
	  !readByte(&atx[1]) ||
	  !readByte(&aty[1]) ||
	  !readByte(&atx[2]) ||
	  !readByte(&aty[2]) ||
	  !readByte(&atx[3]) ||
	  !readByte(&aty[3])) {
	goto eofError;
      }
    } else {
      if (!readByte(&atx[0]) ||
	  !readByte(&aty[0])) {
	goto eofError;
      }
    }
  }

  if (!mmr) {
    resetGenericStats(templ, NULL);
    arithDecoder->start();
  }

  bitmap = readGenericBitmap(mmr, w, h, templ, tpgdOn, gFalse,
			     NULL, atx, aty, mmr ? length - 18 : 0);
  if (!bitmap)
    return;

  if (imm) {
    if (pageH == 0xffffffff && y + h > curPageH) {
      pageBitmap->expand(y + h, pageDefPixel);
    }
    pageBitmap->combine(bitmap, x, y, extCombOp);
    delete bitmap;

  } else {
    bitmap->setSegNum(segNum);
    segments->append(bitmap);
  }

  if (imm && length == 0xffffffff) {
    readULong(&rowCount);
  }

  return;

 eofError:
  error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
}


int Fraction::round() const
{
  return (numerator + denominator/2)/denominator;
}


void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
  if (!is_hidden_)
    return;

  TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
  is_hidden_ = false;

  if (new_content_rendering_timeout_ &&
      new_content_rendering_timeout_->IsRunning()) {
    new_content_rendering_timeout_->Stop();
    ClearDisplayedGraphics();
  }

   SendScreenRects();
   RestartHangMonitorTimeoutIfNecessary();

  bool needs_repainting = true;
  needs_repainting_on_restore_ = false;
  Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));

  process_->WidgetRestored();

  bool is_visible = true;
  NotificationService::current()->Notify(
      NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
      Source<RenderWidgetHost>(this),
      Details<bool>(&is_visible));

  WasResized();
}


ReadUserLogFileState::convertState(
	ReadUserLog::FileState			&state,
	ReadUserLogFileState::FileState	*&internal )
{
	ReadUserLogFileState::FileStatePub	*pub;
	convertState(state, pub);
	internal = &(pub->internal);
	return true;
}


static uint64_t vfio_rtl8168_window_quirk_read(void *opaque,

                                               hwaddr addr, unsigned size)

{

    VFIOQuirk *quirk = opaque;

    VFIOPCIDevice *vdev = quirk->vdev;

    switch (addr) {

    case 4: /* address */

        if (quirk->data.flags) {

            trace_vfio_rtl8168_window_quirk_read_fake(

                    memory_region_name(&quirk->mem),

                    vdev->vbasedev.name);

            return quirk->data.address_match ^ 0x10000000U;

        }

        break;

    case 0: /* data */

        if (quirk->data.flags) {

            uint64_t val;

            trace_vfio_rtl8168_window_quirk_read_table(

                    memory_region_name(&quirk->mem),

                    vdev->vbasedev.name);

            if (!(vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX)) {

                return 0;

            }

            memory_region_dispatch_read(&vdev->pdev.msix_table_mmio,

                                        (hwaddr)(quirk->data.address_match

                                                 & 0xfff),

                                        &val,

                                        size,

                                        MEMTXATTRS_UNSPECIFIED);

            return val;

        }

    }

    trace_vfio_rtl8168_window_quirk_read_direct(memory_region_name(&quirk->mem),

                                                vdev->vbasedev.name);

    return vfio_region_read(&vdev->bars[quirk->data.bar].region,

                            addr + 0x70, size);

}


static void free_unused_array_pages(void)
{
	unsigned i;

	for (i = event_array_pages; i < MAX_EVENT_ARRAY_PAGES; i++) {
		if (!event_array[i])
			break;
		free_page((unsigned long)event_array[i]);
		event_array[i] = NULL;
	}
}


AllocMidQEntry(const struct smb_hdr *smb_buffer, struct TCP_Server_Info *server)
{
	struct mid_q_entry *temp;

	if (server == NULL) {
		cERROR(1, "Null TCP session in AllocMidQEntry");
		return NULL;
	}

	temp = mempool_alloc(cifs_mid_poolp, GFP_NOFS);
	if (temp == NULL)
		return temp;
	else {
		memset(temp, 0, sizeof(struct mid_q_entry));
		temp->mid = smb_buffer->Mid;	/* always LE */
		temp->pid = current->pid;
		temp->command = cpu_to_le16(smb_buffer->Command);
		cFYI(1, "For smb_command %d", smb_buffer->Command);
	/*	do_gettimeofday(&temp->when_sent);*/ /* easier to use jiffies */
		/* when mid allocated can be before when sent */
		temp->when_alloc = jiffies;
		temp->server = server;

		/*
		 * The default is for the mid to be synchronous, so the
		 * default callback just wakes up the current task.
		 */
		temp->callback = cifs_wake_up_task;
		temp->callback_data = current;
	}

	atomic_inc(&midCount);
	temp->mid_state = MID_REQUEST_ALLOCATED;
	return temp;
}


proto_item * proto_tree_add_int64 ( proto_tree * tree , int hfindex , tvbuff_t * tvb , gint start , gint length , gint64 value ) {
 proto_item * pi = NULL ;
 header_field_info * hfinfo ;
 CHECK_FOR_NULL_TREE ( tree ) ;
 TRY_TO_FAKE_THIS_ITEM ( tree , hfindex , hfinfo ) ;
 switch ( hfinfo -> type ) {
 case FT_INT40 : case FT_INT48 : case FT_INT56 : case FT_INT64 : pi = proto_tree_add_pi ( tree , hfinfo , tvb , start , & length ) ;
 proto_tree_set_int64 ( PNODE_FINFO ( pi ) , value ) ;
 break ;
 default : DISSECTOR_ASSERT_NOT_REACHED ( ) ;
 }
 return pi ;
 }


static inline u64 perf_clock(void)
{
	return local_clock();
}


static int spl_filesystem_file_is_empty_line ( spl_filesystem_object * intern TSRMLS_DC ) {
 if ( intern -> u . file . current_line ) {
 return intern -> u . file . current_line_len == 0 ;
 }
 else if ( intern -> u . file . current_zval ) {
 switch ( Z_TYPE_P ( intern -> u . file . current_zval ) ) {
 case IS_STRING : return Z_STRLEN_P ( intern -> u . file . current_zval ) == 0 ;
 case IS_ARRAY : if ( SPL_HAS_FLAG ( intern -> flags , SPL_FILE_OBJECT_READ_CSV ) && zend_hash_num_elements ( Z_ARRVAL_P ( intern -> u . file . current_zval ) ) == 1 ) {
 zval * * first = Z_ARRVAL_P ( intern -> u . file . current_zval ) -> pListHead -> pData ;
 return Z_TYPE_PP ( first ) == IS_STRING && Z_STRLEN_PP ( first ) == 0 ;
 }
 return zend_hash_num_elements ( Z_ARRVAL_P ( intern -> u . file . current_zval ) ) == 0 ;
 case IS_NULL : return 1 ;
 default : return 0 ;
 }
 }
 else {
 return 1 ;
 }
 }


void GpuProcessHost::OnCommandBufferCreated(const int32 route_id) {
  TRACE_EVENT0("gpu", "GpuProcessHostUIShim::OnCommandBufferCreated");

  if (!create_command_buffer_requests_.empty()) {
    CreateCommandBufferCallback callback =
        create_command_buffer_requests_.front();
    create_command_buffer_requests_.pop();
    if (route_id == MSG_ROUTING_NONE)
      CreateCommandBufferError(callback, route_id);
    else
      callback.Run(route_id);
  }
}


static int qemuMonitorSendDiskPassphrase ( qemuMonitorPtr mon , qemuMonitorMessagePtr msg , const char * data , size_t len ATTRIBUTE_UNUSED , void * opaque ) {
 virConnectPtr conn = opaque ;
 char * path ;
 char * passphrase = NULL ;
 size_t passphrase_len = 0 ;
 int res ;
 const char * pathStart ;
 const char * pathEnd ;
 pathStart = strstr ( data , DISK_ENCRYPTION_PREFIX ) ;
 pathEnd = strstr ( data , DISK_ENCRYPTION_POSTFIX ) ;
 if ( ! pathStart || ! pathEnd || pathStart >= pathEnd ) {
 qemuReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "Unable to extract disk path from %s" ) , data ) ;
 return - 1 ;
 }
 pathStart += strlen ( DISK_ENCRYPTION_PREFIX ) ;
 if ( ! ( path = strndup ( pathStart , pathEnd - pathStart ) ) ) {
 virReportOOMError ( ) ;
 return - 1 ;
 }
 res = qemuMonitorGetDiskSecret ( mon , conn , path , & passphrase , & passphrase_len ) ;
 VIR_FREE ( path ) ;
 if ( res < 0 ) return - 1 ;
 if ( VIR_REALLOC_N ( msg -> txBuffer , msg -> txLength + passphrase_len + 1 + 1 ) < 0 ) {
 memset ( passphrase , 0 , passphrase_len ) ;
 VIR_FREE ( passphrase ) ;
 virReportOOMError ( ) ;
 return - 1 ;
 }
 memcpy ( msg -> txBuffer + msg -> txLength , passphrase , passphrase_len ) ;
 msg -> txLength += passphrase_len ;
 msg -> txBuffer [ msg -> txLength ] = '\r' ;
 msg -> txLength ++ ;
 msg -> txBuffer [ msg -> txLength ] = '\0' ;
 memset ( passphrase , 0 , passphrase_len ) ;
 VIR_FREE ( passphrase ) ;
 return 0 ;
 }


SoundPool::~SoundPool()
{
    ALOGV("SoundPool destructor");
    mDecodeThread->quit();
    quit();

 Mutex::Autolock lock(&mLock);

    mChannels.clear();
 if (mChannelPool)
 delete [] mChannelPool;
    ALOGV("clear samples");
    mSamples.clear();

 if (mDecodeThread)
 delete mDecodeThread;
}


onig_name_to_group_numbers(regex_t* reg, const UChar* name,
			   const UChar* name_end, int** nums)
{
  return ONIG_NO_SUPPORT_CONFIG;
}


flatpak_proxy_add_wildcarded_policy (FlatpakProxy *proxy,
                                     const char   *name,
                                     FlatpakPolicy policy)
{
  g_hash_table_replace (proxy->wildcard_policy, g_strdup (name), GINT_TO_POINTER (policy));
}


static MagickBooleanType ReadPSDChannelZip(Image *image,
  const PixelChannel channel,const PSDCompressionType compression,
  const size_t compact_size,ExceptionInfo *exception)
{
  MagickBooleanType
    status;

  unsigned char
    *p;

  size_t
    count,
    packet_size,
    row_size;

  ssize_t
    y;

  unsigned char
    *compact_pixels,
    *pixels;

  z_stream
    stream;

  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
       "      layer data is ZIP compressed");

  if ((MagickSizeType) compact_size > GetBlobSize(image))
    ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
      image->filename);
  compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
    sizeof(*compact_pixels));
  if (compact_pixels == (unsigned char *) NULL)
    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
      image->filename);

  packet_size=GetPSDPacketSize(image);
  row_size=image->columns*packet_size;
  count=image->rows*row_size;

  pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
  if (pixels == (unsigned char *) NULL)
    {
      compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
      ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
        image->filename);
    }
  if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)
    {
      pixels=(unsigned char *) RelinquishMagickMemory(pixels);
      compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
      ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
        image->filename);
    }

  memset(&stream,0,sizeof(stream));
  stream.data_type=Z_BINARY;
  stream.next_in=(Bytef *)compact_pixels;
  stream.avail_in=(uInt) compact_size;
  stream.next_out=(Bytef *)pixels;
  stream.avail_out=(uInt) count;

  if (inflateInit(&stream) == Z_OK)
    {
      int
        ret;

      while (stream.avail_out > 0)
      {
        ret=inflate(&stream,Z_SYNC_FLUSH);
        if ((ret != Z_OK) && (ret != Z_STREAM_END))
          {
            (void) inflateEnd(&stream);
            compact_pixels=(unsigned char *) RelinquishMagickMemory(
              compact_pixels);
            pixels=(unsigned char *) RelinquishMagickMemory(pixels);
            return(MagickFalse);
          }
        if (ret == Z_STREAM_END)
          break;
      }
      (void) inflateEnd(&stream);
    }

  if (compression == ZipWithPrediction)
    {
      if (packet_size == 1)
        Unpredict8Bit(image,pixels,count,row_size);
      else if (packet_size == 2)
        Unpredict16Bit(image,pixels,count,row_size);
      else if (packet_size == 4)
      {
        unsigned char
          *output_pixels;

        output_pixels=(unsigned char *) AcquireQuantumMemory(count,
          sizeof(*output_pixels));
        if (pixels == (unsigned char *) NULL)
          {
            compact_pixels=(unsigned char *) RelinquishMagickMemory(
              compact_pixels);
            pixels=(unsigned char *) RelinquishMagickMemory(pixels);
            ThrowBinaryException(ResourceLimitError,
              "MemoryAllocationFailed",image->filename);
          }
        Unpredict32Bit(image,pixels,output_pixels,row_size);
        pixels=(unsigned char *) RelinquishMagickMemory(pixels);
        pixels=output_pixels;
      }
    }

  status=MagickTrue;
  p=pixels;
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    status=ReadPSDChannelPixels(image,y,channel,p,exception);
    if (status == MagickFalse)
      break;

    p+=row_size;
  }

  compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
  pixels=(unsigned char *) RelinquishMagickMemory(pixels);
  return(status);
}


StringOrdinal ExtensionPrefs::CreateFirstAppLaunchOrdinal(
    const StringOrdinal& page_ordinal) const {
  const StringOrdinal& min_ordinal =
      GetMinOrMaxAppLaunchOrdinalsOnPage(page_ordinal,
                                         ExtensionPrefs::MIN_ORDINAL);

  if (min_ordinal.IsValid())
    return min_ordinal.CreateBefore();
  else
    return StringOrdinal::CreateInitialOrdinal();
}


xmlSplitQName(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlChar **prefix) {
    xmlChar buf[XML_MAX_NAMELEN + 5];
    xmlChar *buffer = NULL;
 int len = 0;
 int max = XML_MAX_NAMELEN;
    xmlChar *ret = NULL;
 const xmlChar *cur = name;
 int c;

 if (prefix == NULL) return(NULL);
 *prefix = NULL;

 if (cur == NULL) return(NULL);

#ifndef XML_XML_NAMESPACE
 /* xml: prefix is not really a namespace */
 if ((cur[0] == 'x') && (cur[1] == 'm') &&
 (cur[2] == 'l') && (cur[3] == ':'))
 return(xmlStrdup(name));
#endif

 /* nasty but well=formed */
 if (cur[0] == ':')
 return(xmlStrdup(name));

    c = *cur++;
 while ((c != 0) && (c != ':') && (len < max)) { /* tested bigname.xml */
	buf[len++] = c;
	c = *cur++;
 }
 if (len >= max) {
 /*
	 * Okay someone managed to make a huge name, so he's ready to pay
	 * for the processing speed.
	 */
	max = len * 2;

	buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 if (buffer == NULL) {
	    xmlErrMemory(ctxt, NULL);
 return(NULL);
 }
	memcpy(buffer, buf, len);
 while ((c != 0) && (c != ':')) { /* tested bigname.xml */
 if (len + 10 > max) {
	        xmlChar *tmp;

		max *= 2;
		tmp = (xmlChar *) xmlRealloc(buffer,
						max * sizeof(xmlChar));
 if (tmp == NULL) {
		    xmlFree(buffer);
		    xmlErrMemory(ctxt, NULL);
 return(NULL);
 }
		buffer = tmp;
 }
	    buffer[len++] = c;
	    c = *cur++;
 }
	buffer[len] = 0;
 }

 if ((c == ':') && (*cur == 0)) {
 if (buffer != NULL)
	    xmlFree(buffer);
 *prefix = NULL;
 return(xmlStrdup(name));
 }

 if (buffer == NULL)
	ret = xmlStrndup(buf, len);
 else {
	ret = buffer;
	buffer = NULL;
	max = XML_MAX_NAMELEN;
 }

 if (c == ':') {
	c = *cur;
 *prefix = ret;
 if (c == 0) {
 return(xmlStrndup(BAD_CAST "", 0));
 }
	len = 0;

 /*
	 * Check that the first character is proper to start
	 * a new name
	 */
 if (!(((c >= 0x61) && (c <= 0x7A)) ||
 ((c >= 0x41) && (c <= 0x5A)) ||
 (c == '_') || (c == ':'))) {
 int l;
 int first = CUR_SCHAR(cur, l);

 if (!IS_LETTER(first) && (first != '_')) {
		xmlFatalErrMsgStr(ctxt, XML_NS_ERR_QNAME,
 "Name %s is not XML Namespace compliant\n",
				  name);
 }
 }
	cur++;

 while ((c != 0) && (len < max)) { /* tested bigname2.xml */
	    buf[len++] = c;
	    c = *cur++;
 }
 if (len >= max) {
 /*
	     * Okay someone managed to make a huge name, so he's ready to pay
	     * for the processing speed.
	     */
	    max = len * 2;

	    buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 if (buffer == NULL) {
	        xmlErrMemory(ctxt, NULL);
 return(NULL);
 }
	    memcpy(buffer, buf, len);
 while (c != 0) { /* tested bigname2.xml */
 if (len + 10 > max) {
		    xmlChar *tmp;

		    max *= 2;
		    tmp = (xmlChar *) xmlRealloc(buffer,
						    max * sizeof(xmlChar));
 if (tmp == NULL) {
			xmlErrMemory(ctxt, NULL);
			xmlFree(buffer);
 return(NULL);
 }
		    buffer = tmp;
 }
		buffer[len++] = c;
		c = *cur++;
 }
	    buffer[len] = 0;
 }

 if (buffer == NULL)
	    ret = xmlStrndup(buf, len);
 else {
	    ret = buffer;
 }
 }

 return(ret);
}


static int pmcraid_reset_bringdown(struct pmcraid_instance *pinstance)
{
	return pmcraid_reset_reload(pinstance,
				    SHUTDOWN_NORMAL,
				    IOA_STATE_UNKNOWN);
}


static void rose_timer_expiry(struct timer_list *t)
{
	struct rose_sock *rose = from_timer(rose, t, timer);
	struct sock *sk = &rose->sock;

	bh_lock_sock(sk);
	switch (rose->state) {
	case ROSE_STATE_1:	/* T1 */
	case ROSE_STATE_4:	/* T2 */
		rose_write_internal(sk, ROSE_CLEAR_REQUEST);
		rose->state = ROSE_STATE_2;
		rose_start_t3timer(sk);
		break;

	case ROSE_STATE_2:	/* T3 */
		rose->neighbour->use--;
		rose_disconnect(sk, ETIMEDOUT, -1, -1);
		break;

	case ROSE_STATE_3:	/* HB */
		if (rose->condition & ROSE_COND_ACK_PENDING) {
			rose->condition &= ~ROSE_COND_ACK_PENDING;
			rose_enquiry_response(sk);
		}
		break;
	}
	bh_unlock_sock(sk);
}


static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
    int i;
    int64_t creation_time;
    int version = avio_r8(pb); /* version */
    avio_rb24(pb); /* flags */

    if (version == 1) {
        creation_time = avio_rb64(pb);
        avio_rb64(pb);
    } else {
        creation_time = avio_rb32(pb);
        avio_rb32(pb); /* modification time */
    }
    mov_metadata_creation_time(&c->fc->metadata, creation_time);
    c->time_scale = avio_rb32(pb); /* time scale */
    if (c->time_scale <= 0) {
        av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
        c->time_scale = 1;
    }
    av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);

    c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
    // set the AVCodecContext duration because the duration of individual tracks
    // may be inaccurate
    if (c->time_scale > 0 && !c->trex_data)
        c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
    avio_rb32(pb); /* preferred scale */

    avio_rb16(pb); /* preferred volume */

    avio_skip(pb, 10); /* reserved */

    /* movie display matrix, store it in main context and use it later on */
    for (i = 0; i < 3; i++) {
        c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
        c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
        c->movie_display_matrix[i][2] = avio_rb32(pb); //  2.30 fixed point
    }

    avio_rb32(pb); /* preview time */
    avio_rb32(pb); /* preview duration */
    avio_rb32(pb); /* poster time */
    avio_rb32(pb); /* selection time */
    avio_rb32(pb); /* selection duration */
    avio_rb32(pb); /* current time */
    avio_rb32(pb); /* next track ID */

    return 0;
}


static void setup_frame(int sig, struct target_sigaction *ka,

                        target_sigset_t *set, CPUM68KState *env)

{

    struct target_sigframe *frame;

    abi_ulong frame_addr;

    abi_ulong retcode_addr;

    abi_ulong sc_addr;

    int err = 0;

    int i;

    frame_addr = get_sigframe(ka, env, sizeof *frame);

    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

	goto give_sigsegv;

    __put_user(sig, &frame->sig);

    sc_addr = frame_addr + offsetof(struct target_sigframe, sc);

    __put_user(sc_addr, &frame->psc);

    err |= setup_sigcontext(&frame->sc, env, set->sig[0]);

    if (err)

	goto give_sigsegv;

    for(i = 1; i < TARGET_NSIG_WORDS; i++) {

        if (__put_user(set->sig[i], &frame->extramask[i - 1]))

            goto give_sigsegv;

    }

    /* Set up to return from userspace.  */

    retcode_addr = frame_addr + offsetof(struct target_sigframe, retcode);

    __put_user(retcode_addr, &frame->pretcode);

    /* moveq #,d0; trap #0 */

    __put_user(0x70004e40 + (TARGET_NR_sigreturn << 16),

                      (long *)(frame->retcode));

    if (err)

        goto give_sigsegv;

    /* Set up to return from userspace */

    env->aregs[7] = frame_addr;

    env->pc = ka->_sa_handler;

    unlock_user_struct(frame, frame_addr, 1);

    return;

give_sigsegv:

    unlock_user_struct(frame, frame_addr, 1);

    force_sig(TARGET_SIGSEGV);

}


static void acm_tty_unthrottle(struct tty_struct *tty)
{
	struct acm *acm = tty->driver_data;
	unsigned int was_throttled;

	spin_lock_irq(&acm->read_lock);
	was_throttled = acm->throttled;
	acm->throttled = 0;
	acm->throttle_req = 0;
	spin_unlock_irq(&acm->read_lock);

	if (was_throttled)
		acm_submit_read_urbs(acm, GFP_KERNEL);
}


static void test_bug28386()
{
  int rc;
  MYSQL_STMT *stmt;
  MYSQL_RES *result;
  MYSQL_ROW row;
  MYSQL_BIND bind;
  const char hello[]= "hello world!";

  DBUG_ENTER("test_bug28386");
  myheader("test_bug28386");

  rc= mysql_query(mysql, "select @@global.log_output");
  myquery(rc);

  result= mysql_store_result(mysql);
  DIE_UNLESS(result);

  row= mysql_fetch_row(result);
  if (! strstr(row[0], "TABLE"))
  {
    mysql_free_result(result);
    if (! opt_silent)
      printf("Skipping the test since logging to tables is not enabled\n");
    /* Log output is not to tables */
    return;
  }
  mysql_free_result(result);

  enable_query_logs(1);

  stmt= mysql_simple_prepare(mysql, "SELECT ?");
  check_stmt(stmt);

  memset(&bind, 0, sizeof(bind));

  bind.buffer_type= MYSQL_TYPE_STRING;
  bind.buffer= (void *) hello;
  bind.buffer_length= sizeof(hello);

  mysql_stmt_bind_param(stmt, &bind);
  mysql_stmt_send_long_data(stmt, 0, hello, sizeof(hello));

  rc= mysql_stmt_execute(stmt);
  check_execute(stmt, rc);

  rc= my_process_stmt_result(stmt);
  DIE_UNLESS(rc == 1);

  rc= mysql_stmt_reset(stmt);
  check_execute(stmt, rc);

  rc= mysql_stmt_close(stmt);
  DIE_UNLESS(!rc);

  rc= mysql_query(mysql, "select * from mysql.general_log where "
                         "command_type='Close stmt' or "
                         "command_type='Reset stmt' or "
                         "command_type='Long Data'");
  myquery(rc);

  result= mysql_store_result(mysql);
  mytest(result);

  DIE_UNLESS(mysql_num_rows(result) == 3);

  mysql_free_result(result);

  restore_query_logs();

  DBUG_VOID_RETURN;
}


int slirp_remove_hostfwd(int is_udp, struct in_addr host_addr, int host_port)

{

    struct socket *so;

    struct socket *head = (is_udp ? &udb : &tcb);

    struct sockaddr_in addr;

    int port = htons(host_port);

    socklen_t addr_len;

    int n = 0;

 loop_again:

    for (so = head->so_next; so != head; so = so->so_next) {

        addr_len = sizeof(addr);

        if (getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&

            addr.sin_addr.s_addr == host_addr.s_addr &&

            addr.sin_port == port) {

            close(so->s);

            sofree(so);

            n++;

            goto loop_again;

        }

    }

    return n;

}


usage(char *cmd)
{
	int i;

	fprintf(stderr, "USAGE: %s", cmd);
	fprintf(stderr, " [OPTIONS] COMMAND [COMMAND ARGS]\n\n");

	fprintf(stderr,
			"OPTIONS:\n");
	fprintf(stderr, "  -i <VAL>\t\tinstance to connect to (0 - default)\n");

	fprintf(stderr,
			"COMMANDS:\n");
	for(i=0;i<commandListLen;i++){
		fprintf(stderr, "  %-21s %s\n",commandList[i].name,commandList[i].desc);
	}
	fflush(stderr);

}


  void CreateUnifiedStream(const url::Origin& security_origin) {
    std::string output_id = GetNondefaultIdExpectedToPassPermissionsCheck();
    std::string input_id = GetNondefaultInputId();
    std::string hashed_output_id = MediaStreamManager::GetHMACForMediaDeviceID(
        kSalt, url::Origin(GURL(kSecurityOrigin)), output_id);
    audio_manager_->CreateDeviceAssociation(input_id, output_id);
    int session_id = media_stream_manager_->audio_input_device_manager()->Open(
        StreamDeviceInfo(MEDIA_DEVICE_AUDIO_CAPTURE, "Fake input device",
                         input_id));
    base::RunLoop().RunUntilIdle();

    media::AudioParameters params(
        media::AudioParameters::AUDIO_FAKE, media::CHANNEL_LAYOUT_STEREO,
        media::AudioParameters::kAudioCDSampleRate, 16,
        media::AudioParameters::kAudioCDSampleRate / 10);

    EXPECT_CALL(*host_.get(),
                OnDeviceAuthorized(kStreamId, media::OUTPUT_DEVICE_STATUS_OK, _,
                                   hashed_output_id))
        .Times(1);
    EXPECT_CALL(*host_.get(), WasNotifiedOfCreation(kStreamId, _));
    EXPECT_CALL(mirroring_manager_, AddDiverter(render_process_host_.GetID(),
                                                kRenderFrameId, NotNull()))
        .RetiresOnSaturation();
    EXPECT_CALL(mirroring_manager_, RemoveDiverter(NotNull()))
        .RetiresOnSaturation();

    host_->OnRequestDeviceAuthorization(kStreamId, kRenderFrameId, session_id,
                                        /*device id*/ std::string(),
                                        security_origin);

    auth_run_loop_.Run();

    host_->OnCreateStream(kStreamId, kRenderFrameId, params);

    SyncWithAudioThread();
  }


static bool NeedsInnerBorderRadiusClip(const LayoutObject& object) {
  if (!object.StyleRef().HasBorderRadius())
    return false;
  if (object.IsBox() && NeedsOverflowClip(object))
    return true;
  if (object.IsLayoutReplaced() && !object.IsSVGRoot())
    return true;
  return false;
}


bool EnumerateAllWindows(EnumerateWindowsDelegate* delegate, int max_depth) {
  XID root = GetX11RootWindow();
  return EnumerateChildren(delegate, root, max_depth, 0);
}


static inline void tcg_out_ldst(TCGContext *s, int ret, int addr,

                                int offset, int op)

{

    if (check_fit_tl(offset, 13)) {

        tcg_out32(s, op | INSN_RD(ret) | INSN_RS1(addr) |

                  INSN_IMM13(offset));

    } else {

        tcg_out_movi(s, TCG_TYPE_PTR, TCG_REG_T1, offset);

        tcg_out_ldst_rr(s, ret, addr, TCG_REG_T1, op);

    }

}


MagickExport MagickBooleanType InvokeDynamicImageFilter(const char *tag,
  Image **image,const int argc,const char **argv,ExceptionInfo *exception)
{
  PolicyRights
    rights;

  assert(image != (Image **) NULL);
  assert((*image)->signature == MagickCoreSignature);
  if ((*image)->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
  rights=ReadPolicyRights;
  if (IsRightsAuthorized(FilterPolicyDomain,rights,tag) == MagickFalse)
    {
      errno=EPERM;
      (void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
        "NotAuthorized","`%s'",tag);
      return(MagickFalse);
    }
#if defined(MAGICKCORE_BUILD_MODULES)
  (void) tag;
  (void) argc;
  (void) argv;
  (void) exception;
#else
  {
    ImageFilterHandler
      *image_filter;

    image_filter=(ImageFilterHandler *) NULL;
    if (LocaleCompare("analyze",tag) == 0)
      image_filter=(ImageFilterHandler *) analyzeImage;
    if (image_filter == (ImageFilterHandler *) NULL)
      (void) ThrowMagickException(exception,GetMagickModule(),ModuleError,
        "UnableToLoadModule","`%s'",tag);
    else
      {
        size_t
          signature;

        if ((*image)->debug != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            "Invoking \"%s\" static image filter",tag);
        signature=image_filter(image,argc,argv,exception);
        if ((*image)->debug != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),"\"%s\" completes",
            tag);
        if (signature != MagickImageFilterSignature)
          {
            (void) ThrowMagickException(exception,GetMagickModule(),ModuleError,
              "ImageFilterSignatureMismatch","'%s': %8lx != %8lx",tag,
              (unsigned long) signature,(unsigned long)
              MagickImageFilterSignature);
            return(MagickFalse);
          }
      }
  }
#endif
  return(MagickTrue);
}


gettoken_query(QPRS_STATE *state, int32 *val, int32 *lenval, char **strval, uint16 *flag)
{
	int			charlen;

	for (;;)
	{
		charlen = pg_mblen(state->buf);

		switch (state->state)
		{
			case WAITOPERAND:
				if (charlen == 1 && t_iseq(state->buf, '!'))
				{
					(state->buf)++;
					*val = (int32) '!';
					return OPR;
				}
				else if (charlen == 1 && t_iseq(state->buf, '('))
				{
					state->count++;
					(state->buf)++;
					return OPEN;
				}
				else if (ISALNUM(state->buf))
				{
					state->state = INOPERAND;
					*strval = state->buf;
					*lenval = charlen;
					*flag = 0;
				}
				else if (!t_isspace(state->buf))
					ereport(ERROR,
							(errcode(ERRCODE_SYNTAX_ERROR),
							 errmsg("operand syntax error")));
				break;
			case INOPERAND:
				if (ISALNUM(state->buf))
				{
					if (*flag)
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("modificators syntax error")));
					*lenval += charlen;
				}
				else if (charlen == 1 && t_iseq(state->buf, '%'))
					*flag |= LVAR_SUBLEXEME;
				else if (charlen == 1 && t_iseq(state->buf, '@'))
					*flag |= LVAR_INCASE;
				else if (charlen == 1 && t_iseq(state->buf, '*'))
					*flag |= LVAR_ANYEND;
				else
				{
					state->state = WAITOPERATOR;
					return VAL;
				}
				break;
			case WAITOPERATOR:
				if (charlen == 1 && (t_iseq(state->buf, '&') || t_iseq(state->buf, '|')))
				{
					state->state = WAITOPERAND;
					*val = (int32) *(state->buf);
					(state->buf)++;
					return OPR;
				}
				else if (charlen == 1 && t_iseq(state->buf, ')'))
				{
					(state->buf)++;
					state->count--;
					return (state->count < 0) ? ERR : CLOSE;
				}
				else if (*(state->buf) == '\0')
					return (state->count) ? ERR : END;
				else if (charlen == 1 && !t_iseq(state->buf, ' '))
					return ERR;
				break;
			default:
				return ERR;
				break;
		}

		state->buf += charlen;
	}
}


void PrintDialogGtk::OnJobCompleted(GtkPrintJob* job, GError* error) {
  gtk_widget_destroy(dialog_);

  if (error)
    LOG(ERROR) << "Printing failed: " << error->message;

  if (job)
    g_object_unref(job);

  file_util::Delete(path_to_pdf_, false);

  delete this;
}


static pj_status_t ipp_alloc_codec( pjmedia_codec_factory *factory,
				    const pjmedia_codec_info *id,
				    pjmedia_codec **p_codec)
{
    ipp_private_t *codec_data;
    pjmedia_codec *codec;
    int idx;
    pj_pool_t *pool;
    unsigned i;

    PJ_ASSERT_RETURN(factory && id && p_codec, PJ_EINVAL);
    PJ_ASSERT_RETURN(factory == &ipp_factory.base, PJ_EINVAL);

    pj_mutex_lock(ipp_factory.mutex);

    /* Find codec's index */
    idx = -1;
    for (i = 0; i < PJ_ARRAY_SIZE(ipp_codec); ++i) {
	pj_str_t name = pj_str((char*)ipp_codec[i].name);
	if ((pj_stricmp(&id->encoding_name, &name) == 0) &&
	    (id->clock_rate == (unsigned)ipp_codec[i].clock_rate) &&
	    (id->channel_cnt == (unsigned)ipp_codec[i].channel_count) &&
	    (ipp_codec[i].enabled))
	{
	    idx = i;
	    break;
	}
    }
    if (idx == -1) {
	*p_codec = NULL;
	pj_mutex_unlock(ipp_factory.mutex);
	return PJMEDIA_CODEC_EFAILED;
    }

    /* Create pool for codec instance */
    pool = pjmedia_endpt_create_pool(ipp_factory.endpt, "IPPcodec", 512, 512);
    codec = PJ_POOL_ZALLOC_T(pool, pjmedia_codec);
    PJ_ASSERT_RETURN(codec != NULL, PJ_ENOMEM);
    codec->op = &ipp_op;
    codec->factory = factory;
    codec->codec_data = PJ_POOL_ZALLOC_T(pool, ipp_private_t);
    codec_data = (ipp_private_t*) codec->codec_data;

    /* Create PLC if codec has no internal PLC */
    if (!ipp_codec[idx].has_native_plc) {
	pj_status_t status;
	status = pjmedia_plc_create(pool, ipp_codec[idx].clock_rate,
				    ipp_codec[idx].samples_per_frame, 0,
				    &codec_data->plc);
	if (status != PJ_SUCCESS) {
	    pj_pool_release(pool);
	    pj_mutex_unlock(ipp_factory.mutex);
	    return status;
	}
    }

    /* Create silence detector if codec has no internal VAD */
    if (!ipp_codec[idx].has_native_vad) {
	pj_status_t status;
	status = pjmedia_silence_det_create(pool,
					    ipp_codec[idx].clock_rate,
					    ipp_codec[idx].samples_per_frame,
					    &codec_data->vad);
	if (status != PJ_SUCCESS) {
	    pj_pool_release(pool);
	    pj_mutex_unlock(ipp_factory.mutex);
	    return status;
	}
    }

    codec_data->pool = pool;
    codec_data->codec_idx = idx;

    pj_mutex_unlock(ipp_factory.mutex);

    *p_codec = codec;
    return PJ_SUCCESS;
}


bool TestBrowserWindow::ShouldHideUIForFullscreen() const {
  return false;
}


void WebContentsImpl::OnCreditCardInputShownOnHttp() {
  controller_.ssl_manager()->DidShowCreditCardInputOnHttp();
}


static GF_Node *lsr_read_text(GF_LASeRCodec *lsr, u32 same_type)
{
	u32 flag;
	GF_FieldInfo info;
	GF_Node *elt = gf_node_new(lsr->sg, TAG_SVG_text);
	if (same_type) {
		if (lsr->prev_text) {
			lsr_restore_base(lsr, (SVG_Element *)elt, (SVG_Element *)lsr->prev_text, (same_type==2) ? 1 : 0, 0);
		} else {
			GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[LASeR] sametext coded in bitstream but no text defined !\n"));
		}
		lsr_read_id(lsr, elt);
		if (same_type==2) lsr_read_fill(lsr, elt);
		lsr_read_coord_list(lsr, elt, TAG_SVG_ATT_text_x, "x");
		lsr_read_coord_list(lsr, elt, TAG_SVG_ATT_text_y, "y");
	} else {
		lsr_read_id(lsr, elt);
		lsr_read_rare_full(lsr, elt);
		lsr_read_fill(lsr, elt);
		lsr_read_stroke(lsr, elt);

		GF_LSR_READ_INT(lsr, flag, 1, "editable");
		if (flag) {
			lsr->last_error = gf_node_get_attribute_by_tag(elt, TAG_SVG_ATT_editable, 1, 0, &info);
			*(SVG_Boolean*)info.far_ptr = flag;
		}
		lsr_read_float_list(lsr, elt, TAG_SVG_ATT_text_rotate, NULL, "rotate");
		lsr_read_coord_list(lsr, elt, TAG_SVG_ATT_text_x, "x");
		lsr_read_coord_list(lsr, elt, TAG_SVG_ATT_text_y, "y");
		lsr_read_any_attribute(lsr, elt, 1);
		lsr->prev_text = (SVG_Element*)elt;
	}
	lsr_read_group_content(lsr, elt, same_type);
	return elt;
}


EventTarget* Document::errorEventTarget()
{
    return domWindow();
}


 */
static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq)
{
	bfq_log_bfqq(bfqq->bfqd, bfqq,
		"may_budget_timeout: wait_request %d left %d timeout %d",
		bfq_bfqq_wait_request(bfqq),
			bfq_bfqq_budget_left(bfqq) >=  bfqq->entity.budget / 3,
		bfq_bfqq_budget_timeout(bfqq));

	return (!bfq_bfqq_wait_request(bfqq) ||
		bfq_bfqq_budget_left(bfqq) >=  bfqq->entity.budget / 3)
		&&
		bfq_bfqq_budget_timeout(bfqq);


R_API ut64 r_bin_java_rti_annotations_attr_calc_size(RBinJavaAttrInfo *attr) {
	ut64 size = 0;
	if (!attr) {
		// TODO eprintf allocation fail
		return size;
	}
	size += (6 + r_bin_java_annotation_array_calc_size (&(attr->info.annotation_array)));
	return size;
}


bool NPJSObject::NP_SetProperty(NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
{
     return toNPJSObject(npObject)->setProperty(propertyName, value);
 }


sysContact_handler(snmp_varbind_t *varbind, uint32_t *oid)
{
  snmp_api_set_string(varbind, oid, "Contiki-NG, https://github.com/contiki-ng/contiki-ng");
}


void bdrv_drain(BlockDriverState *bs)

{

    while (bdrv_drain_one(bs)) {

        /* Keep iterating */

    }

}


void AOClient::pktModCall(AreaData* area, int argc, QStringList argv, AOPacket packet)
{
    for (AOClient* client : server->clients) {
        if (client->authenticated)
            client->sendPacket(packet);
    }
    area->log(current_char, ipid, packet);

    if (ConfigManager::discordWebhookEnabled()) {
        QString name = ooc_name;
        if (ooc_name.isEmpty())
            name = current_char;

        emit server->modcallWebhookRequest(name, server->areas[current_area]->name(), packet.contents[0], area->buffer());
    }

    area->flushLogs();
}


  SSLHandshakeServerDoVerify(
      AsyncSSLSocket::UniquePtr socket,
      bool preverifyResult,
      bool verifyResult)
      : SSLHandshakeBase(std::move(socket), preverifyResult, verifyResult) {
    socket_->sslAccept(
        this,
        std::chrono::milliseconds::zero(),
        folly::SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
  }


static void FUNCC(pred8x8_left_dc)(uint8_t *_src, int stride){

    int i;

    int dc0, dc2;

    pixel4 dc0splat, dc2splat;

    pixel *src = (pixel*)_src;

    stride /= sizeof(pixel);

    dc0=dc2=0;

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

        dc0+= src[-1+i*stride];

        dc2+= src[-1+(i+4)*stride];

    }

    dc0splat = PIXEL_SPLAT_X4((dc0 + 2)>>2);

    dc2splat = PIXEL_SPLAT_X4((dc2 + 2)>>2);

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

        ((pixel4*)(src+i*stride))[0]=

        ((pixel4*)(src+i*stride))[1]= dc0splat;

    }

    for(i=4; i<8; i++){

        ((pixel4*)(src+i*stride))[0]=

        ((pixel4*)(src+i*stride))[1]= dc2splat;

    }

}


void WebSocketJob::OnConnected(
    SocketStream* socket, int max_pending_send_allowed) {
  if (state_ == CLOSED)
    return;
  DCHECK_EQ(CONNECTING, state_);
  if (delegate_)
    delegate_->OnConnected(socket, max_pending_send_allowed);
}