fep_client_dispatch (FepClient *client)
{
  static const struct
  {
    FepControlCommand command;
    void (*handler) (FepClient *client,
		     FepControlMessage *request,
		     FepControlMessage *response);
  } handlers[] =
      {
	{ FEP_CONTROL_KEY_EVENT, command_key_event },
	{ FEP_CONTROL_RESIZE_EVENT, command_resize_event },
      };
  FepControlMessage request, response;
  int retval;
  int i;

  retval = _fep_read_control_message (client->control, &request);
  if (retval < 0)
    return -1;

  for (i = 0;
       i < SIZEOF (handlers) && handlers[i].command != request.command;
       i++)
    ;
  if (i == SIZEOF (handlers))
    {
      _fep_control_message_free_args (&request);
      fep_log (FEP_LOG_LEVEL_WARNING,
	       "no handler defined for %d", request.command);
      return -1;
    }

  client->filter_running = true;
  handlers[i].handler (client, &request, &response);
  _fep_control_message_free_args (&request);
  _fep_write_control_message (client->control, &response);
  _fep_control_message_free_args (&response);
  client->filter_running = false;

  /* flush queued messages during handler is executed */
  while (client->messages)
    {
      FepList *_head = client->messages;
      FepControlMessage *_message = _head->data;

      client->messages = _head->next;

      _fep_write_control_message (client->control, _message);
      _fep_control_message_free (_message);
      free (_head);
    }

  return retval;
}


void ChromeContentBrowserClient::RegisterIOThreadServiceHandlers(
    content::ServiceManagerConnection* connection) {
  connection->AddServiceRequestHandler(
      chrome::mojom::kServiceName,
      ChromeService::GetInstance()->CreateChromeServiceRequestHandler());

#if defined(OS_ANDROID)
  connection->AddServiceRequestHandler(
      proxy_resolver::mojom::kProxyResolverServiceName,
      base::BindRepeating([](service_manager::mojom::ServiceRequest request) {
        service_manager::Service::RunAsyncUntilTermination(
            std::make_unique<proxy_resolver::ProxyResolverService>(
                std::move(request)));
      }));
  connection->AddServiceRequestHandler(
      "download_manager", base::BindRepeating(&StartDownloadManager));
#endif
}


void RenderProcessHostImpl::WidgetRestored() {
  DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
  visible_widgets_++;
  SetBackgrounded(false);
}


static __always_inline int do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt,
					       unsigned size)
{
	unsigned done_size = ctxt->fetch.end - ctxt->fetch.ptr;

	if (unlikely(done_size < size))
		return __do_insn_fetch_bytes(ctxt, size - done_size);
	else
		return X86EMUL_CONTINUE;
}


ProcGrabServer(ClientPtr client)
{
    int rc;

    REQUEST_SIZE_MATCH(xReq);
    if (grabState != GrabNone && client != grabClient) {
        ResetCurrentRequest(client);
        client->sequence--;
        BITSET(grabWaiters, client->index);
        IgnoreClient(client);
        return Success;
    }
    rc = OnlyListenToOneClient(client);
    if (rc != Success)
        return rc;
    grabState = GrabActive;
    grabClient = client;
    mark_client_grab(client);

    if (ServerGrabCallback) {
        ServerGrabInfoRec grabinfo;

        grabinfo.client = client;
        grabinfo.grabstate = SERVER_GRABBED;
        CallCallbacks(&ServerGrabCallback, (void *) &grabinfo);
    }

    return Success;
}


void NavigationController::LoadIfNecessary() {
  if (!needs_reload_)
    return;

  needs_reload_ = false;
  pending_entry_index_ = last_committed_entry_index_;
  NavigateToPendingEntry(false);
}


static int ptrace_peek_siginfo(struct task_struct *child,
				unsigned long addr,
				unsigned long data)
{
	struct ptrace_peeksiginfo_args arg;
	struct sigpending *pending;
	struct sigqueue *q;
	int ret, i;

	ret = copy_from_user(&arg, (void __user *) addr,
				sizeof(struct ptrace_peeksiginfo_args));
	if (ret)
		return -EFAULT;

	if (arg.flags & ~PTRACE_PEEKSIGINFO_SHARED)
		return -EINVAL; /* unknown flags */

	if (arg.nr < 0)
		return -EINVAL;

	/* Ensure arg.off fits in an unsigned long */
	if (arg.off > ULONG_MAX)
		return 0;

	if (arg.flags & PTRACE_PEEKSIGINFO_SHARED)
		pending = &child->signal->shared_pending;
	else
		pending = &child->pending;

	for (i = 0; i < arg.nr; ) {
		kernel_siginfo_t info;
		unsigned long off = arg.off + i;
		bool found = false;

		spin_lock_irq(&child->sighand->siglock);
		list_for_each_entry(q, &pending->list, list) {
			if (!off--) {
				found = true;
				copy_siginfo(&info, &q->info);
				break;
			}
		}
		spin_unlock_irq(&child->sighand->siglock);

		if (!found) /* beyond the end of the list */
			break;

#ifdef CONFIG_COMPAT
		if (unlikely(in_compat_syscall())) {
			compat_siginfo_t __user *uinfo = compat_ptr(data);

			if (copy_siginfo_to_user32(uinfo, &info)) {
				ret = -EFAULT;
				break;
			}

		} else
#endif
		{
			siginfo_t __user *uinfo = (siginfo_t __user *) data;

			if (copy_siginfo_to_user(uinfo, &info)) {
				ret = -EFAULT;
				break;
			}
		}

		data += sizeof(siginfo_t);
		i++;

		if (signal_pending(current))
			break;

		cond_resched();
	}

	if (i > 0)
		return i;

	return ret;
}


void WebPluginDelegatePepper::Paint(WebKit::WebCanvas* canvas,
                                    const gfx::Rect& rect) {
#if defined(OS_WIN) || defined(OS_LINUX)
  if (nested_delegate_) {
  } else {
    if (!committed_bitmap_.isNull()) {
      gfx::Point origin(window_rect_.origin().x(), window_rect_.origin().y());
      canvas->drawBitmap(committed_bitmap_,
                         SkIntToScalar(window_rect_.origin().x()),
                         SkIntToScalar(window_rect_.origin().y()));
    }
  }
#endif
}


void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) {
  static const char allow[] = "allow";
  static const char options[] = "options";
  static const char policyURI[] = "policy-uri";
  static const char allowMessage[] =
      "The 'allow' directive has been replaced with 'default-src'. Please use "
      "that directive instead, as 'allow' has no effect.";
  static const char optionsMessage[] =
      "The 'options' directive has been replaced with 'unsafe-inline' and "
      "'unsafe-eval' source expressions for the 'script-src' and 'style-src' "
      "directives. Please use those directives instead, as 'options' has no "
      "effect.";
  static const char policyURIMessage[] =
      "The 'policy-uri' directive has been removed from the "
      "specification. Please specify a complete policy via "
      "the Content-Security-Policy header.";

  String message =
      "Unrecognized Content-Security-Policy directive '" + name + "'.\n";
  MessageLevel level = ErrorMessageLevel;
  if (equalIgnoringCase(name, allow)) {
    message = allowMessage;
  } else if (equalIgnoringCase(name, options)) {
    message = optionsMessage;
  } else if (equalIgnoringCase(name, policyURI)) {
    message = policyURIMessage;
  } else if (getDirectiveType(name) != DirectiveType::Undefined) {
    message = "The Content-Security-Policy directive '" + name +
              "' is implemented behind a flag which is currently disabled.\n";
    level = InfoMessageLevel;
  }

  logToConsole(message, level);
}


 nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric)
 {
 	NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config);
	guint32 mtu = nm_ip4_config_get_mtu (config);
 	int i;

 	g_return_val_if_fail (ifindex > 0, FALSE);
	g_return_val_if_fail (ifindex > 0, FALSE);
	g_return_val_if_fail (config != NULL, FALSE);

	/* Addresses */
	nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric);

	/* Routes */
	{
		int count = nm_ip4_config_get_num_routes (config);
		GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count);
		const NMPlatformIP4Route *route;
		gboolean success;

		for (i = 0; i < count; i++) {
			route = nm_ip4_config_get_route (config, i);

			/* Don't add the route if it's more specific than one of the subnets
			 * the device already has an IP address on.
			 */
			if (   route->gateway == 0
			    && nm_ip4_config_destination_is_direct (config, route->network, route->plen))
				continue;

			g_array_append_vals (routes, route, 1);
		}

		success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes);
		g_array_unref (routes);
 			return FALSE;
 	}

	/* MTU */
	if (mtu && mtu != nm_platform_link_get_mtu (ifindex))
		nm_platform_link_set_mtu (ifindex, mtu);
 	return TRUE;
 }


read_next_symbol(struct archive_read *a, struct huffman_code *code)
{
  unsigned char bit;
  unsigned int bits;
  int length, value, node;
  struct rar *rar;
  struct rar_br *br;

  if (!code->table)
  {
    if (make_table(a, code) != (ARCHIVE_OK))
      return -1;
  }

  rar = (struct rar *)(a->format->data);
  br = &(rar->br);

  /* Look ahead (peek) at bits */
  if (!rar_br_read_ahead(a, br, code->tablesize)) {
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
                      "Truncated RAR file data");
    rar->valid = 0;
    return -1;
  }
  bits = rar_br_bits(br, code->tablesize);

  length = code->table[bits].length;
  value = code->table[bits].value;

  if (length < 0)
  {
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
                      "Invalid prefix code in bitstream");
    return -1;
  }

  if (length <= code->tablesize)
  {
    /* Skip length bits */
    rar_br_consume(br, length);
    return value;
  }

  /* Skip tablesize bits */
  rar_br_consume(br, code->tablesize);

  node = value;
  while (!(code->tree[node].branches[0] ==
    code->tree[node].branches[1]))
  {
    if (!rar_br_read_ahead(a, br, 1)) {
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
                        "Truncated RAR file data");
      rar->valid = 0;
      return -1;
    }
    bit = rar_br_bits(br, 1);
    rar_br_consume(br, 1);

    if (code->tree[node].branches[bit] < 0)
    {
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
                        "Invalid prefix code in bitstream");
      return -1;
    }
    node = code->tree[node].branches[bit];
  }

  return code->tree[node].branches[0];
}


R_API void U(copy_type_info_to_stack_frame_list_up_to_idx)(RList * type_list, RList * sf_list, ut64 idx) {
	RListIter *iter, *iter_tmp;
	RBinJavaVerificationObj *ver_obj, *new_ver_obj;
	ut32 pos = 0;
	if (type_list == NULL) {
		return;
	}
	if (sf_list == NULL) {
		return;
	}
	r_list_foreach_safe (type_list, iter, iter_tmp, ver_obj) {
		new_ver_obj = (RBinJavaVerificationObj *) malloc (sizeof (RBinJavaVerificationObj));
		// FIXME: how to handle failed memory allocation?
		if (new_ver_obj && ver_obj) {
			memcpy (new_ver_obj, ver_obj, sizeof (RBinJavaVerificationObj));
			if (!r_list_append (sf_list, (void *) new_ver_obj)) {
				R_FREE (new_ver_obj);
			}
		} else {
			R_FREE (new_ver_obj);
		}
		pos++;
		if (pos == idx) {
			break;
		}
	}
}


static inline uint32_t e1000e_ring_len ( E1000ECore * core , const E1000E_RingInfo * r ) {
 return core -> mac [ r -> dlen ] ;
 }


uint32_t do_find_service(const uint16_t *s, size_t len, uid_t uid, pid_t spid)
{
 struct svcinfo *si = find_svc(s, len);

 if (!si || !si->handle) {
 return 0;
 }

 if (!si->allow_isolated) {
 uid_t appid = uid % AID_USER;
 if (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END) {
 return 0;
 }
 }

 if (!svc_can_find(s, len, spid, uid)) {
 return 0;
 }

 return si->handle;
}


