int bdrv_commit(BlockDriverState *bs)
{
    BlockDriver *drv = bs->drv;
    int64_t sector, total_sectors, length, backing_length;
    int n, ro, open_flags;
    int ret = 0;
    uint8_t *buf = NULL;
    char filename[PATH_MAX];

    if (!drv)
        return -ENOMEDIUM;

    if (!bs->backing_hd) {
        return -ENOTSUP;
    }

    if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
        return -EBUSY;
    }

    ro = bs->backing_hd->read_only;
    /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
    pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
    open_flags =  bs->backing_hd->open_flags;

    if (ro) {
        if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
            return -EACCES;
        }
    }

    length = bdrv_getlength(bs);
    if (length < 0) {
        ret = length;
        goto ro_cleanup;
    }

    backing_length = bdrv_getlength(bs->backing_hd);
    if (backing_length < 0) {
        ret = backing_length;
        goto ro_cleanup;
    }

    /* If our top snapshot is larger than the backing file image,
     * grow the backing file image if possible.  If not possible,
     * we must return an error */
    if (length > backing_length) {
        ret = bdrv_truncate(bs->backing_hd, length);
        if (ret < 0) {
            goto ro_cleanup;
        }
    }

    total_sectors = length >> BDRV_SECTOR_BITS;
    buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);

    for (sector = 0; sector < total_sectors; sector += n) {
        ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
        if (ret < 0) {
            goto ro_cleanup;
        }
        if (ret) {
            ret = bdrv_read(bs, sector, buf, n);
            if (ret < 0) {
                goto ro_cleanup;
            }

            ret = bdrv_write(bs->backing_hd, sector, buf, n);
            if (ret < 0) {
                goto ro_cleanup;
            }
        }
    }

    if (drv->bdrv_make_empty) {
        ret = drv->bdrv_make_empty(bs);
        if (ret < 0) {
            goto ro_cleanup;
        }
        bdrv_flush(bs);
    }

    /*
     * Make sure all data we wrote to the backing device is actually
     * stable on disk.
     */
    if (bs->backing_hd) {
        bdrv_flush(bs->backing_hd);
    }

    ret = 0;
ro_cleanup:
    g_free(buf);

    if (ro) {
        /* ignoring error return here */
        bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
    }

    return ret;
}


QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)

{

    QemuOpts *opts;

    QTAILQ_FOREACH(opts, &list->head, next) {

        if (!opts->id) {

            if (!id) {

                return opts;

            }

            continue;

        }

        if (strcmp(opts->id, id) != 0) {

            continue;

        }

        return opts;

    }

    return NULL;

}


    //! Return a pointer to the first pixel value \const.
    const T* data() const {
      return _data;


 virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
 if (video->frame() == kStepDownFrame) {
 struct vpx_scaling_mode mode = {VP8E_FOURFIVE, VP8E_THREEFIVE};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
 }
 if (video->frame() == kStepUpFrame) {
 struct vpx_scaling_mode mode = {VP8E_NORMAL, VP8E_NORMAL};
      encoder->Control(VP8E_SET_SCALEMODE, &mode);
 }
 }


static int i8042_pm_resume_noirq(struct device *dev)
{
	if (!pm_resume_via_firmware())
		i8042_interrupt(0, NULL);

	return 0;
}


TEST(BasicFlatBufferModel, TestReadRuntimeVersionFromModel) {
  // First read a model that doesn't have the runtime string.
  auto model1 = FlatBufferModel::BuildFromFile(
      "tensorflow/lite/testdata/test_model.bin");
  ASSERT_TRUE(model1);
  ASSERT_EQ(model1->GetMinimumRuntime(), "");

  // Read a model that has minimum runtime string populated.
  auto model2 = FlatBufferModel::BuildFromFile(
      "tensorflow/lite/testdata/test_min_runtime.bin");
  ASSERT_TRUE(model2);
  // Check that we have read the runtime string correctly.
  ASSERT_EQ(model2->GetMinimumRuntime(), "1.5.0");
}


static int sbr_make_f_master ( AACContext * ac , SpectralBandReplication * sbr , SpectrumParameters * spectrum ) {
 unsigned int temp , max_qmf_subbands = 0 ;
 unsigned int start_min , stop_min ;
 int k ;
 const int8_t * sbr_offset_ptr ;
 int16_t stop_dk [ 13 ] ;
 if ( sbr -> sample_rate < 32000 ) {
 temp = 3000 ;
 }
 else if ( sbr -> sample_rate < 64000 ) {
 temp = 4000 ;
 }
 else temp = 5000 ;
 switch ( sbr -> sample_rate ) {
 case 16000 : sbr_offset_ptr = sbr_offset [ 0 ] ;
 break ;
 case 22050 : sbr_offset_ptr = sbr_offset [ 1 ] ;
 break ;
 case 24000 : sbr_offset_ptr = sbr_offset [ 2 ] ;
 break ;
 case 32000 : sbr_offset_ptr = sbr_offset [ 3 ] ;
 break ;
 case 44100 : case 48000 : case 64000 : sbr_offset_ptr = sbr_offset [ 4 ] ;
 break ;
 case 88200 : case 96000 : case 128000 : case 176400 : case 192000 : sbr_offset_ptr = sbr_offset [ 5 ] ;
 break ;
 default : av_log ( ac -> avctx , AV_LOG_ERROR , "Unsupported sample rate for SBR: %d\n" , sbr -> sample_rate ) ;
 return - 1 ;
 }
 start_min = ( ( temp << 7 ) + ( sbr -> sample_rate >> 1 ) ) / sbr -> sample_rate ;
 stop_min = ( ( temp << 8 ) + ( sbr -> sample_rate >> 1 ) ) / sbr -> sample_rate ;
 sbr -> k [ 0 ] = start_min + sbr_offset_ptr [ spectrum -> bs_start_freq ] ;
 if ( spectrum -> bs_stop_freq < 14 ) {
 sbr -> k [ 2 ] = stop_min ;
 make_bands ( stop_dk , stop_min , 64 , 13 ) ;
 qsort ( stop_dk , 13 , sizeof ( stop_dk [ 0 ] ) , qsort_comparison_function_int16 ) ;
 for ( k = 0 ;
 k < spectrum -> bs_stop_freq ;
 k ++ ) sbr -> k [ 2 ] += stop_dk [ k ] ;
 }
 else if ( spectrum -> bs_stop_freq == 14 ) {
 sbr -> k [ 2 ] = 2 * sbr -> k [ 0 ] ;
 }
 else if ( spectrum -> bs_stop_freq == 15 ) {
 sbr -> k [ 2 ] = 3 * sbr -> k [ 0 ] ;
 }
 else {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Invalid bs_stop_freq: %d\n" , spectrum -> bs_stop_freq ) ;
 return - 1 ;
 }
 sbr -> k [ 2 ] = FFMIN ( 64 , sbr -> k [ 2 ] ) ;
 if ( sbr -> sample_rate <= 32000 ) {
 max_qmf_subbands = 48 ;
 }
 else if ( sbr -> sample_rate == 44100 ) {
 max_qmf_subbands = 35 ;
 }
 else if ( sbr -> sample_rate >= 48000 ) max_qmf_subbands = 32 ;
 else av_assert0 ( 0 ) ;
 if ( sbr -> k [ 2 ] - sbr -> k [ 0 ] > max_qmf_subbands ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Invalid bitstream, too many QMF subbands: %d\n" , sbr -> k [ 2 ] - sbr -> k [ 0 ] ) ;
 return - 1 ;
 }
 if ( ! spectrum -> bs_freq_scale ) {
 int dk , k2diff ;
 dk = spectrum -> bs_alter_scale + 1 ;
 sbr -> n_master = ( ( sbr -> k [ 2 ] - sbr -> k [ 0 ] + ( dk & 2 ) ) >> dk ) << 1 ;
 if ( check_n_master ( ac -> avctx , sbr -> n_master , sbr -> spectrum_params . bs_xover_band ) ) return - 1 ;
 for ( k = 1 ;
 k <= sbr -> n_master ;
 k ++ ) sbr -> f_master [ k ] = dk ;
 k2diff = sbr -> k [ 2 ] - sbr -> k [ 0 ] - sbr -> n_master * dk ;
 if ( k2diff < 0 ) {
 sbr -> f_master [ 1 ] -- ;
 sbr -> f_master [ 2 ] -= ( k2diff < - 1 ) ;
 }
 else if ( k2diff ) {
 sbr -> f_master [ sbr -> n_master ] ++ ;
 }
 sbr -> f_master [ 0 ] = sbr -> k [ 0 ] ;
 for ( k = 1 ;
 k <= sbr -> n_master ;
 k ++ ) sbr -> f_master [ k ] += sbr -> f_master [ k - 1 ] ;
 }
 else {
 int half_bands = 7 - spectrum -> bs_freq_scale ;
 int two_regions , num_bands_0 ;
 int vdk0_max , vdk1_min ;
 int16_t vk0 [ 49 ] ;
 if ( 49 * sbr -> k [ 2 ] > 110 * sbr -> k [ 0 ] ) {
 two_regions = 1 ;
 sbr -> k [ 1 ] = 2 * sbr -> k [ 0 ] ;
 }
 else {
 two_regions = 0 ;
 sbr -> k [ 1 ] = sbr -> k [ 2 ] ;
 }
 num_bands_0 = lrintf ( half_bands * log2f ( sbr -> k [ 1 ] / ( float ) sbr -> k [ 0 ] ) ) * 2 ;
 if ( num_bands_0 <= 0 ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Invalid num_bands_0: %d\n" , num_bands_0 ) ;
 return - 1 ;
 }
 vk0 [ 0 ] = 0 ;
 make_bands ( vk0 + 1 , sbr -> k [ 0 ] , sbr -> k [ 1 ] , num_bands_0 ) ;
 qsort ( vk0 + 1 , num_bands_0 , sizeof ( vk0 [ 1 ] ) , qsort_comparison_function_int16 ) ;
 vdk0_max = vk0 [ num_bands_0 ] ;
 vk0 [ 0 ] = sbr -> k [ 0 ] ;
 for ( k = 1 ;
 k <= num_bands_0 ;
 k ++ ) {
 if ( vk0 [ k ] <= 0 ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Invalid vDk0[%d]: %d\n" , k , vk0 [ k ] ) ;
 return - 1 ;
 }
 vk0 [ k ] += vk0 [ k - 1 ] ;
 }
 if ( two_regions ) {
 int16_t vk1 [ 49 ] ;
 float invwarp = spectrum -> bs_alter_scale ? 0.76923076923076923077f : 1.0f ;
 int num_bands_1 = lrintf ( half_bands * invwarp * log2f ( sbr -> k [ 2 ] / ( float ) sbr -> k [ 1 ] ) ) * 2 ;
 make_bands ( vk1 + 1 , sbr -> k [ 1 ] , sbr -> k [ 2 ] , num_bands_1 ) ;
 vdk1_min = array_min_int16 ( vk1 + 1 , num_bands_1 ) ;
 if ( vdk1_min < vdk0_max ) {
 int change ;
 qsort ( vk1 + 1 , num_bands_1 , sizeof ( vk1 [ 1 ] ) , qsort_comparison_function_int16 ) ;
 change = FFMIN ( vdk0_max - vk1 [ 1 ] , ( vk1 [ num_bands_1 ] - vk1 [ 1 ] ) >> 1 ) ;
 vk1 [ 1 ] += change ;
 vk1 [ num_bands_1 ] -= change ;
 }
 qsort ( vk1 + 1 , num_bands_1 , sizeof ( vk1 [ 1 ] ) , qsort_comparison_function_int16 ) ;
 vk1 [ 0 ] = sbr -> k [ 1 ] ;
 for ( k = 1 ;
 k <= num_bands_1 ;
 k ++ ) {
 if ( vk1 [ k ] <= 0 ) {
 av_log ( ac -> avctx , AV_LOG_ERROR , "Invalid vDk1[%d]: %d\n" , k , vk1 [ k ] ) ;
 return - 1 ;
 }
 vk1 [ k ] += vk1 [ k - 1 ] ;
 }
 sbr -> n_master = num_bands_0 + num_bands_1 ;
 if ( check_n_master ( ac -> avctx , sbr -> n_master , sbr -> spectrum_params . bs_xover_band ) ) return - 1 ;
 memcpy ( & sbr -> f_master [ 0 ] , vk0 , ( num_bands_0 + 1 ) * sizeof ( sbr -> f_master [ 0 ] ) ) ;
 memcpy ( & sbr -> f_master [ num_bands_0 + 1 ] , vk1 + 1 , num_bands_1 * sizeof ( sbr -> f_master [ 0 ] ) ) ;
 }
 else {
 sbr -> n_master = num_bands_0 ;
 if ( check_n_master ( ac -> avctx , sbr -> n_master , sbr -> spectrum_params . bs_xover_band ) ) return - 1 ;
 memcpy ( sbr -> f_master , vk0 , ( num_bands_0 + 1 ) * sizeof ( sbr -> f_master [ 0 ] ) ) ;
 }
 }
 return 0 ;
 }


