int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
	unsigned long old_cr4 = kvm_read_cr4(vcpu);
	unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
				   X86_CR4_PAE | X86_CR4_SMEP;
	if (cr4 & CR4_RESERVED_BITS)
		return 1;

	if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
		return 1;

	if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
		return 1;

	if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS))
		return 1;

	if (is_long_mode(vcpu)) {
		if (!(cr4 & X86_CR4_PAE))
			return 1;
	} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
		   && ((cr4 ^ old_cr4) & pdptr_bits)
		   && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
				   kvm_read_cr3(vcpu)))
		return 1;

	if (kvm_x86_ops->set_cr4(vcpu, cr4))
		return 1;

	if ((cr4 ^ old_cr4) & pdptr_bits)
		kvm_mmu_reset_context(vcpu);

	if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
		kvm_update_cpuid(vcpu);

	return 0;
}


long do_rt_sigreturn(CPUAlphaState *env)

{

    abi_ulong frame_addr = env->ir[IR_A0];

    struct target_rt_sigframe *frame;

    sigset_t set;

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    target_to_host_sigset(&set, &frame->uc.tuc_sigmask);

    sigprocmask(SIG_SETMASK, &set, NULL);

    if (restore_sigcontext(env, &frame->uc.tuc_mcontext)) {

        goto badframe;

    }

    if (do_sigaltstack(frame_addr + offsetof(struct target_rt_sigframe,

                                             uc.tuc_stack),

                       0, env->ir[IR_SP]) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->ir[IR_V0];

 badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

}


void __rds_put_mr_final(struct rds_mr *mr)
{
	rds_destroy_mr(mr);
	kfree(mr);
}


EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
{
    DOMWindow* domWindow = this->domWindow();
    if (!domWindow)
        return 0;
    return domWindow->getAttributeEventListener(eventType, isolatedWorld);
}


_public_ void sd_bus_default_flush_close(void) {
        flush_close(default_starter_bus);
        flush_close(default_user_bus);
        flush_close(default_system_bus);
}


static int de_fmtutil_default_iff_chunk_handler(deark *c, struct de_iffctx *ictx)
{
	i64 dpos = ictx->chunkctx->dpos;
	i64 dlen = ictx->chunkctx->dlen;
	u32 chunktype = ictx->chunkctx->chunk4cc.id;

	switch(chunktype) {
		// Note that chunks appearing here should also be listed below,
		// in de_fmtutil_is_standard_iff_chunk().
	case CODE__c_:
		do_iff_text_chunk(c, ictx, dpos, dlen, "copyright");
		break;
	case CODE_ANNO:
		do_iff_anno(c, ictx, dpos, dlen);
		break;
	case CODE_AUTH:
		do_iff_text_chunk(c, ictx, dpos, dlen, "author");
		break;
	case CODE_NAME:
		do_iff_text_chunk(c, ictx, dpos, dlen, "name");
		break;
	case CODE_TEXT:
		do_iff_text_chunk(c, ictx, dpos, dlen, "text");
		break;
	}

	// Note we do not set ictx->handled. The caller is responsible for that.
	return 1;
}


static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
    gint64 *data_offset)
{
	gint64	offset;

	/* Find the next packet */
	offset = toshiba_seek_next_packet(wth, err, err_info);
	if (offset < 1)
		return FALSE;
	*data_offset = offset;

	/* Parse the packet */
	return parse_toshiba_packet(wth->fh, &wth->phdr, wth->frame_buffer,
	    err, err_info);
}


Response NetworkHandler::CanEmulateNetworkConditions(bool* result) {
  *result = true;
  return Response::OK();
}


static inline int propagate_entity_load_avg(struct sched_entity *se)
{
	struct cfs_rq *cfs_rq, *gcfs_rq;

	if (entity_is_task(se))
		return 0;

	gcfs_rq = group_cfs_rq(se);
	if (!gcfs_rq->propagate)
		return 0;

	gcfs_rq->propagate = 0;

	cfs_rq = cfs_rq_of(se);

	add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);

	update_tg_cfs_util(cfs_rq, se, gcfs_rq);
	update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);

	return 1;
}


SecureElementStatus_t SecureElementRestoreNvmCtx( void* seNvmCtx )
{
    // Restore nvm context
    if( seNvmCtx != 0 )
    {
        memcpy1( ( uint8_t* ) &SeNvmCtx, ( uint8_t* ) seNvmCtx, sizeof( SeNvmCtx ) );
        return SECURE_ELEMENT_SUCCESS;
    }
    else
    {
        return SECURE_ELEMENT_ERROR_NPE;
    }
}


TEST_P(SslReadBufferLimitTest, TestBind) {
  std::string address_string = TestUtility::getIpv4Loopback();
  if (GetParam() == Network::Address::IpVersion::v4) {
    source_address_ = Network::Address::InstanceConstSharedPtr{
        new Network::Address::Ipv4Instance(address_string, 0, nullptr)};
  } else {
    address_string = "::1";
    source_address_ = Network::Address::InstanceConstSharedPtr{
        new Network::Address::Ipv6Instance(address_string, 0, nullptr)};
  }

  initialize();

  EXPECT_CALL(listener_callbacks_, onAccept_(_))
      .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void {
        server_connection_ = dispatcher_->createServerConnection(
            std::move(socket), server_ssl_socket_factory_->createTransportSocket(nullptr),
            stream_info_);
        server_connection_->addConnectionCallbacks(server_callbacks_);
        server_connection_->addReadFilter(read_filter_);
        EXPECT_EQ("", server_connection_->nextProtocol());
      }));

  EXPECT_CALL(client_callbacks_, onEvent(Network::ConnectionEvent::Connected))
      .WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
  dispatcher_->run(Event::Dispatcher::RunType::Block);

  EXPECT_EQ(address_string,
            server_connection_->connectionInfoProvider().remoteAddress()->ip()->addressAsString());

  disconnect();
}


Resource* ResourceFetcher::RequestResource(
    FetchRequest& request,
    const ResourceFactory& factory,
    const SubstituteData& substitute_data) {
  unsigned long identifier = CreateUniqueIdentifier();
  ResourceRequest& resource_request = request.MutableResourceRequest();
  network_instrumentation::ScopedResourceLoadTracker
      scoped_resource_load_tracker(identifier, resource_request);
  SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.Fetch.RequestResourceTime");
  TRACE_EVENT1("blink", "ResourceFetcher::requestResource", "url",
               UrlForTraceEvent(request.Url()));

  Resource* resource = nullptr;
  ResourceRequestBlockedReason blocked_reason =
      ResourceRequestBlockedReason::kNone;

  PrepareRequestResult result = PrepareRequest(
      request, factory, substitute_data, identifier, blocked_reason);
  if (result == kAbort)
    return nullptr;
  if (result == kBlock)
    return ResourceForBlockedRequest(request, factory, blocked_reason);

  if (!request.IsSpeculativePreload()) {
    Context().RecordLoadingActivity(identifier, resource_request,
                                    factory.GetType(),
                                    request.Options().initiator_info.name);
  }

  bool is_data_url = resource_request.Url().ProtocolIsData();
  bool is_static_data = is_data_url || substitute_data.IsValid() || archive_;
  if (is_static_data) {
    resource = ResourceForStaticData(request, factory, substitute_data);
    if (!resource && !is_data_url && archive_)
      return nullptr;
  }
  if (!resource) {
    resource =
        GetMemoryCache()->ResourceForURL(request.Url(), GetCacheIdentifier());
  }

  MakePreloadedResourceBlockOnloadIfNeeded(resource, request);

  const RevalidationPolicy policy = DetermineRevalidationPolicy(
      factory.GetType(), request, resource, is_static_data);
  TRACE_EVENT_INSTANT1("blink", "ResourceFetcher::determineRevalidationPolicy",
                       TRACE_EVENT_SCOPE_THREAD, "revalidationPolicy", policy);

  UpdateMemoryCacheStats(resource, policy, request, factory, is_static_data);

  switch (policy) {
    case kReload:
      GetMemoryCache()->Remove(resource);
    case kLoad:
      resource = CreateResourceForLoading(request, request.Charset(), factory);
      break;
    case kRevalidate:
      InitializeRevalidation(resource_request, resource);
      break;
    case kUse:
      if (resource->IsLinkPreload() && !request.IsLinkPreload())
        resource->SetLinkPreload(false);
      break;
  }
  if (!resource)
    return nullptr;

  CHECK_EQ(resource->GetType(), factory.GetType());

  if (!resource->IsAlive())
    dead_stats_recorder_.Update(policy);

  if (policy != kUse)
    resource->SetIdentifier(identifier);

  if (!request.IsSpeculativePreload() || policy != kUse) {
    if (resource_request.Priority() > resource->GetResourceRequest().Priority())
      resource->DidChangePriority(resource_request.Priority(), 0);
  }

  DCHECK(EqualIgnoringFragmentIdentifier(resource->Url(), request.Url()));
  RequestLoadStarted(identifier, resource, request, policy, is_static_data);
  document_resources_.Set(
      MemoryCache::RemoveFragmentIdentifierIfNeeded(request.Url()), resource);

  if (!ResourceNeedsLoad(resource, request, policy))
    return resource;

  if (!StartLoad(resource))
    return nullptr;
  scoped_resource_load_tracker.resourceLoadContinuesBeyondScope();

  DCHECK(!resource->ErrorOccurred() ||
         request.Options().synchronous_policy == kRequestSynchronously);
  return resource;
}


Browser* GetOrCreateBrowser(Profile* profile, bool user_gesture) {
  Browser* browser = chrome::FindTabbedBrowser(profile, false);
  return browser ? browser
                 : new Browser(Browser::CreateParams(profile, user_gesture));
}


_dbus_header_cache_one (DBusHeader     *header,
                        int             field_code,
                        DBusTypeReader *variant_reader)
{
  header->fields[field_code].value_pos =
    _dbus_type_reader_get_value_pos (variant_reader);

#if 0
  _dbus_verbose ("cached value_pos %d for field %d\n",
                 header->fields[field_code].value_pos, field_code)
#endif
}


void mime_hdr_presence_unset ( MIMEHdrImpl * h , const char * well_known_str ) {
 uint64_t mask = mime_field_presence_mask ( well_known_str ) ;
 if ( mask != 0 ) {
 h -> m_presence_bits &= ( ~ mask ) ;
 }
 }


int GetCountFromBackgroundPage(const Extension* extension,
                               content::BrowserContext* context,
                               const std::string& variable_name) {
  ExtensionHost* host =
      ProcessManager::Get(context)->GetBackgroundHostForExtension(
          extension->id());
  if (!host || !host->host_contents())
    return -1;

  int count = -1;
  if (!ExecuteScriptAndExtractInt(
          host->host_contents(),
          "window.domAutomationController.send(" + variable_name + ")", &count))
    return -1;
  return count;
}


std::string get_wml_location(const std::string &filename, const std::string &current_dir)
{
	DBG_FS << "Looking for '" << filename << "'." << std::endl;

	assert(game_config::path.empty() == false);

	std::string result;

	if (filename.empty()) {
		LOG_FS << "  invalid filename" << std::endl;
		return result;
	}

	if (filename.find("..") != std::string::npos) {
		ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
		return result;
	}

	bool already_found = false;

	if (filename[0] == '~')
	{
		// If the filename starts with '~', look in the user data directory.
		result = get_user_data_dir() + "/data/" + filename.substr(1);
		DBG_FS << "  trying '" << result << "'" << std::endl;

		already_found = file_exists(result) || is_directory(result);
	}
	else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
	{
		// If the filename begins with a "./", look in the same directory
		// as the file currently being preprocessed.

		if (!current_dir.empty())
		{
			result = current_dir;
		}
		else
		{
			result = game_config::path;
		}

		result += filename.substr(2);
	}
	else if (!game_config::path.empty())
		result = game_config::path + "/data/" + filename;

	DBG_FS << "  trying '" << result << "'" << std::endl;

	if (result.empty() ||
	    (!already_found && !file_exists(result) && !is_directory(result)))
	{
		DBG_FS << "  not found" << std::endl;
		result.clear();
	}
	else
		DBG_FS << "  found: '" << result << "'" << std::endl;

	return result;
}