SPL_METHOD(SplDoublyLinkedList, getIteratorMode)
{
	spl_dllist_object *intern;

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	intern = Z_SPLDLLIST_P(getThis());

	RETURN_LONG(intern->flags);
}


    template<typename t>
    CImg<T>& draw_image(const int x0, const int y0, const int z0,
                        const CImg<t>& sprite, const float opacity=1) {
      return draw_image(x0,y0,z0,0,sprite,opacity);


static int hns_nic_init_affinity_mask(int q_num, int ring_idx,
				      struct hnae_ring *ring, cpumask_t *mask)
{
	int cpu;

	/* Diffrent irq banlance between 16core and 32core.
	 * The cpu mask set by ring index according to the ring flag
	 * which indicate the ring is tx or rx.
	 */
	if (q_num == num_possible_cpus()) {
		if (is_tx_ring(ring))
			cpu = ring_idx;
		else
			cpu = ring_idx - q_num;
	} else {
		if (is_tx_ring(ring))
			cpu = ring_idx * 2;
		else
			cpu = (ring_idx - q_num) * 2 + 1;
	}

	cpumask_clear(mask);
	cpumask_set_cpu(cpu, mask);

	return cpu;
}


TEST_F ( TemplateURLTest , ReplaceAssistedQueryStats ) {
 struct TestData {
 const base : : string16 search_term ;
 const std : : string aqs ;
 const std : : string base_url ;
 const std : : string url ;
 const std : : string expected_result ;
 }
 test_data [ ] = {
 {
 ASCIIToUTF16 ( "foo" ) , "chrome.0.0l6" , "http://foo/" , "{
google:baseURL}
?{
searchTerms}
{
google:assistedQueryStats}
" , "http://foo/?foo" }
 , {
 ASCIIToUTF16 ( "foo" ) , "chrome.0.0l6" , "https://foo/" , "{
google:baseURL}
?{
searchTerms}
{
google:assistedQueryStats}
" , "https://foo/?fooaqs=chrome.0.0l6&" }
 , {
 ASCIIToUTF16 ( "foo" ) , "" , "https://foo/" , "{
google:baseURL}
?{
searchTerms}
{
google:assistedQueryStats}
" , "https://foo/?foo" }
 , {
 ASCIIToUTF16 ( "foo" ) , "chrome.0.0l6" , "http://www.google.com" , "http://foo?{
searchTerms}
{
google:assistedQueryStats}
" , "http://foo/?foo" }
 , {
 ASCIIToUTF16 ( "foo" ) , "chrome.0.0l6" , "https://www.google.com" , "https://foo?{
searchTerms}
{
google:assistedQueryStats}
" , "https://foo/?fooaqs=chrome.0.0l6&" }
 , }
 ;
 TemplateURLData data ;
 data . input_encodings . push_back ( "UTF-8" ) ;
 for ( size_t i = 0 ;
 i < arraysize ( test_data ) ;
 ++ i ) {
 data . SetURL ( test_data [ i ] . url ) ;
 TemplateURL url ( data ) ;
 EXPECT_TRUE ( url . url_ref ( ) . IsValid ( search_terms_data_ ) ) ;
 ASSERT_TRUE ( url . url_ref ( ) . SupportsReplacement ( search_terms_data_ ) ) ;
 TemplateURLRef : : SearchTermsArgs search_terms_args ( test_data [ i ] . search_term ) ;
 search_terms_args . assisted_query_stats = test_data [ i ] . aqs ;
 search_terms_data_ . set_google_base_url ( test_data [ i ] . base_url ) ;
 GURL result ( url . url_ref ( ) . ReplaceSearchTerms ( search_terms_args , search_terms_data_ ) ) ;
 ASSERT_TRUE ( result . is_valid ( ) ) ;
 EXPECT_EQ ( test_data [ i ] . expected_result , result . spec ( ) ) ;
 }
 }


static int32_t uncurl_read_chunk_len(struct uncurl_conn *ucc, uint32_t *len)
{
	int32_t r = UNCURL_ERR_MAX_CHUNK;

	char chunk_len[LEN_CHUNK];
	memset(chunk_len, 0, LEN_CHUNK);

	for (uint32_t x = 0; x < LEN_CHUNK - 1; x++) {
		int32_t e;

		e = ucc->read(ucc->ctx, chunk_len + x, 1);
		if (e != UNCURL_OK) {r = e; break;}

		if (x > 0 && chunk_len[x - 1] == '\r' && chunk_len[x] == '\n') {
			chunk_len[x - 1] = '\0';
			*len = strtoul(chunk_len, NULL, 16);
			return UNCURL_OK;
		}
	}

	*len = 0;

	return r;
}


int mysqld_main ( int argc , char * * argv ) # endif {
 my_progname = argv [ 0 ] ;
 sf_leaking_memory = 1 ;
 # ifdef HAVE_NPTL ld_assume_kernel_is_set = ( getenv ( "LD_ASSUME_KERNEL" ) != 0 ) ;
 # endif # ifndef _WIN32 if ( my_init ( ) ) {
 fprintf ( stderr , "my_init() failed." ) ;
 return 1 ;
 }
 # endif orig_argc = argc ;
 orig_argv = argv ;
 my_getopt_use_args_separator = TRUE ;
 if ( load_defaults ( MYSQL_CONFIG_NAME , load_default_groups , & argc , & argv ) ) return 1 ;
 my_getopt_use_args_separator = FALSE ;
 defaults_argc = argc ;
 defaults_argv = argv ;
 remaining_argc = argc ;
 remaining_argv = argv ;
 system_charset_info = & my_charset_utf8_general_ci ;
 init_sql_statement_names ( ) ;
 sys_var_init ( ) ;
 # ifdef WITH_PERFSCHEMA_STORAGE_ENGINE int ho_error ;
 DYNAMIC_ARRAY all_early_options ;
 my_getopt_register_get_addr ( NULL ) ;
 my_getopt_skip_unknown = TRUE ;
 my_init_dynamic_array ( & all_early_options , sizeof ( my_option ) , 100 , 25 ) ;
 sys_var_add_options ( & all_early_options , sys_var : : PARSE_EARLY ) ;
 add_terminator ( & all_early_options ) ;
 buffered_logs . init ( ) ;
 my_getopt_error_reporter = buffered_option_error_reporter ;
 ho_error = handle_options ( & remaining_argc , & remaining_argv , ( my_option * ) ( all_early_options . buffer ) , NULL ) ;
 delete_dynamic ( & all_early_options ) ;
 if ( ho_error == 0 ) {
 remaining_argc ++ ;
 remaining_argv -- ;
 if ( pfs_param . m_enabled ) {
 PSI_hook = initialize_performance_schema ( & pfs_param ) ;
 if ( PSI_hook == NULL ) {
 pfs_param . m_enabled = false ;
 buffered_logs . buffer ( WARNING_LEVEL , "Performance schema disabled (reason: init failed)." ) ;
 }
 }
 }
 # else # endif # ifdef HAVE_PSI_INTERFACE if ( PSI_hook ) PSI_server = ( PSI * ) PSI_hook -> get_interface ( PSI_CURRENT_VERSION ) ;
 if ( PSI_server ) {
 init_server_psi_keys ( ) ;
 PSI_thread * psi = PSI_server -> new_thread ( key_thread_main , NULL , 0 ) ;
 if ( psi ) PSI_server -> set_thread ( psi ) ;
 my_thread_global_reinit ( ) ;
 }
 # endif init_error_log_mutex ( ) ;
 mysql_audit_initialize ( ) ;
 logger . init_base ( ) ;
 # ifdef WITH_PERFSCHEMA_STORAGE_ENGINE if ( ho_error ) {
 buffered_logs . print ( ) ;
 buffered_logs . cleanup ( ) ;
 exit ( ho_error ) ;
 }
 # endif # ifdef _CUSTOMSTARTUPCONFIG_ if ( _cust_check_startup ( ) ) {
 / * _cust_check_startup will report startup failure error * / exit ( 1 ) ;
 }
 # endif if ( init_common_variables ( ) ) unireg_abort ( 1 ) ;
 init_signals ( ) ;
 my_thread_stack_size = my_setstacksize ( & connection_attrib , my_thread_stack_size ) ;
 ( void ) thr_setconcurrency ( concurrency ) ;
 select_thread = pthread_self ( ) ;
 select_thread_in_use = 1 ;
 # ifdef HAVE_LIBWRAP libwrapName = my_progname + dirname_length ( my_progname ) ;
 openlog ( libwrapName , LOG_PID , LOG_AUTH ) ;
 # endif # ifndef DBUG_OFF test_lc_time_sz ( ) ;
 srand ( ( uint ) time ( NULL ) ) ;
 # endif check_data_home ( mysql_real_data_home ) ;
 if ( my_setwd ( mysql_real_data_home , opt_abort ? 0 : MYF ( MY_WME ) ) && ! opt_abort ) unireg_abort ( 1 ) ;
 if ( ( user_info = check_user ( mysqld_user ) ) ) {
 # if defined ( HAVE_MLOCKALL ) && defined ( MCL_CURRENT ) if ( locked_in_memory ) set_effective_user ( user_info ) ;
 else # endif set_user ( mysqld_user , user_info ) ;
 }
 if ( opt_bin_log && ! server_id ) {
 server_id = 1 ;
 # ifdef EXTRA_DEBUG sql_print_warning ( "You have enabled the binary log, but you haven't set " "server-id to a non-zero value: we force server id to 1;
 " "updates will be logged to the binary log, but " "connections from slaves will not be accepted." ) ;
 # endif }
 # if defined ( _WIN32 ) && ! defined ( EMBEDDED_LIBRARY ) Service . SetSlowStarting ( slow_start_timeout ) ;
 # endif if ( init_server_components ( ) ) unireg_abort ( 1 ) ;
 init_ssl ( ) ;
 network_init ( ) ;
 # ifdef __WIN__ if ( ! opt_console ) {
 if ( reopen_fstreams ( log_error_file , stdout , stderr ) ) unireg_abort ( 1 ) ;
 setbuf ( stderr , NULL ) ;
 FreeConsole ( ) ;
 }
 # endif my_str_malloc = & my_str_malloc_mysqld ;
 my_str_free = & my_str_free_mysqld ;
 start_signal_handler ( ) ;
 if ( mysql_rm_tmp_tables ( ) || acl_init ( opt_noacl ) || my_tz_init ( ( THD * ) 0 , default_tz_name , opt_bootstrap ) ) {
 abort_loop = 1 ;
 select_thread_in_use = 0 ;
 ( void ) pthread_kill ( signal_thread , MYSQL_KILL_SIGNAL ) ;
 delete_pid_file ( MYF ( MY_WME ) ) ;
 if ( unix_sock != INVALID_SOCKET ) unlink ( mysqld_unix_port ) ;
 exit ( 1 ) ;
 }
 if ( ! opt_noacl ) ( void ) grant_init ( ) ;
 if ( ! opt_bootstrap ) servers_init ( 0 ) ;
 udf_init ( ) ;
 init_status_vars ( ) ;
 if ( opt_bootstrap ) opt_skip_slave_start = 1 ;
 binlog_unsafe_map_init ( ) ;
 if ( init_slave ( ) && ! active_mi ) {
 unireg_abort ( 1 ) ;
 }
 # ifdef WITH_PERFSCHEMA_STORAGE_ENGINE initialize_performance_schema_acl ( opt_bootstrap ) ;
 if ( ! opt_bootstrap ) check_performance_schema ( ) ;
 # endif initialize_information_schema_acl ( ) ;
 execute_ddl_log_recovery ( ) ;
 if ( Events : : init ( opt_noacl || opt_bootstrap ) ) unireg_abort ( 1 ) ;
 if ( opt_bootstrap ) {
 select_thread_in_use = 0 ;
 bootstrap ( mysql_stdin ) ;
 if ( ! kill_in_progress ) unireg_abort ( bootstrap_error ? 1 : 0 ) ;
 else {
 sleep ( 2 ) ;
 exit ( 0 ) ;
 }
 }
 if ( opt_init_file && * opt_init_file ) {
 if ( read_init_file ( opt_init_file ) ) unireg_abort ( 1 ) ;
 }
 create_shutdown_thread ( ) ;
 start_handle_manager ( ) ;
 sql_print_information ( ER_DEFAULT ( ER_STARTUP ) , my_progname , server_version , ( ( unix_sock == INVALID_SOCKET ) ? ( char * ) "" : mysqld_unix_port ) , mysqld_port , MYSQL_COMPILATION_COMMENT ) ;
 # if defined ( _WIN32 ) && ! defined ( EMBEDDED_LIBRARY ) Service . SetRunning ( ) ;
 # endif mysql_mutex_lock ( & LOCK_server_started ) ;
 mysqld_server_started = 1 ;
 mysql_cond_signal ( & COND_server_started ) ;
 mysql_mutex_unlock ( & LOCK_server_started ) ;
 # if defined ( _WIN32 ) || defined ( HAVE_SMEM ) handle_connections_methods ( ) ;
 # else handle_connections_sockets ( ) ;
 # endif DBUG_PRINT ( "quit" , ( "Exiting main thread" ) ) ;
 # ifndef __WIN__ # ifdef EXTRA_DEBUG2 sql_print_error ( "Before Lock_thread_count" ) ;
 # endif mysql_mutex_lock ( & LOCK_thread_count ) ;
 DBUG_PRINT ( "quit" , ( "Got thread_count mutex" ) ) ;
 select_thread_in_use = 0 ;
 mysql_mutex_unlock ( & LOCK_thread_count ) ;
 mysql_cond_broadcast ( & COND_thread_count ) ;
 # ifdef EXTRA_DEBUG2 sql_print_error ( "After lock_thread_count" ) ;
 # endif # endif # ifdef HAVE_PSI_INTERFACE if ( PSI_server ) PSI_server -> delete_current_thread ( ) ;
 # endif mysql_mutex_lock ( & LOCK_thread_count ) ;
 while ( ! ready_to_exit ) mysql_cond_wait ( & COND_thread_count , & LOCK_thread_count ) ;
 mysql_mutex_unlock ( & LOCK_thread_count ) ;
 # if defined ( __WIN__ ) && ! defined ( EMBEDDED_LIBRARY ) if ( Service . IsNT ( ) && start_mode ) Service . Stop ( ) ;
 else {
 Service . SetShutdownEvent ( 0 ) ;
 if ( hEventShutdown ) CloseHandle ( hEventShutdown ) ;
 }
 # endif mysqld_exit ( 0 ) ;
 return 0 ;
 }