static guint32 amf_get_u29 ( tvbuff_t * tvb , int offset , guint * lenp ) {
 guint len = 0 ;
 guint8 iByte ;
 guint32 iValue ;
 iByte = tvb_get_guint8 ( tvb , offset ) ;
 iValue = ( iByte & 0x7F ) ;
 offset ++ ;
 len ++ ;
 if ( ! ( iByte & 0x80 ) ) {
 * lenp = len ;
 return iValue ;
 }
 iByte = tvb_get_guint8 ( tvb , offset ) ;
 iValue = ( iValue << 7 ) | ( iByte & 0x7F ) ;
 offset ++ ;
 len ++ ;
 if ( ! ( iByte & 0x80 ) ) {
 * lenp = len ;
 return iValue ;
 }
 iByte = tvb_get_guint8 ( tvb , offset ) ;
 iValue = ( iValue << 7 ) | ( iByte & 0x7F ) ;
 offset ++ ;
 len ++ ;
 if ( ! ( iByte & 0x80 ) ) {
 * lenp = len ;
 return iValue ;
 }
 iByte = tvb_get_guint8 ( tvb , offset ) ;
 iValue = ( iValue << 8 ) | iByte ;
 len ++ ;
 * lenp = len ;
 return iValue ;
 }


void ExtensionPrefs::SetAppLaunchIndex(const std::string& extension_id,
                                       int index) {
  DCHECK_GE(index, 0);
  UpdateExtensionPref(extension_id, kPrefAppLaunchIndex,
                      Value::CreateIntegerValue(index));
}


void ClientControlledShellSurface::OnDeviceScaleFactorChanged(float old_dsf,
                                                              float new_dsf) {
  views::View::OnDeviceScaleFactorChanged(old_dsf, new_dsf);
  UpdateFrameWidth();
}


RequestQuery ParseQuery(const GURL& url) {
  RequestQuery queries;
  for (QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
    std::string unescaped_query;
    UnescapeBinaryURLComponent(
        it.GetKey(), UnescapeRule::REPLACE_PLUS_WITH_SPACE, &unescaped_query);
    queries[unescaped_query].push_back(it.GetUnescapedValue());
  }
  return queries;
}


DEFINE_TEST(test_read_format_rar5_blake2)
{
	const la_ssize_t proper_size = 814;
	uint8_t buf[814];

	PROLOGUE("test_read_format_rar5_blake2.rar");
	assertA(0 == archive_read_next_header(a, &ae));
	assertEqualInt(proper_size, archive_entry_size(ae));

	/* Should blake2 calculation fail, we'll get a failure return
	 * value from archive_read_data(). */

	assertA(proper_size == archive_read_data(a, buf, proper_size));

	/* To be extra pedantic, let's also check crc32 of the poem. */
	assertEqualInt(crc32(0, buf, proper_size), 0x7E5EC49E);

	assertA(ARCHIVE_EOF == archive_read_next_header(a, &ae));
	EPILOGUE();
}


static FORCEINLINE mstate GetMSpace(nedpool *p, threadcache *tc, int mymspace, size_t size) THROWSPEC
{	/* Returns a locked and ready for use mspace */
	mstate m=p->m[mymspace];
	assert(m);
	if(!TRY_LOCK(&p->m[mymspace]->mutex)) m=FindMSpace(p, tc, &mymspace, size);\
	/*assert(IS_LOCKED(&p->m[mymspace]->mutex));*/
	return m;
}


ssize_t v9fs_get_xattr(FsContext *ctx, const char *path,
                       const char *name, void *value, size_t size)
{
    XattrOperations *xops = get_xattr_operations(ctx->xops, name);
    if (xops) {
        return xops->getxattr(ctx, path, name, value, size);
    }
    errno = EOPNOTSUPP;
    return -1;
}


static int local_lremovexattr(FsContext *ctx,

                              const char *path, const char *name)

{

    if ((ctx->fs_sm == SM_MAPPED) &&

        (strncmp(name, "user.virtfs.", 12) == 0)) {

        /*

         * Don't allow fetch of user.virtfs namesapce

         * in case of mapped security

         */

        errno = EACCES;

        return -1;

    }

    return lremovexattr(rpath(ctx, path), name);

}


void RenderFrameHostImpl::SetNetworkFactoryForTesting(
    const CreateNetworkFactoryCallback& create_network_factory_callback) {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(create_network_factory_callback.is_null() ||
         g_create_network_factory_callback_for_test.Get().is_null())
      << "It is not expected that this is called with non-null callback when "
      << "another overriding callback is already set.";
  g_create_network_factory_callback_for_test.Get() =
      create_network_factory_callback;
}


DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient(
    const net::BackoffEntry::Policy& backoff_policy,
    DataReductionProxyRequestOptions* request_options,
    DataReductionProxyMutableConfigValues* config_values,
    DataReductionProxyConfig* config,
    DataReductionProxyIOData* io_data,
    network::NetworkConnectionTracker* network_connection_tracker,
    ConfigStorer config_storer)
    : request_options_(request_options),
      config_values_(config_values),
      config_(config),
      io_data_(io_data),
      network_connection_tracker_(network_connection_tracker),
      config_storer_(config_storer),
      backoff_policy_(backoff_policy),
      backoff_entry_(&backoff_policy_),
      config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())),
      enabled_(false),
      remote_config_applied_(false),
#if defined(OS_ANDROID)
      foreground_fetch_pending_(false),
#endif
      previous_request_failed_authentication_(false),
      failed_attempts_before_success_(0),
      fetch_in_progress_(false),
      client_config_override_used_(false) {
  DCHECK(request_options);
  DCHECK(config_values);
   DCHECK(config);
   DCHECK(io_data);
   DCHECK(config_service_url_.is_valid());

   const base::CommandLine& command_line =
       *base::CommandLine::ForCurrentProcess();
  client_config_override_ = command_line.GetSwitchValueASCII(
      switches::kDataReductionProxyServerClientConfig);

  thread_checker_.DetachFromThread();
}


static int rtnl_setlink(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg)
{
	struct net *net = sock_net(skb->sk);
	struct ifinfomsg *ifm;
	struct net_device *dev;
	int err;
	struct nlattr *tb[IFLA_MAX+1];
	char ifname[IFNAMSIZ];

	err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy);
	if (err < 0)
		goto errout;

	if (tb[IFLA_IFNAME])
		nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ);
	else
		ifname[0] = '\0';

	err = -EINVAL;
	ifm = nlmsg_data(nlh);
	if (ifm->ifi_index > 0)
		dev = __dev_get_by_index(net, ifm->ifi_index);
	else if (tb[IFLA_IFNAME])
		dev = __dev_get_by_name(net, ifname);
	else
		goto errout;

	if (dev == NULL) {
		err = -ENODEV;
		goto errout;
	}

	err = validate_linkmsg(dev, tb);
	if (err < 0)
		goto errout;

	err = do_setlink(dev, ifm, tb, ifname, 0);
errout:
	return err;
}


int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si)
{
    EVP_MD_CTX mctx;
    EVP_PKEY_CTX *pctx;
    unsigned char *abuf = NULL;
    int alen;
    size_t siglen;
    const EVP_MD *md = NULL;

    md = EVP_get_digestbyobj(si->digest_alg->algorithm);
    if (md == NULL)
        return 0;

    EVP_MD_CTX_init(&mctx);
    if (EVP_DigestSignInit(&mctx, &pctx, md, NULL, si->pkey) <= 0)
        goto err;

    if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
                          EVP_PKEY_CTRL_PKCS7_SIGN, 0, si) <= 0) {
        PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
        goto err;
    }

    alen = ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, &abuf,
                         ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
    if (!abuf)
        goto err;
    if (EVP_DigestSignUpdate(&mctx, abuf, alen) <= 0)
        goto err;
    OPENSSL_free(abuf);
    abuf = NULL;
    if (EVP_DigestSignFinal(&mctx, NULL, &siglen) <= 0)
        goto err;
    abuf = OPENSSL_malloc(siglen);
    if (!abuf)
        goto err;
    if (EVP_DigestSignFinal(&mctx, abuf, &siglen) <= 0)
        goto err;

    if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
                          EVP_PKEY_CTRL_PKCS7_SIGN, 1, si) <= 0) {
        PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
        goto err;
    }

    EVP_MD_CTX_cleanup(&mctx);

    ASN1_STRING_set0(si->enc_digest, abuf, siglen);

    return 1;

 err:
    OPENSSL_free(abuf);
    EVP_MD_CTX_cleanup(&mctx);
    return 0;

}


  void FindAndTestFilePath(const FilePath& file_path) {
    GDataEntry* entry = FindEntry(file_path);
    ASSERT_TRUE(entry) << "Entry can't be found " << file_path.value();
    EXPECT_EQ(entry->GetFilePath(), file_path);
  }


  LookupResult* top_lookup_result() {
    return thread_local_top_.top_lookup_result_;
  }


bool WebSocketProtocol<isServer>::handleFragment(char *data, size_t length, unsigned int remainingBytes, int opCode, bool fin, void *user) {
    uS::Socket s((uv_poll_t *) user);
    typename WebSocket<isServer>::Data *webSocketData = (typename WebSocket<isServer>::Data *) s.getSocketData();

    if (opCode < 3) {
        if (!remainingBytes && fin && !webSocketData->fragmentBuffer.length()) {
            if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME) {
                webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::ENABLED;
                Hub *hub = ((Group<isServer> *) s.getSocketData()->nodeData)->hub;
                data = hub->inflate(data, length);
                if (!data) {
                    forceClose(user);
                    return true;
                }
            }

            if (opCode == 1 && !isValidUtf8((unsigned char *) data, length)) {
                forceClose(user);
                return true;
            }

            ((Group<isServer> *) s.getSocketData()->nodeData)->messageHandler(WebSocket<isServer>(s), data, length, (OpCode) opCode);
            if (s.isClosed() || s.isShuttingDown()) {
                return true;
            }
        } else {
            webSocketData->fragmentBuffer.append(data, length);
            if (!remainingBytes && fin) {
                length = webSocketData->fragmentBuffer.length();
                if (webSocketData->compressionStatus == WebSocket<isServer>::Data::CompressionStatus::COMPRESSED_FRAME) {
                    webSocketData->compressionStatus = WebSocket<isServer>::Data::CompressionStatus::ENABLED;
                    Hub *hub = ((Group<isServer> *) s.getSocketData()->nodeData)->hub;
                    webSocketData->fragmentBuffer.append("....");
                    data = hub->inflate((char *) webSocketData->fragmentBuffer.data(), length);
                    if (!data) {
                        forceClose(user);
                        return true;
                    }
                } else {
                    data = (char *) webSocketData->fragmentBuffer.data();
                }

                if (opCode == 1 && !isValidUtf8((unsigned char *) data, length)) {
                    forceClose(user);
                    return true;
                }

                ((Group<isServer> *) s.getSocketData()->nodeData)->messageHandler(WebSocket<isServer>(s), data, length, (OpCode) opCode);
                if (s.isClosed() || s.isShuttingDown()) {
                    return true;
                }
                webSocketData->fragmentBuffer.clear();
            }
        }
    } else {
        // todo: we don't need to buffer up in most cases!
        webSocketData->controlBuffer.append(data, length);
        if (!remainingBytes && fin) {
            if (opCode == CLOSE) {
                CloseFrame closeFrame = parseClosePayload((char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
                WebSocket<isServer>(s).close(closeFrame.code, closeFrame.message, closeFrame.length);
                return true;
            } else {
                if (opCode == PING) {
                    WebSocket<isServer>(s).send(webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length(), (OpCode) OpCode::PONG);
                    ((Group<isServer> *) s.getSocketData()->nodeData)->pingHandler(WebSocket<isServer>(s), (char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
                    if (s.isClosed() || s.isShuttingDown()) {
                        return true;
                    }
                } else if (opCode == PONG) {
                    ((Group<isServer> *) s.getSocketData()->nodeData)->pongHandler(WebSocket<isServer>(s), (char *) webSocketData->controlBuffer.data(), webSocketData->controlBuffer.length());
                    if (s.isClosed() || s.isShuttingDown()) {
                        return true;
                    }
                }
            }
            webSocketData->controlBuffer.clear();
        }
    }

    return false;
}


AP4_MetaDataStringAtom::WriteFields(AP4_ByteStream& stream)
{
    stream.WriteUI32(m_Reserved);
    return stream.Write(m_Value.GetChars(), m_Value.GetLength());
}


format_SET_IPV4_DST(const struct ofpact_ipv4 *a,
                    const struct ofpact_format_params *fp)
{
    ds_put_format(fp->s, "%smod_nw_dst:%s"IP_FMT,
                  colors.param, colors.end, IP_ARGS(a->ipv4));
}


_PyObject_ArenaMalloc(void *ctx, size_t size)
{
    return malloc(size);
}


static int floppy_revalidate(struct gendisk *disk)
{
	int drive = (long)disk->private_data;
	int cf;
	int res = 0;

	if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
	    test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
	    test_bit(drive, &fake_change) ||
	    drive_no_geom(drive)) {
		if (WARN(atomic_read(&usage_count) == 0,
			 "VFS: revalidate called on non-open device.\n"))
			return -EFAULT;

		lock_fdc(drive, false);
		cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
		      test_bit(FD_VERIFY_BIT, &UDRS->flags));
		if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) {
			process_fd_request();	/*already done by another thread */
			return 0;
		}
		UDRS->maxblock = 0;
		UDRS->maxtrack = 0;
		if (buffer_drive == drive)
			buffer_track = -1;
		clear_bit(drive, &fake_change);
		clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
		if (cf)
			UDRS->generation++;
		if (drive_no_geom(drive)) {
			/* auto-sensing */
			res = __floppy_read_block_0(opened_bdev[drive], drive);
		} else {
			if (cf)
				poll_drive(false, FD_RAW_NEED_DISK);
			process_fd_request();
		}
	}
	set_capacity(disk, floppy_sizes[UDRS->fd_device]);
	return res;
}


