static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 0; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) skip_bits1(gb); /* marker bit */ length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length) y = get_xbits(gb, length); skip_bits1(gb); /* marker bit */ ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the mpeg4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* this is mostly identical to the mpeg4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16 * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16 * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16 * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16 * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: s->sprite_offset[0][0] = s->sprite_offset[0][1] = s->sprite_offset[1][0] = s->sprite_offset[1][1] = 0; s->sprite_delta[0][0] = a; s->sprite_delta[0][1] = s->sprite_delta[1][0] = 0; s->sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only s->sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; s->sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; s->sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); s->sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); s->sprite_delta[0][0] = a; s->sprite_delta[0][1] = s->sprite_delta[1][0] = 0; s->sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + rho)) + (-r * sprite_ref[0][0] + virtual_ref[0][0]) * (-vop_ref[0][0]) + (r * sprite_ref[0][1] - virtual_ref[0][1]) * (-vop_ref[0][1]) + (1 << (alpha + rho - 1)); s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + rho)) + (-r * sprite_ref[0][1] + virtual_ref[0][1]) * (-vop_ref[0][0]) + (-r * sprite_ref[0][0] + virtual_ref[0][0]) * (-vop_ref[0][1]) + (1 << (alpha + rho - 1)); s->sprite_offset[1][0] = ((-r * sprite_ref[0][0] + virtual_ref[0][0]) * (-2 * vop_ref[0][0] + 1) + (r * sprite_ref[0][1] - virtual_ref[0][1]) * (-2 * vop_ref[0][1] + 1) + 2 * w2 * r * sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); s->sprite_offset[1][1] = ((-r * sprite_ref[0][1] + virtual_ref[0][1]) * (-2 * vop_ref[0][0] + 1) + (-r * sprite_ref[0][0] + virtual_ref[0][0]) * (-2 * vop_ref[0][1] + 1) + 2 * w2 * r * sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); s->sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); s->sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + beta + rho - min_ab)) + (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + (1 << (alpha + beta + rho - min_ab - 1)); s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + beta + rho - min_ab)) + (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + (1 << (alpha + beta + rho - min_ab - 1)); s->sprite_offset[1][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + (1 << (alpha + beta + rho - min_ab + 1)); s->sprite_offset[1][1] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + (1 << (alpha + beta + rho - min_ab + 1)); s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3; s->sprite_delta[0][1] = (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3; s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3; s->sprite_delta[1][1] = (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (s->sprite_delta[0][0] == a << ctx->sprite_shift[0] && s->sprite_delta[0][1] == 0 && s->sprite_delta[1][0] == 0 && s->sprite_delta[1][1] == a << ctx->sprite_shift[0]) { s->sprite_offset[0][0] >>= ctx->sprite_shift[0]; s->sprite_offset[0][1] >>= ctx->sprite_shift[0]; s->sprite_offset[1][0] >>= ctx->sprite_shift[1]; s->sprite_offset[1][1] >>= ctx->sprite_shift[1]; s->sprite_delta[0][0] = a; s->sprite_delta[0][1] = 0; s->sprite_delta[1][0] = 0; s->sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { s->sprite_offset[0][i] <<= shift_y; s->sprite_offset[1][i] <<= shift_c; s->sprite_delta[0][i] <<= shift_y; s->sprite_delta[1][i] <<= shift_y; ctx->sprite_shift[i] = 16; } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } return 0; }


jiffies_to_timespec(const unsigned long jiffies, struct timespec *value)
{
	/*
	 * Convert jiffies to nanoseconds and separate with
	 * one divide.
	 */
	u64 nsec = (u64)jiffies * TICK_NSEC;
	value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &value->tv_nsec);
}


static int dissect_h245_INTEGER_1_127 ( 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 , 1U , 127U , NULL , FALSE ) ;
 return offset ;
 }


static CodeBook unpack_codebook ( GetBitContext * gb , unsigned depth , unsigned size ) {
 unsigned i , j ;
 CodeBook cb = {
 0 }
 ;
 if ( ! can_safely_read ( gb , size * 34 ) ) return cb ;
 if ( size >= INT_MAX / sizeof ( MacroBlock ) ) return cb ;
 cb . blocks = av_malloc ( size ? size * sizeof ( MacroBlock ) : 1 ) ;
 if ( ! cb . blocks ) return cb ;
 cb . depth = depth ;
 cb . size = size ;
 for ( i = 0 ;
 i < size ;
 i ++ ) {
 unsigned mask_bits = get_bits ( gb , 4 ) ;
 unsigned color0 = get_bits ( gb , 15 ) ;
 unsigned color1 = get_bits ( gb , 15 ) ;
 for ( j = 0 ;
 j < 4 ;
 j ++ ) {
 if ( mask_bits & ( 1 << j ) ) cb . blocks [ i ] . pixels [ j ] = color1 ;
 else cb . blocks [ i ] . pixels [ j ] = color0 ;
 }
 }
 return cb ;
 }


void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value)
{
	/*
	 * Convert jiffies to nanoseconds and separate with
	 * one divide.
	 */
	u64 nsec = (u64)jiffies * TICK_NSEC;
	long tv_usec;

	value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tv_usec);
	tv_usec /= NSEC_PER_USEC;
	value->tv_usec = tv_usec;
}


static void monitor_find_completion(Monitor *mon, const char *cmdline) { const char *cmdname; char *args[MAX_ARGS]; int nb_args, i, len; const char *ptype, *str; const mon_cmd_t *cmd; MonitorBlockComplete mbs; parse_cmdline(cmdline, &nb_args, args); #ifdef DEBUG_COMPLETION for (i = 0; i < nb_args; i++) { monitor_printf(mon, "arg%d = '%s'\n", i, args[i]); } #endif /* if the line ends with a space, it means we want to complete the next arg */ len = strlen(cmdline); if (len > 0 && qemu_isspace(cmdline[len - 1])) { if (nb_args >= MAX_ARGS) { goto cleanup; } args[nb_args++] = g_strdup(""); } if (nb_args <= 1) { /* command completion */ if (nb_args == 0) cmdname = ""; else cmdname = args[0]; readline_set_completion_index(mon->rs, strlen(cmdname)); for (cmd = mon->cmd_table; cmd->name != NULL; cmd++) { cmd_completion(mon, cmdname, cmd->name); } } else { /* find the command */ for (cmd = mon->cmd_table; cmd->name != NULL; cmd++) { if (compare_cmd(args[0], cmd->name)) { break; } } if (!cmd->name) { goto cleanup; } ptype = next_arg_type(cmd->args_type); for(i = 0; i < nb_args - 2; i++) { if (*ptype != '\0') { ptype = next_arg_type(ptype); while (*ptype == '?') ptype = next_arg_type(ptype); } } str = args[nb_args - 1]; if (*ptype == '-' && ptype[1] != '\0') { ptype = next_arg_type(ptype); } switch(*ptype) { case 'F': /* file completion */ readline_set_completion_index(mon->rs, strlen(str)); file_completion(mon, str); break; case 'B': /* block device name completion */ mbs.mon = mon; mbs.input = str; readline_set_completion_index(mon->rs, strlen(str)); bdrv_iterate(block_completion_it, &mbs); break; case 's': /* XXX: more generic ? */ if (!strcmp(cmd->name, "info")) { readline_set_completion_index(mon->rs, strlen(str)); for(cmd = info_cmds; cmd->name != NULL; cmd++) { cmd_completion(mon, str, cmd->name); } } else if (!strcmp(cmd->name, "sendkey")) { char *sep = strrchr(str, '-'); if (sep) str = sep + 1; readline_set_completion_index(mon->rs, strlen(str)); for (i = 0; i < Q_KEY_CODE_MAX; i++) { cmd_completion(mon, str, QKeyCode_lookup[i]); } } else if (!strcmp(cmd->name, "help|?")) { readline_set_completion_index(mon->rs, strlen(str)); for (cmd = mon->cmd_table; cmd->name != NULL; cmd++) { cmd_completion(mon, str, cmd->name); } } break; default: break; } } cleanup: for (i = 0; i < nb_args; i++) { g_free(args[i]); } }


void xmlHashScanFull ( xmlHashTablePtr table , xmlHashScannerFull f , void * data ) {
 int i , nb ;
 xmlHashEntryPtr iter ;
 xmlHashEntryPtr next ;
 if ( table == NULL ) return ;
 if ( f == NULL ) return ;
 if ( table -> table ) {
 for ( i = 0 ;
 i < table -> size ;
 i ++ ) {
 if ( table -> table [ i ] . valid == 0 ) continue ;
 iter = & ( table -> table [ i ] ) ;
 while ( iter ) {
 next = iter -> next ;
 nb = table -> nbElems ;
 if ( ( f != NULL ) && ( iter -> payload != NULL ) ) f ( iter -> payload , data , iter -> name , iter -> name2 , iter -> name3 ) ;
 if ( nb != table -> nbElems ) {
 if ( iter == & ( table -> table [ i ] ) ) {
 if ( table -> table [ i ] . valid == 0 ) iter = NULL ;
 if ( table -> table [ i ] . next != next ) iter = & ( table -> table [ i ] ) ;
 }
 else iter = next ;
 }
 else iter = next ;
 }
 }
 }
 }


int do_adjtimex(struct timex *txc)
{
	long mtemp, save_adjust;
	s64 freq_adj;
	int result;

	/* In order to modify anything, you gotta be super-user! */
	if (txc->modes && !capable(CAP_SYS_TIME))
		return -EPERM;

	/* Now we validate the data before disabling interrupts */

	if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT) {
	  /* singleshot must not be used with any other mode bits */
		if (txc->modes != ADJ_OFFSET_SINGLESHOT &&
					txc->modes != ADJ_OFFSET_SS_READ)
			return -EINVAL;
	}

	if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET))
	  /* adjustment Offset limited to +- .512 seconds */
		if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE )
			return -EINVAL;

	/* if the quartz is off by more than 10% something is VERY wrong ! */
	if (txc->modes & ADJ_TICK)
		if (txc->tick <  900000/USER_HZ ||
		    txc->tick > 1100000/USER_HZ)
			return -EINVAL;

	write_seqlock_irq(&xtime_lock);
	result = time_state;	/* mostly `TIME_OK' */

	/* Save for later - semantics of adjtime is to return old value */
	save_adjust = time_adjust;

#if 0	/* STA_CLOCKERR is never set yet */
	time_status &= ~STA_CLOCKERR;		/* reset STA_CLOCKERR */
#endif
	/* If there are input parameters, then process them */
	if (txc->modes)
	{
	    if (txc->modes & ADJ_STATUS)	/* only set allowed bits */
		time_status =  (txc->status & ~STA_RONLY) |
			      (time_status & STA_RONLY);

	    if (txc->modes & ADJ_FREQUENCY) {	/* p. 22 */
		if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) {
		    result = -EINVAL;
		    goto leave;
		}
		time_freq = ((s64)txc->freq * NSEC_PER_USEC)
				>> (SHIFT_USEC - SHIFT_NSEC);
	    }

	    if (txc->modes & ADJ_MAXERROR) {
		if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) {
		    result = -EINVAL;
		    goto leave;
		}
		time_maxerror = txc->maxerror;
	    }

	    if (txc->modes & ADJ_ESTERROR) {
		if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) {
		    result = -EINVAL;
		    goto leave;
		}
		time_esterror = txc->esterror;
	    }

	    if (txc->modes & ADJ_TIMECONST) {	/* p. 24 */
		if (txc->constant < 0) {	/* NTP v4 uses values > 6 */
		    result = -EINVAL;
		    goto leave;
		}
		time_constant = min(txc->constant + 4, (long)MAXTC);
	    }

	    if (txc->modes & ADJ_OFFSET) {	/* values checked earlier */
		if (txc->modes == ADJ_OFFSET_SINGLESHOT) {
		    /* adjtime() is independent from ntp_adjtime() */
		    time_adjust = txc->offset;
		}
		else if (time_status & STA_PLL) {
		    time_offset = txc->offset * NSEC_PER_USEC;

		    /*
		     * Scale the phase adjustment and
		     * clamp to the operating range.
		     */
		    time_offset = min(time_offset, (s64)MAXPHASE * NSEC_PER_USEC);
		    time_offset = max(time_offset, (s64)-MAXPHASE * NSEC_PER_USEC);

		    /*
		     * Select whether the frequency is to be controlled
		     * and in which mode (PLL or FLL). Clamp to the operating
		     * range. Ugly multiply/divide should be replaced someday.
		     */

		    if (time_status & STA_FREQHOLD || time_reftime == 0)
		        time_reftime = xtime.tv_sec;
		    mtemp = xtime.tv_sec - time_reftime;
		    time_reftime = xtime.tv_sec;

		    freq_adj = time_offset * mtemp;
		    freq_adj = shift_right(freq_adj, time_constant * 2 +
					   (SHIFT_PLL + 2) * 2 - SHIFT_NSEC);
		    if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC))
			freq_adj += div_s64(time_offset << (SHIFT_NSEC - SHIFT_FLL), mtemp);
		    freq_adj += time_freq;
		    freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC);
		    time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC);
		    time_offset = div_s64(time_offset, NTP_INTERVAL_FREQ);
		    time_offset <<= SHIFT_UPDATE;
		} /* STA_PLL */
	    } /* txc->modes & ADJ_OFFSET */
	    if (txc->modes & ADJ_TICK)
		tick_usec = txc->tick;

	    if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
		    ntp_update_frequency();
	} /* txc->modes */