static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
    AC3HeaderInfo *hdr = NULL;
    struct eac3_info *info;
    int num_blocks, ret;

    if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
        return AVERROR(ENOMEM);
    info = track->eac3_priv;

    if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
        /* drop the packets until we see a good one */
        if (!track->entry) {
            av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
            ret = 0;
        } else
            ret = AVERROR_INVALIDDATA;
        goto end;
    }

    info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
    num_blocks = hdr->num_blocks;

    if (!info->ec3_done) {
        /* AC-3 substream must be the first one */
        if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
            ret = AVERROR(EINVAL);
            goto end;
        }

        /* this should always be the case, given that our AC-3 parser
         * concatenates dependent frames to their independent parent */
        if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
            /* substream ids must be incremental */
            if (hdr->substreamid > info->num_ind_sub + 1) {
                ret = AVERROR(EINVAL);
                goto end;
            }

            if (hdr->substreamid == info->num_ind_sub + 1) {
                //info->num_ind_sub++;
                avpriv_request_sample(track->par, "Multiple independent substreams");
                ret = AVERROR_PATCHWELCOME;
                goto end;
            } else if (hdr->substreamid < info->num_ind_sub ||
                       hdr->substreamid == 0 && info->substream[0].bsid) {
                info->ec3_done = 1;
                goto concatenate;
            }
        }

        /* fill the info needed for the "dec3" atom */
        info->substream[hdr->substreamid].fscod = hdr->sr_code;
        info->substream[hdr->substreamid].bsid  = hdr->bitstream_id;
        info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
        info->substream[hdr->substreamid].acmod = hdr->channel_mode;
        info->substream[hdr->substreamid].lfeon = hdr->lfe_on;

        /* Parse dependent substream(s), if any */
        if (pkt->size != hdr->frame_size) {
            int cumul_size = hdr->frame_size;
            int parent = hdr->substreamid;

            while (cumul_size != pkt->size) {
                GetBitContext gbc;
                int i;
                ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
                if (ret < 0)
                    goto end;
                if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
                    ret = AVERROR(EINVAL);
                    goto end;
                }
                info->substream[parent].num_dep_sub++;
                ret /= 8;

                /* header is parsed up to lfeon, but custom channel map may be needed */
                init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
                /* skip bsid */
                skip_bits(&gbc, 5);
                /* skip volume control params */
                for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
                    skip_bits(&gbc, 5); // skip dialog normalization
                    if (get_bits1(&gbc)) {
                        skip_bits(&gbc, 8); // skip compression gain word
                    }
                }
                /* get the dependent stream channel map, if exists */
                if (get_bits1(&gbc))
                    info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
                else
                    info->substream[parent].chan_loc |= hdr->channel_mode;
                cumul_size += hdr->frame_size;
            }
        }
    }

concatenate:
    if (!info->num_blocks && num_blocks == 6) {
        ret = pkt->size;
        goto end;
    }
    else if (info->num_blocks + num_blocks > 6) {
        ret = AVERROR_INVALIDDATA;
        goto end;
    }

    if (!info->num_blocks) {
        ret = av_packet_ref(&info->pkt, pkt);
        if (!ret)
            info->num_blocks = num_blocks;
        goto end;
    } else {
        if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
            goto end;
        memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
        info->num_blocks += num_blocks;
        info->pkt.duration += pkt->duration;
        if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
            goto end;
        if (info->num_blocks != 6)
            goto end;
        av_packet_unref(pkt);
        av_packet_move_ref(pkt, &info->pkt);
        info->num_blocks = 0;
    }
    ret = pkt->size;

end:
    av_free(hdr);

    return ret;
}


mrb_io_alloc(mrb_state *mrb)
{
  struct mrb_io *fptr;

  fptr = (struct mrb_io *)mrb_malloc(mrb, sizeof(struct mrb_io));
  fptr->fd = -1;
  fptr->fd2 = -1;
  fptr->pid = 0;
  fptr->readable = 0;
  fptr->writable = 0;
  fptr->sync = 0;
  fptr->is_socket = 0;
  return fptr;
}


static void enforcedRangeLongLongAttrAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
    ExceptionState exceptionState(ExceptionState::SetterContext, "enforcedRangeLongLongAttr", "TestObject", info.Holder(), info.GetIsolate());
    TestObject* imp = V8TestObject::toNative(info.Holder());
    V8TRYCATCH_EXCEPTION_VOID(long long, cppValue, toInt64(jsValue, EnforceRange, exceptionState), exceptionState);
    imp->setEnforcedRangeLongLongAttr(cppValue);
}


hfs_attr_walk_lzvn_rsrc(const TSK_FS_ATTR * fs_attr,
    int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr)
{
    return hfs_attr_walk_compressed_rsrc(
      fs_attr, flags, a_action, ptr,
      hfs_read_lzvn_block_table,
      hfs_decompress_lzvn_block
    );
}


static int call_undef_hook(struct pt_regs *regs, unsigned int instr)
{
	struct undef_hook *hook;
	unsigned long flags;
	int (*fn)(struct pt_regs *regs, unsigned int instr) = NULL;

	raw_spin_lock_irqsave(&undef_lock, flags);
	list_for_each_entry(hook, &undef_hook, node)
		if ((instr & hook->instr_mask) == hook->instr_val &&
		    (regs->ARM_cpsr & hook->cpsr_mask) == hook->cpsr_val)
			fn = hook->fn;
	raw_spin_unlock_irqrestore(&undef_lock, flags);

	return fn ? fn(regs, instr) : 1;
}


void ssl_set_client_disabled(SSL *s)
	{
	CERT *c = s->cert;
	c->mask_a = 0;
	c->mask_k = 0;
	/* Don't allow TLS 1.2 only ciphers if we don't suppport them */
	if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
		c->mask_ssl = SSL_TLSV1_2;
	else
		c->mask_ssl = 0;
	ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK);
	/* Disable static DH if we don't include any appropriate
	 * signature algorithms.
	 */
	if (c->mask_a & SSL_aRSA)
		c->mask_k |= SSL_kDHr|SSL_kECDHr;
	if (c->mask_a & SSL_aDSS)
		c->mask_k |= SSL_kDHd;
	if (c->mask_a & SSL_aECDSA)
		c->mask_k |= SSL_kECDHe;
#ifndef OPENSSL_NO_KRB5
	if (!kssl_tgt_is_available(s->kssl_ctx))
		{
		c->mask_a |= SSL_aKRB5;
		c->mask_k |= SSL_kKRB5;
		}
#endif
#ifndef OPENSSL_NO_PSK
	/* with PSK there must be client callback set */
	if (!s->psk_client_callback)
		{
		c->mask_a |= SSL_aPSK;
		c->mask_k |= SSL_kPSK;
		}
#endif /* OPENSSL_NO_PSK */
	c->valid = 1;
	}


gsicc_get_profile_handle_clist(cmm_profile_t *picc_profile, gs_memory_t *memory)
{
    gcmmhprofile_t profile_handle = NULL;
    unsigned int profile_size;
    int size;
    gx_device_clist_reader *pcrdev = (gx_device_clist_reader*) picc_profile->dev;
    unsigned char *buffer_ptr;
    int64_t position;
    gsicc_serialized_profile_t profile_header;
    int k;

    if( pcrdev != NULL) {

        /* Check ICC table for hash code and get the whole size icc raw buffer
           plus serialized header information */
        position = gsicc_search_icc_table(pcrdev->icc_table,
                                          picc_profile->hashcode, &size);
        if ( position < 0 )
            return 0;  /* Not found. */

        /* Get the ICC buffer.  We really want to avoid this transfer.
           I need to write  an interface to the CMM to do this through
           the clist ioprocs */
        /* Allocate the buffer */
        profile_size = size - GSICC_SERIALIZED_SIZE;
        /* Profile and its members are ALL in non-gc memory */
        buffer_ptr = gs_alloc_bytes(memory->non_gc_memory, profile_size,
                                            "gsicc_get_profile_handle_clist");
        if (buffer_ptr == NULL)
            return 0;
        picc_profile->buffer = buffer_ptr;
        clist_read_chunk(pcrdev, position + GSICC_SERIALIZED_SIZE,
            profile_size, (unsigned char *) buffer_ptr);
        profile_handle = gscms_get_profile_handle_mem(memory->non_gc_memory, buffer_ptr, profile_size);
        /* We also need to get some of the serialized information */
        clist_read_chunk(pcrdev, position, GSICC_SERIALIZED_SIZE,
                        (unsigned char *) (&profile_header));
        picc_profile->buffer_size = profile_header.buffer_size;
        picc_profile->data_cs = profile_header.data_cs;
        picc_profile->default_match = profile_header.default_match;
        picc_profile->hash_is_valid = profile_header.hash_is_valid;
        picc_profile->hashcode = profile_header.hashcode;
        picc_profile->islab = profile_header.islab;
        picc_profile->num_comps = profile_header.num_comps;
        picc_profile->rend_is_valid = profile_header.rend_is_valid;
        picc_profile->rend_cond = profile_header.rend_cond;
        picc_profile->isdevlink = profile_header.isdevlink;
        for ( k = 0; k < profile_header.num_comps; k++ ) {
            picc_profile->Range.ranges[k].rmax =
                profile_header.Range.ranges[k].rmax;
            picc_profile->Range.ranges[k].rmin =
                profile_header.Range.ranges[k].rmin;
        }
        return profile_handle;
     }
     return 0;
}


void WebPage::insertText(const BlackBerry::Platform::String& string)
{
    if (d->m_page->defersLoading())
        return;
    d->m_inputHandler->insertText(string);
}


const char *urlGetAnchor(struct URL *url) {
  return url->anchor;
}


static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
{
	struct dm_table *map = NULL;

	lockdep_assert_held(&md->suspend_lock);

	if (md->internal_suspend_count++)
		return; /* nested internal suspend */

	if (dm_suspended_md(md)) {
		set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
		return; /* nest suspend */
	}

	map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));

	/*
	 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
	 * supported.  Properly supporting a TASK_INTERRUPTIBLE internal suspend
	 * would require changing .presuspend to return an error -- avoid this
	 * until there is a need for more elaborate variants of internal suspend.
	 */
	(void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
			    DMF_SUSPENDED_INTERNALLY);

	dm_table_postsuspend_targets(map);
}


static void xfrm_policy_destroy_rcu(struct rcu_head *head)
{
	struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);

	security_xfrm_policy_free(policy->security);
	kfree(policy);
}


void HTMLConstructionSite::insertTextNode(const String& characters)
{
    AttachmentSite site;
    site.parent = currentElement();
    site.nextChild = 0;
    if (shouldFosterParent())
        findFosterSite(site);

    Node* previousChild = site.nextChild ? site.nextChild->previousSibling() : site.parent->lastChild();
    if (previousChild && previousChild->isTextNode()) {
        CharacterData* textNode = static_cast<CharacterData*>(previousChild);
        textNode->parserAppendData(characters);
        return;
    }

    attachAtSite(site, Text::create(m_document, characters));
}


 void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
  exit_code_ = exit_code;
   BOOL result = SetEvent(process_exit_event_);
   EXPECT_TRUE(result);
 }


SPL_METHOD(SplDoublyLinkedList, serialize)
{
	spl_dllist_object     *intern   = Z_SPLDLLIST_P(getThis());
	smart_str              buf      = {0};
	spl_ptr_llist_element *current  = intern->llist->head, *next;
	zval                   flags;
	php_serialize_data_t   var_hash;

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	PHP_VAR_SERIALIZE_INIT(var_hash);

	/* flags */
	ZVAL_LONG(&flags, intern->flags);
	php_var_serialize(&buf, &flags, &var_hash);
	zval_ptr_dtor(&flags);

	/* elements */
	while (current) {
		smart_str_appendc(&buf, ':');
		next = current->next;

		php_var_serialize(&buf, &current->data, &var_hash);

		current = next;
	}

	smart_str_0(&buf);

	/* done */
	PHP_VAR_SERIALIZE_DESTROY(var_hash);

	if (buf.s) {
		RETURN_NEW_STR(buf.s);
	} else {
		RETURN_NULL();
	}

} /* }}} */


void CommandData::ProcessCommand()
{
#ifndef SFX_MODULE

  const wchar *SingleCharCommands=L"FUADPXETK";
  if (Command[0]!=0 && Command[1]!=0 && wcschr(SingleCharCommands,Command[0])!=NULL || *ArcName==0)
    OutHelp(*Command==0 ? RARX_SUCCESS:RARX_USERERROR); // Return 'success' for 'rar' without parameters.

  const wchar *ArcExt=GetExt(ArcName);
#ifdef _UNIX
  if (ArcExt==NULL && (!FileExist(ArcName) || IsDir(GetFileAttr(ArcName))))
    wcsncatz(ArcName,L".rar",ASIZE(ArcName));
#else
  if (ArcExt==NULL)
    wcsncatz(ArcName,L".rar",ASIZE(ArcName));
#endif
  // Treat arcname.part1 as arcname.part1.rar.
  if (ArcExt!=NULL && wcsnicomp(ArcExt,L".part",5)==0 && IsDigit(ArcExt[5]) &&
      !FileExist(ArcName))
  {
    wchar Name[NM];
    wcsncpyz(Name,ArcName,ASIZE(Name));
    wcsncatz(Name,L".rar",ASIZE(Name));
    if (FileExist(Name))
      wcsncpyz(ArcName,Name,ASIZE(ArcName));
  }

  if (wcschr(L"AFUMD",*Command)==NULL && !ArcInMem)
  {
    if (GenerateArcName)
      GenerateArchiveName(ArcName,ASIZE(ArcName),GenerateMask,false);

    StringList ArcMasks;
    ArcMasks.AddString(ArcName);
    ScanTree Scan(&ArcMasks,Recurse,SaveSymLinks,SCAN_SKIPDIRS);
    FindData FindData;
    while (Scan.GetNext(&FindData)==SCAN_SUCCESS)
      AddArcName(FindData.Name);
  }
  else
    AddArcName(ArcName);
#endif

  switch(Command[0])
  {
    case 'P':
    case 'X':
    case 'E':
    case 'T':
    case 'I':
      {
        CmdExtract Extract(this);
        Extract.DoExtract();
      }
      break;
#ifndef SILENT
    case 'V':
    case 'L':
      ListArchive(this);
      break;
    default:
      OutHelp(RARX_USERERROR);
#endif
  }
  if (!BareOutput)
    mprintf(L"\n");
}