void GDataDirectoryService::GetEntryInfoPairByPathsAfterGetFirst(
    const FilePath& first_path,
    const FilePath& second_path,
    const GetEntryInfoPairCallback& callback,
    GDataFileError error,
    scoped_ptr<GDataEntryProto> entry_proto) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  scoped_ptr<EntryInfoPairResult> result(new EntryInfoPairResult);
  result->first.path = first_path;
  result->first.error = error;
  result->first.proto = entry_proto.Pass();

  if (error != GDATA_FILE_OK) {
    callback.Run(result.Pass());
    return;
  }

  GetEntryInfoByPath(
      second_path,
      base::Bind(&GDataDirectoryService::GetEntryInfoPairByPathsAfterGetSecond,
                 weak_ptr_factory_.GetWeakPtr(),
                 second_path,
                 callback,
                 base::Passed(&result)));
}


  void Compute(OpKernelContext *ctx) override {
    const Tensor *indices_t, *values_t, *shape_t, *dense_t;
    OP_REQUIRES_OK(ctx, ctx->input("sp_indices", &indices_t));
    OP_REQUIRES_OK(ctx, ctx->input("sp_values", &values_t));
    OP_REQUIRES_OK(ctx, ctx->input("sp_shape", &shape_t));
    OP_REQUIRES_OK(ctx, ctx->input("dense", &dense_t));

    // Validations.
    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),
                errors::InvalidArgument(
                    "Input sp_indices should be a matrix but received shape: ",
                    indices_t->shape().DebugString()));
    OP_REQUIRES(ctx,
                TensorShapeUtils::IsVector(values_t->shape()) &&
                    TensorShapeUtils::IsVector(shape_t->shape()),
                errors::InvalidArgument(
                    "Inputs sp_values and sp_shape should be vectors "
                    "but received shapes: ",
                    values_t->shape().DebugString(), " and ",
                    shape_t->shape().DebugString()));

    const auto indices_mat = indices_t->matrix<int64>();
    const auto shape_vec = shape_t->vec<int64>();
    const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));
    const auto rhs_dims = BCast::FromShape(dense_t->shape());
    BCast b(lhs_dims, rhs_dims, false);  // false for keeping the same num dims.

    // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal
    // to dims in rhs (from right to left).
    auto VecGreaterEq = [](ArraySlice<int64> lhs, ArraySlice<int64> rhs) {
      if (lhs.size() < rhs.size()) return false;
      for (size_t i = 0; i < rhs.size(); ++i) {
        if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;
      }
      return true;
    };
    OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),
                errors::InvalidArgument(
                    "SparseDenseBinaryOpShared broadcasts dense to sparse "
                    "only; got incompatible shapes: [",
                    absl::StrJoin(lhs_dims, ","), "] vs. [",
                    absl::StrJoin(rhs_dims, ","), "]"));

    Tensor *output_values = nullptr;
    Tensor dense_gathered;
    const int64 nnz = indices_t->dim_size(0);
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_output(0, TensorShape({nnz}), &output_values));
    OP_REQUIRES_OK(
        ctx, ctx->allocate_temp(DataTypeToEnum<T>::value, TensorShape({nnz}),
                                &dense_gathered));

    // Pulls relevant entries from the dense side, with reshape and broadcasting
    // *of the dense side* taken into account.  Use a TensorRef to avoid blowing
    // up memory.
    //
    // We can directly use the sparse indices to look up dense side, because
    // "b.y_reshape()" and "b.y_bcast()" are guaranteed to have rank "ndims".
    auto dense_gathered_flat = dense_gathered.flat<T>();
    const int ndims = lhs_dims.size();
    switch (ndims) {
#define CASE(NDIM)                                                             \
  case NDIM: {                                                                 \
    TensorRef<Eigen::Tensor<const T, NDIM, Eigen::RowMajor>> rhs_ref =         \
        dense_t->shaped<T, NDIM>(b.y_reshape())                                \
            .broadcast(BCast::ToIndexArray<NDIM>(b.y_bcast()));                \
    Eigen::array<Eigen::DenseIndex, NDIM> idx;                                 \
    bool indices_valid = true;                                                 \
    for (int i = 0; i < nnz; ++i) {                                            \
      for (int d = 0; d < NDIM; ++d) {                                         \
        idx[d] = internal::SubtleMustCopy(indices_mat(i, d));                  \
        if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) {                  \
          indices_valid = false;                                               \
        }                                                                      \
      }                                                                        \
      OP_REQUIRES(                                                             \
          ctx, indices_valid,                                                  \
          errors::InvalidArgument("Provided indices are out-of-bounds w.r.t. " \
                                  "dense side with broadcasted shape"));       \
      dense_gathered_flat(i) = rhs_ref.coeff(idx);                             \
    }                                                                          \
    break;                                                                     \
  }

      CASE(1);
      CASE(2);
      CASE(3);
      CASE(4);
      CASE(5);
      default:
        OP_REQUIRES(
            ctx, false,
            errors::InvalidArgument("Only tensors with ranks between 1 and 5 "
                                    "are currently supported.  Tensor rank: ",
                                    ndims));
#undef CASE
    }

    output_values->flat<T>().device(ctx->eigen_device<Device>()) =
        values_t->flat<T>().binaryExpr(dense_gathered_flat,
                                       typename Functor::func());
  }


  const cc::PropertyTrees& GetPropertyTrees() {
    return *web_layer_tree_view_->GetLayerTreeHost()->property_trees();
  }


void iov_iter_advance(struct iov_iter *i, size_t bytes)
{
	BUG_ON(i->count < bytes);

	__iov_iter_advance_iov(i, bytes);
	i->count -= bytes;
}


static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
			u8 *object, char *what,
			u8 *start, unsigned int value, unsigned int bytes)
{
	u8 *fault;
	u8 *end;

	fault = check_bytes(start, value, bytes);
	if (!fault)
		return 1;

	end = start + bytes;
	while (end > fault && end[-1] == value)
		end--;

	slab_bug(s, "%s overwritten", what);
	printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
					fault, end - 1, fault[0], value);
	print_trailer(s, page, object);

	restore_bytes(s, what, value, fault, end);
	return 0;
}


read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,
    struct _7z_folder *f, size_t numFolders)
{
	const unsigned char *p;
	uint64_t *usizes;
	size_t unpack_streams;
	int type;
	unsigned i;
	uint32_t numDigests;

	memset(ss, 0, sizeof(*ss));

	for (i = 0; i < numFolders; i++)
		f[i].numUnpackStreams = 1;

	if ((p = header_bytes(a, 1)) == NULL)
		return (-1);
	type = *p;

	if (type == kNumUnPackStream) {
		unpack_streams = 0;
		for (i = 0; i < numFolders; i++) {
			if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0)
				return (-1);
			if (UMAX_ENTRY < f[i].numUnpackStreams)
				return (-1);
			if (unpack_streams > SIZE_MAX - UMAX_ENTRY) {
				return (-1);
			}
			unpack_streams += (size_t)f[i].numUnpackStreams;
		}
		if ((p = header_bytes(a, 1)) == NULL)
			return (-1);
		type = *p;
	} else
		unpack_streams = numFolders;

	ss->unpack_streams = unpack_streams;
	if (unpack_streams) {
		ss->unpackSizes = calloc(unpack_streams,
		    sizeof(*ss->unpackSizes));
		ss->digestsDefined = calloc(unpack_streams,
		    sizeof(*ss->digestsDefined));
		ss->digests = calloc(unpack_streams,
		    sizeof(*ss->digests));
		if (ss->unpackSizes == NULL || ss->digestsDefined == NULL ||
		    ss->digests == NULL)
			return (-1);
	}

	usizes = ss->unpackSizes;
	for (i = 0; i < numFolders; i++) {
		unsigned pack;
		uint64_t sum;

		if (f[i].numUnpackStreams == 0)
			continue;

		sum = 0;
		if (type == kSize) {
			for (pack = 1; pack < f[i].numUnpackStreams; pack++) {
				if (parse_7zip_uint64(a, usizes) < 0)
					return (-1);
				sum += *usizes++;
			}
		}
		*usizes++ = folder_uncompressed_size(&f[i]) - sum;
	}

	if (type == kSize) {
		if ((p = header_bytes(a, 1)) == NULL)
			return (-1);
		type = *p;
	}

	for (i = 0; i < unpack_streams; i++) {
		ss->digestsDefined[i] = 0;
		ss->digests[i] = 0;
	}

	numDigests = 0;
	for (i = 0; i < numFolders; i++) {
		if (f[i].numUnpackStreams != 1 || !f[i].digest_defined)
			numDigests += (uint32_t)f[i].numUnpackStreams;
	}

	if (type == kCRC) {
		struct _7z_digests tmpDigests;
		unsigned char *digestsDefined = ss->digestsDefined;
		uint32_t * digests = ss->digests;
		int di = 0;

		memset(&tmpDigests, 0, sizeof(tmpDigests));
		if (read_Digests(a, &(tmpDigests), numDigests) < 0) {
			free_Digest(&tmpDigests);
			return (-1);
		}
		for (i = 0; i < numFolders; i++) {
			if (f[i].numUnpackStreams == 1 && f[i].digest_defined) {
				*digestsDefined++ = 1;
				*digests++ = f[i].digest;
			} else {
				unsigned j;

				for (j = 0; j < f[i].numUnpackStreams;
				    j++, di++) {
					*digestsDefined++ =
					    tmpDigests.defineds[di];
					*digests++ =
					    tmpDigests.digests[di];
				}
			}
		}
		free_Digest(&tmpDigests);
		if ((p = header_bytes(a, 1)) == NULL)
			return (-1);
		type = *p;
	}

	/*
	 *  Must be kEnd.
	 */
	if (type != kEnd)
		return (-1);
	return (0);
}


FileBrowserHandler* Extension::LoadFileBrowserHandler(
    const DictionaryValue* file_browser_handler, std::string* error) {
  scoped_ptr<FileBrowserHandler> result(
      new FileBrowserHandler());
  result->set_extension_id(id());

  std::string id;
  if (!file_browser_handler->HasKey(keys::kPageActionId) ||
      !file_browser_handler->GetString(keys::kPageActionId, &id)) {
    *error = errors::kInvalidPageActionId;
    return NULL;
  }
  result->set_id(id);

  std::string title;
  if (!file_browser_handler->HasKey(keys::kPageActionDefaultTitle) ||
      !file_browser_handler->GetString(keys::kPageActionDefaultTitle, &title)) {
    *error = errors::kInvalidPageActionDefaultTitle;
    return NULL;
  }
  result->set_title(title);

  ListValue* list_value = NULL;
  if (!file_browser_handler->HasKey(keys::kFileFilters) ||
      !file_browser_handler->GetList(keys::kFileFilters, &list_value) ||
      list_value->empty()) {
    *error = errors::kInvalidFileFiltersList;
    return NULL;
  }
  for (size_t i = 0; i < list_value->GetSize(); ++i) {
    std::string filter;
    if (!list_value->GetString(i, &filter)) {
      *error = ExtensionErrorUtils::FormatErrorMessage(
          errors::kInvalidFileFilterValue, base::IntToString(i));
      return NULL;
    }
    URLPattern pattern(URLPattern::SCHEME_FILESYSTEM);
    if (pattern.Parse(filter, URLPattern::ERROR_ON_PORTS) !=
        URLPattern::PARSE_SUCCESS) {
      *error = ExtensionErrorUtils::FormatErrorMessage(
          errors::kInvalidURLPatternError, filter);
      return NULL;
    }
    result->AddPattern(pattern);
  }

  std::string default_icon;
  if (file_browser_handler->HasKey(keys::kPageActionDefaultIcon)) {
    if (!file_browser_handler->GetString(
            keys::kPageActionDefaultIcon,&default_icon) ||
        default_icon.empty()) {
      *error = errors::kInvalidPageActionIconPath;
      return NULL;
    }
    result->set_icon_path(default_icon);
  }

  return result.release();
}


void *hashtable_get(hashtable_t *hashtable, const char *key)
{
    pair_t *pair;
    size_t hash;
    bucket_t *bucket;

    hash = hash_str(key);
    bucket = &hashtable->buckets[hash & hashmask(hashtable->order)];

    pair = hashtable_find_pair(hashtable, bucket, key, hash);
    if(!pair)
        return NULL;

    return pair->value;
}