void nfs_clear_verifier_delegated(struct inode *inode)
{
	struct dentry *alias;

	if (!inode)
		return;
	spin_lock(&inode->i_lock);
	hlist_for_each_entry(alias, &inode->i_dentry, d_u.d_alias) {
		spin_lock(&alias->d_lock);
		nfs_unset_verifier_delegated(&alias->d_time);
		spin_unlock(&alias->d_lock);
	}
	spin_unlock(&inode->i_lock);
}


static char *tcm_loop_parse_pr_out_transport_id(
	struct se_portal_group *se_tpg,
	const char *buf,
	u32 *out_tid_len,
	char **port_nexus_ptr)
{
	struct tcm_loop_tpg *tl_tpg =
			(struct tcm_loop_tpg *)se_tpg->se_tpg_fabric_ptr;
	struct tcm_loop_hba *tl_hba = tl_tpg->tl_hba;

	switch (tl_hba->tl_proto_id) {
	case SCSI_PROTOCOL_SAS:
		return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
					port_nexus_ptr);
	case SCSI_PROTOCOL_FCP:
		return fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
					port_nexus_ptr);
	case SCSI_PROTOCOL_ISCSI:
		return iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
					port_nexus_ptr);
	default:
		printk(KERN_ERR "Unknown tl_proto_id: 0x%02x, using"
			" SAS emulation\n", tl_hba->tl_proto_id);
		break;
	}

	return sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
			port_nexus_ptr);
}


Pickler_get_memo(PicklerObject *self)
{
    return PicklerMemoProxy_New(self);
}


void FileBrowserPrivateGetDriveFilesFunction::OnFileReady(
    drive::FileError error,
    const base::FilePath& local_path,
    scoped_ptr<drive::ResourceEntry> entry) {
  base::FilePath drive_path = remaining_drive_paths_.front();

  if (error == drive::FILE_ERROR_OK) {
    local_paths_.push_back(local_path.AsUTF8Unsafe());
    DVLOG(1) << "Got " << drive_path.value() << " as " << local_path.value();
  } else {
    local_paths_.push_back("");
    DVLOG(1) << "Failed to get " << drive_path.value()
             << " with error code: " << error;
  }

  remaining_drive_paths_.pop();

  GetFileOrSendResponse();
}


void FrameSelection::ClearPreviousCaretVisualRect(const LayoutBlock& block) {
  frame_caret_->ClearPreviousVisualRect(block);
}


IRBuilder &LReference::getBuilder() {
  return irgen_->Builder;
}


translated_function_exists(char_u *name, int is_global)
{
    if (builtin_function(name, -1))
	return has_internal_func(name);
    return find_func(name, is_global, NULL) != NULL;
}


int inet_csk_listen_start(struct sock *sk, int backlog)
{
	struct inet_connection_sock *icsk = inet_csk(sk);
	struct inet_sock *inet = inet_sk(sk);
	int err = -EADDRINUSE;

	reqsk_queue_alloc(&icsk->icsk_accept_queue);

	sk->sk_max_ack_backlog = backlog;
	sk->sk_ack_backlog = 0;
	inet_csk_delack_init(sk);

	/* There is race window here: we announce ourselves listening,
	 * but this transition is still not validated by get_port().
	 * It is OK, because this socket enters to hash table only
	 * after validation is complete.
	 */
	sk_state_store(sk, TCP_LISTEN);
	if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
		inet->inet_sport = htons(inet->inet_num);

		sk_dst_reset(sk);
		err = sk->sk_prot->hash(sk);

		if (likely(!err))
			return 0;
	}

	sk->sk_state = TCP_CLOSE;
	return err;
}


void LocalFrameClientImpl::DidObserveLoadingBehavior(
    WebLoadingBehaviorFlag behavior) {
  if (web_frame_->Client())
    web_frame_->Client()->DidObserveLoadingBehavior(behavior);
}


dissect_SPOOL_PRINTER_INFO(tvbuff_t *tvb, int offset, packet_info *pinfo,
			   proto_tree *tree, dcerpc_info *di, guint8 *drep)
{
	proto_tree *subtree;
	guint32 level;
	proto_tree *item;

	subtree = proto_tree_add_subtree(
		tree, tvb, offset, 0, ett_SPOOL_PRINTER_INFO_LEVEL, &item, "Spool printer info level");

	offset = dissect_ndr_uint32(
		tvb, offset, pinfo, subtree, di, drep, hf_level, &level);

	switch(level) {
	case 3: {
		guint32 devmode_ptr, secdesc_ptr;

		/* I can't seem to get this working with the correct
		   dissect_ndr_pointer() function so let's cheat and
		   dissect the pointers by hand. )-: */

		offset = dissect_ndr_uint32(
			tvb, offset, pinfo, subtree, di, drep,
			hf_spool_printer_info_devmode_ptr,
			&devmode_ptr);

		offset = dissect_ndr_uint32(
			tvb, offset, pinfo, subtree, di, drep,
			hf_spool_printer_info_secdesc_ptr,
			&secdesc_ptr);

		if (devmode_ptr)
			offset = dissect_DEVMODE_CTR(
				tvb, offset, pinfo, subtree, di, drep);

		if (secdesc_ptr)
			offset = dissect_SEC_DESC_BUF(
				tvb, offset, pinfo, subtree, di, drep);

	break;
	}
	case 2:
	default:
		expert_add_info_format(pinfo, item, &ei_spool_printer_info_level, "Unknown spool printer info level %d", level);
		break;
	}

	return offset;
}


void ff_aac_search_for_pred(AACEncContext *s, SingleChannelElement *sce)

{

    int sfb, i, count = 0, cost_coeffs = 0, cost_pred = 0;

    const int pmax = FFMIN(sce->ics.max_sfb, ff_aac_pred_sfb_max[s->samplerate_index]);

    float *O34  = &s->scoefs[128*0], *P34 = &s->scoefs[128*1];

    float *SENT = &s->scoefs[128*2], *S34 = &s->scoefs[128*3];

    float *QERR = &s->scoefs[128*4];

    if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        sce->ics.predictor_present = 0;

        return;

    }

    if (!sce->ics.predictor_initialized) {

        reset_all_predictors(sce->predictor_state);

        sce->ics.predictor_initialized = 1;

        memcpy(sce->prcoeffs, sce->coeffs, 1024*sizeof(float));

        for (i = 1; i < 31; i++)

            sce->ics.predictor_reset_count[i] = i;

    }

    update_pred_resets(sce);

    memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));

    for (sfb = PRED_SFB_START; sfb < pmax; sfb++) {

        int cost1, cost2, cb_p;

        float dist1, dist2, dist_spec_err = 0.0f;

        const int cb_n = sce->band_type[sfb];

        const int start_coef = sce->ics.swb_offset[sfb];

        const int num_coeffs = sce->ics.swb_offset[sfb + 1] - start_coef;

        const FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[sfb];

        if (start_coef + num_coeffs > MAX_PREDICTORS ||

            (s->cur_channel && sce->band_type[sfb] >= INTENSITY_BT2) ||

            sce->band_type[sfb] == NOISE_BT)

            continue;

        /* Normal coefficients */

        abs_pow34_v(O34, &sce->coeffs[start_coef], num_coeffs);

        dist1 = quantize_and_encode_band_cost(s, NULL, &sce->coeffs[start_coef], NULL,

                                              O34, num_coeffs, sce->sf_idx[sfb],

                                              cb_n, s->lambda / band->threshold, INFINITY, &cost1, NULL, 0);

        cost_coeffs += cost1;

        /* Encoded coefficients - needed for #bits, band type and quant. error */

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

            SENT[i] = sce->coeffs[start_coef + i] - sce->prcoeffs[start_coef + i];

        abs_pow34_v(S34, SENT, num_coeffs);

        if (cb_n < RESERVED_BT)

            cb_p = find_min_book(find_max_val(1, num_coeffs, S34), sce->sf_idx[sfb]);

        else

            cb_p = cb_n;

        quantize_and_encode_band_cost(s, NULL, SENT, QERR, S34, num_coeffs,

                                      sce->sf_idx[sfb], cb_p, s->lambda / band->threshold, INFINITY,

                                      &cost2, NULL, 0);

        /* Reconstructed coefficients - needed for distortion measurements */

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

            sce->prcoeffs[start_coef + i] += QERR[i] != 0.0f ? (sce->prcoeffs[start_coef + i] - QERR[i]) : 0.0f;

        abs_pow34_v(P34, &sce->prcoeffs[start_coef], num_coeffs);

        if (cb_n < RESERVED_BT)

            cb_p = find_min_book(find_max_val(1, num_coeffs, P34), sce->sf_idx[sfb]);

        else

            cb_p = cb_n;

        dist2 = quantize_and_encode_band_cost(s, NULL, &sce->prcoeffs[start_coef], NULL,

                                              P34, num_coeffs, sce->sf_idx[sfb],

                                              cb_p, s->lambda / band->threshold, INFINITY, NULL, NULL, 0);

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

            dist_spec_err += (O34[i] - P34[i])*(O34[i] - P34[i]);

        dist_spec_err *= s->lambda / band->threshold;

        dist2 += dist_spec_err;

        if (dist2 <= dist1 && cb_p <= cb_n) {

            cost_pred += cost2;

            sce->ics.prediction_used[sfb] = 1;

            sce->band_alt[sfb]  = cb_n;

            sce->band_type[sfb] = cb_p;

            count++;

        } else {

            cost_pred += cost1;

            sce->band_alt[sfb] = cb_p;

        }

    }

    if (count && cost_coeffs < cost_pred) {

        count = 0;

        for (sfb = PRED_SFB_START; sfb < pmax; sfb++)

            RESTORE_PRED(sce, sfb);

        memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));

    }

    sce->ics.predictor_present = !!count;

}


RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
    RenderWidgetHostImpl* receiving_widget) {
  if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
    return receiving_widget;

  if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
    return receiving_widget;

  FrameTreeNode* focused_frame = frame_tree_.GetFocusedFrame();
  if (!focused_frame)
    return receiving_widget;

  RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
  if (!view)
    return nullptr;

  return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
}


config_ntpd(
	config_tree *ptree
	)
{
	config_nic_rules(ptree);
	io_open_sockets();
	config_monitor(ptree);
	config_auth(ptree);
	config_tos(ptree);
	config_access(ptree);
	config_tinker(ptree);
	config_system_opts(ptree);
	config_logconfig(ptree);
	config_phone(ptree);
	config_setvar(ptree);
	config_ttl(ptree);
	config_trap(ptree);
	config_vars(ptree);
	config_other_modes(ptree);
	config_peers(ptree);
	config_unpeers(ptree);
	config_fudge(ptree);
	config_qos(ptree);

#ifdef TEST_BLOCKING_WORKER
	{
		struct addrinfo hints;

		memset(&hints, 0, sizeof(hints));
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_protocol = IPPROTO_TCP;
		getaddrinfo_sometime("www.cnn.com", "ntp", &hints,
				     INITIAL_DNS_RETRY,
				     gai_test_callback, (void *)1);
		hints.ai_family = AF_INET6;
		getaddrinfo_sometime("ipv6.google.com", "ntp", &hints,
				     INITIAL_DNS_RETRY,
				     gai_test_callback, (void *)0x600);
	}
#endif
}


LocalFrameClientImpl::CreateServiceWorkerProvider() {
  if (!web_frame_->Client())
    return nullptr;
  return web_frame_->Client()->CreateServiceWorkerProvider();
}


static unsigned int floppy_check_events(struct gendisk *disk,
					unsigned int clearing)
{
	int drive = (long)disk->private_data;

	if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
	    test_bit(FD_VERIFY_BIT, &UDRS->flags))
		return DISK_EVENT_MEDIA_CHANGE;

	if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) {
		lock_fdc(drive, false);
		poll_drive(false, 0);
		process_fd_request();
	}

	if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
	    test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
	    test_bit(drive, &fake_change) ||
	    drive_no_geom(drive))
		return DISK_EVENT_MEDIA_CHANGE;
	return 0;
}