xmlXPtrGetChildNo(xmlXPathParserContextPtr ctxt, int indx) {
    xmlNodePtr cur = NULL;
    xmlXPathObjectPtr obj;
    xmlNodeSetPtr oldset;

    CHECK_TYPE(XPATH_NODESET);
    obj = valuePop(ctxt);
    oldset = obj->nodesetval;
    if ((indx <= 0) || (oldset == NULL) || (oldset->nodeNr != 1)) {
	xmlXPathFreeObject(obj);
	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
	return;
    }
    cur = xmlXPtrGetNthChild(oldset->nodeTab[0], indx);
    if (cur == NULL) {
	xmlXPathFreeObject(obj);
	valuePush(ctxt, xmlXPathNewNodeSet(NULL));
	return;
    }
    oldset->nodeTab[0] = cur;
    valuePush(ctxt, obj);
}


struct btrfs_block_group *btrfs_lookup_block_group(
		struct btrfs_fs_info *info, u64 bytenr)
{
	return block_group_cache_tree_search(info, bytenr, 1);
}


IN_PROC_BROWSER_TEST_F ( FullscreenControllerInteractiveTest , MAYBE_MouseLockSilentAfterTargetUnlock ) {
 ASSERT_TRUE ( test_server ( ) -> Start ( ) ) ;
 ui_test_utils : : NavigateToURL ( browser ( ) , test_server ( ) -> GetURL ( kFullscreenMouseLockHTML ) ) ;
 ASSERT_FALSE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_1 , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_TRUE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( IsMouseLockPermissionRequested ( ) ) ;
 ASSERT_FALSE ( IsMouseLocked ( ) ) ;
 AcceptCurrentFullscreenOrMouseLockRequest ( ) ;
 ASSERT_TRUE ( IsMouseLocked ( ) ) ;
 ASSERT_TRUE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_U , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_FALSE ( IsMouseLocked ( ) ) ;
 ASSERT_FALSE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_1 , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_TRUE ( IsMouseLocked ( ) ) ;
 ASSERT_FALSE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_U , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_FALSE ( IsMouseLocked ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_D , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_TRUE ( IsMouseLocked ( ) ) ;
 ASSERT_FALSE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_ESCAPE , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_FALSE ( IsMouseLocked ( ) ) ;
 ASSERT_TRUE ( ui_test_utils : : SendKeyPressAndWait ( browser ( ) , ui : : VKEY_1 , false , false , false , false , chrome : : NOTIFICATION_MOUSE_LOCK_CHANGED , content : : NotificationService : : AllSources ( ) ) ) ;
 ASSERT_TRUE ( IsFullscreenBubbleDisplayed ( ) ) ;
 ASSERT_TRUE ( IsMouseLocked ( ) ) ;
 }


void WebsiteSettingsPopupView::SetSelectedTab(TabId tab_id) {
  tabbed_pane_->SelectTabAt(tab_id);
}


int gdImageColorClosest (gdImagePtr im, int r, int g, int b)
{
	return gdImageColorClosestAlpha (im, r, g, b, gdAlphaOpaque);
}


static int fbiogetputcmap(struct fb_info *info, unsigned int cmd, unsigned long arg)
{
	struct fbcmap32 __user *argp = (void __user *)arg;
	struct fbcmap __user *p = compat_alloc_user_space(sizeof(*p));
	u32 addr;
	int ret;

	ret = copy_in_user(p, argp, 2 * sizeof(int));
	ret |= get_user(addr, &argp->red);
	ret |= put_user(compat_ptr(addr), &p->red);
	ret |= get_user(addr, &argp->green);
	ret |= put_user(compat_ptr(addr), &p->green);
	ret |= get_user(addr, &argp->blue);
	ret |= put_user(compat_ptr(addr), &p->blue);
	if (ret)
		return -EFAULT;
	return info->fbops->fb_ioctl(info,
			(cmd == FBIOPUTCMAP32) ?
			FBIOPUTCMAP_SPARC : FBIOGETCMAP_SPARC,
			(unsigned long)p);
}


void test_stat(const char *path)
{
	struct stat sb;
	if (stat(path, &sb) >= 0) {
		fprintf(stderr, "leak at stat of %s\n", path);
		exit(1);
	}
	if (errno != ENOENT) {
		fprintf(stderr, "leak at stat of %s: errno was %d\n", path, errno);
		exit(1);
	}
}


void DesktopWindowTreeHostX11::AddObserver(
    DesktopWindowTreeHostObserverX11* observer) {
  observer_list_.AddObserver(observer);
}


struct posix_acl *get_cached_acl(struct inode *inode, int type)
{
	struct posix_acl **p = acl_by_type(inode, type);
	struct posix_acl *acl;

	for (;;) {
		rcu_read_lock();
		acl = rcu_dereference(*p);
		if (!acl || is_uncached_acl(acl) ||
		    atomic_inc_not_zero(&acl->a_refcount))
			break;
		rcu_read_unlock();
		cpu_relax();
	}
	rcu_read_unlock();
	return acl;
}


static void ebt_standard_compat_from_user(void *dst, const void *src)
{
	int v = *(compat_int_t *)src;

	if (v >= 0)
		v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
	memcpy(dst, &v, sizeof(v));
}


struct ipx_interface *ipxitf_find_using_net(__be32 net)
{
	struct ipx_interface *i;

	spin_lock_bh(&ipx_interfaces_lock);
	if (net) {
		list_for_each_entry(i, &ipx_interfaces, node)
			if (i->if_netnum == net)
				goto hold;
		i = NULL;
		goto unlock;
	}

	i = ipx_primary_net;
	if (i)
hold:
		ipxitf_hold(i);
unlock:
	spin_unlock_bh(&ipx_interfaces_lock);
	return i;
}


val_wrap_args(OM_uint32 *minor_status,
              gss_ctx_id_t context_handle,
              int conf_req_flag,
              gss_qop_t qop_req,
              gss_buffer_t input_message_buffer,
              int *conf_state,
              gss_buffer_t output_message_buffer)
{
    /* Initialize outputs. */

    if (minor_status != NULL)
        *minor_status = 0;

    if (output_message_buffer != GSS_C_NO_BUFFER) {
        output_message_buffer->length = 0;
        output_message_buffer->value = NULL;
    }

    /* Validate arguments. */

    if (minor_status == NULL)
        return (GSS_S_CALL_INACCESSIBLE_WRITE);

    if (context_handle == GSS_C_NO_CONTEXT)
        return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);

    if (input_message_buffer == GSS_C_NO_BUFFER)
        return (GSS_S_CALL_INACCESSIBLE_READ);

    if (output_message_buffer == GSS_C_NO_BUFFER)
        return (GSS_S_CALL_INACCESSIBLE_WRITE);

    return (GSS_S_COMPLETE);
}


static inline int pfkey_mode_to_xfrm ( int mode ) {
 switch ( mode ) {
 case IPSEC_MODE_ANY : case IPSEC_MODE_TRANSPORT : return XFRM_MODE_TRANSPORT ;
 case IPSEC_MODE_TUNNEL : return XFRM_MODE_TUNNEL ;
 case IPSEC_MODE_BEET : return XFRM_MODE_BEET ;
 default : return - 1 ;
 }
 }


 BpOMXObserver(const sp<IBinder> &impl)
 : BpInterface<IOMXObserver>(impl) {
 }


my_object_send_car (MyObject *obj, GValueArray *invals, GValueArray **outvals, GError **error)


bool xmp_files_get_format_info(XmpFileType format,
                               XmpFileFormatOptions *options)
{
    RESET_ERROR;

    bool result = false;
    try {
        result = SXMPFiles::GetFormatInfo(format, (XMP_OptionBits *)options);
    }
    catch (const XMP_Error &e) {
        set_error(e);
        return false;
    }
    return result;
}


int evdns_server_request_respond ( struct evdns_server_request * _req , int err ) {
 struct server_request * req = TO_SERVER_REQUEST ( _req ) ;
 struct evdns_server_port * port = req -> port ;
 int r ;
 if ( ! req -> response ) {
 if ( ( r = evdns_server_request_format_response ( req , err ) ) < 0 ) return r ;
 }
 r = sendto ( port -> socket , req -> response , req -> response_len , 0 , ( struct sockaddr * ) & req -> addr , req -> addrlen ) ;
 if ( r < 0 ) {
 int sock_err = last_error ( port -> socket ) ;
 if ( ! error_is_eagain ( sock_err ) ) return - 1 ;
 if ( port -> pending_replies ) {
 req -> prev_pending = port -> pending_replies -> prev_pending ;
 req -> next_pending = port -> pending_replies ;
 req -> prev_pending -> next_pending = req -> next_pending -> prev_pending = req ;
 }
 else {
 req -> prev_pending = req -> next_pending = req ;
 port -> pending_replies = req ;
 port -> choked = 1 ;
 ( void ) event_del ( & port -> event ) ;
 event_set ( & port -> event , port -> socket , ( port -> closing ? 0 : EV_READ ) | EV_WRITE | EV_PERSIST , server_port_ready_callback , port ) ;
 if ( event_add ( & port -> event , NULL ) < 0 ) {
 log ( EVDNS_LOG_WARN , "Error from libevent when adding event for DNS server" ) ;
 }
 }
 return 1 ;
 }
 if ( server_request_free ( req ) ) return 0 ;
 if ( port -> pending_replies ) server_port_flush ( port ) ;
 return 0 ;
 }


static void pcnet_transmit(PCNetState *s)

{

    hwaddr xmit_cxda = 0;

    int count = CSR_XMTRL(s)-1;

    int add_crc = 0;

    int bcnt;

    s->xmit_pos = -1;

    if (!CSR_TXON(s)) {

        s->csr[0] &= ~0x0008;

        return;

    }

    s->tx_busy = 1;

    txagain:

    if (pcnet_tdte_poll(s)) {

        struct pcnet_TMD tmd;

        TMDLOAD(&tmd, PHYSADDR(s,CSR_CXDA(s)));

#ifdef PCNET_DEBUG_TMD

        printf("  TMDLOAD 0x%08x\n", PHYSADDR(s,CSR_CXDA(s)));

        PRINT_TMD(&tmd);

#endif

        if (GET_FIELD(tmd.status, TMDS, STP)) {

            s->xmit_pos = 0;

            xmit_cxda = PHYSADDR(s,CSR_CXDA(s));

            if (BCR_SWSTYLE(s) != 1)

                add_crc = GET_FIELD(tmd.status, TMDS, ADDFCS);

        }

        if (s->lnkst == 0 &&

            (!CSR_LOOP(s) || (!CSR_INTL(s) && !BCR_TMAULOOP(s)))) {

            SET_FIELD(&tmd.misc, TMDM, LCAR, 1);

            SET_FIELD(&tmd.status, TMDS, ERR, 1);

            SET_FIELD(&tmd.status, TMDS, OWN, 0);

            s->csr[0] |= 0xa000; /* ERR | CERR */

            s->xmit_pos = -1;

            goto txdone;

        }

        if (s->xmit_pos < 0) {

            goto txdone;

        }

        bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT);

        /* if multi-tmd packet outsizes s->buffer then skip it silently.

           Note: this is not what real hw does */

        if (s->xmit_pos + bcnt > sizeof(s->buffer)) {

            s->xmit_pos = -1;

            goto txdone;

        }

        s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr),

                         s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s));

        s->xmit_pos += bcnt;

        if (!GET_FIELD(tmd.status, TMDS, ENP)) {

            goto txdone;

        }

#ifdef PCNET_DEBUG

        printf("pcnet_transmit size=%d\n", s->xmit_pos);

#endif

        if (CSR_LOOP(s)) {

            if (BCR_SWSTYLE(s) == 1)

                add_crc = !GET_FIELD(tmd.status, TMDS, NOFCS);

            s->looptest = add_crc ? PCNET_LOOPTEST_CRC : PCNET_LOOPTEST_NOCRC;

            pcnet_receive(qemu_get_queue(s->nic), s->buffer, s->xmit_pos);

            s->looptest = 0;

        } else {

            if (s->nic) {

                qemu_send_packet(qemu_get_queue(s->nic), s->buffer,

                                 s->xmit_pos);

            }

        }

        s->csr[0] &= ~0x0008;   /* clear TDMD */

        s->csr[4] |= 0x0004;    /* set TXSTRT */

        s->xmit_pos = -1;

    txdone:

        SET_FIELD(&tmd.status, TMDS, OWN, 0);

        TMDSTORE(&tmd, PHYSADDR(s,CSR_CXDA(s)));

        if (!CSR_TOKINTD(s) || (CSR_LTINTEN(s) && GET_FIELD(tmd.status, TMDS, LTINT)))

            s->csr[0] |= 0x0200;    /* set TINT */

        if (CSR_XMTRC(s)<=1)

            CSR_XMTRC(s) = CSR_XMTRL(s);

        else

            CSR_XMTRC(s)--;

        if (count--)

            goto txagain;

    } else

    if (s->xmit_pos >= 0) {

        struct pcnet_TMD tmd;

        TMDLOAD(&tmd, xmit_cxda);

        SET_FIELD(&tmd.misc, TMDM, BUFF, 1);

        SET_FIELD(&tmd.misc, TMDM, UFLO, 1);

        SET_FIELD(&tmd.status, TMDS, ERR, 1);

        SET_FIELD(&tmd.status, TMDS, OWN, 0);

        TMDSTORE(&tmd, xmit_cxda);

        s->csr[0] |= 0x0200;    /* set TINT */

        if (!CSR_DXSUFLO(s)) {

            s->csr[0] &= ~0x0010;

        } else

        if (count--)

          goto txagain;

    }

    s->tx_busy = 0;

}


