static int read_and_execute ( bool interactive ) {
 # if defined ( __WIN__ ) String tmpbuf ;
 String buffer ;
 # endif char * line = NULL ;
 char in_string = 0 ;
 ulong line_number = 0 ;
 bool ml_comment = 0 ;
 COMMANDS * com ;
 ulong line_length = 0 ;
 status . exit_status = 1 ;
 real_binary_mode = ! interactive && opt_binary_mode ;
 while ( ! aborted ) {
 if ( ! interactive ) {
 line = batch_readline ( status . line_buff , real_binary_mode ) ;
 if ( line ) {
 line_length = status . line_buff -> read_length ;
 if ( ! real_binary_mode && strlen ( line ) != line_length ) {
 status . exit_status = 1 ;
 String msg ;
 msg . append ( "ASCII '\\0' appeared in the statement, but this is not " "allowed unless option --binary-mode is enabled and mysql is " "run in non-interactive mode. Set --binary-mode to 1 if ASCII " "'\\0' is expected. Query: '" ) ;
 msg . append ( glob_buffer ) ;
 msg . append ( line ) ;
 msg . append ( "'." ) ;
 put_info ( msg . c_ptr ( ) , INFO_ERROR ) ;
 break ;
 }
 if ( ! line_number && ( uchar ) line [ 0 ] == 0xEF && ( uchar ) line [ 1 ] == 0xBB && ( uchar ) line [ 2 ] == 0xBF ) {
 line += 3 ;
 line_length -= 3 ;
 }
 }
 line_number ++ ;
 if ( ! glob_buffer . length ( ) ) status . query_start_line = line_number ;
 }
 else {
 char * prompt = ( char * ) ( ml_comment ? " /*> " : glob_buffer . is_empty ( ) ? construct_prompt ( ) : ! in_string ? " -> " : in_string == '\'' ? " '> " : ( in_string == '`' ? " `> " : " \"> " ) ) ;
 if ( opt_outfile && glob_buffer . is_empty ( ) ) fflush ( OUTFILE ) ;
 # if defined ( __WIN__ ) tee_fputs ( prompt , stdout ) ;
 if ( ! tmpbuf . is_alloced ( ) ) tmpbuf . alloc ( 65535 ) ;
 tmpbuf . length ( 0 ) ;
 buffer . length ( 0 ) ;
 size_t clen ;
 do {
 line = my_cgets ( ( char * ) tmpbuf . ptr ( ) , tmpbuf . alloced_length ( ) - 1 , & clen ) ;
 buffer . append ( line , clen ) ;
 }
 while ( tmpbuf . alloced_length ( ) <= clen ) ;
 if ( line ) line = buffer . c_ptr ( ) ;
 # else if ( opt_outfile ) fputs ( prompt , OUTFILE ) ;
 if ( line ) free ( line ) ;
 line = readline ( prompt ) ;
 # endif if ( opt_outfile && line ) fprintf ( OUTFILE , "%s\n" , line ) ;
 line_length = line ? strlen ( line ) : 0 ;
 }
 if ( ! line ) {
 if ( status . line_buff && status . line_buff -> error ) status . exit_status = 1 ;
 else status . exit_status = 0 ;
 break ;
 }
 if ( ( named_cmds || glob_buffer . is_empty ( ) ) && ! ml_comment && ! in_string && ( com = find_command ( line ) ) ) {
 if ( ( * com -> func ) ( & glob_buffer , line ) > 0 ) break ;
 if ( glob_buffer . is_empty ( ) ) in_string = 0 ;
 # ifdef HAVE_READLINE if ( interactive && status . add_to_history && not_in_history ( line ) ) add_history ( line ) ;
 # endif continue ;
 }
 if ( add_line ( glob_buffer , line , line_length , & in_string , & ml_comment , status . line_buff ? status . line_buff -> truncated : 0 ) ) break ;
 }
 if ( ! interactive && ! status . exit_status ) {
 remove_cntrl ( glob_buffer ) ;
 if ( ! glob_buffer . is_empty ( ) ) {
 status . exit_status = 1 ;
 if ( com_go ( & glob_buffer , line ) <= 0 ) status . exit_status = 0 ;
 }
 }
 # if defined ( __WIN__ ) buffer . free ( ) ;
 tmpbuf . free ( ) ;
 # else if ( interactive ) free ( line ) ;
 # endif real_binary_mode = FALSE ;
 return status . exit_status ;
 }


bool IsValidHostName(base::StringPiece host,
                     base::StringPiece domain_in_lower_case,
                     SubdomainPermission subdomain_permission,
                     base::StringPiece* tld) {
  if (host.find(domain_in_lower_case) == base::StringPiece::npos)
    return false;

  size_t tld_length =
      net::registry_controlled_domains::GetCanonicalHostRegistryLength(
          host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
          net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
  if ((tld_length == 0) || (tld_length == std::string::npos))
    return false;

  base::StringPiece host_minus_tld =
      host.substr(0, host.length() - tld_length - 1);

  if (tld)
    *tld = host.substr(host.length() - tld_length);

  if (base::LowerCaseEqualsASCII(host_minus_tld, domain_in_lower_case))
    return true;

  if (subdomain_permission == ALLOW_SUBDOMAIN) {
    std::string dot_domain(".");
    domain_in_lower_case.AppendToString(&dot_domain);
    return base::EndsWith(host_minus_tld, dot_domain,
                          base::CompareCase::INSENSITIVE_ASCII);
  }

  std::string www_domain("www.");
  domain_in_lower_case.AppendToString(&www_domain);
  return base::LowerCaseEqualsASCII(host_minus_tld, www_domain);
}


ModuleExport void UnregisterDCMImage(void)
{
  (void) UnregisterMagickInfo("DCM");
}


static int read_one_dev(struct btrfs_fs_info *fs_info,
			struct extent_buffer *leaf,
			struct btrfs_dev_item *dev_item)
{
	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
	struct btrfs_device *device;
	u64 devid;
	int ret;
	u8 fs_uuid[BTRFS_FSID_SIZE];
	u8 dev_uuid[BTRFS_UUID_SIZE];

	devid = btrfs_device_id(leaf, dev_item);
	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
			   BTRFS_UUID_SIZE);
	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
			   BTRFS_FSID_SIZE);

	if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
		fs_devices = open_seed_devices(fs_info, fs_uuid);
		if (IS_ERR(fs_devices))
			return PTR_ERR(fs_devices);
	}

	device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
				   fs_uuid);
	if (!device) {
		if (!btrfs_test_opt(fs_info, DEGRADED)) {
			btrfs_report_missing_device(fs_info, devid,
							dev_uuid, true);
			return -ENOENT;
		}

		device = add_missing_dev(fs_devices, devid, dev_uuid);
		if (IS_ERR(device)) {
			btrfs_err(fs_info,
				"failed to add missing dev %llu: %ld",
				devid, PTR_ERR(device));
			return PTR_ERR(device);
		}
		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
	} else {
		if (!device->bdev) {
			if (!btrfs_test_opt(fs_info, DEGRADED)) {
				btrfs_report_missing_device(fs_info,
						devid, dev_uuid, true);
				return -ENOENT;
			}
			btrfs_report_missing_device(fs_info, devid,
							dev_uuid, false);
		}

		if (!device->bdev &&
		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
			/*
			 * this happens when a device that was properly setup
			 * in the device info lists suddenly goes bad.
			 * device->bdev is NULL, and so we have to set
			 * device->missing to one here
			 */
			device->fs_devices->missing_devices++;
			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
		}

		/* Move the device to its own fs_devices */
		if (device->fs_devices != fs_devices) {
			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
							&device->dev_state));

			list_move(&device->dev_list, &fs_devices->devices);
			device->fs_devices->num_devices--;
			fs_devices->num_devices++;

			device->fs_devices->missing_devices--;
			fs_devices->missing_devices++;

			device->fs_devices = fs_devices;
		}
	}

	if (device->fs_devices != fs_info->fs_devices) {
		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
		if (device->generation !=
		    btrfs_device_generation(leaf, dev_item))
			return -EINVAL;
	}

	fill_device_from_item(leaf, dev_item, device);
	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
		device->fs_devices->total_rw_bytes += device->total_bytes;
		atomic64_add(device->total_bytes - device->bytes_used,
				&fs_info->free_chunk_space);
	}
	ret = 0;
	return ret;
}


static void check_exception(PowerPCCPU *cpu, sPAPREnvironment *spapr,

                            uint32_t token, uint32_t nargs,

                            target_ulong args,

                            uint32_t nret, target_ulong rets)

{

    uint32_t mask, buf, len, event_len;

    uint64_t xinfo;

    sPAPREventLogEntry *event;

    struct rtas_error_log *hdr;

    if ((nargs < 6) || (nargs > 7) || nret != 1) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    xinfo = rtas_ld(args, 1);

    mask = rtas_ld(args, 2);

    buf = rtas_ld(args, 4);

    len = rtas_ld(args, 5);

    if (nargs == 7) {

        xinfo |= (uint64_t)rtas_ld(args, 6) << 32;

    }

    event = rtas_event_log_dequeue(mask);

    if (!event) {

        goto out_no_events;

    }

    hdr = event->data;

    event_len = be32_to_cpu(hdr->extended_length) + sizeof(*hdr);

    if (event_len < len) {

        len = event_len;

    }

    cpu_physical_memory_write(buf, event->data, len);

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

    g_free(event->data);

    g_free(event);

    /* according to PAPR+, the IRQ must be left asserted, or re-asserted, if

     * there are still pending events to be fetched via check-exception. We

     * do the latter here, since our code relies on edge-triggered

     * interrupts.

     */

    if (rtas_event_log_contains(mask)) {

        qemu_irq_pulse(xics_get_qirq(spapr->icp, spapr->check_exception_irq));

    }

    return;

out_no_events:

    rtas_st(rets, 0, RTAS_OUT_NO_ERRORS_FOUND);

}


static bool bf_is_ampdu_not_probing(struct ath_buf *bf)
{
    struct ieee80211_tx_info *info = IEEE80211_SKB_CB(bf->bf_mpdu);
    return bf_isampdu(bf) && !(info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE);
}


bool NPJSObject::hasMethod(NPIdentifier methodName)
{
    IdentifierRep* identifierRep = static_cast<IdentifierRep*>(methodName);

    if (!identifierRep->isString())
        return false;

    ExecState* exec = m_objectMap->globalExec();
    if (!exec)
        return false;

    JSLock lock(SilenceAssertionsOnly);

    JSValue value = m_jsObject->get(exec, identifierFromIdentifierRep(exec, identifierRep));
    exec->clearException();

    CallData callData;
    return getCallData(value, callData) != CallTypeNone;
}


void hmp_info_cpus(Monitor *mon, const QDict *qdict)

{

    CpuInfoList *cpu_list, *cpu;

    cpu_list = qmp_query_cpus(NULL);

    for (cpu = cpu_list; cpu; cpu = cpu->next) {

        int active = ' ';

        if (cpu->value->CPU == monitor_get_cpu_index()) {

            active = '*';

        }

        monitor_printf(mon, "%c CPU #%" PRId64 ":", active, cpu->value->CPU);

        switch (cpu->value->arch) {

        case CPU_INFO_ARCH_X86:

            monitor_printf(mon, " pc=0x%016" PRIx64, cpu->value->u.x86->pc);

            break;

        case CPU_INFO_ARCH_PPC:

            monitor_printf(mon, " nip=0x%016" PRIx64, cpu->value->u.ppc->nip);

            break;

        case CPU_INFO_ARCH_SPARC:

            monitor_printf(mon, " pc=0x%016" PRIx64,

                           cpu->value->u.q_sparc->pc);

            monitor_printf(mon, " npc=0x%016" PRIx64,

                           cpu->value->u.q_sparc->npc);

            break;

        case CPU_INFO_ARCH_MIPS:

            monitor_printf(mon, " PC=0x%016" PRIx64, cpu->value->u.q_mips->PC);

            break;

        case CPU_INFO_ARCH_TRICORE:

            monitor_printf(mon, " PC=0x%016" PRIx64, cpu->value->u.tricore->PC);

            break;

        default:

            break;

        }

        if (cpu->value->halted) {

            monitor_printf(mon, " (halted)");

        }

        monitor_printf(mon, " thread_id=%" PRId64 "\n", cpu->value->thread_id);

    }

    qapi_free_CpuInfoList(cpu_list);

}


static __inline USHORT CalculateIpv6PseudoHeaderChecksum(IPv6Header *pIpHeader, USHORT headerAndPayloadLen)
{
    tIPv6PseudoHeader ipph;
    USHORT checksum;
    ipph.ipph_src[0]  = pIpHeader->ip6_src_address[0];
    ipph.ipph_src[1]  = pIpHeader->ip6_src_address[1];
    ipph.ipph_src[2]  = pIpHeader->ip6_src_address[2];
    ipph.ipph_src[3]  = pIpHeader->ip6_src_address[3];
    ipph.ipph_dest[0] = pIpHeader->ip6_dst_address[0];
    ipph.ipph_dest[1] = pIpHeader->ip6_dst_address[1];
    ipph.ipph_dest[2] = pIpHeader->ip6_dst_address[2];
    ipph.ipph_dest[3] = pIpHeader->ip6_dst_address[3];
    ipph.z1 = ipph.z2 = ipph.z3 = 0;
    ipph.ipph_protocol = pIpHeader->ip6_next_header;
    ipph.ipph_length = swap_short(headerAndPayloadLen);
    checksum = CheckSumCalculatorFlat(&ipph, sizeof(ipph));
    return ~checksum;
}