static void autocomplete_file(RLineCompletion *completion, const char *str) {
	r_return_if_fail (str);
	char *pipe = strchr (str, '>');

	if (pipe) {
		str = r_str_trim_head_ro (pipe + 1);
	}
	if (str && !*str) {
		autocomplete_process_path (completion, str, "./");
	} else {
		autocomplete_process_path (completion, str, str);
	}

}


void PasswordAutofillAgent::SetPasswordGenerationAgent(
    PasswordGenerationAgent* generation_agent) {
  password_generation_agent_ = generation_agent;
}


PHP_FUNCTION(imagecreatefromxpm)
{
	_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XPM, "XPM", gdImageCreateFromXpm, NULL);
}


void WebMediaPlayerImpl::ScheduleRestart() {
  if (pipeline_controller_.IsPipelineRunning() &&
      !pipeline_controller_.IsPipelineSuspended()) {
    pending_suspend_resume_cycle_ = true;
    UpdatePlayState();
  }
}


bool ChromeContentBrowserClientExtensionsPart::ShouldSwapProcessesForRedirect(
    content::BrowserContext* browser_context,
    const GURL& current_url,
    const GURL& new_url) {
  return CrossesExtensionProcessBoundary(
      ExtensionRegistry::Get(browser_context)->enabled_extensions(),
      current_url, new_url, false);
}


TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
  const TfLiteTensor* input;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));

  output->type = input->type;
  return context->ResizeTensor(context, output,
                               TfLiteIntArrayCopy(input->dims));
}


int callback_glewlwyd_get_user_auth_scheme_module_list (const struct _u_request * request, struct _u_response * response, void * user_auth_scheme_data) {
  UNUSED(request);
  struct config_elements * config = (struct config_elements *)user_auth_scheme_data;
  json_t * j_module;

  j_module = get_user_auth_scheme_module_list(config);
  if (check_result_value(j_module, G_OK)) {
    ulfius_set_json_body_response(response, 200, json_object_get(j_module, "module"));
  } else {
    y_log_message(Y_LOG_LEVEL_ERROR, "callback_glewlwyd_get_user_auth_scheme_module_list - Error get_user_auth_scheme_module_list");
    response->status = 500;
  }
  json_decref(j_module);
  return U_CALLBACK_CONTINUE;
}


PassRefPtr<Element> HTMLConstructionSite::createHTMLElement(AtomicHTMLToken& token)
{
    QualifiedName tagName(nullAtom, token.name(), xhtmlNamespaceURI);
    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, m_document, form(), true);
    element->setAttributeMap(token.takeAtributes(), m_fragmentScriptingPermission);
    ASSERT(element->isHTMLElement());
    return element.release();
}


JsVar *jspEvaluateModule(JsVar *moduleContents) {
  assert(jsvIsString(moduleContents) || jsvIsFunction(moduleContents));
  if (jsvIsFunction(moduleContents)) {
    moduleContents = jsvObjectGetChild(moduleContents,JSPARSE_FUNCTION_CODE_NAME,0);
    if (!jsvIsString(moduleContents)) {
      jsvUnLock(moduleContents);
      return 0;
    }
  } else
    jsvLockAgain(moduleContents);
  JsVar *scope = jsvNewObject();
  JsVar *scopeExports = jsvNewObject();
  if (!scope || !scopeExports) { // out of mem
    jsvUnLock3(scope, scopeExports, moduleContents);
    return 0;
  }
  JsVar *exportsName = jsvAddNamedChild(scope, scopeExports, "exports");
  jsvUnLock2(scopeExports, jsvAddNamedChild(scope, scope, "module"));

  JsExecFlags oldExecute = execInfo.execute;
  JsVar *oldThisVar = execInfo.thisVar;
  execInfo.thisVar = scopeExports; // set 'this' variable to exports
  jsvUnLock(jspEvaluateVar(moduleContents, scope, 0));
  execInfo.thisVar = oldThisVar;
  execInfo.execute = oldExecute; // make sure we fully restore state after parsing a module

  jsvUnLock2(moduleContents, scope);
  return jsvSkipNameAndUnLock(exportsName);
}


vips_foreign_operation_init( void )
{
	extern GType vips_foreign_load_rad_get_type( void );
	extern GType vips_foreign_save_rad_file_get_type( void );
	extern GType vips_foreign_save_rad_buffer_get_type( void );
	extern GType vips_foreign_load_mat_get_type( void );
	extern GType vips_foreign_load_ppm_get_type( void );
	extern GType vips_foreign_save_ppm_get_type( void );
	extern GType vips_foreign_load_png_get_type( void );
	extern GType vips_foreign_load_png_buffer_get_type( void );
	extern GType vips_foreign_save_png_file_get_type( void );
	extern GType vips_foreign_save_png_buffer_get_type( void );
	extern GType vips_foreign_load_csv_get_type( void );
	extern GType vips_foreign_save_csv_get_type( void );
	extern GType vips_foreign_load_matrix_get_type( void );
	extern GType vips_foreign_save_matrix_get_type( void );
	extern GType vips_foreign_print_matrix_get_type( void );
	extern GType vips_foreign_load_fits_get_type( void );
	extern GType vips_foreign_save_fits_get_type( void );
	extern GType vips_foreign_load_analyze_get_type( void );
	extern GType vips_foreign_load_openexr_get_type( void );
	extern GType vips_foreign_load_openslide_get_type( void );
	extern GType vips_foreign_load_jpeg_file_get_type( void );
	extern GType vips_foreign_load_jpeg_buffer_get_type( void );
	extern GType vips_foreign_save_jpeg_file_get_type( void );
	extern GType vips_foreign_save_jpeg_buffer_get_type( void );
	extern GType vips_foreign_save_jpeg_mime_get_type( void );
	extern GType vips_foreign_load_tiff_file_get_type( void );
	extern GType vips_foreign_load_tiff_buffer_get_type( void );
	extern GType vips_foreign_save_tiff_file_get_type( void );
	extern GType vips_foreign_save_tiff_buffer_get_type( void );
	extern GType vips_foreign_load_vips_get_type( void );
	extern GType vips_foreign_save_vips_get_type( void );
	extern GType vips_foreign_load_raw_get_type( void );
	extern GType vips_foreign_save_raw_get_type( void );
	extern GType vips_foreign_save_raw_fd_get_type( void );
	extern GType vips_foreign_load_magick_file_get_type( void );
	extern GType vips_foreign_load_magick_buffer_get_type( void );
	extern GType vips_foreign_load_magick7_file_get_type( void );
	extern GType vips_foreign_load_magick7_buffer_get_type( void );
	extern GType vips_foreign_save_dz_file_get_type( void );
	extern GType vips_foreign_save_dz_buffer_get_type( void );
	extern GType vips_foreign_load_webp_file_get_type( void );
	extern GType vips_foreign_load_webp_buffer_get_type( void );
	extern GType vips_foreign_save_webp_file_get_type( void );
	extern GType vips_foreign_save_webp_buffer_get_type( void );
	extern GType vips_foreign_load_pdf_get_type( void );
	extern GType vips_foreign_load_pdf_file_get_type( void );
	extern GType vips_foreign_load_pdf_buffer_get_type( void );
	extern GType vips_foreign_load_svg_get_type( void );
	extern GType vips_foreign_load_svg_file_get_type( void );
	extern GType vips_foreign_load_svg_buffer_get_type( void );
	extern GType vips_foreign_load_gif_get_type( void );
	extern GType vips_foreign_load_gif_file_get_type( void );
	extern GType vips_foreign_load_gif_buffer_get_type( void );

	vips_foreign_load_csv_get_type();
	vips_foreign_save_csv_get_type();
	vips_foreign_load_matrix_get_type();
	vips_foreign_save_matrix_get_type();
	vips_foreign_print_matrix_get_type();
	vips_foreign_load_raw_get_type();
	vips_foreign_save_raw_get_type();
	vips_foreign_save_raw_fd_get_type();
	vips_foreign_load_vips_get_type();
	vips_foreign_save_vips_get_type();

#ifdef HAVE_ANALYZE
	vips_foreign_load_analyze_get_type();
#endif /*HAVE_ANALYZE*/

#ifdef HAVE_PPM
	vips_foreign_load_ppm_get_type();
	vips_foreign_save_ppm_get_type();
#endif /*HAVE_PPM*/

#ifdef HAVE_RADIANCE
	vips_foreign_load_rad_get_type();
	vips_foreign_save_rad_file_get_type();
	vips_foreign_save_rad_buffer_get_type();
#endif /*HAVE_RADIANCE*/

#ifdef HAVE_POPPLER
	vips_foreign_load_pdf_get_type();
	vips_foreign_load_pdf_file_get_type();
	vips_foreign_load_pdf_buffer_get_type();
#endif /*HAVE_POPPLER*/

#ifdef HAVE_RSVG
	vips_foreign_load_svg_get_type();
	vips_foreign_load_svg_file_get_type();
	vips_foreign_load_svg_buffer_get_type();
#endif /*HAVE_RSVG*/

#ifdef HAVE_GIFLIB
	vips_foreign_load_gif_get_type();
	vips_foreign_load_gif_file_get_type();
	vips_foreign_load_gif_buffer_get_type();
#endif /*HAVE_GIFLIB*/

#ifdef HAVE_GSF
	vips_foreign_save_dz_file_get_type();
	vips_foreign_save_dz_buffer_get_type();
#endif /*HAVE_GSF*/

#ifdef HAVE_PNG
	vips_foreign_load_png_get_type();
	vips_foreign_load_png_buffer_get_type();
	vips_foreign_save_png_file_get_type();
	vips_foreign_save_png_buffer_get_type();
#endif /*HAVE_PNG*/

#ifdef HAVE_MATIO
	vips_foreign_load_mat_get_type();
#endif /*HAVE_MATIO*/

#ifdef HAVE_JPEG
	vips_foreign_load_jpeg_file_get_type();
	vips_foreign_load_jpeg_buffer_get_type();
	vips_foreign_save_jpeg_file_get_type();
	vips_foreign_save_jpeg_buffer_get_type();
	vips_foreign_save_jpeg_mime_get_type();
#endif /*HAVE_JPEG*/

#ifdef HAVE_LIBWEBP
	vips_foreign_load_webp_file_get_type();
	vips_foreign_load_webp_buffer_get_type();
	vips_foreign_save_webp_file_get_type();
	vips_foreign_save_webp_buffer_get_type();
#endif /*HAVE_LIBWEBP*/

#ifdef HAVE_TIFF
	vips_foreign_load_tiff_file_get_type();
	vips_foreign_load_tiff_buffer_get_type();
	vips_foreign_save_tiff_file_get_type();
	vips_foreign_save_tiff_buffer_get_type();
#endif /*HAVE_TIFF*/

#ifdef HAVE_OPENSLIDE
	vips_foreign_load_openslide_get_type();
#endif /*HAVE_OPENSLIDE*/

#ifdef HAVE_MAGICK
	vips_foreign_load_magick_file_get_type();
	vips_foreign_load_magick_buffer_get_type();
#endif /*HAVE_MAGICK*/

#ifdef HAVE_MAGICK7
	vips_foreign_load_magick7_file_get_type();
	vips_foreign_load_magick7_buffer_get_type();
#endif /*HAVE_MAGICK7*/

#ifdef HAVE_CFITSIO
	vips_foreign_load_fits_get_type();
	vips_foreign_save_fits_get_type();
#endif /*HAVE_CFITSIO*/

#ifdef HAVE_OPENEXR
	vips_foreign_load_openexr_get_type();
#endif /*HAVE_OPENEXR*/

	vips__foreign_load_operation =
		g_quark_from_static_string( "vips-foreign-load-operation" );
}


static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
  va_list ap;
  va_start(ap, zFmt);
  sqlite3_free(pCsr->base.pVtab->zErrMsg);
  pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  va_end(ap);
}