leave:	if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0)
		result = TIME_ERROR;

	if ((txc->modes == ADJ_OFFSET_SINGLESHOT) ||
			(txc->modes == ADJ_OFFSET_SS_READ))
		txc->offset = save_adjust;
	else
		txc->offset = ((long)shift_right(time_offset, SHIFT_UPDATE)) *
	    			NTP_INTERVAL_FREQ / 1000;
	txc->freq	   = (time_freq / NSEC_PER_USEC) <<
				(SHIFT_USEC - SHIFT_NSEC);
	txc->maxerror	   = time_maxerror;
	txc->esterror	   = time_esterror;
	txc->status	   = time_status;
	txc->constant	   = time_constant;
	txc->precision	   = 1;
	txc->tolerance	   = MAXFREQ;
	txc->tick	   = tick_usec;

	/* PPS is not implemented, so these are zero */
	txc->ppsfreq	   = 0;
	txc->jitter	   = 0;
	txc->shift	   = 0;
	txc->stabil	   = 0;
	txc->jitcnt	   = 0;
	txc->calcnt	   = 0;
	txc->errcnt	   = 0;
	txc->stbcnt	   = 0;
	write_sequnlock_irq(&xtime_lock);
	do_gettimeofday(&txc->time);
	notify_cmos_timer();
	return(result);
}


fetch_next_cert_ldap (cert_fetch_context_t context,
                      unsigned char **value, size_t *valuelen)
{
  gpg_error_t err;
  unsigned char hdr[5];
  char *p, *pend;
  int n;
  int okay = 0;
  /* int is_cms = 0; */

  *value = NULL;
  *valuelen = 0;

  err = 0;
  while (!err)
    {
      err = read_buffer (context->reader, hdr, 5);
      if (err)
        break;
      n = (hdr[1] << 24)|(hdr[2]<<16)|(hdr[3]<<8)|hdr[4];
      if (*hdr == 'V' && okay)
        {
#if 0  /* That code is not yet ready.  */

          if (is_cms)
            {
              /* The certificate needs to be parsed from CMS data. */
              ksba_cms_t cms;
              ksba_stop_reason_t stopreason;
              int i;

              err = ksba_cms_new (&cms);
              if (err)
                goto leave;
              err = ksba_cms_set_reader_writer (cms, context->reader, NULL);
              if (err)
                {
                  log_error ("ksba_cms_set_reader_writer failed: %s\n",
                             gpg_strerror (err));
                  goto leave;
                }

              do
                {
                  err = ksba_cms_parse (cms, &stopreason);
                  if (err)
                    {
                      log_error ("ksba_cms_parse failed: %s\n",
                                 gpg_strerror (err));
                      goto leave;
                    }

                  if (stopreason == KSBA_SR_BEGIN_DATA)
                    log_error ("userSMIMECertificate is not "
                               "a certs-only message\n");
                }
              while (stopreason != KSBA_SR_READY);

              for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
                {
                  check_and_store (ctrl, stats, cert, 0);
                  ksba_cert_release (cert);
                  cert = NULL;
                }
              if (!i)
                log_error ("no certificate found\n");
              else
                any = 1;
            }
          else
#endif
            {
              *value = xtrymalloc (n);
              if (!*value)
                return gpg_error_from_errno (errno);
              *valuelen = n;
              err = read_buffer (context->reader, *value, n);
              break; /* Ready or error.  */
            }
        }
      else if (!n && *hdr == 'A')
        okay = 0;
      else if (n)
        {
          if (n > context->tmpbufsize)
            {
              xfree (context->tmpbuf);
              context->tmpbufsize = 0;
              context->tmpbuf = xtrymalloc (n+1);
              if (!context->tmpbuf)
                return gpg_error_from_errno (errno);
              context->tmpbufsize = n;
            }
          err = read_buffer (context->reader, context->tmpbuf, n);
          if (err)
            break;
          if (*hdr == 'A')
            {
              p = context->tmpbuf;
              p[n] = 0; /*(we allocated one extra byte for this.)*/
              /* fixme: is_cms = 0; */
              if ( (pend = strchr (p, ';')) )
                *pend = 0; /* Strip off the extension. */
              if (!ascii_strcasecmp (p, USERCERTIFICATE))
                {
                  if (DBG_LOOKUP)
                    log_debug ("fetch_next_cert_ldap: got attribute '%s'\n",
                               USERCERTIFICATE);
                  okay = 1;
                }
              else if (!ascii_strcasecmp (p, CACERTIFICATE))
                {
                  if (DBG_LOOKUP)
                    log_debug ("fetch_next_cert_ldap: got attribute '%s'\n",
                               CACERTIFICATE);
                  okay = 1;
                }
              else if (!ascii_strcasecmp (p, X509CACERT))
                {
                  if (DBG_LOOKUP)
                    log_debug ("fetch_next_cert_ldap: got attribute '%s'\n",
                               CACERTIFICATE);
                  okay = 1;
                }
/*               else if (!ascii_strcasecmp (p, USERSMIMECERTIFICATE)) */
/*                 { */
/*                   if (DBG_LOOKUP) */
/*                     log_debug ("fetch_next_cert_ldap: got attribute '%s'\n", */
/*                                USERSMIMECERTIFICATE); */
/*                   okay = 1; */
/*                   is_cms = 1; */
/*                 } */
              else
                {
                  if (DBG_LOOKUP)
                    log_debug ("fetch_next_cert_ldap: got attribute '%s'"
                               " -  ignored\n", p);
                  okay = 0;
                }
            }
          else if (*hdr == 'E')
            {
              p = context->tmpbuf;
              p[n] = 0; /*(we allocated one extra byte for this.)*/
              if (!strcmp (p, "truncated"))
                {
                  context->truncated = 1;
                  log_info (_("ldap_search hit the size limit of"
                              " the server\n"));
                }
            }
        }
    }

  if (err)
    {
      xfree (*value);
      *value = NULL;
      *valuelen = 0;
      if (gpg_err_code (err) == GPG_ERR_EOF && context->truncated)
        {
          context->truncated = 0; /* So that the next call would return EOF. */
          err = gpg_error (GPG_ERR_TRUNCATED);
        }
    }

  return err;
}


setup_arch (char **cmdline_p)
{
	unw_init();

	ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);

	*cmdline_p = __va(ia64_boot_param->command_line);
	strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);

	efi_init();
	io_port_init();

#ifdef CONFIG_IA64_GENERIC
	/* machvec needs to be parsed from the command line
	 * before parse_early_param() is called to ensure
	 * that ia64_mv is initialised before any command line
	 * settings may cause console setup to occur
	 */
	machvec_init_from_cmdline(*cmdline_p);
#endif

	parse_early_param();

	if (early_console_setup(*cmdline_p) == 0)
		mark_bsp_online();

#ifdef CONFIG_ACPI
	/* Initialize the ACPI boot-time table parser */
	acpi_table_init();
# ifdef CONFIG_ACPI_NUMA
	acpi_numa_init();
	per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ?
		32 : cpus_weight(early_cpu_possible_map)), additional_cpus);
# endif
#else
# ifdef CONFIG_SMP
	smp_build_cpu_map();	/* happens, e.g., with the Ski simulator */
# endif
#endif /* CONFIG_APCI_BOOT */

	find_memory();

	/* process SAL system table: */
	ia64_sal_init(__va(efi.sal_systab));

#ifdef CONFIG_ITANIUM
	ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist);
#else
	{
		u64 num_phys_stacked;

		if (ia64_pal_rse_info(&num_phys_stacked, 0) == 0 && num_phys_stacked > 96)
			ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist);
	}
#endif

#ifdef CONFIG_SMP
	cpu_physical_id(0) = hard_smp_processor_id();
#endif

	cpu_init();	/* initialize the bootstrap CPU */
	mmu_context_init();	/* initialize context_id bitmap */

	check_sal_cache_flush();

#ifdef CONFIG_ACPI
	acpi_boot_init();
#endif

#ifdef CONFIG_VT
	if (!conswitchp) {
# if defined(CONFIG_DUMMY_CONSOLE)
		conswitchp = &dummy_con;
# endif
# if defined(CONFIG_VGA_CONSOLE)
		/*
		 * Non-legacy systems may route legacy VGA MMIO range to system
		 * memory.  vga_con probes the MMIO hole, so memory looks like
		 * a VGA device to it.  The EFI memory map can tell us if it's
		 * memory so we can avoid this problem.
		 */
		if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)
			conswitchp = &vga_con;
# endif
	}
#endif

	/* enable IA-64 Machine Check Abort Handling unless disabled */
	if (!nomca)
		ia64_mca_init();

	platform_setup(cmdline_p);
	paging_init();
}


convert_le_u32 (const unsigned char *buf)
{
  return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
}


static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags)
{
	/*
	 * Protect the call to nfs4_state_set_mode_locked and
	 * serialise the stateid update
	 */
	write_seqlock(&state->seqlock);
	if (deleg_stateid != NULL) {
		memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data));
		set_bit(NFS_DELEGATED_STATE, &state->flags);
	}
	if (open_stateid != NULL)
		nfs_set_open_stateid_locked(state, open_stateid, open_flags);
	write_sequnlock(&state->seqlock);
	spin_lock(&state->owner->so_lock);
	update_open_stateflags(state, open_flags);
	spin_unlock(&state->owner->so_lock);
}


static byte * gs_heap_alloc_string ( gs_memory_t * mem , uint nbytes , client_name_t cname ) {
 return gs_heap_alloc_bytes ( mem , nbytes , cname ) ;
 }


void arch_pick_mmap_layout(struct mm_struct *mm)
{
	unsigned long random_factor = 0UL;
	unsigned long gap;

	if (current->flags & PF_RANDOMIZE) {
		random_factor = get_random_int();
		if (test_thread_flag(TIF_32BIT))
			random_factor &= ((1 * 1024 * 1024) - 1);
		else
			random_factor = ((random_factor << PAGE_SHIFT) &
					 0xffffffffUL);
	}

	/*
	 * Fall back to the standard layout if the personality
	 * bit is set, or if the expected stack growth is unlimited:
	 */
	gap = rlimit(RLIMIT_STACK);
	if (!test_thread_flag(TIF_32BIT) ||
	    (current->personality & ADDR_COMPAT_LAYOUT) ||
	    gap == RLIM_INFINITY ||
	    sysctl_legacy_va_layout) {
		mm->mmap_base = TASK_UNMAPPED_BASE + random_factor;
		mm->get_unmapped_area = arch_get_unmapped_area;
		mm->unmap_area = arch_unmap_area;
	} else {
		/* We know it's 32-bit */
		unsigned long task_size = STACK_TOP32;

		if (gap < 128 * 1024 * 1024)
			gap = 128 * 1024 * 1024;
		if (gap > (task_size / 6 * 5))
			gap = (task_size / 6 * 5);

		mm->mmap_base = PAGE_ALIGN(task_size - gap - random_factor);
		mm->get_unmapped_area = arch_get_unmapped_area_topdown;
		mm->unmap_area = arch_unmap_area_topdown;
	}
}


struct zip_cdir * _zip_cdir_new ( int nentry , struct zip_error * error ) {
 struct zip_cdir * cd ;
 if ( ( cd = ( struct zip_cdir * ) malloc ( sizeof ( * cd ) ) ) == NULL ) {
 _zip_error_set ( error , ZIP_ER_MEMORY , 0 ) ;
 return NULL ;
 }
 if ( nentry > ( ( size_t ) - 1 ) / sizeof ( * ( cd -> entry ) ) || ( cd -> entry = ( struct zip_dirent * ) malloc ( sizeof ( * ( cd -> entry ) ) * ( size_t ) nentry ) ) == NULL ) {
 _zip_error_set ( error , ZIP_ER_MEMORY , 0 ) ;
 free ( cd ) ;
 return NULL ;
 }
 cd -> nentry = nentry ;
 cd -> size = cd -> offset = 0 ;
 cd -> comment = NULL ;
 cd -> comment_len = 0 ;
 return cd ;
 }


static int dissect_h245_OCTET_STRING_SIZE_2 ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_octet_string ( tvb , offset , actx , tree , hf_index , 2 , 2 , FALSE , NULL ) ;
 return offset ;
 }


static int php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht TSRMLS_DC)
{
	zval            **z_date = NULL;
	zval            **z_timezone = NULL;
	zval            **z_timezone_type = NULL;
	zval             *tmp_obj = NULL;
	timelib_tzinfo   *tzi;
	php_timezone_obj *tzobj;

	if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) {
		convert_to_string(*z_date);
		if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) {
			convert_to_long(*z_timezone_type);
			if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) {
				convert_to_string(*z_timezone);

				switch (Z_LVAL_PP(z_timezone_type)) {
					case TIMELIB_ZONETYPE_OFFSET:
					case TIMELIB_ZONETYPE_ABBR: {
						char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2);
						int ret;
						snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone));
						ret = php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC);
						efree(tmp);
						return 1 == ret;
					}

					case TIMELIB_ZONETYPE_ID: {
						int ret;
						convert_to_string(*z_timezone);

						tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC);

						if (tzi == NULL) {
							return 0;
						}

						ALLOC_INIT_ZVAL(tmp_obj);
						tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC);
						tzobj->type = TIMELIB_ZONETYPE_ID;
						tzobj->tzi.tz = tzi;
						tzobj->initialized = 1;

						ret = php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC);
						zval_ptr_dtor(&tmp_obj);
						return 1 == ret;
					}
				}
			}
		}
	}
	return 0;


static void ivi_huff_desc_copy ( IVIHuffDesc * dst , const IVIHuffDesc * src ) {
 dst -> num_rows = src -> num_rows ;
 memcpy ( dst -> xbits , src -> xbits , src -> num_rows ) ;
 }


void HeaderMapImpl::remove(const LowerCaseString& key) {
  EntryCb cb = ConstSingleton<StaticLookupTable>::get().find(key.get());
  if (cb) {
    StaticLookupResponse ref_lookup_response = cb(*this);
    removeInline(ref_lookup_response.entry_);
  } else {
    for (auto i = headers_.begin(); i != headers_.end();) {
      if (i->key() == key.get().c_str()) {
        subtractSize(i->key().size() + i->value().size());
        i = headers_.erase(i);
      } else {
        ++i;
      }
    }
  }
}


