  Compute_Funcs( TT_ExecContext  exc )
  {
    if ( exc->GS.freeVector.x == 0x4000 )
      exc->F_dot_P = exc->GS.projVector.x;
    else if ( exc->GS.freeVector.y == 0x4000 )
      exc->F_dot_P = exc->GS.projVector.y;
    else
      exc->F_dot_P =
        ( (FT_Long)exc->GS.projVector.x * exc->GS.freeVector.x +
          (FT_Long)exc->GS.projVector.y * exc->GS.freeVector.y ) >> 14;

    if ( exc->GS.projVector.x == 0x4000 )
      exc->func_project = (TT_Project_Func)Project_x;
    else if ( exc->GS.projVector.y == 0x4000 )
      exc->func_project = (TT_Project_Func)Project_y;
    else
      exc->func_project = (TT_Project_Func)Project;

    if ( exc->GS.dualVector.x == 0x4000 )
      exc->func_dualproj = (TT_Project_Func)Project_x;
    else if ( exc->GS.dualVector.y == 0x4000 )
      exc->func_dualproj = (TT_Project_Func)Project_y;
    else
      exc->func_dualproj = (TT_Project_Func)Dual_Project;

    exc->func_move      = (TT_Move_Func)Direct_Move;
    exc->func_move_orig = (TT_Move_Func)Direct_Move_Orig;

    if ( exc->F_dot_P == 0x4000L )
    {
      if ( exc->GS.freeVector.x == 0x4000 )
      {
        exc->func_move      = (TT_Move_Func)Direct_Move_X;
        exc->func_move_orig = (TT_Move_Func)Direct_Move_Orig_X;
      }
      else if ( exc->GS.freeVector.y == 0x4000 )
      {
        exc->func_move      = (TT_Move_Func)Direct_Move_Y;
        exc->func_move_orig = (TT_Move_Func)Direct_Move_Orig_Y;
      }
    }

    /* at small sizes, F_dot_P can become too small, resulting   */
    /* in overflows and `spikes' in a number of glyphs like `w'. */

    if ( FT_ABS( exc->F_dot_P ) < 0x400L )
      exc->F_dot_P = 0x4000L;

    /* Disable cached aspect ratio */
    exc->tt_metrics.ratio = 0;
  }


static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
{
	return to_vmx(vcpu)->nested.msrs.misc_low &
		MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
}


static uint32_t virtio_pci_config_readb ( void * opaque , uint32_t addr ) {
 VirtIOPCIProxy * proxy = opaque ;
 uint32_t config = VIRTIO_PCI_CONFIG ( & proxy -> pci_dev ) ;
 addr -= proxy -> addr ;
 if ( addr < config ) return virtio_ioport_read ( proxy , addr ) ;
 addr -= config ;
 return virtio_config_readb ( proxy -> vdev , addr ) ;
 }


static void parseOptions(int argc, char **argv) {
  int option_idx = 0, do_capture = 0;
  char *__pcap_file = NULL, *bind_mask = NULL;
  int thread_id, opt;
#ifdef linux
  u_int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
#endif

#ifdef DEBUG_TRACE
  trace = fopen("/tmp/ndpiReader.log", "a");

  if(trace) fprintf(trace, " #### %s #### \n", __FUNCTION__);
#endif

#ifdef USE_DPDK
  {
    int ret = rte_eal_init(argc, argv);

    if(ret < 0)
      rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");

    argc -= ret, argv += ret;
  }
#endif

  while((opt = getopt_long(argc, argv, "e:c:C:df:g:i:hp:P:l:s:tv:V:n:Jrp:w:q0123:456:7:89:m:T:U:",
			   longopts, &option_idx)) != EOF) {
#ifdef DEBUG_TRACE
    if(trace) fprintf(trace, " #### -%c [%s] #### \n", opt, optarg ? optarg : "");
#endif

    switch (opt) {
    case 'd':
      enable_protocol_guess = 0;
      break;

    case 'e':
      human_readeable_string_len = atoi(optarg);
      break;

    case 'i':
    case '3':
      _pcap_file[0] = optarg;
      break;

    case 'm':
      pcap_analysis_duration = atol(optarg);
      break;

    case 'f':
    case '6':
      bpfFilter = optarg;
      break;

    case 'g':
      bind_mask = optarg;
      break;

    case 'l':
      num_loops = atoi(optarg);
      break;

    case 'n':
      num_threads = atoi(optarg);
      break;

    case 'p':
      _protoFilePath = optarg;
      break;

    case 'c':
      _customCategoryFilePath = optarg;
      break;

    case 'C':
      if((csv_fp = fopen(optarg, "w")) == NULL)
	printf("Unable to write on CSV file %s\n", optarg);
      break;

    case 's':
      capture_for = atoi(optarg);
      capture_until = capture_for + time(NULL);
      break;

    case 't':
      decode_tunnels = 1;
      break;

    case 'r':
      printf("ndpiReader - nDPI (%s)\n", ndpi_revision());
      exit(0);

    case 'v':
      verbose = atoi(optarg);
      break;

    case 'V':
      nDPI_LogLevel  = atoi(optarg);
      if(nDPI_LogLevel < 0) nDPI_LogLevel = 0;
      if(nDPI_LogLevel > 3) {
	nDPI_LogLevel = 3;
	_debug_protocols = strdup("all");
      }
      break;

    case 'h':
      help(1);
      break;

    case 'J':
      enable_joy_stats = 1;
      break;

    case 'P':
      {
	int _min_pattern_len, _max_pattern_len,
	  _max_num_packets_per_flow, _max_packet_payload_dissection,
	  _max_num_reported_top_payloads;

	enable_payload_analyzer = 1;
	if(sscanf(optarg, "%d:%d:%d:%d:%d", &_min_pattern_len, &_max_pattern_len,
		  &_max_num_packets_per_flow,
		  &_max_packet_payload_dissection,
		  &_max_num_reported_top_payloads) == 5) {
	  min_pattern_len = _min_pattern_len, max_pattern_len = _max_pattern_len;
	  max_num_packets_per_flow = _max_num_packets_per_flow, max_packet_payload_dissection = _max_packet_payload_dissection;
	  max_num_reported_top_payloads = _max_num_reported_top_payloads;
	  if(min_pattern_len > max_pattern_len) min_pattern_len = max_pattern_len;
	  if(min_pattern_len < 2)               min_pattern_len = 2;
	  if(max_pattern_len > 16)              max_pattern_len = 16;
	  if(max_num_packets_per_flow == 0)     max_num_packets_per_flow = 1;
	  if(max_packet_payload_dissection < 4) max_packet_payload_dissection = 4;
	  if(max_num_reported_top_payloads == 0) max_num_reported_top_payloads = 1;
	} else {
	  printf("Invalid -P format. Ignored\n");
	  help(0);
	}
      }
      break;

    case 'w':
      results_path = strdup(optarg);
      if((results_file = fopen(results_path, "w")) == NULL) {
	printf("Unable to write in file %s: quitting\n", results_path);
	return;
      }
      break;

    case 'q':
      quiet_mode = 1;
      nDPI_LogLevel = 0;
      break;

      /* Extcap */
    case '0':
      extcap_interfaces();
      break;

    case '1':
      printf("extcap {version=%s}\n", ndpi_revision());
      break;

    case '2':
      extcap_dlts();
      break;

    case '4':
      extcap_config();
      break;

    case '5':
      do_capture = 1;
      break;

    case '7':
      extcap_capture_fifo = strdup(optarg);
      break;

    case '8':
      nDPI_LogLevel = NDPI_LOG_DEBUG_EXTRA;
      _debug_protocols = strdup("all");
      break;

    case '9':
      extcap_packet_filter = ndpi_get_proto_by_name(ndpi_info_mod, optarg);
      if(extcap_packet_filter == NDPI_PROTOCOL_UNKNOWN) extcap_packet_filter = atoi(optarg);
      break;

    case 257:
      _debug_protocols = strdup(optarg);
      break;

    case 'T':
      max_num_tcp_dissected_pkts = atoi(optarg);
      if(max_num_tcp_dissected_pkts < 3) max_num_tcp_dissected_pkts = 3;
      break;

    case 'U':
      max_num_udp_dissected_pkts = atoi(optarg);
      if(max_num_udp_dissected_pkts < 3) max_num_udp_dissected_pkts = 3;
      break;

    default:
      help(0);
      break;
    }
  }

  if(_pcap_file[0] == NULL)
    help(0);

  if(csv_fp)
    printCSVHeader();

#ifndef USE_DPDK
  if(strchr(_pcap_file[0], ',')) { /* multiple ingress interfaces */
    num_threads = 0;               /* setting number of threads = number of interfaces */
    __pcap_file = strtok(_pcap_file[0], ",");
    while(__pcap_file != NULL && num_threads < MAX_NUM_READER_THREADS) {
      _pcap_file[num_threads++] = __pcap_file;
      __pcap_file = strtok(NULL, ",");
    }
  } else {
    if(num_threads > MAX_NUM_READER_THREADS) num_threads = MAX_NUM_READER_THREADS;
    for(thread_id = 1; thread_id < num_threads; thread_id++)
      _pcap_file[thread_id] = _pcap_file[0];
  }

#ifdef linux
    for(thread_id = 0; thread_id < num_threads; thread_id++)
      core_affinity[thread_id] = -1;

    if(num_cores > 1 && bind_mask != NULL) {
      char *core_id = strtok(bind_mask, ":");
      thread_id = 0;
      while(core_id != NULL && thread_id < num_threads) {
        core_affinity[thread_id++] = atoi(core_id) % num_cores;
        core_id = strtok(NULL, ":");
      }
    }
#endif
#endif

#ifdef DEBUG_TRACE
  if(trace) fclose(trace);
#endif
}


int Pipe::tcp_read_wait()
{
  if (sd < 0)
    return -EINVAL;
  struct pollfd pfd;
  short evmask;
  pfd.fd = sd;
  pfd.events = POLLIN;
#if defined(__linux__)
  pfd.events |= POLLRDHUP;
#endif

  if (has_pending_data())
    return 0;

  int r = poll(&pfd, 1, msgr->timeout);
  if (r < 0)
    return -errno;
  if (r == 0)
    return -EAGAIN;

  evmask = POLLERR | POLLHUP | POLLNVAL;
#if defined(__linux__)
  evmask |= POLLRDHUP;
#endif
  if (pfd.revents & evmask)
    return -1;

  if (!(pfd.revents & POLLIN))
    return -1;

  return 0;
}


image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
     image_pixel *that, png_const_structp pp,
    PNG_CONST transform_display *display)
 {
    if (that->bit_depth == 16)
    {
      that->sample_depth = that->bit_depth = 8;
 if (that->red_sBIT > 8) that->red_sBIT = 8;
 if (that->green_sBIT > 8) that->green_sBIT = 8;
 if (that->blue_sBIT > 8) that->blue_sBIT = 8;
 if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;

 /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
       * configuration option is set.  From 1.5.4 the flag is never set and the
       * 'scale' API (above) must be used.
       */
#     ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
#        if PNG_LIBPNG_VER >= 10504
#           error PNG_READ_ACCURATE_SCALE should not be set
#        endif

 /* The strip 16 algorithm drops the low 8 bits rather than calculating
          * 1/257, so we need to adjust the permitted errors appropriately:
          * Notice that this is only relevant prior to the addition of the

           * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
           */
          {
            PNG_CONST double d = (255-128.5)/65535;
             that->rede += d;
             that->greene += d;
             that->bluee += d;
            that->alphae += d;
 }
#     endif
 }

 this->next->mod(this->next, that, pp, display);
}


Chapters::~Chapters() {
 while (m_editions_count > 0) {

     Edition& e = m_editions[--m_editions_count];
     e.Clear();
   }
 }


static ssize_t map_write(struct file *file, const char __user *buf,
			 size_t count, loff_t *ppos,
			 int cap_setid,
			 struct uid_gid_map *map,
			 struct uid_gid_map *parent_map)
{
	struct seq_file *seq = file->private_data;
	struct user_namespace *ns = seq->private;
	struct uid_gid_map new_map;
	unsigned idx;
	struct uid_gid_extent *extent = NULL;
	unsigned long page = 0;
	char *kbuf, *pos, *next_line;
	ssize_t ret = -EINVAL;

	/*
	 * The id_map_mutex serializes all writes to any given map.
	 *
	 * Any map is only ever written once.
	 *
	 * An id map fits within 1 cache line on most architectures.
	 *
	 * On read nothing needs to be done unless you are on an
	 * architecture with a crazy cache coherency model like alpha.
	 *
	 * There is a one time data dependency between reading the
	 * count of the extents and the values of the extents.  The
	 * desired behavior is to see the values of the extents that
	 * were written before the count of the extents.
	 *
	 * To achieve this smp_wmb() is used on guarantee the write
	 * order and smp_read_barrier_depends() is guaranteed that we
	 * don't have crazy architectures returning stale data.
	 *
	 */
	mutex_lock(&id_map_mutex);

	ret = -EPERM;
	/* Only allow one successful write to the map */
	if (map->nr_extents != 0)
		goto out;

	/* Require the appropriate privilege CAP_SETUID or CAP_SETGID
	 * over the user namespace in order to set the id mapping.
	 */
	if (cap_valid(cap_setid) && !ns_capable(ns, cap_setid))
		goto out;

	/* Get a buffer */
	ret = -ENOMEM;
	page = __get_free_page(GFP_TEMPORARY);
	kbuf = (char *) page;
	if (!page)
		goto out;

	/* Only allow <= page size writes at the beginning of the file */
	ret = -EINVAL;
	if ((*ppos != 0) || (count >= PAGE_SIZE))
		goto out;

	/* Slurp in the user data */
	ret = -EFAULT;
	if (copy_from_user(kbuf, buf, count))
		goto out;
	kbuf[count] = '\0';

