static int target_pread(int fd, abi_ulong ptr, abi_ulong len, abi_ulong offset) { void *buf; int ret; buf = lock_user(VERIFY_WRITE, ptr, len, 0); ret = pread(fd, buf, len, offset); unlock_user(buf, ptr, len); return ret;


static void parseServerLog(HttpRoute *route, cchar *key, MprJson *prop)
{
    MprTicks    timestamp;
    cchar       *location;
    ssize       size;
    int         level, anew, backup;

    if (mprGetCmdlineLogging()) {
        mprLog("warn http config", 4, "Already logging. Ignoring log configuration");
        return;
    }
    location = mprReadJson(prop, "location");
    level = (int) stoi(mprReadJson(prop, "level"));
    backup = (int) stoi(mprReadJson(prop, "backup"));
    anew = smatch(mprReadJson(prop, "anew"), "true");
    size = (ssize) httpGetNumber(mprReadJson(prop, "size"));
    timestamp = httpGetNumber(mprReadJson(prop, "timestamp"));

    if (size < HTTP_TRACE_MIN_LOG_SIZE) {
        size = HTTP_TRACE_MIN_LOG_SIZE;
    }
    if (location == 0) {
        httpParseError(route, "Missing location");
        return;
    }
    if (!smatch(location, "stdout") && !smatch(location, "stderr")) {
        location = httpMakePath(route, 0, location);
    }
    mprSetLogBackup(size, backup, anew ? MPR_LOG_ANEW : 0);

    if (mprStartLogging(location, 0) < 0) {
        httpParseError(route, "Cannot write to error log: %s", location);
        return;
    }
    mprSetLogLevel(level);
    mprLogConfig();
    if (timestamp) {
        httpSetTimestamp(timestamp);
    }
}


static ssize_t nports_show(struct device *dev, struct device_attribute *attr,
			   char *out)
{
	char *s = out;

	/*
	 * Half the ports are for SPEED_HIGH and half for SPEED_SUPER, thus the * 2.
	 */
	out += sprintf(out, "%d\n", VHCI_PORTS * vhci_num_controllers);
	return out - s;
}


static void parseTrace(HttpRoute *route, cchar *key, MprJson *prop)
{
    MprJson     *levels, *child;
    cchar       *location;
    ssize       size, maxContent;
    cchar       *format, *formatter;
    char        level;
    int         anew, backup, ji;

    if (route->trace && route->trace->flags & MPR_LOG_CMDLINE) {
        mprLog("info http config", 4, "Already tracing. Ignoring trace configuration");
        return;
    }
    size = (ssize) httpGetNumber(mprGetJson(prop, "size"));
    format = mprGetJson(prop, "format");
    formatter = mprGetJson(prop, "formatter");
    location = mprGetJson(prop, "location");
    level = (char) stoi(mprGetJson(prop, "level"));
    backup = (int) stoi(mprGetJson(prop, "backup"));
    anew = smatch(mprGetJson(prop, "anew"), "true");
    maxContent = (ssize) httpGetNumber(mprGetJson(prop, "content"));

    if (level < 0) {
        level = 0;
    } else if (level > 5) {
        level = 5;
    }
    if (size < (10 * 1000)) {
        httpParseError(route, "Trace log size is too small. Must be larger than 10K");
        return;
    }
    if (location == 0) {
        httpParseError(route, "Missing trace filename");
        return;
    }
    if (!smatch(location, "stdout") && !smatch(location, "stderr")) {
        location = httpMakePath(route, 0, location);
    }
    if ((levels = mprGetJsonObj(prop, "levels")) != 0) {
        for (ITERATE_CONFIG(route, prop, child, ji)) {
            httpSetTraceEventLevel(route->trace, child->name, (int) stoi(child->value));
        }
    }
    route->trace = httpCreateTrace(route->trace);
    httpSetTraceFormatterName(route->trace, formatter);
    httpSetTraceLogFile(route->trace, location, size, backup, format, anew ? MPR_LOG_ANEW : 0);
    httpSetTraceFormat(route->trace, format);
    httpSetTraceContentSize(route->trace, maxContent);
    httpSetTraceLevel(level);
}


static void stub_recv_cmd_submit(struct stub_device *sdev,
				 struct usbip_header *pdu)
{
	int ret;
	struct stub_priv *priv;
	struct usbip_device *ud = &sdev->ud;
	struct usb_device *udev = sdev->udev;
	int pipe = get_pipe(sdev, pdu->base.ep, pdu->base.direction);

	priv = stub_priv_alloc(sdev, pdu);
	if (!priv)
		return;

	/* setup a urb */
	if (usb_pipeisoc(pipe))
		priv->urb = usb_alloc_urb(pdu->u.cmd_submit.number_of_packets,
					  GFP_KERNEL);
	else
		priv->urb = usb_alloc_urb(0, GFP_KERNEL);

	if (!priv->urb) {
		usbip_event_add(ud, SDEV_EVENT_ERROR_MALLOC);
		return;
	}

	/* allocate urb transfer buffer, if needed */
	if (pdu->u.cmd_submit.transfer_buffer_length > 0) {
		priv->urb->transfer_buffer =
			kzalloc(pdu->u.cmd_submit.transfer_buffer_length,
				GFP_KERNEL);
		if (!priv->urb->transfer_buffer) {
			usbip_event_add(ud, SDEV_EVENT_ERROR_MALLOC);
			return;
		}
	}

	/* copy urb setup packet */
	priv->urb->setup_packet = kmemdup(&pdu->u.cmd_submit.setup, 8,
					  GFP_KERNEL);
	if (!priv->urb->setup_packet) {
		dev_err(&udev->dev, "allocate setup_packet\n");
		usbip_event_add(ud, SDEV_EVENT_ERROR_MALLOC);
		return;
	}

	/* set other members from the base header of pdu */
	priv->urb->context                = (void *) priv;
	priv->urb->dev                    = udev;
	priv->urb->pipe                   = pipe;
	priv->urb->complete               = stub_complete;

	usbip_pack_pdu(pdu, priv->urb, USBIP_CMD_SUBMIT, 0);

	if (usbip_recv_xbuff(ud, priv->urb) < 0)
		return;

	if (usbip_recv_iso(ud, priv->urb) < 0)
		return;

	/* no need to submit an intercepted request, but harmless? */
	tweak_special_requests(priv->urb);

	masking_bogus_flags(priv->urb);
	/* urb is now ready to submit */
	ret = usb_submit_urb(priv->urb, GFP_KERNEL);

	if (ret == 0)
		usbip_dbg_stub_rx("submit urb ok, seqnum %u\n",
				  pdu->base.seqnum);
	else {
		dev_err(&udev->dev, "submit_urb error, %d\n", ret);
		usbip_dump_header(pdu);
		usbip_dump_urb(priv->urb);

		/*
		 * Pessimistic.
		 * This connection will be discarded.
		 */
		usbip_event_add(ud, SDEV_EVENT_ERROR_SUBMIT);
	}

	usbip_dbg_stub_rx("Leave\n");
}


static void setConfigDefaults(HttpRoute *route)
{
    route->mode = mprReadJson(route->config, "app.mode");
    if (smatch(route->mode, "debug")) {
        httpSetRouteShowErrors(route, 1);
        route->keepSource = 1;
    }
}


static int adx_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame_ptr , AVPacket * avpkt ) {
 AVFrame * frame = data ;
 int buf_size = avpkt -> size ;
 ADXContext * c = avctx -> priv_data ;
 int16_t * * samples ;
 int samples_offset ;
 const uint8_t * buf = avpkt -> data ;
 int num_blocks , ch , ret ;
 if ( c -> eof ) {
 * got_frame_ptr = 0 ;
 return buf_size ;
 }
 if ( ! c -> header_parsed && buf_size >= 2 && AV_RB16 ( buf ) == 0x8000 ) {
 int header_size ;
 if ( ( ret = avpriv_adx_decode_header ( avctx , buf , buf_size , & header_size , c -> coeff ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "error parsing ADX header\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 c -> channels = avctx -> channels ;
 c -> header_parsed = 1 ;
 if ( buf_size < header_size ) return AVERROR_INVALIDDATA ;
 buf += header_size ;
 buf_size -= header_size ;
 }
 if ( ! c -> header_parsed ) return AVERROR_INVALIDDATA ;
 num_blocks = buf_size / ( BLOCK_SIZE * c -> channels ) ;
 if ( ! num_blocks || buf_size % ( BLOCK_SIZE * avctx -> channels ) ) {
 if ( buf_size >= 4 && ( AV_RB16 ( buf ) & 0x8000 ) ) {
 c -> eof = 1 ;
 * got_frame_ptr = 0 ;
 return avpkt -> size ;
 }
 return AVERROR_INVALIDDATA ;
 }
 frame -> nb_samples = num_blocks * BLOCK_SAMPLES ;
 if ( ( ret = ff_get_buffer ( avctx , frame ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return ret ;
 }
 samples = ( int16_t * * ) frame -> extended_data ;
 samples_offset = 0 ;
 while ( num_blocks -- ) {
 for ( ch = 0 ;
 ch < c -> channels ;
 ch ++ ) {
 if ( adx_decode ( c , samples [ ch ] , samples_offset , buf , ch ) ) {
 c -> eof = 1 ;
 buf = avpkt -> data + avpkt -> size ;
 break ;
 }
 buf_size -= BLOCK_SIZE ;
 buf += BLOCK_SIZE ;
 }
 samples_offset += BLOCK_SAMPLES ;
 }
 * got_frame_ptr = 1 ;
 return buf - avpkt -> data ;
 }


static int dissect_diameter_3gpp2_exp_res ( tvbuff_t * tvb , packet_info * pinfo _U_ , proto_tree * tree , void * data ) {
 proto_item * pi ;
 diam_sub_dis_t * diam_sub_dis ;
 if ( data == NULL ) return 0 ;
 diam_sub_dis = ( diam_sub_dis_t * ) data ;
 if ( tree ) {
 pi = proto_tree_add_item ( tree , hf_diameter_3gpp2_exp_res , tvb , 0 , 4 , ENC_BIG_ENDIAN ) ;
 diam_sub_dis -> avp_str = ( char * ) wmem_alloc ( wmem_packet_scope ( ) , ITEM_LABEL_LENGTH + 1 ) ;
 proto_item_fill_label ( PITEM_FINFO ( pi ) , diam_sub_dis -> avp_str ) ;
 diam_sub_dis -> avp_str = strstr ( diam_sub_dis -> avp_str , ": " ) + 2 ;
 }
 return 4 ;
 }


static void arm_gic_common_realize(DeviceState *dev, Error **errp) { GICState *s = ARM_GIC_COMMON(dev); int num_irq = s->num_irq; if (s->num_cpu > GIC_NCPU) { error_setg(errp, "requested %u CPUs exceeds GIC maximum %d", s->num_cpu, GIC_NCPU); s->num_irq += GIC_BASE_IRQ; if (s->num_irq > GIC_MAXIRQ) { error_setg(errp, "requested %u interrupt lines exceeds GIC maximum %d", num_irq, GIC_MAXIRQ); /* ITLinesNumber is represented as (N / 32) - 1 (see * gic_dist_readb) so this is an implementation imposed * restriction, not an architectural one: */ if (s->num_irq < 32 || (s->num_irq % 32)) { error_setg(errp, "%d interrupt lines unsupported: not divisible by 32", num_irq);


static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
			 u32 __user *uaddr2, int nr_wake, int nr_requeue,
			 u32 *cmpval, int requeue_pi)
{
	union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
	int drop_count = 0, task_count = 0, ret;
	struct futex_pi_state *pi_state = NULL;
	struct futex_hash_bucket *hb1, *hb2;
	struct futex_q *this, *next;
	DEFINE_WAKE_Q(wake_q);

	/*
	 * When PI not supported: return -ENOSYS if requeue_pi is true,
	 * consequently the compiler knows requeue_pi is always false past
	 * this point which will optimize away all the conditional code
	 * further down.
	 */
	if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
		return -ENOSYS;

	if (requeue_pi) {
		/*
		 * Requeue PI only works on two distinct uaddrs. This
		 * check is only valid for private futexes. See below.
		 */
		if (uaddr1 == uaddr2)
			return -EINVAL;

		/*
		 * requeue_pi requires a pi_state, try to allocate it now
		 * without any locks in case it fails.
		 */
		if (refill_pi_state_cache())
			return -ENOMEM;
		/*
		 * requeue_pi must wake as many tasks as it can, up to nr_wake
		 * + nr_requeue, since it acquires the rt_mutex prior to
		 * returning to userspace, so as to not leave the rt_mutex with
		 * waiters and no owner.  However, second and third wake-ups
		 * cannot be predicted as they involve race conditions with the
		 * first wake and a fault while looking up the pi_state.  Both
		 * pthread_cond_signal() and pthread_cond_broadcast() should
		 * use nr_wake=1.
		 */
		if (nr_wake != 1)
			return -EINVAL;
	}

retry:
	ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
	if (unlikely(ret != 0))
		goto out;
	ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
			    requeue_pi ? VERIFY_WRITE : VERIFY_READ);
	if (unlikely(ret != 0))
		goto out_put_key1;

	/*
	 * The check above which compares uaddrs is not sufficient for
	 * shared futexes. We need to compare the keys:
	 */
	if (requeue_pi && match_futex(&key1, &key2)) {
		ret = -EINVAL;
		goto out_put_keys;
	}

	hb1 = hash_futex(&key1);
	hb2 = hash_futex(&key2);

retry_private:
	hb_waiters_inc(hb2);
	double_lock_hb(hb1, hb2);

	if (likely(cmpval != NULL)) {
		u32 curval;

		ret = get_futex_value_locked(&curval, uaddr1);

		if (unlikely(ret)) {
			double_unlock_hb(hb1, hb2);
			hb_waiters_dec(hb2);

			ret = get_user(curval, uaddr1);
			if (ret)
				goto out_put_keys;

			if (!(flags & FLAGS_SHARED))
				goto retry_private;

			put_futex_key(&key2);
			put_futex_key(&key1);
			goto retry;
		}
		if (curval != *cmpval) {
			ret = -EAGAIN;
			goto out_unlock;
		}
	}

	if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
		/*
		 * Attempt to acquire uaddr2 and wake the top waiter. If we
		 * intend to requeue waiters, force setting the FUTEX_WAITERS
		 * bit.  We force this here where we are able to easily handle
		 * faults rather in the requeue loop below.
		 */
		ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
						 &key2, &pi_state, nr_requeue);

		/*
		 * At this point the top_waiter has either taken uaddr2 or is
		 * waiting on it.  If the former, then the pi_state will not
		 * exist yet, look it up one more time to ensure we have a
		 * reference to it. If the lock was taken, ret contains the
		 * vpid of the top waiter task.
		 * If the lock was not taken, we have pi_state and an initial
		 * refcount on it. In case of an error we have nothing.
		 */
		if (ret > 0) {
			WARN_ON(pi_state);
			drop_count++;
			task_count++;
			/*
			 * If we acquired the lock, then the user space value
			 * of uaddr2 should be vpid. It cannot be changed by
			 * the top waiter as it is blocked on hb2 lock if it
			 * tries to do so. If something fiddled with it behind
			 * our back the pi state lookup might unearth it. So
			 * we rather use the known value than rereading and
			 * handing potential crap to lookup_pi_state.
			 *
			 * If that call succeeds then we have pi_state and an
			 * initial refcount on it.
			 */
			ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state);
		}

		switch (ret) {
		case 0:
			/* We hold a reference on the pi state. */
			break;

			/* If the above failed, then pi_state is NULL */
		case -EFAULT:
			double_unlock_hb(hb1, hb2);
			hb_waiters_dec(hb2);
			put_futex_key(&key2);
			put_futex_key(&key1);
			ret = fault_in_user_writeable(uaddr2);
			if (!ret)
				goto retry;
			goto out;
		case -EAGAIN:
			/*
			 * Two reasons for this:
			 * - Owner is exiting and we just wait for the
			 *   exit to complete.
			 * - The user space value changed.
			 */
			double_unlock_hb(hb1, hb2);
			hb_waiters_dec(hb2);
			put_futex_key(&key2);
			put_futex_key(&key1);
			cond_resched();
			goto retry;
		default:
			goto out_unlock;
		}
	}

	plist_for_each_entry_safe(this, next, &hb1->chain, list) {
		if (task_count - nr_wake >= nr_requeue)
			break;

		if (!match_futex(&this->key, &key1))
			continue;

		/*
		 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
		 * be paired with each other and no other futex ops.
		 *
		 * We should never be requeueing a futex_q with a pi_state,
		 * which is awaiting a futex_unlock_pi().
		 */
		if ((requeue_pi && !this->rt_waiter) ||
		    (!requeue_pi && this->rt_waiter) ||
		    this->pi_state) {
			ret = -EINVAL;
			break;
		}

		/*
		 * Wake nr_wake waiters.  For requeue_pi, if we acquired the
		 * lock, we already woke the top_waiter.  If not, it will be
		 * woken by futex_unlock_pi().
		 */
		if (++task_count <= nr_wake && !requeue_pi) {
			mark_wake_futex(&wake_q, this);
			continue;
		}

		/* Ensure we requeue to the expected futex for requeue_pi. */
		if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
			ret = -EINVAL;
			break;
		}

		/*
		 * Requeue nr_requeue waiters and possibly one more in the case
		 * of requeue_pi if we couldn't acquire the lock atomically.
		 */
		if (requeue_pi) {
			/*
			 * Prepare the waiter to take the rt_mutex. Take a
			 * refcount on the pi_state and store the pointer in
			 * the futex_q object of the waiter.
			 */
			get_pi_state(pi_state);
			this->pi_state = pi_state;
			ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
							this->rt_waiter,
							this->task);
			if (ret == 1) {
				/*
				 * We got the lock. We do neither drop the
				 * refcount on pi_state nor clear
				 * this->pi_state because the waiter needs the
				 * pi_state for cleaning up the user space
				 * value. It will drop the refcount after
				 * doing so.
				 */
				requeue_pi_wake_futex(this, &key2, hb2);
				drop_count++;
				continue;
			} else if (ret) {
				/*
				 * rt_mutex_start_proxy_lock() detected a
				 * potential deadlock when we tried to queue
				 * that waiter. Drop the pi_state reference
				 * which we took above and remove the pointer
				 * to the state from the waiters futex_q
				 * object.
				 */
				this->pi_state = NULL;
				put_pi_state(pi_state);
				/*
				 * We stop queueing more waiters and let user
				 * space deal with the mess.
				 */
				break;
			}
		}
		requeue_futex(this, hb1, hb2, &key2);
		drop_count++;
	}

	/*
	 * We took an extra initial reference to the pi_state either
	 * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
	 * need to drop it here again.
	 */
	put_pi_state(pi_state);

out_unlock:
	double_unlock_hb(hb1, hb2);
	wake_up_q(&wake_q);
	hb_waiters_dec(hb2);

	/*
	 * drop_futex_key_refs() must be called outside the spinlocks. During
	 * the requeue we moved futex_q's from the hash bucket at key1 to the
	 * one at key2 and updated their key pointer.  We no longer need to
	 * hold the references to key1.
	 */
	while (--drop_count >= 0)
		drop_futex_key_refs(&key1);

out_put_keys:
	put_futex_key(&key2);
out_put_key1:
	put_futex_key(&key1);
out:
	return ret ? ret : task_count;
}


PUBLIC int mprWriteJsonObj(MprJson *obj, cchar *key, MprJson *value)
{
    if (setProperty(obj, sclone(key), value) == 0) {
        return MPR_ERR_CANT_WRITE;
    }
    return 0;
}


int ff_dct_quantize_c ( MpegEncContext * s , int16_t * block , int n , int qscale , int * overflow ) {
 int i , j , level , last_non_zero , q , start_i ;
 const int * qmat ;
 const uint8_t * scantable = s -> intra_scantable . scantable ;
 int bias ;
 int max = 0 ;
 unsigned int threshold1 , threshold2 ;
 s -> dsp . fdct ( block ) ;
 if ( s -> dct_error_sum ) s -> denoise_dct ( s , block ) ;
 if ( s -> mb_intra ) {
 if ( ! s -> h263_aic ) {
 if ( n < 4 ) q = s -> y_dc_scale ;
 else q = s -> c_dc_scale ;
 q = q << 3 ;
 }
 else q = 1 << 3 ;
 block [ 0 ] = ( block [ 0 ] + ( q >> 1 ) ) / q ;
 start_i = 1 ;
 last_non_zero = 0 ;
 qmat = s -> q_intra_matrix [ qscale ] ;
 bias = s -> intra_quant_bias << ( QMAT_SHIFT - QUANT_BIAS_SHIFT ) ;
 }
 else {
 start_i = 0 ;
 last_non_zero = - 1 ;
 qmat = s -> q_inter_matrix [ qscale ] ;
 bias = s -> inter_quant_bias << ( QMAT_SHIFT - QUANT_BIAS_SHIFT ) ;
 }
 threshold1 = ( 1 << QMAT_SHIFT ) - bias - 1 ;
 threshold2 = ( threshold1 << 1 ) ;
 for ( i = 63 ;
 i >= start_i ;
 i -- ) {
 j = scantable [ i ] ;
 level = block [ j ] * qmat [ j ] ;
 if ( ( ( unsigned ) ( level + threshold1 ) ) > threshold2 ) {
 last_non_zero = i ;
 break ;
 }
 else {
 block [ j ] = 0 ;
 }
 }
 for ( i = start_i ;
 i <= last_non_zero ;
 i ++ ) {
 j = scantable [ i ] ;
 level = block [ j ] * qmat [ j ] ;
 if ( ( ( unsigned ) ( level + threshold1 ) ) > threshold2 ) {
 if ( level > 0 ) {
 level = ( bias + level ) >> QMAT_SHIFT ;
 block [ j ] = level ;
 }
 else {
 level = ( bias - level ) >> QMAT_SHIFT ;
 block [ j ] = - level ;
 }
 max |= level ;
 }
 else {
 block [ j ] = 0 ;
 }
 }
 * overflow = s -> max_qcoeff < max ;
 if ( s -> dsp . idct_permutation_type != FF_NO_IDCT_PERM ) ff_block_permute ( block , s -> dsp . idct_permutation , scantable , last_non_zero ) ;
 return last_non_zero ;
 }


static int archive_read_format_cpio_cleanup ( struct archive_read * a ) {
 struct cpio * cpio ;
 cpio = ( struct cpio * ) ( a -> format -> data ) ;
 while ( cpio -> links_head != NULL ) {
 struct links_entry * lp = cpio -> links_head -> next ;
 if ( cpio -> links_head -> name ) free ( cpio -> links_head -> name ) ;
 free ( cpio -> links_head ) ;
 cpio -> links_head = lp ;
 }
 free ( cpio ) ;
 ( a -> format -> data ) = NULL ;
 return ( ARCHIVE_OK ) ;
 }


static int vvalue_tvb_get1 ( tvbuff_t * tvb , int offset , void * val ) {
 guint8 * ui1 = ( guint8 * ) val ;
 * ui1 = tvb_get_guint8 ( tvb , offset ) ;
 return 1 ;
 }


static int do_cmd (xd3_stream *stream, const char *buf)
{
  int ret;
  if ((ret = system (buf)) != 0)
    {
      if (WIFEXITED (ret))
	{
	  stream->msg = "command exited non-zero";
	  IF_DEBUG1 (XPR(NT "command was: %s\n", buf));
	}
      else
	{
	  stream->msg = "abnormal command termination";
	}
      return ret;
    }
  return 0;
}


gcry_error_t gcry_pk_genkey ( gcry_sexp_t * r_key , gcry_sexp_t s_parms ) {
 gcry_pk_spec_t * pubkey = NULL ;
 gcry_module_t module = NULL ;
 gcry_sexp_t list = NULL ;
 gcry_sexp_t l2 = NULL ;
 gcry_sexp_t l3 = NULL ;
 char * name = NULL ;
 size_t n ;
 gcry_err_code_t rc = GPG_ERR_NO_ERROR ;
 int i , j ;
 const char * algo_name = NULL ;
 int algo ;
 const char * sec_elems = NULL , * pub_elems = NULL ;
 gcry_mpi_t skey [ 12 ] ;
 gcry_mpi_t * factors = NULL ;
 gcry_sexp_t extrainfo = NULL ;
 unsigned int nbits = 0 ;
 unsigned long use_e = 0 ;
 skey [ 0 ] = NULL ;
 * r_key = NULL ;
 REGISTER_DEFAULT_PUBKEYS ;
 list = gcry_sexp_find_token ( s_parms , "genkey" , 0 ) ;
 if ( ! list ) {
 rc = GPG_ERR_INV_OBJ ;
 goto leave ;
 }
 l2 = gcry_sexp_cadr ( list ) ;
 gcry_sexp_release ( list ) ;
 list = l2 ;
 l2 = NULL ;
 if ( ! list ) {
 rc = GPG_ERR_NO_OBJ ;
 goto leave ;
 }
 name = _gcry_sexp_nth_string ( list , 0 ) ;
 if ( ! name ) {
 rc = GPG_ERR_INV_OBJ ;
 goto leave ;
 }
 ath_mutex_lock ( & pubkeys_registered_lock ) ;
 module = gcry_pk_lookup_name ( name ) ;
 ath_mutex_unlock ( & pubkeys_registered_lock ) ;
 gcry_free ( name ) ;
 name = NULL ;
 if ( ! module ) {
 rc = GPG_ERR_PUBKEY_ALGO ;
 goto leave ;
 }
 pubkey = ( gcry_pk_spec_t * ) module -> spec ;
 algo = module -> mod_id ;
 algo_name = pubkey -> aliases ? * pubkey -> aliases : NULL ;
 if ( ! algo_name || ! * algo_name ) algo_name = pubkey -> name ;
 pub_elems = pubkey -> elements_pkey ;
 sec_elems = pubkey -> elements_skey ;
 if ( strlen ( sec_elems ) >= DIM ( skey ) ) BUG ( ) ;
 l2 = gcry_sexp_find_token ( list , "rsa-use-e" , 0 ) ;
 if ( l2 ) {
 char buf [ 50 ] ;
 const char * s ;
 s = gcry_sexp_nth_data ( l2 , 1 , & n ) ;
 if ( ! s || n >= DIM ( buf ) - 1 ) {
 rc = GPG_ERR_INV_OBJ ;
 goto leave ;
 }
 memcpy ( buf , s , n ) ;
 buf [ n ] = 0 ;
 use_e = strtoul ( buf , NULL , 0 ) ;
 gcry_sexp_release ( l2 ) ;
 l2 = NULL ;
 }
 else use_e = 65537 ;
 l2 = gcry_sexp_find_token ( list , "nbits" , 0 ) ;
 if ( l2 ) {
 char buf [ 50 ] ;
 const char * s ;
 s = gcry_sexp_nth_data ( l2 , 1 , & n ) ;
 if ( ! s || n >= DIM ( buf ) - 1 ) {
 rc = GPG_ERR_INV_OBJ ;
 goto leave ;
 }
 memcpy ( buf , s , n ) ;
 buf [ n ] = 0 ;
 nbits = ( unsigned int ) strtoul ( buf , NULL , 0 ) ;
 gcry_sexp_release ( l2 ) ;
 l2 = NULL ;
 }
 else nbits = 0 ;
 rc = pubkey_generate ( module -> mod_id , nbits , use_e , list , skey , & factors , & extrainfo ) ;
 gcry_sexp_release ( list ) ;
 list = NULL ;
 if ( rc ) goto leave ;
 {
 char * string , * p ;
 size_t nelem = 0 , nelem_cp = 0 , needed = 0 ;
 gcry_mpi_t mpis [ 30 ] ;
 int percent_s_idx = - 1 ;
 nelem = strlen ( pub_elems ) + strlen ( sec_elems ) ;
 if ( factors ) {
 for ( i = 0 ;
 factors [ i ] ;
 i ++ ) nelem ++ ;
 }
 nelem_cp = nelem ;
 needed += nelem * 10 ;
 needed += 2 * strlen ( algo_name ) + 300 + 5 ;
 if ( nelem > DIM ( mpis ) ) BUG ( ) ;
 nelem = 0 ;
 string = p = gcry_malloc ( needed ) ;
 if ( ! string ) {
 rc = gpg_err_code_from_syserror ( ) ;
 goto leave ;
 }
 p = stpcpy ( p , "(key-data" ) ;
 p = stpcpy ( p , "(public-key(" ) ;
 p = stpcpy ( p , algo_name ) ;
 for ( i = 0 ;
 pub_elems [ i ] ;
 i ++ ) {
 * p ++ = '(' ;
 * p ++ = pub_elems [ i ] ;
 p = stpcpy ( p , "%m)" ) ;
 mpis [ nelem ++ ] = skey [ i ] ;
 }
 if ( extrainfo && ( algo == GCRY_PK_ECDSA || algo == GCRY_PK_ECDH ) ) {
 percent_s_idx = nelem ;
 p = stpcpy ( p , "%S" ) ;
 }
 p = stpcpy ( p , "))" ) ;
 p = stpcpy ( p , "(private-key(" ) ;
 p = stpcpy ( p , algo_name ) ;
 for ( i = 0 ;
 sec_elems [ i ] ;
 i ++ ) {
 * p ++ = '(' ;
 * p ++ = sec_elems [ i ] ;
 p = stpcpy ( p , "%m)" ) ;
 mpis [ nelem ++ ] = skey [ i ] ;
 }
 p = stpcpy ( p , "))" ) ;
 skey [ i ] = NULL ;
 if ( extrainfo && percent_s_idx == - 1 ) {
 p = stpcpy ( p , "%S" ) ;
 }
 else if ( factors && factors [ 0 ] ) {
 p = stpcpy ( p , "(misc-key-info(pm1-factors" ) ;
 for ( i = 0 ;
 factors [ i ] ;
 i ++ ) {
 p = stpcpy ( p , "%m" ) ;
 mpis [ nelem ++ ] = factors [ i ] ;
 }
 p = stpcpy ( p , "))" ) ;
 }
 strcpy ( p , ")" ) ;
 gcry_assert ( p - string < needed ) ;
 while ( nelem < DIM ( mpis ) ) mpis [ nelem ++ ] = NULL ;
 {
 int elem_n = strlen ( pub_elems ) + strlen ( sec_elems ) ;
 void * * arg_list ;
 arg_list = gcry_calloc ( nelem_cp + 1 , sizeof * arg_list ) ;
 if ( ! arg_list ) {
 rc = gpg_err_code_from_syserror ( ) ;
 goto leave ;
 }
 for ( i = j = 0 ;
 i < elem_n ;
 i ++ ) {
 if ( i == percent_s_idx ) arg_list [ j ++ ] = & extrainfo ;
 arg_list [ j ++ ] = mpis + i ;
 }
 if ( extrainfo && percent_s_idx == - 1 ) arg_list [ j ] = & extrainfo ;
 else if ( factors && factors [ 0 ] ) {
 for ( ;
 i < nelem_cp ;
 i ++ ) arg_list [ j ++ ] = factors + i - elem_n ;
 }
 rc = gcry_sexp_build_array ( r_key , NULL , string , arg_list ) ;
 gcry_free ( arg_list ) ;
 if ( rc ) BUG ( ) ;
 gcry_assert ( DIM ( mpis ) == 30 ) ;
 }
 gcry_free ( string ) ;
 }
 leave : gcry_free ( name ) ;
 gcry_sexp_release ( extrainfo ) ;
 release_mpi_array ( skey ) ;
 if ( factors ) {
 release_mpi_array ( factors ) ;
 gcry_free ( factors ) ;
 }
 gcry_sexp_release ( l3 ) ;
 gcry_sexp_release ( l2 ) ;
 gcry_sexp_release ( list ) ;
 if ( module ) {
 ath_mutex_lock ( & pubkeys_registered_lock ) ;
 _gcry_module_release ( module ) ;
 ath_mutex_unlock ( & pubkeys_registered_lock ) ;
 }
 return gcry_error ( rc ) ;
 }


void http_hdr_adjust ( HTTPHdrImpl * , int32_t , int32_t , int32_t ) {
 ink_release_assert ( ! "http_hdr_adjust not implemented" ) ;
 }


QPDF::reconstruct_xref(QPDFExc& e)
{
    if (this->m->reconstructed_xref)
    {
        // Avoid xref reconstruction infinite loops. This is getting
        // very hard to reproduce because qpdf is throwing many fewer
        // exceptions while parsing. Most situations are warnings now.
        throw e;
    }

    this->m->reconstructed_xref = true;

    warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		 "file is damaged"));
    warn(e);
    warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		 "Attempting to reconstruct cross-reference table"));

    // Delete all references to type 1 (uncompressed) objects
    std::set<QPDFObjGen> to_delete;
    for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
	     this->m->xref_table.begin();
	 iter != this->m->xref_table.end(); ++iter)
    {
	if (((*iter).second).getType() == 1)
	{
	    to_delete.insert((*iter).first);
	}
    }
    for (std::set<QPDFObjGen>::iterator iter = to_delete.begin();
	 iter != to_delete.end(); ++iter)
    {
	this->m->xref_table.erase(*iter);
    }

    this->m->file->seek(0, SEEK_END);
    qpdf_offset_t eof = this->m->file->tell();
    this->m->file->seek(0, SEEK_SET);
    bool in_obj = false;
    qpdf_offset_t line_start = 0;
    // Don't allow very long tokens here during recovery.
    static size_t const MAX_LEN = 100;
    while (this->m->file->tell() < eof)
    {
        this->m->file->findAndSkipNextEOL();
        qpdf_offset_t next_line_start = this->m->file->tell();
        this->m->file->seek(line_start, SEEK_SET);
        QPDFTokenizer::Token t1 = readToken(this->m->file, true, MAX_LEN);
        qpdf_offset_t token_start =
            this->m->file->tell() - t1.getValue().length();
        if (token_start >= next_line_start)
        {
            // don't process yet
        }
	else if (in_obj)
	{
            if (t1 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj"))
	    {
		in_obj = false;
	    }
	}
        else
        {
            if (t1.getType() == QPDFTokenizer::tt_integer)
            {
                QPDFTokenizer::Token t2 =
                    readToken(this->m->file, true, MAX_LEN);
                QPDFTokenizer::Token t3 =
                    readToken(this->m->file, true, MAX_LEN);
                if ((t2.getType() == QPDFTokenizer::tt_integer) &&
                    (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj")))
                {
                    in_obj = true;
                    int obj = atoi(t1.getValue().c_str());
                    int gen = atoi(t2.getValue().c_str());
                    insertXrefEntry(obj, 1, token_start, gen, true);
                }
            }
            else if ((! this->m->trailer.isInitialized()) &&
                     (t1 == QPDFTokenizer::Token(
                         QPDFTokenizer::tt_word, "trailer")))
            {
                QPDFObjectHandle t =
                    readObject(this->m->file, "trailer", 0, 0, false);
                if (! t.isDictionary())
                {
                    // Oh well.  It was worth a try.
                }
                else
                {
                    setTrailer(t);
                }
            }
	}
        this->m->file->seek(next_line_start, SEEK_SET);
        line_start = next_line_start;
    }

    if (! this->m->trailer.isInitialized())
    {
	// We could check the last encountered object to see if it was
	// an xref stream.  If so, we could try to get the trailer
	// from there.  This may make it possible to recover files
	// with bad startxref pointers even when they have object
	// streams.

	throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		      "unable to find trailer "
		      "dictionary while recovering damaged file");
    }

    // We could iterate through the objects looking for streams and
    // try to find objects inside of them, but it's probably not worth
    // the trouble.  Acrobat can't recover files with any errors in an
    // xref stream, and this would be a real long shot anyway.  If we
    // wanted to do anything that involved looking at stream contents,
    // we'd also have to call initializeEncryption() here.  It's safe
    // to call it more than once.
}


test_make_inputs (xd3_stream *stream, xoff_t *ss_out, xoff_t *ts_out)
{
  usize_t ts = (mt_random (&static_mtrand) % TEST_FILE_MEAN) + TEST_FILE_MEAN / 2;
  usize_t ss = (mt_random (&static_mtrand) % TEST_FILE_MEAN) + TEST_FILE_MEAN / 2;
  uint8_t *buf = (uint8_t*) malloc (ts + ss), *sbuf = buf, *tbuf = buf + ss;
  usize_t sadd = 0, sadd_max = (usize_t)(ss * TEST_ADD_RATIO);
  FILE  *tf = NULL, *sf = NULL;
  usize_t i, j;
  int ret;

  if (buf == NULL) { return ENOMEM; }

  if ((tf = fopen (TEST_TARGET_FILE, "w")) == NULL ||
      (ss_out != NULL && (sf = fopen (TEST_SOURCE_FILE, "w")) == NULL))
    {
      stream->msg = "write failed";
      ret = get_errno ();
      goto failure;
    }

  if (ss_out != NULL)
    {
      for (i = 0; i < ss; )
	{
	  sbuf[i++] = (uint8_t) mt_random (&static_mtrand);
	}
    }

  /* Then modify the data to produce copies, everything not copied is
   * an add.  The following logic produces the TEST_ADD_RATIO.  The
   * variable SADD contains the number of adds so far, which should
   * not exceed SADD_MAX. */

  /* XPR(NT "ss = %u ts = %u\n", ss, ts); */
  for (i = 0; i < ts; )
    {
      usize_t left = ts - i;
      usize_t next = mt_exp_rand ((uint32_t) TEST_ADD_MEAN,
				  (uint32_t) TEST_ADD_MAX);
      usize_t add_left = sadd_max - sadd;
      double add_prob = (left == 0) ? 0 : (add_left / (double) left);
      int do_copy;

      next = min (left, next);
      do_copy = (next > add_left ||
		 (mt_random (&static_mtrand) / \
		  (double)USIZE_T_MAX) >= add_prob);

      if (ss_out == NULL)
	{
	  do_copy &= (i > 0);
	}
      else
	{
	  do_copy &= (ss - next) > 0;
	}

      if (do_copy)
	{
	  /* Copy */
	  size_t offset = mt_random (&static_mtrand) % ((ss_out == NULL) ?
							i :
							(ss - next));
	  /* XPR(NT "[%u] copy %u at %u ", i, next, offset); */

	  for (j = 0; j < next; j += 1)
	    {
	      char c = ((ss_out == NULL) ? tbuf : sbuf)[offset + j];
	      /* XPR(NT "%x%x", (c >> 4) & 0xf, c & 0xf); */
	      tbuf[i++] = c;
	    }
	  /* XPR(NT "\n"); */
	}
      else
	{
	  /* Add */
	  /* XPR(NT "[%u] add %u ", i, next); */
	  for (j = 0; j < next; j += 1)
	    {
	      char c = (char) mt_random (&static_mtrand);
	      /* XPR(NT "%x%x", (c >> 4) & 0xf, c & 0xf); */
	      tbuf[i++] = c;
	    }
	  /* XPR(NT "\n"); */
	  sadd += next;
	}
    }

  /* XPR(NT "sadd = %u max = %u\n", sadd, sadd_max); */

  if ((fwrite (tbuf, 1, ts, tf) != ts) ||
      (ss_out != NULL && (fwrite (sbuf, 1, ss, sf) != ss)))
    {
      stream->msg = "write failed";
      ret = get_errno ();
      goto failure;
    }

  if ((ret = fclose (tf)) || (ss_out != NULL && (ret = fclose (sf))))
    {
      stream->msg = "close failed";
      ret = get_errno ();
      goto failure;
    }

  if (ts_out) { (*ts_out) = ts; }
  if (ss_out) { (*ss_out) = ss; }

 failure:
  free (buf);
  return ret;
}


QPDF::readObjectAtOffset(bool try_recovery,
			 qpdf_offset_t offset, std::string const& description,
			 int exp_objid, int exp_generation,
			 int& objid, int& generation)
{
    if (! this->m->attempt_recovery)
    {
        try_recovery = false;
    }
    setLastObjectDescription(description, exp_objid, exp_generation);

    // Special case: if offset is 0, just return null.  Some PDF
    // writers, in particular "Mac OS X 10.7.5 Quartz PDFContext", may
    // store deleted objects in the xref table as "0000000000 00000
    // n", which is not correct, but it won't hurt anything for to
    // ignore these.
    if (offset == 0)
    {
        QTC::TC("qpdf", "QPDF bogus 0 offset", 0);
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		     this->m->last_object_description, 0,
		     "object has offset 0"));
        return QPDFObjectHandle::newNull();
    }

    this->m->file->seek(offset, SEEK_SET);

    QPDFTokenizer::Token tobjid = readToken(this->m->file);
    QPDFTokenizer::Token tgen = readToken(this->m->file);
    QPDFTokenizer::Token tobj = readToken(this->m->file);

    bool objidok = (tobjid.getType() == QPDFTokenizer::tt_integer);
    int genok = (tgen.getType() == QPDFTokenizer::tt_integer);
    int objok = (tobj == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj"));

    QTC::TC("qpdf", "QPDF check objid", objidok ? 1 : 0);
    QTC::TC("qpdf", "QPDF check generation", genok ? 1 : 0);
    QTC::TC("qpdf", "QPDF check obj", objok ? 1 : 0);

    try
    {
	if (! (objidok && genok && objok))
	{
	    QTC::TC("qpdf", "QPDF expected n n obj");
	    throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			  this->m->last_object_description, offset,
			  "expected n n obj");
	}
	objid = atoi(tobjid.getValue().c_str());
	generation = atoi(tgen.getValue().c_str());

        if (objid == 0)
        {
            QTC::TC("qpdf", "QPDF object id 0");
            throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
                          this->m->last_object_description, offset,
                          "object with ID 0");
        }

	if ((exp_objid >= 0) &&
	    (! ((objid == exp_objid) && (generation == exp_generation))))
	{
	    QTC::TC("qpdf", "QPDF err wrong objid/generation");
	    QPDFExc e(qpdf_e_damaged_pdf, this->m->file->getName(),
                      this->m->last_object_description, offset,
                      std::string("expected ") +
                      QUtil::int_to_string(exp_objid) + " " +
                      QUtil::int_to_string(exp_generation) + " obj");
            if (try_recovery)
            {
                // Will be retried below
                throw e;
            }
            else
            {
                // We can try reading the object anyway even if the ID
                // doesn't match.
                warn(e);
            }
	}
    }
    catch (QPDFExc& e)
    {
	if ((exp_objid >= 0) && try_recovery)
	{
	    // Try again after reconstructing xref table
	    reconstruct_xref(e);
	    QPDFObjGen og(exp_objid, exp_generation);
	    if (this->m->xref_table.count(og) &&
		(this->m->xref_table[og].getType() == 1))
	    {
		qpdf_offset_t new_offset = this->m->xref_table[og].getOffset();
		QPDFObjectHandle result = readObjectAtOffset(
		    false, new_offset, description,
		    exp_objid, exp_generation, objid, generation);
		QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset");
		return result;
	    }
	    else
	    {
		QTC::TC("qpdf", "QPDF object gone after xref reconstruction");
		warn(QPDFExc(
			 qpdf_e_damaged_pdf, this->m->file->getName(),
			 "", 0,
			 std::string(
			     "object " +
			     QUtil::int_to_string(exp_objid) +
			     " " +
			     QUtil::int_to_string(exp_generation) +
			     " not found in file after regenerating"
			     " cross reference table")));
		return QPDFObjectHandle::newNull();
	    }
	}
	else
	{
	    throw e;
	}
    }

    QPDFObjectHandle oh = readObject(
	this->m->file, description, objid, generation, false);

    if (! (readToken(this->m->file) ==
	   QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj")))
    {
	QTC::TC("qpdf", "QPDF err expected endobj");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
		     this->m->last_object_description,
                     this->m->file->getLastOffset(),
		     "expected endobj"));
    }

    QPDFObjGen og(objid, generation);
    if (! this->m->obj_cache.count(og))
    {
	// Store the object in the cache here so it gets cached
	// whether we first know the offset or whether we first know
	// the object ID and generation (in which we case we would get
	// here through resolve).

	// Determine the end offset of this object before and after
	// white space.  We use these numbers to validate
	// linearization hint tables.  Offsets and lengths of objects
	// may imply the end of an object to be anywhere between these
	// values.
	qpdf_offset_t end_before_space = this->m->file->tell();

	// skip over spaces
	while (true)
	{
	    char ch;
	    if (this->m->file->read(&ch, 1))
	    {
		if (! isspace(static_cast<unsigned char>(ch)))
		{
		    this->m->file->seek(-1, SEEK_CUR);
		    break;
		}
	    }
	    else
	    {
		throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
			      this->m->last_object_description, offset,
			      "EOF after endobj");
	    }
	}
	qpdf_offset_t end_after_space = this->m->file->tell();

	this->m->obj_cache[og] =
	    ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
		     end_before_space, end_after_space);
    }

    return oh;
}