PredictorSetupDecode(TIFF* tif)
{
	TIFFPredictorState* sp = PredictorState(tif);
	TIFFDirectory* td = &tif->tif_dir;

	if (!(*sp->setupdecode)(tif) || !PredictorSetup(tif))
		return 0;

	if (sp->predictor == 2) {
		switch (td->td_bitspersample) {
			case 8:  sp->decodepfunc = horAcc8; break;
			case 16: sp->decodepfunc = horAcc16; break;
			case 32: sp->decodepfunc = horAcc32; break;
		}
		/*
		 * Override default decoding method with one that does the
		 * predictor stuff.
		 */
                if( tif->tif_decoderow != PredictorDecodeRow )
                {
                    sp->decoderow = tif->tif_decoderow;
                    tif->tif_decoderow = PredictorDecodeRow;
                    sp->decodestrip = tif->tif_decodestrip;
                    tif->tif_decodestrip = PredictorDecodeTile;
                    sp->decodetile = tif->tif_decodetile;
                    tif->tif_decodetile = PredictorDecodeTile;
                }

		/*
		 * If the data is horizontally differenced 16-bit data that
		 * requires byte-swapping, then it must be byte swapped before
		 * the accumulation step.  We do this with a special-purpose
		 * routine and override the normal post decoding logic that
		 * the library setup when the directory was read.
		 */
		if (tif->tif_flags & TIFF_SWAB) {
			if (sp->decodepfunc == horAcc16) {
				sp->decodepfunc = swabHorAcc16;
				tif->tif_postdecode = _TIFFNoPostDecode;
            } else if (sp->decodepfunc == horAcc32) {
				sp->decodepfunc = swabHorAcc32;
				tif->tif_postdecode = _TIFFNoPostDecode;
            }
		}
	}

	else if (sp->predictor == 3) {
		sp->decodepfunc = fpAcc;
		/*
		 * Override default decoding method with one that does the
		 * predictor stuff.
		 */
                if( tif->tif_decoderow != PredictorDecodeRow )
                {
                    sp->decoderow = tif->tif_decoderow;
                    tif->tif_decoderow = PredictorDecodeRow;
                    sp->decodestrip = tif->tif_decodestrip;
                    tif->tif_decodestrip = PredictorDecodeTile;
                    sp->decodetile = tif->tif_decodetile;
                    tif->tif_decodetile = PredictorDecodeTile;
                }
		/*
		 * The data should not be swapped outside of the floating
		 * point predictor, the accumulation routine should return
		 * byres in the native order.
		 */
		if (tif->tif_flags & TIFF_SWAB) {
			tif->tif_postdecode = _TIFFNoPostDecode;
		}
		/*
		 * Allocate buffer to keep the decoded bytes before
		 * rearranging in the right order
		 */
	}

	return 1;
}


    inline U16 readU16() { check(2); int b0 = *ptr++; int b1 = *ptr++;
                           return b0 << 8 | b1; }


TypedValue HHVM_FUNCTION(strchr,
                         const String& haystack,
                         const Variant& needle) {
  return HHVM_FN(strstr)(haystack, needle);
}


Curl_ssl_connect(struct Curl_easy *data, struct connectdata *conn,
                 int sockindex)
{
  CURLcode result;

#ifndef CURL_DISABLE_PROXY
  if(conn->bits.proxy_ssl_connected[sockindex]) {
    result = ssl_connect_init_proxy(conn, sockindex);
    if(result)
      return result;
  }
#endif

  if(!ssl_prefs_check(data))
    return CURLE_SSL_CONNECT_ERROR;

  /* mark this is being ssl-enabled from here on. */
  conn->ssl[sockindex].use = TRUE;
  conn->ssl[sockindex].state = ssl_connection_negotiating;

  result = Curl_ssl->connect_blocking(data, conn, sockindex);

  if(!result)
    Curl_pgrsTime(data, TIMER_APPCONNECT); /* SSL is connected */
  else
    conn->ssl[sockindex].use = FALSE;

  return result;
}


check_connection(void)
{
    make_connection();
    if (X_DISPLAY == NULL)
    {
	emsg(_("E240: No connection to the X server"));
	return FAIL;
    }
    return OK;
}


static int ntop_http_redirect(lua_State* vm) {
  char *url, str[512];

  ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__);

  if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
  if((url = (char*)lua_tostring(vm, 1)) == NULL)  return(CONST_LUA_PARAM_ERROR);

  snprintf(str, sizeof(str), "HTTP/1.1 302 Found\r\n"
	   "Location: %s\r\n\r\n"
	   "\n"
	   "\n"
	   "<title>Moved</title>\n"
	   "\n"
	   "\n"
	   "
Moved
\n"
	   "
This page has moved to %s.
\n"
	   "\n"
	   "\n", url, url, url);

  lua_pushstring(vm, str);

  return(CONST_LUA_OK);
}


/* Append uint to ds, with optional replace */
void replace_dynstr_append_uint(DYNAMIC_STRING *ds, uint val)
{
  char buff[22]; /* This should be enough for any int */
  char *end= longlong10_to_str(val, buff, 10);


Response InspectorNetworkAgent::setBypassServiceWorker(bool bypass) {
  state_->setBoolean(NetworkAgentState::kBypassServiceWorker, bypass);
  return Response::OK();
}


void RenderViewImpl::SetGuestToEmbedderChannel(
    content::old::GuestToEmbedderChannel* channel) {
  guest_to_embedder_channel_ = channel;
}


static pj_status_t circ_init(pj_pool_factory *factory,
                             circ_buf_t *cb, pj_size_t cap)
{
    cb->cap    = cap;
    cb->readp  = 0;
    cb->writep = 0;
    cb->size   = 0;

    /* Initial pool holding the buffer elements */
    cb->pool = pj_pool_create(factory, "tls-circ%p", cap, cap, NULL);
    if (!cb->pool)
        return PJ_ENOMEM;

    /* Allocate circular buffer */
    cb->buf = pj_pool_alloc(cb->pool, cap);
    if (!cb->buf) {
        pj_pool_release(cb->pool);
        return PJ_ENOMEM;
    }

    return PJ_SUCCESS;
}


JNI_SendTabToSelfAndroidBridge_GetEntryByGUID(
    JNIEnv* env,
    const JavaParamRef<jobject>& j_profile,
    const JavaParamRef<jstring>& j_guid) {
  SendTabToSelfModel* model = GetModel(j_profile);
  if (!model->IsReady()) {
    return nullptr;
  }

  const std::string guid = ConvertJavaStringToUTF8(env, j_guid);
  const SendTabToSelfEntry* found_entry = model->GetEntryByGUID(guid);

  if (found_entry == nullptr) {
    return nullptr;
  }

  return CreateJavaSendTabToSelfEntry(env, found_entry);
}


   This function decrypts the crypttext */
PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes)
{
	int i, count = 0;
	int *key_sizes;

	MCRYPT_GET_TD_ARG
	array_init(return_value);

	key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count);

	for (i = 0; i < count; i++) {
		add_index_long(return_value, i, key_sizes[i]);
	}

	mcrypt_free(key_sizes);


smtp_report_timeout(struct smtp_session *s)
{
	if (! SESSION_FILTERED(s))
		return;

	report_smtp_timeout("smtp-in", s->id);
}


static int output_packet(InputStream *ist, int ist_index,

                         OutputStream *ost_table, int nb_ostreams,

                         const AVPacket *pkt)

{

    AVFormatContext *os;

    OutputStream *ost;

    int ret, i;

    int got_output;

    void *buffer_to_free = NULL;

    static unsigned int samples_size= 0;

    AVSubtitle subtitle, *subtitle_to_free;

    int64_t pkt_pts = AV_NOPTS_VALUE;

#if CONFIG_AVFILTER

    int frame_available;

#endif

    float quality;

    AVPacket avpkt;

    int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);

    if(ist->next_pts == AV_NOPTS_VALUE)

        ist->next_pts= ist->pts;

    if (pkt == NULL) {

        /* EOF handling */

        av_init_packet(&avpkt);

        avpkt.data = NULL;

        avpkt.size = 0;

        goto handle_eof;

    } else {

        avpkt = *pkt;

    }

    if(pkt->dts != AV_NOPTS_VALUE)

        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);

    if(pkt->pts != AV_NOPTS_VALUE)

        pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);

    //while we have more to decode or while the decoder did output something on EOF

    while (avpkt.size > 0 || (!pkt && got_output)) {

        uint8_t *data_buf, *decoded_data_buf;

        int data_size, decoded_data_size;

        AVFrame *decoded_frame, *filtered_frame;

    handle_eof:

        ist->pts= ist->next_pts;

        if(avpkt.size && avpkt.size != pkt->size)

            av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,

                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);

            ist->showed_multi_packet_warning=1;

        /* decode the packet if needed */

        decoded_frame    = filtered_frame = NULL;

        decoded_data_buf = NULL; /* fail safe */

        decoded_data_size= 0;

        data_buf  = avpkt.data;

        data_size = avpkt.size;

        subtitle_to_free = NULL;

        if (ist->decoding_needed) {

            switch(ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:{

                if(pkt && samples_size < FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE)) {

                    samples_size = FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE);

                    av_free(samples);

                    samples= av_malloc(samples_size);

                }

                decoded_data_size= samples_size;

                    /* XXX: could avoid copy if PCM 16 bits with same

                       endianness as CPU */

                ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,

                                            &avpkt);

                if (ret < 0)

                    return ret;

                avpkt.data += ret;

                avpkt.size -= ret;

                data_size   = ret;

                got_output  = decoded_data_size > 0;

                /* Some bug in mpeg audio decoder gives */

                /* decoded_data_size < 0, it seems they are overflows */

                if (!got_output) {

                    /* no audio frame */

                    continue;

                }

                decoded_data_buf = (uint8_t *)samples;

                ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /

                    (ist->st->codec->sample_rate * ist->st->codec->channels);

                break;}

            case AVMEDIA_TYPE_VIDEO:

                    decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;

                    if (!(decoded_frame = avcodec_alloc_frame()))

                        return AVERROR(ENOMEM);

                    avpkt.pts = pkt_pts;

                    avpkt.dts = ist->pts;

                    pkt_pts = AV_NOPTS_VALUE;

                    ret = avcodec_decode_video2(ist->st->codec,

                                                decoded_frame, &got_output, &avpkt);

                    quality = same_quant ? decoded_frame->quality : 0;

                    if (ret < 0)

                        goto fail;

                    if (!got_output) {

                        /* no picture yet */

                        av_freep(&decoded_frame);

                        goto discard_packet;

                    }

                    ist->next_pts = ist->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,

                                                                 decoded_frame->pkt_dts);

                    if (ist->st->codec->time_base.num != 0) {

                        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                        ist->next_pts += ((int64_t)AV_TIME_BASE *

                                          ist->st->codec->time_base.num * ticks) /

                            ist->st->codec->time_base.den;

                    }

                    avpkt.size = 0;

                    buffer_to_free = NULL;

                    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

                    break;

            case AVMEDIA_TYPE_SUBTITLE:

                ret = avcodec_decode_subtitle2(ist->st->codec,

                                               &subtitle, &got_output, &avpkt);

                if (ret < 0)

                    return ret;

                if (!got_output) {

                    goto discard_packet;

                }

                subtitle_to_free = &subtitle;

                avpkt.size = 0;

                break;

            default:

                return -1;

            }

        } else {

            switch(ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /

                    ist->st->codec->sample_rate;

                break;

            case AVMEDIA_TYPE_VIDEO:

                if (ist->st->codec->time_base.num != 0) {

                    int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                    ist->next_pts += ((int64_t)AV_TIME_BASE *

                                      ist->st->codec->time_base.num * ticks) /

                        ist->st->codec->time_base.den;

                }

                break;

            }

            avpkt.size = 0;

        }

        // preprocess audio (volume)

        if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (audio_volume != 256) {

                switch (ist->st->codec->sample_fmt) {

                case AV_SAMPLE_FMT_U8:

                {

                    uint8_t *volp = samples;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;

                        *volp++ = av_clip_uint8(v);

                    }

                    break;

                }

                case AV_SAMPLE_FMT_S16:

                {

                short *volp;

                volp = samples;

                for(i=0;i<(decoded_data_size / sizeof(short));i++) {

                    int v = ((*volp) * audio_volume + 128) >> 8;

                    *volp++ = av_clip_int16(v);

                }

                break;

                }

                case AV_SAMPLE_FMT_S32:

                {

                    int32_t *volp = samples;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);

                        *volp++ = av_clipl_int32(v);

                    }

                    break;

                }

                case AV_SAMPLE_FMT_FLT:

                {

                    float *volp = samples;

                    float scale = audio_volume / 256.f;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        *volp++ *= scale;

                    }

                    break;

                }

                case AV_SAMPLE_FMT_DBL:

                {

                    double *volp = samples;

                    double scale = audio_volume / 256.;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        *volp++ *= scale;

                    }

                    break;

                }

                default:

                    av_log(NULL, AV_LOG_FATAL,

                           "Audio volume adjustment on sample format %s is not supported.\n",

                           av_get_sample_fmt_name(ist->st->codec->sample_fmt));

                    exit_program(1);

                }

            }

        }

        /* frame rate emulation */

        if (input_files[ist->file_index].rate_emu) {

            int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);

            int64_t now = av_gettime() - ist->start;

            if (pts > now)

                usleep(pts - now);

        }

        /* if output time reached then transcode raw format,

           encode packets and output them */

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

            OutputFile *of = &output_files[ost_table[i].file_index];

            int frame_size;

            ost = &ost_table[i];

            if (ost->source_index != ist_index)

                continue;

            if (of->start_time && ist->pts < of->start_time)

                continue;

            if (of->recording_time != INT64_MAX &&

                av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,

                              (AVRational){1, 1000000}) >= 0) {

                ost->is_past_recording_time = 1;

                continue;

            }