static unsigned long stack_maxrandom_size(void)
{
	unsigned long max = 0;
	if ((current->flags & PF_RANDOMIZE) &&
		!(current->personality & ADDR_NO_RANDOMIZE)) {
		max = ((-1UL) & STACK_RND_MASK) << PAGE_SHIFT;
	}

	return max;
}


R_API RBinSymbol *r_bin_file_add_method(RBinFile *bf, const char *klass, const char *method, int nargs) {
	r_return_val_if_fail (bf, NULL);

	RBinClass *c = r_bin_file_add_class (bf, klass, NULL, 0);
	if (!c) {
		eprintf ("Cannot allocate class %s\n", klass);
		return NULL;
	}
	RBinSymbol *sym = __getMethod (bf, klass, method);
	if (!sym) {
		sym = R_NEW0 (RBinSymbol);
		if (sym) {
			sym->name = strdup (method);
			r_list_append (c->methods, sym);
			char *name = r_str_newf ("%s::%s", klass, method);
			ht_pp_insert (bf->o->methods_ht, name, sym);
			free (name);
		}
	}
	return sym;
}


Document* BaseAudioContext::GetDocument() const {
  return To<Document>(GetExecutionContext());
}


guestfs___parse_major_minor (guestfs_h *g, struct inspect_fs *fs)
{
  char *major, *minor;

  if (match2 (g, fs->product_name, re_major_minor, &major, &minor)) {
    fs->major_version = guestfs___parse_unsigned_int (g, major);
    free (major);
    if (fs->major_version == -1) {
      free (minor);
      return -1;
    }
    fs->minor_version = guestfs___parse_unsigned_int (g, minor);
    free (minor);
    if (fs->minor_version == -1)
      return -1;
  }
  return 0;
}


bool FrameSelection::Contains(const LayoutPoint& point) {
  if (GetDocument().GetLayoutViewItem().IsNull())
    return false;

  const VisibleSelectionInFlatTree& visible_selection =
      ComputeVisibleSelectionInFlatTree();
  if (!visible_selection.IsRange())
    return false;

  HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
  HitTestResult result(request, point);
  GetDocument().GetLayoutViewItem().HitTest(result);
  Node* inner_node = result.InnerNode();
  if (!inner_node || !inner_node->GetLayoutObject())
    return false;

  const VisiblePositionInFlatTree& visible_pos =
      CreateVisiblePosition(FromPositionInDOMTree<EditingInFlatTreeStrategy>(
          inner_node->GetLayoutObject()->PositionForPoint(
              result.LocalPoint())));
  if (visible_pos.IsNull())
    return false;

  const VisiblePositionInFlatTree& visible_start =
      visible_selection.VisibleStart();
  const VisiblePositionInFlatTree& visible_end = visible_selection.VisibleEnd();
  if (visible_start.IsNull() || visible_end.IsNull())
    return false;

  const PositionInFlatTree& start = visible_start.DeepEquivalent();
  const PositionInFlatTree& end = visible_end.DeepEquivalent();
  const PositionInFlatTree& pos = visible_pos.DeepEquivalent();
  return start.CompareTo(pos) <= 0 && pos.CompareTo(end) <= 0;
}


xml_acl_disable(xmlNode *xml)
{
    if(xml_acl_enabled(xml)) {
        xml_private_t *p = xml->doc->_private;

        /* Catch anything that was created but shouldn't have been */
        __xml_acl_apply(xml);
        __xml_acl_post_process(xml);
        clear_bit(p->flags, xpf_acl_enabled);
    }
}


const Tracks* Segment::GetTracks() const
const SegmentInfo* Segment::GetInfo() const { return m_pInfo; }

const Cues* Segment::GetCues() const { return m_pCues; }

const Chapters* Segment::GetChapters() const { return m_pChapters; }

const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; }

long long Segment::GetDuration() const {
  assert(m_pInfo);
  return m_pInfo->GetDuration();
 }


v8::Handle<v8::Value> V8TestEventConstructor::constructorCallback(const v8::Arguments& args)
{
    INC_STATS("DOM.TestEventConstructor.Constructor");

    if (!args.IsConstructCall())
        return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");

    if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
         return args.Holder();

     if (args.Length() < 1)
        return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());

     STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]);
     TestEventConstructorInit eventInit;
    if (args.Length() >= 2) {
        EXCEPTION_BLOCK(Dictionary, options, args[1]);
        if (!fillTestEventConstructorInit(eventInit, options))
            return v8::Undefined();
    }

    RefPtr<TestEventConstructor> event = TestEventConstructor::create(type, eventInit);

    V8DOMWrapper::setDOMWrapper(args.Holder(), &info, event.get());
    V8DOMWrapper::setJSWrapperForDOMObject(event.release(), v8::Persistent<v8::Object>::New(args.Holder()), args.GetIsolate());
    return args.Holder();
}


void setup_SSL_CTX(SSL_CTX* ctx) {
#ifdef SSL_MODE_RELEASE_BUFFERS
  SSL_CTX_set_mode(
      ctx,
      SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE |
          SSL_MODE_RELEASE_BUFFERS);
#else
  SSL_CTX_set_mode(
      ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
#endif
// SSL_CTX_set_mode is a Macro
#ifdef SSL_MODE_WRITE_IOVEC
  SSL_CTX_set_mode(ctx, SSL_CTX_get_mode(ctx) | SSL_MODE_WRITE_IOVEC);
#endif
}


int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)
{
  uchar *end= mysql->net.read_pos+length;
  size_t item_len;
  mysql->affected_rows= net_field_length_ll(&pos);
  mysql->insert_id=	  net_field_length_ll(&pos);
  mysql->server_status=uint2korr(pos);
  pos+=2;
  mysql->warning_count=uint2korr(pos);
  pos+=2;
  if (pos > end)
    goto corrupted;
  if (pos < end)
  {
    if ((item_len= net_field_length(&pos)))
      mysql->info=(char*) pos;
    if (pos + item_len > end)
      goto corrupted;

    /* check if server supports session tracking */
    if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)
    {
      ma_clear_session_state(mysql);
      pos+= item_len;

      if (mysql->server_status & SERVER_SESSION_STATE_CHANGED)
      {
        int i;
        if (pos < end)
        {
          LIST *session_item;
          MYSQL_LEX_STRING *str= NULL;
          enum enum_session_state_type si_type;
          uchar *old_pos= pos;

          item_len= net_field_length(&pos);  /* length for all items */
          if (pos + item_len > end)
            goto corrupted;
          end= pos + item_len;

          /* length was already set, so make sure that info will be zero terminated */
          if (mysql->info)
            *old_pos= 0;

          while (pos < end)
          {
            size_t plen;
            char *data;
            si_type= (enum enum_session_state_type)net_field_length(&pos);
            switch(si_type) {
            case SESSION_TRACK_SCHEMA:
            case SESSION_TRACK_STATE_CHANGE:
            case SESSION_TRACK_TRANSACTION_CHARACTERISTICS:
            case SESSION_TRACK_SYSTEM_VARIABLES:
              if (si_type != SESSION_TRACK_STATE_CHANGE)
                net_field_length(&pos); /* ignore total length, item length will follow next */
              plen= net_field_length(&pos);
              if (pos + plen > end)
                goto corrupted;
              if (!(session_item= ma_multi_malloc(0,
                                  &session_item, sizeof(LIST),
                                  &str, sizeof(MYSQL_LEX_STRING),
                                  &data, plen,
                                  NULL)))
                  goto oom;
              str->length= plen;
              str->str= data;
              memcpy(str->str, (char *)pos, plen);
              pos+= plen;
              session_item->data= str;
              mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);

              /* in case schema has changed, we have to update mysql->db */
              if (si_type == SESSION_TRACK_SCHEMA)
              {
                free(mysql->db);
                mysql->db= malloc(plen + 1);
                memcpy(mysql->db, str->str, plen);
                mysql->db[plen]= 0;
              }
              else if (si_type == SESSION_TRACK_SYSTEM_VARIABLES)
              {
                my_bool set_charset= 0;
                /* make sure that we update charset in case it has changed */
                if (!strncmp(str->str, "character_set_client", str->length))
                  set_charset= 1;
                plen= net_field_length(&pos);
                if (pos + plen > end)
                  goto corrupted;
                if (!(session_item= ma_multi_malloc(0,
                                    &session_item, sizeof(LIST),
                                    &str, sizeof(MYSQL_LEX_STRING),
                                    &data, plen,
                                    NULL)))
                  goto oom;
                str->length= plen;
                str->str= data;
                memcpy(str->str, (char *)pos, plen);
                pos+= plen;
                session_item->data= str;
                mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);
                if (set_charset && str->length < CHARSET_NAME_LEN &&
                    strncmp(mysql->charset->csname, str->str, str->length) != 0)
                {
                  char cs_name[CHARSET_NAME_LEN];
                  const MARIADB_CHARSET_INFO *cs_info;
                  memcpy(cs_name, str->str, str->length);
                  cs_name[str->length]= 0;
                  if ((cs_info = mysql_find_charset_name(cs_name)))
                    mysql->charset= cs_info;
                }
              }
              break;
            default:
              /* not supported yet */
              plen= net_field_length(&pos);
              if (pos + plen > end)
                goto corrupted;
              pos+= plen;
              break;
            }
          }
        }
        for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++)
        {
          mysql->extension->session_state[i].list= list_reverse(mysql->extension->session_state[i].list);
          mysql->extension->session_state[i].current= mysql->extension->session_state[i].list;
        }
      }
    }
  }
  /* CONC-351: clear session state information */
  else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)
    ma_clear_session_state(mysql);
  return(0);

oom:
  ma_clear_session_state(mysql);
  SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);
  return -1;

corrupted:
  ma_clear_session_state(mysql);
  SET_CLIENT_ERROR(mysql, CR_MALFORMED_PACKET, SQLSTATE_UNKNOWN, 0);
  return -1;
}


void blk_mq_free_hctx_request(struct blk_mq_hw_ctx *hctx, struct request *rq)
{
	struct blk_mq_ctx *ctx = rq->mq_ctx;

	ctx->rq_completed[rq_is_sync(rq)]++;
	__blk_mq_free_request(hctx, ctx, rq);

}


void Scrollbar::updateThumbPosition()
{
    updateThumb();
}


static inline void f2fs_i_xnid_write(struct inode *inode, nid_t xnid)
{
	F2FS_I(inode)->i_xattr_nid = xnid;
	f2fs_mark_inode_dirty_sync(inode, true);
}


static String ValueBackColor(const EditorInternalCommand&,
                             LocalFrame& frame,
                             Event*) {
  return ValueStyle(frame, CSSPropertyBackgroundColor);
}


void StopChildProcess(base::ProcessHandle handle) {
  DCHECK(CurrentlyOnProcessLauncherTaskRunner());
  JNIEnv* env = AttachCurrentThread();
  DCHECK(env);
  Java_ChildProcessLauncherHelperImpl_stop(env, static_cast<jint>(handle));
}


void BrowserMainLoop::Init() {
  TRACE_EVENT0("startup", "BrowserMainLoop::Init");

  parts_.reset(
      GetContentClient()->browser()->CreateBrowserMainParts(parameters_));
}


GF_Err sidx_Read(GF_Box *s,GF_BitStream *bs)
{
	u32 i;
	GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s;

	ptr->reference_ID = gf_bs_read_u32(bs);
	ptr->timescale = gf_bs_read_u32(bs);
	ISOM_DECREASE_SIZE(ptr, 8);

	if (ptr->version==0) {
		ptr->earliest_presentation_time = gf_bs_read_u32(bs);
		ptr->first_offset = gf_bs_read_u32(bs);
		ISOM_DECREASE_SIZE(ptr, 8);
	} else {
		ptr->earliest_presentation_time = gf_bs_read_u64(bs);
		ptr->first_offset = gf_bs_read_u64(bs);
		ISOM_DECREASE_SIZE(ptr, 16);
	}
	gf_bs_read_u16(bs); /* reserved */
	ptr->nb_refs = gf_bs_read_u16(bs);
	ISOM_DECREASE_SIZE(ptr, 4);

	ptr->refs = gf_malloc(sizeof(GF_SIDXReference)*ptr->nb_refs);
	for (i=0; i<ptr->nb_refs; i++) {
		ptr->refs[i].reference_type = gf_bs_read_int(bs, 1);
		ptr->refs[i].reference_size = gf_bs_read_int(bs, 31);
		ptr->refs[i].subsegment_duration = gf_bs_read_u32(bs);
		ptr->refs[i].starts_with_SAP = gf_bs_read_int(bs, 1);
		ptr->refs[i].SAP_type = gf_bs_read_int(bs, 3);
		ptr->refs[i].SAP_delta_time = gf_bs_read_int(bs, 28);

		ISOM_DECREASE_SIZE(ptr, 12);
	}
	return GF_OK;
}