static int planarRgb16ToRgb16Wrapper(SwsContext *c, const uint8_t *src[],

                                     int srcStride[], int srcSliceY, int srcSliceH,

                                     uint8_t *dst[], int dstStride[])

{

    const uint16_t *src102[] = { (uint16_t *)src[1], (uint16_t *)src[0], (uint16_t *)src[2] };

    const uint16_t *src201[] = { (uint16_t *)src[2], (uint16_t *)src[0], (uint16_t *)src[1] };

    int stride102[] = { srcStride[1], srcStride[0], srcStride[2] };

    int stride201[] = { srcStride[2], srcStride[0], srcStride[1] };

    const AVPixFmtDescriptor *src_format = av_pix_fmt_desc_get(c->srcFormat);

    const AVPixFmtDescriptor *dst_format = av_pix_fmt_desc_get(c->dstFormat);

    int bits_per_sample = src_format->comp[0].depth_minus1 + 1;

    int swap = 0;

    if ( HAVE_BIGENDIAN && !(src_format->flags & AV_PIX_FMT_FLAG_BE) ||

        !HAVE_BIGENDIAN &&   src_format->flags & AV_PIX_FMT_FLAG_BE)

        swap++;

    if ( HAVE_BIGENDIAN && !(dst_format->flags & AV_PIX_FMT_FLAG_BE) ||

        !HAVE_BIGENDIAN &&   dst_format->flags & AV_PIX_FMT_FLAG_BE)

        swap += 2;

    if ((src_format->flags & (AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB)) !=

        (AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB)) {

        av_log(c, AV_LOG_ERROR, "unsupported planar RGB conversion %s -> %s\n",

               src_format->name, dst_format->name);

        return srcSliceH;

    }

    switch (c->dstFormat) {

    case AV_PIX_FMT_BGR48LE:

    case AV_PIX_FMT_BGR48BE:

        gbr16ptopacked16(src102, stride102,

                         dst[0] + srcSliceY * dstStride[0], dstStride[0],

                         srcSliceH, 0, swap, bits_per_sample, c->srcW);

        break;

    case AV_PIX_FMT_RGB48LE:

    case AV_PIX_FMT_RGB48BE:

        gbr16ptopacked16(src201, stride201,

                         dst[0] + srcSliceY * dstStride[0], dstStride[0],

                         srcSliceH, 0, swap, bits_per_sample, c->srcW);

        break;

    case AV_PIX_FMT_RGBA64LE:

    case AV_PIX_FMT_RGBA64BE:

         gbr16ptopacked16(src201, stride201,

                          dst[0] + srcSliceY * dstStride[0], dstStride[0],

                          srcSliceH, 1, swap, bits_per_sample, c->srcW);

        break;

    case AV_PIX_FMT_BGRA64LE:

    case AV_PIX_FMT_BGRA64BE:

        gbr16ptopacked16(src102, stride102,

                         dst[0] + srcSliceY * dstStride[0], dstStride[0],

                         srcSliceH, 1, swap, bits_per_sample, c->srcW);

        break;

    default:

        av_log(c, AV_LOG_ERROR,

               "unsupported planar RGB conversion %s -> %s\n",

               src_format->name, dst_format->name);

    }

    return srcSliceH;

}


GF_Err diST_box_read(GF_Box *s, GF_BitStream *bs)
{
	GF_DIMSScriptTypesBox *p = (GF_DIMSScriptTypesBox *)s;

	p->content_script_types = gf_malloc(sizeof(char) * (s->size+1));
	if (!p->content_script_types) return GF_OUT_OF_MEM;
	gf_bs_read_data(bs, p->content_script_types, s->size);
	p->content_script_types[s->size] = 0;
	return GF_OK;
}


void webkit_web_view_notify_ready(WebKitWebView* webView)
{
    g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView));

    gboolean isHandled = FALSE;
    g_signal_emit(webView, webkit_web_view_signals[WEB_VIEW_READY], 0, &isHandled);
}


static void uivector_init(uivector* p)
{
  p->data = NULL;
  p->size = p->allocsize = 0;
}


int64_t av_get_channel_layout(const char *name)

{

    int i = 0;

    do {

        if (!strcmp(channel_layout_map[i].name, name))

            return channel_layout_map[i].layout;

        i++;

    } while (channel_layout_map[i].name);

    return 0;

}


void NavigationControllerImpl::PruneAllButVisibleInternal() {
  CHECK(CanPruneAllButVisible());

  entries_.erase(entries_.begin(),
                 entries_.begin() + last_committed_entry_index_);
  entries_.erase(entries_.begin() + 1, entries_.end());
  last_committed_entry_index_ = 0;
}


static void sbr_qmf_analysis ( AVFloatDSPContext * dsp , FFTContext * mdct , SBRDSPContext * sbrdsp , const float * in , float * x , float z [ 320 ] , float W [ 2 ] [ 32 ] [ 32 ] [ 2 ] , int buf_idx ) {
 int i ;
 memcpy ( x , x + 1024 , ( 320 - 32 ) * sizeof ( x [ 0 ] ) ) ;
 memcpy ( x + 288 , in , 1024 * sizeof ( x [ 0 ] ) ) ;
 for ( i = 0 ;
 i < 32 ;
 i ++ ) {
 dsp -> vector_fmul_reverse ( z , sbr_qmf_window_ds , x , 320 ) ;
 sbrdsp -> sum64x5 ( z ) ;
 sbrdsp -> qmf_pre_shuffle ( z ) ;
 mdct -> imdct_half ( mdct , z , z + 64 ) ;
 sbrdsp -> qmf_post_shuffle ( W [ buf_idx ] [ i ] , z ) ;
 x += 32 ;
 }
 }


static int ath_max_framelen(int usec, int mcs, bool ht40, bool sgi)
{
	int streams = HT_RC_2_STREAMS(mcs);
	int symbols, bits;
	int bytes = 0;

	symbols = sgi ? TIME_SYMBOLS_HALFGI(usec) : TIME_SYMBOLS(usec);
	bits = symbols * bits_per_symbol[mcs % 8][ht40] * streams;
	bits -= OFDM_PLCP_BITS;
	bytes = bits / 8;
	bytes -= L_STF + L_LTF + L_SIG + HT_SIG + HT_STF + HT_LTF(streams);
	if (bytes > 65532)
		bytes = 65532;

	return bytes;
}


void ndp_msgra_router_lifetime_set(struct ndp_msgra *msgra,
				   uint16_t router_lifetime)
{
	msgra->ra->nd_ra_router_lifetime = htons(router_lifetime);
}


QString Utility::URLEncodePath(const QString &path)
{
    QString newpath = path;
    QUrl href = QUrl(newpath);
    QString scheme = href.scheme();
    if (!scheme.isEmpty()) {
        scheme = scheme + "://";
        newpath.remove(0, scheme.length());
    }
    QByteArray encoded_url = QUrl::toPercentEncoding(newpath, QByteArray("/#"));
    return scheme + QString::fromUtf8(encoded_url.constData(), encoded_url.count());
}


static bool cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(bool)val; }


static ssize_t net_rx_packet(NetClientState *nc, const uint8_t *buf, size_t size)

{

    struct XenNetDev *netdev = qemu_get_nic_opaque(nc);

    netif_rx_request_t rxreq;

    RING_IDX rc, rp;

    void *page;

    if (netdev->xendev.be_state != XenbusStateConnected) {

        return -1;

    }

    rc = netdev->rx_ring.req_cons;

    rp = netdev->rx_ring.sring->req_prod;

    xen_rmb(); /* Ensure we see queued requests up to 'rp'. */

    if (rc == rp || RING_REQUEST_CONS_OVERFLOW(&netdev->rx_ring, rc)) {

        xen_be_printf(&netdev->xendev, 2, "no buffer, drop packet\n");

        return -1;

    }

    if (size > XC_PAGE_SIZE - NET_IP_ALIGN) {

        xen_be_printf(&netdev->xendev, 0, "packet too big (%lu > %ld)",

                      (unsigned long)size, XC_PAGE_SIZE - NET_IP_ALIGN);

        return -1;

    }

    memcpy(&rxreq, RING_GET_REQUEST(&netdev->rx_ring, rc), sizeof(rxreq));

    netdev->rx_ring.req_cons = ++rc;

    page = xc_gnttab_map_grant_ref(netdev->xendev.gnttabdev,

                                   netdev->xendev.dom,

                                   rxreq.gref, PROT_WRITE);

    if (page == NULL) {

        xen_be_printf(&netdev->xendev, 0, "error: rx gref dereference failed (%d)\n",

                      rxreq.gref);

        net_rx_response(netdev, &rxreq, NETIF_RSP_ERROR, 0, 0, 0);

        return -1;

    }

    memcpy(page + NET_IP_ALIGN, buf, size);

    xc_gnttab_munmap(netdev->xendev.gnttabdev, page, 1);

    net_rx_response(netdev, &rxreq, NETIF_RSP_OKAY, NET_IP_ALIGN, size, 0);

    return size;

}


  virtual TabContentsWrapper* AddBlankTabAt(int index, bool foreground) {
    return NULL;
  }


int nghttp2_session_add_rst_stream(nghttp2_session *session, int32_t stream_id,
                                   uint32_t error_code) {
  int rv;
  nghttp2_outbound_item *item;
  nghttp2_frame *frame;
  nghttp2_stream *stream;
  nghttp2_mem *mem;

  mem = &session->mem;
  stream = nghttp2_session_get_stream(session, stream_id);
  if (stream && stream->state == NGHTTP2_STREAM_CLOSING) {
    return 0;
  }

  /* Cancel pending request HEADERS in ob_syn if this RST_STREAM
     refers to that stream. */
  if (!session->server && nghttp2_session_is_my_stream_id(session, stream_id) &&
      nghttp2_outbound_queue_top(&session->ob_syn)) {
    nghttp2_headers_aux_data *aux_data;
    nghttp2_frame *headers_frame;

    headers_frame = &nghttp2_outbound_queue_top(&session->ob_syn)->frame;
    assert(headers_frame->hd.type == NGHTTP2_HEADERS);

    if (headers_frame->hd.stream_id <= stream_id &&
        (uint32_t)stream_id < session->next_stream_id) {

      for (item = session->ob_syn.head; item; item = item->qnext) {
        aux_data = &item->aux_data.headers;

        if (item->frame.hd.stream_id < stream_id) {
          continue;
        }

        /* stream_id in ob_syn queue must be strictly increasing.  If
           we found larger ID, then we can break here. */
        if (item->frame.hd.stream_id > stream_id || aux_data->canceled) {
          break;
        }

        aux_data->error_code = error_code;
        aux_data->canceled = 1;

        return 0;
      }
    }
  }

  item = nghttp2_mem_malloc(mem, sizeof(nghttp2_outbound_item));
  if (item == NULL) {
    return NGHTTP2_ERR_NOMEM;
  }

  nghttp2_outbound_item_init(item);

  frame = &item->frame;

  nghttp2_frame_rst_stream_init(&frame->rst_stream, stream_id, error_code);
  rv = nghttp2_session_add_item(session, item);
  if (rv != 0) {
    nghttp2_frame_rst_stream_free(&frame->rst_stream);
    nghttp2_mem_free(mem, item);
    return rv;
  }
  return 0;
}


static const command_t *find_command(const char *name) {
 for (size_t i = 0; i < ARRAY_SIZE(commands); ++i)
 if (!strcmp(commands[i].name, name))
 return &commands[i];
 return NULL;
}


    uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
    {
        AssertMsg(this->head, "array head should never be null");
        uint candidateIndex;

        if (index == JavascriptArray::InvalidIndex)
        {
            candidateIndex = head->left;
        }
        else
        {
            candidateIndex = index + 1;
        }

        SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);

        while (current != nullptr)
        {
            if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
            {
                for (uint i = candidateIndex - current->left; i < current->length; i++)
                {
                    if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
                    {
                        return i + current->left;
                    }
                }
            }
            current = (SparseArraySegment<T>*)current->next;
            if (current != NULL)
            {
                if (candidateIndex < current->left)
                {
                    candidateIndex = current->left;
                }
            }
        }
        return JavascriptArray::InvalidIndex;
    }