#if CONFIG_AVFILTER

            if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

                ost->input_video_filter) {

                AVRational sar;

                if (ist->st->sample_aspect_ratio.num)

                    sar = ist->st->sample_aspect_ratio;

                else

                    sar = ist->st->codec->sample_aspect_ratio;

                av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, ist->pts, sar);

                if (!(filtered_frame = avcodec_alloc_frame())) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

            frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||

                !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);

            while (frame_available) {

                AVRational ist_pts_tb;

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter)

                    get_filtered_video_frame(ost->output_video_filter, filtered_frame, &ost->picref, &ist_pts_tb);

                if (ost->picref)

                    ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

#else

                filtered_frame = decoded_frame;

#endif

                os = output_files[ost->file_index].ctx;

                /* set the input output pts pairs */

                //ost->sync_ipts = (double)(ist->pts + input_files[ist->file_index].ts_offset - start_time)/ AV_TIME_BASE;

                if (ost->encoding_needed) {

                    av_assert0(ist->decoding_needed);

                    switch(ost->st->codec->codec_type) {

                    case AVMEDIA_TYPE_AUDIO:

                        do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);

                        break;

                    case AVMEDIA_TYPE_VIDEO:

#if CONFIG_AVFILTER

                        if (ost->picref->video && !ost->frame_aspect_ratio)

                            ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;

#endif

                        do_video_out(os, ost, ist, filtered_frame, &frame_size,

                                     same_quant ? quality : ost->st->codec->global_quality);

                        if (vstats_filename && frame_size)

                            do_video_stats(os, ost, frame_size);

                        break;

                    case AVMEDIA_TYPE_SUBTITLE:

                        do_subtitle_out(os, ost, ist, &subtitle,

                                        pkt->pts);

                        break;

                    default:

                        abort();

                    }

                } else {

                    AVPacket opkt;

                    int64_t ost_tb_start_time= av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);

                    av_init_packet(&opkt);

                    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)

#if !CONFIG_AVFILTER

                        continue;

#else

                        goto cont;

#endif

                    /* no reencoding needed : output the packet directly */

                    /* force the input stream PTS */

                    if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

                        audio_size += data_size;

                    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

                        video_size += data_size;

                        ost->sync_opts++;

                    }

                    opkt.stream_index= ost->index;

                    if(pkt->pts != AV_NOPTS_VALUE)

                        opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;

                    else

                        opkt.pts= AV_NOPTS_VALUE;

                    if (pkt->dts == AV_NOPTS_VALUE)

                        opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);

                    else

                        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);

                    opkt.dts -= ost_tb_start_time;

                    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);

                    opkt.flags= pkt->flags;

                    //FIXME remove the following 2 lines they shall be replaced by the bitstream filters

                    if(   ost->st->codec->codec_id != CODEC_ID_H264

                       && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO

                       && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO

                       ) {

                        if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))

                            opkt.destruct= av_destruct_packet;

                    } else {

                        opkt.data = data_buf;

                        opkt.size = data_size;

                    }

                    write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);

                    ost->st->codec->frame_number++;

                    ost->frame_number++;

                    av_free_packet(&opkt);

                }

#if CONFIG_AVFILTER

                cont:

                frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&

                                   ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);

                if (ost->picref)

                    avfilter_unref_buffer(ost->picref);

            }

            av_freep(&filtered_frame);

#endif

            }

fail:

        av_free(buffer_to_free);

        /* XXX: allocate the subtitles in the codec ? */

        if (subtitle_to_free) {

            avsubtitle_free(subtitle_to_free);

            subtitle_to_free = NULL;

        }

        av_freep(&decoded_frame);

        if (ret < 0)

            return ret;

    }

 discard_packet:

    return 0;

}


void mime_field_value_set_uint ( HdrHeap * heap , MIMEHdrImpl * mh , MIMEField * field , uint32_t value ) {
 char buf [ 16 ] ;
 int len = mime_format_uint ( buf , value , sizeof ( buf ) ) ;
 mime_field_value_set ( heap , mh , field , buf , len , true ) ;
 }


DECLAREContigPutFunc(putRGBcontig16bittile)
{
	int samplesperpixel = img->samplesperpixel;
	uint16 *wp = (uint16 *)pp;
	(void) y;
	fromskew *= samplesperpixel;
	for( ; h > 0; --h) {
		for (x = w; x > 0; --x) {
			*cp++ = PACK(img->Bitdepth16To8[wp[0]],
			    img->Bitdepth16To8[wp[1]],
			    img->Bitdepth16To8[wp[2]]);
			wp += samplesperpixel;
		}
		cp += toskew;
		wp += fromskew;
	}
}


static void udp_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb)
{
	struct dst_entry *dst = skb_dst(skb);

	dst_hold(dst);
	sk->sk_rx_dst = dst;
}


unsigned long long Chapters::Atom::GetUID() const
const char* SegmentInfo::GetWritingAppAsUTF8() const {
  return m_pWritingAppAsUTF8;
 }


static int update_offset(RTMPContext *rt, int size)

{

    int old_flv_size;

    // generate packet header and put data into buffer for FLV demuxer

    if (rt->flv_off < rt->flv_size) {

        // There is old unread data in the buffer, thus append at the end

        old_flv_size  = rt->flv_size;

        rt->flv_size += size + 15;

    } else {

        // All data has been read, write the new data at the start of the buffer

        old_flv_size = 0;

        rt->flv_size = size + 15;

        rt->flv_off  = 0;

    }

    return old_flv_size;

}


void AuthenticatorSheetModelBase::OnCancel() {
  if (dialog_model())
    dialog_model()->Cancel();
}


int flush_blocks ( MI_CHECK * param , KEY_CACHE * key_cache , File file ) {
 if ( flush_key_blocks ( key_cache , file , FLUSH_RELEASE ) ) {
 mi_check_print_error ( param , "%d when trying to write bufferts" , my_errno ) ;
 return ( 1 ) ;
 }
 if ( ! param -> using_global_keycache ) end_key_cache ( key_cache , 1 ) ;
 return 0 ;
 }


static uint64_t cmd646_cmd_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

    CMD646BAR *cmd646bar = opaque;

    if (addr != 2 || size != 1) {

        return ((uint64_t)1 << (size * 8)) - 1;

    }

    return ide_status_read(cmd646bar->bus, addr + 2);

}


 void CachingPermutedEntropyProvider::RegisterPrefs(
     PrefRegistrySimple* registry) {
  registry->RegisterStringPref(
      chrome_variations::prefs::kVariationsPermutedEntropyCache, std::string());
 }


static int php_zip_parse_options(zval *options, long *remove_all_path,
	char **remove_path, int *remove_path_len, char **add_path, int *add_path_len TSRMLS_DC) /* {{{ */
{
	zval **option;
	if (zend_hash_find(HASH_OF(options), "remove_all_path", sizeof("remove_all_path"), (void **)&option) == SUCCESS) {
		long opt;
		if (Z_TYPE_PP(option) != IS_LONG) {
			zval tmp = **option;
			zval_copy_ctor(&tmp);
			convert_to_long(&tmp);
			opt = Z_LVAL(tmp);
		} else {
			opt = Z_LVAL_PP(option);
		}
		*remove_all_path = opt;
	}

	/* If I add more options, it would make sense to create a nice static struct and loop over it. */
	if (zend_hash_find(HASH_OF(options), "remove_path", sizeof("remove_path"), (void **)&option) == SUCCESS) {
		if (Z_TYPE_PP(option) != IS_STRING) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "remove_path option expected to be a string");
			return -1;
		}

		if (Z_STRLEN_PP(option) < 1) {
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Empty string given as remove_path option");
			return -1;
		}

		if (Z_STRLEN_PP(option) >= MAXPATHLEN) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "remove_path string is too long (max: %i, %i given)",
						MAXPATHLEN - 1, Z_STRLEN_PP(option));
			return -1;
		}
		*remove_path_len = Z_STRLEN_PP(option);
		*remove_path = Z_STRVAL_PP(option);
	}

	if (zend_hash_find(HASH_OF(options), "add_path", sizeof("add_path"), (void **)&option) == SUCCESS) {
		if (Z_TYPE_PP(option) != IS_STRING) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_path option expected to be a string");
			return -1;
		}

		if (Z_STRLEN_PP(option) < 1) {
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Empty string given as the add_path option");
			return -1;
		}

		if (Z_STRLEN_PP(option) >= MAXPATHLEN) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_path string too long (max: %i, %i given)",
						MAXPATHLEN - 1, Z_STRLEN_PP(option));
			return -1;
		}
		*add_path_len = Z_STRLEN_PP(option);
		*add_path = Z_STRVAL_PP(option);
	}
	return 1;
}
/* }}} */


void WebGL2RenderingContextBase::RemoveBoundBuffer(WebGLBuffer* buffer) {
  if (bound_copy_read_buffer_ == buffer)
    bound_copy_read_buffer_ = nullptr;
  if (bound_copy_write_buffer_ == buffer)
    bound_copy_write_buffer_ = nullptr;
  if (bound_pixel_pack_buffer_ == buffer)
    bound_pixel_pack_buffer_ = nullptr;
  if (bound_pixel_unpack_buffer_ == buffer)
    bound_pixel_unpack_buffer_ = nullptr;
  if (bound_transform_feedback_buffer_ == buffer)
    bound_transform_feedback_buffer_ = nullptr;
  if (bound_uniform_buffer_ == buffer)
    bound_uniform_buffer_ = nullptr;

  transform_feedback_binding_->UnbindBuffer(buffer);

  WebGLRenderingContextBase::RemoveBoundBuffer(buffer);
}