lyd_replace(struct lyd_node *orig, struct lyd_node *repl, int destroy)
{
    struct lyd_node *iter, *last;

    if (!repl) {
        /* remove the old one */
        goto finish;
    }

    if (repl->parent || repl->prev->next) {
        /* isolate the new node */
        repl->next = NULL;
        repl->prev = repl;
        last = repl;
    } else {
        /* get the last node of a possible list of nodes to be inserted */
        for(last = repl; last->next; last = last->next) {
            /* part of the parent changes */
            last->parent = orig->parent;
        }
    }

    /* parent */
    if (orig->parent) {
        if (orig->parent->child == orig) {
            orig->parent->child = repl;
        }
        orig->parent = NULL;
    }

    /* predecessor */
    if (orig->prev == orig) {
        /* the old was alone */
        goto finish;
    }
    if (orig->prev->next) {
        orig->prev->next = repl;
    }
    repl->prev = orig->prev;
    orig->prev = orig;

    /* successor */
    if (orig->next) {
        orig->next->prev = last;
        last->next = orig->next;
        orig->next = NULL;
    } else {
        /* fix the last pointer */
        if (repl->parent) {
            repl->parent->child->prev = last;
        } else {
            /* get the first sibling */
            for (iter = repl; iter->prev != orig; iter = iter->prev);
            iter->prev = last;
        }
    }

finish:
    /* remove the old one */
    if (destroy) {
        lyd_free(orig);
    }
}


iemsg(char *s)
{
    if (!emsg_not_now())
    {
	emsg_core((char_u *)s);
#if defined(ABORT_ON_INTERNAL_ERROR) && defined(FEAT_EVAL)
	set_vim_var_string(VV_ERRMSG, (char_u *)s, -1);
	abort();
#endif
    }
}


eap_send_failure(esp)
eap_state *esp;
{
	u_char *outp;

	outp = outpacket_buf;

	MAKEHEADER(outp, PPP_EAP);

	PUTCHAR(EAP_FAILURE, outp);
	esp->es_server.ea_id++;
	PUTCHAR(esp->es_server.ea_id, outp);
	PUTSHORT(EAP_HEADERLEN, outp);

	output(esp->es_unit, outpacket_buf, EAP_HEADERLEN + PPP_HDRLEN);

	esp->es_server.ea_state = eapBadAuth;
	auth_peer_fail(esp->es_unit, PPP_EAP);
}


MediaControlCastButtonElement::MediaControlCastButtonElement(
    MediaControls& mediaControls,
    bool isOverlayButton)
    : MediaControlInputElement(mediaControls, MediaCastOnButton),
      m_isOverlayButton(isOverlayButton) {
  if (m_isOverlayButton)
    recordMetrics(CastOverlayMetrics::Created);
  setIsPlayingRemotely(false);
}


static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
{
	return static_call(kvm_x86_complete_emulated_msr)(vcpu, vcpu->run->msr.error);
}


static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
				       int level)
{
	printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level);

	/* 010b (write-only) */
	WARN_ON((spte & 0x7) == 0x2);

	/* 110b (write/execute) */
	WARN_ON((spte & 0x7) == 0x6);

	/* 100b (execute-only) and value not supported by logical processor */
	if (!cpu_has_vmx_ept_execute_only())
		WARN_ON((spte & 0x7) == 0x4);

	/* not 000b */
	if ((spte & 0x7)) {
		u64 rsvd_bits = spte & ept_rsvd_mask(spte, level);

		if (rsvd_bits != 0) {
			printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n",
					 __func__, rsvd_bits);
			WARN_ON(1);
		}

		if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) {
			u64 ept_mem_type = (spte & 0x38) >> 3;

			if (ept_mem_type == 2 || ept_mem_type == 3 ||
			    ept_mem_type == 7) {
				printk(KERN_ERR "%s: ept_mem_type=0x%llx\n",
						__func__, ept_mem_type);
				WARN_ON(1);
			}
		}
	}
}


static int sas_configure_phy(struct domain_device *dev, int phy_id,
				    u8 *sas_addr, int include)
{
	int index;
	int present;
	int res;

	res = sas_configure_present(dev, phy_id, sas_addr, &index, &present);
	if (res)
		return res;
	if (include ^ present)
		return sas_configure_set(dev, phy_id, sas_addr, index,include);

	return res;
}


  void AddNodeInputs() {
    for (int i = 0; i < result_.nodes.size(); i++) {
      NodeInfo& node_info = nodes_[i];
      for (const auto& p : node_info.data_inputs) {
        result_.nodes[i].add_input(Name(p.first, p.second));
      }
      for (int index : node_info.control_inputs) {
        result_.nodes[i].add_input(Dep(index));
      }
    }
  }


void exit_io_context(void)
{
	struct io_context *ioc;

	task_lock(current);
	ioc = current->io_context;
	current->io_context = NULL;
	task_unlock(current);

	if (atomic_dec_and_test(&ioc->nr_tasks)) {
		if (ioc->aic && ioc->aic->exit)
			ioc->aic->exit(ioc->aic);
		cfq_exit(ioc);

	}
	put_io_context(ioc);
}


static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
{
    assert(fv);
    MemoryRegionSection section = {
        .fv = fv,
        .mr = mr,
        .offset_within_address_space = 0,
        .offset_within_region = 0,
        .size = int128_2_64(),
    };

    return phys_section_add(map, &section);
}


PassRefPtr<TypeBuilder::Page::Frame> InspectorPageAgent::buildObjectForFrame(Frame* frame)
{
    RefPtr<TypeBuilder::Page::Frame> frameObject = TypeBuilder::Page::Frame::create()
        .setId(frameId(frame))
        .setLoaderId(loaderId(frame->loader().documentLoader()))
        .setUrl(urlWithoutFragment(frame->document()->url()).string())
        .setMimeType(frame->loader().documentLoader()->responseMIMEType())
        .setSecurityOrigin(frame->document()->securityOrigin()->toRawString());
    if (frame->tree().parent())
        frameObject->setParentId(frameId(frame->tree().parent()));
    if (frame->ownerElement()) {
        AtomicString name = frame->ownerElement()->getNameAttribute();
        if (name.isEmpty())
            name = frame->ownerElement()->getAttribute(HTMLNames::idAttr);
        frameObject->setName(name);
    }

    return frameObject;
}


struct se_portal_group *tcm_loop_make_naa_tpg(
	struct se_wwn *wwn,
	struct config_group *group,
	const char *name)
{
	struct tcm_loop_hba *tl_hba = container_of(wwn,
			struct tcm_loop_hba, tl_hba_wwn);
	struct tcm_loop_tpg *tl_tpg;
	char *tpgt_str, *end_ptr;
	int ret;
	unsigned short int tpgt;

	tpgt_str = strstr(name, "tpgt_");
	if (!tpgt_str) {
		printk(KERN_ERR "Unable to locate \"tpgt_#\" directory"
				" group\n");
		return ERR_PTR(-EINVAL);
	}
	tpgt_str += 5; /* Skip ahead of "tpgt_" */
	tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0);

	if (tpgt > TL_TPGS_PER_HBA) {
		printk(KERN_ERR "Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:"
				" %u\n", tpgt, TL_TPGS_PER_HBA);
		return ERR_PTR(-EINVAL);
	}
	tl_tpg = &tl_hba->tl_hba_tpgs[tpgt];
	tl_tpg->tl_hba = tl_hba;
	tl_tpg->tl_tpgt = tpgt;
	/*
	 * Register the tl_tpg as a emulated SAS TCM Target Endpoint
	 */
	ret = core_tpg_register(&tcm_loop_fabric_configfs->tf_ops,
			wwn, &tl_tpg->tl_se_tpg, tl_tpg,
			TRANSPORT_TPG_TYPE_NORMAL);
	if (ret < 0)
		return ERR_PTR(-ENOMEM);

	printk(KERN_INFO "TCM_Loop_ConfigFS: Allocated Emulated %s"
		" Target Port %s,t,0x%04x\n", tcm_loop_dump_proto_id(tl_hba),
		config_item_name(&wwn->wwn_group.cg_item), tpgt);

	return &tl_tpg->tl_se_tpg;
}


static ssize_t ui_write(struct file *filp, const char __user *buf,
			size_t count, loff_t *f_pos)
{
	struct hfi1_devdata *dd = filp->private_data;
	void __iomem *base;
	unsigned long total, data, csr_off;
	int in_lcb;

	/* only write 8 byte quantities */
	if ((count % 8) != 0)
		return -EINVAL;
	/* offset must be 8-byte aligned */
	if ((*f_pos % 8) != 0)
		return -EINVAL;
	/* source buffer must be 8-byte aligned */
	if ((unsigned long)buf % 8 != 0)
		return -EINVAL;
	/* must be in range */
	if (*f_pos + count > dd->kregend - dd->kregbase)
		return -EINVAL;

	base = (void __iomem *)dd->kregbase + *f_pos;
	csr_off = *f_pos;
	in_lcb = 0;
	for (total = 0; total < count; total += 8, csr_off += 8) {
		if (get_user(data, (unsigned long __user *)(buf + total)))
			break;
		/* accessing LCB CSRs requires a special procedure */
		if (is_lcb_offset(csr_off)) {
			if (!in_lcb) {
				int ret = acquire_lcb_access(dd, 1);

				if (ret)
					break;
				in_lcb = 1;
			}
		} else {
			if (in_lcb) {
				release_lcb_access(dd, 1);
				in_lcb = 0;
			}
		}
		writeq(data, base + total);
	}
	if (in_lcb)
		release_lcb_access(dd, 1);
	*f_pos += total;
	return total;
}


int get_ctty_devnr(pid_t pid, dev_t *d) {
        int r;
        _cleanup_free_ char *line = NULL;
        const char *p;
        unsigned long ttynr;

        assert(pid >= 0);

        p = procfs_file_alloca(pid, "stat");
        r = read_one_line_file(p, &line);
        if (r < 0)
                return r;

        p = strrchr(line, ')');
        if (!p)
                return -EIO;

        p++;

        if (sscanf(p, " "
                   "%*c "  /* state */
                   "%*d "  /* ppid */
                   "%*d "  /* pgrp */
                   "%*d "  /* session */
                   "%lu ", /* ttynr */
                   &ttynr) != 1)
                return -EIO;

        if (major(ttynr) == 0 && minor(ttynr) == 0)
                return -ENXIO;

        if (d)
                *d = (dev_t) ttynr;

        return 0;
}


obj2ast_unaryop(PyObject* obj, unaryop_ty* out, PyArena* arena)
{
    int isinstance;

    isinstance = PyObject_IsInstance(obj, (PyObject *)Invert_type);
    if (isinstance == -1) {
        return 1;
    }
    if (isinstance) {
        *out = Invert;
        return 0;
    }
    isinstance = PyObject_IsInstance(obj, (PyObject *)Not_type);
    if (isinstance == -1) {
        return 1;
    }
    if (isinstance) {
        *out = Not;
        return 0;
    }
    isinstance = PyObject_IsInstance(obj, (PyObject *)UAdd_type);
    if (isinstance == -1) {
        return 1;
    }
    if (isinstance) {
        *out = UAdd;
        return 0;
    }
    isinstance = PyObject_IsInstance(obj, (PyObject *)USub_type);
    if (isinstance == -1) {
        return 1;
    }
    if (isinstance) {
        *out = USub;
        return 0;
    }

    PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %R", obj);
    return 1;
}


static int cxusb_dualdig4_rev2_frontend_attach(struct dvb_usb_adapter *adap)
{
	struct dib0700_adapter_state *state = adap->priv;

	if (usb_set_interface(adap->dev->udev, 0, 1) < 0)
		err("set interface failed");

	cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0);

	cxusb_bluebird_gpio_pulse(adap->dev, 0x02, 1);

	if (!dvb_attach(dib7000p_attach, &state->dib7000p_ops))
		return -ENODEV;

	if (state->dib7000p_ops.i2c_enumeration(&adap->dev->i2c_adap, 1, 18,
				       &cxusb_dualdig4_rev2_config) < 0) {
		printk(KERN_WARNING "Unable to enumerate dib7000p\n");
		return -ENODEV;
	}

	adap->fe_adap[0].fe = state->dib7000p_ops.init(&adap->dev->i2c_adap, 0x80,
					      &cxusb_dualdig4_rev2_config);
	if (adap->fe_adap[0].fe == NULL)
		return -EIO;

	return 0;
}


pseudo_register_job_info(ClassAd* ad)
{
	Shadow->updateFromStarterClassAd(ad);
	return 0;
}


bool BCheckRateLimitReportBadPacket( SteamNetworkingMicroseconds usecNow )
{
	static SteamNetworkingMicroseconds s_usecLastReport;
	if ( s_usecLastReport + k_nMillion*2 > usecNow )
		return false;
	s_usecLastReport = usecNow;
	return true;
}


static long bt_sock_data_wait(struct sock *sk, long timeo)
{
	DECLARE_WAITQUEUE(wait, current);

	add_wait_queue(sk_sleep(sk), &wait);
	for (;;) {
		set_current_state(TASK_INTERRUPTIBLE);

		if (!skb_queue_empty(&sk->sk_receive_queue))
			break;

		if (sk->sk_err || (sk->sk_shutdown & RCV_SHUTDOWN))
			break;

		if (signal_pending(current) || !timeo)
			break;

		set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
		release_sock(sk);
		timeo = schedule_timeout(timeo);
		lock_sock(sk);
		clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
	}

	__set_current_state(TASK_RUNNING);
	remove_wait_queue(sk_sleep(sk), &wait);
	return timeo;
}