static void floatArrayAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
    TestObjectPythonV8Internal::floatArrayAttributeAttributeGetter(info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


static int parse_bss_select(struct nlattr *nla, struct wiphy *wiphy,
			    struct cfg80211_bss_selection *bss_select)
{
	struct nlattr *attr[NL80211_BSS_SELECT_ATTR_MAX + 1];
	struct nlattr *nest;
	int err;
	bool found = false;
	int i;

	/* only process one nested attribute */
	nest = nla_data(nla);
	if (!nla_ok(nest, nla_len(nest)))
		return -EINVAL;

	err = nla_parse_nested_deprecated(attr, NL80211_BSS_SELECT_ATTR_MAX,
					  nest, nl80211_bss_select_policy,
					  NULL);
	if (err)
		return err;

	/* only one attribute may be given */
	for (i = 0; i <= NL80211_BSS_SELECT_ATTR_MAX; i++) {
		if (attr[i]) {
			if (found)
				return -EINVAL;
			found = true;
		}
	}

	bss_select->behaviour = __NL80211_BSS_SELECT_ATTR_INVALID;

	if (attr[NL80211_BSS_SELECT_ATTR_RSSI])
		bss_select->behaviour = NL80211_BSS_SELECT_ATTR_RSSI;

	if (attr[NL80211_BSS_SELECT_ATTR_BAND_PREF]) {
		bss_select->behaviour = NL80211_BSS_SELECT_ATTR_BAND_PREF;
		bss_select->param.band_pref =
			nla_get_u32(attr[NL80211_BSS_SELECT_ATTR_BAND_PREF]);
		if (!is_band_valid(wiphy, bss_select->param.band_pref))
			return -EINVAL;
	}

	if (attr[NL80211_BSS_SELECT_ATTR_RSSI_ADJUST]) {
		struct nl80211_bss_select_rssi_adjust *adj_param;

		adj_param = nla_data(attr[NL80211_BSS_SELECT_ATTR_RSSI_ADJUST]);
		bss_select->behaviour = NL80211_BSS_SELECT_ATTR_RSSI_ADJUST;
		bss_select->param.adjust.band = adj_param->band;
		bss_select->param.adjust.delta = adj_param->delta;
		if (!is_band_valid(wiphy, bss_select->param.adjust.band))
			return -EINVAL;
	}

	/* user-space did not provide behaviour attribute */
	if (bss_select->behaviour == __NL80211_BSS_SELECT_ATTR_INVALID)
		return -EINVAL;

	if (!(wiphy->bss_select_support & BIT(bss_select->behaviour)))
		return -EINVAL;

	return 0;
}


path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path)
{
	const char *s = path_init(nd, flags);
	int err;

	while (!(err = link_path_walk(s, nd)) &&
		(err = lookup_last(nd)) > 0) {
		s = trailing_symlink(nd);
	}
	if (!err && (nd->flags & LOOKUP_RCU))
		err = unlazy_walk(nd);
	if (!err)
		err = handle_lookup_down(nd);
	if (!err) {
		*path = nd->path;
		nd->path.mnt = NULL;
		nd->path.dentry = NULL;
	}
	terminate_walk(nd);
	return err;
}


static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
{
	int i;

	for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
		if (ffs->eps_addrmap[i] == endpoint_address)
			return i;
	return -ENOENT;
}


static inline RefPtr<DocumentFragment> createFragmentFromSource(const String& sourceString, const String& sourceMIMEType, Document* outputDoc)
{
    RefPtr<DocumentFragment> fragment = outputDoc->createDocumentFragment();
    if (sourceMIMEType == "text/html") {
        RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc);
        fragment->parseHTML(sourceString, fakeBody.get());
    } else if (sourceMIMEType == "text/plain")
        fragment->parserAddChild(Text::create(outputDoc, sourceString));
    else {
        bool successfulParse = fragment->parseXML(sourceString, 0);
        if (!successfulParse)
            return 0;
    }
    return fragment;
}


static u32 tcp_v6_init_seq(const struct sk_buff *skb)
{
	return secure_tcpv6_seq(ipv6_hdr(skb)->daddr.s6_addr32,
				ipv6_hdr(skb)->saddr.s6_addr32,
				tcp_hdr(skb)->dest,
				tcp_hdr(skb)->source);
}


do_PrefetchAbort(unsigned long addr, unsigned int ifsr, struct pt_regs *regs)
{
	const struct fsr_info *inf = ifsr_info + fsr_fs(ifsr);
	struct siginfo info;

	if (!inf->fn(addr, ifsr | FSR_LNX_PF, regs))
		return;

	printk(KERN_ALERT "Unhandled prefetch abort: %s (0x%03x) at 0x%08lx\n",
		inf->name, ifsr, addr);

	info.si_signo = inf->sig;
	info.si_errno = 0;
	info.si_code  = inf->code;
	info.si_addr  = (void __user *)addr;
	arm_notify_die("", regs, &info, ifsr, 0);
}


bool WebGL2RenderingContextBase::ValidateBufferTarget(const char* function_name,
                                                      GLenum target) {
  switch (target) {
    case GL_ARRAY_BUFFER:
    case GL_COPY_READ_BUFFER:
    case GL_COPY_WRITE_BUFFER:
    case GL_ELEMENT_ARRAY_BUFFER:
    case GL_PIXEL_PACK_BUFFER:
    case GL_PIXEL_UNPACK_BUFFER:
    case GL_TRANSFORM_FEEDBACK_BUFFER:
    case GL_UNIFORM_BUFFER:
      return true;
    default:
      SynthesizeGLError(GL_INVALID_ENUM, function_name, "invalid target");
      return false;
  }
}


static uint32_t rtl8139_io_readl(void *opaque, uint8_t addr)

{

    RTL8139State *s = opaque;

    uint32_t ret;

    switch (addr)

    {

        case RxMissed:

            ret = s->RxMissed;

            DPRINTF("RxMissed read val=0x%08x\n", ret);

            break;

        case TxConfig:

            ret = rtl8139_TxConfig_read(s);

            break;

        case RxConfig:

            ret = rtl8139_RxConfig_read(s);

            break;

        case TxStatus0 ... TxStatus0+4*4-1:

            ret = rtl8139_TxStatus_read(s, addr, 4);

            break;

        case TxAddr0 ... TxAddr0+4*4-1:

            ret = rtl8139_TxAddr_read(s, addr-TxAddr0);

            break;

        case RxBuf:

            ret = rtl8139_RxBuf_read(s);

            break;

        case RxRingAddrLO:

            ret = s->RxRingAddrLO;

            DPRINTF("C+ RxRing low bits read val=0x%08x\n", ret);

            break;

        case RxRingAddrHI:

            ret = s->RxRingAddrHI;

            DPRINTF("C+ RxRing high bits read val=0x%08x\n", ret);

            break;

        case Timer:

            ret = muldiv64(qemu_get_clock_ns(vm_clock) - s->TCTR_base,

                           PCI_FREQUENCY, get_ticks_per_sec());

            DPRINTF("TCTR Timer read val=0x%08x\n", ret);

            break;

        case FlashReg:

            ret = s->TimerInt;

            DPRINTF("FlashReg TimerInt read val=0x%08x\n", ret);

            break;

        default:

            DPRINTF("ioport read(l) addr=0x%x via read(b)\n", addr);

            ret  = rtl8139_io_readb(opaque, addr);

            ret |= rtl8139_io_readb(opaque, addr + 1) << 8;

            ret |= rtl8139_io_readb(opaque, addr + 2) << 16;

            ret |= rtl8139_io_readb(opaque, addr + 3) << 24;

            DPRINTF("read(l) addr=0x%x val=%08x\n", addr, ret);

            break;

    }

    return ret;

}


static void migrate_check_parameter(QTestState *who, const char *parameter,

                                    const char *value)

{

    QDict *rsp, *rsp_return;

    const char *result;

    rsp = wait_command(who, "{ 'execute': 'query-migrate-parameters' }");

    rsp_return = qdict_get_qdict(rsp, "return");

    result = g_strdup_printf("%" PRId64,

                             qdict_get_try_int(rsp_return,  parameter, -1));

    g_assert_cmpstr(result, ==, value);

    QDECREF(rsp);

}


std::string base_name(const std::string& file)
// Analogous to POSIX basename(3), but for C++ string-object pathnames
{
#ifdef _WIN32
	static const std::string dir_separators = "\\/:";
#else
	static const std::string dir_separators = "/";
#endif

	std::string::size_type pos = file.find_last_of(dir_separators);

	if(pos == std::string::npos)
		return file;
	if(pos >= file.size()-1)
		return "";

	return file.substr(pos+1);
}


static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
{
	return LIBUSB_ERROR_NOT_SUPPORTED;
}


int stream_int_check_timeouts(struct stream_interface *si)
{
	if (tick_is_expired(si->exp, now_ms)) {
		si->flags |= SI_FL_EXP;
		return 1;
	}
	return 0;
}