QPDF::read_xref(qpdf_offset_t xref_offset)
{
    std::map<int, int> free_table;
    while (xref_offset)
    {
        char buf[7];
        memset(buf, 0, sizeof(buf));
	this->m->file->seek(xref_offset, SEEK_SET);
	this->m->file->read(buf, sizeof(buf) - 1);
        // The PDF spec says xref must be followed by a line
        // terminator, but files exist in the wild where it is
        // terminated by arbitrary whitespace.
        if ((strncmp(buf, "xref", 4) == 0) &&
            QUtil::is_space(buf[4]))
	{
            QTC::TC("qpdf", "QPDF xref space",
                    ((buf[4] == '\n') ? 0 :
                     (buf[4] == '\r') ? 1 :
                     (buf[4] == ' ') ? 2 : 9999));
            int skip = 4;
            // buf is null-terminated, and QUtil::is_space('\0') is
            // false, so this won't overrun.
            while (QUtil::is_space(buf[skip]))
            {
                ++skip;
            }
            xref_offset = read_xrefTable(xref_offset + skip);
	}
	else
	{
	    xref_offset = read_xrefStream(xref_offset);
	}
    }

    if (! this->m->trailer.isInitialized())
    {
        throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
                      "unable to find trailer while reading xref");
    }
    int size = this->m->trailer.getKey("/Size").getIntValue();
    int max_obj = 0;
    if (! this->m->xref_table.empty())
    {
	max_obj = (*(this->m->xref_table.rbegin())).first.getObj();
    }
    if (! this->m->deleted_objects.empty())
    {
	max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin()));
    }
    if (size != max_obj + 1)
    {
	QTC::TC("qpdf", "QPDF xref size mismatch");
	warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
		     std::string("reported number of objects (") +
		     QUtil::int_to_string(size) +
		     ") inconsistent with actual number of objects (" +
		     QUtil::int_to_string(max_obj + 1) + ")"));
    }

    // We no longer need the deleted_objects table, so go ahead and
    // clear it out to make sure we never depend on its being set.
    this->m->deleted_objects.clear();
}