void vp9_sad ## m ## x ## n ## x4d_c ( const uint8_t * src , int src_stride , const uint8_t * const refs [ ] , int ref_stride , unsigned int * sads ) {
 int i ;
 for ( i = 0 ;
 i < 4 ;
 ++ i ) sads [ i ] = vp9_sad ## m ## x ## n ## _c ( src , src_stride , refs [ i ] , ref_stride ) ;
 \ }
 sadMxN ( 64 , 64 ) sadMxNxK ( 64 , 64 , 3 ) sadMxNxK ( 64 , 64 , 8 ) sadMxNx4D ( 64 , 64 ) sadMxN ( 64 , 32 ) sadMxNx4D ( 64 , 32 )


static void spapr_cpu_core_realize(DeviceState *dev, Error **errp) { sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev)); CPUCore *cc = CPU_CORE(OBJECT(dev)); const char *typename = object_class_get_name(sc->cpu_class); size_t size = object_type_get_instance_size(typename); Error *local_err = NULL; Object *obj; int i; sc->threads = g_malloc0(size * cc->nr_threads); for (i = 0; i < cc->nr_threads; i++) { char id[32]; void *obj = sc->threads + i * size; object_initialize(obj, size, typename); snprintf(id, sizeof(id), "thread[%d]", i); object_property_add_child(OBJECT(sc), id, obj, &local_err); if (local_err) { goto err; } } object_child_foreach(OBJECT(dev), spapr_cpu_core_realize_child, &local_err); if (local_err) { goto err; } else { return; } err: while (--i >= 0) { obj = sc->threads + i * size; object_unparent(obj); } g_free(sc->threads); error_propagate(errp, local_err); }


static ssize_t qio_channel_websock_readv ( QIOChannel * ioc , const struct iovec * iov , size_t niov , int * * fds , size_t * nfds , Error * * errp ) {
 QIOChannelWebsock * wioc = QIO_CHANNEL_WEBSOCK ( ioc ) ;
 size_t i ;
 ssize_t got = 0 ;
 ssize_t ret ;
 if ( wioc -> io_err ) {
 error_propagate ( errp , error_copy ( wioc -> io_err ) ) ;
 return - 1 ;
 }
 if ( ! wioc -> rawinput . offset ) {
 ret = qio_channel_websock_read_wire ( QIO_CHANNEL_WEBSOCK ( ioc ) , errp ) ;
 if ( ret < 0 ) {
 return ret ;
 }
 }
 for ( i = 0 ;
 i < niov ;
 i ++ ) {
 size_t want = iov [ i ] . iov_len ;
 if ( want > ( wioc -> rawinput . offset - got ) ) {
 want = ( wioc -> rawinput . offset - got ) ;
 }
 memcpy ( iov [ i ] . iov_base , wioc -> rawinput . buffer + got , want ) ;
 got += want ;
 if ( want < iov [ i ] . iov_len ) {
 break ;
 }
 }
 buffer_advance ( & wioc -> rawinput , got ) ;
 qio_channel_websock_set_watch ( wioc ) ;
 return got ;
 }


void proto_reg_handoff_bta2dp ( void ) {
 sbc_handle = find_dissector_add_dependency ( "sbc" , proto_bta2dp ) ;
 mp2t_handle = find_dissector_add_dependency ( "mp2t" , proto_bta2dp ) ;
 mpeg_audio_handle = find_dissector_add_dependency ( "mpeg-audio" , proto_bta2dp ) ;
 atrac_handle = find_dissector_add_dependency ( "atrac" , proto_bta2dp ) ;
 rtp_handle = find_dissector_add_dependency ( "rtp" , proto_bta2dp ) ;
 dissector_add_string ( "bluetooth.uuid" , "110a" , bta2dp_handle ) ;
 dissector_add_string ( "bluetooth.uuid" , "110b" , bta2dp_handle ) ;
 dissector_add_string ( "bluetooth.uuid" , "110d" , bta2dp_handle ) ;
 dissector_add_for_decode_as ( "btl2cap.cid" , bta2dp_handle ) ;
 }


void HttpGrpcAccessLog::emitLog(const Http::HeaderMap& request_headers,
                                const Http::HeaderMap& response_headers,
                                const Http::HeaderMap& response_trailers,
                                const StreamInfo::StreamInfo& stream_info) {
  // Common log properties.
  // TODO(mattklein123): Populate sample_rate field.
  envoy::data::accesslog::v2::HTTPAccessLogEntry log_entry;
  GrpcCommon::Utility::extractCommonAccessLogProperties(*log_entry.mutable_common_properties(),
                                                        stream_info);

  if (stream_info.protocol()) {
    switch (stream_info.protocol().value()) {
    case Http::Protocol::Http10:
      log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP10);
      break;
    case Http::Protocol::Http11:
      log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP11);
      break;
    case Http::Protocol::Http2:
      log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP2);
      break;
    }
  }

  // HTTP request properties.
  // TODO(mattklein123): Populate port field.
  auto* request_properties = log_entry.mutable_request();
  if (request_headers.Scheme() != nullptr) {
    request_properties->set_scheme(std::string(request_headers.Scheme()->value().getStringView()));
  }
  if (request_headers.Host() != nullptr) {
    request_properties->set_authority(std::string(request_headers.Host()->value().getStringView()));
  }
  if (request_headers.Path() != nullptr) {
    request_properties->set_path(std::string(request_headers.Path()->value().getStringView()));
  }
  if (request_headers.UserAgent() != nullptr) {
    request_properties->set_user_agent(
        std::string(request_headers.UserAgent()->value().getStringView()));
  }
  if (request_headers.Referer() != nullptr) {
    request_properties->set_referer(
        std::string(request_headers.Referer()->value().getStringView()));
  }
  if (request_headers.ForwardedFor() != nullptr) {
    request_properties->set_forwarded_for(
        std::string(request_headers.ForwardedFor()->value().getStringView()));
  }
  if (request_headers.RequestId() != nullptr) {
    request_properties->set_request_id(
        std::string(request_headers.RequestId()->value().getStringView()));
  }
  if (request_headers.EnvoyOriginalPath() != nullptr) {
    request_properties->set_original_path(
        std::string(request_headers.EnvoyOriginalPath()->value().getStringView()));
  }
  request_properties->set_request_headers_bytes(request_headers.byteSize());
  request_properties->set_request_body_bytes(stream_info.bytesReceived());
  if (request_headers.Method() != nullptr) {
    envoy::api::v2::core::RequestMethod method =
        envoy::api::v2::core::RequestMethod::METHOD_UNSPECIFIED;
    envoy::api::v2::core::RequestMethod_Parse(
        std::string(request_headers.Method()->value().getStringView()), &method);
    request_properties->set_request_method(method);
  }
  if (!request_headers_to_log_.empty()) {
    auto* logged_headers = request_properties->mutable_request_headers();

    for (const auto& header : request_headers_to_log_) {
      const Http::HeaderEntry* entry = request_headers.get(header);
      if (entry != nullptr) {
        logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
      }
    }
  }

  // HTTP response properties.
  auto* response_properties = log_entry.mutable_response();
  if (stream_info.responseCode()) {
    response_properties->mutable_response_code()->set_value(stream_info.responseCode().value());
  }
  if (stream_info.responseCodeDetails()) {
    response_properties->set_response_code_details(stream_info.responseCodeDetails().value());
  }
  response_properties->set_response_headers_bytes(response_headers.byteSize());
  response_properties->set_response_body_bytes(stream_info.bytesSent());
  if (!response_headers_to_log_.empty()) {
    auto* logged_headers = response_properties->mutable_response_headers();

    for (const auto& header : response_headers_to_log_) {
      const Http::HeaderEntry* entry = response_headers.get(header);
      if (entry != nullptr) {
        logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
      }
    }
  }

  if (!response_trailers_to_log_.empty()) {
    auto* logged_headers = response_properties->mutable_response_trailers();

    for (const auto& header : response_trailers_to_log_) {
      const Http::HeaderEntry* entry = response_trailers.get(header);
      if (entry != nullptr) {
        logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
      }
    }
  }

  tls_slot_->getTyped<ThreadLocalLogger>().logger_->log(std::move(log_entry));
}


void HttpGrpcAccessLog::emitLog(const Http::HeaderMap& request_headers,
                                const Http::HeaderMap& response_headers,
                                const Http::HeaderMap& response_trailers,
                                const StreamInfo::StreamInfo& stream_info) {
  // Common log properties.
  // TODO(mattklein123): Populate sample_rate field.
  envoy::data::accesslog::v2::HTTPAccessLogEntry log_entry;
  GrpcCommon::Utility::extractCommonAccessLogProperties(*log_entry.mutable_common_properties(),
                                                        stream_info);

  if (stream_info.protocol()) {
    switch (stream_info.protocol().value()) {
    case Http::Protocol::Http10:
      log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP10);
      break;
    case Http::Protocol::Http11:
      log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP11);
      break;
    case Http::Protocol::Http2:
      log_entry.set_protocol_version(envoy::data::accesslog::v2::HTTPAccessLogEntry::HTTP2);
      break;
    }
  }

  // HTTP request properties.
  // TODO(mattklein123): Populate port field.
  auto* request_properties = log_entry.mutable_request();
  if (request_headers.Scheme() != nullptr) {
    request_properties->set_scheme(std::string(request_headers.Scheme()->value().getStringView()));
  }
  if (request_headers.Host() != nullptr) {
    request_properties->set_authority(std::string(request_headers.Host()->value().getStringView()));
  }
  if (request_headers.Path() != nullptr) {
    request_properties->set_path(std::string(request_headers.Path()->value().getStringView()));
  }
  if (request_headers.UserAgent() != nullptr) {
    request_properties->set_user_agent(
        std::string(request_headers.UserAgent()->value().getStringView()));
  }
  if (request_headers.Referer() != nullptr) {
    request_properties->set_referer(
        std::string(request_headers.Referer()->value().getStringView()));
  }
  if (request_headers.ForwardedFor() != nullptr) {
    request_properties->set_forwarded_for(
        std::string(request_headers.ForwardedFor()->value().getStringView()));
  }
  if (request_headers.RequestId() != nullptr) {
    request_properties->set_request_id(
        std::string(request_headers.RequestId()->value().getStringView()));
  }
  if (request_headers.EnvoyOriginalPath() != nullptr) {
    request_properties->set_original_path(
        std::string(request_headers.EnvoyOriginalPath()->value().getStringView()));
  }
  request_properties->set_request_headers_bytes(request_headers.byteSize().value());
  request_properties->set_request_body_bytes(stream_info.bytesReceived());
  if (request_headers.Method() != nullptr) {
    envoy::api::v2::core::RequestMethod method =
        envoy::api::v2::core::RequestMethod::METHOD_UNSPECIFIED;
    envoy::api::v2::core::RequestMethod_Parse(
        std::string(request_headers.Method()->value().getStringView()), &method);
    request_properties->set_request_method(method);
  }
  if (!request_headers_to_log_.empty()) {
    auto* logged_headers = request_properties->mutable_request_headers();

    for (const auto& header : request_headers_to_log_) {
      const Http::HeaderEntry* entry = request_headers.get(header);
      if (entry != nullptr) {
        logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
      }
    }
  }

  // HTTP response properties.
  auto* response_properties = log_entry.mutable_response();
  if (stream_info.responseCode()) {
    response_properties->mutable_response_code()->set_value(stream_info.responseCode().value());
  }
  if (stream_info.responseCodeDetails()) {
    response_properties->set_response_code_details(stream_info.responseCodeDetails().value());
  }
  response_properties->set_response_headers_bytes(response_headers.byteSize().value());
  response_properties->set_response_body_bytes(stream_info.bytesSent());
  if (!response_headers_to_log_.empty()) {
    auto* logged_headers = response_properties->mutable_response_headers();

    for (const auto& header : response_headers_to_log_) {
      const Http::HeaderEntry* entry = response_headers.get(header);
      if (entry != nullptr) {
        logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
      }
    }
  }

  if (!response_trailers_to_log_.empty()) {
    auto* logged_headers = response_properties->mutable_response_trailers();

    for (const auto& header : response_trailers_to_log_) {
      const Http::HeaderEntry* entry = response_trailers.get(header);
      if (entry != nullptr) {
        logged_headers->insert({header.get(), std::string(entry->value().getStringView())});
      }
    }
  }

  tls_slot_->getTyped<ThreadLocalLogger>().logger_->log(std::move(log_entry));
}


static void set_sensor_type(IPMIBmcSim *ibs, uint8_t *cmd, unsigned int cmd_len, uint8_t *rsp, unsigned int *rsp_len, unsigned int max_rsp_len) { IPMISensor *sens; IPMI_CHECK_CMD_LEN(5); if ((cmd[2] > MAX_SENSORS) || !IPMI_SENSOR_GET_PRESENT(ibs->sensors + cmd[2])) { rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT; return; } sens = ibs->sensors + cmd[2]; sens->sensor_type = cmd[3]; sens->evt_reading_type_code = cmd[4] & 0x7f; }


TEST(HeaderMapImplTest, LargeCharInHeader) {
  HeaderMapImpl headers;
  LowerCaseString static_key("\x90hello");
  std::string ref_value("value");
  headers.addReference(static_key, ref_value);
  EXPECT_EQ(headers.byteSize().value(), countBytesForTest(headers));
  EXPECT_EQ("value", headers.get(static_key)->value().getStringView());
}


static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov, int iovcnt) { uint8_t buffer[4096]; size_t offset; offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer)); return nc->info->receive(nc, buffer, offset); }