int cil_gen_userattributeset(struct cil_db *db, struct cil_tree_node *parse_current, struct cil_tree_node *ast_node)
{
	enum cil_syntax syntax[] = {
		CIL_SYN_STRING,
		CIL_SYN_STRING,
		CIL_SYN_STRING | CIL_SYN_LIST,
		CIL_SYN_END
	};
	int syntax_len = sizeof(syntax)/sizeof(*syntax);
	struct cil_userattributeset *attrset = NULL;
	int rc = SEPOL_ERR;

	if (db == NULL || parse_current == NULL || ast_node == NULL) {
		goto exit;
	}

	rc = __cil_verify_syntax(parse_current, syntax, syntax_len);
	if (rc != SEPOL_OK) {
		goto exit;
	}

	cil_userattributeset_init(&attrset);

	attrset->attr_str = parse_current->next->data;

	rc = cil_gen_expr(parse_current->next->next, CIL_USER, &attrset->str_expr);
	if (rc != SEPOL_OK) {
		goto exit;
	}
	ast_node->data = attrset;
	ast_node->flavor = CIL_USERATTRIBUTESET;

	return SEPOL_OK;

exit:
	cil_tree_log(parse_current, CIL_ERR, "Bad userattributeset declaration");
	cil_destroy_userattributeset(attrset);

	return rc;
}


BackgroundContentsService::~BackgroundContentsService() {
  DCHECK(contents_map_.empty());
}


Jsi_Value *Jsi_CommandCreateSpecs(Jsi_Interp *interp, const char *name, Jsi_CmdSpec *cmdSpecs,
    void *privData, int flags)
{
    int i = 0;
    Jsi_Value *proto = NULL;
    Jsi_CmdProc *cmdProc = NULL;
    if (!cmdSpecs[0].name)
        return NULL;
    if (!name)
        name = cmdSpecs[0].name;
    name = Jsi_KeyAdd(interp, name);
    if (flags & JSI_CMDSPEC_PROTO) {
        proto = (Jsi_Value*)privData;
        privData = NULL;
        i++;
    /*} else if (!Jsi_Strcmp(name, cmdSpecs[0].name)) {
        cmdProc = cmdSpecs[0].proc;
        i++;*/
    } else if (!*name)
        proto = NULL;
    else {
        if (!(flags & JSI_CMDSPEC_ISOBJ)) {
            cmdProc = cmdSpecs[0].proc;
            proto = jsi_CommandCreate(interp, name, cmdProc, privData, 0, cmdSpecs);
        } else {
            proto = jsi_ProtoValueNew(interp, name, NULL);
        }
    }
    jsi_PkgInfo *pkg = jsi_PkgGet(interp, name);
    for (; cmdSpecs[i].name; i++)
        CommandCreateWithSpec(interp,  cmdSpecs, i, proto, privData, name, pkg);

    bool isNew;
    Jsi_MapEntry *hPtr = Jsi_MapEntryNew(interp->cmdSpecTbl, name, &isNew);
    if (!hPtr || !isNew) {
        Jsi_LogBug("failed cmdspec register: %s", name);
        return NULL;
    }
    Jsi_CmdSpecItem *op, *p = (Jsi_CmdSpecItem*)Jsi_Calloc(1,sizeof(*p));
    SIGINIT(p,CMDSPECITEM);
    p->spec = cmdSpecs;
    p->flags = flags;
    p->proto = proto;
    p->privData = privData;
    p->name = (const char*)Jsi_MapKeyGet(hPtr, 0);
    p->hPtr = hPtr;
    Jsi_CmdSpec *csi = cmdSpecs;
    p->isCons = (csi && csi->flags&JSI_CMD_IS_CONSTRUCTOR);
    while (csi->name)
        csi++;
    p->help = csi->help;
    p->info = csi->info;
    if (!isNew) {
        op = (Jsi_CmdSpecItem*)Jsi_MapValueGet(hPtr);
        p->next = op;
    }
    Jsi_MapValueSet(hPtr, p);
    return proto;
}


njs_promise_prototype_then(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
    njs_index_t unused)
{
    njs_int_t                 ret;
    njs_value_t               *promise, *fulfilled, *rejected, constructor;
    njs_function_t            *function;
    njs_promise_capability_t  *capability;

    promise = njs_argument(args, 0);

    if (njs_slow_path(!njs_is_promise(promise))) {
        goto failed;
    }

    function = njs_promise_create_function(vm, sizeof(njs_promise_context_t));
    function->u.native = njs_promise_constructor;

    njs_set_function(&constructor, function);

    ret = njs_value_species_constructor(vm, promise, &constructor,
                                        &constructor);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    capability = njs_promise_new_capability(vm, &constructor);
    if (njs_slow_path(capability == NULL)) {
        return NJS_ERROR;
    }

    fulfilled = njs_arg(args, nargs, 1);
    rejected = njs_arg(args, nargs, 2);

    return njs_promise_perform_then(vm, promise, fulfilled, rejected,
                                    capability);

failed:

    njs_type_error(vm, "required a promise object");

    return NJS_ERROR;
}


void PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id,
                                            bool success) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  PreresolveJob* job = preresolve_jobs_.Lookup(job_id);
  DCHECK(job);

  bool need_preconnect = success && job->need_preconnect();
  if (need_preconnect) {
    PreconnectUrl(job->url, job->num_sockets, job->allow_credentials,
                  job->network_isolation_key);
   }

   PreresolveInfo* info = job->info;
  if (info)
    info->stats->requests_stats.emplace_back(job->url, need_preconnect);
   preresolve_jobs_.Remove(job_id);
   --inflight_preresolves_count_;
   if (info) {
    DCHECK_LE(1u, info->inflight_count);
    --info->inflight_count;
  }
  if (info && info->is_done())
    AllPreresolvesForUrlFinished(info);
  TryToLaunchPreresolveJobs();
}


void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
{
	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
	while (fs_devices) {
		fs_devices->fs_info = fs_info;
		fs_devices = fs_devices->seed;
	}
}


static int nfs4_xdr_enc_setclientid_confirm(struct rpc_rqst *req, __be32 *p, struct nfs_client *clp)
{
	struct xdr_stream xdr;
	struct compound_hdr hdr = {
		.nops	= 3,
	};
	const u32 lease_bitmap[2] = { FATTR4_WORD0_LEASE_TIME, 0 };
	int status;

	xdr_init_encode(&xdr, &req->rq_snd_buf, p);
	encode_compound_hdr(&xdr, &hdr);
	status = encode_setclientid_confirm(&xdr, clp);
	if (!status)
		status = encode_putrootfh(&xdr);
	if (!status)
		status = encode_fsinfo(&xdr, lease_bitmap);
	return status;
}


static sector_t flakey_map_sector(struct dm_target *ti, sector_t bi_sector)
{
	struct flakey_c *fc = ti->private;

	return fc->start + dm_target_offset(ti, bi_sector);
}


num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
{
	int len;
	unsigned int entrycount = 0;
	unsigned int next_offset = 0;
	char *entryptr;
	FILE_DIRECTORY_INFO *dir_info;

	if (bufstart == NULL)
		return 0;

	entryptr = bufstart;

	while (1) {
		if (entryptr + next_offset < entryptr ||
		    entryptr + next_offset > end_of_buf ||
		    entryptr + next_offset + size > end_of_buf) {
			cifs_dbg(VFS, "malformed search entry would overflow\n");
			break;
		}

		entryptr = entryptr + next_offset;
		dir_info = (FILE_DIRECTORY_INFO *)entryptr;

		len = le32_to_cpu(dir_info->FileNameLength);
		if (entryptr + len < entryptr ||
		    entryptr + len > end_of_buf ||
		    entryptr + len + size > end_of_buf) {
			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
				 end_of_buf);
			break;
		}

		*lastentry = entryptr;
		entrycount++;

		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
		if (!next_offset)
			break;
	}

	return entrycount;
}


void Document::InheritHtmlAndBodyElementStyles(StyleRecalcChange change) {
  DCHECK(InStyleRecalc());
  DCHECK(documentElement());

  bool did_recalc_document_element = false;
  RefPtr<ComputedStyle> document_element_style =
      documentElement()->MutableComputedStyle();
  if (change == kForce)
    documentElement()->ClearAnimationStyleChange();
  if (!document_element_style || documentElement()->NeedsStyleRecalc() ||
      change == kForce) {
    document_element_style =
        EnsureStyleResolver().StyleForElement(documentElement());
    did_recalc_document_element = true;
  }

  WritingMode root_writing_mode = document_element_style->GetWritingMode();
  TextDirection root_direction = document_element_style->Direction();

  HTMLElement* body = this->body();
  RefPtr<ComputedStyle> body_style;

  if (body) {
    body_style = body->MutableComputedStyle();
    if (did_recalc_document_element)
      body->ClearAnimationStyleChange();
    if (!body_style || body->NeedsStyleRecalc() ||
        did_recalc_document_element) {
      body_style = EnsureStyleResolver().StyleForElement(
          body, document_element_style.Get(), document_element_style.Get());
    }
    root_writing_mode = body_style->GetWritingMode();
    root_direction = body_style->Direction();
  }

  const ComputedStyle* background_style = document_element_style.Get();
  if (isHTMLHtmlElement(documentElement()) && isHTMLBodyElement(body) &&
      !background_style->HasBackground())
    background_style = body_style.Get();

  Node& root_scroller = GetRootScrollerController().EffectiveRootScroller();
  RefPtr<ComputedStyle> root_scroller_style;
  if (this != &root_scroller) {
    DCHECK(root_scroller.IsElementNode());
    Element* root_scroller_element = ToElement(&root_scroller);
    root_scroller_style = root_scroller_element->MutableComputedStyle();

    if (!root_scroller_style || root_scroller_element->NeedsStyleRecalc()) {
      root_scroller_style =
          EnsureStyleResolver().StyleForElement(root_scroller_element);
    }

    background_style = root_scroller_style.Get();
  }

  Color background_color =
      background_style->VisitedDependentColor(CSSPropertyBackgroundColor);
  FillLayer background_layers = background_style->BackgroundLayers();
  for (auto current_layer = &background_layers; current_layer;
       current_layer = current_layer->Next()) {
    current_layer->SetClip(kBorderFillBox);

    if (current_layer->Attachment() == kScrollBackgroundAttachment)
      current_layer->SetAttachment(kLocalBackgroundAttachment);
  }
  EImageRendering image_rendering = background_style->ImageRendering();

  const ComputedStyle* overflow_style = nullptr;
  if (Element* element =
          ViewportDefiningElement(document_element_style.Get())) {
    if (element == body) {
      overflow_style = body_style.Get();
    } else {
      DCHECK_EQ(element, documentElement());
      overflow_style = document_element_style.Get();

      if (body_style && !body_style->IsOverflowVisible())
        UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport);
    }
  }

  if (GetStyleEngine().UsesRemUnits() &&
      (documentElement()->NeedsAttach() ||
       !documentElement()->GetComputedStyle() ||
       documentElement()->GetComputedStyle()->FontSize() !=
           document_element_style->FontSize())) {
    EnsureStyleResolver().InvalidateMatchedPropertiesCache();
    documentElement()->SetNeedsStyleRecalc(
        kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
                                 StyleChangeReason::kFontSizeChange));
  }

  EOverflowAnchor overflow_anchor = EOverflowAnchor::kAuto;
  EOverflow overflow_x = EOverflow::kAuto;
  EOverflow overflow_y = EOverflow::kAuto;
  float column_gap = 0;
  if (overflow_style) {
    overflow_anchor = overflow_style->OverflowAnchor();
    overflow_x = overflow_style->OverflowX();
    overflow_y = overflow_style->OverflowY();
    if (overflow_x == EOverflow::kVisible)
      overflow_x = EOverflow::kAuto;
    if (overflow_y == EOverflow::kVisible)
      overflow_y = EOverflow::kAuto;
    if (overflow_anchor == EOverflowAnchor::kVisible)
      overflow_anchor = EOverflowAnchor::kAuto;
    column_gap = overflow_style->ColumnGap();
  }

  ScrollSnapType snap_type = overflow_style->GetScrollSnapType();

  RefPtr<ComputedStyle> viewport_style = GetLayoutViewItem().MutableStyle();
  if (viewport_style->GetWritingMode() != root_writing_mode ||
      viewport_style->Direction() != root_direction ||
      viewport_style->VisitedDependentColor(CSSPropertyBackgroundColor) !=
          background_color ||
      viewport_style->BackgroundLayers() != background_layers ||
      viewport_style->ImageRendering() != image_rendering ||
      viewport_style->OverflowAnchor() != overflow_anchor ||
      viewport_style->OverflowX() != overflow_x ||
      viewport_style->OverflowY() != overflow_y ||
      viewport_style->ColumnGap() != column_gap ||
      viewport_style->GetScrollSnapType() != snap_type) {
    RefPtr<ComputedStyle> new_style = ComputedStyle::Clone(*viewport_style);
    new_style->SetWritingMode(root_writing_mode);
    new_style->SetDirection(root_direction);
    new_style->SetBackgroundColor(background_color);
    new_style->AccessBackgroundLayers() = background_layers;
    new_style->SetImageRendering(image_rendering);
    new_style->SetOverflowAnchor(overflow_anchor);
    new_style->SetOverflowX(overflow_x);
    new_style->SetOverflowY(overflow_y);
    new_style->SetColumnGap(column_gap);
    new_style->SetScrollSnapType(snap_type);
    GetLayoutViewItem().SetStyle(new_style);
    SetupFontBuilder(*new_style);
  }

  if (body) {
    if (const ComputedStyle* style = body->GetComputedStyle()) {
      if (style->Direction() != root_direction ||
          style->GetWritingMode() != root_writing_mode)
        body->SetNeedsStyleRecalc(kSubtreeStyleChange,
                                  StyleChangeReasonForTracing::Create(
                                      StyleChangeReason::kWritingModeChange));
    }
  }

  if (const ComputedStyle* style = documentElement()->GetComputedStyle()) {
    if (style->Direction() != root_direction ||
        style->GetWritingMode() != root_writing_mode)
      documentElement()->SetNeedsStyleRecalc(
          kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
                                   StyleChangeReason::kWritingModeChange));
  }
}