static int kvm_s390_io_adapter_map(S390FLICState *fs, uint32_t id, uint64_t map_addr, bool do_map) { struct kvm_s390_io_adapter_req req = { .id = id, .type = do_map ? KVM_S390_IO_ADAPTER_MAP : KVM_S390_IO_ADAPTER_UNMAP, .addr = map_addr, }; struct kvm_device_attr attr = { .group = KVM_DEV_FLIC_ADAPTER_MODIFY, .addr = (uint64_t)&req, }; KVMS390FLICState *flic = KVM_S390_FLIC(fs); int r; if (!kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING)) { /* nothing to do */ return 0; } r = ioctl(flic->fd, KVM_SET_DEVICE_ATTR, &attr); return r ? -errno : 0; }


int net_init_bridge(const NetClientOptions *opts, const char *name, NetClientState *peer, Error **errp) { /* FIXME error_setg(errp, ...) on failure */ const NetdevBridgeOptions *bridge; const char *helper, *br; TAPState *s; int fd, vnet_hdr; assert(opts->kind == NET_CLIENT_OPTIONS_KIND_BRIDGE); bridge = opts->bridge; helper = bridge->has_helper ? bridge->helper : DEFAULT_BRIDGE_HELPER; br = bridge->has_br ? bridge->br : DEFAULT_BRIDGE_INTERFACE; fd = net_bridge_run_helper(helper, br); if (fd == -1) { return -1; } fcntl(fd, F_SETFL, O_NONBLOCK); vnet_hdr = tap_probe_vnet_hdr(fd); s = net_tap_fd_init(peer, "bridge", name, fd, vnet_hdr); snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s,br=%s", helper, br); return 0; }


void irc_core_deinit(void)
{
	signal_emit("chat protocol deinit", 1, chat_protocol_find("IRC"));

	cap_deinit();
	irc_expandos_deinit();
	netsplit_deinit();
	lag_deinit();
	irc_commands_deinit();
	ctcp_deinit();

	irc_queries_deinit();
	irc_channels_deinit();
	irc_irc_deinit();
	irc_servers_deinit();
	irc_chatnets_deinit();
        irc_session_deinit();

	chat_protocol_unregister("IRC");
}


int qemuMonitorJSONAddPCIHostDevice ( qemuMonitorPtr mon ATTRIBUTE_UNUSED , virDomainDevicePCIAddress * hostAddr ATTRIBUTE_UNUSED , virDomainDevicePCIAddress * guestAddr ATTRIBUTE_UNUSED ) {
 qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "pci_add not suppported in JSON mode" ) ) ;
 return - 1 ;
 }