static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
			      int alen, int flags)
{
	struct sock *sk = sock->sk;
	struct net *net = sock_net(sk);
	struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
	struct sock *other;
	unsigned int hash;
	int err;

	if (addr->sa_family != AF_UNSPEC) {
		err = unix_mkname(sunaddr, alen, &hash);
		if (err < 0)
			goto out;
		alen = err;

		if (test_bit(SOCK_PASSCRED, &sock->flags) &&
		    !unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
			goto out;

restart:
		other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
		if (!other)
			goto out;

		unix_state_double_lock(sk, other);

		/* Apparently VFS overslept socket death. Retry. */
		if (sock_flag(other, SOCK_DEAD)) {
			unix_state_double_unlock(sk, other);
			sock_put(other);
			goto restart;
		}

		err = -EPERM;
		if (!unix_may_send(sk, other))
			goto out_unlock;

		err = security_unix_may_send(sk->sk_socket, other->sk_socket);
		if (err)
			goto out_unlock;

	} else {
		/*
		 *	1003.1g breaking connected state with AF_UNSPEC
		 */
		other = NULL;
		unix_state_double_lock(sk, other);
	}

	/*
	 * If it was connected, reconnect.
	 */
	if (unix_peer(sk)) {
		struct sock *old_peer = unix_peer(sk);
		unix_peer(sk) = other;
		unix_state_double_unlock(sk, other);

		if (other != old_peer)
			unix_dgram_disconnected(sk, old_peer);
		sock_put(old_peer);
	} else {
		unix_peer(sk) = other;
		unix_state_double_unlock(sk, other);
	}
	return 0;

out_unlock:
	unix_state_double_unlock(sk, other);
	sock_put(other);
out:
	return err;
}


const char* AsyncSSLSocket::getSSLServerNameNoThrow() const {
  if (clientHelloInfo_ && !clientHelloInfo_->clientHelloSNIHostname_.empty()) {
    return clientHelloInfo_->clientHelloSNIHostname_.c_str();
  }
  return getSSLServerNameFromSSL(ssl_.get());
}


static uc_err mem_map(uc_engine *uc, uint64_t address, size_t size,
                      uint32_t perms, MemoryRegion *block)
{
    MemoryRegion **regions;
    int pos;

    if (block == NULL) {
        return UC_ERR_NOMEM;
    }

    if ((uc->mapped_block_count & (MEM_BLOCK_INCR - 1)) == 0) { // time to grow
        regions = (MemoryRegion **)g_realloc(
            uc->mapped_blocks,
            sizeof(MemoryRegion *) * (uc->mapped_block_count + MEM_BLOCK_INCR));
        if (regions == NULL) {
            return UC_ERR_NOMEM;
        }
        uc->mapped_blocks = regions;
    }

    pos = bsearch_mapped_blocks(uc, block->addr);

    // shift the array right to give space for the new pointer
    memmove(&uc->mapped_blocks[pos + 1], &uc->mapped_blocks[pos],
            sizeof(MemoryRegion *) * (uc->mapped_block_count - pos));

    uc->mapped_blocks[pos] = block;
    uc->mapped_block_count++;

    return UC_ERR_OK;
}


acpi_object_type acpi_ns_get_type(struct acpi_namespace_node * node)
{
	ACPI_FUNCTION_TRACE(ns_get_type);

	if (!node) {
		ACPI_WARNING((AE_INFO, "Null Node parameter"));
		return_UINT8(ACPI_TYPE_ANY);
	}

	return_UINT8(node->type);
}


int xps_count_font_encodings ( fz_font * font ) {
 FT_Face face = font -> ft_face ;
 return face -> num_charmaps ;
 }


mainloop_gio_callback(GIOChannel *gio, GIOCondition condition, gpointer data)
{
    gboolean keep = TRUE;
    mainloop_io_t *client = data;

    if(condition & G_IO_IN) {
        if(client->ipc) {
            long rc = 0;
            int max = 10;
            do {
                rc = crm_ipc_read(client->ipc);
                if(rc <= 0) {
                    crm_trace("Message acquisition from %s[%p] failed: %s (%ld)",
                              client->name, client, pcmk_strerror(rc), rc);

                } else if(client->dispatch_fn_ipc) {
                    const char *buffer = crm_ipc_buffer(client->ipc);
                    crm_trace("New message from %s[%p] = %d", client->name, client, rc, condition);
                    if(client->dispatch_fn_ipc(buffer, rc, client->userdata) < 0) {
                        crm_trace("Connection to %s no longer required", client->name);
                        keep = FALSE;
                    }
                }

            } while(keep && rc > 0 && --max > 0);

        } else {
            crm_trace("New message from %s[%p]", client->name, client);
            if(client->dispatch_fn_io) {
                if(client->dispatch_fn_io(client->userdata) < 0) {
                    crm_trace("Connection to %s no longer required", client->name);
                    keep = FALSE;
                }
            }
        }
    }

    if(client->ipc && crm_ipc_connected(client->ipc) == FALSE) {
        crm_err("Connection to %s[%p] closed (I/O condition=%d)", client->name, client, condition);
        keep = FALSE;

    } else if(condition & (G_IO_HUP|G_IO_NVAL|G_IO_ERR)) {
        crm_trace("The connection %s[%p] has been closed (I/O condition=%d, refcount=%d)",
                  client->name, client, condition, mainloop_gio_refcount(client));
        keep = FALSE;

    } else if((condition & G_IO_IN) == 0) {
        /*
          #define 	GLIB_SYSDEF_POLLIN     =1
          #define 	GLIB_SYSDEF_POLLPRI    =2
          #define 	GLIB_SYSDEF_POLLOUT    =4
          #define 	GLIB_SYSDEF_POLLERR    =8
          #define 	GLIB_SYSDEF_POLLHUP    =16
          #define 	GLIB_SYSDEF_POLLNVAL   =32

          typedef enum
          {
            G_IO_IN	GLIB_SYSDEF_POLLIN,
            G_IO_OUT	GLIB_SYSDEF_POLLOUT,
            G_IO_PRI	GLIB_SYSDEF_POLLPRI,
            G_IO_ERR	GLIB_SYSDEF_POLLERR,
            G_IO_HUP	GLIB_SYSDEF_POLLHUP,
            G_IO_NVAL	GLIB_SYSDEF_POLLNVAL
          } GIOCondition;

          A bitwise combination representing a condition to watch for on an event source.

          G_IO_IN	There is data to read.
          G_IO_OUT	Data can be written (without blocking).
          G_IO_PRI	There is urgent data to read.
          G_IO_ERR	Error condition.
          G_IO_HUP	Hung up (the connection has been broken, usually for pipes and sockets).
          G_IO_NVAL	Invalid request. The file descriptor is not open.
        */
        crm_err("Strange condition: %d", condition);
    }

    /* keep == FALSE results in mainloop_gio_destroy() being called
     * just before the source is removed from mainloop
     */
    return keep;
}


int ssl3_check_finished(SSL *s)
	{
	int ok;
	long n;
	/* If we have no ticket it cannot be a resumed session. */
	if (!s->session->tlsext_tick)
		return 1;
	/* this function is called when we really expect a Certificate
	 * message, so permit appropriate message length */
	n=s->method->ssl_get_message(s,
		SSL3_ST_CR_CERT_A,
		SSL3_ST_CR_CERT_B,
		-1,
		s->max_cert_list,
		&ok);
	if (!ok) return((int)n);
	s->s3->tmp.reuse_message = 1;
	if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
		|| (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
		return 2;

	return 1;
	}


istr_set_get_as_list (GHashTable *table)
{
    GList *list;

    list = NULL;
    g_hash_table_foreach (table, add_istr_to_list, &list);
    return list;
}


static int php_zlib_decode(const char *in_buf, size_t in_len, char **out_buf, size_t *out_len, int encoding, size_t max_len TSRMLS_DC)
{
	int status = Z_DATA_ERROR;
	z_stream Z;

	memset(&Z, 0, sizeof(z_stream));
	Z.zalloc = php_zlib_alloc;
	Z.zfree = php_zlib_free;

	if (in_len) {
retry_raw_inflate:
		status = inflateInit2(&Z, encoding);
		if (Z_OK == status) {
			Z.next_in = (Bytef *) in_buf;
			Z.avail_in = in_len + 1; /* NOTE: data must be zero terminated */

			switch (status = php_zlib_inflate_rounds(&Z, max_len, out_buf, out_len)) {
				case Z_STREAM_END:
					inflateEnd(&Z);
					return SUCCESS;

				case Z_DATA_ERROR:
					/* raw deflated data? */
					if (PHP_ZLIB_ENCODING_ANY == encoding) {
						inflateEnd(&Z);
						encoding = PHP_ZLIB_ENCODING_RAW;
						goto retry_raw_inflate;
					}
			}
			inflateEnd(&Z);
		}
	}

	*out_buf = NULL;
	*out_len = 0;

	php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", zError(status));
	return FAILURE;
}


long video_ioctl2(struct file *file,
	       unsigned int cmd, unsigned long arg)
{
	return video_usercopy(file, cmd, arg, __video_do_ioctl);
}


void CheckDownloadComplete(CanDownloadCallback can_download_cb, bool allow) {
  std::move(can_download_cb).Run(true, allow);
}


  void modifyRequirement(const std::string& yaml) {
    TestUtility::loadFromYaml(yaml, *proto_config_.mutable_rules(0)->mutable_requires());
  }


unsigned long iov_pages(const struct iovec *iov, int offset,
			unsigned long nr_segs)
{
	unsigned long seg, base;
	int pages = 0, len, size;

	while (nr_segs && (offset >= iov->iov_len)) {
		offset -= iov->iov_len;
		++iov;
		--nr_segs;
	}

	for (seg = 0; seg < nr_segs; seg++) {
		base = (unsigned long)iov[seg].iov_base + offset;
		len = iov[seg].iov_len - offset;
		size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
		pages += size;
		offset = 0;
	}

	return pages;
}


void LoginDisplayHostWebUI::TryToPlayOobeStartupSound() {
  if (is_voice_interaction_oobe_)
    return;

  if (oobe_startup_sound_played_ || login_prompt_visible_time_.is_null() ||
      !CrasAudioHandler::Get()->GetPrimaryActiveOutputNode()) {
    return;
  }

  oobe_startup_sound_played_ = true;

  if (base::TimeTicks::Now() - login_prompt_visible_time_ >
      base::TimeDelta::FromMilliseconds(kStartupSoundMaxDelayMs)) {
    return;
  }

  AccessibilityManager::Get()->PlayEarcon(SOUND_STARTUP,
                                          PlaySoundOption::ALWAYS);
}


GF_Err strk_box_size(GF_Box *s)
{
	return GF_OK;


static int mxf_parse_handle_essence(MXFContext *mxf)
{
    AVIOContext *pb = mxf->fc->pb;
    int64_t ret;

    if (mxf->parsing_backward) {
        return mxf_seek_to_previous_partition(mxf);
    } else {
        if (!mxf->footer_partition) {
            av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n");
            return 0;
        }

        av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n");

        /* remember where we were so we don't end up seeking further back than this */
        mxf->last_forward_tell = avio_tell(pb);

        if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
            av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n");
            return -1;
        }

        /* seek to FooterPartition and parse backward */
        if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
            av_log(mxf->fc, AV_LOG_ERROR,
                   "failed to seek to FooterPartition @ 0x%" PRIx64
                   " (%"PRId64") - partial file?\n",
                   mxf->run_in + mxf->footer_partition, ret);
            return ret;
        }

        mxf->current_partition = NULL;
        mxf->parsing_backward = 1;
    }

    return 1;
}


static void rtmpt_debug ( const char * fmt , ... ) {
 ( void ) fmt ;
 }


  virtual SafeBrowsingBlockingPage* CreateSafeBrowsingPage(
      SafeBrowsingService* service,
      TabContents* tab_contents,
      const SafeBrowsingBlockingPage::UnsafeResourceList& unsafe_resources) {
    return new TestSafeBrowsingBlockingPage(service, tab_contents,
                                            unsafe_resources);
  }


bool RenderFrameImpl::runModalPromptDialog(
    const blink::WebString& message,
    const blink::WebString& default_value,
    blink::WebString* actual_value) {
  base::string16 result;
  bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
                                 message,
                                 default_value,
                                 frame_->document().url(),
                                 &result);
  if (ok)
    actual_value->assign(result);
  return ok;
}


bool aio_poll(AioContext *ctx, bool blocking)

{

    AioHandler *node;

    int i, ret;

    bool progress;

    int64_t timeout;

    aio_context_acquire(ctx);

    progress = false;

    /* aio_notify can avoid the expensive event_notifier_set if

     * everything (file descriptors, bottom halves, timers) will

     * be re-evaluated before the next blocking poll().  This is

     * already true when aio_poll is called with blocking == false;

     * if blocking == true, it is only true after poll() returns,

     * so disable the optimization now.

     */

    if (blocking) {

        atomic_add(&ctx->notify_me, 2);

    }

    ctx->walking_handlers++;

    assert(npfd == 0);

    /* fill pollfds */

    if (!aio_epoll_enabled(ctx)) {

        QLIST_FOREACH(node, &ctx->aio_handlers, node) {

            if (!node->deleted && node->pfd.events

                && aio_node_check(ctx, node->is_external)) {

                add_pollfd(node);

            }

        }

    }

    timeout = blocking ? aio_compute_timeout(ctx) : 0;

    /* wait until next event */

    if (timeout) {

        aio_context_release(ctx);

    }

    if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) {

        AioHandler epoll_handler;

        epoll_handler.pfd.fd = ctx->epollfd;

        epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR;

        npfd = 0;

        add_pollfd(&epoll_handler);

        ret = aio_epoll(ctx, pollfds, npfd, timeout);

    } else  {

        ret = qemu_poll_ns(pollfds, npfd, timeout);

    }

    if (blocking) {

        atomic_sub(&ctx->notify_me, 2);

    }

    if (timeout) {

        aio_context_acquire(ctx);

    }

    aio_notify_accept(ctx);

    /* if we have any readable fds, dispatch event */

    if (ret > 0) {

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

            nodes[i]->pfd.revents = pollfds[i].revents;

        }

    }

    npfd = 0;

    ctx->walking_handlers--;

    /* Run dispatch even if there were no readable fds to run timers */

    if (aio_dispatch(ctx, ret > 0)) {

        progress = true;

    }

    aio_context_release(ctx);

    return progress;

}