TEST(HeaderMapImplTest, SetRemovesAllValues) {
  HeaderMapImpl headers;

  LowerCaseString key1("hello");
  LowerCaseString key2("olleh");
  std::string ref_value1("world");
  std::string ref_value2("planet");
  std::string ref_value3("globe");
  std::string ref_value4("earth");
  std::string ref_value5("blue marble");

  headers.addReference(key1, ref_value1);
  headers.addReference(key2, ref_value2);
  headers.addReference(key1, ref_value3);
  headers.addReference(key1, ref_value4);
  EXPECT_EQ(headers.byteSize().value(), countBytesForTest(headers));

  using MockCb = testing::MockFunction<void(const std::string&, const std::string&)>;

  {
    MockCb cb;

    InSequence seq;
    EXPECT_CALL(cb, Call("hello", "world"));
    EXPECT_CALL(cb, Call("olleh", "planet"));
    EXPECT_CALL(cb, Call("hello", "globe"));
    EXPECT_CALL(cb, Call("hello", "earth"));

    headers.iterate(
        [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {
          static_cast<MockCb*>(cb_v)->Call(std::string(header.key().getStringView()),
                                           std::string(header.value().getStringView()));
          return HeaderMap::Iterate::Continue;
        },
        &cb);
  }

  headers.setReference(key1, ref_value5); // set moves key to end

  {
    MockCb cb;

    InSequence seq;
    EXPECT_CALL(cb, Call("olleh", "planet"));
    EXPECT_CALL(cb, Call("hello", "blue marble"));

    headers.iterate(
        [](const Http::HeaderEntry& header, void* cb_v) -> HeaderMap::Iterate {
          static_cast<MockCb*>(cb_v)->Call(std::string(header.key().getStringView()),
                                           std::string(header.value().getStringView()));
          return HeaderMap::Iterate::Continue;
        },
        &cb);
  }
}


static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait)
{
	struct nfs4_state_owner *owner = state->owner;
	int call_close = 0;
	int newstate;

	atomic_inc(&owner->so_count);
	/* Protect against nfs4_find_state() */
	spin_lock(&owner->so_lock);
	switch (mode & (FMODE_READ | FMODE_WRITE)) {
		case FMODE_READ:
			state->n_rdonly--;
			break;
		case FMODE_WRITE:
			state->n_wronly--;
			break;
		case FMODE_READ|FMODE_WRITE:
			state->n_rdwr--;
	}
	newstate = FMODE_READ|FMODE_WRITE;
	if (state->n_rdwr == 0) {
		if (state->n_rdonly == 0) {
			newstate &= ~FMODE_READ;
			call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags);
			call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags);
		}
		if (state->n_wronly == 0) {
			newstate &= ~FMODE_WRITE;
			call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags);
			call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags);
		}
		if (newstate == 0)
			clear_bit(NFS_DELEGATED_STATE, &state->flags);
	}
	nfs4_state_set_mode_locked(state, newstate);
	spin_unlock(&owner->so_lock);

	if (!call_close) {
		nfs4_put_open_state(state);
		nfs4_put_state_owner(owner);
	} else
		nfs4_do_close(path, state, wait);
}


void nfs4_close_state(struct path *path, struct nfs4_state *state, mode_t mode)
{
	__nfs4_close(path, state, mode, 0);
}


void HttpIntegrationTest::testManyRequestHeaders(std::chrono::milliseconds time) {
  config_helper_.addConfigModifier(
      [&](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm)
          -> void { hcm.mutable_max_request_headers_kb()->set_value(96); });
  max_request_headers_kb_ = 96;

  Http::TestHeaderMapImpl big_headers{
      {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}, {":authority", "host"}};

  for (int i = 0; i < 20000; i++) {
    big_headers.addCopy(std::to_string(i), std::string(0, 'a'));
  }
  initialize();

  codec_client_ = makeHttpConnection(lookupPort("http"));

  auto response =
      sendRequestAndWaitForResponse(big_headers, 0, default_response_headers_, 0, 0, time);

  EXPECT_TRUE(response->complete());
  EXPECT_EQ("200", response->headers().Status()->value().getStringView());
}


static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; block_acct_done(bdrv_get_stats(s->qdev.conf.bs), &r->acct); } if (r->req.io_canceled) { goto done; } if (ret < 0) { if (scsi_handle_rw_error(r, -ret)) { goto done; } } n = r->qiov.size / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_write_do_fua(r); return; } else { scsi_init_iovec(r, SCSI_DMA_BUF_SIZE); DPRINTF("Write complete tag=0x%x more=%zd\n", r->req.tag, r->qiov.size); scsi_req_data(&r->req, r->qiov.size); } done: if (!r->req.io_canceled) { scsi_req_unref(&r->req); } }


static int asf_write_packet ( AVFormatContext * s , AVPacket * pkt ) {
 ASFContext * asf = s -> priv_data ;
 AVIOContext * pb = s -> pb ;
 ASFStream * stream ;
 AVCodecContext * codec ;
 uint32_t packet_number ;
 int64_t pts ;
 int start_sec ;
 int flags = pkt -> flags ;
 int ret ;
 uint64_t offset = avio_tell ( pb ) ;
 codec = s -> streams [ pkt -> stream_index ] -> codec ;
 stream = & asf -> streams [ pkt -> stream_index ] ;
 if ( codec -> codec_type == AVMEDIA_TYPE_AUDIO ) flags &= ~ AV_PKT_FLAG_KEY ;
 pts = ( pkt -> pts != AV_NOPTS_VALUE ) ? pkt -> pts : pkt -> dts ;
 av_assert0 ( pts != AV_NOPTS_VALUE ) ;
 pts *= 10000 ;
 asf -> duration = FFMAX ( asf -> duration , pts + pkt -> duration * 10000 ) ;
 packet_number = asf -> nb_packets ;
 put_frame ( s , stream , s -> streams [ pkt -> stream_index ] , pkt -> dts , pkt -> data , pkt -> size , flags ) ;
 start_sec = ( int ) ( ( PREROLL_TIME * 10000 + pts + ASF_INDEXED_INTERVAL - 1 ) / ASF_INDEXED_INTERVAL ) ;
 if ( ( ! asf -> is_streamed ) && ( flags & AV_PKT_FLAG_KEY ) ) {
 uint16_t packet_count = asf -> nb_packets - packet_number ;
 ret = update_index ( s , start_sec , packet_number , packet_count , offset ) ;
 if ( ret < 0 ) return ret ;
 }
 asf -> end_sec = start_sec ;
 return 0 ;
 }


TEST_P(DownstreamProtocolIntegrationTest, LargeRequestTrailersRejected) {
  testLargeRequestTrailers(66, 60);
}


            Status readUTF8String( StringData* out ) {
                int sz;
                if ( !readNumber<int>( &sz ) )
                    return makeError("invalid bson", _idElem);

                if ( out ) {
                    *out = StringData( _buffer + _position, sz );
                }

                if ( !skip( sz - 1 ) )
                    return makeError("invalid bson", _idElem);

                char c;
                if ( !readNumber<char>( &c ) )
                    return makeError("invalid bson", _idElem);

                if ( c != 0 )
                    return makeError("not null terminated string", _idElem);

                return Status::OK();
            }