mono_blob_entry_hash (const char* str)
{
	guint len, h;
	const char *end;
	len = mono_metadata_decode_blob_size (str, &str);
	if (len > 0) {
		end = str + len;
		h = *str;
		for (str += 1; str < end; str++)
			h = (h << 5) - h + *str;
		return h;
	} else {
		return 0;
	}
}


evdns_request_insert(struct request *req, struct request **head) {
	ASSERT_LOCKED(req->base);
	ASSERT_VALID_REQUEST(req);
	if (!*head) {
		*head = req;
		req->next = req->prev = req;
		return;
	}

	req->prev = (*head)->prev;
	req->prev->next = req;
	req->next = *head;
	(*head)->prev = req;
}


void RenderViewImpl::didChangeContentsSize(WebFrame* frame,
                                           const WebSize& size) {
  if (webview()->mainFrame() != frame)
    return;
  WebView* frameView = frame->view();
  if (!frameView)
    return;

  bool has_horizontal_scrollbar = frame->hasHorizontalScrollbar();
  bool has_vertical_scrollbar = frame->hasVerticalScrollbar();

  if (has_horizontal_scrollbar != cached_has_main_frame_horizontal_scrollbar_ ||
      has_vertical_scrollbar != cached_has_main_frame_vertical_scrollbar_) {
    Send(new ViewHostMsg_DidChangeScrollbarsForMainFrame(
          routing_id_, has_horizontal_scrollbar, has_vertical_scrollbar));

    cached_has_main_frame_horizontal_scrollbar_ = has_horizontal_scrollbar;
    cached_has_main_frame_vertical_scrollbar_ = has_vertical_scrollbar;
  }
}


static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
{
	struct discovered_devs *discdevs;
	HDEVINFO dev_info = { 0 };
 	const char* usb_class[] = {"USB", "NUSB3", "IUSB3"};
 	SP_DEVINFO_DATA dev_info_data = { 0 };
 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
 #define MAX_ENUM_GUIDS 64
 	const GUID* guid[MAX_ENUM_GUIDS];
 #define HCD_PASS 0
 #define HUB_PASS 1
 #define GEN_PASS 2
 #define DEV_PASS 3
 	int r = LIBUSB_SUCCESS;
 	int api, sub_api;
 	size_t class_index = 0;
	unsigned int nb_guids, pass, i, j, ancestor;
	char path[MAX_PATH_LENGTH];
	char strbuf[MAX_PATH_LENGTH];
	struct libusb_device *dev, *parent_dev;
	struct windows_device_priv *priv, *parent_priv;
	char* dev_interface_path = NULL;
	char* dev_id_path = NULL;
	unsigned long session_id;
	DWORD size, reg_type, port_nr, install_state;
	HKEY key;
	WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
	GUID* if_guid;
	LONG s;
	libusb_device** unref_list;
	unsigned int unref_size = 64;
	unsigned int unref_cur = 0;

	// PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.

 	guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
 	guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
 	guid[GEN_PASS] = NULL;
 	guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
	nb_guids = DEV_PASS+1;

 	unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
 	if (unref_list == NULL) {
		return LIBUSB_ERROR_NO_MEM;
	}

 	for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
 #ifdef ENUM_DEBUG
		const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "EXT" };
		usbi_dbg("\n#### PROCESSING %ss %s", passname[(pass<=DEV_PASS)?pass:DEV_PASS+1],
 			(pass!=GEN_PASS)?guid_to_string(guid[pass]):"");
 #endif
 		for (i = 0; ; i++) {
			safe_free(dev_interface_details);
			safe_free(dev_interface_path);
			safe_free(dev_id_path);
			priv = parent_priv = NULL;
			dev = parent_dev = NULL;

			if (r != LIBUSB_SUCCESS) {
				break;
			}
			if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
				usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
				break;
			}
			if (pass != GEN_PASS) {
				dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
				if (dev_interface_details == NULL) {
					break;
				} else {
					dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
					if (dev_interface_path == NULL) {
						usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
						continue;
					}
				}
			} else {
				for (; class_index < ARRAYSIZE(usb_class); class_index++) {
					if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
						break;
					i = 0;
				}
				if (class_index >= ARRAYSIZE(usb_class))
					break;
			}

			if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
				usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
					dev_info_data.DevInst);
				continue;
			}
			dev_id_path = sanitize_path(path);
			if (dev_id_path == NULL) {
				usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
					dev_info_data.DevInst);
				continue;
			}
#ifdef ENUM_DEBUG
			usbi_dbg("PRO: %s", dev_id_path);
#endif

			port_nr = 0;
			if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
				if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
					&reg_type, (BYTE*)&port_nr, 4, &size))
				  || (size != 4) ) {
					usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
						dev_id_path, windows_error_str(0));
					continue;
				}
			}

			api = USB_API_UNSUPPORTED;
			sub_api = SUB_API_NOTSET;
			switch (pass) {
			case HCD_PASS:
				break;
			case GEN_PASS:
				size = sizeof(strbuf);
				if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
					&reg_type, (BYTE*)strbuf, size, &size)) {
						usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
						usbi_info(ctx, "libusbx will not be able to access it.");
				}
				key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
				if (key != INVALID_HANDLE_VALUE) {
					size = sizeof(guid_string_w);
					s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &reg_type,
						(BYTE*)guid_string_w, &size);
					pRegCloseKey(key);
					if (s == ERROR_SUCCESS) {
						if (nb_guids >= MAX_ENUM_GUIDS) {
							usbi_err(ctx, "program assertion failed: too many GUIDs");
							LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
						}
						if_guid = (GUID*) calloc(1, sizeof(GUID));
						pCLSIDFromString(guid_string_w, if_guid);
						guid[nb_guids++] = if_guid;
						usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
 					}
 				}
 				break;
 			default:
 				if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
					&reg_type, (BYTE*)&install_state, 4, &size))
				  || (size != 4) ){
					usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
						dev_id_path, windows_error_str(0));
				} else if (install_state != 0) {
					usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
						dev_id_path, install_state);
					continue;
				}
				get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
				break;
			}

			switch (pass) {
			case HCD_PASS:
			case DEV_PASS:
			case HUB_PASS:
				break;
			default:
				parent_dev = NULL;
				for (ancestor = 1; parent_dev == NULL; ancestor++) {
					session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
					if (session_id == 0) {
						break;
					}
					parent_dev = usbi_get_device_by_session_id(ctx, session_id);
				}
				if (parent_dev == NULL) {
					usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
					continue;
				}
				parent_priv = _device_priv(parent_dev);
				if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
					continue;
				}
				break;
			}

			if (pass <= DEV_PASS) {	// For subsequent passes, we'll lookup the parent
				session_id = htab_hash(dev_id_path);
				dev = usbi_get_device_by_session_id(ctx, session_id);
				if (dev == NULL) {
					if (pass == DEV_PASS) {
						usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
							" - ignoring", dev_id_path);
						continue;
					}
					usbi_dbg("allocating new device for session [%X]", session_id);
					if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
					}
					windows_device_priv_init(dev);
					unref_list[unref_cur++] = dev;
					if (unref_cur >= unref_size) {
						unref_size += 64;
						unref_list = usbi_reallocf(unref_list, unref_size*sizeof(libusb_device*));
						if (unref_list == NULL) {
							usbi_err(ctx, "could not realloc list for unref - aborting.");
							LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
						}
					}
				} else {
					usbi_dbg("found existing device for session [%X] (%d.%d)",
						session_id, dev->bus_number, dev->device_address);
				}
				priv = _device_priv(dev);
			}

			switch (pass) {
			case HCD_PASS:
				dev->bus_number = (uint8_t)(i + 1);	// bus 0 is reserved for disconnected
				dev->device_address = 0;
				dev->num_configurations = 0;
				priv->apib = &usb_api_backend[USB_API_HUB];
				priv->sub_api = SUB_API_NOTSET;
				priv->depth = UINT8_MAX;	// Overflow to 0 for HCD Hubs
				priv->path = dev_interface_path; dev_interface_path = NULL;
				break;
			case HUB_PASS:
			case DEV_PASS:
				if (priv->path != NULL)
					break;
				priv->path = dev_interface_path; dev_interface_path = NULL;
				priv->apib = &usb_api_backend[api];
				priv->sub_api = sub_api;
				switch(api) {
 				case USB_API_COMPOSITE:
 				case USB_API_HUB:
 					break;
 				default:
 					priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
					if (priv->usb_interface[0].path != NULL) {
						safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
					} else {
						usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
					}
					for(j=0; j<USB_MAXINTERFACES; j++) {
						priv->usb_interface[j].apib = &usb_api_backend[api];
					}
					break;
				}
				break;
			case GEN_PASS:
				r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
				if (r == LIBUSB_SUCCESS) {
					discdevs = discovered_devs_append(*_discdevs, dev);
					if (!discdevs) {
						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
					}
					*_discdevs = discdevs;
				} else if (r == LIBUSB_ERROR_NO_DEVICE) {
 					r = LIBUSB_SUCCESS;
 				}
 				break;
			default:	// later passes
				if (parent_priv->apib->id == USB_API_COMPOSITE) {
 					usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
 					switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api)) {
 					case LIBUSB_SUCCESS:
						dev_interface_path = NULL;
						break;
					case LIBUSB_ERROR_ACCESS:
						break;
					default:
						LOOP_BREAK(r);
						break;
					}
				}
				break;
			}
		}
 	}

	for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
 		safe_free(guid[pass]);
 	}

	for (i=0; i<unref_cur; i++) {
		safe_unref_device(unref_list[i]);
	}
	safe_free(unref_list);

	return r;
}


static void save_nonewprivs(void) {
	if (arg_nonewprivs == 0)
		return;

	FILE *fp = fopen(RUN_NONEWPRIVS_CFG, "wxe");
	if (fp) {
		fprintf(fp, "\n");
		SET_PERMS_STREAM(fp, 0, 0, 0644); // assume mode 0644
		fclose(fp);
	}
	else {
		fprintf(stderr, "Error: cannot save nonewprivs state\n");
		exit(1);
	}
}


PJ_DEF(pj_status_t) pjmedia_codec_ipp_init( pjmedia_endpt *endpt )
{
    pjmedia_codec_mgr *codec_mgr;
    pj_str_t codec_name;
    pj_status_t status;

    if (ipp_factory.pool != NULL) {
	/* Already initialized. */
	return PJ_SUCCESS;
    }

    /* Create IPP codec factory. */
    ipp_factory.base.op = &ipp_factory_op;
    ipp_factory.base.factory_data = NULL;
    ipp_factory.endpt = endpt;
    ipp_factory.g7221_pcm_shift = PJMEDIA_G7221_DEFAULT_PCM_SHIFT;

    ipp_factory.pool = pjmedia_endpt_create_pool(endpt, "IPP codecs", 4000, 4000);
    if (!ipp_factory.pool)
	return PJ_ENOMEM;

    /* Create mutex. */
    status = pj_mutex_create_simple(ipp_factory.pool, "IPP codecs",
				    &ipp_factory.mutex);
    if (status != PJ_SUCCESS)
	goto on_error;

    /* Get the codec manager. */
    codec_mgr = pjmedia_endpt_get_codec_mgr(endpt);
    if (!codec_mgr) {
	status = PJ_EINVALIDOP;
	goto on_error;
    }

    /* Register format match callback. */
#if PJMEDIA_HAS_INTEL_IPP_CODEC_G722_1
    pj_cstr(&codec_name, "G7221");
    status = pjmedia_sdp_neg_register_fmt_match_cb(
					&codec_name,
					&pjmedia_codec_g7221_match_sdp);
    if (status != PJ_SUCCESS)
	goto on_error;
#endif

#if PJMEDIA_HAS_INTEL_IPP_CODEC_AMR
    pj_cstr(&codec_name, "AMR");
    status = pjmedia_sdp_neg_register_fmt_match_cb(
					&codec_name,
					&pjmedia_codec_amr_match_sdp);
    if (status != PJ_SUCCESS)
	goto on_error;
#endif

#if PJMEDIA_HAS_INTEL_IPP_CODEC_AMRWB
    pj_cstr(&codec_name, "AMR-WB");
    status = pjmedia_sdp_neg_register_fmt_match_cb(
					&codec_name,
					&pjmedia_codec_amr_match_sdp);
    if (status != PJ_SUCCESS)
	goto on_error;
#endif

    /* Suppress compile warning */
    PJ_UNUSED_ARG(codec_name);

    /* Register codec factory to endpoint. */
    status = pjmedia_codec_mgr_register_factory(codec_mgr,
						&ipp_factory.base);
    if (status != PJ_SUCCESS)
	goto on_error;

    /* Done. */
    return PJ_SUCCESS;

on_error:
    pj_pool_release(ipp_factory.pool);
    ipp_factory.pool = NULL;
    return status;
}