	/* Parse the user data */
	ret = -EINVAL;
	pos = kbuf;
	new_map.nr_extents = 0;
	for (;pos; pos = next_line) {
		extent = &new_map.extent[new_map.nr_extents];

		/* Find the end of line and ensure I don't look past it */
		next_line = strchr(pos, '\n');
		if (next_line) {
			*next_line = '\0';
			next_line++;
			if (*next_line == '\0')
				next_line = NULL;
		}

		pos = skip_spaces(pos);
		extent->first = simple_strtoul(pos, &pos, 10);
		if (!isspace(*pos))
			goto out;

		pos = skip_spaces(pos);
		extent->lower_first = simple_strtoul(pos, &pos, 10);
		if (!isspace(*pos))
			goto out;

		pos = skip_spaces(pos);
		extent->count = simple_strtoul(pos, &pos, 10);
		if (*pos && !isspace(*pos))
			goto out;

		/* Verify there is not trailing junk on the line */
		pos = skip_spaces(pos);
		if (*pos != '\0')
			goto out;

		/* Verify we have been given valid starting values */
		if ((extent->first == (u32) -1) ||
		    (extent->lower_first == (u32) -1 ))
			goto out;

		/* Verify count is not zero and does not cause the extent to wrap */
		if ((extent->first + extent->count) <= extent->first)
			goto out;
		if ((extent->lower_first + extent->count) <= extent->lower_first)
			goto out;

		/* Do the ranges in extent overlap any previous extents? */
		if (mappings_overlap(&new_map, extent))
			goto out;

		new_map.nr_extents++;

		/* Fail if the file contains too many extents */
		if ((new_map.nr_extents == UID_GID_MAP_MAX_EXTENTS) &&
		    (next_line != NULL))
			goto out;
	}
	/* Be very certaint the new map actually exists */
	if (new_map.nr_extents == 0)
		goto out;

	ret = -EPERM;
	/* Validate the user is allowed to use user id's mapped to. */
	if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
		goto out;

	/* Map the lower ids from the parent user namespace to the
	 * kernel global id space.
	 */
	for (idx = 0; idx < new_map.nr_extents; idx++) {
		u32 lower_first;
		extent = &new_map.extent[idx];

		lower_first = map_id_range_down(parent_map,
						extent->lower_first,
						extent->count);

		/* Fail if we can not map the specified extent to
		 * the kernel global id space.
		 */
		if (lower_first == (u32) -1)
			goto out;

		extent->lower_first = lower_first;
	}

	/* Install the map */
	memcpy(map->extent, new_map.extent,
		new_map.nr_extents*sizeof(new_map.extent[0]));
	smp_wmb();
	map->nr_extents = new_map.nr_extents;

	*ppos = count;
	ret = count;
out:
	mutex_unlock(&id_map_mutex);
	if (page)
		free_page(page);
	return ret;
}


int tls_construct_server_key_exchange ( SSL * s ) {
 # ifndef OPENSSL_NO_DH EVP_PKEY * pkdh = NULL ;
 int j ;
 # endif # ifndef OPENSSL_NO_EC unsigned char * encodedPoint = NULL ;
 int encodedlen = 0 ;
 int curve_id = 0 ;
 # endif EVP_PKEY * pkey ;
 const EVP_MD * md = NULL ;
 unsigned char * p , * d ;
 int al , i ;
 unsigned long type ;
 int n ;
 const BIGNUM * r [ 4 ] ;
 int nr [ 4 ] , kn ;
 BUF_MEM * buf ;
 EVP_MD_CTX * md_ctx = EVP_MD_CTX_new ( ) ;
 if ( md_ctx == NULL ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_MALLOC_FAILURE ) ;
 al = SSL_AD_INTERNAL_ERROR ;
 goto f_err ;
 }
 type = s -> s3 -> tmp . new_cipher -> algorithm_mkey ;
 buf = s -> init_buf ;
 r [ 0 ] = r [ 1 ] = r [ 2 ] = r [ 3 ] = NULL ;
 n = 0 ;
 # ifndef OPENSSL_NO_PSK if ( type & SSL_PSK ) {
 n += 2 ;
 if ( s -> cert -> psk_identity_hint ) n += strlen ( s -> cert -> psk_identity_hint ) ;
 }
 if ( type & ( SSL_kPSK | SSL_kRSAPSK ) ) {
 }
 else # endif # ifndef OPENSSL_NO_DH if ( type & ( SSL_kDHE | SSL_kDHEPSK ) ) {
 CERT * cert = s -> cert ;
 EVP_PKEY * pkdhp = NULL ;
 DH * dh ;
 if ( s -> cert -> dh_tmp_auto ) {
 DH * dhp = ssl_get_auto_dh ( s ) ;
 pkdh = EVP_PKEY_new ( ) ;
 if ( pkdh == NULL || dhp == NULL ) {
 DH_free ( dhp ) ;
 al = SSL_AD_INTERNAL_ERROR ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto f_err ;
 }
 EVP_PKEY_assign_DH ( pkdh , dhp ) ;
 pkdhp = pkdh ;
 }
 else {
 pkdhp = cert -> dh_tmp ;
 }
 if ( ( pkdhp == NULL ) && ( s -> cert -> dh_tmp_cb != NULL ) ) {
 DH * dhp = s -> cert -> dh_tmp_cb ( s , 0 , 1024 ) ;
 pkdh = ssl_dh_to_pkey ( dhp ) ;
 if ( pkdh == NULL ) {
 al = SSL_AD_INTERNAL_ERROR ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto f_err ;
 }
 pkdhp = pkdh ;
 }
 if ( pkdhp == NULL ) {
 al = SSL_AD_HANDSHAKE_FAILURE ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , SSL_R_MISSING_TMP_DH_KEY ) ;
 goto f_err ;
 }
 if ( ! ssl_security ( s , SSL_SECOP_TMP_DH , EVP_PKEY_security_bits ( pkdhp ) , 0 , pkdhp ) ) {
 al = SSL_AD_HANDSHAKE_FAILURE ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , SSL_R_DH_KEY_TOO_SMALL ) ;
 goto f_err ;
 }
 if ( s -> s3 -> tmp . pkey != NULL ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto err ;
 }
 s -> s3 -> tmp . pkey = ssl_generate_pkey ( pkdhp ) ;
 if ( s -> s3 -> tmp . pkey == NULL ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_EVP_LIB ) ;
 goto err ;
 }
 dh = EVP_PKEY_get0_DH ( s -> s3 -> tmp . pkey ) ;
 EVP_PKEY_free ( pkdh ) ;
 pkdh = NULL ;
 DH_get0_pqg ( dh , & r [ 0 ] , NULL , & r [ 1 ] ) ;
 DH_get0_key ( dh , & r [ 2 ] , NULL ) ;
 }
 else # endif # ifndef OPENSSL_NO_EC if ( type & ( SSL_kECDHE | SSL_kECDHEPSK ) ) {
 int nid ;
 if ( s -> s3 -> tmp . pkey != NULL ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto err ;
 }
 nid = tls1_shared_curve ( s , - 2 ) ;
 curve_id = tls1_ec_nid2curve_id ( nid ) ;
 if ( curve_id == 0 ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , SSL_R_UNSUPPORTED_ELLIPTIC_CURVE ) ;
 goto err ;
 }
 s -> s3 -> tmp . pkey = ssl_generate_pkey_curve ( curve_id ) ;
 if ( s -> s3 -> tmp . pkey == NULL ) {
 al = SSL_AD_INTERNAL_ERROR ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_EVP_LIB ) ;
 goto f_err ;
 }
 encodedlen = EVP_PKEY_get1_tls_encodedpoint ( s -> s3 -> tmp . pkey , & encodedPoint ) ;
 if ( encodedlen == 0 ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_EC_LIB ) ;
 goto err ;
 }
 n += 4 + encodedlen ;
 r [ 0 ] = NULL ;
 r [ 1 ] = NULL ;
 r [ 2 ] = NULL ;
 r [ 3 ] = NULL ;
 }
 else # endif # ifndef OPENSSL_NO_SRP if ( type & SSL_kSRP ) {
 if ( ( s -> srp_ctx . N == NULL ) || ( s -> srp_ctx . g == NULL ) || ( s -> srp_ctx . s == NULL ) || ( s -> srp_ctx . B == NULL ) ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , SSL_R_MISSING_SRP_PARAM ) ;
 goto err ;
 }
 r [ 0 ] = s -> srp_ctx . N ;
 r [ 1 ] = s -> srp_ctx . g ;
 r [ 2 ] = s -> srp_ctx . s ;
 r [ 3 ] = s -> srp_ctx . B ;
 }
 else # endif {
 al = SSL_AD_HANDSHAKE_FAILURE ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE ) ;
 goto f_err ;
 }
 for ( i = 0 ;
 i < 4 && r [ i ] != NULL ;
 i ++ ) {
 nr [ i ] = BN_num_bytes ( r [ i ] ) ;
 # ifndef OPENSSL_NO_SRP if ( ( i == 2 ) && ( type & SSL_kSRP ) ) n += 1 + nr [ i ] ;
 else # endif # ifndef OPENSSL_NO_DH if ( ( i == 2 ) && ( type & ( SSL_kDHE | SSL_kDHEPSK ) ) ) n += 2 + nr [ 0 ] ;
 else # endif n += 2 + nr [ i ] ;
 }
 if ( ! ( s -> s3 -> tmp . new_cipher -> algorithm_auth & ( SSL_aNULL | SSL_aSRP ) ) && ! ( s -> s3 -> tmp . new_cipher -> algorithm_mkey & SSL_PSK ) ) {
 if ( ( pkey = ssl_get_sign_pkey ( s , s -> s3 -> tmp . new_cipher , & md ) ) == NULL ) {
 al = SSL_AD_DECODE_ERROR ;
 goto f_err ;
 }
 kn = EVP_PKEY_size ( pkey ) ;
 if ( SSL_USE_SIGALGS ( s ) ) kn += 2 ;
 kn += 2 ;
 }
 else {
 pkey = NULL ;
 kn = 0 ;
 }
 if ( ! BUF_MEM_grow_clean ( buf , n + SSL_HM_HEADER_LENGTH ( s ) + kn ) ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_LIB_BUF ) ;
 goto err ;
 }
 d = p = ssl_handshake_start ( s ) ;
 # ifndef OPENSSL_NO_PSK if ( type & SSL_PSK ) {
 if ( s -> cert -> psk_identity_hint ) {
 size_t len = strlen ( s -> cert -> psk_identity_hint ) ;
 if ( len > PSK_MAX_IDENTITY_LEN ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto err ;
 }
 s2n ( len , p ) ;
 memcpy ( p , s -> cert -> psk_identity_hint , len ) ;
 p += len ;
 }
 else {
 s2n ( 0 , p ) ;
 }
 }
 # endif for ( i = 0 ;
 i < 4 && r [ i ] != NULL ;
 i ++ ) {
 # ifndef OPENSSL_NO_SRP if ( ( i == 2 ) && ( type & SSL_kSRP ) ) {
 * p = nr [ i ] ;
 p ++ ;
 }
 else # endif # ifndef OPENSSL_NO_DH if ( ( i == 2 ) && ( type & ( SSL_kDHE | SSL_kDHEPSK ) ) ) {
 s2n ( nr [ 0 ] , p ) ;
 for ( j = 0 ;
 j < ( nr [ 0 ] - nr [ 2 ] ) ;
 ++ j ) {
 * p = 0 ;
 ++ p ;
 }
 }
 else # endif s2n ( nr [ i ] , p ) ;
 BN_bn2bin ( r [ i ] , p ) ;
 p += nr [ i ] ;
 }
 # ifndef OPENSSL_NO_EC if ( type & ( SSL_kECDHE | SSL_kECDHEPSK ) ) {
 * p = NAMED_CURVE_TYPE ;
 p += 1 ;
 * p = 0 ;
 p += 1 ;
 * p = curve_id ;
 p += 1 ;
 * p = encodedlen ;
 p += 1 ;
 memcpy ( p , encodedPoint , encodedlen ) ;
 OPENSSL_free ( encodedPoint ) ;
 encodedPoint = NULL ;
 p += encodedlen ;
 }
 # endif if ( pkey != NULL ) {
 if ( md ) {
 if ( SSL_USE_SIGALGS ( s ) ) {
 if ( ! tls12_get_sigandhash ( p , pkey , md ) ) {
 al = SSL_AD_INTERNAL_ERROR ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto f_err ;
 }
 p += 2 ;
 }
 # ifdef SSL_DEBUG fprintf ( stderr , "Using hash %s\n" , EVP_MD_name ( md ) ) ;
 # endif if ( EVP_SignInit_ex ( md_ctx , md , NULL ) <= 0 || EVP_SignUpdate ( md_ctx , & ( s -> s3 -> client_random [ 0 ] ) , SSL3_RANDOM_SIZE ) <= 0 || EVP_SignUpdate ( md_ctx , & ( s -> s3 -> server_random [ 0 ] ) , SSL3_RANDOM_SIZE ) <= 0 || EVP_SignUpdate ( md_ctx , d , n ) <= 0 || EVP_SignFinal ( md_ctx , & ( p [ 2 ] ) , ( unsigned int * ) & i , pkey ) <= 0 ) {
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_LIB_EVP ) ;
 al = SSL_AD_INTERNAL_ERROR ;
 goto f_err ;
 }
 s2n ( i , p ) ;
 n += i + 2 ;
 if ( SSL_USE_SIGALGS ( s ) ) n += 2 ;
 }
 else {
 al = SSL_AD_HANDSHAKE_FAILURE ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , SSL_R_UNKNOWN_PKEY_TYPE ) ;
 goto f_err ;
 }
 }
 if ( ! ssl_set_handshake_header ( s , SSL3_MT_SERVER_KEY_EXCHANGE , n ) ) {
 al = SSL_AD_HANDSHAKE_FAILURE ;
 SSLerr ( SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE , ERR_R_INTERNAL_ERROR ) ;
 goto f_err ;
 }
 EVP_MD_CTX_free ( md_ctx ) ;
 return 1 ;
 f_err : ssl3_send_alert ( s , SSL3_AL_FATAL , al ) ;
 err : # ifndef OPENSSL_NO_DH EVP_PKEY_free ( pkdh ) ;
 # endif # ifndef OPENSSL_NO_EC OPENSSL_free ( encodedPoint ) ;
 # endif EVP_MD_CTX_free ( md_ctx ) ;
 ossl_statem_set_error ( s ) ;
 return 0 ;
 }