bool CPlayListPLS::Load(const std::string &strFile)
{
  //read it from the file
  std::string strFileName(strFile);
  m_strPlayListName = URIUtils::GetFileName(strFileName);

  Clear();

  bool bShoutCast = false;
  if( StringUtils::StartsWithNoCase(strFileName, "shout://") )
  {
    strFileName.replace(0, 8, "http://");
    m_strBasePath = "";
    bShoutCast = true;
  }
  else
    URIUtils::GetParentPath(strFileName, m_strBasePath);

  CFile file;
  if (!file.Open(strFileName) )
  {
    file.Close();
    return false;
  }

  if (file.GetLength() > 1024*1024)
  {
    CLog::Log(LOGWARNING, "{} - File is larger than 1 MB, most likely not a playlist",
              __FUNCTION__);
    return false;
  }

  char szLine[4096];
  std::string strLine;

  // run through looking for the [playlist] marker.
  // if we find another http stream, then load it.
  while (true)
  {
    if ( !file.ReadString(szLine, sizeof(szLine) ) )
    {
      file.Close();
      return size() > 0;
    }
    strLine = szLine;
    StringUtils::Trim(strLine);
    if(StringUtils::EqualsNoCase(strLine, START_PLAYLIST_MARKER))
      break;

    // if there is something else before playlist marker, this isn't a pls file
    if(!strLine.empty())
      return false;
  }

  bool bFailed = false;
  while (file.ReadString(szLine, sizeof(szLine) ) )
  {
    strLine = szLine;
    StringUtils::RemoveCRLF(strLine);
    size_t iPosEqual = strLine.find('=');
    if (iPosEqual != std::string::npos)
    {
      std::string strLeft = strLine.substr(0, iPosEqual);
      iPosEqual++;
      std::string strValue = strLine.substr(iPosEqual);
      StringUtils::ToLower(strLeft);
      StringUtils::TrimLeft(strLeft);

      if (strLeft == "numberofentries")
      {
        m_vecItems.reserve(atoi(strValue.c_str()));
      }
      else if (StringUtils::StartsWith(strLeft, "file"))
      {
        std::vector <int>::size_type idx = atoi(strLeft.c_str() + 4);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }

        // Skip self - do not load playlist recursively
        if (StringUtils::EqualsNoCase(URIUtils::GetFileName(strValue),
                                      URIUtils::GetFileName(strFileName)))
          continue;

        if (m_vecItems[idx - 1]->GetLabel().empty())
          m_vecItems[idx - 1]->SetLabel(URIUtils::GetFileName(strValue));
        CFileItem item(strValue, false);
        if (bShoutCast && !item.IsAudio())
          strValue.replace(0, 7, "shout://");

        strValue = URIUtils::SubstitutePath(strValue);
        CUtil::GetQualifiedFilename(m_strBasePath, strValue);
        g_charsetConverter.unknownToUTF8(strValue);
        m_vecItems[idx - 1]->SetPath(strValue);
      }
      else if (StringUtils::StartsWith(strLeft, "title"))
      {
        std::vector <int>::size_type idx = atoi(strLeft.c_str() + 5);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }
        g_charsetConverter.unknownToUTF8(strValue);
        m_vecItems[idx - 1]->SetLabel(strValue);
      }
      else if (StringUtils::StartsWith(strLeft, "length"))
      {
        std::vector <int>::size_type idx = atoi(strLeft.c_str() + 6);
        if (!Resize(idx))
        {
          bFailed = true;
          break;
        }
        m_vecItems[idx - 1]->GetMusicInfoTag()->SetDuration(atol(strValue.c_str()));
      }
      else if (strLeft == "playlistname")
      {
        m_strPlayListName = strValue;
        g_charsetConverter.unknownToUTF8(m_strPlayListName);
      }
    }
  }
  file.Close();

  if (bFailed)
  {
    CLog::Log(LOGERROR,
              "File {} is not a valid PLS playlist. Location of first file,title or length is not "
              "permitted (eg. File0 should be File1)",
              URIUtils::GetFileName(strFileName));
    return false;
  }

  // check for missing entries
  ivecItems p = m_vecItems.begin();
  while ( p != m_vecItems.end())
  {
    if ((*p)->GetPath().empty())
    {
      p = m_vecItems.erase(p);
    }
    else
    {
      ++p;
    }
  }

  return true;
}


int posix_cpu_clock_getres(const clockid_t which_clock, struct timespec *tp)
{
	int error = check_clock(which_clock);
	if (!error) {
		tp->tv_sec = 0;
		tp->tv_nsec = ((NSEC_PER_SEC + HZ - 1) / HZ);
		if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {
			/*
			 * If sched_clock is using a cycle counter, we
			 * don't have any idea of its true resolution
			 * exported, but it is much more than 1s/HZ.
			 */
			tp->tv_nsec = 1;
		}
	}
	return error;
}


void FrameLoader::Trace(blink::Visitor* visitor) {
  visitor->Trace(frame_);
   visitor->Trace(progress_tracker_);
   visitor->Trace(document_loader_);
   visitor->Trace(provisional_document_loader_);
  visitor->Trace(last_origin_document_);
 }


dwg_decode_common_entity_handle_data (Bit_Chain *dat, Bit_Chain *hdl_dat,
                                      Dwg_Object *restrict obj)
{

  Dwg_Data *dwg = obj->parent;
  Dwg_Object_Entity *_obj, *_ent;
  BITCODE_BL vcount;
  int error = 0;

  _obj = _ent = obj->tio.entity;

  // deferred from common_entity_data, which has no hdl_dat
  if (dat->version >= R_2007 && _ent->color.flag & 0x40)
    FIELD_HANDLE (color.handle, 0, 430);

    // clang-format off
  #include "common_entity_handle_data.spec"
  // clang-format on

  return error;
}


void AudioContext::fireCompletionEvent()
{
    ASSERT(isMainThread());
    if (!isMainThread())
        return;

    AudioBuffer* renderedBuffer = m_renderTarget.get();

    setContextState(Closed);

    ASSERT(renderedBuffer);
    if (!renderedBuffer)
        return;

    if (executionContext()) {
        dispatchEvent(OfflineAudioCompletionEvent::create(renderedBuffer));
        m_offlineResolver->resolve(renderedBuffer);
    }
}


static void ShiftMetaOffset(GF_MetaBox *meta, u64 offset)
{
	u32 i, count;
	if (!meta->item_locations) return;

	count = gf_list_count(meta->item_locations->location_entries);
	for (i=0; i<count; i++) {
		GF_ItemLocationEntry *iloc = (GF_ItemLocationEntry *)gf_list_get(meta->item_locations->location_entries, i);
		if (iloc->data_reference_index) continue;
		if (iloc->construction_method == 2) continue;
		if (!iloc->base_offset) {
			GF_ItemExtentEntry *entry = (GF_ItemExtentEntry *)gf_list_get(iloc->extent_entries, 0);
			if (entry && !entry->extent_length && !entry->original_extent_offset && (gf_list_count(iloc->extent_entries)==1) )
				continue;
		}

		iloc->base_offset += offset;
	}
}


vmnc_fill_buffer (GstVMncDec * dec, GstVideoCodecFrame * frame)
{
  GstFlowReturn ret;
  GstMapInfo map;

  ret =
      gst_video_decoder_allocate_output_frame (GST_VIDEO_DECODER (dec), frame);
  if (ret != GST_FLOW_OK)
    return ret;

  gst_buffer_map (frame->output_buffer, &map, GST_MAP_READWRITE);

  memcpy (map.data, dec->imagedata, map.size);

  if (dec->cursor.visible)
    render_cursor (dec, map.data);

  gst_buffer_unmap (frame->output_buffer, &map);

  return GST_FLOW_OK;
}


openscript(
    char_u	*name,
    int		directly)	// when TRUE execute directly
{
    if (curscript + 1 == NSCRIPT)
    {
	emsg(_(e_scripts_nested_too_deep));
	return;
    }

    // Disallow sourcing a file in the sandbox, the commands would be executed
    // later, possibly outside of the sandbox.
    if (check_secure())
	return;

#ifdef FEAT_EVAL
    if (ignore_script)
	// Not reading from script, also don't open one.  Warning message?
	return;
#endif

    if (scriptin[curscript] != NULL)	// already reading script
	++curscript;
				// use NameBuff for expanded name
    expand_env(name, NameBuff, MAXPATHL);
    if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
    {
	semsg(_(e_cant_open_file_str), name);
	if (curscript)
	    --curscript;
	return;
    }
    if (save_typebuf() == FAIL)
	return;

    /*
     * Execute the commands from the file right now when using ":source!"
     * after ":global" or ":argdo" or in a loop.  Also when another command
     * follows.  This means the display won't be updated.  Don't do this
     * always, "make test" would fail.
     */
    if (directly)
    {
	oparg_T	oa;
	int	oldcurscript;
	int	save_State = State;
	int	save_restart_edit = restart_edit;
	int	save_insertmode = p_im;
	int	save_finish_op = finish_op;
	int	save_msg_scroll = msg_scroll;

	State = NORMAL;
	msg_scroll = FALSE;	// no msg scrolling in Normal mode
	restart_edit = 0;	// don't go to Insert mode
	p_im = FALSE;		// don't use 'insertmode'
	clear_oparg(&oa);
	finish_op = FALSE;

	oldcurscript = curscript;
	do
	{
	    update_topline_cursor();	// update cursor position and topline
	    normal_cmd(&oa, FALSE);	// execute one command
	    (void)vpeekc();		// check for end of file
	}
	while (scriptin[oldcurscript] != NULL);

	State = save_State;
	msg_scroll = save_msg_scroll;
	restart_edit = save_restart_edit;
	p_im = save_insertmode;
	finish_op = save_finish_op;
    }
}


void ContentLine_Analyzer::EndpointEOF(bool is_orig)
	{
	if ( offset > 0 )
		DeliverStream(1, (const u_char*) "\n", is_orig);
	}


ksba_name_enum (ksba_name_t name, int idx)
{
  if (!name || idx < 0)
    return NULL;
  if (idx >= name->n_names)
    return NULL;  /* end of list */

  return name->names[idx];
}


error::Error GLES2DecoderPassthroughImpl::DoDepthRangef(GLclampf zNear,
                                                        GLclampf zFar) {
  api()->glDepthRangefFn(zNear, zFar);
  return error::kNoError;
}


static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
                            PRIntn flags, PRIntervalTime timeout)
{
  const PRSendFN send_fn = fd->lower->methods->send;
  const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
  if(rv < 0)
    /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
    nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
  return rv;
}


TEST_P(TcpTunnelingIntegrationTest, ResetStreamTest) {
  if (upstreamProtocol() == Http::CodecType::HTTP1) {
    return;
  }
  enableHalfClose(false);
  initialize();

  setUpConnection(fake_upstream_connection_);

  // Reset the stream.
  upstream_request_->encodeResetStream();
  tcp_client_->waitForDisconnect();
}


static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
{
    AVIOContext *pb = s->pb;
    ASFContext *asf = s->priv_data;
    int desc_count, i, ret;

    desc_count = avio_rl16(pb);
    for (i = 0; i < desc_count; i++) {
        int name_len, value_type, value_len;
        char name[1024];

        name_len = avio_rl16(pb);
        if (name_len % 2)   // must be even, broken lavf versions wrote len-1
            name_len += 1;
        if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
            avio_skip(pb, name_len - ret);
        value_type = avio_rl16(pb);
        value_len  = avio_rl16(pb);
        if (!value_type && value_len % 2)
            value_len += 1;
        /* My sample has that stream set to 0 maybe that mean the container.
         * ASF stream count starts at 1. I am using 0 to the container value
         * since it's unused. */
        if (!strcmp(name, "AspectRatioX"))
            asf->dar[0].num = get_value(s->pb, value_type, 32);
        else if (!strcmp(name, "AspectRatioY"))
            asf->dar[0].den = get_value(s->pb, value_type, 32);
        else
            get_tag(s, name, value_type, value_len, 32);
    }

    return 0;
}


void WebGLRenderingContextBase::MaybeRestoreContext(TimerBase*) {
  DCHECK(isContextLost());

  if (!restore_allowed_)
    return;

  if (canvas()) {
    LocalFrame* frame = canvas()->GetDocument().GetFrame();
    if (!frame)
      return;
    if (frame->Client()->ShouldBlockWebGL())
      return;

    Settings* settings = frame->GetSettings();
    if (settings && ((version_ == 1 && !settings->GetWebGL1Enabled()) ||
                     (version_ == 2 && !settings->GetWebGL2Enabled()))) {
      return;
    }
  }

  DCHECK(!GetDrawingBuffer());

  auto* execution_context = Host()->GetTopExecutionContext();
  Platform::ContextAttributes attributes = ToPlatformContextAttributes(
      CreationAttributes(), Version(),
      SupportOwnOffscreenSurface(execution_context));
  Platform::GraphicsInfo gl_info;
  std::unique_ptr<WebGraphicsContext3DProvider> context_provider;
  bool using_gpu_compositing;
  const auto& url = Host()->GetExecutionContextUrl();

  if (IsMainThread()) {
    using_gpu_compositing = !Platform::Current()->IsGpuCompositingDisabled();
    context_provider =
        Platform::Current()->CreateOffscreenGraphicsContext3DProvider(
            attributes, url, &gl_info);
  } else {
    context_provider = CreateContextProviderOnWorkerThread(
        attributes, &gl_info, &using_gpu_compositing, url);
  }
  scoped_refptr<DrawingBuffer> buffer;
  if (context_provider && context_provider->BindToCurrentThread()) {
    buffer =
        CreateDrawingBuffer(std::move(context_provider), using_gpu_compositing);
  }
  if (!buffer) {
    if (context_lost_mode_ == kRealLostContext) {
      restore_timer_.StartOneShot(kSecondsBetweenRestoreAttempts, FROM_HERE);
    } else {
      SynthesizeGLError(GL_INVALID_OPERATION, "", "error restoring context");
    }
    return;
  }

  drawing_buffer_ = std::move(buffer);
  GetDrawingBuffer()->Bind(GL_FRAMEBUFFER);
  lost_context_errors_.clear();
  context_lost_mode_ = kNotLostContext;
  auto_recovery_method_ = kManual;
  restore_allowed_ = false;
  RemoveFromEvictedList(this);

  SetupFlags();
  InitializeNewContext();
  MarkContextChanged(kCanvasContextChanged);
  WebGLContextEvent* event =
      WebGLContextEvent::Create(EventTypeNames::webglcontextrestored, "");
  Host()->HostDispatchEvent(event);
}