static struct branch * new_branch ( const char * name ) {
 unsigned int hc = hc_str ( name , strlen ( name ) ) % branch_table_sz ;
 struct branch * b = lookup_branch ( name ) ;
 if ( b ) die ( "Invalid attempt to create duplicate branch: %s" , name ) ;
 if ( check_refname_format ( name , REFNAME_ALLOW_ONELEVEL ) ) die ( "Branch name doesn't conform to GIT standards: %s" , name ) ;
 b = pool_calloc ( 1 , sizeof ( struct branch ) ) ;
 b -> name = pool_strdup ( name ) ;
 b -> table_next_branch = branch_table [ hc ] ;
 b -> branch_tree . versions [ 0 ] . mode = S_IFDIR ;
 b -> branch_tree . versions [ 1 ] . mode = S_IFDIR ;
 b -> num_notes = 0 ;
 b -> active = 0 ;
 b -> pack_id = MAX_PACK_ID ;
 branch_table [ hc ] = b ;
 branch_count ++ ;
 return b ;
 }


yang_check_must(struct lys_module *module, struct lys_restr *must, uint size, struct unres_schema *unres)
{
    uint i;

    for (i = 0; i < size; ++i) {
        if (yang_check_ext_instance(module, &must[i].ext, must[i].ext_size, &must[i], unres)) {
            return EXIT_FAILURE;
        }
    }
    return EXIT_SUCCESS;
}


static void* lookupOpenGLFunctionAddress(const char* functionName, bool* success = 0)
{
    if (success && !*success)
        return 0;

    void* target = getProcAddress(functionName);
    if (target)
        return target;

    String fullFunctionName(functionName);
    fullFunctionName.append("ARB");
    target = getProcAddress(fullFunctionName.utf8().data());
    if (target)
        return target;

    fullFunctionName = functionName;
    fullFunctionName.append("EXT");
    target = getProcAddress(fullFunctionName.utf8().data());

#if defined(GL_ES_VERSION_2_0)
     fullFunctionName = functionName;
     fullFunctionName.append("ANGLE");
     target = getProcAddress(fullFunctionName.utf8().data());
    if (target)
        return target;

     fullFunctionName = functionName;
     fullFunctionName.append("APPLE");
    target = getProcAddress(fullFunctionName.utf8().data());
#endif

    if (!target && success)
        *success = false;

    return target;
}


static void m68020_cpu_initfn(Object *obj)

{

    M68kCPU *cpu = M68K_CPU(obj);

    CPUM68KState *env = &cpu->env;

    m68k_set_feature(env, M68K_FEATURE_M68000);

    m68k_set_feature(env, M68K_FEATURE_USP);

    m68k_set_feature(env, M68K_FEATURE_WORD_INDEX);

    m68k_set_feature(env, M68K_FEATURE_QUAD_MULDIV);

    m68k_set_feature(env, M68K_FEATURE_BRAL);

    m68k_set_feature(env, M68K_FEATURE_BCCL);

    m68k_set_feature(env, M68K_FEATURE_BITFIELD);

    m68k_set_feature(env, M68K_FEATURE_EXT_FULL);

    m68k_set_feature(env, M68K_FEATURE_SCALED_INDEX);

    m68k_set_feature(env, M68K_FEATURE_LONG_MULDIV);

    m68k_set_feature(env, M68K_FEATURE_FPU);

    m68k_set_feature(env, M68K_FEATURE_CAS);

    m68k_set_feature(env, M68K_FEATURE_BKPT);

    m68k_set_feature(env, M68K_FEATURE_RTD);

}


static int __register_ftrace_function(struct ftrace_ops *ops)
{
	if (unlikely(ftrace_disabled))
		return -ENODEV;

	if (FTRACE_WARN_ON(ops == &global_ops))
		return -EINVAL;

	if (WARN_ON(ops->flags & FTRACE_OPS_FL_ENABLED))
		return -EBUSY;

	/* We don't support both control and global flags set. */
	if ((ops->flags & FL_GLOBAL_CONTROL_MASK) == FL_GLOBAL_CONTROL_MASK)
		return -EINVAL;

#ifndef CONFIG_DYNAMIC_FTRACE_WITH_REGS
	/*
	 * If the ftrace_ops specifies SAVE_REGS, then it only can be used
	 * if the arch supports it, or SAVE_REGS_IF_SUPPORTED is also set.
	 * Setting SAVE_REGS_IF_SUPPORTED makes SAVE_REGS irrelevant.
	 */
	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS &&
	    !(ops->flags & FTRACE_OPS_FL_SAVE_REGS_IF_SUPPORTED))
		return -EINVAL;

	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS_IF_SUPPORTED)
		ops->flags |= FTRACE_OPS_FL_SAVE_REGS;
#endif

	if (!core_kernel_data((unsigned long)ops))
		ops->flags |= FTRACE_OPS_FL_DYNAMIC;

	if (ops->flags & FTRACE_OPS_FL_GLOBAL) {
		add_ftrace_list_ops(&ftrace_global_list, &global_ops, ops);
		ops->flags |= FTRACE_OPS_FL_ENABLED;
	} else if (ops->flags & FTRACE_OPS_FL_CONTROL) {
		if (control_ops_alloc(ops))
			return -ENOMEM;
		add_ftrace_list_ops(&ftrace_control_list, &control_ops, ops);
	} else
		add_ftrace_ops(&ftrace_ops_list, ops);

	if (ftrace_enabled)
		update_ftrace_function();

	return 0;
}


static bool nfs_readdir_page_needs_filling(struct page *page)
{
	struct nfs_cache_array *array;
	bool ret;

	array = kmap_atomic(page);
	ret = !nfs_readdir_array_is_full(array);
	kunmap_atomic(array);
	return ret;
}


char* Jsi_ValueGetStringLen(Jsi_Interp *interp, Jsi_Value *pv, int *lenPtr)
{
    if (!pv)
        return NULL;
    Jsi_String *s = jsi_ValueString(pv);
    if (!s)
        return NULL;
    if (lenPtr)
        *lenPtr = (s->len<0 ? (int)Jsi_Strlen(s->str) : s->len);
    return s->str;
}


int qemuAgentGetFSInfo ( qemuAgentPtr mon , virDomainFSInfoPtr * * info , virDomainDefPtr vmdef ) {
 size_t i , j , k ;
 int ret = - 1 ;
 ssize_t ndata = 0 , ndisk ;
 char * * alias ;
 virJSONValuePtr cmd ;
 virJSONValuePtr reply = NULL ;
 virJSONValuePtr data ;
 virDomainFSInfoPtr * info_ret = NULL ;
 virPCIDeviceAddress pci_address ;
 cmd = qemuAgentMakeCommand ( "guest-get-fsinfo" , NULL ) ;
 if ( ! cmd ) return ret ;
 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-fsinfo reply was missing return data" ) ) ;
 goto cleanup ;
 }
 if ( data -> type != VIR_JSON_TYPE_ARRAY ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "guest-get-fsinfo return information was not " "an array" ) ) ;
 goto cleanup ;
 }
 ndata = virJSONValueArraySize ( data ) ;
 if ( ! ndata ) {
 ret = 0 ;
 * info = NULL ;
 goto cleanup ;
 }
 if ( VIR_ALLOC_N ( info_ret , ndata ) < 0 ) goto cleanup ;
 for ( i = 0 ;
 i < ndata ;
 i ++ ) {
 virJSONValuePtr entry = virJSONValueArrayGet ( data , ndata - 1 - i ) ;
 if ( ! entry ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "array element '%zd' of '%zd' missing in " "guest-get-fsinfo return data" ) , i , ndata ) ;
 goto cleanup ;
 }
 if ( VIR_ALLOC ( info_ret [ i ] ) < 0 ) goto cleanup ;
 if ( VIR_STRDUP ( info_ret [ i ] -> mountpoint , virJSONValueObjectGetString ( entry , "mountpoint" ) ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'mountpoint' missing in reply of " "guest-get-fsinfo" ) ) ;
 goto cleanup ;
 }
 if ( VIR_STRDUP ( info_ret [ i ] -> name , virJSONValueObjectGetString ( entry , "name" ) ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'name' missing in reply of guest-get-fsinfo" ) ) ;
 goto cleanup ;
 }
 if ( VIR_STRDUP ( info_ret [ i ] -> fstype , virJSONValueObjectGetString ( entry , "type" ) ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'type' missing in reply of guest-get-fsinfo" ) ) ;
 goto cleanup ;
 }
 if ( ! ( entry = virJSONValueObjectGet ( entry , "disk" ) ) ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'disk' missing in reply of guest-get-fsinfo" ) ) ;
 goto cleanup ;
 }
 if ( entry -> type != VIR_JSON_TYPE_ARRAY ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "guest-get-fsinfo 'disk' data was not an array" ) ) ;
 goto cleanup ;
 }
 ndisk = virJSONValueArraySize ( entry ) ;
 if ( ! ndisk ) continue ;
 if ( VIR_ALLOC_N ( info_ret [ i ] -> devAlias , ndisk ) < 0 ) goto cleanup ;
 alias = info_ret [ i ] -> devAlias ;
 info_ret [ i ] -> ndevAlias = 0 ;
 for ( j = 0 ;
 j < ndisk ;
 j ++ ) {
 virJSONValuePtr disk = virJSONValueArrayGet ( entry , j ) ;
 virJSONValuePtr pci ;
 int diskaddr [ 3 ] , pciaddr [ 4 ] ;
 const char * diskaddr_comp [ ] = {
 "bus" , "target" , "unit" }
 ;
 const char * pciaddr_comp [ ] = {
 "domain" , "bus" , "slot" , "function" }
 ;
 virDomainDiskDefPtr diskDef ;
 if ( ! disk ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "array element '%zd' of '%zd' missing in " "guest-get-fsinfo 'disk' data" ) , j , ndisk ) ;
 goto cleanup ;
 }
 if ( ! ( pci = virJSONValueObjectGet ( disk , "pci-controller" ) ) ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "'pci-controller' missing in guest-get-fsinfo " "'disk' data" ) ) ;
 goto cleanup ;
 }
 for ( k = 0 ;
 k < 3 ;
 k ++ ) {
 if ( virJSONValueObjectGetNumberInt ( disk , diskaddr_comp [ k ] , & diskaddr [ k ] ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "'%s' missing in guest-get-fsinfo " "'disk' data" ) , diskaddr_comp [ k ] ) ;
 goto cleanup ;
 }
 }
 for ( k = 0 ;
 k < 4 ;
 k ++ ) {
 if ( virJSONValueObjectGetNumberInt ( pci , pciaddr_comp [ k ] , & pciaddr [ k ] ) < 0 ) {
 virReportError ( VIR_ERR_INTERNAL_ERROR , _ ( "'%s' missing in guest-get-fsinfo " "'pci-address' data" ) , pciaddr_comp [ k ] ) ;
 goto cleanup ;
 }
 }
 pci_address . domain = pciaddr [ 0 ] ;
 pci_address . bus = pciaddr [ 1 ] ;
 pci_address . slot = pciaddr [ 2 ] ;
 pci_address . function = pciaddr [ 3 ] ;
 if ( ! ( diskDef = virDomainDiskByAddress ( vmdef , & pci_address , diskaddr [ 0 ] , diskaddr [ 1 ] , diskaddr [ 2 ] ) ) ) continue ;
 if ( VIR_STRDUP ( * alias , diskDef -> dst ) < 0 ) goto cleanup ;
 if ( * alias ) {
 alias ++ ;
 info_ret [ i ] -> ndevAlias ++ ;
 }
 }
 }
 * info = info_ret ;
 info_ret = NULL ;
 ret = ndata ;
 cleanup : if ( info_ret ) {
 for ( i = 0 ;
 i < ndata ;
 i ++ ) virDomainFSInfoFree ( info_ret [ i ] ) ;
 VIR_FREE ( info_ret ) ;
 }
 virJSONValueFree ( cmd ) ;
 virJSONValueFree ( reply ) ;
 return ret ;
 }