build_spcr(GArray *table_data, GArray *linker, VirtGuestInfo *guest_info)

{

    AcpiSerialPortConsoleRedirection *spcr;

    const MemMapEntry *uart_memmap = &guest_info->memmap[VIRT_UART];

    int irq = guest_info->irqmap[VIRT_UART] + ARM_SPI_BASE;

    spcr = acpi_data_push(table_data, sizeof(*spcr));

    spcr->interface_type = 0x3;    /* ARM PL011 UART */

    spcr->base_address.space_id = AML_SYSTEM_MEMORY;

    spcr->base_address.bit_width = 8;

    spcr->base_address.bit_offset = 0;

    spcr->base_address.access_width = 1;

    spcr->base_address.address = cpu_to_le64(uart_memmap->base);

    spcr->interrupt_types = (1 << 3); /* Bit[3] ARMH GIC interrupt */

    spcr->gsi = cpu_to_le32(irq);  /* Global System Interrupt */

    spcr->baud = 3;                /* Baud Rate: 3 = 9600 */

    spcr->parity = 0;              /* No Parity */

    spcr->stopbits = 1;            /* 1 Stop bit */

    spcr->flowctrl = (1 << 1);     /* Bit[1] = RTS/CTS hardware flow control */

    spcr->term_type = 0;           /* Terminal Type: 0 = VT100 */

    spcr->pci_device_id = 0xffff;  /* PCI Device ID: not a PCI device */

    spcr->pci_vendor_id = 0xffff;  /* PCI Vendor ID: not a PCI device */

    build_header(linker, table_data, (void *)spcr, "SPCR", sizeof(*spcr), 2,

                 NULL);

}


bool WebRequestPermissions::CanExtensionAccessInitiator(
    const extensions::InfoMap* extension_info_map,
    const extensions::ExtensionId extension_id,
    const base::Optional<url::Origin>& initiator,
    int tab_id,
    bool crosses_incognito) {
  PermissionsData::AccessType access = PermissionsData::ACCESS_ALLOWED;
  if (initiator) {
    access = CanExtensionAccessURL(
        extension_info_map, extension_id, initiator->GetURL(), tab_id,
        crosses_incognito, WebRequestPermissions::REQUIRE_HOST_PERMISSION,
        base::nullopt);
  }
  return access == PermissionsData::ACCESS_ALLOWED;
}


perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
{
	struct stackframe fr;

	if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
		/* We don't support guest os callchain now */
		return;
	}

	fr.fp = regs->ARM_fp;
	fr.sp = regs->ARM_sp;
	fr.lr = regs->ARM_lr;
	fr.pc = regs->ARM_pc;
	walk_stackframe(&fr, callchain_trace, entry);
}


static int rtrs_clt_ib_dev_init(struct rtrs_ib_dev *dev)
{
	if (!(dev->ib_dev->attrs.device_cap_flags &
	      IB_DEVICE_MEM_MGT_EXTENSIONS)) {
		pr_err("Memory registrations not supported.\n");
		return -ENOTSUPP;
	}

	return 0;
}


void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
    RenderFrameHost* old_host,
    RenderFrameHost* new_host) {
  NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
                    new_host->GetRenderViewHost());
}


void ff_avg_h264_qpel8_mc13_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_8x8_msa(src + stride - 2,

                                         src - (stride * 2),

                                         stride, dst, stride);

}


void ff_celp_lp_synthesis_filterf(float *out, const float *filter_coeffs,

                                  const float* in, int buffer_length,

                                  int filter_length)

{

    int i,n;

#if 0 // Unoptimized code path for improved readability

    for (n = 0; n < buffer_length; n++) {

        out[n] = in[n];

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

            out[n] -= filter_coeffs[i-1] * out[n-i];

    }

#else

    float out0, out1, out2, out3;

    float old_out0, old_out1, old_out2, old_out3;

    float a,b,c;

    a = filter_coeffs[0];

    b = filter_coeffs[1];

    c = filter_coeffs[2];

    b -= filter_coeffs[0] * filter_coeffs[0];

    c -= filter_coeffs[1] * filter_coeffs[0];

    c -= filter_coeffs[0] * b;

    old_out0 = out[-4];

    old_out1 = out[-3];

    old_out2 = out[-2];

    old_out3 = out[-1];

    for (n = 0; n <= buffer_length - 4; n+=4) {

        float tmp0,tmp1,tmp2;

        float val;

        out0 = in[0];

        out1 = in[1];

        out2 = in[2];

        out3 = in[3];

        out0 -= filter_coeffs[2] * old_out1;

        out1 -= filter_coeffs[2] * old_out2;

        out2 -= filter_coeffs[2] * old_out3;

        out0 -= filter_coeffs[1] * old_out2;

        out1 -= filter_coeffs[1] * old_out3;

        out0 -= filter_coeffs[0] * old_out3;

        val = filter_coeffs[3];

        out0 -= val * old_out0;

        out1 -= val * old_out1;

        out2 -= val * old_out2;

        out3 -= val * old_out3;

        for (i = 5; i <= filter_length; i += 2) {

            old_out3 = out[-i];

            val = filter_coeffs[i-1];

            out0 -= val * old_out3;

            out1 -= val * old_out0;

            out2 -= val * old_out1;

            out3 -= val * old_out2;

            old_out2 = out[-i-1];

            val = filter_coeffs[i];

            out0 -= val * old_out2;

            out1 -= val * old_out3;

            out2 -= val * old_out0;

            out3 -= val * old_out1;

            FFSWAP(float, old_out0, old_out2);

            old_out1 = old_out3;

        }

        tmp0 = out0;

        tmp1 = out1;

        tmp2 = out2;

        out3 -= a * tmp2;

        out2 -= a * tmp1;

        out1 -= a * tmp0;

        out3 -= b * tmp1;

        out2 -= b * tmp0;

        out3 -= c * tmp0;

        out[0] = out0;

        out[1] = out1;

        out[2] = out2;

        out[3] = out3;

        old_out0 = out0;

        old_out1 = out1;

        old_out2 = out2;

        old_out3 = out3;

        out += 4;

        in  += 4;

    }

    out -= n;

    in -= n;

    for (; n < buffer_length; n++) {

        out[n] = in[n];

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

            out[n] -= filter_coeffs[i-1] * out[n-i];

    }

#endif

}


bool LengthGreater ( const base : : string16 & string_a , const base : : string16 & string_b ) {
 return string_a . length ( ) > string_b . length ( ) ;
 }


static inline bool isValidNamePart(UChar32 c)
{
    if (isValidNameStart(c))
        return true;

    if (c == 0x00B7 || c == 0x0387)
        return true;

    if (c == '-' || c == '.')
        return true;

    const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
    if (!(Unicode::category(c) & otherNamePartMask))
        return false;

    if (c >= 0xF900 && c < 0xFFFE)
        return false;

    CharDecompositionType decompType = decompositionType(c);
    if (decompType == DecompositionFont || decompType == DecompositionCompat)
        return false;

    return true;
}


LockScreenMediaControlsView::LockScreenMediaControlsView(
    service_manager::Connector* connector,
    const Callbacks& callbacks)
    : connector_(connector),
      hide_controls_timer_(new base::OneShotTimer()),
      media_controls_enabled_(callbacks.media_controls_enabled),
      hide_media_controls_(callbacks.hide_media_controls),
      show_media_controls_(callbacks.show_media_controls) {
  DCHECK(callbacks.media_controls_enabled);
  DCHECK(callbacks.hide_media_controls);
  DCHECK(callbacks.show_media_controls);

  Shell::Get()->media_controller()->SetMediaControlsDismissed(false);

  middle_spacing_ = std::make_unique<NonAccessibleView>();
  middle_spacing_->set_owned_by_client();

  set_notify_enter_exit_on_child(true);

   contents_view_ = AddChildView(std::make_unique<views::View>());
   contents_view_->SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kVertical, kMediaControlsInsets));
   contents_view_->SetBackground(views::CreateRoundedRectBackground(
       kMediaControlsBackground, kMediaControlsCornerRadius));

   contents_view_->SetPaintToLayer();  // Needed for opacity animation.
   contents_view_->layer()->SetFillsBoundsOpaquely(false);

  // session. It also contains the close button.
  header_row_ = contents_view_->AddChildView(
      std::make_unique<MediaControlsHeaderView>(base::BindOnce(
          &LockScreenMediaControlsView::Dismiss, base::Unretained(this))));

   auto session_artwork = std::make_unique<views::ImageView>();
  session_artwork->SetPreferredSize(kArtworkSize);
  session_artwork->SetHorizontalAlignment(
      views::ImageView::Alignment::kLeading);
   session_artwork_ = contents_view_->AddChildView(std::move(session_artwork));

   progress_ = contents_view_->AddChildView(
      std::make_unique<media_message_center::MediaControlsProgressView>(
          base::BindRepeating(&LockScreenMediaControlsView::SeekTo,
                              base::Unretained(this))));

  auto button_row = std::make_unique<NonAccessibleView>();
  auto* button_row_layout =
      button_row->SetLayoutManager(std::make_unique<views::BoxLayout>(
          views::BoxLayout::Orientation::kHorizontal, kButtonRowInsets,
          kMediaButtonRowSeparator));
  button_row_layout->set_cross_axis_alignment(
      views::BoxLayout::CrossAxisAlignment::kCenter);
  button_row_layout->set_main_axis_alignment(
      views::BoxLayout::MainAxisAlignment::kCenter);
  button_row->SetPreferredSize(kMediaControlsButtonRowSize);
  button_row_ = contents_view_->AddChildView(std::move(button_row));

  CreateMediaButton(
      kChangeTrackIconSize, MediaSessionAction::kPreviousTrack,
      l10n_util::GetStringUTF16(
          IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PREVIOUS_TRACK));

  CreateMediaButton(
      kSeekingIconsSize, MediaSessionAction::kSeekBackward,
      l10n_util::GetStringUTF16(
          IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_BACKWARD));

  auto play_pause_button = views::CreateVectorToggleImageButton(this);
  play_pause_button->set_tag(static_cast<int>(MediaSessionAction::kPause));
  play_pause_button->SetPreferredSize(kMediaButtonSize);
  play_pause_button->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
  play_pause_button->SetTooltipText(l10n_util::GetStringUTF16(
      IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE));
  play_pause_button->SetToggledTooltipText(l10n_util::GetStringUTF16(
      IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PLAY));
  play_pause_button_ = button_row_->AddChildView(std::move(play_pause_button));

  views::SetImageFromVectorIcon(
      play_pause_button_,
      GetVectorIconForMediaAction(MediaSessionAction::kPause),
      kPlayPauseIconSize, kMediaButtonColor);
  views::SetToggledImageFromVectorIcon(
      play_pause_button_,
      GetVectorIconForMediaAction(MediaSessionAction::kPlay),
      kPlayPauseIconSize, kMediaButtonColor);

  CreateMediaButton(
      kSeekingIconsSize, MediaSessionAction::kSeekForward,
      l10n_util::GetStringUTF16(
          IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_FORWARD));

  CreateMediaButton(kChangeTrackIconSize, MediaSessionAction::kNextTrack,
                    l10n_util::GetStringUTF16(
                        IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_NEXT_TRACK));

  MediaSessionMetadataChanged(base::nullopt);
  MediaSessionPositionChanged(base::nullopt);
  MediaControllerImageChanged(
      media_session::mojom::MediaSessionImageType::kSourceIcon, SkBitmap());
  SetArtwork(base::nullopt);

  if (!connector_)
    return;

  mojo::Remote<media_session::mojom::MediaControllerManager>
      controller_manager_remote;
  connector_->Connect(media_session::mojom::kServiceName,
                      controller_manager_remote.BindNewPipeAndPassReceiver());
  controller_manager_remote->CreateActiveMediaController(
      media_controller_remote_.BindNewPipeAndPassReceiver());

  media_controller_remote_->AddObserver(
      observer_receiver_.BindNewPipeAndPassRemote());

  media_controller_remote_->ObserveImages(
      media_session::mojom::MediaSessionImageType::kArtwork,
      kMinimumArtworkSize, kDesiredArtworkSize,
      artwork_observer_receiver_.BindNewPipeAndPassRemote());

  media_controller_remote_->ObserveImages(
      media_session::mojom::MediaSessionImageType::kSourceIcon,
      kMinimumIconSize, kDesiredIconSize,
      icon_observer_receiver_.BindNewPipeAndPassRemote());
}


static struct inode *mqueue_get_inode(struct super_block *sb,
		struct ipc_namespace *ipc_ns, umode_t mode,
		struct mq_attr *attr)
{
	struct user_struct *u = current_user();
	struct inode *inode;
	int ret = -ENOMEM;

	inode = new_inode(sb);
	if (!inode)
		goto err;

	inode->i_ino = get_next_ino();
	inode->i_mode = mode;
	inode->i_uid = current_fsuid();
	inode->i_gid = current_fsgid();
	inode->i_mtime = inode->i_ctime = inode->i_atime = current_time(inode);