static void sasl_start(IRC_SERVER_REC *server, const char *data, const char *from)
{
	IRC_SERVER_CONNECT_REC *conn;

	conn = server->connrec;

	switch (conn->sasl_mechanism) {
		case SASL_MECHANISM_PLAIN:
			irc_send_cmd_now(server, "AUTHENTICATE PLAIN");
			break;

		case SASL_MECHANISM_EXTERNAL:
			irc_send_cmd_now(server, "AUTHENTICATE EXTERNAL");
			break;
	}
	server->sasl_timeout = g_timeout_add(SASL_TIMEOUT, (GSourceFunc) sasl_timeout, server);
}


static void sasl_success(IRC_SERVER_REC *server, const char *data, const char *from)
{
	if (server->sasl_timeout != 0) {
		g_source_remove(server->sasl_timeout);
		server->sasl_timeout = 0;
	}

	server->sasl_success = TRUE;

	signal_emit("server sasl success", 1, server);

	/* The authentication succeeded, time to finish the CAP negotiation */
	cap_finish_negotiation(server);
}


static void sasl_already(IRC_SERVER_REC *server, const char *data, const char *from)
{
	if (server->sasl_timeout != 0) {
		g_source_remove(server->sasl_timeout);
		server->sasl_timeout = 0;
	}

	server->sasl_success = TRUE;

	signal_emit("server sasl success", 1, server);

	/* We're already authenticated, do nothing */
	cap_finish_negotiation(server);
}