int ip_check_mc_rcu(struct in_device *in_dev, __be32 mc_addr, __be32 src_addr, u16 proto)
{
	struct ip_mc_list *im;
	struct ip_sf_list *psf;
	int rv = 0;

	for_each_pmc_rcu(in_dev, im) {
		if (im->multiaddr == mc_addr)
			break;
	}
	if (im && proto == IPPROTO_IGMP) {
		rv = 1;
	} else if (im) {
		if (src_addr) {
			for (psf=im->sources; psf; psf=psf->sf_next) {
				if (psf->sf_inaddr == src_addr)
					break;
			}
			if (psf)
				rv = psf->sf_count[MCAST_INCLUDE] ||
					psf->sf_count[MCAST_EXCLUDE] !=
					im->sfcount[MCAST_EXCLUDE];
			else
				rv = im->sfcount[MCAST_EXCLUDE] != 0;
		} else
			rv = 1; /* unspecified source; tentatively allow */
	}
	return rv;
}


PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiBrokerProcess(
    int render_process_id,
    const FilePath& plugin_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (filter_ && !filter_->CanLoadPlugin(render_process_id, plugin_path))
    return NULL;

  PpapiPluginProcessHost* plugin_host = FindPpapiBrokerProcess(plugin_path);
  if (plugin_host)
    return plugin_host;

  PepperPluginInfo* info = GetRegisteredPpapiPluginInfo(plugin_path);
  if (!info)
    return NULL;

  return PpapiPluginProcessHost::CreateBrokerHost(*info);
}


STATIC void
S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
			 HV *widecharmap, AV *revcharmap, U32 next_alloc,
			 U32 depth)
{
    U32 state;
    SV *sv=sv_newmortal();
    int colwidth= widecharmap ? 6 : 4;
    GET_RE_DEBUG_FLAGS_DECL;

    PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;

    /* print out the table precompression.  */
    Perl_re_indentf( aTHX_  "State :Word | Transition Data\n",
            depth+1 );
    Perl_re_indentf( aTHX_  "%s",
            depth+1, "------:-----+-----------------\n" );

    for( state=1 ; state < next_alloc ; state ++ ) {
        U16 charid;

        Perl_re_indentf( aTHX_  " %4" UVXf " :",
            depth+1, (UV)state  );
        if ( ! trie->states[ state ].wordnum ) {
            Perl_re_printf( aTHX_  "%5s| ","");
        } else {
            Perl_re_printf( aTHX_  "W%4x| ",
                trie->states[ state ].wordnum
            );
        }
        for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
	    SV ** const tmp = av_fetch( revcharmap,
                                        TRIE_LIST_ITEM(state, charid).forid, 0);
	    if ( tmp ) {
                Perl_re_printf( aTHX_  "%*s:%3X=%4" UVXf " | ",
                    colwidth,
                    pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
                              colwidth,
                              PL_colors[0], PL_colors[1],
                              (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
                              | PERL_PV_ESCAPE_FIRSTCHAR
                    ) ,
                    TRIE_LIST_ITEM(state, charid).forid,
                    (UV)TRIE_LIST_ITEM(state, charid).newstate
                );
                if (!(charid % 10))
                    Perl_re_printf( aTHX_  "\n%*s| ",
                        (int)((depth * 2) + 14), "");
            }
        }
        Perl_re_printf( aTHX_  "\n");
    }


    JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
    {
        if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
        {
            return nullptr;
        }

        if (JavascriptArray::Is(originalArray)
            && !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
            && DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
            && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
        {
            return nullptr;
        }

        Var constructor = scriptContext->GetLibrary()->GetUndefined();

        if (JavascriptOperators::IsArray(originalArray))
        {
            if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
            {
                return nullptr;
            }

            if (JavascriptOperators::IsConstructor(constructor))
            {
                ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
                if (constructorScriptContext != scriptContext)
                {
                    if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
                    {
                        constructor = scriptContext->GetLibrary()->GetUndefined();
                    }
                }
            }

            if (JavascriptOperators::IsObject(constructor))
            {
                if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
                {
                    if (pIsBuiltinArrayCtor != nullptr)
                    {
                        *pIsBuiltinArrayCtor = false;
                    }

                    return nullptr;
                }
                if (constructor == scriptContext->GetLibrary()->GetNull())
                {
                    constructor = scriptContext->GetLibrary()->GetUndefined();
                }
            }
        }

        if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
        {
            if (length > UINT_MAX)
            {
                JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
            }

            if (nullptr == pIsIntArray)
            {
                return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
            }
            else
            {
                // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
                JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
                pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
                return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
            }
        }

        if (!JavascriptOperators::IsConstructor(constructor))
        {
            JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
        }

        if (pIsBuiltinArrayCtor != nullptr)
        {
            *pIsBuiltinArrayCtor = false;
        }

        Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
        Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));

        return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
    }


static bool parseAimateMotionNode(QSvgNode *parent,
                                  const QXmlStreamAttributes &attributes,
                                  QSvgHandler *)
{
    Q_UNUSED(parent); Q_UNUSED(attributes);
    return true;
}


bool FileDescriptorSet::Add(int fd) {
  if (descriptors_.size() == MAX_DESCRIPTORS_PER_MESSAGE)
    return false;

  struct base::FileDescriptor sd;
  sd.fd = fd;
  sd.auto_close = false;
  descriptors_.push_back(sd);
  return true;
}


  explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) {
  }


xwd_loader_goto_first_frame (G_GNUC_UNUSED XwdLoader *loader)
{
}


static struct sched_group *find_busiest_group(struct lb_env *env)
{
	struct sg_lb_stats *local, *busiest;
	struct sd_lb_stats sds;

	init_sd_lb_stats(&sds);

	/*
	 * Compute the various statistics relavent for load balancing at
	 * this level.
	 */
	update_sd_lb_stats(env, &sds);

	if (sched_energy_enabled()) {
		struct root_domain *rd = env->dst_rq->rd;

		if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
			goto out_balanced;
	}

	local = &sds.local_stat;
	busiest = &sds.busiest_stat;

	/* ASYM feature bypasses nice load balance check */
	if (check_asym_packing(env, &sds))
		return sds.busiest;

	/* There is no busy sibling group to pull tasks from */
	if (!sds.busiest || busiest->sum_nr_running == 0)
		goto out_balanced;

	/* XXX broken for overlapping NUMA groups */
	sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
						/ sds.total_capacity;

	/*
	 * If the busiest group is imbalanced the below checks don't
	 * work because they assume all things are equal, which typically
	 * isn't true due to cpus_ptr constraints and the like.
	 */
	if (busiest->group_type == group_imbalanced)
		goto force_balance;

	/*
	 * When dst_cpu is idle, prevent SMP nice and/or asymmetric group
	 * capacities from resulting in underutilization due to avg_load.
	 */
	if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) &&
	    busiest->group_no_capacity)
		goto force_balance;

	/* Misfit tasks should be dealt with regardless of the avg load */
	if (busiest->group_type == group_misfit_task)
		goto force_balance;

	/*
	 * If the local group is busier than the selected busiest group
	 * don't try and pull any tasks.
	 */
	if (local->avg_load >= busiest->avg_load)
		goto out_balanced;

	/*
	 * Don't pull any tasks if this group is already above the domain
	 * average load.
	 */
	if (local->avg_load >= sds.avg_load)
		goto out_balanced;

	if (env->idle == CPU_IDLE) {
		/*
		 * This CPU is idle. If the busiest group is not overloaded
		 * and there is no imbalance between this and busiest group
		 * wrt idle CPUs, it is balanced. The imbalance becomes
		 * significant if the diff is greater than 1 otherwise we
		 * might end up to just move the imbalance on another group
		 */
		if ((busiest->group_type != group_overloaded) &&
				(local->idle_cpus <= (busiest->idle_cpus + 1)))
			goto out_balanced;
	} else {
		/*
		 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
		 * imbalance_pct to be conservative.
		 */
		if (100 * busiest->avg_load <=
				env->sd->imbalance_pct * local->avg_load)
			goto out_balanced;
	}

force_balance:
	/* Looks like there is an imbalance. Compute it */
	env->src_grp_type = busiest->group_type;
	calculate_imbalance(env, &sds);
	return env->imbalance ? sds.busiest : NULL;

out_balanced:
	env->imbalance = 0;
	return NULL;
}


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

{

    AVStream *st;

    int len, ret;

    for(;;) {

        /* select current input stream component */

        st = s->cur_st;

        if (st) {

            if (!st->parser) {

                /* no parsing needed: we just output the packet as is */

                /* raw data support */

                *pkt = s->cur_pkt;

                compute_pkt_fields(s, st, NULL, pkt);

                s->cur_st = NULL;

                return 0;

            } else if (s->cur_len > 0) {

                /* we use the MPEG semantics: the pts and dts in a

                   packet are given from the first frame beginning in

                   it */

                if (!st->got_frame) {

                    st->cur_frame_pts = s->cur_pkt.pts;

                    st->cur_frame_dts = s->cur_pkt.dts;

                    s->cur_pkt.pts = AV_NOPTS_VALUE;

                    s->cur_pkt.dts = AV_NOPTS_VALUE;

                    st->got_frame = 1;

                }

                len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size,

                                      s->cur_ptr, s->cur_len);

                /* increment read pointer */

                s->cur_ptr += len;

                s->cur_len -= len;

                /* return packet if any */

                if (pkt->size) {

                    pkt->duration = 0;

                    pkt->stream_index = st->index;

                    pkt->pts = st->cur_frame_pts;

                    pkt->dts = st->cur_frame_dts;

                    pkt->destruct = av_destruct_packet_nofree;

                    compute_pkt_fields(s, st, st->parser, pkt);

                    st->got_frame = 0;

                    return 0;

                }

            } else {

                s->cur_st = NULL;

            }

        } else {

            /* free previous packet */

            if (s->cur_st && s->cur_st->parser)

                av_free_packet(&s->cur_pkt);

            /* read next packet */

            ret = av_read_packet(s, &s->cur_pkt);

            if (ret < 0)

                return ret;

            /* convert the packet time stamp units and handle wrapping */

            s->cur_pkt.pts = convert_timestamp_units(s,

                                               &s->last_pkt_pts, &s->last_pkt_pts_frac,

                                               &s->last_pkt_stream_pts,

                                               s->cur_pkt.pts);

            s->cur_pkt.dts = convert_timestamp_units(s,

                                               &s->last_pkt_dts,  &s->last_pkt_dts_frac,

                                               &s->last_pkt_stream_dts,

                                               s->cur_pkt.dts);

#if 0

            if (s->cur_pkt.stream_index == 1) {

                if (s->cur_pkt.pts != AV_NOPTS_VALUE)

                    printf("PACKET pts=%0.3f\n",

                           (double)s->cur_pkt.pts / AV_TIME_BASE);

                if (s->cur_pkt.dts != AV_NOPTS_VALUE)

                    printf("PACKET dts=%0.3f\n",

                           (double)s->cur_pkt.dts / AV_TIME_BASE);

            }

#endif

            /* duration field */

            if (s->cur_pkt.duration != 0) {

                s->cur_pkt.duration = ((int64_t)s->cur_pkt.duration * AV_TIME_BASE * s->pts_num) /

                    s->pts_den;

            }

            st = s->streams[s->cur_pkt.stream_index];

            s->cur_st = st;

            s->cur_ptr = s->cur_pkt.data;

            s->cur_len = s->cur_pkt.size;

            if (st->need_parsing && !st->parser) {

                st->parser = av_parser_init(st->codec.codec_id);

                if (!st->parser) {

                    /* no parser available : just output the raw packets */

                    st->need_parsing = 0;

                }

            }

        }

    }

}