MagickExport char *CanonicalXMLContent(const char *content,
  const MagickBooleanType pedantic)
{
  char
    *base64,
    *canonical_content;

  register const unsigned char
    *p;

  register ssize_t
    i;

  size_t
    extent,
    length;

  unsigned char
    *utf8;

  utf8=ConvertLatin1ToUTF8((const unsigned char *) content);
  if (utf8 == (unsigned char *) NULL)
    return((char *) NULL);
  for (p=utf8; *p != '\0'; p++)
    if ((*p < 0x20) && (*p != 0x09) && (*p != 0x0a) && (*p != 0x0d))
      break;
  if (*p != '\0')
    {
      /*
        String is binary, base64-encode it.
      */
      base64=Base64Encode(utf8,strlen((char *) utf8),&length);
      utf8=(unsigned char *) RelinquishMagickMemory(utf8);
      if (base64 == (char *) NULL)
        return((char *) NULL);
      canonical_content=AcquireString("<base64>");
      (void) ConcatenateString(&canonical_content,base64);
      base64=DestroyString(base64);
      (void) ConcatenateString(&canonical_content,"</base64>");
      return(canonical_content);
    }
  /*
    Substitute predefined entities.
  */
  i=0;
  canonical_content=AcquireString((char *) NULL);
  extent=MaxTextExtent;
  for (p=utf8; *p != '\0'; p++)
  {
    if ((i+MaxTextExtent) > (ssize_t) extent)
      {
        extent+=MaxTextExtent;
        canonical_content=(char *) ResizeQuantumMemory(canonical_content,extent,
          sizeof(*canonical_content));
        if (canonical_content == (char *) NULL)
          return(canonical_content);
      }
    switch (*p)
    {
      case '&':
      {
        i+=FormatLocaleString(canonical_content+i,extent,"&");
        break;
      }
      case '<':
      {
        i+=FormatLocaleString(canonical_content+i,extent,"<");
        break;
      }
      case '>':
      {
        i+=FormatLocaleString(canonical_content+i,extent,">");
        break;
      }
      case '"':
      {
        i+=FormatLocaleString(canonical_content+i,extent,""");
        break;
      }
      case '\n':
      {
        if (pedantic == MagickFalse)
          {
            canonical_content[i++]=(char) (*p);
            break;
          }
        i+=FormatLocaleString(canonical_content+i,extent,"
");
        break;
      }
      case '\t':
      {
        if (pedantic == MagickFalse)
          {
            canonical_content[i++]=(char) (*p);
            break;
          }
        i+=FormatLocaleString(canonical_content+i,extent,"	");
        break;
      }
      case '\r':
      {
        i+=FormatLocaleString(canonical_content+i,extent,"
");
        break;
      }
      default:
      {
        canonical_content[i++]=(char) (*p);
        break;
      }
    }
  }
  canonical_content[i]='\0';
  utf8=(unsigned char *) RelinquishMagickMemory(utf8);
  return(canonical_content);
}


static void H_Update(HMAC_CTX *ctx, uint8_t const *data, int len)
{
	HMAC_Update(ctx, data, len);
}


void numa_default_policy(void)
{
	do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
}


static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
                                  QEMUCursor *c)
{
    VncDisplay *vd = vnc_display;
    VncState *vs;

    cursor_put(vd->cursor);
    g_free(vd->cursor_mask);

    vd->cursor = c;
    cursor_get(vd->cursor);
    vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
    vd->cursor_mask = g_malloc0(vd->cursor_msize);
    cursor_get_mono_mask(c, 0, vd->cursor_mask);

    QTAILQ_FOREACH(vs, &vd->clients, next) {
        vnc_cursor_define(vs);
    }
}


absl::Status ParseInputsWithConstTensor(Node* node, ObjectReader* reader,
                                        TensorOrScalar* tensor_or_scalar) {
  const std::string& opname = node->operation.type;

  // Determine runtime/constant tensors.
  const TfLiteTensor* input0 = reader->GetInputTensor(0);
  if (!input0) {
    return absl::InvalidArgumentError("Couldn't get the 1st input tensor for " +
                                      opname);
  }
  const TfLiteTensor* input1 = reader->GetInputTensor(1);
  if (!input1) {
    return absl::InvalidArgumentError("Couldn't get the 2nd input tensor for " +
                                      opname);
  }
  const bool constant_tensor0 = IsConstantTensor(input0);
  const bool constant_tensor1 = IsConstantTensor(input1);
  if (constant_tensor0 && constant_tensor1) {
    return absl::InvalidArgumentError("No runtime input tensors for " + opname);
  }
  const bool runtime_tensor0 = !constant_tensor0;
  const bool runtime_tensor1 = !constant_tensor1;

  if (runtime_tensor0 && runtime_tensor1) {
    RETURN_IF_ERROR(reader->AddInput(node, 0));
    RETURN_IF_ERROR(reader->AddInput(node, 1));
  } else {
    int runtime_tensor = 0;
    int constant_tensor = 1;
    TfLiteIntArray* constant_dims = input1->dims;
    if (constant_tensor0 && runtime_tensor1) {
      runtime_tensor = 1;
      constant_tensor = 0;
      constant_dims = input0->dims;
    }
    RETURN_IF_ERROR(reader->AddInput(node, runtime_tensor));
    if (constant_dims->size <= 0 || NumElements(constant_dims) == 1) {
      Tensor<Scalar, DataType::FLOAT32> tensor;
      RETURN_IF_ERROR(reader->ReadTensor(constant_tensor, &tensor));
      *tensor_or_scalar = tensor.data[0];
    } else {
      if (CheckIfLinearConvertible(constant_dims).ok()) {
        Tensor<Linear, DataType::FLOAT32> tensor;
        RETURN_IF_ERROR(reader->ReadTensor(constant_tensor, &tensor));
        *tensor_or_scalar = std::move(tensor);
      } else {
        Tensor<HWC, DataType::FLOAT32> tensor;
        RETURN_IF_ERROR(reader->ReadTensor(constant_tensor, &tensor));
        *tensor_or_scalar = std::move(tensor);
      }
    }
  }
  return absl::OkStatus();
}


static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file)
{
	return single_open(file, rfcomm_sock_debugfs_show, inode->i_private);
}


void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, FrameLoadType frameLoadType, HistoryLoadType historyLoadType, ClientRedirectPolicy clientRedirect, Document* initiatingDocument)
{
    ASSERT(!stateObject || frameLoadType == FrameLoadTypeBackForward);

    detachDocumentLoader(m_provisionalDocumentLoader);
    if (!m_frame->host())
        return;
    TemporaryChange<FrameLoadType> loadTypeChange(m_loadType, frameLoadType);
    saveScrollState();

    KURL oldURL = m_frame->document()->url();
    bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
    if (hashChange) {
        m_frame->eventHandler().stopAutoscroll();
        m_frame->localDOMWindow()->enqueueHashchangeEvent(oldURL, url);
    }
    m_documentLoader->setIsClientRedirect(clientRedirect == ClientRedirectPolicy::ClientRedirect);
    updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, nullptr, ScrollRestorationAuto, frameLoadType, initiatingDocument);

    m_documentLoader->initialScrollState().wasScrolledByUser = false;

    checkCompleted();

    m_frame->localDOMWindow()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());

    if (historyLoadType == HistorySameDocumentLoad)
        restoreScrollPositionAndViewState();

    processFragment(url, NavigationWithinSameDocument);
    takeObjectSnapshot();
}


 status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) {
    return BasicClient::dump(fd, args);
}

status_t CameraDeviceClient::dumpClient(int fd, const Vector<String16>& args) {
     String8 result;
     result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n",
             mCameraId,
            getRemoteCallback()->asBinder().get(),
            mClientPid);
    result.append("  State: ");

    mFrameProcessor->dump(fd, args);

 return dumpDevice(fd, args);
}


ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async)
{
    const node * const n = is_async ? CHILD(n0, 1) : n0;
    int i, n_items, nch_minus_type, has_type_comment;
    asdl_seq *items, *body;
    string type_comment;

    if (is_async && c->c_feature_version < 5) {
        ast_error(c, n,
                "Async with statements are only supported in Python 3.5 and greater");
        return NULL;
    }

    REQ(n, with_stmt);

    has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT;
    nch_minus_type = NCH(n) - has_type_comment;

    n_items = (nch_minus_type - 2) / 2;
    items = _Ta3_asdl_seq_new(n_items, c->c_arena);
    if (!items)
        return NULL;
    for (i = 1; i < nch_minus_type - 2; i += 2) {
        withitem_ty item = ast_for_with_item(c, CHILD(n, i));
        if (!item)
            return NULL;
        asdl_seq_SET(items, (i - 1) / 2, item);
    }

    body = ast_for_suite(c, CHILD(n, NCH(n) - 1));
    if (!body)
        return NULL;

    if (has_type_comment) {
        type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2));
        if (!type_comment)
            return NULL;
    }
    else
        type_comment = NULL;

    if (is_async)
        return AsyncWith(items, body, type_comment, LINENO(n0), n0->n_col_offset, c->c_arena);
    else
        return With(items, body, type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}


static void i40e_send_version(struct i40e_pf *pf)
{
	struct i40e_driver_version dv;

	dv.major_version = DRV_VERSION_MAJOR;
	dv.minor_version = DRV_VERSION_MINOR;
	dv.build_version = DRV_VERSION_BUILD;
	dv.subbuild_version = 0;
	strlcpy(dv.driver_string, DRV_VERSION, sizeof(dv.driver_string));
	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
}


MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
                                MemTxAttrs attrs,
                                const void *buf, hwaddr len)
{
    MemTxResult result = MEMTX_OK;
    FlatView *fv;

    if (len > 0) {
        fv = address_space_to_flatview(as);
        result = flatview_write(as->uc, fv, addr, attrs, buf, len);
    }

    return result;
}


FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
{
	FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
	FLAC__int32 x, *residual = decoder->private_->residual[channel];
 unsigned i;

	decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;

	subframe->data = residual;

 for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
 if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
 return false; /* read_callback_ sets the state for us */
		residual[i] = x;
 }

 /* decode the subframe */
 if(do_full_decode)
		memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);

 return true;
}


static int timer_coldplug(Unit *u) {
        Timer *t = TIMER(u);

        assert(t);
        assert(t->state == TIMER_DEAD);

        if (t->deserialized_state != t->state) {

                if (t->deserialized_state == TIMER_WAITING)
                        timer_enter_waiting(t, false);
                else
                        timer_set_state(t, t->deserialized_state);
        }

        return 0;
}


void ExtensionViewGuest::ApplyAttributes(const base::DictionaryValue& params) {
  std::string src;
  params.GetString(extensionview::kAttributeSrc, &src);
  NavigateGuest(src, false /* force_navigation */);
}


void SelectRightNameType(const ServerFieldTypeSet& old_types,
                         ServerFieldTypeSet* new_types,
                         bool is_credit_card) {
  ServerFieldTypeSet upload_types;
  if (old_types.count(NAME_FIRST) && old_types.count(CREDIT_CARD_NAME_FIRST)) {
    if (is_credit_card) {
      new_types->insert(CREDIT_CARD_NAME_FIRST);
    } else {
      new_types->insert(NAME_FIRST);
    }
  } else if (old_types.count(NAME_LAST) &&
             old_types.count(CREDIT_CARD_NAME_LAST)) {
    if (is_credit_card) {
      new_types->insert(CREDIT_CARD_NAME_LAST);
    } else {
      new_types->insert(NAME_LAST);
    }
  } else if (old_types.count(NAME_FULL) &&
             old_types.count(CREDIT_CARD_NAME_FULL)) {
    if (is_credit_card) {
      new_types->insert(CREDIT_CARD_NAME_FULL);
    } else {
      new_types->insert(NAME_FULL);
    }
  } else {
    *new_types = old_types;
  }
}


static inline void gen_op_mulscc(TCGv dst, TCGv src1, TCGv src2)

{

    TCGv r_temp, zero;

    r_temp = tcg_temp_new();

    /* old op:

    if (!(env->y & 1))

        T1 = 0;

    */

    zero = tcg_const_tl(0);

    tcg_gen_andi_tl(cpu_cc_src, src1, 0xffffffff);

    tcg_gen_andi_tl(r_temp, cpu_y, 0x1);

    tcg_gen_andi_tl(cpu_cc_src2, src2, 0xffffffff);

    tcg_gen_movcond_tl(TCG_COND_EQ, cpu_cc_src2, r_temp, zero,

                       zero, cpu_cc_src2);

    tcg_temp_free(zero);

    // b2 = T0 & 1;

    // env->y = (b2 << 31) | (env->y >> 1);

    tcg_gen_andi_tl(r_temp, cpu_cc_src, 0x1);

    tcg_gen_shli_tl(r_temp, r_temp, 31);

    tcg_gen_shri_tl(cpu_tmp0, cpu_y, 1);

    tcg_gen_andi_tl(cpu_tmp0, cpu_tmp0, 0x7fffffff);

    tcg_gen_or_tl(cpu_tmp0, cpu_tmp0, r_temp);

    tcg_gen_andi_tl(cpu_y, cpu_tmp0, 0xffffffff);

    // b1 = N ^ V;

    gen_mov_reg_N(cpu_tmp0, cpu_psr);

    gen_mov_reg_V(r_temp, cpu_psr);

    tcg_gen_xor_tl(cpu_tmp0, cpu_tmp0, r_temp);

    tcg_temp_free(r_temp);

    // T0 = (b1 << 31) | (T0 >> 1);

    // src1 = T0;

    tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, 31);

    tcg_gen_shri_tl(cpu_cc_src, cpu_cc_src, 1);

    tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_tmp0);

    tcg_gen_add_tl(cpu_cc_dst, cpu_cc_src, cpu_cc_src2);

    tcg_gen_mov_tl(dst, cpu_cc_dst);

}


static int filter_frame(AVFilterLink *inlink, AVFrame *frame)

{

    AVFilterContext *ctx = inlink->dst;

    AudioEchoContext *s = ctx->priv;

    AVFrame *out_frame;

    if (av_frame_is_writable(frame)) {

        out_frame = frame;

    } else {

        out_frame = ff_get_audio_buffer(inlink, frame->nb_samples);

        if (!out_frame)

            return AVERROR(ENOMEM);

        av_frame_copy_props(out_frame, frame);

    }

    s->echo_samples(s, s->delayptrs, frame->extended_data, out_frame->extended_data,

                    frame->nb_samples, inlink->channels);

    s->next_pts = frame->pts + av_rescale_q(frame->nb_samples, (AVRational){1, inlink->sample_rate}, inlink->time_base);

    if (frame != out_frame)

        av_frame_free(&frame);

    return ff_filter_frame(ctx->outputs[0], out_frame);

}


static void load_defaults(struct btd_adapter *adapter)
{
	struct mgmt_tlv_list *list;
	unsigned int err = 0;

	if (!btd_opts.defaults.num_entries ||
	    !btd_has_kernel_features(KERNEL_SET_SYSTEM_CONFIG))
		return;

	list = mgmt_tlv_list_new();

	if (!load_bredr_defaults(adapter, list, &btd_opts.defaults.br))
		goto done;

	if (!load_le_defaults(adapter, list, &btd_opts.defaults.le))
		goto done;

	err = mgmt_send_tlv(adapter->mgmt, MGMT_OP_SET_DEF_SYSTEM_CONFIG,
			adapter->dev_id, list, NULL, NULL, NULL);

done:
	if (!err)
		btd_error(adapter->dev_id,
				"Failed to set default system config for hci%u",
				adapter->dev_id);

	mgmt_tlv_list_free(list);
}


NOEXPORT int options_file(char *path, CONF_TYPE type,
        SERVICE_OPTIONS **section_ptr) {
    DISK_FILE *df;
    char line_text[CONFLINELEN], *errstr;
    char config_line[CONFLINELEN], *config_opt, *config_arg;
    int i, line_number=0;
#ifndef USE_WIN32
    int fd;
    char *tmp_str;
#endif

    s_log(LOG_NOTICE, "Reading configuration from %s %s",
        type==CONF_FD ? "descriptor" : "file", path);
#ifndef USE_WIN32
    if(type==CONF_FD) { /* file descriptor */
        fd=(int)strtol(path, &tmp_str, 10);
        if(tmp_str==path || *tmp_str) { /* not a number */
            s_log(LOG_ERR, "Invalid file descriptor number");
            print_syntax();
            return 1;
        }
        df=file_fdopen(fd);
    } else
#endif
        df=file_open(path, FILE_MODE_READ);
    if(!df) {
        s_log(LOG_ERR, "Cannot open configuration file");
        if(type!=CONF_RELOAD)
            print_syntax();
        return 1;
    }

    while(file_getline(df, line_text, CONFLINELEN)>=0) {
        memcpy(config_line, line_text, CONFLINELEN);
        ++line_number;
        config_opt=config_line;
        if(line_number==1) {
            if(config_opt[0]==(char)0xef &&
                    config_opt[1]==(char)0xbb &&
                    config_opt[2]==(char)0xbf) {
                s_log(LOG_NOTICE, "UTF-8 byte order mark detected");
                config_opt+=3;
            } else {
                s_log(LOG_NOTICE, "UTF-8 byte order mark not detected");
            }
        }

        while(isspace((unsigned char)*config_opt))
            ++config_opt; /* remove initial whitespaces */
        for(i=(int)strlen(config_opt)-1; i>=0 && isspace((unsigned char)config_opt[i]); --i)
            config_opt[i]='\0'; /* remove trailing whitespaces */
        if(config_opt[0]=='\0' || config_opt[0]=='#' || config_opt[0]==';') /* empty or comment */
            continue;

        if(config_opt[0]=='[' && config_opt[strlen(config_opt)-1]==']') { /* new section */
            if(init_section(0, section_ptr)) {
                file_close(df);
                return 1;
            }

            /* append a new SERVICE_OPTIONS structure to the list */
            {
                SERVICE_OPTIONS *new_section;
                new_section=str_alloc_detached(sizeof(SERVICE_OPTIONS));
                new_section->next=NULL;
                (*section_ptr)->next=new_section;
                *section_ptr=new_section;
            }

            /* initialize the newly allocated section */
            ++config_opt;
            config_opt[strlen(config_opt)-1]='\0';
            (*section_ptr)->servname=str_dup_detached(config_opt);
            (*section_ptr)->session=NULL;
            parse_service_option(CMD_SET_COPY, section_ptr, NULL, NULL);
            continue;
        }

        config_arg=strchr(config_line, '=');
        if(!config_arg) {
            s_log(LOG_ERR, "%s:%d: \"%s\": No '=' found",
                path, line_number, line_text);
            file_close(df);
            return 1;
        }
        *config_arg++='\0'; /* split into option name and argument value */
        for(i=(int)strlen(config_opt)-1; i>=0 && isspace((unsigned char)config_opt[i]); --i)
            config_opt[i]='\0'; /* remove trailing whitespaces */
        while(isspace((unsigned char)*config_arg))
            ++config_arg; /* remove initial whitespaces */

        errstr=option_not_found;
        /* try global options first (e.g. for 'debug') */
        if(!new_service_options.next)
            errstr=parse_global_option(CMD_SET_VALUE, &new_global_options, config_opt, config_arg);
        if(errstr==option_not_found)
            errstr=parse_service_option(CMD_SET_VALUE, section_ptr, config_opt, config_arg);
        if(errstr) {
            s_log(LOG_ERR, "%s:%d: \"%s\": %s",
                path, line_number, line_text, errstr);
            file_close(df);
            return 1;
        }
    }
    file_close(df);
    return 0;
}


  bool WouldExceedMemoryLimit(std::size_t bytes) const {
    return bytes + current_bytes_ > memory_limit_;
  }


int kernel_recvmsg(struct socket *sock, struct msghdr *msg,
		   struct kvec *vec, size_t num, size_t size, int flags)
{
	mm_segment_t oldfs = get_fs();
	int result;

	set_fs(KERNEL_DS);
	/*
	 * the following is safe, since for compiler definitions of kvec and
	 * iovec are identical, yielding the same in-core layout and alignment
	 */
	iov_iter_init(&msg->msg_iter, READ, (struct iovec *)vec, num, size);
	result = sock_recvmsg(sock, msg, size, flags);
	set_fs(oldfs);
	return result;
}


static int32_t BindFrameWrapper(
 void *userData, int32_t index, uint8_t **yuv) {
 SoftAVCEncoder *encoder = static_cast<SoftAVCEncoder *>(userData);
    CHECK(encoder != NULL);
 return encoder->bindOutputBuffer(index, yuv);
}


static void my_init_destination_fn(j_compress_ptr cinfo)
{
	struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;

	// Configure the destination manager to use our buffer.
	wctx->pub.next_output_byte = wctx->buffer;
	wctx->pub.free_in_buffer = wctx->buffer_len;
}


static void print_lat_help_header(struct seq_file *m)
{
	seq_puts(m, "#                  _------=> CPU#            \n"
		    "#                 / _-----=> irqs-off        \n"
		    "#                | / _----=> need-resched    \n"
		    "#                || / _---=> hardirq/softirq \n"
		    "#                ||| / _--=> preempt-depth   \n"
		    "#                |||| /     delay            \n"
		    "#  cmd     pid   ||||| time  |   caller      \n"
		    "#     \\   /      |||||  \\    |   /         \n");
}


static void bus_detach_inotify_event(sd_bus *bus) {
        assert(bus);

        if (bus->inotify_event_source) {
                sd_event_source_set_enabled(bus->inotify_event_source, SD_EVENT_OFF);
                bus->inotify_event_source = sd_event_source_unref(bus->inotify_event_source);
        }
}


_PyMemoTable_ResizeTable(PyMemoTable *self, size_t min_size)
{
    PyMemoEntry *oldtable = NULL;
    PyMemoEntry *oldentry, *newentry;
    size_t new_size = MT_MINSIZE;
    size_t to_process;

    assert(min_size > 0);

    if (min_size > PY_SSIZE_T_MAX) {
        PyErr_NoMemory();
        return -1;
    }

    /* Find the smallest valid table size >= min_size. */
    while (new_size < min_size) {
        new_size <<= 1;
    }
    /* new_size needs to be a power of two. */
    assert((new_size & (new_size - 1)) == 0);

    /* Allocate new table. */
    oldtable = self->mt_table;
    self->mt_table = PyMem_NEW(PyMemoEntry, new_size);
    if (self->mt_table == NULL) {
        self->mt_table = oldtable;
        PyErr_NoMemory();
        return -1;
    }
    self->mt_allocated = new_size;
    self->mt_mask = new_size - 1;
    memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size);

    /* Copy entries from the old table. */
    to_process = self->mt_used;
    for (oldentry = oldtable; to_process > 0; oldentry++) {
        if (oldentry->me_key != NULL) {
            to_process--;
            /* newentry is a pointer to a chunk of the new
               mt_table, so we're setting the key:value pair
               in-place. */
            newentry = _PyMemoTable_Lookup(self, oldentry->me_key);
            newentry->me_key = oldentry->me_key;
            newentry->me_value = oldentry->me_value;
        }
    }

    /* Deallocate the old table. */
    PyMem_FREE(oldtable);
    return 0;
}


btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans,
			    struct btrfs_root *root,
			    struct btrfs_path *path, u64 dir,
			    u64 objectid, const char *name, int name_len,
			    int mod)
{
	int ret;
	struct btrfs_key key;
	int ins_len = mod < 0 ? -1 : 0;
	int cow = mod != 0;

	key.objectid = dir;
	key.type = BTRFS_DIR_INDEX_KEY;
	key.offset = objectid;

	ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow);
	if (ret < 0)
		return ERR_PTR(ret);
	if (ret > 0)
		return ERR_PTR(-ENOENT);
	return btrfs_match_dir_item_name(root, path, name, name_len);
}


static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size)

{

    const uint8_t *sizes = buf;

    int i;

    s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2);

    buf      += 3 * (s->num_coeff_partitions - 1);

    buf_size -= 3 * (s->num_coeff_partitions - 1);

    if (buf_size < 0)

        return -1;

    for (i = 0; i < s->num_coeff_partitions - 1; i++) {

        int size = AV_RL24(sizes + 3 * i);

        if (buf_size - size < 0)

            return -1;

        ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size);

        buf      += size;

        buf_size -= size;

    }

    ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size);

    return 0;

}


static void main_get_appheader ( xd3_stream * stream , main_file * ifile , main_file * output , main_file * sfile ) {
 uint8_t * apphead ;
 usize_t appheadsz ;
 int ret ;
 if ( ! option_use_appheader ) {
 return ;
 }
 ret = xd3_get_appheader ( stream , & apphead , & appheadsz ) ;
 if ( ret != 0 ) {
 return ;
 }
 if ( appheadsz > 0 ) {
 char * start = ( char * ) apphead ;
 char * slash ;
 int place = 0 ;
 char * parsed [ 4 ] ;
 memset ( parsed , 0 , sizeof ( parsed ) ) ;
 while ( ( slash = strchr ( start , '/' ) ) != NULL ) {
 * slash = 0 ;
 parsed [ place ++ ] = start ;
 start = slash + 1 ;
 }
 parsed [ place ++ ] = start ;
 if ( place == 2 || place == 4 ) {
 main_get_appheader_params ( output , parsed , 1 , "output" , ifile ) ;
 }
 if ( place == 4 ) {
 main_get_appheader_params ( sfile , parsed + 2 , 0 , "source" , ifile ) ;
 }
 }
 option_use_appheader = 0 ;
 return ;
 }


clear_fd (gpointer data)
{
  int *fd_p = data;

  if (fd_p != NULL && *fd_p != -1)
    close (*fd_p);
}


SkColor Textfield::GetSelectionBackgroundColor() const {
  return use_default_selection_background_color_
             ? GetNativeTheme()->GetSystemColor(
                   ui::NativeTheme::
                       kColorId_TextfieldSelectionBackgroundFocused)
             : selection_background_color_;
}


static zend_long spl_ptr_llist_count(spl_ptr_llist *llist) /* {{{ */
{
	return (zend_long)llist->count;
}
/* }}} */


pkinit_decode_data_fs(krb5_context context,
                      pkinit_identity_crypto_context id_cryptoctx,
                      const uint8_t *data, unsigned int data_len,
                      uint8_t **decoded_data, unsigned int *decoded_data_len)
{
    X509 *cert = sk_X509_value(id_cryptoctx->my_certs,
                               id_cryptoctx->cert_index);
    EVP_PKEY *pkey = id_cryptoctx->my_key;
    uint8_t *buf;
    int buf_len, decrypt_len;

    *decoded_data = NULL;
    *decoded_data_len = 0;

    if (cert != NULL && !X509_check_private_key(cert, pkey)) {
        pkiDebug("private key does not match certificate\n");
        return KRB5KDC_ERR_PREAUTH_FAILED;
    }

    buf_len = EVP_PKEY_size(pkey);
    buf = malloc(buf_len + 10);
    if (buf == NULL)
        return KRB5KDC_ERR_PREAUTH_FAILED;

    decrypt_len = EVP_PKEY_decrypt_old(buf, data, data_len, pkey);
    if (decrypt_len <= 0) {
        pkiDebug("unable to decrypt received data (len=%d)\n", data_len);
        free(buf);
        return KRB5KDC_ERR_PREAUTH_FAILED;
    }

    *decoded_data = buf;
    *decoded_data_len = decrypt_len;
    return 0;
}


static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
{
	return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
}


Document& InputMethodController::GetDocument() const {
  DCHECK(IsAvailable());
  return *GetFrame().GetDocument();
}


static inline int pte_special(pte_t pte)
{
	return pte_flags(pte) & _PAGE_SPECIAL;
}


int RenderViewImpl::GetEnabledBindings() {
  return enabled_bindings_;
}


static struct device *tty_get_device(struct tty_struct *tty)
{
	dev_t devt = tty_devnum(tty);
	return class_find_device(tty_class, NULL, &devt, dev_match_devt);
}


PyObject* ast2obj_cmpop(cmpop_ty o)
{
    switch(o) {
        case Eq:
            Py_INCREF(Eq_singleton);
            return Eq_singleton;
        case NotEq:
            Py_INCREF(NotEq_singleton);
            return NotEq_singleton;
        case Lt:
            Py_INCREF(Lt_singleton);
            return Lt_singleton;
        case LtE:
            Py_INCREF(LtE_singleton);
            return LtE_singleton;
        case Gt:
            Py_INCREF(Gt_singleton);
            return Gt_singleton;
        case GtE:
            Py_INCREF(GtE_singleton);
            return GtE_singleton;
        case Is:
            Py_INCREF(Is_singleton);
            return Is_singleton;
        case IsNot:
            Py_INCREF(IsNot_singleton);
            return IsNot_singleton;
        case In:
            Py_INCREF(In_singleton);
            return In_singleton;
        case NotIn:
            Py_INCREF(NotIn_singleton);
            return NotIn_singleton;
        default:
            /* should never happen, but just in case ... */
            PyErr_Format(PyExc_SystemError, "unknown cmpop found");
            return NULL;
    }
}


void tb_flush(CPUState *cpu)
{
    unsigned tb_flush_count = cpu->uc->tcg_ctx->tb_ctx.tb_flush_count;
    do_tb_flush(cpu, RUN_ON_CPU_HOST_INT(tb_flush_count));
}


static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir,
				    unsigned int flags, bool *need_lookup)
{
	struct dentry *dentry;
	int error;

	*need_lookup = false;
	dentry = d_lookup(dir, name);
	if (dentry) {
		if (dentry->d_flags & DCACHE_OP_REVALIDATE) {
			error = d_revalidate(dentry, flags);
			if (unlikely(error <= 0)) {
				if (error < 0) {
					dput(dentry);
					return ERR_PTR(error);
				} else if (!d_invalidate(dentry)) {
					dput(dentry);
					dentry = NULL;
				}
			}
		}
	}

	if (!dentry) {
		dentry = d_alloc(dir, name);
		if (unlikely(!dentry))
			return ERR_PTR(-ENOMEM);

		*need_lookup = true;
	}
	return dentry;
}


static int read_tfra(MOVContext *mov, AVIOContext *f)
{
    MOVFragmentIndex* index = NULL;
    int version, fieldlength, i, j;
    int64_t pos = avio_tell(f);
    uint32_t size = avio_rb32(f);
    void *tmp;

    if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
        return 1;
    }
    av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
    index = av_mallocz(sizeof(MOVFragmentIndex));
    if (!index) {
        return AVERROR(ENOMEM);
    }

    tmp = av_realloc_array(mov->fragment_index_data,
                           mov->fragment_index_count + 1,
                           sizeof(MOVFragmentIndex*));
    if (!tmp) {
        av_freep(&index);
        return AVERROR(ENOMEM);
    }
    mov->fragment_index_data = tmp;
    mov->fragment_index_data[mov->fragment_index_count++] = index;

    version = avio_r8(f);
    avio_rb24(f);
    index->track_id = avio_rb32(f);
    fieldlength = avio_rb32(f);
    index->item_count = avio_rb32(f);
    index->items = av_mallocz_array(
            index->item_count, sizeof(MOVFragmentIndexItem));
    if (!index->items) {
        index->item_count = 0;
        return AVERROR(ENOMEM);
    }
    for (i = 0; i < index->item_count; i++) {
        int64_t time, offset;

        if (avio_feof(f)) {
            index->item_count = 0;
            av_freep(&index->items);
            return AVERROR_INVALIDDATA;
        }

        if (version == 1) {
            time   = avio_rb64(f);
            offset = avio_rb64(f);
        } else {
            time   = avio_rb32(f);
            offset = avio_rb32(f);
        }
        index->items[i].time = time;
        index->items[i].moof_offset = offset;
        for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
            avio_r8(f);
        for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
            avio_r8(f);
        for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
            avio_r8(f);
    }

    avio_seek(f, pos + size, SEEK_SET);
    return 0;
}


static void sco_chan_del(struct sock *sk, int err)
{
	struct sco_conn *conn;

	conn = sco_pi(sk)->conn;

	BT_DBG("sk %p, conn %p, err %d", sk, conn, err);

	if (conn) {
		sco_conn_lock(conn);
		conn->sk = NULL;
		sco_pi(sk)->conn = NULL;
		sco_conn_unlock(conn);

		if (conn->hcon)
			hci_conn_drop(conn->hcon);
	}

	sk->sk_state = BT_CLOSED;
	sk->sk_err   = err;
	sk->sk_state_change(sk);

	sock_set_flag(sk, SOCK_ZAPPED);
}


  void AddHost(AppCacheHost* host) {
    std::pair<NotifyHostMap::iterator , bool> ret = hosts_to_notify.insert(
        NotifyHostMap::value_type(host->frontend(), HostIds()));
    ret.first->second.push_back(host->host_id());
  }


bool FileSystemOperation::SetPendingOperationType(OperationType type) {
  if (pending_operation_ != kOperationNone)
    return false;
  pending_operation_ = type;
  return true;
}


static gboolean nbd_accept(QIOChannel *ioc, GIOCondition condition,

                           gpointer opaque)

{

    QIOChannelSocket *cioc;

    if (!nbd_server) {

        return FALSE;

    }

    cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),

                                     NULL);

    if (!cioc) {

        return TRUE;

    }

    qio_channel_set_name(QIO_CHANNEL(cioc), "nbd-server");

    nbd_client_new(NULL, cioc,

                   nbd_server->tlscreds, NULL,

                   nbd_client_put);

    object_unref(OBJECT(cioc));

    return TRUE;

}


R_API int r_bin_java_load_bin(RBinJavaObj *bin, const ut8 *buf, ut64 buf_sz) {
	ut64 adv = 0;
	R_BIN_JAVA_GLOBAL_BIN = bin;
	if (!bin) {
		return false;
	}
	r_bin_java_reset_bin_info (bin);
	memcpy ((ut8 *) &bin->cf, buf, 10);
	if (memcmp (bin->cf.cafebabe, "\xCA\xFE\xBA\xBE", 4)) {
		eprintf ("r_bin_java_new_bin: Invalid header (%02x %02x %02x %02x)\n",
			bin->cf.cafebabe[0], bin->cf.cafebabe[1],
			bin->cf.cafebabe[2], bin->cf.cafebabe[3]);
		return false;
	}
	if (bin->cf.major[0] == bin->cf.major[1] && bin->cf.major[0] == 0) {
		eprintf ("Java CLASS with MACH0 header?\n");
		return false;
	}
	adv += 8;
	// -2 so that the cp_count will be parsed
	adv += r_bin_java_parse_cp_pool (bin, adv, buf, buf_sz);
	if (adv > buf_sz) {
		eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Constant Pool.\n");
		return true;
	}
	adv += r_bin_java_read_class_file2 (bin, adv, buf, buf_sz);
	if (adv > buf_sz) {
		eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after class file info.\n");
		return true;
	}
	IFDBG eprintf("This class: %d %s\n", bin->cf2.this_class, bin->cf2.this_class_name);
	IFDBG eprintf("0x%"PFMT64x " Access flags: 0x%04x\n", adv, bin->cf2.access_flags);
	adv += r_bin_java_parse_interfaces (bin, adv, buf, buf_sz);
	if (adv > buf_sz) {
		eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Interfaces.\n");
		return true;
	}
	adv += r_bin_java_parse_fields (bin, adv, buf, buf_sz);
	if (adv > buf_sz) {
		eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Fields.\n");
		return true;
	}
	adv += r_bin_java_parse_methods (bin, adv, buf, buf_sz);
	if (adv > buf_sz) {
		eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Methods.\n");
		return true;
	}
	adv += r_bin_java_parse_attrs (bin, adv, buf, buf_sz);
	bin->calc_size = adv;
	// if (adv > buf_sz) {
	// eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Attributes.\n");
	// return true;
	// }

	// add_cp_objs_to_sdb(bin);
	// add_method_infos_to_sdb(bin);
	// add_field_infos_to_sdb(bin);
	return true;
}


bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
{
    SQObjectPtr temp;
    bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic;
    if(_locked && !belongs_to_static_table)
        return false; //the class already has an instance so cannot be modified
    if(_members->Get(key,temp) && _isfield(temp)) //overrides the default value
    {
        _defaultvalues[_member_idx(temp)].val = val;
        return true;
    }
	if (_members->CountUsed() >= MEMBER_MAX_COUNT) {
		return false;
	}
    if(belongs_to_static_table) {
        SQInteger mmidx;
        if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&
            (mmidx = ss->GetMetaMethodIdxByName(key)) != -1) {
            _metamethods[mmidx] = val;
        }
        else {
            SQObjectPtr theval = val;
            if(_base && sq_type(val) == OT_CLOSURE) {
                theval = _closure(val)->Clone();
                _closure(theval)->_base = _base;
                __ObjAddRef(_base); //ref for the closure
            }
            if(sq_type(temp) == OT_NULL) {
                bool isconstructor;
                SQVM::IsEqual(ss->_constructoridx, key, isconstructor);
                if(isconstructor) {
                    _constructoridx = (SQInteger)_methods.size();
                }
                SQClassMember m;
                m.val = theval;
                _members->NewSlot(key,SQObjectPtr(_make_method_idx(_methods.size())));
                _methods.push_back(m);
            }
            else {
                _methods[_member_idx(temp)].val = theval;
            }
        }
        return true;
    }
    SQClassMember m;
    m.val = val;
    _members->NewSlot(key,SQObjectPtr(_make_field_idx(_defaultvalues.size())));
    _defaultvalues.push_back(m);
    return true;
}


mrb_proc_cfunc_env_get(mrb_state *mrb, mrb_int idx)
{
  const struct RProc *p = mrb->c->ci->proc;
  struct REnv *e;

  if (!p || !MRB_PROC_CFUNC_P(p)) {
    mrb_raise(mrb, E_TYPE_ERROR, "Can't get cfunc env from non-cfunc proc");
  }
  e = MRB_PROC_ENV(p);
  if (!e) {
    mrb_raise(mrb, E_TYPE_ERROR, "Can't get cfunc env from cfunc Proc without REnv");
  }
  if (idx < 0 || MRB_ENV_LEN(e) <= idx) {
    mrb_raisef(mrb, E_INDEX_ERROR, "Env index out of range: %i (expected: 0 <= index < %i)",
               idx, MRB_ENV_LEN(e));
  }

  return e->stack[idx];
}


static unsigned long get_memlimit(const char *cgroup)
{
	char *memlimit_str = NULL;
	unsigned long memlimit = -1;

	if (cgfs_get_value("memory", cgroup, "memory.limit_in_bytes", &memlimit_str))
		memlimit = strtoul(memlimit_str, NULL, 10);

	free(memlimit_str);

	return memlimit;
}


static void ext4_destroy_lazyinit_thread(void)
{
	/*
	 * If thread exited earlier
	 * there's nothing to be done.
	 */
	if (!ext4_li_info || !ext4_lazyinit_task)
		return;

	kthread_stop(ext4_lazyinit_task);
}


static void hub_set_initial_usb2_lpm_policy(struct usb_device *udev)
{
	struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent);
	int connect_type = USB_PORT_CONNECT_TYPE_UNKNOWN;

	if (!udev->usb2_hw_lpm_capable)
		return;

	if (hub)
		connect_type = hub->ports[udev->portnum - 1]->connect_type;

	if ((udev->bos->ext_cap->bmAttributes & cpu_to_le32(USB_BESL_SUPPORT)) ||
			connect_type == USB_PORT_CONNECT_TYPE_HARD_WIRED) {
		udev->usb2_hw_lpm_allowed = 1;
		usb_set_usb2_hardware_lpm(udev, 1);
	}
}


    JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
    {
        AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");

        return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
    }


v8::Handle<v8::Object> V8TestObjectPython::createWrapper(PassRefPtr<TestObjectPython> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
    ASSERT(impl);
    ASSERT(!DOMDataStore::containsWrapper<V8TestObjectPython>(impl.get(), isolate));
    if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
        const WrapperTypeInfo* actualInfo = ScriptWrappable::getTypeInfoFromObject(impl.get());
        RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
    }

    v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
    if (UNLIKELY(wrapper.IsEmpty()))
        return wrapper;

    installPerContextEnabledProperties(wrapper, impl.get(), isolate);
    V8DOMWrapper::associateObjectWithWrapper<V8TestObjectPython>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
    return wrapper;
}


static int ipcget_new(struct ipc_namespace *ns, struct ipc_ids *ids,
		struct ipc_ops *ops, struct ipc_params *params)
{
	int err;

	down_write(&ids->rw_mutex);
	err = ops->getnew(ns, params);
	up_write(&ids->rw_mutex);
	return err;
}


static void add_cache_tree(struct cache_tree *it, struct rev_info *revs,
			   struct strbuf *path)
{
	size_t baselen = path->len;
	int i;

	if (it->entry_count >= 0) {
		struct tree *tree = lookup_tree(it->sha1);
		add_pending_object_with_path(revs, &tree->object, "",
					     040000, path->buf);
	}

	for (i = 0; i < it->subtree_nr; i++) {
		struct cache_tree_sub *sub = it->down[i];
		strbuf_addf(path, "%s%s", baselen ? "/" : "", sub->name);
		add_cache_tree(sub->cache_tree, revs, path);
		strbuf_setlen(path, baselen);
	}

}


static irqreturn_t armpmu_dispatch_irq(int irq, void *dev)
{
	struct arm_pmu *armpmu = (struct arm_pmu *) dev;
	struct platform_device *plat_device = armpmu->plat_device;
	struct arm_pmu_platdata *plat = dev_get_platdata(&plat_device->dev);

	if (plat && plat->handle_irq)
		return plat->handle_irq(irq, dev, armpmu->handle_irq);
	else
		return armpmu->handle_irq(irq, dev);
}


 void TranslateMessageInfoBar::Layout() {
   TranslateInfoBarBase::Layout();

  int x = icon_->bounds().right() + InfoBar::kIconLabelSpacing;
   gfx::Size label_pref_size = label_->GetPreferredSize();
   int available_width = GetAvailableWidth() - x;
   gfx::Size button_pref_size;
   if (button_) {
     button_pref_size = button_->GetPreferredSize();
     available_width -=
        (button_pref_size.width() + InfoBar::kButtonInLabelSpacing);
   }
  label_->SetBounds(x, InfoBar::OffsetY(this, label_pref_size),
                     std::min(label_pref_size.width(), available_width),
                     label_pref_size.height());

   if (button_) {
     button_->SetBounds(label_->bounds().right() +
                          InfoBar::kButtonInLabelSpacing,
                       InfoBar::OffsetY(this, button_pref_size),
                        button_pref_size.width(), button_pref_size.height());
   }
 }


static void bnxt_re_process_req_wc(struct ib_wc *wc, struct bnxt_qplib_cqe *cqe)
{
	switch (cqe->type) {
	case BNXT_QPLIB_SWQE_TYPE_SEND:
		wc->opcode = IB_WC_SEND;
		break;
	case BNXT_QPLIB_SWQE_TYPE_SEND_WITH_IMM:
		wc->opcode = IB_WC_SEND;
		wc->wc_flags |= IB_WC_WITH_IMM;
		break;
	case BNXT_QPLIB_SWQE_TYPE_SEND_WITH_INV:
		wc->opcode = IB_WC_SEND;
		wc->wc_flags |= IB_WC_WITH_INVALIDATE;
		break;
	case BNXT_QPLIB_SWQE_TYPE_RDMA_WRITE:
		wc->opcode = IB_WC_RDMA_WRITE;
		break;
	case BNXT_QPLIB_SWQE_TYPE_RDMA_WRITE_WITH_IMM:
		wc->opcode = IB_WC_RDMA_WRITE;
		wc->wc_flags |= IB_WC_WITH_IMM;
		break;
	case BNXT_QPLIB_SWQE_TYPE_RDMA_READ:
		wc->opcode = IB_WC_RDMA_READ;
		break;
	case BNXT_QPLIB_SWQE_TYPE_ATOMIC_CMP_AND_SWP:
		wc->opcode = IB_WC_COMP_SWAP;
		break;
	case BNXT_QPLIB_SWQE_TYPE_ATOMIC_FETCH_AND_ADD:
		wc->opcode = IB_WC_FETCH_ADD;
		break;
	case BNXT_QPLIB_SWQE_TYPE_LOCAL_INV:
		wc->opcode = IB_WC_LOCAL_INV;
		break;
	case BNXT_QPLIB_SWQE_TYPE_REG_MR:
		wc->opcode = IB_WC_REG_MR;
		break;
	default:
		wc->opcode = IB_WC_SEND;
		break;
	}

	wc->status = __req_to_ib_wc_status(cqe->status);
}


void IOThread::InitializeNetworkOptions(const CommandLine& command_line) {
  if (command_line.HasSwitch(switches::kEnableFileCookies)) {
    net::CookieMonster::EnableFileScheme();
  }

  if (is_spdy_disabled_by_policy_) {
    base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
    if (trial)
      trial->Disable();
  } else {
    std::string spdy_trial_group =
        base::FieldTrialList::FindFullName(kSpdyFieldTrialName);

    if (command_line.HasSwitch(switches::kEnableIPPooling))
      globals_->enable_spdy_ip_pooling.set(true);

    if (command_line.HasSwitch(switches::kDisableIPPooling))
      globals_->enable_spdy_ip_pooling.set(false);

    if (command_line.HasSwitch(switches::kEnableWebSocketOverSpdy)) {
      net::WebSocketJob::set_websocket_over_spdy_enabled(true);
    }

    if (command_line.HasSwitch(switches::kMaxSpdyConcurrentStreams)) {
      globals_->max_spdy_concurrent_streams_limit.set(
          GetSwitchValueAsInt(command_line,
                              switches::kMaxSpdyConcurrentStreams));
    }
    if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
      globals_->trusted_spdy_proxy.set(
          command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
    }
    if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
      net::URLFetcher::SetIgnoreCertificateRequests(true);

    if (command_line.HasSwitch(switches::kUseSpdy)) {
      std::string spdy_mode =
          command_line.GetSwitchValueASCII(switches::kUseSpdy);
      EnableSpdy(spdy_mode);
    } else if (command_line.HasSwitch(switches::kEnableHttp2Draft04)) {
      net::HttpStreamFactory::EnableNpnHttp2Draft04();
    } else if (command_line.HasSwitch(switches::kEnableSpdy4a2)) {
      net::HttpStreamFactory::EnableNpnSpdy4a2();
    } else if (command_line.HasSwitch(switches::kDisableSpdy31)) {
      net::HttpStreamFactory::EnableNpnSpdy3();
    } else if (command_line.HasSwitch(switches::kEnableSpdy2)) {
      net::HttpStreamFactory::EnableNpnSpdy31WithSpdy2();
    } else if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
      net::HttpStreamFactory::EnableNpnHttpOnly();
    } else {
      if (spdy_trial_group == kSpdyFieldTrialDisabledGroupName &&
          !command_line.HasSwitch(switches::kEnableWebSocketOverSpdy)) {
         net::HttpStreamFactory::set_spdy_enabled(false);
      } else {
        net::HttpStreamFactory::EnableNpnSpdy31();
      }
    }
  }

  if (command_line.HasSwitch(switches::kEnableTcpFastOpen))
    net::SetTCPFastOpenEnabled(true);
}


void crypto_unregister_template(struct crypto_template *tmpl)
{
	struct crypto_instance *inst;
	struct hlist_node *n;
	struct hlist_head *list;
	LIST_HEAD(users);

	down_write(&crypto_alg_sem);

	BUG_ON(list_empty(&tmpl->list));
	list_del_init(&tmpl->list);

	list = &tmpl->instances;
	hlist_for_each_entry(inst, list, list) {
		int err = crypto_remove_alg(&inst->alg, &users);
		BUG_ON(err);
	}

	crypto_notify(CRYPTO_MSG_TMPL_UNREGISTER, tmpl);

	up_write(&crypto_alg_sem);

	hlist_for_each_entry_safe(inst, n, list, list) {
		BUG_ON(atomic_read(&inst->alg.cra_refcnt) != 1);
		tmpl->free(inst);
	}
	crypto_remove_final(&users);
}


static void ib_uverbs_free_hw_resources(struct ib_uverbs_device *uverbs_dev,
					struct ib_device *ib_dev)
{
	struct ib_uverbs_file *file;
	struct ib_uverbs_async_event_file *event_file;
	struct ib_event event;

	/* Pending running commands to terminate */
	uverbs_disassociate_api_pre(uverbs_dev);
	event.event = IB_EVENT_DEVICE_FATAL;
	event.element.port_num = 0;
	event.device = ib_dev;

	mutex_lock(&uverbs_dev->lists_mutex);
	while (!list_empty(&uverbs_dev->uverbs_file_list)) {
		file = list_first_entry(&uverbs_dev->uverbs_file_list,
					struct ib_uverbs_file, list);
		list_del_init(&file->list);
		kref_get(&file->ref);

		/* We must release the mutex before going ahead and calling
		 * uverbs_cleanup_ufile, as it might end up indirectly calling
		 * uverbs_close, for example due to freeing the resources (e.g
		 * mmput).
		 */
		mutex_unlock(&uverbs_dev->lists_mutex);

		ib_uverbs_event_handler(&file->event_handler, &event);
		uverbs_destroy_ufile_hw(file, RDMA_REMOVE_DRIVER_REMOVE);
		kref_put(&file->ref, ib_uverbs_release_file);

		mutex_lock(&uverbs_dev->lists_mutex);
	}

	while (!list_empty(&uverbs_dev->uverbs_events_file_list)) {
		event_file = list_first_entry(&uverbs_dev->
					      uverbs_events_file_list,
					      struct ib_uverbs_async_event_file,
					      list);
		spin_lock_irq(&event_file->ev_queue.lock);
		event_file->ev_queue.is_closed = 1;
		spin_unlock_irq(&event_file->ev_queue.lock);

		list_del(&event_file->list);
		ib_unregister_event_handler(
			&event_file->uverbs_file->event_handler);
		event_file->uverbs_file->event_handler.device =
			NULL;

		wake_up_interruptible(&event_file->ev_queue.poll_wait);
		kill_fasync(&event_file->ev_queue.async_queue, SIGIO, POLL_IN);
	}
	mutex_unlock(&uverbs_dev->lists_mutex);

	uverbs_disassociate_api(uverbs_dev->uapi);
}


static __be32 *encode_entryplus_baggage(struct nfsd3_readdirres *cd, __be32 *p, const char *name, int namlen, u64 ino)
{
	struct svc_fh	*fh = &cd->scratch;
	__be32 err;

	fh_init(fh, NFS3_FHSIZE);
	err = compose_entry_fh(cd, fh, name, namlen, ino);
	if (err) {
		*p++ = 0;
		*p++ = 0;
		goto out;
	}
	p = encode_post_op_attr(cd->rqstp, p, fh);
	*p++ = xdr_one;			/* yes, a file handle follows */
	p = encode_fh(p, fh);
out:
	fh_put(fh);
	return p;
}


static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */
{
/*
	This is how the time string is formatted:

   snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
      ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
*/

	time_t ret;
	struct tm thetime;
	char * strbuf;
        char * thestr;
        long gmadjust = 0;

       if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME) {
               php_error_docref(NULL TSRMLS_CC, E_WARNING, "illegal ASN1 data type for timestamp");
                return (time_t)-1;
        }

       if (ASN1_STRING_length(timestr) != strlen(ASN1_STRING_data(timestr))) {
               php_error_docref(NULL TSRMLS_CC, E_WARNING, "illegal length in timestamp");
               return (time_t)-1;
       }

       if (ASN1_STRING_length(timestr) < 13) {
               php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to parse time string %s correctly", timestr->data);
               return (time_t)-1;
       }

       strbuf = estrdup((char *)ASN1_STRING_data(timestr));

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

        /* we work backwards so that we can use atoi more easily */

       thestr = strbuf + ASN1_STRING_length(timestr) - 3;

        thetime.tm_sec = atoi(thestr);
        *thestr = '\0';
	thetime.tm_mon = atoi(thestr)-1;
	*thestr = '\0';
	thestr -= 2;
	thetime.tm_year = atoi(thestr);

	if (thetime.tm_year < 68) {
		thetime.tm_year += 100;
	}

	thetime.tm_isdst = -1;
	ret = mktime(&thetime);

#if HAVE_TM_GMTOFF
	gmadjust = thetime.tm_gmtoff;
#else
	/*
	** If correcting for daylight savings time, we set the adjustment to
	** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
	** set the adjustment to the main timezone + 3600 seconds.
	*/
	gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);
#endif
	ret += gmadjust;

	efree(strbuf);

	return ret;
}
/* }}} */


gfx::Point RootWindowHostLinux::GetLocationOnNativeScreen() const {
  return bounds_.origin();
}


MONGO_EXPORT int bson_append_new_oid( bson *b, const char *name ) {
    bson_oid_t oid;
    bson_oid_gen( &oid );
    return bson_append_oid( b, name, &oid );
}


static void test_date()
{
  int        rc;

  myheader("test_date");

  rc= mysql_query(mysql, "DROP TABLE IF EXISTS test_date");
  myquery(rc);

  rc= mysql_query(mysql, "CREATE TABLE test_date(c1 TIMESTAMP, \
                                                 c2 TIME, \
                                                 c3 DATETIME, \
                                                 c4 DATE)");

  myquery(rc);

  bind_date_conv(5,FALSE);
}


buflist_new(
    char_u	*ffname_arg,	// full path of fname or relative
    char_u	*sfname_arg,	// short fname or NULL
    linenr_T	lnum,		// preferred cursor line
    int		flags)		// BLN_ defines
{
    char_u	*ffname = ffname_arg;
    char_u	*sfname = sfname_arg;
    buf_T	*buf;
#ifdef UNIX
    stat_T	st;
#endif

    if (top_file_num == 1)
	hash_init(&buf_hashtab);

    fname_expand(curbuf, &ffname, &sfname);	// will allocate ffname

    /*
     * If the file name already exists in the list, update the entry.
     */
#ifdef UNIX
    // On Unix we can use inode numbers when the file exists.  Works better
    // for hard links.
    if (sfname == NULL || mch_stat((char *)sfname, &st) < 0)
	st.st_dev = (dev_T)-1;
#endif
    if (ffname != NULL && !(flags & (BLN_DUMMY | BLN_NEW)) && (buf =
#ifdef UNIX
		buflist_findname_stat(ffname, &st)
#else
		buflist_findname(ffname)
#endif
		) != NULL)
    {
	vim_free(ffname);
	if (lnum != 0)
	    buflist_setfpos(buf, (flags & BLN_NOCURWIN) ? NULL : curwin,
						      lnum, (colnr_T)0, FALSE);

	if ((flags & BLN_NOOPT) == 0)
	    // copy the options now, if 'cpo' doesn't have 's' and not done
	    // already
	    buf_copy_options(buf, 0);

	if ((flags & BLN_LISTED) && !buf->b_p_bl)
	{
	    bufref_T bufref;

	    buf->b_p_bl = TRUE;
	    set_bufref(&bufref, buf);
	    if (!(flags & BLN_DUMMY))
	    {
		if (apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf)
			&& !bufref_valid(&bufref))
		    return NULL;
	    }
	}
	return buf;
    }

    /*
     * If the current buffer has no name and no contents, use the current
     * buffer.	Otherwise: Need to allocate a new buffer structure.
     *
     * This is the ONLY place where a new buffer structure is allocated!
     * (A spell file buffer is allocated in spell.c, but that's not a normal
     * buffer.)
     */
    buf = NULL;
    if ((flags & BLN_CURBUF) && curbuf_reusable())
    {
	buf = curbuf;
	// It's like this buffer is deleted.  Watch out for autocommands that
	// change curbuf!  If that happens, allocate a new buffer anyway.
	if (curbuf->b_p_bl)
	    apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
	if (buf == curbuf)
	    apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
#ifdef FEAT_EVAL
	if (aborting())		// autocmds may abort script processing
	{
	    vim_free(ffname);
	    return NULL;
	}
#endif
	if (buf == curbuf)
	{
	    // Make sure 'bufhidden' and 'buftype' are empty
	    clear_string_option(&buf->b_p_bh);
	    clear_string_option(&buf->b_p_bt);
	}
    }
    if (buf != curbuf || curbuf == NULL)
    {
	buf = ALLOC_CLEAR_ONE(buf_T);
	if (buf == NULL)
	{
	    vim_free(ffname);
	    return NULL;
	}
#ifdef FEAT_EVAL
	// init b: variables
	buf->b_vars = dict_alloc();
	if (buf->b_vars == NULL)
	{
	    vim_free(ffname);
	    vim_free(buf);
	    return NULL;
	}
	init_var_dict(buf->b_vars, &buf->b_bufvar, VAR_SCOPE);
#endif
	init_changedtick(buf);
    }

    if (ffname != NULL)
    {
	buf->b_ffname = ffname;
	buf->b_sfname = vim_strsave(sfname);
    }

    clear_wininfo(buf);
    buf->b_wininfo = ALLOC_CLEAR_ONE(wininfo_T);

    if ((ffname != NULL && (buf->b_ffname == NULL || buf->b_sfname == NULL))
	    || buf->b_wininfo == NULL)
    {
	if (buf->b_sfname != buf->b_ffname)
	    VIM_CLEAR(buf->b_sfname);
	else
	    buf->b_sfname = NULL;
	VIM_CLEAR(buf->b_ffname);
	if (buf != curbuf)
	    free_buffer(buf);
	return NULL;
    }

    if (buf == curbuf)
    {
	// free all things allocated for this buffer
	buf_freeall(buf, 0);
	if (buf != curbuf)	 // autocommands deleted the buffer!
	    return NULL;
#if defined(FEAT_EVAL)
	if (aborting())		// autocmds may abort script processing
	    return NULL;
#endif
	free_buffer_stuff(buf, FALSE);	// delete local variables et al.

	// Init the options.
	buf->b_p_initialized = FALSE;
	buf_copy_options(buf, BCO_ENTER);

#ifdef FEAT_KEYMAP
	// need to reload lmaps and set b:keymap_name
	curbuf->b_kmap_state |= KEYMAP_INIT;
#endif
    }
    else
    {
	// put the new buffer at the end of the buffer list
	buf->b_next = NULL;
	if (firstbuf == NULL)		// buffer list is empty
	{
	    buf->b_prev = NULL;
	    firstbuf = buf;
	}
	else				// append new buffer at end of list
	{
	    lastbuf->b_next = buf;
	    buf->b_prev = lastbuf;
	}
	lastbuf = buf;

	if ((flags & BLN_REUSE) && buf_reuse.ga_len > 0)
	{
	    // Recycle a previously used buffer number.  Used for buffers which
	    // are normally hidden, e.g. in a popup window.  Avoids that the
	    // buffer number grows rapidly.
	    --buf_reuse.ga_len;
	    buf->b_fnum = ((int *)buf_reuse.ga_data)[buf_reuse.ga_len];

	    // Move buffer to the right place in the buffer list.
	    while (buf->b_prev != NULL && buf->b_fnum < buf->b_prev->b_fnum)
	    {
		buf_T	*prev = buf->b_prev;

		prev->b_next = buf->b_next;
		if (prev->b_next != NULL)
		    prev->b_next->b_prev = prev;
		buf->b_next = prev;
		buf->b_prev = prev->b_prev;
		if (buf->b_prev != NULL)
		    buf->b_prev->b_next = buf;
		prev->b_prev = buf;
		if (lastbuf == buf)
		    lastbuf = prev;
		if (firstbuf == prev)
		    firstbuf = buf;
	    }
	}
	else
	    buf->b_fnum = top_file_num++;
	if (top_file_num < 0)		// wrap around (may cause duplicates)
	{
	    emsg(_("W14: Warning: List of file names overflow"));
	    if (emsg_silent == 0 && !in_assert_fails)
	    {
		out_flush();
		ui_delay(3001L, TRUE);	// make sure it is noticed
	    }
	    top_file_num = 1;
	}
	buf_hashtab_add(buf);

	// Always copy the options from the current buffer.
	buf_copy_options(buf, BCO_ALWAYS);
    }

    buf->b_wininfo->wi_fpos.lnum = lnum;
    buf->b_wininfo->wi_win = curwin;

#ifdef FEAT_SYN_HL
    hash_init(&buf->b_s.b_keywtab);
    hash_init(&buf->b_s.b_keywtab_ic);
#endif

    buf->b_fname = buf->b_sfname;
#ifdef UNIX
    if (st.st_dev == (dev_T)-1)
	buf->b_dev_valid = FALSE;
    else
    {
	buf->b_dev_valid = TRUE;
	buf->b_dev = st.st_dev;
	buf->b_ino = st.st_ino;
    }
#endif
    buf->b_u_synced = TRUE;
    buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
    if (flags & BLN_DUMMY)
	buf->b_flags |= BF_DUMMY;
    buf_clear_file(buf);
    clrallmarks(buf);			// clear marks
    fmarks_check_names(buf);		// check file marks for this file
    buf->b_p_bl = (flags & BLN_LISTED) ? TRUE : FALSE;	// init 'buflisted'
    if (!(flags & BLN_DUMMY))
    {
	bufref_T bufref;

	// Tricky: these autocommands may change the buffer list.  They could
	// also split the window with re-using the one empty buffer. This may
	// result in unexpectedly losing the empty buffer.
	set_bufref(&bufref, buf);
	if (apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, buf)
		&& !bufref_valid(&bufref))
	    return NULL;
	if (flags & BLN_LISTED)
	{
	    if (apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf)
		    && !bufref_valid(&bufref))
		return NULL;
	}
#ifdef FEAT_EVAL
	if (aborting())		// autocmds may abort script processing
	    return NULL;
#endif
    }

    return buf;
}


static void freestack (lua_State *L) {
  if (L->stack == NULL)
    return;  /* stack not completely built yet */
  L->ci = &L->base_ci;  /* free the entire 'ci' list */
  luaE_freeCI(L);
  lua_assert(L->nci == 0);
  luaM_freearray(L, L->stack, L->stacksize);  /* free stack array */
}


static uint8_t read_u8(uint8_t *data, size_t offset)
{
    return data[offset];
}


_PUBLIC_ bool strhasupper(const char *string)
{
	struct smb_iconv_handle *ic = get_iconv_handle();
	return strhasupper_handle(ic, string);
}


static void vcpu_load_eoi_exitmap(struct kvm_vcpu *vcpu)
{
	u64 eoi_exit_bitmap[4];

	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
		return;

	if (to_hv_vcpu(vcpu)) {
		bitmap_or((ulong *)eoi_exit_bitmap,
			  vcpu->arch.ioapic_handled_vectors,
			  to_hv_synic(vcpu)->vec_bitmap, 256);
		static_call_cond(kvm_x86_load_eoi_exitmap)(vcpu, eoi_exit_bitmap);
		return;
	}

	static_call_cond(kvm_x86_load_eoi_exitmap)(
		vcpu, (u64 *)vcpu->arch.ioapic_handled_vectors);
}


void *dupClientReplyValue(void *o) {
    incrRefCount((robj*)o);
    return o;
}


static int ldm_get_vstr (const u8 *block, u8 *buffer, int buflen)
{
	int length;

	BUG_ON (!block || !buffer);

	length = block[0];
	if (length >= buflen) {
		ldm_error ("Truncating string %d -> %d.", length, buflen);
		length = buflen - 1;
	}
	memcpy (buffer, block + 1, length);
	buffer[length] = 0;
	return length;
}


static uint16_t inv_bits ( uint16_t val , int nbits ) {
 uint16_t res ;
 if ( nbits <= 8 ) {
 res = ff_reverse [ val ] >> ( 8 - nbits ) ;
 }
 else res = ( ( ff_reverse [ val & 0xFF ] << 8 ) + ( ff_reverse [ val >> 8 ] ) ) >> ( 16 - nbits ) ;
 return res ;
 }


static uint32 GetLinearSlideDownTable    (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable));     return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideDownTable[i]     : LinearSlideUpTable[i]; }


void RTCPeerConnectionHandler::RemoveTrackUnifiedPlanOnSignalingThread(
    rtc::scoped_refptr<webrtc::RtpSenderInterface> sender,
    TransceiverStateSurfacer* transceiver_state_surfacer,
    bool* result) {
  *result = native_peer_connection_->RemoveTrack(sender);
  std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> transceivers;
  if (*result) {
    rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver_for_sender =
        nullptr;
    for (const auto& transceiver : native_peer_connection_->GetTransceivers()) {
      if (transceiver->sender() == sender) {
        transceiver_for_sender = transceiver;
        break;
      }
    }
    DCHECK(transceiver_for_sender);
    transceivers = {transceiver_for_sender};
  }
  transceiver_state_surfacer->Initialize(track_adapter_map_,
                                         std::move(transceivers));
}


FloatRect EffectPaintPropertyNode::MapRect(const FloatRect& input_rect) const {
  FloatRect rect = input_rect;
  rect.MoveBy(-state_.paint_offset);
  FloatRect result = state_.filter.MapRect(rect);
  result.MoveBy(state_.paint_offset);
  return result;
}


mailimf_number_parse(const char * message, size_t length,
		     size_t * indx, uint32_t * result)
{
  size_t cur_token;
  int digit;
  uint32_t number;
  int parsed;
  int r;

  cur_token = * indx;
  parsed = FALSE;

  number = 0;
  while (1) {
    r = mailimf_digit_parse(message, length, &cur_token, &digit);
    if (r != MAILIMF_NO_ERROR) {
      if (r == MAILIMF_ERROR_PARSE)
	break;
      else
	return r;
    }
    number *= 10;
    number += digit;
    parsed = TRUE;
  }

  if (!parsed)
    return MAILIMF_ERROR_PARSE;

  * result = number;
  * indx = cur_token;

  return MAILIMF_NO_ERROR;
}


QJsonArray Helper::getBlockDevices(const QString &commandExtraArg)
{
    const QByteArray &array = Helper::callLsblk(commandExtraArg);

    QJsonParseError error;

    const QJsonDocument &jd = QJsonDocument::fromJson(QString::fromUtf8(array).toUtf8(), &error);

    if (error.error != QJsonParseError::NoError) {
        dCError(error.errorString());
    }

    return jd.object().value("blockdevices").toArray();
}


static int __pyx_tp_traverse_17clickhouse_driver_14bufferedreader_BufferedSocketReader(PyObject *o, visitproc v, void *a) {
  int e;
  struct __pyx_obj_17clickhouse_driver_14bufferedreader_BufferedSocketReader *p = (struct __pyx_obj_17clickhouse_driver_14bufferedreader_BufferedSocketReader *)o;
  e = ((likely(__pyx_ptype_17clickhouse_driver_14bufferedreader_BufferedReader)) ? ((__pyx_ptype_17clickhouse_driver_14bufferedreader_BufferedReader->tp_traverse) ? __pyx_ptype_17clickhouse_driver_14bufferedreader_BufferedReader->tp_traverse(o, v, a) : 0) : __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_17clickhouse_driver_14bufferedreader_BufferedSocketReader)); if (e) return e;
  if (p->sock) {
    e = (*v)(p->sock, a); if (e) return e;
  }
  return 0;
}


int blk_rq_unmap_user(struct bio *bio)
{
	struct bio *mapped_bio;
	int ret = 0, ret2;

	while (bio) {
		mapped_bio = bio;
		if (unlikely(bio_flagged(bio, BIO_BOUNCED)))
			mapped_bio = bio->bi_private;

		ret2 = __blk_rq_unmap_user(mapped_bio);
		if (ret2 && !ret)
			ret = ret2;

		mapped_bio = bio;
		bio = bio->bi_next;
		bio_put(mapped_bio);
	}

	return ret;
}


PP_Bool IsWidget(PP_Resource resource) {
  return BoolToPPBool(!!Resource::GetAs<PPB_Widget_Impl>(resource));
}


static cdk_error_t skip_packet(cdk_stream_t inp, size_t pktlen)
{
	byte buf[BUFSIZE];
	size_t nread, buflen = DIM(buf);

	while (pktlen > 0) {
		cdk_error_t rc;
		rc = stream_read(inp, buf, pktlen > buflen ? buflen : pktlen,
			    &nread);
		if (rc)
			return rc;
		pktlen -= nread;
	}

	assert(pktlen == 0);
	return 0;
}


static void mmtimer_set_next_timer(int nodeid)
{
	struct mmtimer_node *n = &timers[nodeid];
	struct mmtimer *x;
	struct k_itimer *t;
	int o;

restart:
	if (n->next == NULL)
		return;

	x = rb_entry(n->next, struct mmtimer, list);
	t = x->timer;
	if (!t->it.mmtimer.incr) {
		/* Not an interval timer */
		if (!mmtimer_setup(x->cpu, COMPARATOR,
					t->it.mmtimer.expires)) {
			/* Late setup, fire now */
			tasklet_schedule(&n->tasklet);
		}
		return;
	}

	/* Interval timer */
	o = 0;
	while (!mmtimer_setup(x->cpu, COMPARATOR, t->it.mmtimer.expires)) {
		unsigned long e, e1;
		struct rb_node *next;
		t->it.mmtimer.expires += t->it.mmtimer.incr << o;
		t->it_overrun += 1 << o;
		o++;
		if (o > 20) {
			printk(KERN_ALERT "mmtimer: cannot reschedule timer\n");
			t->it.mmtimer.clock = TIMER_OFF;
			n->next = rb_next(&x->list);
			rb_erase(&x->list, &n->timer_head);
			kfree(x);
			goto restart;
		}

		e = t->it.mmtimer.expires;
		next = rb_next(&x->list);

		if (next == NULL)
			continue;

		e1 = rb_entry(next, struct mmtimer, list)->
			timer->it.mmtimer.expires;
		if (e > e1) {
			n->next = next;
			rb_erase(&x->list, &n->timer_head);
			mmtimer_add_list(x);
			goto restart;
		}
	}
}


static SQInteger string_find(HSQUIRRELVM v)
{
    SQInteger top,start_idx=0;
    const SQChar *str,*substr,*ret;
    if(((top=sq_gettop(v))>1) && SQ_SUCCEEDED(sq_getstring(v,1,&str)) && SQ_SUCCEEDED(sq_getstring(v,2,&substr))){
        if(top>2)sq_getinteger(v,3,&start_idx);
        if((sq_getsize(v,1)>start_idx) && (start_idx>=0)){
            ret=scstrstr(&str[start_idx],substr);
            if(ret){
                sq_pushinteger(v,(SQInteger)(ret-str));
                return 1;
            }
        }
        return 0;
    }
    return sq_throwerror(v,_SC("invalid param"));
}


static void monitor_print_error(Monitor *mon)

{

    qerror_print(mon->error);

    QDECREF(mon->error);

    mon->error = NULL;

}


DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_strings)
{
    int ret = 1;
    /*
     * OPENSSL_NO_AUTOERRINIT is provided here to prevent at compile time
     * pulling in all the error strings during static linking
     */
#if !defined(OPENSSL_NO_ERR) && !defined(OPENSSL_NO_AUTOERRINIT)
# ifdef OPENSSL_INIT_DEBUG
    fprintf(stderr, "OPENSSL_INIT: ossl_init_load_crypto_strings: "
                    "err_load_crypto_strings_int()\n");
# endif
    ret = err_load_crypto_strings_int();
    load_crypto_strings_inited = 1;
#endif
    return ret;
}


static void xdr_buf_pages_copy_left(const struct xdr_buf *buf,
				    unsigned int base, unsigned int len,
				    unsigned int shift)
{
	unsigned int pgto;

	if (base >= buf->page_len)
		return;
	if (len > buf->page_len - base)
		len = buf->page_len - base;
	/* Shift data into head */
	if (shift > base) {
		const struct kvec *head = buf->head;
		unsigned int hdto = head->iov_len + base - shift;
		unsigned int hdlen = len;

		if (WARN_ONCE(shift > head->iov_len + base,
			      "SUNRPC: Misaligned data.\n"))
			return;
		if (hdto + hdlen > head->iov_len)
			hdlen = head->iov_len - hdto;
		_copy_from_pages(head->iov_base + hdto, buf->pages,
				 buf->page_base + base, hdlen);
		base += hdlen;
		len -= hdlen;
		if (!len)
			return;
	}
	pgto = base - shift;
	_shift_data_left_pages(buf->pages, buf->page_base + pgto,
			       buf->page_base + base, len);
}


int do_send_sig_info(int sig, struct siginfo *info, struct task_struct *p,
			bool group)
{
	unsigned long flags;
	int ret = -ESRCH;

	if (lock_task_sighand(p, &flags)) {
		ret = send_signal(sig, info, p, group);
		unlock_task_sighand(p, &flags);
	}

	return ret;
}


static __always_inline void set_root_rcu(struct nameidata *nd)
{
	if (!nd->root.mnt) {
		struct fs_struct *fs = current->fs;
		unsigned seq;

		do {
			seq = read_seqcount_begin(&fs->seq);
			nd->root = fs->root;
			nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq);
		} while (read_seqcount_retry(&fs->seq, seq));
	}
}


PHP_FUNCTION(openssl_pkey_new)
{
	struct php_x509_request req;
	zval * args = NULL;
	zval **data;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &args) == FAILURE) {
		return;
	}
	RETVAL_FALSE;

	if (args && Z_TYPE_P(args) == IS_ARRAY) {
		EVP_PKEY *pkey;

		if (zend_hash_find(Z_ARRVAL_P(args), "rsa", sizeof("rsa"), (void**)&data) == SUCCESS &&
		    Z_TYPE_PP(data) == IS_ARRAY) {
		    pkey = EVP_PKEY_new();
		    if (pkey) {
				RSA *rsa = RSA_new();
				if (rsa) {
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, n);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, e);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, d);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, p);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, q);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, dmp1);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, dmq1);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, iqmp);
					if (rsa->n && rsa->d) {
						if (EVP_PKEY_assign_RSA(pkey, rsa)) {
							RETURN_RESOURCE(zend_list_insert(pkey, le_key));
						}
					}
					RSA_free(rsa);
				}
				EVP_PKEY_free(pkey);
			}
			RETURN_FALSE;
		} else if (zend_hash_find(Z_ARRVAL_P(args), "dsa", sizeof("dsa"), (void**)&data) == SUCCESS &&
		           Z_TYPE_PP(data) == IS_ARRAY) {
		    pkey = EVP_PKEY_new();
		    if (pkey) {
				DSA *dsa = DSA_new();
				if (dsa) {
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, p);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, q);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, g);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, priv_key);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, pub_key);
					if (dsa->p && dsa->q && dsa->g) {
						if (!dsa->priv_key && !dsa->pub_key) {
							DSA_generate_key(dsa);
						}
						if (EVP_PKEY_assign_DSA(pkey, dsa)) {
							RETURN_RESOURCE(zend_list_insert(pkey, le_key));
						}
					}
					DSA_free(dsa);
				}
				EVP_PKEY_free(pkey);
			}
			RETURN_FALSE;
		} else if (zend_hash_find(Z_ARRVAL_P(args), "dh", sizeof("dh"), (void**)&data) == SUCCESS &&
		           Z_TYPE_PP(data) == IS_ARRAY) {
		    pkey = EVP_PKEY_new();
		    if (pkey) {
				DH *dh = DH_new();
				if (dh) {
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, p);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, g);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, priv_key);
					OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, pub_key);
					if (dh->p && dh->g) {
						if (!dh->pub_key) {
							DH_generate_key(dh);
						}
						if (EVP_PKEY_assign_DH(pkey, dh)) {
							RETURN_RESOURCE(zend_list_insert(pkey, le_key));
						}
					}
					DH_free(dh);
				}
				EVP_PKEY_free(pkey);
			}
			RETURN_FALSE;
		}
	}

	PHP_SSL_REQ_INIT(&req);

	if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS)
	{
		if (php_openssl_generate_private_key(&req TSRMLS_CC)) {
			/* pass back a key resource */
			RETVAL_RESOURCE(zend_list_insert(req.priv_key, le_key));
			/* make sure the cleanup code doesn't zap it! */
			req.priv_key = NULL;
		}
	}
	PHP_SSL_REQ_DISPOSE(&req);
}


static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk)
{
  Image
    *image;

  /* The unknown chunk structure contains the chunk data:
     png_byte name[5];
     png_byte *data;
     png_size_t size;

     Note that libpng has already taken care of the CRC handling.

     Returns one of the following:
         return(-n);  chunk had an error
         return(0);  did not recognize
         return(n);  success
  */

  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
     "    read_user_chunk: found %c%c%c%c chunk",
       chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]);

  if (chunk->name[0]  == 101 &&
      (chunk->name[1] ==  88 || chunk->name[1] == 120 ) &&
      chunk->name[2] ==   73 &&
      chunk-> name[3] == 102)
    {
      /* process eXIf or exIf chunk */

      PNGErrorInfo
        *error_info;

      StringInfo
        *profile;

      unsigned char
        *p;

      png_byte
        *s;

      size_t
        i;

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        " recognized eXIf|exIf chunk");

      image=(Image *) png_get_user_chunk_ptr(ping);

      error_info=(PNGErrorInfo *) png_get_error_ptr(ping);

      profile=BlobToStringInfo((const void *) NULL,chunk->size+6);

      if (profile == (StringInfo *) NULL)
        {
          (void) ThrowMagickException(error_info->exception,GetMagickModule(),
            ResourceLimitError,"MemoryAllocationFailed","`%s'",
            image->filename);
          return(-1);
        }
      p=GetStringInfoDatum(profile);

      if (*p != 'E')
        {
          /* Initialize profile with "Exif\0\0" if it is not
             already present by accident
          */
          *p++ ='E';
          *p++ ='x';
          *p++ ='i';
          *p++ ='f';
          *p++ ='\0';
          *p++ ='\0';
        }
      else
        {
          if (p[1] != 'x' || p[2] != 'i' || p[3] != 'f' ||
              p[4] != '\0' || p[5] != '\0')
            {
              /* Chunk is malformed */
              return(-1);
            }
         }

      /* copy chunk->data to profile */
      s=chunk->data;
      for (i=0; i<chunk->size; i++)
        *p++ = *s++;

      error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
      (void) SetImageProfile(image,"exif",profile,
        error_info->exception);

      return(1);
    }

  /* vpAg (deprecated, replaced by caNv) */
  if (chunk->name[0] == 118 &&
      chunk->name[1] == 112 &&
      chunk->name[2] ==  65 &&
      chunk->name[3] == 103)
    {
      /* recognized vpAg */

      if (chunk->size != 9)
        return(-1); /* Error return */

      if (chunk->data[8] != 0)
        return(0);  /* ImageMagick requires pixel units */

      image=(Image *) png_get_user_chunk_ptr(ping);

      image->page.width=(size_t) ((chunk->data[0] << 24) |
         (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);

      image->page.height=(size_t) ((chunk->data[4] << 24) |
         (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);

      return(1);
    }

  /* caNv */
  if (chunk->name[0] ==  99 &&
      chunk->name[1] ==  97 &&
      chunk->name[2] ==  78 &&
      chunk->name[3] == 118)
    {
      /* recognized caNv */

      if (chunk->size != 16)
        return(-1); /* Error return */

      image=(Image *) png_get_user_chunk_ptr(ping);

      image->page.width=(size_t) ((chunk->data[0] << 24) |
         (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);

      image->page.height=(size_t) ((chunk->data[4] << 24) |
         (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);

      image->page.x=(size_t) ((chunk->data[8] << 24) |
         (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]);

      image->page.y=(size_t) ((chunk->data[12] << 24) |
         (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]);

      return(1);
    }

  return(0); /* Did not recognize */
}


uint8_t* SecureElementGetDevEui( void )
{
    return SeContext.DevEui;
}


void Sys_UnloadDll( void *dllHandle )
{
	if( !dllHandle )
	{
		Com_Printf("Sys_UnloadDll(NULL)\n");
		return;
	}

	Sys_UnloadLibrary(dllHandle);
}


  void doMetadata() override {
    if (saved_response_metadata_ != nullptr) {
      drainSavedResponseMetadata();
    }
  }


static int __init einj_init(void)
{
	int rc;
	acpi_status status;
	struct dentry *fentry;
	struct apei_exec_context ctx;

	if (acpi_disabled)
		return -ENODEV;

	status = acpi_get_table(ACPI_SIG_EINJ, 0,
				(struct acpi_table_header **)&einj_tab);
	if (status == AE_NOT_FOUND)
		return -ENODEV;
	else if (ACPI_FAILURE(status)) {
		const char *msg = acpi_format_exception(status);
		pr_err(EINJ_PFX "Failed to get table, %s\n", msg);
		return -EINVAL;
	}

	rc = einj_check_table(einj_tab);
	if (rc) {
		pr_warning(FW_BUG EINJ_PFX "EINJ table is invalid\n");
		return -EINVAL;
	}

	rc = -ENOMEM;
	einj_debug_dir = debugfs_create_dir("einj", apei_get_debugfs_dir());
	if (!einj_debug_dir)
		goto err_cleanup;
	fentry = debugfs_create_file("available_error_type", S_IRUSR,
				     einj_debug_dir, NULL,
				     &available_error_type_fops);
	if (!fentry)
		goto err_cleanup;
	fentry = debugfs_create_file("error_type", S_IRUSR | S_IWUSR,
				     einj_debug_dir, NULL, &error_type_fops);
	if (!fentry)
		goto err_cleanup;
	fentry = debugfs_create_file("error_inject", S_IWUSR,
				     einj_debug_dir, NULL, &error_inject_fops);
	if (!fentry)
		goto err_cleanup;

	apei_resources_init(&einj_resources);
	einj_exec_ctx_init(&ctx);
	rc = apei_exec_collect_resources(&ctx, &einj_resources);
	if (rc)
		goto err_fini;
	rc = apei_resources_request(&einj_resources, "APEI EINJ");
	if (rc)
		goto err_fini;
	rc = apei_exec_pre_map_gars(&ctx);
	if (rc)
		goto err_release;

	rc = -ENOMEM;
	einj_param = einj_get_parameter_address();
	if ((param_extension || acpi5) && einj_param) {
		fentry = debugfs_create_x32("flags", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &error_flags);
		if (!fentry)
			goto err_unmap;
		fentry = debugfs_create_x64("param1", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &error_param1);
		if (!fentry)
			goto err_unmap;
		fentry = debugfs_create_x64("param2", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &error_param2);
		if (!fentry)
			goto err_unmap;
		fentry = debugfs_create_x64("param3", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &error_param3);
		if (!fentry)
			goto err_unmap;
		fentry = debugfs_create_x64("param4", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &error_param4);
		if (!fentry)
			goto err_unmap;

		fentry = debugfs_create_x32("notrigger", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &notrigger);
		if (!fentry)
			goto err_unmap;
	}

	if (vendor_dev[0]) {
		vendor_blob.data = vendor_dev;
		vendor_blob.size = strlen(vendor_dev);
		fentry = debugfs_create_blob("vendor", S_IRUSR,
					     einj_debug_dir, &vendor_blob);
		if (!fentry)
			goto err_unmap;
		fentry = debugfs_create_x32("vendor_flags", S_IRUSR | S_IWUSR,
					    einj_debug_dir, &vendor_flags);
		if (!fentry)
			goto err_unmap;
	}

	pr_info(EINJ_PFX "Error INJection is initialized.\n");

	return 0;

err_unmap:
	if (einj_param) {
		acpi_size size = (acpi5) ?
			sizeof(struct set_error_type_with_address) :
			sizeof(struct einj_parameter);

		acpi_os_unmap_iomem(einj_param, size);
	}
	apei_exec_post_unmap_gars(&ctx);
err_release:
	apei_resources_release(&einj_resources);
err_fini:
	apei_resources_fini(&einj_resources);
err_cleanup:
	debugfs_remove_recursive(einj_debug_dir);

	return rc;
}


void AudioOutputDevice::SetVolumeOnIOThread(double volume) {
  DCHECK(message_loop()->BelongsToCurrentThread());
  if (stream_id_)
    ipc_->SetVolume(stream_id_, volume);
}


static inline struct task_struct *task_of(struct sched_entity *se)
{
	SCHED_WARN_ON(!entity_is_task(se));
	return container_of(se, struct task_struct, se);
}


      static double mp_vector_set_off(_cimg_math_parser& mp) {
        const unsigned int
          ptr = (unsigned int)mp.opcode[2] + 1,
          siz = (unsigned int)mp.opcode[3];
        const int off = (int)_mp_arg(4);
        if (off>=0 && off<(int)siz) mp.mem[ptr + off] = _mp_arg(5);
        return _mp_arg(5);


HostWindow* RenderMenuList::hostWindow() const
{
    return document()->view()->hostWindow();
}


int cfg80211_external_auth_request(struct net_device *dev,
				   struct cfg80211_external_auth_params *params,
				   gfp_t gfp)
{
	struct wireless_dev *wdev = dev->ieee80211_ptr;
	struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy);
	struct sk_buff *msg;
	void *hdr;

	if (!wdev->conn_owner_nlportid)
		return -EINVAL;

	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
	if (!msg)
		return -ENOMEM;

	hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_EXTERNAL_AUTH);
	if (!hdr)
		goto nla_put_failure;

	if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
	    nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
	    nla_put_u32(msg, NL80211_ATTR_AKM_SUITES, params->key_mgmt_suite) ||
	    nla_put_u32(msg, NL80211_ATTR_EXTERNAL_AUTH_ACTION,
			params->action) ||
	    nla_put(msg, NL80211_ATTR_BSSID, ETH_ALEN, params->bssid) ||
	    nla_put(msg, NL80211_ATTR_SSID, params->ssid.ssid_len,
		    params->ssid.ssid))
		goto nla_put_failure;

	genlmsg_end(msg, hdr);
	genlmsg_unicast(wiphy_net(&rdev->wiphy), msg,
			wdev->conn_owner_nlportid);
	return 0;

 nla_put_failure:
	nlmsg_free(msg);
	return -ENOBUFS;
}


int Pipe::write_ack(uint64_t seq)
{
  ldout(msgr->cct,10) << "write_ack " << seq << dendl;

  char c = CEPH_MSGR_TAG_ACK;
  ceph_le64 s;
  s = seq;

  struct msghdr msg;
  memset(&msg, 0, sizeof(msg));
  struct iovec msgvec[2];
  msgvec[0].iov_base = &c;
  msgvec[0].iov_len = 1;
  msgvec[1].iov_base = &s;
  msgvec[1].iov_len = sizeof(s);
  msg.msg_iov = msgvec;
  msg.msg_iovlen = 2;

  if (do_sendmsg(&msg, 1 + sizeof(s), true) < 0)
    return -1;
  return 0;
}