void palette8torgb32(const uint8_t *src, uint8_t *dst, long num_pixels, const uint8_t *palette) { long i; /* for(i=0; i<num_pixels; i++) ((unsigned *)dst)[i] = ((unsigned *)palette)[ src[i] ]; */ for(i=0; i<num_pixels; i++) { #ifdef WORDS_BIGENDIAN dst[3]= palette[ src[i]*4+2 ]; dst[2]= palette[ src[i]*4+1 ]; dst[1]= palette[ src[i]*4+0 ]; #else //FIXME slow? dst[0]= palette[ src[i]*4+2 ]; dst[1]= palette[ src[i]*4+1 ]; dst[2]= palette[ src[i]*4+0 ]; //dst[3]= 0; /* do we need this cleansing? */ #endif dst+= 4; } }


struct cgroup_ops * cgfs_ops_init ( void ) {
 return & cgfs_ops ;
 }


bool Webm2Pes::WritePesPacket(const VideoFrame& frame,
                              PacketDataBuffer* packet_data) {
  if (frame.buffer().data.get() == nullptr || frame.buffer().length < 1)
    return false;

  Ranges frame_ranges;
  if (frame.codec() == VideoFrame::kVP9) {
    const bool has_superframe_index = ParseVP9SuperFrameIndex(
        frame.buffer().data.get(), frame.buffer().length, &frame_ranges);
    if (has_superframe_index == false) {
      frame_ranges.push_back(Range(0, frame.buffer().length));
    }
  } else {
    frame_ranges.push_back(Range(0, frame.buffer().length));
  }

  const std::int64_t khz90_pts =
      NanosecondsTo90KhzTicks(frame.nanosecond_pts());
  PesHeader header;
  header.optional_header.SetPtsBits(khz90_pts);

  packet_data->clear();

  for (const Range& packet_payload_range : frame_ranges) {
    std::size_t extra_bytes = 0;
    if (packet_payload_range.length > kMaxPayloadSize) {
      extra_bytes = packet_payload_range.length - kMaxPayloadSize;
    }

    // First packet of new frame. Always include PTS and BCMV header.
    header.packet_length =
        packet_payload_range.length - extra_bytes + BCMVHeader::size();
    if (header.Write(true, packet_data) != true) {
      std::fprintf(stderr, "Webm2Pes: packet header write failed.\n");
      return false;
    }

    BCMVHeader bcmv_header(static_cast<uint32_t>(packet_payload_range.length));
    if (bcmv_header.Write(packet_data) != true) {
      std::fprintf(stderr, "Webm2Pes: BCMV write failed.\n");
      return false;
    }

    // Insert the payload at the end of |packet_data|.
    const std::uint8_t* const payload_start =
        frame.buffer().data.get() + packet_payload_range.offset;

    const std::size_t bytes_to_copy = packet_payload_range.length - extra_bytes;
    if (CopyAndEscapeStartCodes(payload_start, bytes_to_copy, packet_data) ==
        false) {
      fprintf(stderr, "Webm2Pes: Payload write failed.\n");
      return false;
    }

    std::size_t bytes_copied = bytes_to_copy;
    while (extra_bytes) {
      // Write PES packets for the remaining data, but omit the PTS and BCMV
      // header.
      const std::size_t extra_bytes_to_copy =
          std::min(kMaxPayloadSize, extra_bytes);
      extra_bytes -= extra_bytes_to_copy;
      header.packet_length = extra_bytes_to_copy;
      if (header.Write(false, packet_data) != true) {
        fprintf(stderr, "Webm2pes: fragment write failed.\n");
        return false;
      }

      const std::uint8_t* fragment_start = payload_start + bytes_copied;
      if (CopyAndEscapeStartCodes(fragment_start, extra_bytes_to_copy,
                                  packet_data) == false) {
        fprintf(stderr, "Webm2Pes: Payload write failed.\n");
        return false;
      }

      bytes_copied += extra_bytes_to_copy;
    }
  }

  return true;
}


SPL_METHOD ( SplFileInfo , func_name ) \ {
 \ spl_filesystem_object * intern = ( spl_filesystem_object * ) zend_object_store_get_object ( getThis ( ) TSRMLS_CC ) ;
 \ zend_error_handling error_handling ;
 \ if ( zend_parse_parameters_none ( ) == FAILURE ) {
 \ return ;
 \ }
 \ \ zend_replace_error_handling ( EH_THROW , spl_ce_RuntimeException , & error_handling TSRMLS_CC ) ;
 \ spl_filesystem_object_get_file_name ( intern TSRMLS_CC ) ;
 \ php_stat ( intern -> file_name , intern -> file_name_len , func_num , return_value TSRMLS_CC ) ;
 \ zend_restore_error_handling ( & error_handling TSRMLS_CC ) ;
 \ }
 FileInfoFunction ( getPerms , FS_PERMS ) FileInfoFunction ( getInode , FS_INODE ) FileInfoFunction ( getSize , FS_SIZE ) FileInfoFunction ( getOwner , FS_OWNER ) FileInfoFunction ( getGroup , FS_GROUP ) FileInfoFunction ( getATime , FS_ATIME ) FileInfoFunction ( getMTime , FS_MTIME ) FileInfoFunction ( getCTime , FS_CTIME ) FileInfoFunction ( getType , FS_TYPE ) FileInfoFunction ( isWritable , FS_IS_W ) FileInfoFunction ( isReadable , FS_IS_R ) FileInfoFunction ( isExecutable , FS_IS_X )


static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
{
  char
    message[MagickPathExtent],
    *text;

  uint32
    count,
    length,
    type;

  unsigned long
    *tietz;

  if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
    (void) SetImageProperty(image,"tiff:artist",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
    (void) SetImageProperty(image,"tiff:copyright",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
    (void) SetImageProperty(image,"tiff:timestamp",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
    (void) SetImageProperty(image,"tiff:document",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
    (void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
    (void) SetImageProperty(image,"comment",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
    (void) SetImageProperty(image,"tiff:make",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
    (void) SetImageProperty(image,"tiff:model",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
    {
      if (count >= MagickPathExtent)
        count=MagickPathExtent-1;
      (void) CopyMagickString(message,text,count+1);
      (void) SetImageProperty(image,"tiff:image-id",message,exception);
    }
  if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
    (void) SetImageProperty(image,"label",text,exception);
  if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
    (void) SetImageProperty(image,"tiff:software",text,exception);
  if (TIFFGetField(tiff,33423,&count,&text) == 1)
    {
      if (count >= MagickPathExtent)
        count=MagickPathExtent-1;
      (void) CopyMagickString(message,text,count+1);
      (void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
    }
  if (TIFFGetField(tiff,36867,&count,&text) == 1)
    {
      if (count >= MagickPathExtent)
        count=MagickPathExtent-1;
      (void) CopyMagickString(message,text,count+1);
      (void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
    }
  if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
    switch (type)
    {
      case 0x01:
      {
        (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
          exception);
        break;
      }
      case 0x02:
      {
        (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
        break;
      }
      case 0x04:
      {
        (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
        break;
      }
      default:
        break;
    }
  if (TIFFGetField(tiff,37706,&length,&tietz) == 1)
    {
      (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]);
      (void) SetImageProperty(image,"tiff:tietz_offset",message,exception);
    }
}


static int put_v4l2_ext_controls32(struct file *file,
				   struct v4l2_ext_controls *kp,
				   struct v4l2_ext_controls32 __user *up)
{
	struct v4l2_ext_control32 __user *ucontrols;
	struct v4l2_ext_control __user *kcontrols =
		(__force struct v4l2_ext_control __user *)kp->controls;
	int n = kp->count;
	compat_caddr_t p;

	if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
	    put_user(kp->which, &up->which) ||
	    put_user(kp->count, &up->count) ||
	    put_user(kp->error_idx, &up->error_idx) ||
	    copy_to_user(up->reserved, kp->reserved, sizeof(up->reserved)))
		return -EFAULT;
	if (!kp->count)
		return 0;

	if (get_user(p, &up->controls))
		return -EFAULT;
	ucontrols = compat_ptr(p);
	if (!access_ok(VERIFY_WRITE, ucontrols, n * sizeof(*ucontrols)))
		return -EFAULT;

	while (--n >= 0) {
		unsigned size = sizeof(*ucontrols);
		u32 id;

		if (get_user(id, &kcontrols->id))
			return -EFAULT;
		/* Do not modify the pointer when copying a pointer control.
		   The contents of the pointer was changed, not the pointer
		   itself. */
		if (ctrl_is_pointer(file, id))
			size -= sizeof(ucontrols->value64);
		if (copy_in_user(ucontrols, kcontrols, size))
			return -EFAULT;
		ucontrols++;
		kcontrols++;
	}
	return 0;
}


static int put_v4l2_standard32(struct v4l2_standard *kp, struct v4l2_standard32 __user *up)
{
	if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
	    put_user(kp->index, &up->index) ||
	    put_user(kp->id, &up->id) ||
	    copy_to_user(up->name, kp->name, sizeof(up->name)) ||
	    copy_to_user(&up->frameperiod, &kp->frameperiod,
			 sizeof(kp->frameperiod)) ||
	    put_user(kp->framelines, &up->framelines) ||
	    copy_to_user(up->reserved, kp->reserved, sizeof(kp->reserved)))
		return -EFAULT;
	return 0;
}


static void U_CALLCONV _HZOpen ( UConverter * cnv , UConverterLoadArgs * pArgs , UErrorCode * errorCode ) {
 UConverter * gbConverter ;
 if ( pArgs -> onlyTestIsLoadable ) {
 ucnv_canCreateConverter ( "GBK" , errorCode ) ;
 return ;
 }
 gbConverter = ucnv_open ( "GBK" , errorCode ) ;
 if ( U_FAILURE ( * errorCode ) ) {
 return ;
 }
 cnv -> toUnicodeStatus = 0 ;
 cnv -> fromUnicodeStatus = 0 ;
 cnv -> mode = 0 ;
 cnv -> fromUChar32 = 0x0000 ;
 cnv -> extraInfo = uprv_calloc ( 1 , sizeof ( UConverterDataHZ ) ) ;
 if ( cnv -> extraInfo != NULL ) {
 ( ( UConverterDataHZ * ) cnv -> extraInfo ) -> gbConverter = gbConverter ;
 }
 else {
 ucnv_close ( gbConverter ) ;
 * errorCode = U_MEMORY_ALLOCATION_ERROR ;
 return ;
 }
 }


bool add_edge_h ( connection_t * c ) {
 edge_t * e ;
 node_t * from , * to ;
 char from_name [ MAX_STRING_SIZE ] ;
 char to_name [ MAX_STRING_SIZE ] ;
 char to_address [ MAX_STRING_SIZE ] ;
 char to_port [ MAX_STRING_SIZE ] ;
 sockaddr_t address ;
 uint32_t options ;
 int weight ;
 if ( sscanf ( c -> buffer , "%*d %*x " MAX_STRING " " MAX_STRING " " MAX_STRING " " MAX_STRING " %x %d" , from_name , to_name , to_address , to_port , & options , & weight ) != 6 ) {
 logger ( LOG_ERR , "Got bad %s from %s (%s)" , "ADD_EDGE" , c -> name , c -> hostname ) ;
 return false ;
 }
 if ( ! check_id ( from_name ) || ! check_id ( to_name ) ) {
 logger ( LOG_ERR , "Got bad %s from %s (%s): %s" , "ADD_EDGE" , c -> name , c -> hostname , "invalid name" ) ;
 return false ;
 }
 if ( seen_request ( c -> buffer ) ) {
 return true ;
 }
 from = lookup_node ( from_name ) ;
 to = lookup_node ( to_name ) ;
 if ( tunnelserver && from != myself && from != c -> node && to != myself && to != c -> node ) {
 ifdebug ( PROTOCOL ) logger ( LOG_WARNING , "Ignoring indirect %s from %s (%s)" , "ADD_EDGE" , c -> name , c -> hostname ) ;
 return true ;
 }
 if ( ! from ) {
 from = new_node ( ) ;
 from -> name = xstrdup ( from_name ) ;
 node_add ( from ) ;
 }
 if ( ! to ) {
 to = new_node ( ) ;
 to -> name = xstrdup ( to_name ) ;
 node_add ( to ) ;
 }
 address = str2sockaddr ( to_address , to_port ) ;
 e = lookup_edge ( from , to ) ;
 if ( e ) {
 if ( e -> weight != weight || e -> options != options || sockaddrcmp ( & e -> address , & address ) ) {
 if ( from == myself ) {
 ifdebug ( PROTOCOL ) logger ( LOG_WARNING , "Got %s from %s (%s) for ourself which does not match existing entry" , "ADD_EDGE" , c -> name , c -> hostname ) ;
 send_add_edge ( c , e ) ;
 return true ;
 }
 else {
 ifdebug ( PROTOCOL ) logger ( LOG_WARNING , "Got %s from %s (%s) which does not match existing entry" , "ADD_EDGE" , c -> name , c -> hostname ) ;
 e -> options = options ;
 if ( sockaddrcmp ( & e -> address , & address ) ) {
 sockaddrfree ( & e -> address ) ;
 e -> address = address ;
 }
 if ( e -> weight != weight ) {
 avl_node_t * node = avl_unlink ( edge_weight_tree , e ) ;
 e -> weight = weight ;
 avl_insert_node ( edge_weight_tree , node ) ;
 }
 goto done ;
 }
 }
 else {
 return true ;
 }
 }
 else if ( from == myself ) {
 ifdebug ( PROTOCOL ) logger ( LOG_WARNING , "Got %s from %s (%s) for ourself which does not exist" , "ADD_EDGE" , c -> name , c -> hostname ) ;
 contradicting_add_edge ++ ;
 e = new_edge ( ) ;
 e -> from = from ;
 e -> to = to ;
 send_del_edge ( c , e ) ;
 free_edge ( e ) ;
 return true ;
 }
 e = new_edge ( ) ;
 e -> from = from ;
 e -> to = to ;
 e -> address = address ;
 e -> options = options ;
 e -> weight = weight ;
 edge_add ( e ) ;
 done : if ( ! tunnelserver ) {
 forward_request ( c ) ;
 }
 graph ( ) ;
 return true ;
 }


static inline void set_num_732 ( unsigned char * p , uint32_t value ) {
 archive_be32enc ( p , value ) ;
 }


static void test_submit_aio(void) { WorkerTestData data = { .n = 0, .ret = -EINPROGRESS }; data.aiocb = thread_pool_submit_aio(pool, worker_cb, &data, done_cb, &data); /* The callbacks are not called until after the first wait. */ active = 1; g_assert_cmpint(data.ret, ==, -EINPROGRESS); qemu_aio_wait_all(); g_assert_cmpint(active, ==, 0); g_assert_cmpint(data.n, ==, 1); g_assert_cmpint(data.ret, ==, 0); }


static int __get_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
	if (get_user(kp->type, &up->type))
		return -EFAULT;

	switch (kp->type) {
	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
	case V4L2_BUF_TYPE_VIDEO_OUTPUT:
		return copy_from_user(&kp->fmt.pix, &up->fmt.pix,
				      sizeof(kp->fmt.pix)) ? -EFAULT : 0;
	case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
	case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
		return copy_from_user(&kp->fmt.pix_mp, &up->fmt.pix_mp,
				      sizeof(kp->fmt.pix_mp)) ? -EFAULT : 0;
	case V4L2_BUF_TYPE_VIDEO_OVERLAY:
	case V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY:
		return get_v4l2_window32(&kp->fmt.win, &up->fmt.win);
	case V4L2_BUF_TYPE_VBI_CAPTURE:
	case V4L2_BUF_TYPE_VBI_OUTPUT:
		return copy_from_user(&kp->fmt.vbi, &up->fmt.vbi,
				      sizeof(kp->fmt.vbi)) ? -EFAULT : 0;
	case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
	case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
		return copy_from_user(&kp->fmt.sliced, &up->fmt.sliced,
				      sizeof(kp->fmt.sliced)) ? -EFAULT : 0;
	case V4L2_BUF_TYPE_SDR_CAPTURE:
	case V4L2_BUF_TYPE_SDR_OUTPUT:
		return copy_from_user(&kp->fmt.sdr, &up->fmt.sdr,
				      sizeof(kp->fmt.sdr)) ? -EFAULT : 0;
	case V4L2_BUF_TYPE_META_CAPTURE:
		return copy_from_user(&kp->fmt.meta, &up->fmt.meta,
				      sizeof(kp->fmt.meta)) ? -EFAULT : 0;
	default:
		return -EINVAL;
	}
}


virLogFilterPtr virLogFilterNew ( const char * match , virLogPriority priority , unsigned int flags ) {
 virLogFilterPtr ret = NULL ;
 char * mdup = NULL ;
 virCheckFlags ( VIR_LOG_STACK_TRACE , NULL ) ;
 if ( priority < VIR_LOG_DEBUG || priority > VIR_LOG_ERROR ) {
 virReportError ( VIR_ERR_INVALID_ARG , _ ( "Invalid log priority %d" ) , priority ) ;
 return NULL ;
 }
 if ( VIR_STRDUP_QUIET ( mdup , match ) < 0 ) return NULL ;
 if ( VIR_ALLOC_QUIET ( ret ) < 0 ) {
 VIR_FREE ( mdup ) ;
 return NULL ;
 }
 ret -> match = mdup ;
 ret -> priority = priority ;
 ret -> flags = flags ;
 return ret ;
 }


static inline Quantum ClampPixel ( const MagickRealType value ) {
 # if ! defined ( MAGICKCORE_HDRI_SUPPORT ) return ( ( Quantum ) value ) ;
 # else if ( value < 0.0 ) return ( ( Quantum ) 0.0 ) ;
 if ( value >= ( MagickRealType ) QuantumRange ) return ( ( Quantum ) QuantumRange ) ;
 return ( ( Quantum ) value ) ;
 # endif }


static void pcx_palette(const uint8_t **src, uint32_t *dst, unsigned int pallen) { unsigned int i; for (i=0; i<pallen; i++) *dst++ = 0xFF000000 | bytestream_get_be24(src); if (pallen < 256) memset(dst, 0, (256 - pallen) * sizeof(*dst)); }