__be32 nfsd4_set_nfs4_label(struct svc_rqst *rqstp, struct svc_fh *fhp,
		struct xdr_netobj *label)
{
	return nfserr_notsupp;
}


void CSoundFile::AdjustSampleLoop(MODINSTRUMENT *pIns)
{
	if (!pIns->pSample) return;
	if (pIns->nLoopEnd > pIns->nLength) pIns->nLoopEnd = pIns->nLength;
	if (pIns->nLoopStart+2 >= pIns->nLoopEnd)
	{
		pIns->nLoopStart = pIns->nLoopEnd = 0;
		pIns->uFlags &= ~CHN_LOOP;
	}
	UINT len = pIns->nLength;
	if (pIns->uFlags & CHN_16BIT)
	{
		short int *pSample = (short int *)pIns->pSample;
		if (pIns->uFlags & CHN_STEREO)
		{
			pSample[len*2+6] = pSample[len*2+4] = pSample[len*2+2] = pSample[len*2] = pSample[len*2-2];
			pSample[len*2+7] = pSample[len*2+5] = pSample[len*2+3] = pSample[len*2+1] = pSample[len*2-1];
		} else
		{
			pSample[len+4] = pSample[len+3] = pSample[len+2] = pSample[len+1] = pSample[len] = pSample[len-1];
		}
		if ((pIns->uFlags & (CHN_LOOP|CHN_PINGPONGLOOP|CHN_STEREO)) == CHN_LOOP)
		{
			if ((pIns->nLoopEnd+3 >= pIns->nLength) || (m_nType & MOD_TYPE_S3M))
			{
				pSample[pIns->nLoopEnd] = pSample[pIns->nLoopStart];
				pSample[pIns->nLoopEnd+1] = pSample[pIns->nLoopStart+1];
				pSample[pIns->nLoopEnd+2] = pSample[pIns->nLoopStart+2];
				pSample[pIns->nLoopEnd+3] = pSample[pIns->nLoopStart+3];
				pSample[pIns->nLoopEnd+4] = pSample[pIns->nLoopStart+4];
			}
		}
	} else
	{
		signed char *pSample = pIns->pSample;
#ifndef FASTSOUNDLIB
		if ((pIns->nLength > 0x100) && (m_nType & (MOD_TYPE_MOD|MOD_TYPE_S3M))
		 && (!(pIns->uFlags & CHN_STEREO)))
		{
			int smpend = pSample[pIns->nLength-1], smpfix = 0, kscan;
			for (kscan=pIns->nLength-1; kscan>0; kscan--)
			{
				smpfix = pSample[kscan-1];
				if (smpfix != smpend) break;
			}
			int delta = smpfix - smpend;
			if (((!(pIns->uFlags & CHN_LOOP)) || (kscan > (int)pIns->nLoopEnd))
			 && ((delta < -8) || (delta > 8)))
			{
				while (kscan<(int)pIns->nLength)
				{
					if (!(kscan & 7))
					{
						if (smpfix > 0) smpfix--;
						if (smpfix < 0) smpfix++;
					}
					pSample[kscan] = (signed char)smpfix;
					kscan++;
				}
			}
		}
#endif
		if (pIns->uFlags & CHN_STEREO)
		{
			pSample[len*2+6] = pSample[len*2+4] = pSample[len*2+2] = pSample[len*2] = pSample[len*2-2];
			pSample[len*2+7] = pSample[len*2+5] = pSample[len*2+3] = pSample[len*2+1] = pSample[len*2-1];
		} else
		{
			pSample[len+4] = pSample[len+3] = pSample[len+2] = pSample[len+1] = pSample[len] = pSample[len-1];
		}
		if ((pIns->uFlags & (CHN_LOOP|CHN_PINGPONGLOOP|CHN_STEREO)) == CHN_LOOP)
		{
			if ((pIns->nLoopEnd+3 >= pIns->nLength) || (m_nType & (MOD_TYPE_MOD|MOD_TYPE_S3M)))
			{
				pSample[pIns->nLoopEnd] = pSample[pIns->nLoopStart];
				pSample[pIns->nLoopEnd+1] = pSample[pIns->nLoopStart+1];
				pSample[pIns->nLoopEnd+2] = pSample[pIns->nLoopStart+2];
				pSample[pIns->nLoopEnd+3] = pSample[pIns->nLoopStart+3];
				pSample[pIns->nLoopEnd+4] = pSample[pIns->nLoopStart+4];
			}
		}
	}
}


cmsBool CMSEXPORT cmsMLUsetASCII(cmsMLU* mlu, const char LanguageCode[3], const char CountryCode[3], const char* ASCIIString)
{
    cmsUInt32Number i, len = (cmsUInt32Number) strlen(ASCIIString)+1;
    wchar_t* WStr;
    cmsBool  rc;
    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);

    if (mlu == NULL) return FALSE;

    WStr = (wchar_t*) _cmsCalloc(mlu ->ContextID, len,  sizeof(wchar_t));
    if (WStr == NULL) return FALSE;

    for (i=0; i < len; i++)
        WStr[i] = (wchar_t) ASCIIString[i];

    rc = AddMLUBlock(mlu, len  * sizeof(wchar_t), WStr, Lang, Cntry);

    _cmsFree(mlu ->ContextID, WStr);
    return rc;

}


isoent_make_sorted_files(struct archive_write *a, struct isoent *isoent,
    struct idr *idr)
{
	struct archive_rb_node *rn;
	struct isoent **children;

	children = malloc(isoent->children.cnt * sizeof(struct isoent *));
	if (children == NULL) {
		archive_set_error(&a->archive, ENOMEM,
		    "Can't allocate memory");
		return (ARCHIVE_FATAL);
	}
	isoent->children_sorted = children;

	ARCHIVE_RB_TREE_FOREACH(rn, &(idr->rbtree)) {
		struct idrent *idrent = (struct idrent *)rn;
		*children ++ = idrent->isoent;
	}
	return (ARCHIVE_OK);
}


void Browser::CrashedPluginHelper(TabContents* tab,
                                  const FilePath& plugin_path) {
  TabContentsWrapper* tcw = TabContentsWrapper::GetCurrentWrapperForContents(
      tab);
  if (!tcw)
    return;

  DCHECK(!plugin_path.value().empty());

  string16 plugin_name = plugin_path.LossyDisplayName();
  webkit::WebPluginInfo plugin_info;
  if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(
          plugin_path, &plugin_info) &&
      !plugin_info.name.empty()) {
    plugin_name = plugin_info.name;
#if defined(OS_MACOSX)
    const std::string kPluginExtension = ".plugin";
    if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))
      plugin_name.erase(plugin_name.length() - kPluginExtension.length());
#endif  // OS_MACOSX
  }
  gfx::Image* icon = &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
      IDR_INFOBAR_PLUGIN_CRASHED);
  tcw->infobar_tab_helper()->AddInfoBar(
      new SimpleAlertInfoBarDelegate(
          tab,
          icon,
          l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
          true));
}


void gf_isom_video_sample_entry_write(GF_VisualSampleEntryBox *ptr, GF_BitStream *bs)
{
	gf_bs_write_data(bs, ptr->reserved, 6);
	gf_bs_write_u16(bs, ptr->dataReferenceIndex);

	gf_bs_write_u16(bs, ptr->version);
	gf_bs_write_u16(bs, ptr->revision);
	gf_bs_write_u32(bs, ptr->vendor);
	gf_bs_write_u32(bs, ptr->temporal_quality);
	gf_bs_write_u32(bs, ptr->spatial_quality);
	gf_bs_write_u16(bs, ptr->Width);
	gf_bs_write_u16(bs, ptr->Height);
	gf_bs_write_u32(bs, ptr->horiz_res);
	gf_bs_write_u32(bs, ptr->vert_res);
	gf_bs_write_u32(bs, ptr->entry_data_size);
	gf_bs_write_u16(bs, ptr->frames_per_sample);
	gf_bs_write_data(bs, ptr->compressor_name, 32);
	gf_bs_write_u16(bs, ptr->bit_depth);
	gf_bs_write_u16(bs, ptr->color_table_index);

	if (gf_sys_old_arch_compat()) {
		//patch for old export
		GF_Box *clap = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_CLAP);
		GF_Box *pasp = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_PASP);
		GF_Box *colr = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_COLR);
		GF_Box *mdcv = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_MDCV);
		GF_Box *clli = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_CLLI);
		GF_Box *ccst = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_CCST);
		GF_Box *auxi = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_AUXI);
		GF_Box *rvcc = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_RVCC);
		GF_Box *sinf = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_SINF);
		GF_Box *btrt = gf_isom_box_find_child(ptr->child_boxes, GF_ISOM_BOX_TYPE_BTRT);
		GF_Box *fiel = gf_isom_box_find_child(ptr->child_boxes, GF_QT_BOX_TYPE_FIEL);
		GF_Box *gamma = gf_isom_box_find_child(ptr->child_boxes, GF_QT_BOX_TYPE_GAMA);

		if (clap) {
			gf_list_del_item(ptr->child_boxes, clap);
			gf_list_add(ptr->child_boxes, clap);
		}
		if (pasp) {
			gf_list_del_item(ptr->child_boxes, pasp);
			gf_list_add(ptr->child_boxes, pasp);
		}
		if (colr) {
			gf_list_del_item(ptr->child_boxes, colr);
			gf_list_add(ptr->child_boxes, colr);
		}
		if (fiel) {
			gf_list_del_item(ptr->child_boxes, fiel);
			gf_list_add(ptr->child_boxes, fiel);
		}
		if (gamma) {
			gf_list_del_item(ptr->child_boxes, gamma);
			gf_list_add(ptr->child_boxes, gamma);
		}
		if (mdcv) {
			gf_list_del_item(ptr->child_boxes, mdcv);
			gf_list_add(ptr->child_boxes, mdcv);
		}
		if (clli) {
			gf_list_del_item(ptr->child_boxes, clli);
			gf_list_add(ptr->child_boxes, clli);
		}
		if (ccst) {
			gf_list_del_item(ptr->child_boxes, ccst);
			gf_list_add(ptr->child_boxes, ccst);
		}
		if (auxi) {
			gf_list_del_item(ptr->child_boxes, auxi);
			gf_list_add(ptr->child_boxes, auxi);
		}
		if (rvcc) {
			gf_list_del_item(ptr->child_boxes, rvcc);
			gf_list_add(ptr->child_boxes, rvcc);
		}
		if (sinf) {
			gf_list_del_item(ptr->child_boxes, sinf);
			gf_list_add(ptr->child_boxes, sinf);
		}
		if (btrt) {
			gf_list_del_item(ptr->child_boxes, btrt);
			gf_list_add(ptr->child_boxes, btrt);
		}
	}

}


void ImageLoader::RejectPendingDecodes(UpdateType update_type) {
  for (auto* it = decode_requests_.begin(); it != decode_requests_.end();) {
    auto& request = *it;
    if (update_type == UpdateType::kAsync &&
        request->state() == DecodeRequest::kPendingMicrotask) {
      ++it;
      continue;
    }
    request->Reject();
    it = decode_requests_.erase(it);
  }
}


void RenderViewHostImpl::OnTakeFocus(bool reverse) {
  RenderViewHostDelegateView* view = delegate_->GetDelegateView();
  if (view)
    view->TakeFocus(reverse);
}


URLRegistry& Blob::registry() const
{
    return BlobURLRegistry::registry();
}


static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
                             struct mschmd_header *chm, int entire)
{
  unsigned int section, name_len, x, errors, num_chunks;
  unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
  struct mschmd_file *fi, *link = NULL;
  off_t offset, length;
  int num_entries;

  /* initialise pointers */
  chm->files         = NULL;
  chm->sysfiles      = NULL;
  chm->chunk_cache   = NULL;
  chm->sec0.base.chm = chm;
  chm->sec0.base.id  = 0;
  chm->sec1.base.chm = chm;
  chm->sec1.base.id  = 1;
  chm->sec1.content  = NULL;
  chm->sec1.control  = NULL;
  chm->sec1.spaninfo = NULL;
  chm->sec1.rtable   = NULL;