	if (S_ISREG(mode)) {
		struct mqueue_inode_info *info;
		unsigned long mq_bytes, mq_treesize;

		inode->i_fop = &mqueue_file_operations;
		inode->i_size = FILENT_SIZE;
		/* mqueue specific info */
		info = MQUEUE_I(inode);
		spin_lock_init(&info->lock);
		init_waitqueue_head(&info->wait_q);
		INIT_LIST_HEAD(&info->e_wait_q[0].list);
		INIT_LIST_HEAD(&info->e_wait_q[1].list);
		info->notify_owner = NULL;
		info->notify_user_ns = NULL;
		info->qsize = 0;
		info->user = NULL;	/* set when all is ok */
		info->msg_tree = RB_ROOT;
		info->node_cache = NULL;
		memset(&info->attr, 0, sizeof(info->attr));
		info->attr.mq_maxmsg = min(ipc_ns->mq_msg_max,
					   ipc_ns->mq_msg_default);
		info->attr.mq_msgsize = min(ipc_ns->mq_msgsize_max,
					    ipc_ns->mq_msgsize_default);
		if (attr) {
			info->attr.mq_maxmsg = attr->mq_maxmsg;
			info->attr.mq_msgsize = attr->mq_msgsize;
		}
		/*
		 * We used to allocate a static array of pointers and account
		 * the size of that array as well as one msg_msg struct per
		 * possible message into the queue size. That's no longer
		 * accurate as the queue is now an rbtree and will grow and
		 * shrink depending on usage patterns.  We can, however, still
		 * account one msg_msg struct per message, but the nodes are
		 * allocated depending on priority usage, and most programs
		 * only use one, or a handful, of priorities.  However, since
		 * this is pinned memory, we need to assume worst case, so
		 * that means the min(mq_maxmsg, max_priorities) * struct
		 * posix_msg_tree_node.
		 */
		mq_treesize = info->attr.mq_maxmsg * sizeof(struct msg_msg) +
			min_t(unsigned int, info->attr.mq_maxmsg, MQ_PRIO_MAX) *
			sizeof(struct posix_msg_tree_node);

		mq_bytes = mq_treesize + (info->attr.mq_maxmsg *
					  info->attr.mq_msgsize);

		spin_lock(&mq_lock);
		if (u->mq_bytes + mq_bytes < u->mq_bytes ||
		    u->mq_bytes + mq_bytes > rlimit(RLIMIT_MSGQUEUE)) {
			spin_unlock(&mq_lock);
			/* mqueue_evict_inode() releases info->messages */
			ret = -EMFILE;
			goto out_inode;
		}
		u->mq_bytes += mq_bytes;
		spin_unlock(&mq_lock);

		/* all is ok */
		info->user = get_uid(u);
	} else if (S_ISDIR(mode)) {
		inc_nlink(inode);
		/* Some things misbehave if size == 0 on a directory */
		inode->i_size = 2 * DIRENT_SIZE;
		inode->i_op = &mqueue_dir_inode_operations;
		inode->i_fop = &simple_dir_operations;
	}

	return inode;
out_inode:
	iput(inode);
err:
	return ERR_PTR(ret);
}


static int parsedate ( const char * date , time_t * output ) {
 time_t t = 0 ;
 int wdaynum = - 1 ;
 int monnum = - 1 ;
 int mdaynum = - 1 ;
 int hournum = - 1 ;
 int minnum = - 1 ;
 int secnum = - 1 ;
 int yearnum = - 1 ;
 int tzoff = - 1 ;
 struct my_tm tm ;
 enum assume dignext = DATE_MDAY ;
 const char * indate = date ;
 int part = 0 ;
 while ( * date && ( part < 6 ) ) {
 bool found = FALSE ;
 skip ( & date ) ;
 if ( ISALPHA ( * date ) ) {
 char buf [ 32 ] = "" ;
 size_t len ;
 if ( sscanf ( date , "%31[ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz]" , buf ) ) len = strlen ( buf ) ;
 else len = 0 ;
 if ( wdaynum == - 1 ) {
 wdaynum = checkday ( buf , len ) ;
 if ( wdaynum != - 1 ) found = TRUE ;
 }
 if ( ! found && ( monnum == - 1 ) ) {
 monnum = checkmonth ( buf ) ;
 if ( monnum != - 1 ) found = TRUE ;
 }
 if ( ! found && ( tzoff == - 1 ) ) {
 tzoff = checktz ( buf ) ;
 if ( tzoff != - 1 ) found = TRUE ;
 }
 if ( ! found ) return PARSEDATE_FAIL ;
 date += len ;
 }
 else if ( ISDIGIT ( * date ) ) {
 int val ;
 char * end ;
 if ( ( secnum == - 1 ) && ( 3 == sscanf ( date , "%02d:%02d:%02d" , & hournum , & minnum , & secnum ) ) ) {
 date += 8 ;
 }
 else if ( ( secnum == - 1 ) && ( 2 == sscanf ( date , "%02d:%02d" , & hournum , & minnum ) ) ) {
 date += 5 ;
 secnum = 0 ;
 }
 else {
 long lval ;
 int error ;
 int old_errno ;
 old_errno = ERRNO ;
 SET_ERRNO ( 0 ) ;
 lval = strtol ( date , & end , 10 ) ;
 error = ERRNO ;
 if ( error != old_errno ) SET_ERRNO ( old_errno ) ;
 if ( error ) return PARSEDATE_FAIL ;
 # if LONG_MAX != INT_MAX if ( ( lval > ( long ) INT_MAX ) || ( lval < ( long ) INT_MIN ) ) return PARSEDATE_FAIL ;
 # endif val = curlx_sltosi ( lval ) ;
 if ( ( tzoff == - 1 ) && ( ( end - date ) == 4 ) && ( val <= 1400 ) && ( indate < date ) && ( ( date [ - 1 ] == '+' || date [ - 1 ] == '-' ) ) ) {
 found = TRUE ;
 tzoff = ( val / 100 * 60 + val % 100 ) * 60 ;
 tzoff = date [ - 1 ] == '+' ? - tzoff : tzoff ;
 }
 if ( ( ( end - date ) == 8 ) && ( yearnum == - 1 ) && ( monnum == - 1 ) && ( mdaynum == - 1 ) ) {
 found = TRUE ;
 yearnum = val / 10000 ;
 monnum = ( val % 10000 ) / 100 - 1 ;
 mdaynum = val % 100 ;
 }
 if ( ! found && ( dignext == DATE_MDAY ) && ( mdaynum == - 1 ) ) {
 if ( ( val > 0 ) && ( val < 32 ) ) {
 mdaynum = val ;
 found = TRUE ;
 }
 dignext = DATE_YEAR ;
 }
 if ( ! found && ( dignext == DATE_YEAR ) && ( yearnum == - 1 ) ) {
 yearnum = val ;
 found = TRUE ;
 if ( yearnum < 1900 ) {
 if ( yearnum > 70 ) yearnum += 1900 ;
 else yearnum += 2000 ;
 }
 if ( mdaynum == - 1 ) dignext = DATE_MDAY ;
 }
 if ( ! found ) return PARSEDATE_FAIL ;
 date = end ;
 }
 }
 part ++ ;
 }
 if ( - 1 == secnum ) secnum = minnum = hournum = 0 ;
 if ( ( - 1 == mdaynum ) || ( - 1 == monnum ) || ( - 1 == yearnum ) ) return PARSEDATE_FAIL ;
 # if SIZEOF_TIME_T < 5 if ( yearnum > 2037 ) {
 * output = 0x7fffffff ;
 return PARSEDATE_LATER ;
 }
 # endif if ( yearnum < 1970 ) {
 * output = 0 ;
 return PARSEDATE_SOONER ;
 }
 if ( ( mdaynum > 31 ) || ( monnum > 11 ) || ( hournum > 23 ) || ( minnum > 59 ) || ( secnum > 60 ) ) return PARSEDATE_FAIL ;
 tm . tm_sec = secnum ;
 tm . tm_min = minnum ;
 tm . tm_hour = hournum ;
 tm . tm_mday = mdaynum ;
 tm . tm_mon = monnum ;
 tm . tm_year = yearnum - 1900 ;
 t = my_timegm ( & tm ) ;
 if ( - 1 != ( int ) t ) {
 long delta = ( long ) ( tzoff != - 1 ? tzoff : 0 ) ;
 if ( ( delta > 0 ) && ( t > LONG_MAX - delta ) ) {
 * output = 0x7fffffff ;
 return PARSEDATE_LATER ;
 }
 t += delta ;
 }
 * output = t ;
 return PARSEDATE_OK ;
 }


static int
nl80211_send_sched_scan_msg(struct sk_buff *msg,
			    struct cfg80211_registered_device *rdev,
			    struct net_device *netdev,
			    u32 pid, u32 seq, int flags, u32 cmd)
{
	void *hdr;

	hdr = nl80211hdr_put(msg, pid, seq, flags, cmd);
	if (!hdr)
		return -1;

	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);

	return genlmsg_end(msg, hdr);

 nla_put_failure:
	genlmsg_cancel(msg, hdr);
	return -EMSGSIZE;


static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,

    int *pnum)

{

    bool res;

    int i;

    if (n <= 0) {

        *pnum = 0;

        return 0;

    }

    res = !!memcmp(buf1, buf2, 512);

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

        buf1 += 512;

        buf2 += 512;

        if (!!memcmp(buf1, buf2, 512) != res) {

            break;

        }

    }

    *pnum = i;

    return res;

}


parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
	int num_items_scanned;
	guint8 character;
	guint8 byte;

	for (num_items_scanned = 0; num_items_scanned < 16; num_items_scanned++) {
		character = *rec++;
		if (character >= '0' && character <= '9')
			byte = character - '0' + 0;
		else if (character >= 'A' && character <= 'F')
			byte = character - 'A' + 0xA;
		else if (character >= 'a' && character <= 'f')
			byte = character - 'a' + 0xa;
		else if (character == ' ' || character == '\r' || character == '\n' || character == '\0') {
			/* Nothing more to parse */
			break;
		} else
			return -1; /* not a hex digit, space before ASCII dump, or EOL */
		byte <<= 4;
		character = *rec++ & 0xFF;
		if (character >= '0' && character <= '9')
			byte += character - '0' + 0;
		else if (character >= 'A' && character <= 'F')
			byte += character - 'A' + 0xA;
		else if (character >= 'a' && character <= 'f')
			byte += character - 'a' + 0xa;
		else
			return -1; /* not a hex digit */
		buf[byte_offset + num_items_scanned] = byte;
		character = *rec++ & 0xFF;
		if (character == '\0' || character == '\r' || character == '\n') {
			/* Nothing more to parse */
			break;
		} else if (character != ' ') {
			/* not space before ASCII dump */
			return -1;
		}
	}
	if (num_items_scanned == 0)
		return -1;

	return num_items_scanned;
}


void GraphicsContext::clearPlatformShadow()
{
    if (paintingDisabled())
        return;
    platformContext()->setDrawLooper(0);
}


IRC_PROTOCOL_CALLBACK(347)
{
    char *pos_args;
    struct t_irc_channel *ptr_channel;
    struct t_gui_buffer *ptr_buffer;
    struct t_irc_modelist *ptr_modelist;

    IRC_PROTOCOL_MIN_ARGS(4);

    pos_args = (argc > 4) ?
        ((argv_eol[4][0] == ':') ? argv_eol[4] + 1 : argv_eol[4]) : NULL;

    ptr_channel = irc_channel_search (server, argv[3]);
    ptr_buffer = (ptr_channel && ptr_channel->nicks) ?
        ptr_channel->buffer : server->buffer;
    ptr_modelist = irc_modelist_search (ptr_channel, 'I');
    if (ptr_modelist)
    {
        if (ptr_modelist->state != IRC_MODELIST_STATE_RECEIVING)
        {
            /*
             * remove all items if no invite was received before
             * the end of invite list
             */
            irc_modelist_item_free_all (ptr_modelist);
        }
        ptr_modelist->state = IRC_MODELIST_STATE_RECEIVED;
    }
    weechat_printf_date_tags (
        irc_msgbuffer_get_target_buffer (
            server, NULL, command, "invitelist", ptr_buffer),
        date,
        irc_protocol_tags (command, "irc_numeric", NULL, NULL),
        "%s%s[%s%s%s]%s%s%s",
        weechat_prefix ("network"),
        IRC_COLOR_CHAT_DELIMITERS,
        IRC_COLOR_CHAT_CHANNEL,
        argv[3],
        IRC_COLOR_CHAT_DELIMITERS,
        IRC_COLOR_RESET,
        (pos_args) ? " " : "",
        (pos_args) ? pos_args : "");

    return WEECHAT_RC_OK;
}


void sqlite3VdbeEnter(Vdbe *p){
  int i;
  sqlite3 *db;
  Db *aDb;
  int nDb;
  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
  db = p->db;
  aDb = db->aDb;
  nDb = db->nDb;
  for(i=0; i<nDb; i++){
    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
      sqlite3BtreeEnter(aDb[i].pBt);
    }
  }
}


void DesktopWindowTreeHostX11::OnCursorVisibilityChangedNative(bool show) {
}


void WebContentsAndroid::OnHide(JNIEnv* env, jobject obj) {
  web_contents_->WasHidden();
}


hup_get_color_string(VOID_ARGS)
{
    return (char *) 0;
}