void MojoAudioOutputIPC::CloseStream() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  stream_provider_.reset();
  stream_.reset();
  binding_.Close();
  delegate_ = nullptr;

  weak_factory_.InvalidateWeakPtrs();
}


static const char *ext4_decode_error(struct super_block *sb, int errno,
				     char nbuf[16])
{
	char *errstr = NULL;

	switch (errno) {
	case -EIO:
		errstr = "IO failure";
		break;
	case -ENOMEM:
		errstr = "Out of memory";
		break;
	case -EROFS:
		if (!sb || (EXT4_SB(sb)->s_journal &&
			    EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
			errstr = "Journal has aborted";
		else
			errstr = "Readonly filesystem";
		break;
	default:
		/* If the caller passed in an extra buffer for unknown
		 * errors, textualise them now.  Else we just return
		 * NULL. */
		if (nbuf) {
			/* Check for truncated error codes... */
			if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
				errstr = nbuf;
		}
		break;
	}

	return errstr;
}


EncodedJSValue JSC_HOST_CALL jsTestInterfaceConstructorFunctionSupplementalMethod4(ExecState* exec)
{
    TestSupplemental::supplementalMethod4();
    return JSValue::encode(jsUndefined());
}


void reset_revision_walk(void)
{
	clear_object_flags(SEEN | ADDED | SHOWN);
}


  explicit SymbolicShapeRefiner(
      const GraphView& graph,
      const absl::flat_hash_map<string, absl::flat_hash_set<int>>& fed_ports,
      const bool aggressive_shape_inference)
      : graph_(graph),
        function_library_(OpRegistry::Global(), graph.graph()->library()),
        fed_ports_(fed_ports),
        aggressive_shape_inference_(aggressive_shape_inference) {
    graph_def_version_ = graph.graph()->versions().producer();
    node_to_context_.reserve(graph.graph()->node_size());
  }


parse(FILE * fp, struct node *root)
{
#ifdef TEST
    extern void     xmalloc_stats(FILE *);
#endif
    char            token[MAXTOKEN];
    char            name[MAXTOKEN+1];
    int             type = LABEL;
    int             lasttype = LABEL;

#define BETWEEN_MIBS          1
#define IN_MIB                2
    int             state = BETWEEN_MIBS;
    struct node    *np, *nnp;
    struct objgroup *oldgroups = NULL, *oldobjects = NULL, *oldnotifs =
        NULL;

    DEBUGMSGTL(("parse-file", "Parsing file:  %s...\n", File));

    if (last_err_module)
        free(last_err_module);
    last_err_module = NULL;

    np = root;
    if (np != NULL) {
        /*
         * now find end of chain
         */
        while (np->next)
            np = np->next;
    }

    while (type != ENDOFFILE) {
        if (lasttype == CONTINUE)
            lasttype = type;
        else
            type = lasttype = get_token(fp, token, MAXTOKEN);

        switch (type) {
        case END:
            if (state != IN_MIB) {
                print_error("Error, END before start of MIB", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            } else {
                struct module  *mp;
#ifdef TEST
                printf("\nNodes for Module %s:\n", name);
                print_nodes(stdout, root);
#endif
                for (mp = module_head; mp; mp = mp->next)
                    if (mp->modid == current_module)
                        break;
                scan_objlist(root, mp, objgroups, "Undefined OBJECT-GROUP");
                scan_objlist(root, mp, objects, "Undefined OBJECT");
                scan_objlist(root, mp, notifs, "Undefined NOTIFICATION");
                objgroups = oldgroups;
                objects = oldobjects;
                notifs = oldnotifs;
                do_linkup(mp, root);
                np = root = NULL;
            }
            state = BETWEEN_MIBS;
#ifdef TEST
            if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
				   NETSNMP_DS_LIB_MIB_WARNINGS)) {
                /* xmalloc_stats(stderr); */
	    }
#endif
            continue;
        case IMPORTS:
            parse_imports(fp);
            continue;
        case EXPORTS:
            while (type != SEMI && type != ENDOFFILE)
                type = get_token(fp, token, MAXTOKEN);
            continue;
        case LABEL:
        case INTEGER:
        case INTEGER32:
        case UINTEGER32:
        case UNSIGNED32:
        case COUNTER:
        case COUNTER64:
        case GAUGE:
        case IPADDR:
        case NETADDR:
        case NSAPADDRESS:
        case OBJSYNTAX:
        case APPSYNTAX:
        case SIMPLESYNTAX:
        case OBJNAME:
        case NOTIFNAME:
        case KW_OPAQUE:
        case TIMETICKS:
            break;
        case ENDOFFILE:
            continue;
        default:
            strlcpy(name, token, sizeof(name));
            type = get_token(fp, token, MAXTOKEN);
            nnp = NULL;
            if (type == MACRO) {
                nnp = parse_macro(fp, name);
                if (nnp == NULL) {
                    print_error("Bad parse of MACRO", NULL, type);
                    gMibError = MODULE_SYNTAX_ERROR;
                    /*
                     * return NULL;
                     */
                }
                free_node(nnp); /* IGNORE */
                nnp = NULL;
            } else
                print_error(name, "is a reserved word", lasttype);
            continue;           /* see if we can parse the rest of the file */
        }
        strlcpy(name, token, sizeof(name));
        type = get_token(fp, token, MAXTOKEN);
        nnp = NULL;

        /*
         * Handle obsolete method to assign an object identifier to a
         * module
         */
        if (lasttype == LABEL && type == LEFTBRACKET) {
            while (type != RIGHTBRACKET && type != ENDOFFILE)
                type = get_token(fp, token, MAXTOKEN);
            if (type == ENDOFFILE) {
                print_error("Expected \"}\"", token, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            type = get_token(fp, token, MAXTOKEN);
        }

        switch (type) {
        case DEFINITIONS:
            if (state != BETWEEN_MIBS) {
                print_error("Error, nested MIBS", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            state = IN_MIB;
            current_module = which_module(name);
            oldgroups = objgroups;
            objgroups = NULL;
            oldobjects = objects;
            objects = NULL;
            oldnotifs = notifs;
            notifs = NULL;
            if (current_module == -1) {
                new_module(name, File);
                current_module = which_module(name);
            }
            DEBUGMSGTL(("parse-mibs", "Parsing MIB: %d %s\n",
                        current_module, name));
            while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE)
                if (type == BEGIN)
                    break;
            break;
        case OBJTYPE:
            nnp = parse_objecttype(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of OBJECT-TYPE", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case OBJGROUP:
            nnp = parse_objectgroup(fp, name, OBJECTS, &objects);
            if (nnp == NULL) {
                print_error("Bad parse of OBJECT-GROUP", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case NOTIFGROUP:
            nnp = parse_objectgroup(fp, name, NOTIFICATIONS, &notifs);
            if (nnp == NULL) {
                print_error("Bad parse of NOTIFICATION-GROUP", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case TRAPTYPE:
            nnp = parse_trapDefinition(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of TRAP-TYPE", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case NOTIFTYPE:
            nnp = parse_notificationDefinition(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of NOTIFICATION-TYPE", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case COMPLIANCE:
            nnp = parse_compliance(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of MODULE-COMPLIANCE", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case AGENTCAP:
            nnp = parse_capabilities(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of AGENT-CAPABILITIES", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case MACRO:
            nnp = parse_macro(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of MACRO", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                /*
                 * return NULL;
                 */
            }
            free_node(nnp);     /* IGNORE */
            nnp = NULL;
            break;
        case MODULEIDENTITY:
            nnp = parse_moduleIdentity(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of MODULE-IDENTITY", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case OBJIDENTITY:
            nnp = parse_objectgroup(fp, name, OBJECTS, &objects);
            if (nnp == NULL) {
                print_error("Bad parse of OBJECT-IDENTITY", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case OBJECT:
            type = get_token(fp, token, MAXTOKEN);
            if (type != IDENTIFIER) {
                print_error("Expected IDENTIFIER", token, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            type = get_token(fp, token, MAXTOKEN);
            if (type != EQUALS) {
                print_error("Expected \"::=\"", token, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            nnp = parse_objectid(fp, name);
            if (nnp == NULL) {
                print_error("Bad parse of OBJECT IDENTIFIER", NULL, type);
                gMibError = MODULE_SYNTAX_ERROR;
                return NULL;
            }
            break;
        case EQUALS:
            nnp = parse_asntype(fp, name, &type, token);
            lasttype = CONTINUE;
            break;
        case ENDOFFILE:
            break;
        default:
            print_error("Bad operator", token, type);
            gMibError = MODULE_SYNTAX_ERROR;
            return NULL;
        }
        if (nnp) {
            if (np)
                np->next = nnp;
            else
                np = root = nnp;
            while (np->next)
                np = np->next;
            if (np->type == TYPE_OTHER)
                np->type = type;
        }
    }
    DEBUGMSGTL(("parse-file", "End of file (%s)\n", File));
    return root;
}


bool TabStrip::ShouldHighlightCloseButtonAfterRemove() {
  return in_tab_close_;
}


static void set_data_queue(fixed_queue_t *queue) {
  upwards_data_queue = queue;
}


nfsd4_encode_getfh(struct nfsd4_compoundres *resp, __be32 nfserr, struct svc_fh **fhpp)
{
	struct xdr_stream *xdr = &resp->xdr;
	struct svc_fh *fhp = *fhpp;
	unsigned int len;
	__be32 *p;

	if (!nfserr) {
		len = fhp->fh_handle.fh_size;
		p = xdr_reserve_space(xdr, len + 4);
		if (!p)
			return nfserr_resource;
		p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, len);
	}
	return nfserr;
}


int qemuAgentGetVCPUs ( qemuAgentPtr mon , qemuAgentCPUInfoPtr * info ) {
 int ret = - 1 ;
 size_t i ;
 virJSONValuePtr cmd ;
 virJSONValuePtr reply = NULL ;
 virJSONValuePtr data = NULL ;
 ssize_t ndata ;
 if ( ! ( cmd = qemuAgentMakeCommand ( "guest-get-vcpus" , NULL ) ) ) return - 1 ;
 if ( qemuAgentCommand ( mon , cmd , & reply , true , VIR_DOMAIN_QEMU_AGENT_COMMAND_BLOCK ) < 0 ) goto cleanup ;
 if ( ! ( data = virJSONValueObjectGet ( reply , "return" ) ) ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "guest-get-vcpus reply was missing return data" ) ) ;
 goto cleanup ;
 }
 if ( data -> type != VIR_JSON_TYPE_ARRAY ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "guest-get-vcpus return information was not an array" ) ) ;
 goto cleanup ;
 }
 ndata = virJSONValueArraySize ( data ) ;
 if ( VIR_ALLOC_N ( * info , ndata ) < 0 ) goto cleanup ;
 for ( i = 0 ;
 i < ndata ;
 i ++ ) {
 virJSONValuePtr entry = virJSONValueArrayGet ( data , i ) ;
 qemuAgentCPUInfoPtr in = * info + i ;
 if ( ! entry ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "array element missing in guest-get-vcpus return " "value" ) ) ;
 goto cleanup ;
 }
 if ( virJSONValueObjectGetNumberUint ( entry , "logical-id" , & in -> id ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'logical-id' missing in reply of guest-get-vcpus" ) ) ;
 goto cleanup ;
 }
 if ( virJSONValueObjectGetBoolean ( entry , "online" , & in -> online ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'online' missing in reply of guest-get-vcpus" ) ) ;
 goto cleanup ;
 }
 if ( virJSONValueObjectGetBoolean ( entry , "can-offline" , & in -> offlinable ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'can-offline' missing in reply of guest-get-vcpus" ) ) ;
 goto cleanup ;
 }
 }
 ret = ndata ;
 cleanup : virJSONValueFree ( cmd ) ;
 virJSONValueFree ( reply ) ;
 return ret ;
 }