  /* read the first header */
  if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
    return MSPACK_ERR_READ;
  }

  /* check ITSF signature */
  if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
    return MSPACK_ERR_SIGNATURE;
  }

  /* check both header GUIDs */
  if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
    D(("incorrect GUIDs"))
    return MSPACK_ERR_SIGNATURE;
  }

  chm->version   = EndGetI32(&buf[chmhead_Version]);
  chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
  chm->language  = EndGetI32(&buf[chmhead_LanguageID]);
  if (chm->version > 3) {
    sys->message(fh, "WARNING; CHM version > 3");
  }

  /* read the header section table */
  if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
    return MSPACK_ERR_READ;
  }

  /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
   * The offset will be corrected later, once HS1 is read.
   */
  if (read_off64(&offset,           &buf[chmhst_OffsetHS0],  sys, fh) ||
      read_off64(&chm->dir_offset,  &buf[chmhst_OffsetHS1],  sys, fh) ||
      read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
  {
    return MSPACK_ERR_DATAFORMAT;
  }

  /* seek to header section 0 */
  if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
    return MSPACK_ERR_SEEK;
  }

  /* read header section 0 */
  if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
    return MSPACK_ERR_READ;
  }
  if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
    return MSPACK_ERR_DATAFORMAT;
  }

  /* seek to header section 1 */
  if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
    return MSPACK_ERR_SEEK;
  }

  /* read header section 1 */
  if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
    return MSPACK_ERR_READ;
  }

  chm->dir_offset = sys->tell(fh);
  chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
  chm->density    = EndGetI32(&buf[chmhs1_Density]);
  chm->depth      = EndGetI32(&buf[chmhs1_Depth]);
  chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
  chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
  chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
  chm->last_pmgl  = EndGetI32(&buf[chmhs1_LastPMGL]);

  if (chm->version < 3) {
    /* versions before 3 don't have chmhst3_OffsetCS0 */
    chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
  }

  /* check if content offset or file size is wrong */
  if (chm->sec0.offset > chm->length) {
    D(("content section begins after file has ended"))
    return MSPACK_ERR_DATAFORMAT;
  }

  /* ensure there are chunks and that chunk size is
   * large enough for signature and num_entries */
  if (chm->chunk_size < (pmgl_Entries + 2)) {
    D(("chunk size not large enough"))
    return MSPACK_ERR_DATAFORMAT;
  }
  if (chm->num_chunks == 0) {
    D(("no chunks"))
    return MSPACK_ERR_DATAFORMAT;
  }

  /* The chunk_cache data structure is not great; large values for num_chunks
   * or num_chunks*chunk_size can exhaust all memory. Until a better chunk
   * cache is implemented, put arbitrary limits on num_chunks and chunk size.
   */
  if (chm->num_chunks > 100000) {
    D(("more than 100,000 chunks"))
    return MSPACK_ERR_DATAFORMAT;
  }
  if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
    D(("chunks larger than entire file"))
    return MSPACK_ERR_DATAFORMAT;
  }

  /* common sense checks on header section 1 fields */
  if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
    sys->message(fh, "WARNING; chunk size is not a power of two");
  }
  if (chm->first_pmgl != 0) {
    sys->message(fh, "WARNING; first PMGL chunk is not zero");
  }
  if (chm->first_pmgl > chm->last_pmgl) {
    D(("first pmgl chunk is after last pmgl chunk"))
    return MSPACK_ERR_DATAFORMAT;
  }
  if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
    D(("index_root outside valid range"))
    return MSPACK_ERR_DATAFORMAT;
  }

  /* if we are doing a quick read, stop here! */
  if (!entire) {
    return MSPACK_ERR_OK;
  }

  /* seek to the first PMGL chunk, and reduce the number of chunks to read */
  if ((x = chm->first_pmgl) != 0) {
    if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
      return MSPACK_ERR_SEEK;
    }
  }
  num_chunks = chm->last_pmgl - x + 1;

  if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
    return MSPACK_ERR_NOMEMORY;
  }

  /* read and process all chunks from FirstPMGL to LastPMGL */
  errors = 0;
  while (num_chunks--) {
    /* read next chunk */
    if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
      sys->free(chunk);
      return MSPACK_ERR_READ;
    }

    /* process only directory (PMGL) chunks */
    if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;

    if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
      sys->message(fh, "WARNING; PMGL quickref area is too small");
    }
    if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
        ((int)chm->chunk_size - pmgl_Entries))
    {
      sys->message(fh, "WARNING; PMGL quickref area is too large");
    }

    p = &chunk[pmgl_Entries];
    end = &chunk[chm->chunk_size - 2];
    num_entries = EndGetI16(end);

    while (num_entries--) {
      READ_ENCINT(name_len);
      if (name_len > (unsigned int) (end - p)) goto chunk_end;
      name = p; p += name_len;
      READ_ENCINT(section);
      READ_ENCINT(offset);
      READ_ENCINT(length);

      /* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
      if (name_len < 2 || !name[0] || !name[1]) continue;

      /* empty files and directory names are stored as a file entry at
       * offset 0 with length 0. We want to keep empty files, but not
       * directory names, which end with a "/" */
      if ((offset == 0) && (length == 0)) {
        if ((name_len > 0) && (name[name_len-1] == '/')) continue;
      }

      if (section > 1) {
        sys->message(fh, "invalid section number '%u'.", section);
        continue;
      }

      if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
        sys->free(chunk);
        return MSPACK_ERR_NOMEMORY;
      }

      fi->next     = NULL;
      fi->filename = (char *) &fi[1];
      fi->section  = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
                                     : (struct mschmd_section *) (&chm->sec1));
      fi->offset   = offset;
      fi->length   = length;
      sys->copy(name, fi->filename, (size_t) name_len);
      fi->filename[name_len] = '\0';

      if (name[0] == ':' && name[1] == ':') {
        /* system file */
        if (memcmp(&name[2], &content_name[2], 31L) == 0) {
          if (memcmp(&name[33], &content_name[33], 8L) == 0) {
            chm->sec1.content = fi;
          }
          else if (memcmp(&name[33], &control_name[33], 11L) == 0) {
            chm->sec1.control = fi;
          }
          else if (memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
            chm->sec1.spaninfo = fi;
          }
          else if (memcmp(&name[33], &rtable_name[33], 72L) == 0) {
            chm->sec1.rtable = fi;
          }
        }
        fi->next = chm->sysfiles;
        chm->sysfiles = fi;
      }
      else {
        /* normal file */
        if (link) link->next = fi; else chm->files = fi;
        link = fi;
      }
    }

    /* this is reached either when num_entries runs out, or if
     * reading data from the chunk reached a premature end of chunk */
  chunk_end:
    if (num_entries >= 0) {
      D(("chunk ended before all entries could be read"))
      errors++;
    }

  }
  sys->free(chunk);
  return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
}


bool Browser::EmbedsFullscreenWidget() const {
  return true;
}


void RenderWidgetHostImpl::SetImportance(ChildProcessImportance importance) {
  if (importance_ == importance)
    return;
  ChildProcessImportance old = importance_;
  importance_ = importance;
  process_->UpdateWidgetImportance(old, importance_);
}


static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
{
	if (!is_guest_mode(vcpu)) {
		vmcs_write64(APIC_ACCESS_ADDR, hpa);
		vmx_flush_tlb(vcpu, true);
	}
}


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

	key.objectid = dir;
	btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
	key.offset = objectid;

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


static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
{
    core_dir_config *d = d_;

    if (ap_cstr_casecmp(arg, "on") == 0) {
        d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
    }
    else if (ap_cstr_casecmp(arg, "off") == 0) {
        d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
    }
    else if (ap_cstr_casecmp(arg, "default") == 0) {
        d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
    }
    else {
        return "AcceptPathInfo must be set to on, off or default";
    }

    return NULL;
}


    IniContainerElement (const IniEntry& e) :
	_t (VALUE),
	_e (e),
//	_s (IniSection ("uninitialized"))
	_s (IniSection ((const IniParser *)NULL))
	{}


dbus_g_proxy_manager_ref (DBusGProxyManager *manager)
{
  g_assert (manager != NULL);
  g_assert (manager->refcount > 0);

  LOCK_MANAGER (manager);

  manager->refcount += 1;

  UNLOCK_MANAGER (manager);

  return manager;
}


static void par_list_remove ( TocEntry * te ) {
 te -> par_prev -> par_next = te -> par_next ;
 te -> par_next -> par_prev = te -> par_prev ;
 te -> par_prev = NULL ;
 te -> par_next = NULL ;
 }


static void aio_free_ring(struct kioctx *ctx)
{
	int i;

	for (i = 0; i < ctx->nr_pages; i++) {
		pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
				page_count(ctx->ring_pages[i]));
		put_page(ctx->ring_pages[i]);
	}

	put_aio_ring_file(ctx);

	if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages)
		kfree(ctx->ring_pages);
}


static void usbredir_handle_interrupt_out_data(USBRedirDevice *dev,

                                               USBPacket *p, uint8_t ep)

{

    /* Output interrupt endpoint, normal async operation */

    struct usb_redir_interrupt_packet_header interrupt_packet;

    uint8_t buf[p->iov.size];

    DPRINTF("interrupt-out ep %02X len %zd id %"PRIu64"\n", ep,

            p->iov.size, p->id);

    if (usbredir_already_in_flight(dev, p->id)) {

        p->status = USB_RET_ASYNC;

        return;

    }

    interrupt_packet.endpoint  = ep;

    interrupt_packet.length    = p->iov.size;

    usb_packet_copy(p, buf, p->iov.size);

    usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);

    usbredirparser_send_interrupt_packet(dev->parser, p->id,

                                    &interrupt_packet, buf, p->iov.size);

    usbredirparser_do_write(dev->parser);

    p->status = USB_RET_ASYNC;

}


static UBool _isRegionSubtag ( const char * s , int32_t len ) {
 if ( len < 0 ) {
 len = ( int32_t ) uprv_strlen ( s ) ;
 }
 if ( len == 2 && _isAlphaString ( s , len ) ) {
 return TRUE ;
 }
 if ( len == 3 && _isNumericString ( s , len ) ) {
 return TRUE ;
 }
 return FALSE ;
 }


static int string_scan_range(RList *list, RBinFile *bf, int min,
			      const ut64 from, const ut64 to, int type) {
	ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
	ut64 str_start, needle = from;
	int count = 0, i, rc, runes;
	int str_type = R_STRING_TYPE_DETECT;

	if (type == -1) {
		type = R_STRING_TYPE_DETECT;
	}
	if (from >= to) {
		eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
		return -1;
	}
	ut8 *buf = calloc (to - from, 1);
	if (!buf || !min) {
		return -1;
	}
	r_buf_read_at (bf->buf, from, buf, to - from);
	// may oobread
	while (needle < to) {
		rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
		if (!rc) {
			needle++;
			continue;
		}
		if (type == R_STRING_TYPE_DETECT) {
			char *w = (char *)buf + needle + rc - from;
			if ((to - needle) > 5) {
				bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
				if (is_wide32) {
					str_type = R_STRING_TYPE_WIDE32;
				} else {
					bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
					str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
				}
			} else {
				str_type = R_STRING_TYPE_ASCII;
			}
		} else {
			str_type = type;
		}
		runes = 0;
		str_start = needle;

		/* Eat a whole C string */
		for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
			RRune r = {0};

			if (str_type == R_STRING_TYPE_WIDE32) {
				rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
				if (rc) {
					rc = 4;
				}
			} else if (str_type == R_STRING_TYPE_WIDE) {
				rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
				if (rc == 1) {
					rc = 2;
				}
			} else {
				rc = r_utf8_decode (buf + needle - from, to - needle, &r);
				if (rc > 1) {
					str_type = R_STRING_TYPE_UTF8;
				}
			}

			/* Invalid sequence detected */
			if (!rc) {
				needle++;
				break;
			}

			needle += rc;

			if (r_isprint (r) && r != '\\') {
				if (str_type == R_STRING_TYPE_WIDE32) {
					if (r == 0xff) {
						r = 0;
					}
				}
				rc = r_utf8_encode (&tmp[i], r);
				runes++;
				/* Print the escape code */
			} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
				if ((i + 32) < sizeof (tmp) && r < 93) {
					tmp[i + 0] = '\\';
					tmp[i + 1] = "       abtnvfr             e  "
					             "                              "
					             "                              "
					             "  \\"[r];
				} else {
					// string too long
					break;
				}
				rc = 2;
				runes++;
			} else {
				/* \0 marks the end of C-strings */
				break;
			}
		}

		tmp[i++] = '\0';

		if (runes >= min) {
			if (str_type == R_STRING_TYPE_ASCII) {
				// reduce false positives
				int j;
				for (j = 0; j < i; j++) {
					char ch = tmp[j];
					if (ch != '\n' && ch != '\r' && ch != '\t') {
						if (!IS_PRINTABLE (tmp[j])) {
							continue;
						}
					}
				}
			}
			RBinString *bs = R_NEW0 (RBinString);
			if (!bs) {
				break;
			}
			bs->type = str_type;
			bs->length = runes;
			bs->size = needle - str_start;
			bs->ordinal = count++;
			// TODO: move into adjust_offset
			switch (str_type) {
			case R_STRING_TYPE_WIDE:
				if (str_start -from> 1) {
					const ut8 *p = buf + str_start - 2 - from;
					if (p[0] == 0xff && p[1] == 0xfe) {
						str_start -= 2; // \xff\xfe
					}
				}
				break;
			case R_STRING_TYPE_WIDE32:
				if (str_start -from> 3) {
					const ut8 *p = buf + str_start - 4 - from;
					if (p[0] == 0xff && p[1] == 0xfe) {
						str_start -= 4; // \xff\xfe\x00\x00
					}
				}
				break;
			}
			bs->paddr = bs->vaddr = str_start;
			bs->string = r_str_ndup ((const char *)tmp, i);
			if (list) {
				r_list_append (list, bs);
			} else {
				print_string (bs, bf);
				r_bin_string_free (bs);
			}
		}
	}
	free (buf);
	return count;
}


static int php_apache2_startup(sapi_module_struct *sapi_module)
{
	if (php_module_startup(sapi_module, &php_apache_module, 1)==FAILURE) {
		return FAILURE;
	}
	return SUCCESS;
}


__glXDrawableRelease(__GLXdrawable *drawable)
{
}


static u32 svm_msrpm_offset(u32 msr)
{
	u32 offset;
	int i;

	for (i = 0; i < NUM_MSR_MAPS; i++) {
		if (msr < msrpm_ranges[i] ||
		    msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
			continue;

		offset  = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
		offset += (i * MSRS_RANGE_SIZE);       /* add range offset */

		/* Now we have the u8 offset - but need the u32 offset */
		return offset / 4;
	}

	/* MSR not in any range */
	return MSR_INVALID;
}