static void dequant ( TwinContext * tctx , GetBitContext * gb , float * out , enum FrameType ftype , const int16_t * cb0 , const int16_t * cb1 , int cb_len ) {
 int pos = 0 ;
 int i , j ;
 for ( i = 0 ;
 i < tctx -> n_div [ ftype ] ;
 i ++ ) {
 int tmp0 , tmp1 ;
 int sign0 = 1 ;
 int sign1 = 1 ;
 const int16_t * tab0 , * tab1 ;
 int length = tctx -> length [ ftype ] [ i >= tctx -> length_change [ ftype ] ] ;
 int bitstream_second_part = ( i >= tctx -> bits_main_spec_change [ ftype ] ) ;
 int bits = tctx -> bits_main_spec [ 0 ] [ ftype ] [ bitstream_second_part ] ;
 if ( bits == 7 ) {
 if ( get_bits1 ( gb ) ) sign0 = - 1 ;
 bits = 6 ;
 }
 tmp0 = get_bits ( gb , bits ) ;
 bits = tctx -> bits_main_spec [ 1 ] [ ftype ] [ bitstream_second_part ] ;
 if ( bits == 7 ) {
 if ( get_bits1 ( gb ) ) sign1 = - 1 ;
 bits = 6 ;
 }
 tmp1 = get_bits ( gb , bits ) ;
 tab0 = cb0 + tmp0 * cb_len ;
 tab1 = cb1 + tmp1 * cb_len ;
 for ( j = 0 ;
 j < length ;
 j ++ ) out [ tctx -> permut [ ftype ] [ pos + j ] ] = sign0 * tab0 [ j ] + sign1 * tab1 [ j ] ;
 pos += length ;
 }
 }


  cf2_getUnitsPerEm( CFF_Decoder*  decoder )
  {
    FT_ASSERT( decoder && decoder->builder.face );
    FT_ASSERT( decoder->builder.face->root.units_per_EM );

    return decoder->builder.face->root.units_per_EM;
  }


static int write_trailer(AVFormatContext *s)

{

    WVMuxContext *wc = s->priv_data;

    AVIOContext *pb = s->pb;

    ff_ape_write(s);

    if (pb->seekable) {

        avio_seek(pb, 12, SEEK_SET);

        avio_wl32(pb, wc->duration);

        avio_flush(pb);

    }

    return 0;

}


static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
  Image *image,ExceptionInfo *exception)
{
  const StringInfo
    *icc_profile;

  MagickBooleanType
    status;

  PSDInfo
    psd_info;

  ssize_t
    i;

  size_t
    length,
    num_channels;

  StringInfo
    *bim_profile;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
  if (status == MagickFalse)
    return(status);
  psd_info.version=1;
  if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
      (image->columns > 30000) || (image->rows > 30000))
    psd_info.version=2;
  (void) WriteBlob(image,4,(const unsigned char *) "8BPS");
  (void) WriteBlobMSBShort(image,psd_info.version);  /* version */
  for (i=1; i <= 6; i++)
    (void) WriteBlobByte(image, 0);  /* 6 bytes of reserved */
  if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) &&
      (SetImageGray(image,exception) != MagickFalse))
    num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
  else
    if ((image_info->type != TrueColorType) &&
        (image_info->type != TrueColorAlphaType) &&
        (image->storage_class == PseudoClass))
      num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
    else
      {
        if (image->storage_class == PseudoClass)
          (void) SetImageStorageClass(image,DirectClass,exception);
        if (image->colorspace != CMYKColorspace)
          num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
        else
          num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
      }
  (void) WriteBlobMSBShort(image,(unsigned short) num_channels);
  (void) WriteBlobMSBLong(image,(unsigned int) image->rows);
  (void) WriteBlobMSBLong(image,(unsigned int) image->columns);
  if (IsImageGray(image) != MagickFalse)
    {
      MagickBooleanType
        monochrome;

      /*
        Write depth & mode.
      */
      monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
        MagickTrue : MagickFalse;
      (void) WriteBlobMSBShort(image,(unsigned short)
        (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
      (void) WriteBlobMSBShort(image,(unsigned short)
        (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
    }
  else
    {
      (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
        PseudoClass ? 8 : image->depth > 8 ? 16 : 8));

      if (((image_info->colorspace != UndefinedColorspace) ||
           (image->colorspace != CMYKColorspace)) &&
          (image_info->colorspace != CMYKColorspace))
        {
          (void) TransformImageColorspace(image,sRGBColorspace,exception);
          (void) WriteBlobMSBShort(image,(unsigned short)
            (image->storage_class == PseudoClass ? IndexedMode : RGBMode));
        }
      else
        {
          if (image->colorspace != CMYKColorspace)
            (void) TransformImageColorspace(image,CMYKColorspace,exception);
          (void) WriteBlobMSBShort(image,CMYKMode);
        }
    }
  if ((IsImageGray(image) != MagickFalse) ||
      (image->storage_class == DirectClass) || (image->colors > 256))
    (void) WriteBlobMSBLong(image,0);
  else
    {
      /*
        Write PSD raster colormap.
      */
      (void) WriteBlobMSBLong(image,768);
      for (i=0; i < (ssize_t) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
          image->colormap[i].red)));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
      for (i=0; i < (ssize_t) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
          image->colormap[i].green)));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
      for (i=0; i < (ssize_t) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
          image->colormap[i].blue)));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
    }
  /*
    Image resource block.
  */
  length=28; /* 0x03EB */
  bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
  icc_profile=GetImageProfile(image,"icc");
  if (bim_profile != (StringInfo *) NULL)
    {
      bim_profile=CloneStringInfo(bim_profile);
      if (icc_profile != (StringInfo *) NULL)
        RemoveICCProfileFromResourceBlock(bim_profile);
      RemoveResolutionFromResourceBlock(bim_profile);
      length+=PSDQuantum(GetStringInfoLength(bim_profile));
    }
  if (icc_profile != (const StringInfo *) NULL)
    length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
  (void) WriteBlobMSBLong(image,(unsigned int) length);
  WriteResolutionResourceBlock(image);
  if (bim_profile != (StringInfo *) NULL)
    {
      (void) WriteBlob(image,GetStringInfoLength(bim_profile),
        GetStringInfoDatum(bim_profile));
      bim_profile=DestroyStringInfo(bim_profile);
    }
  if (icc_profile != (StringInfo *) NULL)
    {
      (void) WriteBlob(image,4,(const unsigned char *) "8BIM");
      (void) WriteBlobMSBShort(image,0x0000040F);
      (void) WriteBlobMSBShort(image,0);
      (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
        icc_profile));
      (void) WriteBlob(image,GetStringInfoLength(icc_profile),
        GetStringInfoDatum(icc_profile));
      if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile)))
        (void) WriteBlobByte(image,0);
    }
  if (status != MagickFalse)
    {
      const char
        *option;

      CompressionType
        compression;

      MagickOffsetType
        size_offset;

      size_t
        size;

      size_offset=TellBlob(image);
      (void) SetPSDSize(&psd_info,image,0);
      option=GetImageOption(image_info,"psd:write-layers");
      if (IsStringFalse(option) != MagickTrue)
        {
          status=WritePSDLayersInternal(image,image_info,&psd_info,&size,
            exception);
          (void) WritePSDSize(&psd_info,image,size+
            (psd_info.version == 1 ? 8 : 12),size_offset);
          (void) WriteBlobMSBLong(image,0);  /* user mask data */
        }
      /*
        Write composite image.
      */
      compression=image->compression;
      if (image_info->compression != UndefinedCompression)
        image->compression=image_info->compression;
      if (image->compression == ZipCompression)
        image->compression=RLECompression;
      if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,
          exception) == 0)
        status=MagickFalse;
      image->compression=compression;
    }
  (void) CloseBlob(image);
  return(status);
}


client_skip_proxy(struct archive_read_filter *self, int64_t request)
{
	if (request < 0)
		__archive_errx(1, "Negative skip requested.");
	if (request == 0)
		return 0;

	if (self->archive->client.skipper != NULL) {
		/* Seek requests over 1GiB are broken down into
		 * multiple seeks.  This avoids overflows when the
		 * requests get passed through 32-bit arguments. */
		int64_t skip_limit = (int64_t)1 << 30;
		int64_t total = 0;
		for (;;) {
			int64_t get, ask = request;
			if (ask > skip_limit)
				ask = skip_limit;
			get = (self->archive->client.skipper)
				(&self->archive->archive, self->data, ask);
			if (get == 0)
				return (total);
			request -= get;
			total += get;
		}
	} else if (self->archive->client.seeker != NULL
		&& request > 64 * 1024) {
		/* If the client provided a seeker but not a skipper,
		 * we can use the seeker to skip forward.
		 *
		 * Note: This isn't always a good idea.  The client
		 * skipper is allowed to skip by less than requested
		 * if it needs to maintain block alignment.  The
		 * seeker is not allowed to play such games, so using
		 * the seeker here may be a performance loss compared
		 * to just reading and discarding.  That's why we
		 * only do this for skips of over 64k.
		 */
		int64_t before = self->position;
		int64_t after = (self->archive->client.seeker)
		    (&self->archive->archive, self->data, request, SEEK_CUR);
		if (after != before + request)
			return ARCHIVE_FATAL;
		return after - before;
	}
	return 0;
}


static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  int rc;                         /* Error code */
  char *zErr = 0;                 /* Error message */
  Vdbe *v = (Vdbe *)p->pStmt;

  /* Set the value of register r[1] in the SQL statement to integer iRow.
  ** This is done directly as a performance optimization
  */
  v->aMem[1].flags = MEM_Int;
  v->aMem[1].u.i = iRow;

  /* If the statement has been run before (and is paused at the OP_ResultRow)
  ** then back it up to the point where it does the OP_NotExists.  This could
  ** have been down with an extra OP_Goto, but simply setting the program
  ** counter is faster. */
  if( v->pc>4 ){
    v->pc = 4;
    assert( v->aOp[v->pc].opcode==OP_NotExists );
    rc = sqlite3VdbeExec(v);
  }else{
    rc = sqlite3_step(p->pStmt);
  }
  if( rc==SQLITE_ROW ){
    VdbeCursor *pC = v->apCsr[0];
    u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
    testcase( pC->nHdrParsed==p->iCol );
    testcase( pC->nHdrParsed==p->iCol+1 );
    if( type<12 ){
      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
          type==0?"null": type==7?"real": "integer"
      );
      rc = SQLITE_ERROR;
      sqlite3_finalize(p->pStmt);
      p->pStmt = 0;
    }else{
      p->iOffset = pC->aType[p->iCol + pC->nField];
      p->nByte = sqlite3VdbeSerialTypeLen(type);
      p->pCsr =  pC->uc.pCursor;
      sqlite3BtreeIncrblobCursor(p->pCsr);
    }
  }

  if( rc==SQLITE_ROW ){
    rc = SQLITE_OK;
  }else if( p->pStmt ){
    rc = sqlite3_finalize(p->pStmt);
    p->pStmt = 0;
    if( rc==SQLITE_OK ){
      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
      rc = SQLITE_ERROR;
    }else{
      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
    }
  }

  assert( rc!=SQLITE_OK || zErr==0 );
  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );

  *pzErr = zErr;
  return rc;
}


qemuProcessDetectIOThreadPIDs(virQEMUDriverPtr driver,
                              virDomainObjPtr vm,
                              int asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuMonitorIOThreadInfoPtr *iothreads = NULL;
    int niothreads = 0;
    int ret = -1;
    size_t i;

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_OBJECT_IOTHREAD)) {
        ret = 0;
        goto cleanup;
    }

    /* Get the list of IOThreads from qemu */
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        goto cleanup;
    ret = qemuMonitorGetIOThreads(priv->mon, &iothreads, &niothreads);
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        goto cleanup;
    if (ret < 0)
        goto cleanup;

    if (niothreads != vm->def->niothreadids) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("got wrong number of IOThread pids from QEMU monitor. "
                         "got %d, wanted %zu"),
                       niothreads, vm->def->niothreadids);
        goto cleanup;
    }

    /* Nothing to do */
    if (niothreads == 0) {
        ret = 0;
        goto cleanup;
    }

    for (i = 0; i < niothreads; i++) {
        virDomainIOThreadIDDefPtr iothrid;

        if (!(iothrid = virDomainIOThreadIDFind(vm->def,
                                                iothreads[i]->iothread_id))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("iothread %d not found"),
                           iothreads[i]->iothread_id);
            goto cleanup;
        }
        iothrid->thread_id = iothreads[i]->thread_id;
    }

    ret = 0;

 cleanup:
    if (iothreads) {
        for (i = 0; i < niothreads; i++)
            VIR_FREE(iothreads[i]);
        VIR_FREE(iothreads);
    }
    return ret;
}


static void musb_packet(MUSBState *s, MUSBEndPoint *ep,

                int epnum, int pid, int len, USBCallback cb, int dir)

{

    USBDevice *dev;

    int ret;

    int idx = epnum && dir;

    int ttype;

    /* ep->type[0,1] contains:

     * in bits 7:6 the speed (0 - invalid, 1 - high, 2 - full, 3 - slow)

     * in bits 5:4 the transfer type (BULK / INT)

     * in bits 3:0 the EP num

     */

    ttype = epnum ? (ep->type[idx] >> 4) & 3 : 0;

    ep->timeout[dir] = musb_timeout(ttype,

                    ep->type[idx] >> 6, ep->interval[idx]);

    ep->interrupt[dir] = ttype == USB_ENDPOINT_XFER_INT;

    ep->delayed_cb[dir] = cb;

    /* A wild guess on the FADDR semantics... */

    usb_packet_setup(&ep->packey[dir].p, pid, ep->faddr[idx],

                     ep->type[idx] & 0xf);

    usb_packet_addbuf(&ep->packey[dir].p, ep->buf[idx], len);

    ep->packey[dir].ep = ep;

    ep->packey[dir].dir = dir;

    dev = usb_find_device(&s->port, ep->packey[dir].p.devaddr);

    ret = usb_handle_packet(dev, &ep->packey[dir].p);

    if (ret == USB_RET_ASYNC) {

        ep->status[dir] = len;

        return;

    }

    ep->status[dir] = ret;

    musb_schedule_cb(&s->port, &ep->packey[dir].p);

}


void ByteCodeGenerator::TrackActivationObjectPropertyForDebugger(
    Js::DebuggerScope *debuggerScope,
    Symbol *symbol,
    Js::DebuggerScopePropertyFlags flags /*= Js::DebuggerScopePropertyFlags_None*/,
    bool isFunctionDeclaration /*= false*/)
{
    Assert(debuggerScope);
    Assert(symbol);

    // Only need to track activation object properties in debug mode.
    if (ShouldTrackDebuggerMetadata() && !symbol->GetIsTrackedForDebugger())
    {
        Js::RegSlot location = symbol->GetLocation();
        Js::PropertyId propertyId = symbol->EnsurePosition(this);

        this->Writer()->AddPropertyToDebuggerScope(
            debuggerScope,
            location,
            propertyId,
            /*shouldConsumeRegister*/ false,
            flags,
            isFunctionDeclaration);

        symbol->SetIsTrackedForDebugger(true);
    }
}


 void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
   WaitableEvent done(false, false);
   scoped_refptr<WorkerTask> task(new WorkerTask(work, &done));
  history_service_->ScheduleDBTask(task.get(), &cancelable_consumer_);
   done.Wait();
 }


RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation(
    const NavigationRequest& request) {
  DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme))
      << "Don't call this method for JavaScript URLs as those create a "
         "temporary  NavigationRequest and we don't want to reset an ongoing "
         "navigation's speculative RFH.";

  RenderFrameHostImpl* navigation_rfh = nullptr;

  SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
  scoped_refptr<SiteInstance> dest_site_instance =
      GetSiteInstanceForNavigationRequest(request);

  bool use_current_rfh = current_site_instance == dest_site_instance;

  bool notify_webui_of_rf_creation = false;
  if (use_current_rfh) {
    if (speculative_render_frame_host_) {
      if (request.from_begin_navigation()) {
        std::set<int> ids = speculative_render_frame_host_
                                ->GetNavigationEntryIdsPendingCommit();
        for (int id : ids)
          frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(id);
      }
      DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost());
    }

    if (frame_tree_node_->IsMainFrame()) {
      UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url,
                                           request.bindings());
    }

    navigation_rfh = render_frame_host_.get();

    DCHECK(!speculative_render_frame_host_);
  } else {

    if (!speculative_render_frame_host_ ||
        speculative_render_frame_host_->GetSiteInstance() !=
            dest_site_instance.get()) {
      if (request.from_begin_navigation() && speculative_render_frame_host_) {
        std::set<int> ids = speculative_render_frame_host_
                                ->GetNavigationEntryIdsPendingCommit();
        for (int id : ids)
          frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded(id);
      }

      CleanUpNavigation();
      bool success = CreateSpeculativeRenderFrameHost(current_site_instance,
                                                      dest_site_instance.get());
      DCHECK(success);
    }
    DCHECK(speculative_render_frame_host_);

    if (frame_tree_node_->IsMainFrame()) {
      bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI(
          request.common_params().url, request.bindings());
      speculative_render_frame_host_->CommitPendingWebUI();
      DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui());
      notify_webui_of_rf_creation =
          changed_web_ui && speculative_render_frame_host_->web_ui();
    }
    navigation_rfh = speculative_render_frame_host_.get();

    if (!render_frame_host_->IsRenderFrameLive()) {
      if (GetRenderFrameProxyHost(dest_site_instance.get())) {
        navigation_rfh->Send(
            new FrameMsg_SwapIn(navigation_rfh->GetRoutingID()));
      }
      CommitPending();

      if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) {
        render_frame_host_->web_ui()->RenderFrameCreated(
            render_frame_host_.get());
        notify_webui_of_rf_creation = false;
      }
    }
  }
  DCHECK(navigation_rfh &&
         (navigation_rfh == render_frame_host_.get() ||
          navigation_rfh == speculative_render_frame_host_.get()));

  if (!navigation_rfh->IsRenderFrameLive()) {
    if (!ReinitializeRenderFrame(navigation_rfh))
      return nullptr;

    notify_webui_of_rf_creation = true;

    if (navigation_rfh == render_frame_host_.get()) {
      EnsureRenderFrameHostVisibilityConsistent();
      EnsureRenderFrameHostPageFocusConsistent();
      delegate_->NotifyMainFrameSwappedFromRenderManager(
          nullptr, render_frame_host_.get());
    }
  }

  if (notify_webui_of_rf_creation && GetNavigatingWebUI() &&
      frame_tree_node_->IsMainFrame()) {
    GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh);
  }

  return navigation_rfh;
}


static int pre_estimate_motion_thread ( AVCodecContext * c , void * arg ) {
 MpegEncContext * s = * ( void * * ) arg ;
 s -> me . pre_pass = 1 ;
 s -> me . dia_size = s -> avctx -> pre_dia_size ;
 s -> first_slice_line = 1 ;
 for ( s -> mb_y = s -> end_mb_y - 1 ;
 s -> mb_y >= s -> start_mb_y ;
 s -> mb_y -- ) {
 for ( s -> mb_x = s -> mb_width - 1 ;
 s -> mb_x >= 0 ;
 s -> mb_x -- ) {
 ff_pre_estimate_p_frame_motion ( s , s -> mb_x , s -> mb_y ) ;
 }
 s -> first_slice_line = 0 ;
 }
 s -> me . pre_pass = 0 ;
 return 0 ;
 }


void DevToolsUIBindings::AddFileSystem(const std::string& file_system_path) {
  CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme));
  file_helper_->AddFileSystem(
      file_system_path,
      base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar,
                 weak_factory_.GetWeakPtr()));
}


static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
	jpc_sot_t *sot = &ms->parms.sot;

	/* Eliminate compiler warning about unused variables. */
	cstate = 0;

	if (jpc_getuint16(in, &sot->tileno) ||
	  jpc_getuint32(in, &sot->len) ||
	  jpc_getuint8(in, &sot->partno) ||
	  jpc_getuint8(in, &sot->numparts)) {
		return -1;
	}
	if (sot->tileno > 65534 || sot->len < 12 || sot->partno > 254 ||
	  sot->numparts < 1 || sot->numparts > 255) {
		return -1;
	}
	if (jas_stream_eof(in)) {
		return -1;
	}
	return 0;
}


static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    AVIContext *avi = s->priv_data;

    AVStream *st;

    int i, index;

    int64_t pos;

    AVIStream *ast;

    if (!avi->index_loaded) {

        /* we only load the index on demand */

        avi_load_index(s);

        avi->index_loaded = 1;

    }

    assert(stream_index>= 0);

    st = s->streams[stream_index];

    ast= st->priv_data;

    index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);

    if(index<0)

        return -1;

    /* find the position */

    pos = st->index_entries[index].pos;

    timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);

    av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",

            timestamp, index, st->index_entries[index].timestamp);

    if (CONFIG_DV_DEMUXER && avi->dv_demux) {

        /* One and only one real stream for DV in AVI, and it has video  */

        /* offsets. Calling with other stream indexes should have failed */

        /* the av_index_search_timestamp call above.                     */

        assert(stream_index == 0);

        /* Feed the DV video stream version of the timestamp to the */

        /* DV demux so it can synthesize correct timestamps.        */

        ff_dv_offset_reset(avi->dv_demux, timestamp);

        avio_seek(s->pb, pos, SEEK_SET);

        avi->stream_index= -1;

        return 0;

    }

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

        AVStream *st2 = s->streams[i];

        AVIStream *ast2 = st2->priv_data;

        ast2->packet_size=

        ast2->remaining= 0;

        if (ast2->sub_ctx) {

            seek_subtitle(st, st2, timestamp);

            continue;

        }

        if (st2->nb_index_entries <= 0)

            continue;

//        assert(st2->codec->block_align);

        assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);

        index = av_index_search_timestamp(

                st2,

                av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),

                flags | AVSEEK_FLAG_BACKWARD);

        if(index<0)

            index=0;

        if(!avi->non_interleaved){

            while(index>0 && st2->index_entries[index].pos > pos)

                index--;

            while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)

                index++;

        }

        av_dlog(s, "%"PRId64" %d %"PRId64"\n",

                timestamp, index, st2->index_entries[index].timestamp);

        /* extract the current frame number */

        ast2->frame_offset = st2->index_entries[index].timestamp;

    }

    /* do the seek */

    avio_seek(s->pb, pos, SEEK_SET);

    avi->stream_index= -1;

    return 0;

}


void SoftAAC2::initPorts() {
    OMX_PARAM_PORTDEFINITIONTYPE def;
 InitOMXParams(&def);

    def.nPortIndex = 0;
    def.eDir = OMX_DirInput;
    def.nBufferCountMin = kNumInputBuffers;
    def.nBufferCountActual = def.nBufferCountMin;
    def.nBufferSize = 8192;
    def.bEnabled = OMX_TRUE;
    def.bPopulated = OMX_FALSE;
    def.eDomain = OMX_PortDomainAudio;
    def.bBuffersContiguous = OMX_FALSE;
    def.nBufferAlignment = 1;

    def.format.audio.cMIMEType = const_cast<char *>("audio/aac");
    def.format.audio.pNativeRender = NULL;
    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
    def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;

    addPort(def);

    def.nPortIndex = 1;
    def.eDir = OMX_DirOutput;
    def.nBufferCountMin = kNumOutputBuffers;
    def.nBufferCountActual = def.nBufferCountMin;
    def.nBufferSize = 4096 * MAX_CHANNEL_COUNT;
    def.bEnabled = OMX_TRUE;
    def.bPopulated = OMX_FALSE;
    def.eDomain = OMX_PortDomainAudio;
    def.bBuffersContiguous = OMX_FALSE;
    def.nBufferAlignment = 2;

    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
    def.format.audio.pNativeRender = NULL;
    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;

    addPort(def);
}


void ExternalProtocolHandler::RecordHandleStateMetrics(bool checkbox_selected,
                                                       BlockState block_state) {
  HandleState handle_state = DONT_LAUNCH;
  switch (block_state) {
    case DONT_BLOCK:
      handle_state = checkbox_selected ? CHECKED_LAUNCH : LAUNCH;
      break;
    case BLOCK:
      handle_state =
          checkbox_selected ? CHECKED_DONT_LAUNCH_DEPRECATED : DONT_LAUNCH;
      break;
    case UNKNOWN:
      NOTREACHED();
      return;
  }
  DCHECK_NE(CHECKED_DONT_LAUNCH_DEPRECATED, handle_state);
  UMA_HISTOGRAM_ENUMERATION(kHandleStateMetric, handle_state,
                            HANDLE_STATE_LAST);
}


static inline void register_rt_sched_group(struct task_group *tg, int cpu)
{
}


long BlockEntry::GetIndex() const { return m_index; }


static void compile_backtrackingpath(compiler_common *common, struct backtrack_common *current)
{
DEFINE_COMPILER;
then_trap_backtrack *save_then_trap = common->then_trap;

while (current)
  {
  if (current->nextbacktracks != NULL)
    set_jumps(current->nextbacktracks, LABEL());
  switch(*current->cc)
    {
    case OP_SET_SOM:
    OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0));
    free_stack(common, 1);
    OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP1, 0);
    break;

    case OP_STAR:
    case OP_MINSTAR:
    case OP_PLUS:
    case OP_MINPLUS:
    case OP_QUERY:
    case OP_MINQUERY:
    case OP_UPTO:
    case OP_MINUPTO:
    case OP_EXACT:
    case OP_POSSTAR:
    case OP_POSPLUS:
    case OP_POSQUERY:
    case OP_POSUPTO:
    case OP_STARI:
    case OP_MINSTARI:
    case OP_PLUSI:
    case OP_MINPLUSI:
    case OP_QUERYI:
    case OP_MINQUERYI:
    case OP_UPTOI:
    case OP_MINUPTOI:
    case OP_EXACTI:
    case OP_POSSTARI:
    case OP_POSPLUSI:
    case OP_POSQUERYI:
    case OP_POSUPTOI:
    case OP_NOTSTAR:
    case OP_NOTMINSTAR:
    case OP_NOTPLUS:
    case OP_NOTMINPLUS:
    case OP_NOTQUERY:
    case OP_NOTMINQUERY:
    case OP_NOTUPTO:
    case OP_NOTMINUPTO:
    case OP_NOTEXACT:
    case OP_NOTPOSSTAR:
    case OP_NOTPOSPLUS:
    case OP_NOTPOSQUERY:
    case OP_NOTPOSUPTO:
    case OP_NOTSTARI:
    case OP_NOTMINSTARI:
    case OP_NOTPLUSI:
    case OP_NOTMINPLUSI:
    case OP_NOTQUERYI:
    case OP_NOTMINQUERYI:
    case OP_NOTUPTOI:
    case OP_NOTMINUPTOI:
    case OP_NOTEXACTI:
    case OP_NOTPOSSTARI:
    case OP_NOTPOSPLUSI:
    case OP_NOTPOSQUERYI:
    case OP_NOTPOSUPTOI:
    case OP_TYPESTAR:
    case OP_TYPEMINSTAR:
    case OP_TYPEPLUS:
    case OP_TYPEMINPLUS:
    case OP_TYPEQUERY:
    case OP_TYPEMINQUERY:
    case OP_TYPEUPTO:
    case OP_TYPEMINUPTO:
    case OP_TYPEEXACT:
    case OP_TYPEPOSSTAR:
    case OP_TYPEPOSPLUS:
    case OP_TYPEPOSQUERY:
    case OP_TYPEPOSUPTO:
    case OP_CLASS:
    case OP_NCLASS:
#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8
    case OP_XCLASS:
#endif
    compile_iterator_backtrackingpath(common, current);
    break;

    case OP_REF:
    case OP_REFI:
    case OP_DNREF:
    case OP_DNREFI:
    compile_ref_iterator_backtrackingpath(common, current);
    break;

    case OP_RECURSE:
    compile_recurse_backtrackingpath(common, current);
    break;

    case OP_ASSERT:
    case OP_ASSERT_NOT:
    case OP_ASSERTBACK:
    case OP_ASSERTBACK_NOT:
    compile_assert_backtrackingpath(common, current);
    break;

    case OP_ASSERT_NA:
    case OP_ASSERTBACK_NA:
    case OP_ONCE:
    case OP_SCRIPT_RUN:
    case OP_BRA:
    case OP_CBRA:
    case OP_COND:
    case OP_SBRA:
    case OP_SCBRA:
    case OP_SCOND:
    compile_bracket_backtrackingpath(common, current);
    break;

    case OP_BRAZERO:
    if (current->cc[1] > OP_ASSERTBACK_NOT)
      compile_bracket_backtrackingpath(common, current);
    else
      compile_assert_backtrackingpath(common, current);
    break;

    case OP_BRAPOS:
    case OP_CBRAPOS:
    case OP_SBRAPOS:
    case OP_SCBRAPOS:
    case OP_BRAPOSZERO:
    compile_bracketpos_backtrackingpath(common, current);
    break;

    case OP_BRAMINZERO:
    compile_braminzero_backtrackingpath(common, current);
    break;

    case OP_MARK:
    OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0));
    if (common->has_skip_arg)
      OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0));
    free_stack(common, common->has_skip_arg ? 5 : 1);
    OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0);
    if (common->has_skip_arg)
      OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0);
    break;

    case OP_THEN:
    case OP_THEN_ARG:
    case OP_PRUNE:
    case OP_PRUNE_ARG:
    case OP_SKIP:
    case OP_SKIP_ARG:
    compile_control_verb_backtrackingpath(common, current);
    break;

    case OP_COMMIT:
    case OP_COMMIT_ARG:
    if (!common->local_quit_available)
      OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE2_ERROR_NOMATCH);
    if (common->quit_label == NULL)
      add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP));
    else
      JUMPTO(SLJIT_JUMP, common->quit_label);
    break;

    case OP_CALLOUT:
    case OP_CALLOUT_STR:
    case OP_FAIL:
    case OP_ACCEPT:
    case OP_ASSERT_ACCEPT:
    set_jumps(current->topbacktracks, LABEL());
    break;

    case OP_THEN_TRAP:
    /* A virtual opcode for then traps. */
    compile_then_trap_backtrackingpath(common, current);
    break;

    default:
    SLJIT_UNREACHABLE();
    break;
    }
  current = current->prev;
  }
common->then_trap = save_then_trap;
}


int graph_cairo_setup (image_desc_t *im)
{
    /* the actual graph is created by going through the individual
       graph elements and then drawing them */
    cairo_surface_destroy(im->surface);
    switch (im->imgformat) {
    case IF_PNG:
        im->surface =
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
                                       im->ximg * im->zoom,
                                       im->yimg * im->zoom);
        break;
    case IF_PDF:
        im->gridfit = 0;
        im->surface = strlen(im->graphfile)
            ? cairo_pdf_surface_create(im->graphfile, im->ximg * im->zoom,
                                       im->yimg * im->zoom)
            : cairo_pdf_surface_create_for_stream
            (&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
        break;
    case IF_EPS:
        im->gridfit = 0;
        im->surface = strlen(im->graphfile)
            ?
            cairo_ps_surface_create(im->graphfile, im->ximg * im->zoom,
                                    im->yimg * im->zoom)
            : cairo_ps_surface_create_for_stream
            (&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
        break;
    case IF_SVG:
        im->gridfit = 0;
        im->surface = strlen(im->graphfile)
            ?
            cairo_svg_surface_create(im->
                                     graphfile,
                                     im->ximg * im->zoom, im->yimg * im->zoom)
            : cairo_svg_surface_create_for_stream
            (&cairo_output, im, im->ximg * im->zoom, im->yimg * im->zoom);
        cairo_svg_surface_restrict_to_version
            (im->surface, CAIRO_SVG_VERSION_1_1);
        break;
    case IF_XML:
    case IF_XMLENUM:
    case IF_CSV:
    case IF_TSV:
    case IF_SSV:
    case IF_JSON:
    case IF_JSONTIME:
        break;
    };
    cairo_destroy(im->cr);
    im->cr = cairo_create(im->surface);
    cairo_set_antialias(im->cr, im->graph_antialias);
    cairo_scale(im->cr, im->zoom, im->zoom);
//    pango_cairo_font_map_set_resolution(PANGO_CAIRO_FONT_MAP(font_map), 100);
    gfx_new_area(im, 0, 0, 0, im->yimg,
                 im->ximg, im->yimg, im->graph_col[GRC_BACK]);
    gfx_add_point(im, im->ximg, 0);
    gfx_close_path(im);
    gfx_new_area(im, im->xorigin,
                 im->yorigin,
                 im->xorigin +
                 im->xsize, im->yorigin,
                 im->xorigin +
                 im->xsize,
                 im->yorigin - im->ysize, im->graph_col[GRC_CANVAS]);
    gfx_add_point(im, im->xorigin, im->yorigin - im->ysize);
    gfx_close_path(im);
    cairo_rectangle(im->cr, im->xorigin, im->yorigin - im->ysize - 1.0,
                    im->xsize, im->ysize + 2.0);
    cairo_clip(im->cr);
    return 0;
}


pjmedia_avi_player_create_streams(pj_pool_t *pool,
                                  const char *filename,
				  unsigned options,
				  pjmedia_avi_streams **p_streams)
{
    pjmedia_avi_hdr avi_hdr;
    struct avi_reader_port *fport[PJMEDIA_AVI_MAX_NUM_STREAMS];
    pj_off_t pos;
    unsigned i, nstr = 0;
    pj_status_t status = PJ_SUCCESS;

    /* Check arguments. */
    PJ_ASSERT_RETURN(pool && filename && p_streams, PJ_EINVAL);

    /* Check the file really exists. */
    if (!pj_file_exists(filename)) {
	return PJ_ENOTFOUND;
    }

    /* Create fport instance. */
    fport[0] = create_avi_port(pool);
    if (!fport[0]) {
	return PJ_ENOMEM;
    }

    /* Get the file size. */
    fport[0]->fsize = pj_file_size(filename);

    /* Size must be more than AVI header size */
    if (fport[0]->fsize <= sizeof(riff_hdr_t) + sizeof(avih_hdr_t) +
                           sizeof(strl_hdr_t))
    {
	return PJMEDIA_EINVALIMEDIATYPE;
    }

    /* Open file. */
    status = pj_file_open(pool, filename, PJ_O_RDONLY, &fport[0]->fd);
    if (status != PJ_SUCCESS)
	return status;

    /* Read the RIFF + AVIH header. */
    status = file_read(fport[0]->fd, &avi_hdr,
                       sizeof(riff_hdr_t) + sizeof(avih_hdr_t));
    if (status != PJ_SUCCESS)
        goto on_error;

    /* Validate AVI file. */
    if (!COMPARE_TAG(avi_hdr.riff_hdr.riff, PJMEDIA_AVI_RIFF_TAG) ||
	!COMPARE_TAG(avi_hdr.riff_hdr.avi, PJMEDIA_AVI_AVI_TAG) ||
        !COMPARE_TAG(avi_hdr.avih_hdr.list_tag, PJMEDIA_AVI_LIST_TAG) ||
        !COMPARE_TAG(avi_hdr.avih_hdr.hdrl_tag, PJMEDIA_AVI_HDRL_TAG) ||
        !COMPARE_TAG(avi_hdr.avih_hdr.avih, PJMEDIA_AVI_AVIH_TAG))
    {
	status = PJMEDIA_EINVALIMEDIATYPE;
        goto on_error;
    }

    PJ_LOG(5, (THIS_FILE, "The AVI file has %d streams.",
               avi_hdr.avih_hdr.num_streams));

    /* Unsupported AVI format. */
    if (avi_hdr.avih_hdr.num_streams > PJMEDIA_AVI_MAX_NUM_STREAMS) {
        status = PJMEDIA_EAVIUNSUPP;
        goto on_error;
    }

    /**
     * TODO: Possibly unsupported AVI format.
     * If you encounter this warning, verify whether the avi player
     * is working properly.
     */
    if (avi_hdr.avih_hdr.flags & AVIF_MUSTUSEINDEX ||
        avi_hdr.avih_hdr.pad > 1)
    {
        PJ_LOG(3, (THIS_FILE, "Warning!!! Possibly unsupported AVI format: "
                   "flags:%d, pad:%d", avi_hdr.avih_hdr.flags,
                   avi_hdr.avih_hdr.pad));
    }

    /* Read the headers of each stream. */
    for (i = 0; i < avi_hdr.avih_hdr.num_streams; i++) {
        pj_size_t elem = 0;
        pj_ssize_t size_to_read;

        /* Read strl header */
        status = file_read(fport[0]->fd, &avi_hdr.strl_hdr[i],
                           sizeof(strl_hdr_t));
        if (status != PJ_SUCCESS)
            goto on_error;

        elem = COMPARE_TAG(avi_hdr.strl_hdr[i].data_type,
                           PJMEDIA_AVI_VIDS_TAG) ?
               sizeof(strf_video_hdr_t) :
               COMPARE_TAG(avi_hdr.strl_hdr[i].data_type,
                           PJMEDIA_AVI_AUDS_TAG) ?
               sizeof(strf_audio_hdr_t) : 0;

        /* Read strf header */
        status = file_read2(fport[0]->fd, &avi_hdr.strf_hdr[i],
                            elem, 0);
        if (status != PJ_SUCCESS)
            goto on_error;

        /* Normalize the endian */
        if (elem == sizeof(strf_video_hdr_t))
            data_to_host2(&avi_hdr.strf_hdr[i],
                          sizeof(strf_video_hdr_sizes)/
                          sizeof(strf_video_hdr_sizes[0]),
                          strf_video_hdr_sizes);
        else if (elem == sizeof(strf_audio_hdr_t))
            data_to_host2(&avi_hdr.strf_hdr[i],
                          sizeof(strf_audio_hdr_sizes)/
                          sizeof(strf_audio_hdr_sizes[0]),
                          strf_audio_hdr_sizes);

        /* Skip the remainder of the header */
        size_to_read = avi_hdr.strl_hdr[i].list_sz - (sizeof(strl_hdr_t) -
                       8) - elem;
	status = pj_file_setpos(fport[0]->fd, size_to_read, PJ_SEEK_CUR);
	if (status != PJ_SUCCESS) {
            goto on_error;
	}
    }

    /* Finish reading the AVIH header */
    status = pj_file_setpos(fport[0]->fd, avi_hdr.avih_hdr.list_sz +
                            sizeof(riff_hdr_t) + 8, PJ_SEEK_SET);
    if (status != PJ_SUCCESS) {
        goto on_error;
    }

    /* Skip any JUNK or LIST INFO until we get MOVI tag */
    do {
        pjmedia_avi_subchunk ch;
        int read = 0;

        status = file_read(fport[0]->fd, &ch, sizeof(pjmedia_avi_subchunk));
        if (status != PJ_SUCCESS) {
            goto on_error;
        }

        if (COMPARE_TAG(ch.id, PJMEDIA_AVI_LIST_TAG))
        {
            read = 4;
            status = file_read(fport[0]->fd, &ch, read);
            if (COMPARE_TAG(ch.id, PJMEDIA_AVI_MOVI_TAG))
                break;
        }

        status = pj_file_setpos(fport[0]->fd, ch.len-read, PJ_SEEK_CUR);
        if (status != PJ_SUCCESS) {
            goto on_error;
        }
    } while(1);

    status = pj_file_getpos(fport[0]->fd, &pos);
    if (status != PJ_SUCCESS)
        goto on_error;

    for (i = 0, nstr = 0; i < avi_hdr.avih_hdr.num_streams; i++) {
	pjmedia_format_id fmt_id;

        /* Skip non-audio, non-video, or disabled streams) */
        if ((!COMPARE_TAG(avi_hdr.strl_hdr[i].data_type,
                          PJMEDIA_AVI_VIDS_TAG) &&
             !COMPARE_TAG(avi_hdr.strl_hdr[i].data_type,
                          PJMEDIA_AVI_AUDS_TAG)) ||
            avi_hdr.strl_hdr[i].flags & AVISF_DISABLED)
        {
            continue;
        }

        if (COMPARE_TAG(avi_hdr.strl_hdr[i].data_type,
                        PJMEDIA_AVI_VIDS_TAG))
        {
            int j;

            if (avi_hdr.strl_hdr[i].flags & AVISF_VIDEO_PALCHANGES) {
                PJ_LOG(4, (THIS_FILE, "Unsupported video stream"));
                continue;
            }

            fmt_id = avi_hdr.strl_hdr[i].codec;
            for (j = sizeof(avi_fmts)/sizeof(avi_fmts[0])-1; j >= 0; j--) {
                /* Check supported video formats here */
                if (fmt_id == avi_fmts[j].fmt_id) {
                    if (avi_fmts[j].eff_fmt_id)
                        fmt_id = avi_fmts[j].eff_fmt_id;
                    break;
                }
            }

            if (j < 0) {
                PJ_LOG(4, (THIS_FILE, "Unsupported video stream"));
                continue;
            }
        } else {
            /* Check supported audio formats here */
	    strf_audio_hdr_t *hdr = (strf_audio_hdr_t*)
				    &avi_hdr.strf_hdr[i].strf_audio_hdr;
            if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_PCM &&
		hdr->bits_per_sample == 16)
	    {
		fmt_id = PJMEDIA_FORMAT_PCM;
	    }
	    else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ALAW)
	    {
		fmt_id = PJMEDIA_FORMAT_PCMA;
	    }
	    else if (hdr->fmt_tag == PJMEDIA_WAVE_FMT_TAG_ULAW)
	    {
		fmt_id = PJMEDIA_FORMAT_PCMU;
	    }
	    else
            {
                PJ_LOG(4, (THIS_FILE, "Unsupported audio stream"));
                continue;
            }
        }

        if (nstr > 0) {
            /* Create fport instance. */
            fport[nstr] = create_avi_port(pool);
            if (!fport[nstr]) {
	        status = PJ_ENOMEM;
                goto on_error;
            }

            /* Open file. */
            status = pj_file_open(pool, filename, PJ_O_RDONLY,
                                  &fport[nstr]->fd);
            if (status != PJ_SUCCESS)
                goto on_error;

            /* Set the file position */
            status = pj_file_setpos(fport[nstr]->fd, pos, PJ_SEEK_SET);
            if (status != PJ_SUCCESS) {
                goto on_error;
            }
        }

        fport[nstr]->stream_id = i;
        fport[nstr]->fmt_id = fmt_id;

        nstr++;
    }

    if (nstr == 0) {
        status = PJMEDIA_EAVIUNSUPP;
        goto on_error;
    }

    for (i = 0; i < nstr; i++) {
        strl_hdr_t *strl_hdr = &avi_hdr.strl_hdr[fport[i]->stream_id];

        /* Initialize */
        fport[i]->options = options;
        fport[i]->fsize = fport[0]->fsize;
        /* Current file position now points to start of data */
        fport[i]->start_data = pos;

        if (COMPARE_TAG(strl_hdr->data_type, PJMEDIA_AVI_VIDS_TAG)) {
            strf_video_hdr_t *strf_hdr =
                &avi_hdr.strf_hdr[fport[i]->stream_id].strf_video_hdr;
            const pjmedia_video_format_info *vfi;

            vfi = pjmedia_get_video_format_info(
                pjmedia_video_format_mgr_instance(),
                strl_hdr->codec);

            fport[i]->bits_per_sample = (vfi ? vfi->bpp : 0);
            fport[i]->usec_per_frame = avi_hdr.avih_hdr.usec_per_frame;
            pjmedia_format_init_video(&fport[i]->base.info.fmt,
                                      fport[i]->fmt_id,
                                      strf_hdr->biWidth,
                                      strf_hdr->biHeight,
                                      strl_hdr->rate,
                                      strl_hdr->scale);
#if 0
            /* The calculation below is wrong. strf_hdr->biSizeImage shows
             * uncompressed size. Looks like we need to go the ugly way to
             * get the bitrage:
             *    http://www.virtualdub.org/blog/pivot/entry.php?id=159
             */
            bps = strf_hdr->biSizeImage * 8 * strl_hdr->rate / strl_hdr->scale;
            if (bps==0) {
        	/* strf_hdr->biSizeImage may be zero for uncompressed RGB */
        	bps = strf_hdr->biWidth * strf_hdr->biHeight *
        		strf_hdr->biBitCount *
        		strl_hdr->rate / strl_hdr->scale;
            }
            fport[i]->base.info.fmt.det.vid.avg_bps = bps;
            fport[i]->base.info.fmt.det.vid.max_bps = bps;
#endif
        } else {
            strf_audio_hdr_t *strf_hdr =
                &avi_hdr.strf_hdr[fport[i]->stream_id].strf_audio_hdr;

            fport[i]->bits_per_sample = strf_hdr->bits_per_sample;
            fport[i]->usec_per_frame = avi_hdr.avih_hdr.usec_per_frame;
            pjmedia_format_init_audio(&fport[i]->base.info.fmt,
                                      fport[i]->fmt_id,
                                      strf_hdr->sample_rate,
                                      strf_hdr->nchannels,
                                      strf_hdr->bits_per_sample,
                                      20000 /* fport[i]->usec_per_frame */,
                                      strf_hdr->bytes_per_sec * 8,
                                      strf_hdr->bytes_per_sec * 8);

	    /* Set format to PCM (we will decode PCMA/U) */
	    if (fport[i]->fmt_id == PJMEDIA_FORMAT_PCMA ||
		fport[i]->fmt_id == PJMEDIA_FORMAT_PCMU)
	    {
		fport[i]->base.info.fmt.id = PJMEDIA_FORMAT_PCM;
		fport[i]->base.info.fmt.det.aud.bits_per_sample = 16;
	    }
	}

        pj_strdup2(pool, &fport[i]->base.info.name, filename);
    }

    /* Done. */
    *p_streams = pj_pool_alloc(pool, sizeof(pjmedia_avi_streams));
    (*p_streams)->num_streams = nstr;
    (*p_streams)->streams = pj_pool_calloc(pool, (*p_streams)->num_streams,
                                           sizeof(pjmedia_port *));
    for (i = 0; i < nstr; i++)
        (*p_streams)->streams[i] = &fport[i]->base;

    PJ_LOG(4,(THIS_FILE,
	      "AVI file player '%.*s' created with "
	      "%d media ports",
	      (int)fport[0]->base.info.name.slen,
	      fport[0]->base.info.name.ptr,
              (*p_streams)->num_streams));

    return PJ_SUCCESS;