static void gen_compute_branch (DisasContext *ctx, uint32_t opc, int insn_bytes, int rs, int rt, int32_t offset) { target_ulong btgt = -1; int blink = 0; int bcond_compute = 0; TCGv t0 = tcg_temp_new(); TCGv t1 = tcg_temp_new(); if (ctx->hflags & MIPS_HFLAG_BMASK) { #ifdef MIPS_DEBUG_DISAS LOG_DISAS("Branch in delay slot at PC 0x" TARGET_FMT_lx "\n", ctx->pc); #endif generate_exception(ctx, EXCP_RI); goto out; } /* Load needed operands */ switch (opc) { case OPC_BEQ: case OPC_BEQL: case OPC_BNE: case OPC_BNEL: /* Compare two registers */ if (rs != rt) { gen_load_gpr(t0, rs); gen_load_gpr(t1, rt); bcond_compute = 1; } btgt = ctx->pc + insn_bytes + offset; break; case OPC_BGEZ: case OPC_BGEZAL: case OPC_BGEZALL: case OPC_BGEZL: case OPC_BGTZ: case OPC_BGTZL: case OPC_BLEZ: case OPC_BLEZL: case OPC_BLTZ: case OPC_BLTZAL: case OPC_BLTZALL: case OPC_BLTZL: /* Compare to zero */ if (rs != 0) { gen_load_gpr(t0, rs); bcond_compute = 1; } btgt = ctx->pc + insn_bytes + offset; break; case OPC_J: case OPC_JAL: case OPC_JALX: /* Jump to immediate */ btgt = ((ctx->pc + insn_bytes) & (int32_t)0xF0000000) | (uint32_t)offset; break; case OPC_JR: case OPC_JALR: case OPC_JALRC: /* Jump to register */ if (offset != 0 && offset != 16) { /* Hint = 0 is JR/JALR, hint 16 is JR.HB/JALR.HB, the others are reserved. */ MIPS_INVAL("jump hint"); generate_exception(ctx, EXCP_RI); goto out; } gen_load_gpr(btarget, rs); break; default: MIPS_INVAL("branch/jump"); generate_exception(ctx, EXCP_RI); goto out; } if (bcond_compute == 0) { /* No condition to be computed */ switch (opc) { case OPC_BEQ: /* rx == rx */ case OPC_BEQL: /* rx == rx likely */ case OPC_BGEZ: /* 0 >= 0 */ case OPC_BGEZL: /* 0 >= 0 likely */ case OPC_BLEZ: /* 0 <= 0 */ case OPC_BLEZL: /* 0 <= 0 likely */ /* Always take */ ctx->hflags |= MIPS_HFLAG_B; MIPS_DEBUG("balways"); break; case OPC_BGEZAL: /* 0 >= 0 */ case OPC_BGEZALL: /* 0 >= 0 likely */ /* Always take and link */ blink = 31; ctx->hflags |= MIPS_HFLAG_B; MIPS_DEBUG("balways and link"); break; case OPC_BNE: /* rx != rx */ case OPC_BGTZ: /* 0 > 0 */ case OPC_BLTZ: /* 0 < 0 */ /* Treat as NOP. */ MIPS_DEBUG("bnever (NOP)"); goto out; case OPC_BLTZAL: /* 0 < 0 */ tcg_gen_movi_tl(cpu_gpr[31], ctx->pc + 8); MIPS_DEBUG("bnever and link"); goto out; case OPC_BLTZALL: /* 0 < 0 likely */ tcg_gen_movi_tl(cpu_gpr[31], ctx->pc + 8); /* Skip the instruction in the delay slot */ MIPS_DEBUG("bnever, link and skip"); ctx->pc += 4; goto out; case OPC_BNEL: /* rx != rx likely */ case OPC_BGTZL: /* 0 > 0 likely */ case OPC_BLTZL: /* 0 < 0 likely */ /* Skip the instruction in the delay slot */ MIPS_DEBUG("bnever and skip"); ctx->pc += 4; goto out; case OPC_J: ctx->hflags |= MIPS_HFLAG_B; MIPS_DEBUG("j " TARGET_FMT_lx, btgt); break; case OPC_JALX: ctx->hflags |= MIPS_HFLAG_BX; /* Fallthrough */ case OPC_JAL: blink = 31; ctx->hflags |= MIPS_HFLAG_B; ctx->hflags |= (ctx->hflags & MIPS_HFLAG_M16 ? MIPS_HFLAG_BDS16 : MIPS_HFLAG_BDS32); MIPS_DEBUG("jal " TARGET_FMT_lx, btgt); break; case OPC_JR: ctx->hflags |= MIPS_HFLAG_BR; if (ctx->hflags & MIPS_HFLAG_M16) ctx->hflags |= MIPS_HFLAG_BDS16; MIPS_DEBUG("jr %s", regnames[rs]); break; case OPC_JALR: case OPC_JALRC: blink = rt; ctx->hflags |= MIPS_HFLAG_BR; if (ctx->hflags & MIPS_HFLAG_M16) ctx->hflags |= MIPS_HFLAG_BDS16; MIPS_DEBUG("jalr %s, %s", regnames[rt], regnames[rs]); break; default: MIPS_INVAL("branch/jump"); generate_exception(ctx, EXCP_RI); goto out; } } else { switch (opc) { case OPC_BEQ: tcg_gen_setcond_tl(TCG_COND_EQ, bcond, t0, t1); MIPS_DEBUG("beq %s, %s, " TARGET_FMT_lx, regnames[rs], regnames[rt], btgt); goto not_likely; case OPC_BEQL: tcg_gen_setcond_tl(TCG_COND_EQ, bcond, t0, t1); MIPS_DEBUG("beql %s, %s, " TARGET_FMT_lx, regnames[rs], regnames[rt], btgt); goto likely; case OPC_BNE: tcg_gen_setcond_tl(TCG_COND_NE, bcond, t0, t1); MIPS_DEBUG("bne %s, %s, " TARGET_FMT_lx, regnames[rs], regnames[rt], btgt); goto not_likely; case OPC_BNEL: tcg_gen_setcond_tl(TCG_COND_NE, bcond, t0, t1); MIPS_DEBUG("bnel %s, %s, " TARGET_FMT_lx, regnames[rs], regnames[rt], btgt); goto likely; case OPC_BGEZ: tcg_gen_setcondi_tl(TCG_COND_GE, bcond, t0, 0); MIPS_DEBUG("bgez %s, " TARGET_FMT_lx, regnames[rs], btgt); goto not_likely; case OPC_BGEZL: tcg_gen_setcondi_tl(TCG_COND_GE, bcond, t0, 0); MIPS_DEBUG("bgezl %s, " TARGET_FMT_lx, regnames[rs], btgt); goto likely; case OPC_BGEZAL: tcg_gen_setcondi_tl(TCG_COND_GE, bcond, t0, 0); MIPS_DEBUG("bgezal %s, " TARGET_FMT_lx, regnames[rs], btgt); blink = 31; goto not_likely; case OPC_BGEZALL: tcg_gen_setcondi_tl(TCG_COND_GE, bcond, t0, 0); blink = 31; MIPS_DEBUG("bgezall %s, " TARGET_FMT_lx, regnames[rs], btgt); goto likely; case OPC_BGTZ: tcg_gen_setcondi_tl(TCG_COND_GT, bcond, t0, 0); MIPS_DEBUG("bgtz %s, " TARGET_FMT_lx, regnames[rs], btgt); goto not_likely; case OPC_BGTZL: tcg_gen_setcondi_tl(TCG_COND_GT, bcond, t0, 0); MIPS_DEBUG("bgtzl %s, " TARGET_FMT_lx, regnames[rs], btgt); goto likely; case OPC_BLEZ: tcg_gen_setcondi_tl(TCG_COND_LE, bcond, t0, 0); MIPS_DEBUG("blez %s, " TARGET_FMT_lx, regnames[rs], btgt); goto not_likely; case OPC_BLEZL: tcg_gen_setcondi_tl(TCG_COND_LE, bcond, t0, 0); MIPS_DEBUG("blezl %s, " TARGET_FMT_lx, regnames[rs], btgt); goto likely; case OPC_BLTZ: tcg_gen_setcondi_tl(TCG_COND_LT, bcond, t0, 0); MIPS_DEBUG("bltz %s, " TARGET_FMT_lx, regnames[rs], btgt); goto not_likely; case OPC_BLTZL: tcg_gen_setcondi_tl(TCG_COND_LT, bcond, t0, 0); MIPS_DEBUG("bltzl %s, " TARGET_FMT_lx, regnames[rs], btgt); goto likely; case OPC_BLTZAL: tcg_gen_setcondi_tl(TCG_COND_LT, bcond, t0, 0); blink = 31; MIPS_DEBUG("bltzal %s, " TARGET_FMT_lx, regnames[rs], btgt); not_likely: ctx->hflags |= MIPS_HFLAG_BC; break; case OPC_BLTZALL: tcg_gen_setcondi_tl(TCG_COND_LT, bcond, t0, 0); blink = 31; MIPS_DEBUG("bltzall %s, " TARGET_FMT_lx, regnames[rs], btgt); likely: ctx->hflags |= MIPS_HFLAG_BL; break; default: MIPS_INVAL("conditional branch/jump"); generate_exception(ctx, EXCP_RI); goto out; } } MIPS_DEBUG("enter ds: link %d cond %02x target " TARGET_FMT_lx, blink, ctx->hflags, btgt); ctx->btarget = btgt; if (blink > 0) { int post_delay = insn_bytes; int lowbit = !!(ctx->hflags & MIPS_HFLAG_M16); if (opc != OPC_JALRC) post_delay += ((ctx->hflags & MIPS_HFLAG_BDS16) ? 2 : 4); tcg_gen_movi_tl(cpu_gpr[blink], ctx->pc + post_delay + lowbit); } out: if (insn_bytes == 2) ctx->hflags |= MIPS_HFLAG_B16; tcg_temp_free(t0); tcg_temp_free(t1); }


static int nntp_date ( struct NntpServer * nserv , time_t * now ) {
 if ( nserv -> hasDATE ) {
 struct NntpData nntp_data ;
 char buf [ LONG_STRING ] ;
 struct tm tm ;
 memset ( & tm , 0 , sizeof ( tm ) ) ;
 nntp_data . nserv = nserv ;
 nntp_data . group = NULL ;
 mutt_str_strfcpy ( buf , "DATE\r\n" , sizeof ( buf ) ) ;
 if ( nntp_query ( & nntp_data , buf , sizeof ( buf ) ) < 0 ) return - 1 ;
 if ( sscanf ( buf , "111 %4d%2d%2d%2d%2d%2d%*s" , & tm . tm_year , & tm . tm_mon , & tm . tm_mday , & tm . tm_hour , & tm . tm_min , & tm . tm_sec ) == 6 ) {
 tm . tm_year -= 1900 ;
 tm . tm_mon -- ;
 * now = timegm ( & tm ) ;
 if ( * now >= 0 ) {
 mutt_debug ( 1 , "server time is %lu\n" , * now ) ;
 return 0 ;
 }
 }
 }
 time ( now ) ;
 return 0 ;
 }


TEST_F ( AutocompleteResultTest , CopyOldMatches ) {
 TestData last [ ] = {
 {
 0 , 1 , 1000 , true }
 , {
 1 , 1 , 500 , true }
 , }
 ;
 TestData current [ ] = {
 {
 2 , 1 , 400 , true }
 , }
 ;
 TestData result [ ] = {
 {
 2 , 1 , 400 , true }
 , {
 1 , 1 , 399 , true }
 , }
 ;
 ASSERT_NO_FATAL_FAILURE ( RunCopyOldMatchesTest ( last , arraysize ( last ) , current , arraysize ( current ) , result , arraysize ( result ) ) ) ;
 }


CertificateValidationContextConfigImpl::CertificateValidationContextConfigImpl(
    const envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext& config,
    Api::Api& api)
    : ca_cert_(Config::DataSource::read(config.trusted_ca(), true, api)),
      ca_cert_path_(Config::DataSource::getPath(config.trusted_ca())
                        .value_or(ca_cert_.empty() ? EMPTY_STRING : INLINE_STRING)),
      certificate_revocation_list_(Config::DataSource::read(config.crl(), true, api)),
      certificate_revocation_list_path_(
          Config::DataSource::getPath(config.crl())
              .value_or(certificate_revocation_list_.empty() ? EMPTY_STRING : INLINE_STRING)),
      subject_alt_name_matchers_(getSubjectAltNameMatchers(config)),
      verify_certificate_hash_list_(config.verify_certificate_hash().begin(),
                                    config.verify_certificate_hash().end()),
      verify_certificate_spki_list_(config.verify_certificate_spki().begin(),
                                    config.verify_certificate_spki().end()),
      allow_expired_certificate_(config.allow_expired_certificate()),
      trust_chain_verification_(config.trust_chain_verification()),
      custom_validator_config_(
          config.has_custom_validator_config()
              ? absl::make_optional<envoy::config::core::v3::TypedExtensionConfig>(
                    config.custom_validator_config())
              : absl::nullopt),
      api_(api), only_verify_leaf_cert_crl_(config.only_verify_leaf_cert_crl()) {
  if (ca_cert_.empty() && custom_validator_config_ == absl::nullopt) {
    if (!certificate_revocation_list_.empty()) {
      throw EnvoyException(fmt::format("Failed to load CRL from {} without trusted CA",
                                       certificateRevocationListPath()));
    }
    if (!subject_alt_name_matchers_.empty()) {
      throw EnvoyException("SAN-based verification of peer certificates without "
                           "trusted CA is insecure and not allowed");
    }
    if (allow_expired_certificate_) {
      throw EnvoyException("Certificate validity period is always ignored without trusted CA");
    }
  }
}


void exit_io_context(void)
{
	struct io_context *ioc;

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

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

	}
	put_io_context(ioc);
}


static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx) { NvencContext *ctx = avctx->priv_data; NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs; NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs; NVENCSTATUS nv_status; NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 }; allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER; if (avctx->pix_fmt == AV_PIX_FMT_CUDA) { ctx->surfaces[idx].in_ref = av_frame_alloc(); if (!ctx->surfaces[idx].in_ref) return AVERROR(ENOMEM); } else { NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 }; ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt); if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) { av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n", av_get_pix_fmt_name(ctx->data_pix_fmt)); return AVERROR(EINVAL); } allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER; allocSurf.width = (avctx->width + 31) & ~31; allocSurf.height = (avctx->height + 31) & ~31; allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED; allocSurf.bufferFmt = ctx->surfaces[idx].format; nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf); if (nv_status != NV_ENC_SUCCESS) { return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed"); } ctx->surfaces[idx].input_surface = allocSurf.inputBuffer; ctx->surfaces[idx].width = allocSurf.width; ctx->surfaces[idx].height = allocSurf.height; } ctx->surfaces[idx].lockCount = 0; /* 1MB is large enough to hold most output frames. * NVENC increases this automaticaly if it is not enough. */ allocOut.size = 1024 * 1024; allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED; nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut); if (nv_status != NV_ENC_SUCCESS) { int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed"); if (avctx->pix_fmt != AV_PIX_FMT_CUDA) p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface); av_frame_free(&ctx->surfaces[idx].in_ref); return err; } ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer; ctx->surfaces[idx].size = allocOut.size; return 0; }


void host_cpuid(uint32_t function, uint32_t count, uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx) { #if defined(CONFIG_KVM) uint32_t vec[4]; #ifdef __x86_64__ asm volatile("cpuid" : "=a"(vec[0]), "=b"(vec[1]), "=c"(vec[2]), "=d"(vec[3]) : "0"(function), "c"(count) : "cc"); #else asm volatile("pusha \n\t" "cpuid \n\t" "mov %%eax, 0(%2) \n\t" "mov %%ebx, 4(%2) \n\t" "mov %%ecx, 8(%2) \n\t" "mov %%edx, 12(%2) \n\t" "popa" : : "a"(function), "c"(count), "S"(vec) : "memory", "cc"); #endif if (eax) *eax = vec[0]; if (ebx) *ebx = vec[1]; if (ecx) *ecx = vec[2]; if (edx) *edx = vec[3]; #endif }


static void _LMBCSOpen ## n ( UConverter * _this , UConverterLoadArgs * pArgs , UErrorCode * err ) \ {
 _LMBCSOpenWorker ( _this , pArgs , err , n ) ;
 }
 static void _LMBCSOpenWorker ( UConverter * _this , UConverterLoadArgs * pArgs , UErrorCode * err , ulmbcs_byte_t OptGroup ) {
 UConverterDataLMBCS * extraInfo = _this -> extraInfo = ( UConverterDataLMBCS * ) uprv_malloc ( sizeof ( UConverterDataLMBCS ) ) ;
 if ( extraInfo != NULL ) {
 UConverterNamePieces stackPieces ;
 UConverterLoadArgs stackArgs = {
 ( int32_t ) sizeof ( UConverterLoadArgs ) }
 ;
 ulmbcs_byte_t i ;
 uprv_memset ( extraInfo , 0 , sizeof ( UConverterDataLMBCS ) ) ;
 stackArgs . onlyTestIsLoadable = pArgs -> onlyTestIsLoadable ;
 for ( i = 0 ;
 i <= ULMBCS_GRP_LAST && U_SUCCESS ( * err ) ;
 i ++ ) {
 if ( OptGroupByteToCPName [ i ] != NULL ) {
 extraInfo -> OptGrpConverter [ i ] = ucnv_loadSharedData ( OptGroupByteToCPName [ i ] , & stackPieces , & stackArgs , err ) ;
 }
 }
 if ( U_FAILURE ( * err ) || pArgs -> onlyTestIsLoadable ) {
 _LMBCSClose ( _this ) ;
 return ;
 }
 extraInfo -> OptGroup = OptGroup ;
 extraInfo -> localeConverterIndex = FindLMBCSLocale ( pArgs -> locale ) ;
 }
 else {
 * err = U_MEMORY_ALLOCATION_ERROR ;
 }
 }
 static void _LMBCSClose ( UConverter * _this ) {
 if ( _this -> extraInfo != NULL ) {
 ulmbcs_byte_t Ix ;
 UConverterDataLMBCS * extraInfo = ( UConverterDataLMBCS * ) _this -> extraInfo ;
 for ( Ix = 0 ;
 Ix <= ULMBCS_GRP_LAST ;
 Ix ++ ) {
 if ( extraInfo -> OptGrpConverter [ Ix ] != NULL ) ucnv_unloadSharedDataIfReady ( extraInfo -> OptGrpConverter [ Ix ] ) ;
 }
 if ( ! _this -> isExtraLocal ) {
 uprv_free ( _this -> extraInfo ) ;
 _this -> extraInfo = NULL ;
 }
 }
 }
 typedef struct LMBCSClone {
 UConverter cnv ;
 UConverterDataLMBCS lmbcs ;
 }
 LMBCSClone ;
 static UConverter * _LMBCSSafeClone ( const UConverter * cnv , void * stackBuffer , int32_t * pBufferSize , UErrorCode * status ) {
 LMBCSClone * newLMBCS ;
 UConverterDataLMBCS * extraInfo ;
 int32_t i ;
 if ( * pBufferSize <= 0 ) {
 * pBufferSize = ( int32_t ) sizeof ( LMBCSClone ) ;
 return NULL ;
 }
 extraInfo = ( UConverterDataLMBCS * ) cnv -> extraInfo ;
 newLMBCS = ( LMBCSClone * ) stackBuffer ;
 uprv_memcpy ( & newLMBCS -> lmbcs , extraInfo , sizeof ( UConverterDataLMBCS ) ) ;
 for ( i = 0 ;
 i <= ULMBCS_GRP_LAST ;
 ++ i ) {
 if ( extraInfo -> OptGrpConverter [ i ] != NULL ) {
 ucnv_incrementRefCount ( extraInfo -> OptGrpConverter [ i ] ) ;
 }
 }
 newLMBCS -> cnv . extraInfo = & newLMBCS -> lmbcs ;
 newLMBCS -> cnv . isExtraLocal = TRUE ;
 return & newLMBCS -> cnv ;
 }
 static size_t LMBCSConversionWorker ( UConverterDataLMBCS * extraInfo , ulmbcs_byte_t group , ulmbcs_byte_t * pStartLMBCS , UChar * pUniChar , ulmbcs_byte_t * lastConverterIndex , UBool * groups_tried ) {
 ulmbcs_byte_t * pLMBCS = pStartLMBCS ;
 UConverterSharedData * xcnv = extraInfo -> OptGrpConverter [ group ] ;
 int bytesConverted ;
 uint32_t value ;
 ulmbcs_byte_t firstByte ;
 U_ASSERT ( xcnv ) ;
 U_ASSERT ( group < ULMBCS_GRP_UNICODE ) ;
 bytesConverted = ucnv_MBCSFromUChar32 ( xcnv , * pUniChar , & value , FALSE ) ;
 if ( bytesConverted > 0 ) {
 firstByte = ( ulmbcs_byte_t ) ( value >> ( ( bytesConverted - 1 ) * 8 ) ) ;
 }
 else {
 groups_tried [ group ] = TRUE ;
 return 0 ;
 }
 * lastConverterIndex = group ;
 U_ASSERT ( ( firstByte <= ULMBCS_C0END ) || ( firstByte >= ULMBCS_C1START ) || ( group == ULMBCS_GRP_EXCEPT ) ) ;
 if ( group != ULMBCS_GRP_EXCEPT && extraInfo -> OptGroup != group ) {
 * pLMBCS ++ = group ;
 if ( bytesConverted == 1 && group >= ULMBCS_DOUBLEOPTGROUP_START ) {
 * pLMBCS ++ = group ;
 }
 }
 if ( bytesConverted == 1 && firstByte < 0x20 ) return 0 ;
 switch ( bytesConverted ) {
 case 4 : * pLMBCS ++ = ( ulmbcs_byte_t ) ( value >> 24 ) ;
 U_FALLTHROUGH ;
 case 3 : * pLMBCS ++ = ( ulmbcs_byte_t ) ( value >> 16 ) ;
 U_FALLTHROUGH ;
 case 2 : * pLMBCS ++ = ( ulmbcs_byte_t ) ( value >> 8 ) ;
 U_FALLTHROUGH ;
 case 1 : * pLMBCS ++ = ( ulmbcs_byte_t ) value ;
 U_FALLTHROUGH ;
 default : break ;
 }
 return ( pLMBCS - pStartLMBCS ) ;
 }
 static size_t LMBCSConvertUni ( ulmbcs_byte_t * pLMBCS , UChar uniChar ) {
 uint8_t LowCh = ( uint8_t ) ( uniChar & 0x00FF ) ;
 uint8_t HighCh = ( uint8_t ) ( uniChar >> 8 ) ;
 * pLMBCS ++ = ULMBCS_GRP_UNICODE ;
 if ( LowCh == 0 ) {
 * pLMBCS ++ = ULMBCS_UNICOMPATZERO ;
 * pLMBCS ++ = HighCh ;
 }
 else {
 * pLMBCS ++ = HighCh ;
 * pLMBCS ++ = LowCh ;
 }
 return ULMBCS_UNICODE_SIZE ;
 }
 static void _LMBCSFromUnicode ( UConverterFromUnicodeArgs * args , UErrorCode * err ) {
 ulmbcs_byte_t lastConverterIndex = 0 ;
 UChar uniChar ;
 ulmbcs_byte_t LMBCS [ ULMBCS_CHARSIZE_MAX ] ;
 ulmbcs_byte_t * pLMBCS ;
 int32_t bytes_written ;
 UBool groups_tried [ ULMBCS_GRP_LAST + 1 ] ;
 UConverterDataLMBCS * extraInfo = ( UConverterDataLMBCS * ) args -> converter -> extraInfo ;
 int sourceIndex = 0 ;
 ulmbcs_byte_t OldConverterIndex = 0 ;
 while ( args -> source < args -> sourceLimit && ! U_FAILURE ( * err ) ) {
 OldConverterIndex = extraInfo -> localeConverterIndex ;
 if ( args -> target >= args -> targetLimit ) {
 * err = U_BUFFER_OVERFLOW_ERROR ;
 break ;
 }
 uniChar = * ( args -> source ) ;
 bytes_written = 0 ;
 pLMBCS = LMBCS ;
 if ( ( uniChar >= 0x80 ) && ( uniChar <= 0xff ) && ( uniChar != 0xB1 ) && ( uniChar != 0xD7 ) && ( uniChar != 0xF7 ) && ( uniChar != 0xB0 ) && ( uniChar != 0xB4 ) && ( uniChar != 0xB6 ) && ( uniChar != 0xA7 ) && ( uniChar != 0xA8 ) ) {
 extraInfo -> localeConverterIndex = ULMBCS_GRP_L1 ;
 }
 if ( ( ( uniChar > ULMBCS_C0END ) && ( uniChar < ULMBCS_C1START ) ) || uniChar == 0 || uniChar == ULMBCS_HT || uniChar == ULMBCS_CR || uniChar == ULMBCS_LF || uniChar == ULMBCS_123SYSTEMRANGE ) {
 * pLMBCS ++ = ( ulmbcs_byte_t ) uniChar ;
 bytes_written = 1 ;
 }
 if ( ! bytes_written ) {
 ulmbcs_byte_t group = FindLMBCSUniRange ( uniChar ) ;
 if ( group == ULMBCS_GRP_UNICODE ) {
 pLMBCS += LMBCSConvertUni ( pLMBCS , uniChar ) ;
 bytes_written = ( int32_t ) ( pLMBCS - LMBCS ) ;
 }
 else if ( group == ULMBCS_GRP_CTRL ) {
 if ( uniChar <= ULMBCS_C0END ) {
 * pLMBCS ++ = ULMBCS_GRP_CTRL ;
 * pLMBCS ++ = ( ulmbcs_byte_t ) ( ULMBCS_CTRLOFFSET + uniChar ) ;
 }
 else if ( uniChar >= ULMBCS_C1START && uniChar <= ULMBCS_C1START + ULMBCS_CTRLOFFSET ) {
 * pLMBCS ++ = ULMBCS_GRP_CTRL ;
 * pLMBCS ++ = ( ulmbcs_byte_t ) ( uniChar & 0x00FF ) ;
 }
 bytes_written = ( int32_t ) ( pLMBCS - LMBCS ) ;
 }
 else if ( group < ULMBCS_GRP_UNICODE ) {
 bytes_written = ( int32_t ) LMBCSConversionWorker ( extraInfo , group , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 if ( ! bytes_written ) {
 uprv_memset ( groups_tried , 0 , sizeof ( groups_tried ) ) ;
 if ( ( extraInfo -> OptGroup != 1 ) && ( ULMBCS_AMBIGUOUS_MATCH ( group , extraInfo -> OptGroup ) ) ) {
 if ( extraInfo -> localeConverterIndex < ULMBCS_DOUBLEOPTGROUP_START ) {
 bytes_written = LMBCSConversionWorker ( extraInfo , ULMBCS_GRP_L1 , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 if ( ! bytes_written ) {
 bytes_written = LMBCSConversionWorker ( extraInfo , ULMBCS_GRP_EXCEPT , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 if ( ! bytes_written ) {
 bytes_written = LMBCSConversionWorker ( extraInfo , extraInfo -> localeConverterIndex , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 }
 else {
 bytes_written = LMBCSConversionWorker ( extraInfo , extraInfo -> localeConverterIndex , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 }
 if ( ! bytes_written && ( extraInfo -> localeConverterIndex ) && ( ULMBCS_AMBIGUOUS_MATCH ( group , extraInfo -> localeConverterIndex ) ) ) {
 bytes_written = ( int32_t ) LMBCSConversionWorker ( extraInfo , extraInfo -> localeConverterIndex , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 if ( ! bytes_written && ( lastConverterIndex ) && ( ULMBCS_AMBIGUOUS_MATCH ( group , lastConverterIndex ) ) ) {
 bytes_written = ( int32_t ) LMBCSConversionWorker ( extraInfo , lastConverterIndex , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 if ( ! bytes_written ) {
 ulmbcs_byte_t grp_start ;
 ulmbcs_byte_t grp_end ;
 ulmbcs_byte_t grp_ix ;
 grp_start = ( ulmbcs_byte_t ) ( ( group == ULMBCS_AMBIGUOUS_MBCS ) ? ULMBCS_DOUBLEOPTGROUP_START : ULMBCS_GRP_L1 ) ;
 grp_end = ( ulmbcs_byte_t ) ( ( group == ULMBCS_AMBIGUOUS_MBCS ) ? ULMBCS_GRP_LAST : ULMBCS_GRP_TH ) ;
 if ( group == ULMBCS_AMBIGUOUS_ALL ) {
 grp_start = ULMBCS_GRP_L1 ;
 grp_end = ULMBCS_GRP_LAST ;
 }
 for ( grp_ix = grp_start ;
 grp_ix <= grp_end && ! bytes_written ;
 grp_ix ++ ) {
 if ( extraInfo -> OptGrpConverter [ grp_ix ] && ! groups_tried [ grp_ix ] ) {
 bytes_written = ( int32_t ) LMBCSConversionWorker ( extraInfo , grp_ix , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 }
 if ( ! bytes_written && grp_start == ULMBCS_GRP_L1 ) {
 bytes_written = ( int32_t ) LMBCSConversionWorker ( extraInfo , ULMBCS_GRP_EXCEPT , pLMBCS , & uniChar , & lastConverterIndex , groups_tried ) ;
 }
 }
 if ( ! bytes_written ) {
 pLMBCS += LMBCSConvertUni ( pLMBCS , uniChar ) ;
 bytes_written = ( int32_t ) ( pLMBCS - LMBCS ) ;
 }
 }
 }
 args -> source ++ ;
 pLMBCS = LMBCS ;
 while ( args -> target < args -> targetLimit && bytes_written -- ) {
 * ( args -> target ) ++ = * pLMBCS ++ ;
 if ( args -> offsets ) {
 * ( args -> offsets ) ++ = sourceIndex ;
 }
 }
 sourceIndex ++ ;
 if ( bytes_written > 0 ) {
 uint8_t * pErrorBuffer = args -> converter -> charErrorBuffer ;
 * err = U_BUFFER_OVERFLOW_ERROR ;
 args -> converter -> charErrorBufferLength = ( int8_t ) bytes_written ;
 while ( bytes_written -- ) {
 * pErrorBuffer ++ = * pLMBCS ++ ;
 }
 }
 extraInfo -> localeConverterIndex = OldConverterIndex ;
 }
 }
 static UChar GetUniFromLMBCSUni ( char const * * ppLMBCSin ) {
 uint8_t HighCh = * ( * ppLMBCSin ) ++ ;
 uint8_t LowCh = * ( * ppLMBCSin ) ++ ;
 if ( HighCh == ULMBCS_UNICOMPATZERO ) {
 HighCh = LowCh ;
 LowCh = 0 ;
 }
 return ( UChar ) ( ( HighCh << 8 ) | LowCh ) ;
 }
 # define CHECK_SOURCE_LIMIT ( index ) if ( args -> source + index > args -> sourceLimit ) {
 * err = U_TRUNCATED_CHAR_FOUND ;
 args -> source = args -> sourceLimit ;
 return 0xffff ;
 }
 static UChar32 _LMBCSGetNextUCharWorker ( UConverterToUnicodeArgs * args , UErrorCode * err ) {
 UChar32 uniChar = 0 ;
 ulmbcs_byte_t CurByte ;
 if ( args -> source >= args -> sourceLimit ) {
 * err = U_ILLEGAL_ARGUMENT_ERROR ;
 return 0xffff ;
 }
 CurByte = * ( ( ulmbcs_byte_t * ) ( args -> source ++ ) ) ;
 if ( ( ( CurByte > ULMBCS_C0END ) && ( CurByte < ULMBCS_C1START ) ) || ( CurByte == 0 ) || CurByte == ULMBCS_HT || CurByte == ULMBCS_CR || CurByte == ULMBCS_LF || CurByte == ULMBCS_123SYSTEMRANGE ) {
 uniChar = CurByte ;
 }
 else {
 UConverterDataLMBCS * extraInfo ;
 ulmbcs_byte_t group ;
 UConverterSharedData * cnv ;
 if ( CurByte == ULMBCS_GRP_CTRL ) {
 ulmbcs_byte_t C0C1byte ;
 CHECK_SOURCE_LIMIT ( 1 ) ;
 C0C1byte = * ( args -> source ) ++ ;
 uniChar = ( C0C1byte < ULMBCS_C1START ) ? C0C1byte - ULMBCS_CTRLOFFSET : C0C1byte ;
 }
 else if ( CurByte == ULMBCS_GRP_UNICODE ) {
 CHECK_SOURCE_LIMIT ( 2 ) ;
 return GetUniFromLMBCSUni ( & ( args -> source ) ) ;
 }
 else if ( CurByte <= ULMBCS_CTRLOFFSET ) {
 group = CurByte ;
 extraInfo = ( UConverterDataLMBCS * ) args -> converter -> extraInfo ;
 if ( group > ULMBCS_GRP_LAST || ( cnv = extraInfo -> OptGrpConverter [ group ] ) == NULL ) {
 * err = U_INVALID_CHAR_FOUND ;
 }
 else if ( group >= ULMBCS_DOUBLEOPTGROUP_START ) {
 CHECK_SOURCE_LIMIT ( 2 ) ;
 if ( * args -> source == group ) {
 ++ args -> source ;
 uniChar = ucnv_MBCSSimpleGetNextUChar ( cnv , args -> source , 1 , FALSE ) ;
 ++ args -> source ;
 }
 else {
 uniChar = ucnv_MBCSSimpleGetNextUChar ( cnv , args -> source , 2 , FALSE ) ;
 args -> source += 2 ;
 }
 }
 else {
 CHECK_SOURCE_LIMIT ( 1 ) ;
 CurByte = * ( args -> source ) ++ ;
 if ( CurByte >= ULMBCS_C1START ) {
 uniChar = _MBCS_SINGLE_SIMPLE_GET_NEXT_BMP ( cnv , CurByte ) ;
 }
 else {
 char bytes [ 2 ] ;
 extraInfo = ( UConverterDataLMBCS * ) args -> converter -> extraInfo ;
 cnv = extraInfo -> OptGrpConverter [ ULMBCS_GRP_EXCEPT ] ;
 bytes [ 0 ] = group ;
 bytes [ 1 ] = CurByte ;
 uniChar = ucnv_MBCSSimpleGetNextUChar ( cnv , bytes , 2 , FALSE ) ;
 }
 }
 }
 else if ( CurByte >= ULMBCS_C1START ) {
 extraInfo = ( UConverterDataLMBCS * ) args -> converter -> extraInfo ;
 group = extraInfo -> OptGroup ;
 cnv = extraInfo -> OptGrpConverter [ group ] ;
 if ( group >= ULMBCS_DOUBLEOPTGROUP_START ) {
 if ( ! ucnv_MBCSIsLeadByte ( cnv , CurByte ) ) {
 CHECK_SOURCE_LIMIT ( 0 ) ;
 uniChar = ucnv_MBCSSimpleGetNextUChar ( cnv , args -> source - 1 , 1 , FALSE ) ;
 }
 else {
 CHECK_SOURCE_LIMIT ( 1 ) ;
 uniChar = ucnv_MBCSSimpleGetNextUChar ( cnv , args -> source - 1 , 2 , FALSE ) ;
 ++ args -> source ;
 }
 }
 else {
 uniChar = _MBCS_SINGLE_SIMPLE_GET_NEXT_BMP ( cnv , CurByte ) ;
 }
 }
 }
 return uniChar ;
 }
 static void _LMBCSToUnicodeWithOffsets ( UConverterToUnicodeArgs * args , UErrorCode * err ) {
 char LMBCS [ ULMBCS_CHARSIZE_MAX ] ;
 UChar uniChar ;
 const char * saveSource ;
 const char * pStartLMBCS = args -> source ;
 const char * errSource = NULL ;
 int8_t savebytes = 0 ;
 while ( U_SUCCESS ( * err ) && args -> sourceLimit > args -> source && args -> targetLimit > args -> target ) {
 saveSource = args -> source ;
 if ( args -> converter -> toULength ) {
 const char * saveSourceLimit ;
 size_t size_old = args -> converter -> toULength ;
 size_t size_new_maybe_1 = sizeof ( LMBCS ) - size_old ;
 size_t size_new_maybe_2 = args -> sourceLimit - args -> source ;
 size_t size_new = ( size_new_maybe_1 < size_new_maybe_2 ) ? size_new_maybe_1 : size_new_maybe_2 ;
 uprv_memcpy ( LMBCS , args -> converter -> toUBytes , size_old ) ;
 uprv_memcpy ( LMBCS + size_old , args -> source , size_new ) ;
 saveSourceLimit = args -> sourceLimit ;
 args -> source = errSource = LMBCS ;
 args -> sourceLimit = LMBCS + size_old + size_new ;
 savebytes = ( int8_t ) ( size_old + size_new ) ;
 uniChar = ( UChar ) _LMBCSGetNextUCharWorker ( args , err ) ;
 args -> source = saveSource + ( ( args -> source - LMBCS ) - size_old ) ;
 args -> sourceLimit = saveSourceLimit ;
 if ( * err == U_TRUNCATED_CHAR_FOUND ) {
 args -> converter -> toULength = savebytes ;
 uprv_memcpy ( args -> converter -> toUBytes , LMBCS , savebytes ) ;
 args -> source = args -> sourceLimit ;
 * err = U_ZERO_ERROR ;
 return ;
 }
 else {
 args -> converter -> toULength = 0 ;
 }
 }
 else {
 errSource = saveSource ;
 uniChar = ( UChar ) _LMBCSGetNextUCharWorker ( args , err ) ;
 savebytes = ( int8_t ) ( args -> source - saveSource ) ;
 }
 if ( U_SUCCESS ( * err ) ) {
 if ( uniChar < 0xfffe ) {
 * ( args -> target ) ++ = uniChar ;
 if ( args -> offsets ) {
 * ( args -> offsets ) ++ = ( int32_t ) ( saveSource - pStartLMBCS ) ;
 }
 }
 else if ( uniChar == 0xfffe ) {
 * err = U_INVALID_CHAR_FOUND ;
 }
 else {
 * err = U_ILLEGAL_CHAR_FOUND ;
 }
 }
 }
 if ( U_SUCCESS ( * err ) && args -> sourceLimit > args -> source && args -> targetLimit <= args -> target ) {
 * err = U_BUFFER_OVERFLOW_ERROR ;
 }
 else if ( U_FAILURE ( * err ) ) {
 args -> converter -> toULength = savebytes ;
 if ( savebytes > 0 ) {
 uprv_memcpy ( args -> converter -> toUBytes , errSource , savebytes ) ;
 }
 if ( * err == U_TRUNCATED_CHAR_FOUND ) {
 * err = U_ZERO_ERROR ;
 }
 }
 }
 DEFINE_LMBCS_OPEN ( 1 ) DEFINE_LMBCS_OPEN ( 2 )


static inline void vga_draw_glyph_line ( uint8_t * d , uint32_t font_data , uint32_t xorcol , uint32_t bgcol ) {
 ( ( uint32_t * ) d ) [ 0 ] = ( - ( ( font_data >> 7 ) ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 1 ] = ( - ( ( font_data >> 6 ) & 1 ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 2 ] = ( - ( ( font_data >> 5 ) & 1 ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 3 ] = ( - ( ( font_data >> 4 ) & 1 ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 4 ] = ( - ( ( font_data >> 3 ) & 1 ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 5 ] = ( - ( ( font_data >> 2 ) & 1 ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 6 ] = ( - ( ( font_data >> 1 ) & 1 ) & xorcol ) ^ bgcol ;
 ( ( uint32_t * ) d ) [ 7 ] = ( - ( ( font_data >> 0 ) & 1 ) & xorcol ) ^ bgcol ;
 }


int proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)
{
	zval **login, **password;

	if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS) {
		unsigned char* buf;
		int len;
		smart_str auth = {0};

		smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));
		smart_str_appendc(&auth, ':');
		if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS) {
			smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));
		}
		smart_str_0(&auth);
		buf = php_base64_encode((unsigned char*)auth.c, auth.len, &len);
		smart_str_append_const(soap_headers, "Proxy-Authorization: Basic ");
		smart_str_appendl(soap_headers, (char*)buf, len);
		smart_str_append_const(soap_headers, "\r\n");
		efree(buf);
		smart_str_free(&auth);
		return 1;
	}
	return 0;
}


static inline void downmix_dualmono_to_stereo(float *samples) { int i; float tmp; for (i = 0; i < 256; i++) { tmp = samples[i] + samples[i + 256]; samples[i] = samples[i + 256] = tmp; } }


static int kvm_get_msrs ( X86CPU * cpu ) {
 CPUX86State * env = & cpu -> env ;
 struct kvm_msr_entry * msrs = cpu -> kvm_msr_buf -> entries ;
 int ret , i ;
 uint64_t mtrr_top_bits ;
 kvm_msr_buf_reset ( cpu ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_SYSENTER_CS , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_SYSENTER_ESP , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_SYSENTER_EIP , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_PAT , 0 ) ;
 if ( has_msr_star ) {
 kvm_msr_entry_add ( cpu , MSR_STAR , 0 ) ;
 }
 if ( has_msr_hsave_pa ) {
 kvm_msr_entry_add ( cpu , MSR_VM_HSAVE_PA , 0 ) ;
 }
 if ( has_msr_tsc_aux ) {
 kvm_msr_entry_add ( cpu , MSR_TSC_AUX , 0 ) ;
 }
 if ( has_msr_tsc_adjust ) {
 kvm_msr_entry_add ( cpu , MSR_TSC_ADJUST , 0 ) ;
 }
 if ( has_msr_tsc_deadline ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_TSCDEADLINE , 0 ) ;
 }
 if ( has_msr_misc_enable ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_MISC_ENABLE , 0 ) ;
 }
 if ( has_msr_smbase ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_SMBASE , 0 ) ;
 }
 if ( has_msr_smi_count ) {
 kvm_msr_entry_add ( cpu , MSR_SMI_COUNT , 0 ) ;
 }
 if ( has_msr_feature_control ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_FEATURE_CONTROL , 0 ) ;
 }
 if ( has_msr_bndcfgs ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_BNDCFGS , 0 ) ;
 }
 if ( has_msr_xss ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_XSS , 0 ) ;
 }
 if ( has_msr_spec_ctrl ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_SPEC_CTRL , 0 ) ;
 }
 if ( ! env -> tsc_valid ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_TSC , 0 ) ;
 env -> tsc_valid = ! runstate_is_running ( ) ;
 }
 # ifdef TARGET_X86_64 if ( lm_capable_kernel ) {
 kvm_msr_entry_add ( cpu , MSR_CSTAR , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_KERNELGSBASE , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_FMASK , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_LSTAR , 0 ) ;
 }
 # endif kvm_msr_entry_add ( cpu , MSR_KVM_SYSTEM_TIME , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_KVM_WALL_CLOCK , 0 ) ;
 if ( env -> features [ FEAT_KVM ] & ( 1 << KVM_FEATURE_ASYNC_PF ) ) {
 kvm_msr_entry_add ( cpu , MSR_KVM_ASYNC_PF_EN , 0 ) ;
 }
 if ( env -> features [ FEAT_KVM ] & ( 1 << KVM_FEATURE_PV_EOI ) ) {
 kvm_msr_entry_add ( cpu , MSR_KVM_PV_EOI_EN , 0 ) ;
 }
 if ( env -> features [ FEAT_KVM ] & ( 1 << KVM_FEATURE_STEAL_TIME ) ) {
 kvm_msr_entry_add ( cpu , MSR_KVM_STEAL_TIME , 0 ) ;
 }
 if ( has_architectural_pmu_version > 0 ) {
 if ( has_architectural_pmu_version > 1 ) {
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_FIXED_CTR_CTRL , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_CTRL , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_STATUS , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_GLOBAL_OVF_CTRL , 0 ) ;
 }
 for ( i = 0 ;
 i < num_architectural_pmu_fixed_counters ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_CORE_PERF_FIXED_CTR0 + i , 0 ) ;
 }
 for ( i = 0 ;
 i < num_architectural_pmu_gp_counters ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_P6_PERFCTR0 + i , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_P6_EVNTSEL0 + i , 0 ) ;
 }
 }
 if ( env -> mcg_cap ) {
 kvm_msr_entry_add ( cpu , MSR_MCG_STATUS , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MCG_CTL , 0 ) ;
 if ( has_msr_mcg_ext_ctl ) {
 kvm_msr_entry_add ( cpu , MSR_MCG_EXT_CTL , 0 ) ;
 }
 for ( i = 0 ;
 i < ( env -> mcg_cap & 0xff ) * 4 ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_MC0_CTL + i , 0 ) ;
 }
 }
 if ( has_msr_hv_hypercall ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_HYPERCALL , 0 ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_GUEST_OS_ID , 0 ) ;
 }
 if ( cpu -> hyperv_vapic ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_APIC_ASSIST_PAGE , 0 ) ;
 }
 if ( cpu -> hyperv_time ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_REFERENCE_TSC , 0 ) ;
 }
 if ( cpu -> hyperv_reenlightenment ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_REENLIGHTENMENT_CONTROL , 0 ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_TSC_EMULATION_CONTROL , 0 ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_TSC_EMULATION_STATUS , 0 ) ;
 }
 if ( has_msr_hv_crash ) {
 int j ;
 for ( j = 0 ;
 j < HV_CRASH_PARAMS ;
 j ++ ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_CRASH_P0 + j , 0 ) ;
 }
 }
 if ( has_msr_hv_runtime ) {
 kvm_msr_entry_add ( cpu , HV_X64_MSR_VP_RUNTIME , 0 ) ;
 }
 if ( cpu -> hyperv_synic ) {
 uint32_t msr ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SCONTROL , 0 ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SIEFP , 0 ) ;
 kvm_msr_entry_add ( cpu , HV_X64_MSR_SIMP , 0 ) ;
 for ( msr = HV_X64_MSR_SINT0 ;
 msr <= HV_X64_MSR_SINT15 ;
 msr ++ ) {
 kvm_msr_entry_add ( cpu , msr , 0 ) ;
 }
 }
 if ( has_msr_hv_stimer ) {
 uint32_t msr ;
 for ( msr = HV_X64_MSR_STIMER0_CONFIG ;
 msr <= HV_X64_MSR_STIMER3_COUNT ;
 msr ++ ) {
 kvm_msr_entry_add ( cpu , msr , 0 ) ;
 }
 }
 if ( env -> features [ FEAT_1_EDX ] & CPUID_MTRR ) {
 kvm_msr_entry_add ( cpu , MSR_MTRRdefType , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix64K_00000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix16K_80000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix16K_A0000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_C0000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_C8000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_D0000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_D8000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_E0000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_E8000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_F0000 , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRfix4K_F8000 , 0 ) ;
 for ( i = 0 ;
 i < MSR_MTRRcap_VCNT ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_MTRRphysBase ( i ) , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_MTRRphysMask ( i ) , 0 ) ;
 }
 }
 if ( env -> features [ FEAT_7_0_EBX ] & CPUID_7_0_EBX_INTEL_PT ) {
 int addr_num = kvm_arch_get_supported_cpuid ( kvm_state , 0x14 , 1 , R_EAX ) & 0x7 ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_CTL , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_STATUS , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_OUTPUT_BASE , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_OUTPUT_MASK , 0 ) ;
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_CR3_MATCH , 0 ) ;
 for ( i = 0 ;
 i < addr_num ;
 i ++ ) {
 kvm_msr_entry_add ( cpu , MSR_IA32_RTIT_ADDR0_A + i , 0 ) ;
 }
 }
 ret = kvm_vcpu_ioctl ( CPU ( cpu ) , KVM_GET_MSRS , cpu -> kvm_msr_buf ) ;
 if ( ret < 0 ) {
 return ret ;
 }
 if ( ret < cpu -> kvm_msr_buf -> nmsrs ) {
 struct kvm_msr_entry * e = & cpu -> kvm_msr_buf -> entries [ ret ] ;
 error_report ( "error: failed to get MSR 0x%" PRIx32 , ( uint32_t ) e -> index ) ;
 }
 assert ( ret == cpu -> kvm_msr_buf -> nmsrs ) ;
 if ( cpu -> fill_mtrr_mask ) {
 QEMU_BUILD_BUG_ON ( TARGET_PHYS_ADDR_SPACE_BITS > 52 ) ;
 assert ( cpu -> phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS ) ;
 mtrr_top_bits = MAKE_64BIT_MASK ( cpu -> phys_bits , 52 - cpu -> phys_bits ) ;
 }
 else {
 mtrr_top_bits = 0 ;
 }
 for ( i = 0 ;
 i < ret ;
 i ++ ) {
 uint32_t index = msrs [ i ] . index ;
 switch ( index ) {
 case MSR_IA32_SYSENTER_CS : env -> sysenter_cs = msrs [ i ] . data ;
 break ;
 case MSR_IA32_SYSENTER_ESP : env -> sysenter_esp = msrs [ i ] . data ;
 break ;
 case MSR_IA32_SYSENTER_EIP : env -> sysenter_eip = msrs [ i ] . data ;
 break ;
 case MSR_PAT : env -> pat = msrs [ i ] . data ;
 break ;
 case MSR_STAR : env -> star = msrs [ i ] . data ;
 break ;
 # ifdef TARGET_X86_64 case MSR_CSTAR : env -> cstar = msrs [ i ] . data ;
 break ;
 case MSR_KERNELGSBASE : env -> kernelgsbase = msrs [ i ] . data ;
 break ;
 case MSR_FMASK : env -> fmask = msrs [ i ] . data ;
 break ;
 case MSR_LSTAR : env -> lstar = msrs [ i ] . data ;
 break ;
 # endif case MSR_IA32_TSC : env -> tsc = msrs [ i ] . data ;
 break ;
 case MSR_TSC_AUX : env -> tsc_aux = msrs [ i ] . data ;
 break ;
 case MSR_TSC_ADJUST : env -> tsc_adjust = msrs [ i ] . data ;
 break ;
 case MSR_IA32_TSCDEADLINE : env -> tsc_deadline = msrs [ i ] . data ;
 break ;
 case MSR_VM_HSAVE_PA : env -> vm_hsave = msrs [ i ] . data ;
 break ;
 case MSR_KVM_SYSTEM_TIME : env -> system_time_msr = msrs [ i ] . data ;
 break ;
 case MSR_KVM_WALL_CLOCK : env -> wall_clock_msr = msrs [ i ] . data ;
 break ;
 case MSR_MCG_STATUS : env -> mcg_status = msrs [ i ] . data ;
 break ;
 case MSR_MCG_CTL : env -> mcg_ctl = msrs [ i ] . data ;
 break ;
 case MSR_MCG_EXT_CTL : env -> mcg_ext_ctl = msrs [ i ] . data ;
 break ;
 case MSR_IA32_MISC_ENABLE : env -> msr_ia32_misc_enable = msrs [ i ] . data ;
 break ;
 case MSR_IA32_SMBASE : env -> smbase = msrs [ i ] . data ;
 break ;
 case MSR_SMI_COUNT : env -> msr_smi_count = msrs [ i ] . data ;
 break ;
 case MSR_IA32_FEATURE_CONTROL : env -> msr_ia32_feature_control = msrs [ i ] . data ;
 break ;
 case MSR_IA32_BNDCFGS : env -> msr_bndcfgs = msrs [ i ] . data ;
 break ;
 case MSR_IA32_XSS : env -> xss = msrs [ i ] . data ;
 break ;
 default : if ( msrs [ i ] . index >= MSR_MC0_CTL && msrs [ i ] . index < MSR_MC0_CTL + ( env -> mcg_cap & 0xff ) * 4 ) {
 env -> mce_banks [ msrs [ i ] . index - MSR_MC0_CTL ] = msrs [ i ] . data ;
 }
 break ;
 case MSR_KVM_ASYNC_PF_EN : env -> async_pf_en_msr = msrs [ i ] . data ;
 break ;
 case MSR_KVM_PV_EOI_EN : env -> pv_eoi_en_msr = msrs [ i ] . data ;
 break ;
 case MSR_KVM_STEAL_TIME : env -> steal_time_msr = msrs [ i ] . data ;
 break ;
 case MSR_CORE_PERF_FIXED_CTR_CTRL : env -> msr_fixed_ctr_ctrl = msrs [ i ] . data ;
 break ;
 case MSR_CORE_PERF_GLOBAL_CTRL : env -> msr_global_ctrl = msrs [ i ] . data ;
 break ;
 case MSR_CORE_PERF_GLOBAL_STATUS : env -> msr_global_status = msrs [ i ] . data ;
 break ;
 case MSR_CORE_PERF_GLOBAL_OVF_CTRL : env -> msr_global_ovf_ctrl = msrs [ i ] . data ;
 break ;
 case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1 : env -> msr_fixed_counters [ index - MSR_CORE_PERF_FIXED_CTR0 ] = msrs [ i ] . data ;
 break ;
 case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1 : env -> msr_gp_counters [ index - MSR_P6_PERFCTR0 ] = msrs [ i ] . data ;
 break ;
 case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1 : env -> msr_gp_evtsel [ index - MSR_P6_EVNTSEL0 ] = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_HYPERCALL : env -> msr_hv_hypercall = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_GUEST_OS_ID : env -> msr_hv_guest_os_id = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_APIC_ASSIST_PAGE : env -> msr_hv_vapic = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_REFERENCE_TSC : env -> msr_hv_tsc = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4 : env -> msr_hv_crash_params [ index - HV_X64_MSR_CRASH_P0 ] = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_VP_RUNTIME : env -> msr_hv_runtime = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_SCONTROL : env -> msr_hv_synic_control = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_SIEFP : env -> msr_hv_synic_evt_page = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_SIMP : env -> msr_hv_synic_msg_page = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15 : env -> msr_hv_synic_sint [ index - HV_X64_MSR_SINT0 ] = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_STIMER0_CONFIG : case HV_X64_MSR_STIMER1_CONFIG : case HV_X64_MSR_STIMER2_CONFIG : case HV_X64_MSR_STIMER3_CONFIG : env -> msr_hv_stimer_config [ ( index - HV_X64_MSR_STIMER0_CONFIG ) / 2 ] = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_STIMER0_COUNT : case HV_X64_MSR_STIMER1_COUNT : case HV_X64_MSR_STIMER2_COUNT : case HV_X64_MSR_STIMER3_COUNT : env -> msr_hv_stimer_count [ ( index - HV_X64_MSR_STIMER0_COUNT ) / 2 ] = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_REENLIGHTENMENT_CONTROL : env -> msr_hv_reenlightenment_control = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_TSC_EMULATION_CONTROL : env -> msr_hv_tsc_emulation_control = msrs [ i ] . data ;
 break ;
 case HV_X64_MSR_TSC_EMULATION_STATUS : env -> msr_hv_tsc_emulation_status = msrs [ i ] . data ;
 break ;
 case MSR_MTRRdefType : env -> mtrr_deftype = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix64K_00000 : env -> mtrr_fixed [ 0 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix16K_80000 : env -> mtrr_fixed [ 1 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix16K_A0000 : env -> mtrr_fixed [ 2 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_C0000 : env -> mtrr_fixed [ 3 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_C8000 : env -> mtrr_fixed [ 4 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_D0000 : env -> mtrr_fixed [ 5 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_D8000 : env -> mtrr_fixed [ 6 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_E0000 : env -> mtrr_fixed [ 7 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_E8000 : env -> mtrr_fixed [ 8 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_F0000 : env -> mtrr_fixed [ 9 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRfix4K_F8000 : env -> mtrr_fixed [ 10 ] = msrs [ i ] . data ;
 break ;
 case MSR_MTRRphysBase ( 0 ) ... MSR_MTRRphysMask ( MSR_MTRRcap_VCNT - 1 ) : if ( index & 1 ) {
 env -> mtrr_var [ MSR_MTRRphysIndex ( index ) ] . mask = msrs [ i ] . data | mtrr_top_bits ;
 }
 else {
 env -> mtrr_var [ MSR_MTRRphysIndex ( index ) ] . base = msrs [ i ] . data ;
 }
 break ;
 case MSR_IA32_SPEC_CTRL : env -> spec_ctrl = msrs [ i ] . data ;
 break ;
 case MSR_IA32_RTIT_CTL : env -> msr_rtit_ctrl = msrs [ i ] . data ;
 break ;
 case MSR_IA32_RTIT_STATUS : env -> msr_rtit_status = msrs [ i ] . data ;
 break ;
 case MSR_IA32_RTIT_OUTPUT_BASE : env -> msr_rtit_output_base = msrs [ i ] . data ;
 break ;
 case MSR_IA32_RTIT_OUTPUT_MASK : env -> msr_rtit_output_mask = msrs [ i ] . data ;
 break ;
 case MSR_IA32_RTIT_CR3_MATCH : env -> msr_rtit_cr3_match = msrs [ i ] . data ;
 break ;
 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B : env -> msr_rtit_addrs [ index - MSR_IA32_RTIT_ADDR0_A ] = msrs [ i ] . data ;
 break ;
 }
 }
 return 0 ;
 }


static always_inline int _pte_check (mmu_ctx_t *ctx, int is_64b, target_ulong pte0, target_ulong pte1, int h, int rw, int type) { target_ulong ptem, mmask; int access, ret, pteh, ptev, pp; access = 0; ret = -1; /* Check validity and table match */ #if defined(TARGET_PPC64) if (is_64b) { ptev = pte64_is_valid(pte0); pteh = (pte0 >> 1) & 1; } else #endif { ptev = pte_is_valid(pte0); pteh = (pte0 >> 6) & 1; } if (ptev && h == pteh) { /* Check vsid & api */ #if defined(TARGET_PPC64) if (is_64b) { ptem = pte0 & PTE64_PTEM_MASK; mmask = PTE64_CHECK_MASK; pp = (pte1 & 0x00000003) | ((pte1 >> 61) & 0x00000004); ctx->nx |= (pte1 >> 2) & 1; /* No execute bit */ ctx->nx |= (pte1 >> 3) & 1; /* Guarded bit */ } else #endif { ptem = pte0 & PTE_PTEM_MASK; mmask = PTE_CHECK_MASK; pp = pte1 & 0x00000003; } if (ptem == ctx->ptem) { if (ctx->raddr != (target_ulong)-1) { /* all matches should have equal RPN, WIMG & PP */ if ((ctx->raddr & mmask) != (pte1 & mmask)) { if (loglevel != 0) fprintf(logfile, "Bad RPN/WIMG/PP\n"); return -3; } } /* Compute access rights */ access = pp_check(ctx->key, pp, ctx->nx); /* Keep the matching PTE informations */ ctx->raddr = pte1; ctx->prot = access; ret = check_prot(ctx->prot, rw, type); if (ret == 0) { /* Access granted */ #if defined (DEBUG_MMU) if (loglevel != 0) fprintf(logfile, "PTE access granted !\n"); #endif } else { /* Access right violation */ #if defined (DEBUG_MMU) if (loglevel != 0) fprintf(logfile, "PTE access rejected\n"); #endif } } } return ret; }


static int nut_read_header(AVFormatContext * avf, AVFormatParameters * ap) { NUTContext * priv = avf->priv_data; ByteIOContext * bc = &avf->pb; nut_demuxer_opts_t dopts = { .input = { .priv = bc, .seek = av_seek, .read = av_read, .eof = NULL, .file_pos = 0, }, .alloc = { av_malloc, av_realloc, av_free }, .read_index = 1, .cache_syncpoints = 1, }; nut_context_t * nut = priv->nut = nut_demuxer_init(&dopts); nut_stream_header_t * s; int ret, i; if ((ret = nut_read_headers(nut, &s, NULL))) { if (ret < 0) av_log(avf, AV_LOG_ERROR, " NUT error: %s\n", nut_error(-ret)); nut_demuxer_uninit(nut); return -1; } priv->s = s; for (i = 0; s[i].type != -1 && i < 2; i++) { AVStream * st = av_new_stream(avf, i); int j; for (j = 0; j < s[i].fourcc_len && j < 8; j++) st->codec->codec_tag |= s[i].fourcc[j]<<(j*8); st->codec->has_b_frames = s[i].decode_delay; st->codec->extradata_size = s[i].codec_specific_len; if (st->codec->extradata_size) { st->codec->extradata = av_mallocz(st->codec->extradata_size); memcpy(st->codec->extradata, s[i].codec_specific, st->codec->extradata_size); } av_set_pts_info(avf->streams[i], 60, s[i].time_base.nom, s[i].time_base.den); st->start_time = 0; st->duration = s[i].max_pts; st->codec->codec_id = codec_get_id(nut_tags, st->codec->codec_tag); switch(s[i].type) { case NUT_AUDIO_CLASS: st->codec->codec_type = CODEC_TYPE_AUDIO; if (st->codec->codec_id == CODEC_ID_NONE) st->codec->codec_id = codec_get_wav_id(st->codec->codec_tag); st->codec->channels = s[i].channel_count; st->codec->sample_rate = s[i].samplerate_nom / s[i].samplerate_denom; break; case NUT_VIDEO_CLASS: st->codec->codec_type = CODEC_TYPE_VIDEO; if (st->codec->codec_id == CODEC_ID_NONE) st->codec->codec_id = codec_get_bmp_id(st->codec->codec_tag); st->codec->width = s[i].width; st->codec->height = s[i].height; st->codec->sample_aspect_ratio.num = s[i].sample_width; st->codec->sample_aspect_ratio.den = s[i].sample_height; break; } if (st->codec->codec_id == CODEC_ID_NONE) av_log(avf, AV_LOG_ERROR, "Unknown codec?!\n"); } return 0; }