on_error:
    fport[0]->base.on_destroy(&fport[0]->base);
    for (i = 1; i < nstr; i++)
        fport[i]->base.on_destroy(&fport[i]->base);
    if (status == AVI_EOF)
        return PJMEDIA_EINVALIMEDIATYPE;
    return status;
}


JsVar *jspeConditionalExpression() {
  return __jspeConditionalExpression(jspeBinaryExpression());
}


static void dumpgasp ( struct alltabs * at , SplineFont * sf ) {
 int i ;
 at -> gaspf = tmpfile ( ) ;
 if ( sf -> gasp_cnt == 0 ) {
 putshort ( at -> gaspf , 0 ) ;
 putshort ( at -> gaspf , 1 ) ;
 putshort ( at -> gaspf , 0xffff ) ;
 putshort ( at -> gaspf , 0x2 ) ;
 }
 else {
 putshort ( at -> gaspf , sf -> gasp_version ) ;
 putshort ( at -> gaspf , sf -> gasp_cnt ) ;
 for ( i = 0 ;
 i < sf -> gasp_cnt ;
 ++ i ) {
 putshort ( at -> gaspf , sf -> gasp [ i ] . ppem ) ;
 putshort ( at -> gaspf , sf -> gasp [ i ] . flags ) ;
 }
 }
 at -> gasplen = ftell ( at -> gaspf ) ;
 }


static void acceptCommonHandler(int fd, int flags, char *ip) {
    client *c;
    if ((c = createClient(fd)) == NULL) {
        serverLog(LL_WARNING,
            "Error registering fd event for the new client: %s (fd=%d)",
            strerror(errno),fd);
        close(fd); /* May be already closed, just ignore errors */
        return;
    }
    /* If maxclient directive is set and this is one client more... close the
     * connection. Note that we create the client instead to check before
     * for this condition, since now the socket is already set in non-blocking
     * mode and we can send an error for free using the Kernel I/O */
    if (listLength(server.clients) > server.maxclients) {
        char *err = "-ERR max number of clients reached\r\n";

        /* That's a best effort error message, don't check write errors */
        if (write(c->fd,err,strlen(err)) == -1) {
            /* Nothing to do, Just to avoid the warning... */
        }
        server.stat_rejected_conn++;
        freeClient(c);
        return;
    }

    /* If the server is running in protected mode (the default) and there
     * is no password set, nor a specific interface is bound, we don't accept
     * requests from non loopback interfaces. Instead we try to explain the
     * user what to do to fix it if needed. */
    if (server.protected_mode &&
        server.bindaddr_count == 0 &&
        server.requirepass == NULL &&
        !(flags & CLIENT_UNIX_SOCKET) &&
        ip != NULL)
    {
        if (strcmp(ip,"127.0.0.1") && strcmp(ip,"::1")) {
            char *err =
                "-DENIED Redis is running in protected mode because protected "
                "mode is enabled, no bind address was specified, no "
                "authentication password is requested to clients. In this mode "
                "connections are only accepted from the loopback interface. "
                "If you want to connect from external computers to Redis you "
                "may adopt one of the following solutions: "
                "1) Just disable protected mode sending the command "
                "'CONFIG SET protected-mode no' from the loopback interface "
                "by connecting to Redis from the same host the server is "
                "running, however MAKE SURE Redis is not publicly accessible "
                "from internet if you do so. Use CONFIG REWRITE to make this "
                "change permanent. "
                "2) Alternatively you can just disable the protected mode by "
                "editing the Redis configuration file, and setting the protected "
                "mode option to 'no', and then restarting the server. "
                "3) If you started the server manually just for testing, restart "
                "it with the '--protected-mode no' option. "
                "4) Setup a bind address or an authentication password. "
                "NOTE: You only need to do one of the above things in order for "
                "the server to start accepting connections from the outside.\r\n";
            if (write(c->fd,err,strlen(err)) == -1) {
                /* Nothing to do, Just to avoid the warning... */
            }
            server.stat_rejected_conn++;
            freeClient(c);
            return;
        }
    }

    server.stat_numconnections++;
    c->flags |= flags;
}


xmlBufAddLen(xmlBufPtr buf, size_t len) {
    if ((buf == NULL) || (buf->error))
        return(-1);
    CHECK_COMPAT(buf)
    if (len > (buf->size - buf->use))
        return(-1);
    buf->use += len;
    UPDATE_COMPAT(buf)
    if (buf->size > buf->use)
        buf->content[buf->use] = 0;
    else
        return(-1);
    return(0);
}


void IRCView::appendCommandMessage(const QString& type,const QString& message, bool parseURL, bool self)
{
    QString commandColor = Preferences::self()->color(Preferences::CommandMessage).name();
    QString prefix="***";
    m_tabNotification = Konversation::tnfControl;

    if(type == i18nc("Message type", "Join"))
    {
        prefix="-->";
        parseURL=false;
    }
    else if(type == i18nc("Message type", "Part") || type == i18nc("Message type", "Quit"))
    {
        prefix="<--";
    }

    prefix=Qt::escape(prefix);

    QString line;
    QChar::Direction dir;
    QString text(filter(message, commandColor, 0, true, parseURL, self, &dir));
    bool rtl = (dir == QChar::DirR);

    if(rtl)
    {
        line = RLE;
        line += LRE;
        line += "%2 %1" + PDF + " %3";
    }
    else
    {
        if (!QApplication::isLeftToRight())
            line += LRE;

        line += "%1 %2 %3";
    }

    line = line.arg(timeStamp(), prefix, text);

    emit textToLog(QString("%1\t%2").arg(type, message));

    doAppend(line, rtl, self);
}


error::Error GLES2DecoderPassthroughImpl::DoVertexAttribIPointer(
    GLuint indx,
    GLint size,
    GLenum type,
    GLsizei stride,
    const void* ptr) {
  api()->glVertexAttribIPointerFn(indx, size, type, stride, ptr);
  return error::kNoError;
}


static void parse_mark(void)
{
	const char *v;
	if (skip_prefix(command_buf.buf, "mark :", &v)) {
		next_mark = strtoumax(v, NULL, 10);
		read_next_command();
	}
	else
		next_mark = 0;
}


static __be32 *encode_cinfo(__be32 *p, struct nfsd4_change_info *c)
{
	*p++ = cpu_to_be32(c->atomic);
	if (c->change_supported) {
		p = xdr_encode_hyper(p, c->before_change);
		p = xdr_encode_hyper(p, c->after_change);
	} else {
		*p++ = cpu_to_be32(c->before_ctime_sec);
		*p++ = cpu_to_be32(c->before_ctime_nsec);
		*p++ = cpu_to_be32(c->after_ctime_sec);
		*p++ = cpu_to_be32(c->after_ctime_nsec);
	}
	return p;
}


static int dissect_h225_T_manufacturerCode ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_integer ( tvb , offset , actx , tree , hf_index , 0U , 65535U , & manufacturerCode , FALSE ) ;
 return offset ;
 }


GF_Err lsr1_Read(GF_Box *s, GF_BitStream *bs)
{
	GF_Err e;
	GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox*)s;

	e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs);
	if (e) return e;

	ISOM_DECREASE_SIZE(ptr, 8);

	return gf_isom_box_array_read(s, bs, lsr1_AddBox);
}


static int sd_suspend(struct device *dev, pm_message_t mesg)
{
	struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
	int ret = 0;

	if (!sdkp)
		return 0;	/* this can happen */

	if (sdkp->WCE) {
		sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
		ret = sd_sync_cache(sdkp);
		if (ret)
			goto done;
	}

	if ((mesg.event & PM_EVENT_SLEEP) && sdkp->device->manage_start_stop) {
		sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
		ret = sd_start_stop_device(sdkp, 0);
	}

done:
	scsi_disk_put(sdkp);
	return ret;
}


static inline int decode_hrd_parameters(H264Context *h, SPS *sps)

{

    int cpb_count, i;

    cpb_count = get_ue_golomb_31(&h->gb) + 1;

    if (cpb_count > 32U) {

        av_log(h->avctx, AV_LOG_ERROR, "cpb_count %d invalid\n", cpb_count);

        return AVERROR_INVALIDDATA;

    }

    get_bits(&h->gb, 4); /* bit_rate_scale */

    get_bits(&h->gb, 4); /* cpb_size_scale */

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

        get_ue_golomb_long(&h->gb); /* bit_rate_value_minus1 */

        get_ue_golomb_long(&h->gb); /* cpb_size_value_minus1 */

        get_bits1(&h->gb);          /* cbr_flag */

    }

    sps->initial_cpb_removal_delay_length = get_bits(&h->gb, 5) + 1;

    sps->cpb_removal_delay_length         = get_bits(&h->gb, 5) + 1;

    sps->dpb_output_delay_length          = get_bits(&h->gb, 5) + 1;

    sps->time_offset_length               = get_bits(&h->gb, 5);

    sps->cpb_cnt                          = cpb_count;

    return 0;

}


sort_pacl(struct posix_acl *pacl)
{
	/* posix_acl_valid requires that users and groups be in order
	 * by uid/gid. */
	int i, j;

	/* no users or groups */
	if (!pacl || pacl->a_count <= 4)
		return;

	i = 1;
	while (pacl->a_entries[i].e_tag == ACL_USER)
		i++;
	sort_pacl_range(pacl, 1, i-1);

	BUG_ON(pacl->a_entries[i].e_tag != ACL_GROUP_OBJ);
	j = ++i;
	while (pacl->a_entries[j].e_tag == ACL_GROUP)
		j++;
	sort_pacl_range(pacl, i, j-1);
	return;
}


void nfs_force_lookup_revalidate(struct inode *dir)
{
	NFS_I(dir)->cache_change_attribute += 2;
}