processQueryTargets(struct module_qstate* qstate, struct iter_qstate* iq,
	struct iter_env* ie, int id)
{
	int tf_policy;
	struct delegpt_addr* target;
	struct outbound_entry* outq;
	int auth_fallback = 0;
	uint8_t* qout_orig = NULL;
	size_t qout_orig_len = 0;

	/* NOTE: a request will encounter this state for each target it
	 * needs to send a query to. That is, at least one per referral,
	 * more if some targets timeout or return throwaway answers. */

	log_query_info(VERB_QUERY, "processQueryTargets:", &qstate->qinfo);
	verbose(VERB_ALGO, "processQueryTargets: targetqueries %d, "
		"currentqueries %d sentcount %d", iq->num_target_queries,
		iq->num_current_queries, iq->sent_count);

	/* Make sure that we haven't run away */
	/* FIXME: is this check even necessary? */
	if(iq->referral_count > MAX_REFERRAL_COUNT) {
		verbose(VERB_QUERY, "request has exceeded the maximum "
			"number of referrrals with %d", iq->referral_count);
		errinf(qstate, "exceeded the maximum of referrals");
		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
	}
	if(iq->sent_count > MAX_SENT_COUNT) {
		verbose(VERB_QUERY, "request has exceeded the maximum "
			"number of sends with %d", iq->sent_count);
		errinf(qstate, "exceeded the maximum number of sends");
		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
	}

	/* Make sure we have a delegation point, otherwise priming failed
	 * or another failure occurred */
	if(!iq->dp) {
		verbose(VERB_QUERY, "Failed to get a delegation, giving up");
		errinf(qstate, "failed to get a delegation (eg. prime failure)");
		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
	}
	if(!ie->supports_ipv6)
		delegpt_no_ipv6(iq->dp);
	if(!ie->supports_ipv4)
		delegpt_no_ipv4(iq->dp);
	delegpt_log(VERB_ALGO, iq->dp);

	if(iq->num_current_queries>0) {
		/* already busy answering a query, this restart is because
		 * more delegpt addrs became available, wait for existing
		 * query. */
		verbose(VERB_ALGO, "woke up, but wait for outstanding query");
		qstate->ext_state[id] = module_wait_reply;
		return 0;
	}

	if(iq->minimisation_state == INIT_MINIMISE_STATE
		&& !(iq->chase_flags & BIT_RD)) {
		/* (Re)set qinfo_out to (new) delegation point, except when
		 * qinfo_out is already a subdomain of dp. This happens when
		 * increasing by more than one label at once (QNAMEs with more
		 * than MAX_MINIMISE_COUNT labels). */
		if(!(iq->qinfo_out.qname_len
			&& dname_subdomain_c(iq->qchase.qname,
				iq->qinfo_out.qname)
			&& dname_subdomain_c(iq->qinfo_out.qname,
				iq->dp->name))) {
			iq->qinfo_out.qname = iq->dp->name;
			iq->qinfo_out.qname_len = iq->dp->namelen;
			iq->qinfo_out.qtype = LDNS_RR_TYPE_A;
			iq->qinfo_out.qclass = iq->qchase.qclass;
			iq->qinfo_out.local_alias = NULL;
			iq->minimise_count = 0;
		}

		iq->minimisation_state = MINIMISE_STATE;
	}
	if(iq->minimisation_state == MINIMISE_STATE) {
		int qchaselabs = dname_count_labels(iq->qchase.qname);
		int labdiff = qchaselabs -
			dname_count_labels(iq->qinfo_out.qname);

		qout_orig = iq->qinfo_out.qname;
		qout_orig_len = iq->qinfo_out.qname_len;
		iq->qinfo_out.qname = iq->qchase.qname;
		iq->qinfo_out.qname_len = iq->qchase.qname_len;
		iq->minimise_count++;
		iq->timeout_count = 0;

		iter_dec_attempts(iq->dp, 1);

		/* Limit number of iterations for QNAMEs with more
		 * than MAX_MINIMISE_COUNT labels. Send first MINIMISE_ONE_LAB
		 * labels of QNAME always individually.
		 */
		if(qchaselabs > MAX_MINIMISE_COUNT && labdiff > 1 &&
			iq->minimise_count > MINIMISE_ONE_LAB) {
			if(iq->minimise_count < MAX_MINIMISE_COUNT) {
				int multilabs = qchaselabs - 1 -
					MINIMISE_ONE_LAB;
				int extralabs = multilabs /
					MINIMISE_MULTIPLE_LABS;

				if (MAX_MINIMISE_COUNT - iq->minimise_count >=
					multilabs % MINIMISE_MULTIPLE_LABS)
					/* Default behaviour is to add 1 label
					 * every iteration. Therefore, decrement
					 * the extralabs by 1 */
					extralabs--;
				if (extralabs < labdiff)
					labdiff -= extralabs;
				else
					labdiff = 1;
			}
			/* Last minimised iteration, send all labels with
			 * QTYPE=NS */
			else
				labdiff = 1;
		}

		if(labdiff > 1) {
			verbose(VERB_QUERY, "removing %d labels", labdiff-1);
			dname_remove_labels(&iq->qinfo_out.qname,
				&iq->qinfo_out.qname_len,
				labdiff-1);
		}
		if(labdiff < 1 || (labdiff < 2
			&& (iq->qchase.qtype == LDNS_RR_TYPE_DS
			|| iq->qchase.qtype == LDNS_RR_TYPE_A)))
			/* Stop minimising this query, resolve "as usual" */
			iq->minimisation_state = DONOT_MINIMISE_STATE;
		else if(!qstate->no_cache_lookup) {
			struct dns_msg* msg = dns_cache_lookup(qstate->env,
				iq->qinfo_out.qname, iq->qinfo_out.qname_len,
				iq->qinfo_out.qtype, iq->qinfo_out.qclass,
				qstate->query_flags, qstate->region,
				qstate->env->scratch, 0);
			if(msg && msg->rep->an_numrrsets == 0
				&& FLAGS_GET_RCODE(msg->rep->flags) ==
				LDNS_RCODE_NOERROR)
				/* no need to send query if it is already
				 * cached as NOERROR/NODATA */
				return 1;
		}
	}
	if(iq->minimisation_state == SKIP_MINIMISE_STATE) {
		if(iq->timeout_count < MAX_MINIMISE_TIMEOUT_COUNT)
			/* Do not increment qname, continue incrementing next
			 * iteration */
			iq->minimisation_state = MINIMISE_STATE;
		else if(!qstate->env->cfg->qname_minimisation_strict)
			/* Too many time-outs detected for this QNAME and QTYPE.
			 * We give up, disable QNAME minimisation. */
			iq->minimisation_state = DONOT_MINIMISE_STATE;
	}
	if(iq->minimisation_state == DONOT_MINIMISE_STATE)
		iq->qinfo_out = iq->qchase;

	/* now find an answer to this query */
	/* see if authority zones have an answer */
	/* now we know the dp, we can check the auth zone for locally hosted
	 * contents */
	if(!iq->auth_zone_avoid && qstate->blacklist) {
		if(auth_zones_can_fallback(qstate->env->auth_zones,
			iq->dp->name, iq->dp->namelen, iq->qinfo_out.qclass)) {
			/* if cache is blacklisted and this zone allows us
			 * to fallback to the internet, then do so, and
			 * fetch results from the internet servers */
			iq->auth_zone_avoid = 1;
		}
	}
	if(iq->auth_zone_avoid) {
		iq->auth_zone_avoid = 0;
		auth_fallback = 1;
	} else if(auth_zones_lookup(qstate->env->auth_zones, &iq->qinfo_out,
		qstate->region, &iq->response, &auth_fallback, iq->dp->name,
		iq->dp->namelen)) {
		/* use this as a response to be processed by the iterator */
		if(verbosity >= VERB_ALGO) {
			log_dns_msg("msg from auth zone",
				&iq->response->qinfo, iq->response->rep);
		}
		if((iq->chase_flags&BIT_RD) && !(iq->response->rep->flags&BIT_AA)) {
			verbose(VERB_ALGO, "forwarder, ignoring referral from auth zone");
		} else {
			lock_rw_wrlock(&qstate->env->auth_zones->lock);
			qstate->env->auth_zones->num_query_up++;
			lock_rw_unlock(&qstate->env->auth_zones->lock);
			iq->num_current_queries++;
			iq->chase_to_rd = 0;
			iq->dnssec_lame_query = 0;
			iq->auth_zone_response = 1;
			return next_state(iq, QUERY_RESP_STATE);
		}
	}
	iq->auth_zone_response = 0;
	if(auth_fallback == 0) {
		/* like we got servfail from the auth zone lookup, and
		 * no internet fallback */
		verbose(VERB_ALGO, "auth zone lookup failed, no fallback,"
			" servfail");
		errinf(qstate, "auth zone lookup failed, fallback is off");
		return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
	}
	if(iq->dp->auth_dp) {
		/* we wanted to fallback, but had no delegpt, only the
		 * auth zone generated delegpt, create an actual one */
		iq->auth_zone_avoid = 1;
		return next_state(iq, INIT_REQUEST_STATE);
	}
	/* but mostly, fallback==1 (like, when no such auth zone exists)
	 * and we continue with lookups */

	tf_policy = 0;
	/* < not <=, because although the array is large enough for <=, the
	 * generated query will immediately be discarded due to depth and
	 * that servfail is cached, which is not good as opportunism goes. */
	if(iq->depth < ie->max_dependency_depth
		&& iq->sent_count < TARGET_FETCH_STOP) {
		tf_policy = ie->target_fetch_policy[iq->depth];
	}

	/* if in 0x20 fallback get as many targets as possible */
	if(iq->caps_fallback) {
		int extra = 0;
		size_t naddr, nres, navail;
		if(!query_for_targets(qstate, iq, ie, id, -1, &extra)) {
			errinf(qstate, "could not fetch nameservers for 0x20 fallback");
			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
		}
		iq->num_target_queries += extra;
		target_count_increase(iq, extra);
		if(iq->num_target_queries > 0) {
			/* wait to get all targets, we want to try em */
			verbose(VERB_ALGO, "wait for all targets for fallback");
			qstate->ext_state[id] = module_wait_reply;
			/* undo qname minimise step because we'll get back here
			 * to do it again */
			if(qout_orig && iq->minimise_count > 0) {
				iq->minimise_count--;
				iq->qinfo_out.qname = qout_orig;
				iq->qinfo_out.qname_len = qout_orig_len;
			}
			return 0;
		}
		/* did we do enough fallback queries already? */
		delegpt_count_addr(iq->dp, &naddr, &nres, &navail);
		/* the current caps_server is the number of fallbacks sent.
		 * the original query is one that matched too, so we have
		 * caps_server+1 number of matching queries now */
		if(iq->caps_server+1 >= naddr*3 ||
			iq->caps_server*2+2 >= MAX_SENT_COUNT) {
			/* *2 on sentcount check because ipv6 may fail */
			/* we're done, process the response */
			verbose(VERB_ALGO, "0x20 fallback had %d responses "
				"match for %d wanted, done.",
				(int)iq->caps_server+1, (int)naddr*3);
			iq->response = iq->caps_response;
			iq->caps_fallback = 0;
			iter_dec_attempts(iq->dp, 3); /* space for fallback */
			iq->num_current_queries++; /* RespState decrements it*/
			iq->referral_count++; /* make sure we don't loop */
			iq->sent_count = 0;
			iq->state = QUERY_RESP_STATE;
			return 1;
		}
		verbose(VERB_ALGO, "0x20 fallback number %d",
			(int)iq->caps_server);

	/* if there is a policy to fetch missing targets
	 * opportunistically, do it. we rely on the fact that once a
	 * query (or queries) for a missing name have been issued,
	 * they will not show up again. */
	} else if(tf_policy != 0) {
		int extra = 0;
		verbose(VERB_ALGO, "attempt to get extra %d targets",
			tf_policy);
		(void)query_for_targets(qstate, iq, ie, id, tf_policy, &extra);
		/* errors ignored, these targets are not strictly necessary for
		 * this result, we do not have to reply with SERVFAIL */
		iq->num_target_queries += extra;
		target_count_increase(iq, extra);
	}

	/* Add the current set of unused targets to our queue. */
	delegpt_add_unused_targets(iq->dp);

	/* Select the next usable target, filtering out unsuitable targets. */
	target = iter_server_selection(ie, qstate->env, iq->dp,
		iq->dp->name, iq->dp->namelen, iq->qchase.qtype,
		&iq->dnssec_lame_query, &iq->chase_to_rd,
		iq->num_target_queries, qstate->blacklist,
		qstate->prefetch_leeway);

	/* If no usable target was selected... */
	if(!target) {
		/* Here we distinguish between three states: generate a new
		 * target query, just wait, or quit (with a SERVFAIL).
		 * We have the following information: number of active
		 * target queries, number of active current queries,
		 * the presence of missing targets at this delegation
		 * point, and the given query target policy. */

		/* Check for the wait condition. If this is true, then
		 * an action must be taken. */
		if(iq->num_target_queries==0 && iq->num_current_queries==0) {
			/* If there is nothing to wait for, then we need
			 * to distinguish between generating (a) new target
			 * query, or failing. */
			if(delegpt_count_missing_targets(iq->dp) > 0) {
				int qs = 0;
				verbose(VERB_ALGO, "querying for next "
					"missing target");
				if(!query_for_targets(qstate, iq, ie, id,
					1, &qs)) {
					errinf(qstate, "could not fetch nameserver");
					errinf_dname(qstate, "at zone", iq->dp->name);
					return error_response(qstate, id,
						LDNS_RCODE_SERVFAIL);
				}
				if(qs == 0 &&
				   delegpt_count_missing_targets(iq->dp) == 0){
					/* it looked like there were missing
					 * targets, but they did not turn up.
					 * Try the bad choices again (if any),
					 * when we get back here missing==0,
					 * so this is not a loop. */
					return 1;
				}
				iq->num_target_queries += qs;
				target_count_increase(iq, qs);
			}
			/* Since a target query might have been made, we
			 * need to check again. */
			if(iq->num_target_queries == 0) {
				/* if in capsforid fallback, instead of last
				 * resort, we agree with the current reply
				 * we have (if any) (our count of addrs bad)*/
				if(iq->caps_fallback && iq->caps_reply) {
					/* we're done, process the response */
					verbose(VERB_ALGO, "0x20 fallback had %d responses, "
						"but no more servers except "
						"last resort, done.",
						(int)iq->caps_server+1);
					iq->response = iq->caps_response;
					iq->caps_fallback = 0;
					iter_dec_attempts(iq->dp, 3); /* space for fallback */
					iq->num_current_queries++; /* RespState decrements it*/
					iq->referral_count++; /* make sure we don't loop */
					iq->sent_count = 0;
					iq->state = QUERY_RESP_STATE;
					return 1;
				}
				return processLastResort(qstate, iq, ie, id);
			}
		}

		/* otherwise, we have no current targets, so submerge
		 * until one of the target or direct queries return. */
		if(iq->num_target_queries>0 && iq->num_current_queries>0) {
			verbose(VERB_ALGO, "no current targets -- waiting "
				"for %d targets to resolve or %d outstanding"
				" queries to respond", iq->num_target_queries,
				iq->num_current_queries);
			qstate->ext_state[id] = module_wait_reply;
		} else if(iq->num_target_queries>0) {
			verbose(VERB_ALGO, "no current targets -- waiting "
				"for %d targets to resolve.",
				iq->num_target_queries);
			qstate->ext_state[id] = module_wait_subquery;
		} else {
			verbose(VERB_ALGO, "no current targets -- waiting "
				"for %d outstanding queries to respond.",
				iq->num_current_queries);
			qstate->ext_state[id] = module_wait_reply;
		}
		/* undo qname minimise step because we'll get back here
		 * to do it again */
		if(qout_orig && iq->minimise_count > 0) {
			iq->minimise_count--;
			iq->qinfo_out.qname = qout_orig;
			iq->qinfo_out.qname_len = qout_orig_len;
		}
		return 0;
	}

	/* if not forwarding, check ratelimits per delegationpoint name */
	if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok) {
		if(!infra_ratelimit_inc(qstate->env->infra_cache, iq->dp->name,
			iq->dp->namelen, *qstate->env->now, &qstate->qinfo,
			qstate->reply)) {
			lock_basic_lock(&ie->queries_ratelimit_lock);
			ie->num_queries_ratelimited++;
			lock_basic_unlock(&ie->queries_ratelimit_lock);
			verbose(VERB_ALGO, "query exceeded ratelimits");
			qstate->was_ratelimited = 1;
			errinf_dname(qstate, "exceeded ratelimit for zone",
				iq->dp->name);
			return error_response(qstate, id, LDNS_RCODE_SERVFAIL);
		}
	}

	/* We have a valid target. */
	if(verbosity >= VERB_QUERY) {
		log_query_info(VERB_QUERY, "sending query:", &iq->qinfo_out);
		log_name_addr(VERB_QUERY, "sending to target:", iq->dp->name,
			&target->addr, target->addrlen);
		verbose(VERB_ALGO, "dnssec status: %s%s",
			iq->dnssec_expected?"expected": "not expected",
			iq->dnssec_lame_query?" but lame_query anyway": "");
	}
	fptr_ok(fptr_whitelist_modenv_send_query(qstate->env->send_query));
	outq = (*qstate->env->send_query)(&iq->qinfo_out,
		iq->chase_flags | (iq->chase_to_rd?BIT_RD:0),
		/* unset CD if to forwarder(RD set) and not dnssec retry
		 * (blacklist nonempty) and no trust-anchors are configured
		 * above the qname or on the first attempt when dnssec is on */
		EDNS_DO| ((iq->chase_to_rd||(iq->chase_flags&BIT_RD)!=0)&&
		!qstate->blacklist&&(!iter_qname_indicates_dnssec(qstate->env,
		&iq->qinfo_out)||target->attempts==1)?0:BIT_CD),
		iq->dnssec_expected, iq->caps_fallback || is_caps_whitelisted(
		ie, iq), &target->addr, target->addrlen,
		iq->dp->name, iq->dp->namelen,
		(iq->dp->ssl_upstream || qstate->env->cfg->ssl_upstream),
		target->tls_auth_name, qstate);
	if(!outq) {
		log_addr(VERB_DETAIL, "error sending query to auth server",
			&target->addr, target->addrlen);
		if(!(iq->chase_flags & BIT_RD) && !iq->ratelimit_ok)
		    infra_ratelimit_dec(qstate->env->infra_cache, iq->dp->name,
			iq->dp->namelen, *qstate->env->now);
		if(qstate->env->cfg->qname_minimisation)
			iq->minimisation_state = SKIP_MINIMISE_STATE;
		return next_state(iq, QUERYTARGETS_STATE);
	}
	outbound_list_insert(&iq->outlist, outq);
	iq->num_current_queries++;
	iq->sent_count++;
	qstate->ext_state[id] = module_wait_reply;

	return 0;
}


static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h) { VncState *vs = ds->opaque; int i; h += y; /* round x down to ensure the loop only spans one 16-pixel block per, iteration. otherwise, if (x % 16) != 0, the last iteration may span two 16-pixel blocks but we only mark the first as dirty */ w += (x % 16); x -= (x % 16); x = MIN(x, vs->width); y = MIN(y, vs->height); w = MIN(x + w, vs->width) - x; h = MIN(h, vs->height); for (; y < h; y++) for (i = 0; i < w; i += 16) vnc_set_bit(vs->dirty_row[y], (x + i) / 16); }


static void musb_async_cancel_device(MUSBState *s, USBDevice *dev) { int ep, dir; for (ep = 0; ep < 16; ep++) { for (dir = 0; dir < 2; dir++) { if (s->ep[ep].packey[dir].p.owner == NULL || s->ep[ep].packey[dir].p.owner->dev != dev) { continue; } usb_cancel_packet(&s->ep[ep].packey[dir].p); /* status updates needed here? */ } } }


static int local_chown(FsContext *fs_ctx, const char *path, FsCred *credp) { if ((credp->fc_uid == -1 && credp->fc_gid == -1) || (fs_ctx->fs_sm == SM_PASSTHROUGH)) { return lchown(rpath(fs_ctx, path), credp->fc_uid, credp->fc_gid); } else if (fs_ctx->fs_sm == SM_MAPPED) { return local_set_xattr(rpath(fs_ctx, path), credp); } else if (fs_ctx->fs_sm == SM_PASSTHROUGH) { return lchown(rpath(fs_ctx, path), credp->fc_uid, credp->fc_gid); } return -1; }


static void encode_mb(MpegEncContext *s, int motion_x, int motion_y) { const int mb_x= s->mb_x; const int mb_y= s->mb_y; int i; #if 0 if (s->interlaced_dct) { dct_linesize = s->linesize * 2; dct_offset = s->linesize; } else { dct_linesize = s->linesize; dct_offset = s->linesize * 8; } #endif if (s->mb_intra) { UINT8 *ptr; int wrap; wrap = s->linesize; ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16; get_pixels(s->block[0], ptr , wrap); get_pixels(s->block[1], ptr + 8, wrap); get_pixels(s->block[2], ptr + 8 * wrap , wrap); get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap); wrap >>=1; ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8; get_pixels(s->block[4], ptr, wrap); ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8; get_pixels(s->block[5], ptr, wrap); }else{ op_pixels_func *op_pix; qpel_mc_func *op_qpix; UINT8 *dest_y, *dest_cb, *dest_cr; UINT8 *ptr; int wrap; dest_y = s->current_picture[0] + (mb_y * 16 * s->linesize ) + mb_x * 16; dest_cb = s->current_picture[1] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8; dest_cr = s->current_picture[2] + (mb_y * 8 * (s->linesize >> 1)) + mb_x * 8; if ((!s->no_rounding) || s->pict_type==B_TYPE){ op_pix = put_pixels_tab; op_qpix= qpel_mc_rnd_tab; }else{ op_pix = put_no_rnd_pixels_tab; op_qpix= qpel_mc_no_rnd_tab; } if (s->mv_dir & MV_DIR_FORWARD) { MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix); if ((!s->no_rounding) || s->pict_type==B_TYPE) op_pix = avg_pixels_tab; else op_pix = avg_no_rnd_pixels_tab; } if (s->mv_dir & MV_DIR_BACKWARD) { MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix); } wrap = s->linesize; ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16; diff_pixels(s->block[0], ptr , dest_y , wrap); diff_pixels(s->block[1], ptr + 8, dest_y + 8, wrap); diff_pixels(s->block[2], ptr + 8 * wrap , dest_y + 8 * wrap , wrap); diff_pixels(s->block[3], ptr + 8 * wrap + 8, dest_y + 8 * wrap + 8, wrap); wrap >>=1; ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8; diff_pixels(s->block[4], ptr, dest_cb, wrap); ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8; diff_pixels(s->block[5], ptr, dest_cr, wrap); } #if 0 { float adap_parm; adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) / ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0); printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d", (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P', s->qscale, adap_parm, s->qscale*adap_parm, s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var); } #endif /* DCT & quantize */ if (s->h263_msmpeg4) { msmpeg4_dc_scale(s); } else if (s->h263_pred) { h263_dc_scale(s); } else { /* default quantization values */ s->y_dc_scale = 8; s->c_dc_scale = 8; } for(i=0;i<6;i++) { s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale); } /* huffman encode */ switch(s->out_format) { case FMT_MPEG1: mpeg1_encode_mb(s, s->block, motion_x, motion_y); break; case FMT_H263: if (s->h263_msmpeg4) msmpeg4_encode_mb(s, s->block, motion_x, motion_y); else if(s->h263_pred) mpeg4_encode_mb(s, s->block, motion_x, motion_y); else h263_encode_mb(s, s->block, motion_x, motion_y); break; case FMT_MJPEG: mjpeg_encode_mb(s, s->block); break; } }


generate_parentside_target_query(struct module_qstate* qstate,
	struct iter_qstate* iq, int id, uint8_t* name, size_t namelen,
	uint16_t qtype, uint16_t qclass)
{
	struct module_qstate* subq;
	if(!generate_sub_request(name, namelen, qtype, qclass, qstate,
		id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0))
		return 0;
	if(subq) {
		struct iter_qstate* subiq =
			(struct iter_qstate*)subq->minfo[id];
		/* blacklist the cache - we want to fetch parent stuff */
		sock_list_insert(&subq->blacklist, NULL, 0, subq->region);
		subiq->query_for_pside_glue = 1;
		if(dname_subdomain_c(name, iq->dp->name)) {
			subiq->dp = delegpt_copy(iq->dp, subq->region);
			subiq->dnssec_expected = iter_indicates_dnssec(
				qstate->env, subiq->dp, NULL,
				subq->qinfo.qclass);
			subiq->refetch_glue = 1;
		} else {
			subiq->dp = dns_cache_find_delegation(qstate->env,
				name, namelen, qtype, qclass, subq->region,
				&subiq->deleg_msg,
				*qstate->env->now+subq->prefetch_leeway);
			/* if no dp, then it's from root, refetch unneeded */
			if(subiq->dp) {
				subiq->dnssec_expected = iter_indicates_dnssec(
					qstate->env, subiq->dp, NULL,
					subq->qinfo.qclass);
				subiq->refetch_glue = 1;
			}
		}
	}
	log_nametypeclass(VERB_QUERY, "new pside target", name, qtype, qclass);
	return 1;
}


void xps_parse_radial_gradient_brush ( xps_document * doc , const fz_matrix * ctm , const fz_rect * area , char * base_uri , xps_resource * dict , fz_xml * root ) {
 xps_parse_gradient_brush ( doc , ctm , area , base_uri , dict , root , xps_draw_radial_gradient ) ;
 }


externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
                        const char **nextPtr) {
  const char *next = s;
  int tok;

  tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  if (tok <= 0) {
    if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
      *nextPtr = s;
      return XML_ERROR_NONE;
    }
    switch (tok) {
    case XML_TOK_INVALID:
      return XML_ERROR_INVALID_TOKEN;
    case XML_TOK_PARTIAL:
      return XML_ERROR_UNCLOSED_TOKEN;
    case XML_TOK_PARTIAL_CHAR:
      return XML_ERROR_PARTIAL_CHAR;
    case XML_TOK_NONE: /* start == end */
    default:
      break;
    }
  }
  /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
     However, when parsing an external subset, doProlog will not accept a BOM
     as valid, and report a syntax error, so we have to skip the BOM
  */
  else if (tok == XML_TOK_BOM) {
    s = next;
    tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  }

  parser->m_processor = prologProcessor;
  return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
                  (XML_Bool)! parser->m_parsingStatus.finalBuffer);
}


static VALUE decode_enum ( unsigned char * der , long length ) {
 ASN1_ENUMERATED * ai ;
 const unsigned char * p ;
 VALUE ret ;
 int status = 0 ;
 p = der ;
 if ( ! ( ai = d2i_ASN1_ENUMERATED ( NULL , & p , length ) ) ) ossl_raise ( eASN1Error , NULL ) ;
 ret = rb_protect ( ( VALUE ( * ) ( VALUE ) ) asn1integer_to_num , ( VALUE ) ai , & status ) ;
 ASN1_ENUMERATED_free ( ai ) ;
 if ( status ) rb_jump_tag ( status ) ;
 return ret ;
 }


static double lfo_get_value(SimpleLFO *lfo) { double phs = FFMIN(100, lfo->phase / FFMIN(1.99, FFMAX(0.01, lfo->pwidth)) + lfo->offset); double val; if (phs > 1) phs = fmod(phs, 1.); switch (lfo->mode) { case SINE: val = sin(phs * 2 * M_PI); break; case TRIANGLE: if (phs > 0.75) val = (phs - 0.75) * 4 - 1; else if (phs > 0.25) val = -4 * phs + 2; else val = phs * 4; break; case SQUARE: val = phs < 0.5 ? -1 : +1; break; case SAWUP: val = phs * 2 - 1; break; case SAWDOWN: val = 1 - phs * 2; break; } return val * lfo->amount; }


static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey)
{
	int ok = 0;
	unsigned char challenge[30];
	unsigned char *signature = NULL;
	unsigned int siglen;
	const EVP_MD *md = EVP_sha1();
	EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
	EVP_PKEY *privkey = PKCS11_get_private_key(authkey);
	EVP_PKEY *pubkey = PKCS11_get_public_key(authkey);

	if (NULL == privkey)
		goto err;
	siglen = EVP_PKEY_size(privkey);
	if (siglen <= 0)
		goto err;
	signature = malloc(siglen);
	if (NULL == signature)
		goto err;

	/* Verify a SHA-1 hash of random data, signed by the key.
	 *
	 * Note that this will not work keys that aren't eligible for signing.
	 * Unfortunately, libp11 currently has no way of checking
	 * C_GetAttributeValue(CKA_SIGN), see
	 * https://github.com/OpenSC/libp11/issues/219. Since we don't want to
	 * implement try and error, we live with this limitation */
	if (1 != randomize(pamh, challenge, sizeof challenge)) {
		goto err;
	}
	if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md
			|| !EVP_SignInit(md_ctx, md)
			|| !EVP_SignUpdate(md_ctx, challenge, sizeof challenge)
			|| !EVP_SignFinal(md_ctx, signature, &siglen, privkey)
			|| !EVP_MD_CTX_reset(md_ctx)
			|| !EVP_VerifyInit(md_ctx, md)
			|| !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge)
			|| 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) {
		pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n",
				ERR_reason_error_string(ERR_get_error()));
		prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key"));
		goto err;
	}
	ok = 1;

err:
	free(signature);
	if (NULL != pubkey)
		EVP_PKEY_free(pubkey);
	if (NULL != privkey)
		EVP_PKEY_free(privkey);
	if (NULL != md_ctx) {
		EVP_MD_CTX_free(md_ctx);
	}
	return ok;
}


static int vaapi_encode_mjpeg_init_picture_params(AVCodecContext *avctx, VAAPIEncodePicture *pic) { VAAPIEncodeContext *ctx = avctx->priv_data; VAEncPictureParameterBufferJPEG *vpic = pic->codec_picture_params; VAAPIEncodeMJPEGContext *priv = ctx->priv_data; vpic->reconstructed_picture = pic->recon_surface; vpic->coded_buf = pic->output_buffer; vpic->picture_width = ctx->input_width; vpic->picture_height = ctx->input_height; vpic->pic_flags.bits.profile = 0; vpic->pic_flags.bits.progressive = 0; vpic->pic_flags.bits.huffman = 1; vpic->pic_flags.bits.interleaved = 0; vpic->pic_flags.bits.differential = 0; vpic->sample_bit_depth = 8; vpic->num_scan = 1; vpic->num_components = 3; vpic->component_id[0] = 1; vpic->component_id[1] = 2; vpic->component_id[2] = 3; priv->component_subsample_h[0] = 2; priv->component_subsample_v[0] = 2; priv->component_subsample_h[1] = 1; priv->component_subsample_v[1] = 1; priv->component_subsample_h[2] = 1; priv->component_subsample_v[2] = 1; vpic->quantiser_table_selector[0] = 0; vpic->quantiser_table_selector[1] = 1; vpic->quantiser_table_selector[2] = 1; vpic->quality = priv->quality; pic->nb_slices = 1; return 0; }


static void get_tile_buffer ( const uint8_t * const data_end , int is_last , struct vpx_internal_error_info * error_info , const uint8_t * * data , vpx_decrypt_cb decrypt_cb , void * decrypt_state , TileBuffer * buf ) {
 size_t size ;
 if ( ! is_last ) {
 if ( ! read_is_valid ( * data , 4 , data_end ) ) vpx_internal_error ( error_info , VPX_CODEC_CORRUPT_FRAME , "Truncated packet or corrupt tile length" ) ;
 if ( decrypt_cb ) {
 uint8_t be_data [ 4 ] ;
 decrypt_cb ( decrypt_state , * data , be_data , 4 ) ;
 size = mem_get_be32 ( be_data ) ;
 }
 else {
 size = mem_get_be32 ( * data ) ;
 }
 * data += 4 ;
 if ( size > ( size_t ) ( data_end - * data ) ) vpx_internal_error ( error_info , VPX_CODEC_CORRUPT_FRAME , "Truncated packet or corrupt tile size" ) ;
 }
 else {
 size = data_end - * data ;
 }
 buf -> data = * data ;
 buf -> size = size ;
 * data += size ;
 }


static int swf_write_audio(AVFormatContext *s, AVCodecContext *enc, const uint8_t *buf, int size) { SWFContext *swf = s->priv_data; int c = 0; /* Flash Player limit */ if ( swf->swf_frame_number >= 16000 ) { return 0; } if (enc->codec_id == CODEC_ID_MP3 ) { for (c=0; c<size; c++) { swf->audio_fifo[(swf->audio_out_pos+c)%AUDIO_FIFO_SIZE] = buf[c]; } swf->audio_size += size; swf->audio_out_pos += size; swf->audio_out_pos %= AUDIO_FIFO_SIZE; } /* if audio only stream make sure we add swf frames */ if ( swf->video_type == 0 ) { swf_write_video(s, enc, 0, 0); } return 0; }


static PyObject * string_decode ( PyStringObject * self , PyObject * args , PyObject * kwargs ) {
 static char * kwlist [ ] = {
 "encoding" , "errors" , 0 }
 ;
 char * encoding = NULL ;
 char * errors = NULL ;
 PyObject * v ;
 if ( ! PyArg_ParseTupleAndKeywords ( args , kwargs , "|ss:decode" , kwlist , & encoding , & errors ) ) return NULL ;
 v = PyString_AsDecodedObject ( ( PyObject * ) self , encoding , errors ) ;
 if ( v == NULL ) goto onError ;
 if ( ! PyString_Check ( v ) && ! PyUnicode_Check ( v ) ) {
 PyErr_Format ( PyExc_TypeError , "decoder did not return a string/unicode object " "(type=%.400s)" , Py_TYPE ( v ) -> tp_name ) ;
 Py_DECREF ( v ) ;
 return NULL ;
 }
 return v ;
 onError : return NULL ;
 }


vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif )
{
	VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );
	GifFileType *file = gif->file;
	ColorMapObject *map = file->Image.ColorMap ?
		file->Image.ColorMap : file->SColorMap;

	GifByteType *extension;

	if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {
		vips_foreign_load_gif_error( gif );
		return( -1 );
	}

	/* Check that the frame looks sane. Perhaps giflib checks
	 * this for us.
	 */
	if( file->Image.Left < 0 ||
		file->Image.Width < 1 ||
		file->Image.Width > 10000 ||
		file->Image.Left + file->Image.Width > file->SWidth ||
		file->Image.Top < 0 ||
		file->Image.Height < 1 ||
		file->Image.Height > 10000 ||
		file->Image.Top + file->Image.Height > file->SHeight ) {
		vips_error( class->nickname, "%s", _( "bad frame size" ) );
		return( -1 );
	}

	/* Test for a non-greyscale colourmap for this frame.
	 */
	if( !gif->has_colour &&
		map ) {
		int i;

		for( i = 0; i < map->ColorCount; i++ )
			if( map->Colors[i].Red != map->Colors[i].Green ||
				map->Colors[i].Green != map->Colors[i].Blue ) {
				gif->has_colour = TRUE;
				break;
			}
	}

	/* Step over compressed image data.
	 */
	do {
		if( vips_foreign_load_gif_code_next( gif, &extension ) )
			return( -1 );
	} while( extension != NULL );

	return( 0 );
}


void PNGAPI png_set_PLTE ( png_structp png_ptr , png_infop info_ptr , png_colorp palette , int num_palette ) {
 png_uint_32 max_palette_length ;
 png_debug1 ( 1 , "in %s storage function" , "PLTE" ) ;
 if ( png_ptr == NULL || info_ptr == NULL ) return ;
 max_palette_length = ( png_ptr -> color_type == PNG_COLOR_TYPE_PALETTE ) ? ( 1 << png_ptr -> bit_depth ) : PNG_MAX_PALETTE_LENGTH ;
 if ( num_palette < 0 || num_palette > ( int ) max_palette_length ) {
 if ( info_ptr -> color_type == PNG_COLOR_TYPE_PALETTE ) png_error ( png_ptr , "Invalid palette length" ) ;
 else {
 png_warning ( png_ptr , "Invalid palette length" ) ;
 return ;
 }
 }
 # ifdef PNG_FREE_ME_SUPPORTED png_free_data ( png_ptr , info_ptr , PNG_FREE_PLTE , 0 ) ;
 # endif png_ptr -> palette = ( png_colorp ) png_calloc ( png_ptr , PNG_MAX_PALETTE_LENGTH * png_sizeof ( png_color ) ) ;
 png_memcpy ( png_ptr -> palette , palette , num_palette * png_sizeof ( png_color ) ) ;
 info_ptr -> palette = png_ptr -> palette ;
 info_ptr -> num_palette = png_ptr -> num_palette = ( png_uint_16 ) num_palette ;
 # ifdef PNG_FREE_ME_SUPPORTED info_ptr -> free_me |= PNG_FREE_PLTE ;
 # else png_ptr -> flags |= PNG_FLAG_FREE_PLTE ;
 # endif info_ptr -> valid |= PNG_INFO_PLTE ;
 }


static void policy_mapping_destroy ( x509_policy_mapping_t * mapping ) {
 free ( mapping -> issuer . ptr ) ;
 free ( mapping -> subject . ptr ) ;
 free ( mapping ) ;
 }


f_pyxeval(typval_T *argvars, typval_T *rettv)
{
# if defined(FEAT_PYTHON) && defined(FEAT_PYTHON3)
    init_pyxversion();
    if (p_pyx == 2)
	f_pyeval(argvars, rettv);
    else
	f_py3eval(argvars, rettv);
# elif defined(FEAT_PYTHON)
    f_pyeval(argvars, rettv);
# elif defined(FEAT_PYTHON3)
    f_py3eval(argvars, rettv);
# endif
}


completion_glob_pattern (string)
     char *string;
{
  register int c;
  char *send;
  int open;

  DECLARE_MBSTATE;

  open = 0;
  send = string + strlen (string);

  while (c = *string++)
    {
      switch (c)
	{
	case '?':
	case '*':
	  return (1);

	case '[':
	  open++;
	  continue;

	case ']':
	  if (open)
	    return (1);
	  continue;

	case '+':
	case '@':
	case '!':
	  if (*string == '(')	/*)*/
	    return (1);
	  continue;

	case '\\':
	  if (*string++ == 0)
	    return (0);
	}

      /* Advance one fewer byte than an entire multibyte character to
	 account for the auto-increment in the loop above. */
#ifdef HANDLE_MULTIBYTE
      string--;
      ADVANCE_CHAR_P (string, send - string);
      string++;
#else
      ADVANCE_CHAR_P (string, send - string);
#endif
    }
  return (0);
}


static void vmport_realizefn ( DeviceState * dev , Error * * errp ) {
 ISADevice * isadev = ISA_DEVICE ( dev ) ;
 VMPortState * s = VMPORT ( dev ) ;
 memory_region_init_io ( & s -> io , OBJECT ( s ) , & vmport_ops , s , "vmport" , 1 ) ;
 isa_register_ioport ( isadev , & s -> io , 0x5658 ) ;
 port_state = s ;
 vmport_register ( VMPORT_CMD_GETVERSION , vmport_cmd_get_version , NULL ) ;
 vmport_register ( VMPORT_CMD_GETRAMSIZE , vmport_cmd_ram_size , NULL ) ;
 }


static int SpoolssDeletePrinter_r ( tvbuff_t * tvb , int offset , packet_info * pinfo , proto_tree * tree , dcerpc_info * di , guint8 * drep _U_ ) {
 offset = dissect_nt_policy_hnd ( tvb , offset , pinfo , tree , di , drep , hf_hnd , NULL , NULL , FALSE , FALSE ) ;
 offset = dissect_doserror ( tvb , offset , pinfo , tree , di , drep , hf_rc , NULL ) ;
 return offset ;
 }


glob_vector (pat, dir, flags)
     char *pat;
     char *dir;
     int flags;
{
  DIR *d;
  register struct dirent *dp;
  struct globval *lastlink, *e, *dirlist;
  register struct globval *nextlink;
  register char *nextname, *npat, *subdir;
  unsigned int count;
  int lose, skip, ndirs, isdir, sdlen, add_current, patlen;
  register char **name_vector;
  register unsigned int i;
  int mflags;		/* Flags passed to strmatch (). */
  int pflags;		/* flags passed to sh_makepath () */
  int nalloca;
  struct globval *firstmalloc, *tmplink;
  char *convfn;

  lastlink = 0;
  count = lose = skip = add_current = 0;

  firstmalloc = 0;
  nalloca = 0;

  name_vector = NULL;

/*itrace("glob_vector: pat = `%s' dir = `%s' flags = 0x%x", pat, dir, flags);*/
  /* If PAT is empty, skip the loop, but return one (empty) filename. */
  if (pat == 0 || *pat == '\0')
    {
      if (glob_testdir (dir, 0) < 0)
	return ((char **) &glob_error_return);

      nextlink = (struct globval *)alloca (sizeof (struct globval));
      if (nextlink == NULL)
	return ((char **) NULL);

      nextlink->next = (struct globval *)0;
      nextname = (char *) malloc (1);
      if (nextname == 0)
	lose = 1;
      else
	{
	  lastlink = nextlink;
	  nextlink->name = nextname;
	  nextname[0] = '\0';
	  count = 1;
	}

      skip = 1;
    }

  patlen = (pat && *pat) ? strlen (pat) : 0;

  /* If the filename pattern (PAT) does not contain any globbing characters,
     we can dispense with reading the directory, and just see if there is
     a filename `DIR/PAT'.  If there is, and we can access it, just make the
     vector to return and bail immediately. */
  if (skip == 0 && glob_pattern_p (pat) == 0)
    {
      int dirlen;
      struct stat finfo;

      if (glob_testdir (dir, 0) < 0)
	return ((char **) &glob_error_return);

      dirlen = strlen (dir);
      nextname = (char *)malloc (dirlen + patlen + 2);
      npat = (char *)malloc (patlen + 1);
      if (nextname == 0 || npat == 0)
	{
	  FREE (nextname);
	  FREE (npat);
	  lose = 1;
	}
      else
	{
	  strcpy (npat, pat);
	  dequote_pathname (npat);

	  strcpy (nextname, dir);
	  nextname[dirlen++] = '/';
	  strcpy (nextname + dirlen, npat);

	  if (GLOB_TESTNAME (nextname) >= 0)
	    {
	      free (nextname);
	      nextlink = (struct globval *)alloca (sizeof (struct globval));
	      if (nextlink)
		{
		  nextlink->next = (struct globval *)0;
		  lastlink = nextlink;
		  nextlink->name = npat;
		  count = 1;
		}
	      else
		{
		  free (npat);
		  lose = 1;
		}
	    }
	  else
	    {
	      free (nextname);
	      free (npat);
	    }
	}

      skip = 1;
    }

  if (skip == 0)
    {
      /* Open the directory, punting immediately if we cannot.  If opendir
	 is not robust (i.e., it opens non-directories successfully), test
	 that DIR is a directory and punt if it's not. */
#if defined (OPENDIR_NOT_ROBUST)
      if (glob_testdir (dir, 0) < 0)
	return ((char **) &glob_error_return);
#endif

      d = opendir (dir);
      if (d == NULL)
	return ((char **) &glob_error_return);

      /* Compute the flags that will be passed to strmatch().  We don't
	 need to do this every time through the loop. */
      mflags = (noglob_dot_filenames ? FNM_PERIOD : 0) | FNM_PATHNAME;

#ifdef FNM_CASEFOLD
      if (glob_ignore_case)
	mflags |= FNM_CASEFOLD;
#endif

      if (extended_glob)
	mflags |= FNM_EXTMATCH;

      add_current = ((flags & (GX_ALLDIRS|GX_ADDCURDIR)) == (GX_ALLDIRS|GX_ADDCURDIR));

      /* Scan the directory, finding all names that match.
	 For each name that matches, allocate a struct globval
	 on the stack and store the name in it.
	 Chain those structs together; lastlink is the front of the chain.  */
      while (1)
	{
	  /* Make globbing interruptible in the shell. */
	  if (interrupt_state || terminating_signal)
	    {
	      lose = 1;
	      break;
	    }
	  else if (signal_is_pending (SIGINT))	/* XXX - make SIGINT traps responsive */
	    {
	      lose = 1;
	      break;
	    }

	  dp = readdir (d);
	  if (dp == NULL)
	    break;

	  /* If this directory entry is not to be used, try again. */
	  if (REAL_DIR_ENTRY (dp) == 0)
	    continue;

#if 0
	  if (dp->d_name == 0 || *dp->d_name == 0)
	    continue;
#endif

#if HANDLE_MULTIBYTE
	  if (MB_CUR_MAX > 1 && mbskipname (pat, dp->d_name, flags))
	    continue;
	  else
#endif
	  if (skipname (pat, dp->d_name, flags))
	    continue;

	  /* If we're only interested in directories, don't bother with files */
	  if (flags & (GX_MATCHDIRS|GX_ALLDIRS))
	    {
	      pflags = (flags & GX_ALLDIRS) ? MP_RMDOT : 0;
	      if (flags & GX_NULLDIR)
		pflags |= MP_IGNDOT;
	      subdir = sh_makepath (dir, dp->d_name, pflags);
	      isdir = glob_testdir (subdir, flags);
	      if (isdir < 0 && (flags & GX_MATCHDIRS))
		{
		  free (subdir);
		  continue;
		}
	    }

	  if (flags & GX_ALLDIRS)
	    {
	      if (isdir == 0)
		{
		  dirlist = finddirs (pat, subdir, (flags & ~GX_ADDCURDIR), &e, &ndirs);
		  if (dirlist == &finddirs_error_return)
		    {
		      free (subdir);
		      lose = 1;
		      break;
		    }
		  if (ndirs)		/* add recursive directories to list */
		    {
		      if (firstmalloc == 0)
		        firstmalloc = e;
		      e->next = lastlink;
		      lastlink = dirlist;
		      count += ndirs;
		    }
		}

	      /* XXX - should we even add this if it's not a directory? */
	      nextlink = (struct globval *) malloc (sizeof (struct globval));
	      if (firstmalloc == 0)
		firstmalloc = nextlink;
	      sdlen = strlen (subdir);
	      nextname = (char *) malloc (sdlen + 1);
	      if (nextlink == 0 || nextname == 0)
		{
		  FREE (nextlink);
		  FREE (nextname);
		  free (subdir);
		  lose = 1;
		  break;
		}
	      nextlink->next = lastlink;
	      lastlink = nextlink;
	      nextlink->name = nextname;
	      bcopy (subdir, nextname, sdlen + 1);
	      free (subdir);
	      ++count;
	      continue;
	    }
	  else if (flags & GX_MATCHDIRS)
	    free (subdir);

	  convfn = fnx_fromfs (dp->d_name, D_NAMLEN (dp));
	  if (strmatch (pat, convfn, mflags) != FNM_NOMATCH)
	    {
	      if (nalloca < ALLOCA_MAX)
		{
		  nextlink = (struct globval *) alloca (sizeof (struct globval));
		  nalloca += sizeof (struct globval);
		}
	      else
		{
		  nextlink = (struct globval *) malloc (sizeof (struct globval));
		  if (firstmalloc == 0)
		    firstmalloc = nextlink;
		}

	      nextname = (char *) malloc (D_NAMLEN (dp) + 1);
	      if (nextlink == 0 || nextname == 0)
		{
		  FREE (nextlink);
		  FREE (nextname);
		  lose = 1;
		  break;
		}
	      nextlink->next = lastlink;
	      lastlink = nextlink;
	      nextlink->name = nextname;
	      bcopy (dp->d_name, nextname, D_NAMLEN (dp) + 1);
	      ++count;
	    }
	}

      (void) closedir (d);
    }

  /* compat: if GX_ADDCURDIR, add the passed directory also.  Add an empty
     directory name as a placeholder if GX_NULLDIR (in which case the passed
     directory name is "."). */
  if (add_current)
    {
      sdlen = strlen (dir);
      nextname = (char *)malloc (sdlen + 1);
      nextlink = (struct globval *) malloc (sizeof (struct globval));
      if (nextlink == 0 || nextname == 0)
	{
	  FREE (nextlink);
	  FREE (nextname);
	  lose = 1;
	}
      else
	{
	  nextlink->name = nextname;
	  nextlink->next = lastlink;
	  lastlink = nextlink;
	  if (flags & GX_NULLDIR)
	    nextname[0] = '\0';
	  else
	    bcopy (dir, nextname, sdlen + 1);
	  ++count;
	}
    }

  if (lose == 0)
    {
      name_vector = (char **) malloc ((count + 1) * sizeof (char *));
      lose |= name_vector == NULL;
    }

  /* Have we run out of memory?	 */
  if (lose)
    {
      tmplink = 0;

      /* Here free the strings we have got.  */
      while (lastlink)
	{
	  /* Since we build the list in reverse order, the first N entries
	     will be allocated with malloc, if firstmalloc is set, from
	     lastlink to firstmalloc. */
	  if (firstmalloc)
	    {
	      if (lastlink == firstmalloc)
		firstmalloc = 0;
	      tmplink = lastlink;
	    }
	  else
	    tmplink = 0;
	  free (lastlink->name);
	  lastlink = lastlink->next;
	  FREE (tmplink);
	}

      /* Don't call QUIT; here; let higher layers deal with it. */

      return ((char **)NULL);
    }

  /* Copy the name pointers from the linked list into the vector.  */
  for (tmplink = lastlink, i = 0; i < count; ++i)
    {
      name_vector[i] = tmplink->name;
      tmplink = tmplink->next;
    }

  name_vector[count] = NULL;

  /* If we allocated some of the struct globvals, free them now. */
  if (firstmalloc)
    {
      tmplink = 0;
      while (lastlink)
	{
	  tmplink = lastlink;
	  if (lastlink == firstmalloc)
	    lastlink = firstmalloc = 0;
	  else
	    lastlink = lastlink->next;
	  free (tmplink);
	}
    }

  return (name_vector);
}


int RENAME(swri_resample)(ResampleContext *c, DELEM *dst, const DELEM *src, int *consumed, int src_size, int dst_size, int update_ctx){ int dst_index, i; int index= c->index; int frac= c->frac; int dst_incr_frac= c->dst_incr % c->src_incr; int dst_incr= c->dst_incr / c->src_incr; av_assert1(c->filter_shift == FILTER_SHIFT); av_assert1(c->felem_size == sizeof(FELEM)); if (c->filter_length == 1 && c->phase_shift == 0) { int64_t index2= (1LL<<32)*c->frac/c->src_incr + (1LL<<32)*index; int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr; int new_size = (src_size * (int64_t)c->src_incr - frac + c->dst_incr - 1) / c->dst_incr; dst_size= FFMIN(dst_size, new_size); for(dst_index=0; dst_index < dst_size; dst_index++){ dst[dst_index] = src[index2>>32]; index2 += incr; } index += dst_index * dst_incr; index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr; frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr; av_assert2(index >= 0); *consumed= index; index = 0; } else if (index >= 0) { int64_t end_index = (1LL + src_size - c->filter_length) << c->phase_shift; int64_t delta_frac = (end_index - index) * c->src_incr - c->frac; int delta_n = (delta_frac + c->dst_incr - 1) / c->dst_incr; int n = FFMIN(dst_size, delta_n); int sample_index; if (!c->linear) { sample_index = index >> c->phase_shift; index &= c->phase_mask; for (dst_index = 0; dst_index < n; dst_index++) { FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index; #ifdef COMMON_CORE COMMON_CORE #else FELEM2 val=0; for (i = 0; i < c->filter_length; i++) { val += src[sample_index + i] * (FELEM2)filter[i]; } OUT(dst[dst_index], val); #endif frac += dst_incr_frac; index += dst_incr; if (frac >= c->src_incr) { frac -= c->src_incr; index++; } sample_index += index >> c->phase_shift; index &= c->phase_mask; } } else { sample_index = index >> c->phase_shift; index &= c->phase_mask; for (dst_index = 0; dst_index < n; dst_index++) { FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index; FELEM2 val=0, v2 = 0; #ifdef LINEAR_CORE LINEAR_CORE #else for (i = 0; i < c->filter_length; i++) { val += src[sample_index + i] * (FELEM2)filter[i]; v2 += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc]; } #endif val += (v2 - val) * (FELEML) frac / c->src_incr; OUT(dst[dst_index], val); frac += dst_incr_frac; index += dst_incr; if (frac >= c->src_incr) { frac -= c->src_incr; index++; } sample_index += index >> c->phase_shift; index &= c->phase_mask; } } *consumed = sample_index; } else { int sample_index = 0; for(dst_index=0; dst_index < dst_size; dst_index++){ FELEM *filter; FELEM2 val=0; sample_index += index >> c->phase_shift; index &= c->phase_mask; filter = ((FELEM*)c->filter_bank) + c->filter_alloc*index; if(sample_index + c->filter_length > src_size || -sample_index >= src_size){ break; }else if(sample_index < 0){ for(i=0; i<c->filter_length; i++) val += src[FFABS(sample_index + i)] * (FELEM2)filter[i]; OUT(dst[dst_index], val); }else if(c->linear){ FELEM2 v2=0; #ifdef LINEAR_CORE LINEAR_CORE #else for(i=0; i<c->filter_length; i++){ val += src[sample_index + i] * (FELEM2)filter[i]; v2 += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc]; } #endif val+=(v2-val)*(FELEML)frac / c->src_incr; OUT(dst[dst_index], val); }else{ #ifdef COMMON_CORE COMMON_CORE #else for(i=0; i<c->filter_length; i++){ val += src[sample_index + i] * (FELEM2)filter[i]; } OUT(dst[dst_index], val); #endif } frac += dst_incr_frac; index += dst_incr; if(frac >= c->src_incr){ frac -= c->src_incr; index++; } } *consumed= FFMAX(sample_index, 0); index += FFMIN(sample_index, 0) << c->phase_shift; } if(update_ctx){ c->frac= frac; c->index= index; } return dst_index; }


static int ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge)
{
	size_t size;
	Stream_Read_UINT8(s, challenge->RespType);
	Stream_Read_UINT8(s, challenge->HiRespType);
	Stream_Read_UINT16(s, challenge->Reserved1);
	Stream_Read_UINT32(s, challenge->Reserved2);
	Stream_Read(s, challenge->Timestamp, 8);
	Stream_Read(s, challenge->ClientChallenge, 8);
	Stream_Read_UINT32(s, challenge->Reserved3);
	size = Stream_Length(s) - Stream_GetPosition(s);

	if (size > UINT32_MAX)
		return -1;

	challenge->cbAvPairs = size;
	challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs);

	if (!challenge->AvPairs)
		return -1;

	Stream_Read(s, challenge->AvPairs, size);
	return 1;
}


int ntlm_read_ntlm_v2_response(wStream* s, NTLMv2_RESPONSE* response)
{
	Stream_Read(s, response->Response, 16);
	return ntlm_read_ntlm_v2_client_challenge(s, &(response->Challenge));
}


static UBool _addAttributeToList ( AttributeListEntry * * first , AttributeListEntry * attr ) {
 UBool bAdded = TRUE ;
 if ( * first == NULL ) {
 attr -> next = NULL ;
 * first = attr ;
 }
 else {
 AttributeListEntry * prev , * cur ;
 int32_t cmp ;
 prev = NULL ;
 cur = * first ;
 while ( TRUE ) {
 if ( cur == NULL ) {
 prev -> next = attr ;
 attr -> next = NULL ;
 break ;
 }
 cmp = uprv_compareInvCharsAsAscii ( attr -> attribute , cur -> attribute ) ;
 if ( cmp < 0 ) {
 if ( prev == NULL ) {
 * first = attr ;
 }
 else {
 prev -> next = attr ;
 }
 attr -> next = cur ;
 break ;
 }
 if ( cmp == 0 ) {
 bAdded = FALSE ;
 break ;
 }
 prev = cur ;
 cur = cur -> next ;
 }
 }
 return bAdded ;
 }


static int write_f(BlockBackend *blk, int argc, char **argv) { struct timeval t1, t2; bool Cflag = false, qflag = false, bflag = false; bool Pflag = false, zflag = false, cflag = false; int flags = 0; int c, cnt; char *buf = NULL; int64_t offset; int64_t count; /* Some compilers get confused and warn if this is not initialized. */ int64_t total = 0; int pattern = 0xcd; while ((c = getopt(argc, argv, "bcCfpP:quz")) != -1) { switch (c) { case 'b': bflag = true; break; case 'c': cflag = true; break; case 'C': Cflag = true; break; case 'f': flags |= BDRV_REQ_FUA; break; case 'p': /* Ignored for backwards compatibility */ break; case 'P': Pflag = true; pattern = parse_pattern(optarg); if (pattern < 0) { return 0; } break; case 'q': qflag = true; break; case 'u': flags |= BDRV_REQ_MAY_UNMAP; break; case 'z': zflag = true; break; default: return qemuio_command_usage(&write_cmd); } } if (optind != argc - 2) { return qemuio_command_usage(&write_cmd); } if (bflag && zflag) { printf("-b and -z cannot be specified at the same time\n"); return 0; } if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) { printf("-f and -b or -c cannot be specified at the same time\n"); return 0; } if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) { printf("-u requires -z to be specified\n"); return 0; } if (zflag && Pflag) { printf("-z and -P cannot be specified at the same time\n"); return 0; } offset = cvtnum(argv[optind]); if (offset < 0) { print_cvtnum_err(offset, argv[optind]); return 0; } optind++; count = cvtnum(argv[optind]); if (count < 0) { print_cvtnum_err(count, argv[optind]); return 0; } else if (count > SIZE_MAX) { printf("length cannot exceed %" PRIu64 ", given %s\n", (uint64_t) SIZE_MAX, argv[optind]); return 0; } if (bflag || cflag) { if (offset & 0x1ff) { printf("offset %" PRId64 " is not sector aligned\n", offset); return 0; } if (count & 0x1ff) { printf("count %"PRId64" is not sector aligned\n", count); return 0; } } if (!zflag) { buf = qemu_io_alloc(blk, count, pattern); } gettimeofday(&t1, NULL); if (bflag) { cnt = do_save_vmstate(blk, buf, offset, count, &total); } else if (zflag) { cnt = do_co_pwrite_zeroes(blk, offset, count, flags, &total); } else if (cflag) { cnt = do_write_compressed(blk, buf, offset, count, &total); } else { cnt = do_pwrite(blk, buf, offset, count, flags, &total); } gettimeofday(&t2, NULL); if (cnt < 0) { printf("write failed: %s\n", strerror(-cnt)); goto out; } if (qflag) { goto out; } /* Finally, report back -- -C gives a parsable format */ t2 = tsub(t2, t1); print_report("wrote", &t2, offset, count, total, cnt, Cflag); out: if (!zflag) { qemu_io_free(buf); } return 0; }


static void gen_mtc0(DisasContext *ctx, TCGv arg, int reg, int sel) { const char *rn = "invalid"; if (sel != 0) check_insn(ctx, ISA_MIPS32); if (ctx->tb->cflags & CF_USE_ICOUNT) { gen_io_start(); } switch (reg) { case 0: switch (sel) { case 0: gen_helper_mtc0_index(cpu_env, arg); rn = "Index"; case 1: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_mvpcontrol(cpu_env, arg); rn = "MVPControl"; CP0_CHECK(ctx->insn_flags & ASE_MT); /* ignored */ rn = "MVPConf0"; CP0_CHECK(ctx->insn_flags & ASE_MT); /* ignored */ rn = "MVPConf1"; CP0_CHECK(ctx->vp); /* ignored */ rn = "VPControl"; default: goto cp0_unimplemented; } case 1: switch (sel) { case 0: /* ignored */ rn = "Random"; case 1: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_vpecontrol(cpu_env, arg); rn = "VPEControl"; CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_vpeconf0(cpu_env, arg); rn = "VPEConf0"; CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_vpeconf1(cpu_env, arg); rn = "VPEConf1"; CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_yqmask(cpu_env, arg); rn = "YQMask"; case 5: CP0_CHECK(ctx->insn_flags & ASE_MT); tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPESchedule)); rn = "VPESchedule"; case 6: CP0_CHECK(ctx->insn_flags & ASE_MT); tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_VPEScheFBack)); rn = "VPEScheFBack"; case 7: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_vpeopt(cpu_env, arg); rn = "VPEOpt"; default: goto cp0_unimplemented; } switch (sel) { case 0: gen_helper_mtc0_entrylo0(cpu_env, arg); rn = "EntryLo0"; case 1: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tcstatus(cpu_env, arg); rn = "TCStatus"; CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tcbind(cpu_env, arg); rn = "TCBind"; CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tcrestart(cpu_env, arg); rn = "TCRestart"; CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tchalt(cpu_env, arg); rn = "TCHalt"; case 5: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tccontext(cpu_env, arg); rn = "TCContext"; case 6: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tcschedule(cpu_env, arg); rn = "TCSchedule"; case 7: CP0_CHECK(ctx->insn_flags & ASE_MT); gen_helper_mtc0_tcschefback(cpu_env, arg); rn = "TCScheFBack"; default: goto cp0_unimplemented; } switch (sel) { case 0: gen_helper_mtc0_entrylo1(cpu_env, arg); rn = "EntryLo1"; case 1: CP0_CHECK(ctx->vp); /* ignored */ rn = "GlobalNumber"; default: goto cp0_unimplemented; } switch (sel) { case 0: gen_helper_mtc0_context(cpu_env, arg); rn = "Context"; case 1: // gen_helper_mtc0_contextconfig(cpu_env, arg); /* SmartMIPS ASE */ rn = "ContextConfig"; goto cp0_unimplemented; CP0_CHECK(ctx->ulri); tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, active_tc.CP0_UserLocal)); rn = "UserLocal"; default: goto cp0_unimplemented; } case 5: switch (sel) { case 0: gen_helper_mtc0_pagemask(cpu_env, arg); rn = "PageMask"; case 1: check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_pagegrain(cpu_env, arg); rn = "PageGrain"; ctx->bstate = BS_STOP; default: goto cp0_unimplemented; } case 6: switch (sel) { case 0: gen_helper_mtc0_wired(cpu_env, arg); rn = "Wired"; case 1: check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_srsconf0(cpu_env, arg); rn = "SRSConf0"; check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_srsconf1(cpu_env, arg); rn = "SRSConf1"; check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_srsconf2(cpu_env, arg); rn = "SRSConf2"; check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_srsconf3(cpu_env, arg); rn = "SRSConf3"; case 5: check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_srsconf4(cpu_env, arg); rn = "SRSConf4"; default: goto cp0_unimplemented; } case 7: switch (sel) { case 0: check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_hwrena(cpu_env, arg); ctx->bstate = BS_STOP; rn = "HWREna"; default: goto cp0_unimplemented; } case 8: switch (sel) { case 0: /* ignored */ rn = "BadVAddr"; case 1: /* ignored */ rn = "BadInstr"; /* ignored */ rn = "BadInstrP"; default: goto cp0_unimplemented; } case 9: switch (sel) { case 0: gen_helper_mtc0_count(cpu_env, arg); rn = "Count"; /* 6,7 are implementation dependent */ default: goto cp0_unimplemented; } case 10: switch (sel) { case 0: gen_helper_mtc0_entryhi(cpu_env, arg); rn = "EntryHi"; default: goto cp0_unimplemented; } case 11: switch (sel) { case 0: gen_helper_mtc0_compare(cpu_env, arg); rn = "Compare"; /* 6,7 are implementation dependent */ default: goto cp0_unimplemented; } case 12: switch (sel) { case 0: save_cpu_state(ctx, 1); gen_helper_mtc0_status(cpu_env, arg); /* BS_STOP isn't good enough here, hflags may have changed. */ gen_save_pc(ctx->pc + 4); ctx->bstate = BS_EXCP; rn = "Status"; case 1: check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_intctl(cpu_env, arg); /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; rn = "IntCtl"; check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_srsctl(cpu_env, arg); /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; rn = "SRSCtl"; check_insn(ctx, ISA_MIPS32R2); gen_mtc0_store32(arg, offsetof(CPUMIPSState, CP0_SRSMap)); /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; rn = "SRSMap"; default: goto cp0_unimplemented; } case 13: switch (sel) { case 0: save_cpu_state(ctx, 1); gen_helper_mtc0_cause(cpu_env, arg); rn = "Cause"; default: goto cp0_unimplemented; } case 14: switch (sel) { case 0: tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_EPC)); rn = "EPC"; default: goto cp0_unimplemented; } case 15: switch (sel) { case 0: /* ignored */ rn = "PRid"; case 1: check_insn(ctx, ISA_MIPS32R2); gen_helper_mtc0_ebase(cpu_env, arg); rn = "EBase"; default: goto cp0_unimplemented; } case 16: switch (sel) { case 0: gen_helper_mtc0_config0(cpu_env, arg); rn = "Config"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; case 1: /* ignored, read only */ rn = "Config1"; gen_helper_mtc0_config2(cpu_env, arg); rn = "Config2"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; gen_helper_mtc0_config3(cpu_env, arg); rn = "Config3"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; gen_helper_mtc0_config4(cpu_env, arg); rn = "Config4"; ctx->bstate = BS_STOP; case 5: gen_helper_mtc0_config5(cpu_env, arg); rn = "Config5"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; /* 6,7 are implementation dependent */ case 6: /* ignored */ rn = "Config6"; case 7: /* ignored */ rn = "Config7"; default: rn = "Invalid config selector"; goto cp0_unimplemented; } case 17: switch (sel) { case 0: gen_helper_mtc0_lladdr(cpu_env, arg); rn = "LLAddr"; case 1: CP0_CHECK(ctx->mrp); gen_helper_mtc0_maar(cpu_env, arg); rn = "MAAR"; CP0_CHECK(ctx->mrp); gen_helper_mtc0_maari(cpu_env, arg); rn = "MAARI"; default: goto cp0_unimplemented; } case 18: switch (sel) { case 0 ... 7: gen_helper_0e1i(mtc0_watchlo, arg, sel); rn = "WatchLo"; default: goto cp0_unimplemented; } case 19: switch (sel) { case 0 ... 7: gen_helper_0e1i(mtc0_watchhi, arg, sel); rn = "WatchHi"; default: goto cp0_unimplemented; } case 20: switch (sel) { case 0: #if defined(TARGET_MIPS64) check_insn(ctx, ISA_MIPS3); gen_helper_mtc0_xcontext(cpu_env, arg); rn = "XContext"; #endif default: goto cp0_unimplemented; } case 21: /* Officially reserved, but sel 0 is used for R1x000 framemask */ CP0_CHECK(!(ctx->insn_flags & ISA_MIPS32R6)); switch (sel) { case 0: gen_helper_mtc0_framemask(cpu_env, arg); rn = "Framemask"; default: goto cp0_unimplemented; } case 22: /* ignored */ rn = "Diagnostic"; /* implementation dependent */ case 23: switch (sel) { case 0: gen_helper_mtc0_debug(cpu_env, arg); /* EJTAG support */ /* BS_STOP isn't good enough here, hflags may have changed. */ gen_save_pc(ctx->pc + 4); ctx->bstate = BS_EXCP; rn = "Debug"; case 1: // gen_helper_mtc0_tracecontrol(cpu_env, arg); /* PDtrace support */ rn = "TraceControl"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; goto cp0_unimplemented; // gen_helper_mtc0_tracecontrol2(cpu_env, arg); /* PDtrace support */ rn = "TraceControl2"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; goto cp0_unimplemented; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; // gen_helper_mtc0_usertracedata(cpu_env, arg); /* PDtrace support */ rn = "UserTraceData"; /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; goto cp0_unimplemented; // gen_helper_mtc0_tracebpc(cpu_env, arg); /* PDtrace support */ /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; rn = "TraceBPC"; goto cp0_unimplemented; default: goto cp0_unimplemented; } case 24: switch (sel) { case 0: /* EJTAG support */ tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_DEPC)); rn = "DEPC"; default: goto cp0_unimplemented; } case 25: switch (sel) { case 0: gen_helper_mtc0_performance0(cpu_env, arg); rn = "Performance0"; case 1: // gen_helper_mtc0_performance1(arg); rn = "Performance1"; goto cp0_unimplemented; // gen_helper_mtc0_performance2(arg); rn = "Performance2"; goto cp0_unimplemented; // gen_helper_mtc0_performance3(arg); rn = "Performance3"; goto cp0_unimplemented; // gen_helper_mtc0_performance4(arg); rn = "Performance4"; goto cp0_unimplemented; case 5: // gen_helper_mtc0_performance5(arg); rn = "Performance5"; goto cp0_unimplemented; case 6: // gen_helper_mtc0_performance6(arg); rn = "Performance6"; goto cp0_unimplemented; case 7: // gen_helper_mtc0_performance7(arg); rn = "Performance7"; goto cp0_unimplemented; default: goto cp0_unimplemented; } case 26: switch (sel) { case 0: gen_helper_mtc0_errctl(cpu_env, arg); ctx->bstate = BS_STOP; rn = "ErrCtl"; default: goto cp0_unimplemented; } case 27: switch (sel) { case 0 ... 3: /* ignored */ rn = "CacheErr"; default: goto cp0_unimplemented; } case 28: switch (sel) { case 0: case 6: gen_helper_mtc0_taglo(cpu_env, arg); rn = "TagLo"; case 1: case 5: case 7: gen_helper_mtc0_datalo(cpu_env, arg); rn = "DataLo"; default: goto cp0_unimplemented; } case 29: switch (sel) { case 0: case 6: gen_helper_mtc0_taghi(cpu_env, arg); rn = "TagHi"; case 1: case 5: case 7: gen_helper_mtc0_datahi(cpu_env, arg); rn = "DataHi"; default: rn = "invalid sel"; goto cp0_unimplemented; } case 30: switch (sel) { case 0: tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_ErrorEPC)); rn = "ErrorEPC"; default: goto cp0_unimplemented; } case 31: switch (sel) { case 0: /* EJTAG support */ gen_mtc0_store32(arg, offsetof(CPUMIPSState, CP0_DESAVE)); rn = "DESAVE"; case 2 ... 7: CP0_CHECK(ctx->kscrexist & (1 << sel)); tcg_gen_st_tl(arg, cpu_env, offsetof(CPUMIPSState, CP0_KScratch[sel-2])); rn = "KScratch"; default: goto cp0_unimplemented; } /* Stop translation as we may have switched the execution mode */ ctx->bstate = BS_STOP; default: goto cp0_unimplemented; } trace_mips_translate_c0("mtc0", rn, reg, sel); /* For simplicity assume that all writes can cause interrupts. */ if (ctx->tb->cflags & CF_USE_ICOUNT) { gen_io_end(); ctx->bstate = BS_STOP; } return; cp0_unimplemented: qemu_log_mask(LOG_UNIMP, "mtc0 %s (reg %d sel %d)\n", rn, reg, sel); }


TEST_P(Http2CodecImplTest, Invalid103) {
  initialize();

  TestRequestHeaderMapImpl request_headers;
  HttpTestUtility::addDefaultHeaders(request_headers);
  EXPECT_CALL(request_decoder_, decodeHeaders_(_, true));
  request_encoder_->encodeHeaders(request_headers, true);

  TestResponseHeaderMapImpl continue_headers{{":status", "100"}};
  EXPECT_CALL(response_decoder_, decode100ContinueHeaders_(_));
  response_encoder_->encode100ContinueHeaders(continue_headers);

  TestResponseHeaderMapImpl early_hint_headers{{":status", "103"}};
  EXPECT_CALL(response_decoder_, decodeHeaders_(_, false));
  response_encoder_->encodeHeaders(early_hint_headers, false);

  EXPECT_THROW_WITH_MESSAGE(response_encoder_->encodeHeaders(early_hint_headers, false),
                            ClientCodecError, "Unexpected 'trailers' with no end stream.");
  EXPECT_EQ(1, stats_store_.counter("http2.too_many_header_frames").value());
}


static int decode_p_frame(FourXContext *f, const uint8_t *buf, int length){ int x, y; const int width= f->avctx->width; const int height= f->avctx->height; uint16_t *src= (uint16_t*)f->last_picture.data[0]; uint16_t *dst= (uint16_t*)f->current_picture.data[0]; const int stride= f->current_picture.linesize[0]>>1; unsigned int bitstream_size, bytestream_size, wordstream_size, extra; if(f->version>1){ extra=20; bitstream_size= AV_RL32(buf+8); wordstream_size= AV_RL32(buf+12); bytestream_size= AV_RL32(buf+16); }else{ extra=0; bitstream_size = AV_RL16(buf-4); wordstream_size= AV_RL16(buf-2); bytestream_size= FFMAX(length - bitstream_size - wordstream_size, 0); } if(bitstream_size+ bytestream_size+ wordstream_size + extra != length || bitstream_size > (1<<26) || bytestream_size > (1<<26) || wordstream_size > (1<<26) ){ av_log(f->avctx, AV_LOG_ERROR, "lengths %d %d %d %d\n", bitstream_size, bytestream_size, wordstream_size, bitstream_size+ bytestream_size+ wordstream_size - length); return -1; } av_fast_malloc(&f->bitstream_buffer, &f->bitstream_buffer_size, bitstream_size + FF_INPUT_BUFFER_PADDING_SIZE); if (!f->bitstream_buffer) return AVERROR(ENOMEM); f->dsp.bswap_buf(f->bitstream_buffer, (const uint32_t*)(buf + extra), bitstream_size/4); memset((uint8_t*)f->bitstream_buffer + bitstream_size, 0, FF_INPUT_BUFFER_PADDING_SIZE); init_get_bits(&f->gb, f->bitstream_buffer, 8*bitstream_size); f->wordstream= (const uint16_t*)(buf + extra + bitstream_size); f->bytestream= buf + extra + bitstream_size + wordstream_size; init_mv(f); for(y=0; y<height; y+=8){ for(x=0; x<width; x+=8){ decode_p_block(f, dst + x, src + x, 3, 3, stride); } src += 8*stride; dst += 8*stride; } if( bitstream_size != (get_bits_count(&f->gb)+31)/32*4 || (((const char*)f->wordstream - (const char*)buf + 2)&~2) != extra + bitstream_size + wordstream_size || (((const char*)f->bytestream - (const char*)buf + 3)&~3) != extra + bitstream_size + wordstream_size + bytestream_size) av_log(f->avctx, AV_LOG_ERROR, " %d %td %td bytes left\n", bitstream_size - (get_bits_count(&f->gb)+31)/32*4, -(((const char*)f->bytestream - (const char*)buf + 3)&~3) + (extra + bitstream_size + wordstream_size + bytestream_size), -(((const char*)f->wordstream - (const char*)buf + 2)&~2) + (extra + bitstream_size + wordstream_size) ); return 0; }


  static CodecStats& atomicGet(AtomicPtr& ptr, Stats::Scope& scope) {
    return *ptr.get([&scope]() -> CodecStats* {
      return new CodecStats{ALL_HTTP2_CODEC_STATS(POOL_COUNTER_PREFIX(scope, "http2."))};
    });
  }


inline static void _slurm_rpc_checkpoint ( slurm_msg_t * msg ) {
 int error_code = SLURM_SUCCESS ;
 DEF_TIMERS ;
 checkpoint_msg_t * ckpt_ptr = ( checkpoint_msg_t * ) msg -> data ;
 slurmctld_lock_t job_write_lock = {
 NO_LOCK , WRITE_LOCK , READ_LOCK , NO_LOCK , READ_LOCK }
 ;
 uid_t uid = g_slurm_auth_get_uid ( msg -> auth_cred , slurmctld_config . auth_info ) ;
 char * op ;
 START_TIMER ;
 switch ( ckpt_ptr -> op ) {
 case CHECK_ABLE : op = "able" ;
 break ;
 case CHECK_CREATE : op = "create" ;
 break ;
 case CHECK_DISABLE : op = "disable" ;
 break ;
 case CHECK_ENABLE : op = "enable" ;
 break ;
 case CHECK_ERROR : op = "error" ;
 break ;
 case CHECK_REQUEUE : op = "requeue" ;
 break ;
 case CHECK_RESTART : op = "restart" ;
 break ;
 case CHECK_VACATE : op = "vacate" ;
 break ;
 default : op = "unknown" ;
 }
 debug2 ( "Processing RPC: REQUEST_CHECKPOINT(%s) from uid=%u" , op , ( unsigned int ) uid ) ;
 lock_slurmctld ( job_write_lock ) ;
 if ( ckpt_ptr -> op == CHECK_RESTART ) {
 error_code = job_restart ( ckpt_ptr , uid , msg -> conn_fd , msg -> protocol_version ) ;
 }
 else if ( ckpt_ptr -> step_id == SLURM_BATCH_SCRIPT ) {
 error_code = job_checkpoint ( ckpt_ptr , uid , msg -> conn_fd , msg -> protocol_version ) ;
 }
 else {
 error_code = job_step_checkpoint ( ckpt_ptr , uid , msg -> conn_fd , msg -> protocol_version ) ;
 }
 unlock_slurmctld ( job_write_lock ) ;
 END_TIMER2 ( "_slurm_rpc_checkpoint" ) ;
 if ( error_code ) {
 if ( ckpt_ptr -> step_id == SLURM_BATCH_SCRIPT ) {
 info ( "_slurm_rpc_checkpoint %s %u: %s" , op , ckpt_ptr -> job_id , slurm_strerror ( error_code ) ) ;
 }
 else {
 info ( "_slurm_rpc_checkpoint %s %u.%u: %s" , op , ckpt_ptr -> job_id , ckpt_ptr -> step_id , slurm_strerror ( error_code ) ) ;
 }
 }
 else {
 if ( ckpt_ptr -> step_id == SLURM_BATCH_SCRIPT ) {
 info ( "_slurm_rpc_checkpoint %s for %u %s" , op , ckpt_ptr -> job_id , TIME_STR ) ;
 }
 else {
 info ( "_slurm_rpc_checkpoint %s for %u.%u %s" , op , ckpt_ptr -> job_id , ckpt_ptr -> step_id , TIME_STR ) ;
 }
 if ( ( ckpt_ptr -> op != CHECK_ABLE ) && ( ckpt_ptr -> op != CHECK_ERROR ) ) {
 schedule_job_save ( ) ;
 }
 }
 }


void ConnectionImpl::StreamImpl::encodeData(Buffer::Instance& data, bool end_stream) {
  ASSERT(!local_end_stream_);
  local_end_stream_ = end_stream;
  pending_send_data_.move(data);
  if (data_deferred_) {
    int rc = nghttp2_session_resume_data(parent_.session_, stream_id_);
    ASSERT(rc == 0);

    data_deferred_ = false;
  }

  parent_.sendPendingFrames();
}


static void x86_cpu_initfn(Object *obj) { CPUState *cs = CPU(obj); X86CPU *cpu = X86_CPU(obj); X86CPUClass *xcc = X86_CPU_GET_CLASS(obj); CPUX86State *env = &cpu->env; FeatureWord w; cs->env_ptr = env; cpu_exec_init(cs, &error_abort); object_property_add(obj, "family", "int", x86_cpuid_version_get_family, x86_cpuid_version_set_family, NULL, NULL, NULL); object_property_add(obj, "model", "int", x86_cpuid_version_get_model, x86_cpuid_version_set_model, NULL, NULL, NULL); object_property_add(obj, "stepping", "int", x86_cpuid_version_get_stepping, x86_cpuid_version_set_stepping, NULL, NULL, NULL); object_property_add_str(obj, "vendor", x86_cpuid_get_vendor, x86_cpuid_set_vendor, NULL); object_property_add_str(obj, "model-id", x86_cpuid_get_model_id, x86_cpuid_set_model_id, NULL); object_property_add(obj, "tsc-frequency", "int", x86_cpuid_get_tsc_freq, x86_cpuid_set_tsc_freq, NULL, NULL, NULL); object_property_add(obj, "apic-id", "int", x86_cpuid_get_apic_id, x86_cpuid_set_apic_id, NULL, NULL, NULL); object_property_add(obj, "feature-words", "X86CPUFeatureWordInfo", x86_cpu_get_feature_words, NULL, NULL, (void *)env->features, NULL); object_property_add(obj, "filtered-features", "X86CPUFeatureWordInfo", x86_cpu_get_feature_words, NULL, NULL, (void *)cpu->filtered_features, NULL); cpu->hyperv_spinlock_attempts = HYPERV_SPINLOCK_NEVER_RETRY; #ifndef CONFIG_USER_ONLY /* Any code creating new X86CPU objects have to set apic-id explicitly */ cpu->apic_id = -1; #endif for (w = 0; w < FEATURE_WORDS; w++) { int bitnr; for (bitnr = 0; bitnr < 32; bitnr++) { x86_cpu_register_feature_bit_props(cpu, w, bitnr); } } x86_cpu_load_def(cpu, xcc->cpu_def, &error_abort); }


TEST_P(Http2CodecImplTest, TrailingHeadersLargeBody) {
  initialize();

  // Buffer server data so we can make sure we don't get any window updates.
  ON_CALL(client_connection_, write(_, _))
      .WillByDefault(
          Invoke([&](Buffer::Instance& data, bool) -> void { server_wrapper_.buffer_.add(data); }));

  TestRequestHeaderMapImpl request_headers;
  HttpTestUtility::addDefaultHeaders(request_headers);
  EXPECT_CALL(request_decoder_, decodeHeaders_(_, false));
  request_encoder_->encodeHeaders(request_headers, false);
  EXPECT_CALL(request_decoder_, decodeData(_, false)).Times(AtLeast(1));
  Buffer::OwnedImpl body(std::string(1024 * 1024, 'a'));
  request_encoder_->encodeData(body, false);
  EXPECT_CALL(request_decoder_, decodeTrailers_(_));
  request_encoder_->encodeTrailers(TestRequestTrailerMapImpl{{"trailing", "header"}});

  // Flush pending data.
  setupDefaultConnectionMocks();
  auto status = server_wrapper_.dispatch(Buffer::OwnedImpl(), *server_);
  EXPECT_TRUE(status.ok());

  TestResponseHeaderMapImpl response_headers{{":status", "200"}};
  EXPECT_CALL(response_decoder_, decodeHeaders_(_, false));
  response_encoder_->encodeHeaders(response_headers, false);
  EXPECT_CALL(response_decoder_, decodeData(_, false));
  Buffer::OwnedImpl world("world");
  response_encoder_->encodeData(world, false);
  EXPECT_CALL(response_decoder_, decodeTrailers_(_));
  response_encoder_->encodeTrailers(TestResponseTrailerMapImpl{{"trailing", "header"}});
}


static av_cold int init(AVFilterContext *ctx, const char *args0) { PanContext *const pan = ctx->priv; char *arg, *arg0, *tokenizer, *args = av_strdup(args0); int out_ch_id, in_ch_id, len, named, ret; int nb_in_channels[2] = { 0, 0 }; // number of unnamed and named input channels double gain; if (!args0) { av_log(ctx, AV_LOG_ERROR, "pan filter needs a channel layout and a set " "of channels definitions as parameter\n"); return AVERROR(EINVAL); } if (!args) return AVERROR(ENOMEM); arg = av_strtok(args, ":", &tokenizer); ret = ff_parse_channel_layout(&pan->out_channel_layout, arg, ctx); if (ret < 0) return ret; pan->nb_output_channels = av_get_channel_layout_nb_channels(pan->out_channel_layout); /* parse channel specifications */ while ((arg = arg0 = av_strtok(NULL, ":", &tokenizer))) { /* channel name */ if (parse_channel_name(&arg, &out_ch_id, &named)) { av_log(ctx, AV_LOG_ERROR, "Expected out channel name, got \"%.8s\"\n", arg); return AVERROR(EINVAL); } if (named) { if (!((pan->out_channel_layout >> out_ch_id) & 1)) { av_log(ctx, AV_LOG_ERROR, "Channel \"%.8s\" does not exist in the chosen layout\n", arg0); return AVERROR(EINVAL); } /* get the channel number in the output channel layout: * out_channel_layout & ((1 << out_ch_id) - 1) are all the * channels that come before out_ch_id, * so their count is the index of out_ch_id */ out_ch_id = av_get_channel_layout_nb_channels(pan->out_channel_layout & (((int64_t)1 << out_ch_id) - 1)); } if (out_ch_id < 0 || out_ch_id >= pan->nb_output_channels) { av_log(ctx, AV_LOG_ERROR, "Invalid out channel name \"%.8s\"\n", arg0); return AVERROR(EINVAL); } if (*arg == '=') { arg++; } else if (*arg == '<') { pan->need_renorm |= (int64_t)1 << out_ch_id; arg++; } else { av_log(ctx, AV_LOG_ERROR, "Syntax error after channel name in \"%.8s\"\n", arg0); return AVERROR(EINVAL); } /* gains */ while (1) { gain = 1; if (sscanf(arg, " %lf %n* %n", &gain, &len, &len)) arg += len; if (parse_channel_name(&arg, &in_ch_id, &named)){ av_log(ctx, AV_LOG_ERROR, "Expected in channel name, got \"%.8s\"\n", arg); return AVERROR(EINVAL); } nb_in_channels[named]++; if (nb_in_channels[!named]) { av_log(ctx, AV_LOG_ERROR, "Can not mix named and numbered channels\n"); return AVERROR(EINVAL); } pan->gain[out_ch_id][in_ch_id] = gain; if (!*arg) break; if (*arg != '+') { av_log(ctx, AV_LOG_ERROR, "Syntax error near \"%.8s\"\n", arg); return AVERROR(EINVAL); } arg++; skip_spaces(&arg); } } pan->need_renumber = !!nb_in_channels[1]; av_free(args); return 0; }


static Int decGetDigits ( Unit * uar , Int len ) {
 Unit * up = uar + ( len - 1 ) ;
 Int digits = ( len - 1 ) * DECDPUN + 1 ;
 # if DECDPUN > 4 uInt const * pow ;
 # endif # if DECCHECK if ( len < 1 ) printf ( "decGetDigits called with len<1 [%ld]\n" , ( LI ) len ) ;
 # endif for ( ;
 up >= uar ;
 up -- ) {
 if ( * up == 0 ) {
 if ( digits == 1 ) break ;
 digits -= DECDPUN ;
 continue ;
 }
 # if DECDPUN > 1 if ( * up < 10 ) break ;
 digits ++ ;
 # if DECDPUN > 2 if ( * up < 100 ) break ;
 digits ++ ;
 # if DECDPUN > 3 if ( * up < 1000 ) break ;
 digits ++ ;
 # if DECDPUN > 4 for ( pow = & powers [ 4 ] ;
 * up >= * pow ;
 pow ++ ) digits ++ ;
 # endif # endif # endif # endif break ;
 }
 return digits ;
 }


void ConnectionImpl::onHeaderField(const char* data, size_t length) {
  // We previously already finished up the headers, these headers are
  // now trailers.
  if (header_parsing_state_ == HeaderParsingState::Done) {
    if (!enable_trailers_) {
      // Ignore trailers.
      return;
    }
    processing_trailers_ = true;
    header_parsing_state_ = HeaderParsingState::Field;
  }
  if (header_parsing_state_ == HeaderParsingState::Value) {
    completeLastHeader();
  }

  current_header_field_.append(data, length);
}


unsigned int DoubleCPDO(const unsigned int opcode) { FPA11 *fpa11 = GET_FPA11(); float64 rFm, rFn = 0; unsigned int Fd, Fm, Fn, nRc = 1; //printk("DoubleCPDO(0x%08x)\n",opcode); Fm = getFm(opcode); if (CONSTANT_FM(opcode)) { rFm = getDoubleConstant(Fm); } else { switch (fpa11->fType[Fm]) { case typeSingle: rFm = float32_to_float64(fpa11->fpreg[Fm].fSingle, &fpa11->fp_status); break; case typeDouble: rFm = fpa11->fpreg[Fm].fDouble; break; case typeExtended: // !! patb //printk("not implemented! why not?\n"); //!! ScottB // should never get here, if extended involved // then other operand should be promoted then // ExtendedCPDO called. break; default: return 0; } } if (!MONADIC_INSTRUCTION(opcode)) { Fn = getFn(opcode); switch (fpa11->fType[Fn]) { case typeSingle: rFn = float32_to_float64(fpa11->fpreg[Fn].fSingle, &fpa11->fp_status); break; case typeDouble: rFn = fpa11->fpreg[Fn].fDouble; break; default: return 0; } } Fd = getFd(opcode); /* !! this switch isn't optimized; better (opcode & MASK_ARITHMETIC_OPCODE)>>24, sort of */ switch (opcode & MASK_ARITHMETIC_OPCODE) { /* dyadic opcodes */ case ADF_CODE: fpa11->fpreg[Fd].fDouble = float64_add(rFn,rFm, &fpa11->fp_status); break; case MUF_CODE: case FML_CODE: fpa11->fpreg[Fd].fDouble = float64_mul(rFn,rFm, &fpa11->fp_status); break; case SUF_CODE: fpa11->fpreg[Fd].fDouble = float64_sub(rFn,rFm, &fpa11->fp_status); break; case RSF_CODE: fpa11->fpreg[Fd].fDouble = float64_sub(rFm,rFn, &fpa11->fp_status); break; case DVF_CODE: case FDV_CODE: fpa11->fpreg[Fd].fDouble = float64_div(rFn,rFm, &fpa11->fp_status); break; case RDF_CODE: case FRD_CODE: fpa11->fpreg[Fd].fDouble = float64_div(rFm,rFn, &fpa11->fp_status); break; #if 0 case POW_CODE: fpa11->fpreg[Fd].fDouble = float64_pow(rFn,rFm); break; case RPW_CODE: fpa11->fpreg[Fd].fDouble = float64_pow(rFm,rFn); break; #endif case RMF_CODE: fpa11->fpreg[Fd].fDouble = float64_rem(rFn,rFm, &fpa11->fp_status); break; #if 0 case POL_CODE: fpa11->fpreg[Fd].fDouble = float64_pol(rFn,rFm); break; #endif /* monadic opcodes */ case MVF_CODE: fpa11->fpreg[Fd].fDouble = rFm; break; case MNF_CODE: { unsigned int *p = (unsigned int*)&rFm; #ifdef WORDS_BIGENDIAN p[0] ^= 0x80000000; #else p[1] ^= 0x80000000; #endif fpa11->fpreg[Fd].fDouble = rFm; } break; case ABS_CODE: { unsigned int *p = (unsigned int*)&rFm; #ifdef WORDS_BIGENDIAN p[0] &= 0x7fffffff; #else p[1] &= 0x7fffffff; #endif fpa11->fpreg[Fd].fDouble = rFm; } break; case RND_CODE: case URD_CODE: fpa11->fpreg[Fd].fDouble = float64_round_to_int(rFm, &fpa11->fp_status); break; case SQT_CODE: fpa11->fpreg[Fd].fDouble = float64_sqrt(rFm, &fpa11->fp_status); break; #if 0 case LOG_CODE: fpa11->fpreg[Fd].fDouble = float64_log(rFm); break; case LGN_CODE: fpa11->fpreg[Fd].fDouble = float64_ln(rFm); break; case EXP_CODE: fpa11->fpreg[Fd].fDouble = float64_exp(rFm); break; case SIN_CODE: fpa11->fpreg[Fd].fDouble = float64_sin(rFm); break; case COS_CODE: fpa11->fpreg[Fd].fDouble = float64_cos(rFm); break; case TAN_CODE: fpa11->fpreg[Fd].fDouble = float64_tan(rFm); break; case ASN_CODE: fpa11->fpreg[Fd].fDouble = float64_arcsin(rFm); break; case ACS_CODE: fpa11->fpreg[Fd].fDouble = float64_arccos(rFm); break; case ATN_CODE: fpa11->fpreg[Fd].fDouble = float64_arctan(rFm); break; #endif case NRM_CODE: break; default: { nRc = 0; } } if (0 != nRc) fpa11->fType[Fd] = typeDouble; return nRc; }


TEST_P(ClusterMemoryTestRunner, MemoryLargeClusterSizeWithRealSymbolTable) {
  symbol_table_creator_test_peer_.setUseFakeSymbolTables(false);

  // A unique instance of ClusterMemoryTest allows for multiple runs of Envoy with
  // differing configuration. This is necessary for measuring the memory consumption
  // between the different instances within the same test.
  const size_t m100 = ClusterMemoryTestHelper::computeMemoryDelta(1, 0, 101, 0, true);
  const size_t m_per_cluster = (m100) / 100;

  // Note: if you are increasing this golden value because you are adding a
  // stat, please confirm that this will be generally useful to most Envoy
  // users. Otherwise you are adding to the per-cluster memory overhead, which
  // will be significant for Envoy installations that are massively
  // multi-tenant.
  //
  // History of golden values:
  //
  // Date        PR       Bytes Per Cluster   Notes
  //                      exact upper-bound
  // ----------  -----    -----------------   -----
  // 2019/08/09  7882     35489       36000   Initial version
  // 2019/09/02  8118     34585       34500   Share symbol-tables in cluster/host stats.
  // 2019/09/16  8100     34585       34500   Add transport socket matcher in cluster.
  // 2019/09/25  8226     34777       35000   dns: enable dns failure refresh rate configuration
  // 2019/09/30  8354     34969       35000   Implement transport socket match.
  // 2019/10/17  8537     34966       35000   add new enum value HTTP3
  // 2019/10/17  8484     34998       35000   stats: add unit support to histogram
  // 2019/11/01  8859     35221       36000   build: switch to libc++ by default
  // 2019/11/15  9040     35029       35500   build: update protobuf to 3.10.1
  // 2019/11/15  9031     35061       35500   upstream: track whether cluster is local
  // 2019/12/10  8779     35053       35000   use var-length coding for name lengths
  // 2020/01/07  9069     35548       35700   upstream: Implement retry concurrency budgets
  // 2020/01/07  9564     35580       36000   RefcountPtr for CentralCache.
  // 2020/01/09  8889     35644       36000   api: add UpstreamHttpProtocolOptions message
  // 2019/01/09  9227     35772       36500   router: per-cluster histograms w/ timeout budget
  // 2020/01/12  9633     35932       36500   config: support recovery of original message when
  //                                          upgrading.
  // 2020/03/16  9964     36220       36800   http2: support custom SETTINGS parameters.
  // 2020/03/24  10501    36300       36800   upstream: upstream_rq_retry_limit_exceeded.
  // 2020/04/02  10624    35564       36000   Use 100 clusters rather than 1000 to avoid timeouts
  // 2020/04/07  10661    35557       36000   fix clang tidy on master
  // 2020/04/23  10531    36281       36800   http: max stream duration upstream support.
  // 2020/05/05  10908    36345       36800   router: add InternalRedirectPolicy and predicate
  // 2020/05/13  10531    36537       36800   Refactor resource manager
  // 2020/05/20  11223    36603       36800   Add primary clusters tracking to cluster manager.
  // 2020/06/10  11561    36603       36923   Make upstreams pluggable

  // Note: when adjusting this value: EXPECT_MEMORY_EQ is active only in CI
  // 'release' builds, where we control the platform and tool-chain. So you
  // will need to find the correct value only after failing CI and looking
  // at the logs.
  //
  // On a local clang8/libstdc++/linux flow, the memory usage was observed in
  // June 2019 to be 64 bytes higher than it is in CI/release. Your mileage may
  // vary.
  //
  // If you encounter a failure here, please see
  // https://github.com/envoyproxy/envoy/blob/master/source/docs/stats.md#stats-memory-tests
  // for details on how to fix.
  EXPECT_MEMORY_EQ(m_per_cluster, 36603);
  EXPECT_MEMORY_LE(m_per_cluster, 38000); // Round up to allow platform variations.
}


static void help ( const char * progname ) {
 printf ( _ ( "%s clusters all previously clustered tables in a database.\n\n" ) , progname ) ;
 printf ( _ ( "Usage:\n" ) ) ;
 printf ( _ ( " %s [OPTION]... [DBNAME]\n" ) , progname ) ;
 printf ( _ ( "\nOptions:\n" ) ) ;
 printf ( _ ( " -a, --all cluster all databases\n" ) ) ;
 printf ( _ ( " -d, --dbname=DBNAME database to cluster\n" ) ) ;
 printf ( _ ( " -e, --echo show the commands being sent to the server\n" ) ) ;
 printf ( _ ( " -q, --quiet don't write any messages\n" ) ) ;
 printf ( _ ( " -t, --table=TABLE cluster specific table(s) only\n" ) ) ;
 printf ( _ ( " -v, --verbose write a lot of output\n" ) ) ;
 printf ( _ ( " -V, --version output version information, then exit\n" ) ) ;
 printf ( _ ( " -?, --help show this help, then exit\n" ) ) ;
 printf ( _ ( "\nConnection options:\n" ) ) ;
 printf ( _ ( " -h, --host=HOSTNAME database server host or socket directory\n" ) ) ;
 printf ( _ ( " -p, --port=PORT database server port\n" ) ) ;
 printf ( _ ( " -U, --username=USERNAME user name to connect as\n" ) ) ;
 printf ( _ ( " -w, --no-password never prompt for password\n" ) ) ;
 printf ( _ ( " -W, --password force password prompt\n" ) ) ;
 printf ( _ ( " --maintenance-db=DBNAME alternate maintenance database\n" ) ) ;
 printf ( _ ( "\nRead the description of the SQL command CLUSTER for details.\n" ) ) ;
 printf ( _ ( "\nReport bugs to <pgsql-bugs@postgresql.org>.\n" ) ) ;
 }


long do_sigreturn(CPUS390XState *env) { sigframe *frame; abi_ulong frame_addr = env->regs[15]; qemu_log("%s: frame_addr 0x%llx\n", __FUNCTION__, (unsigned long long)frame_addr); target_sigset_t target_set; sigset_t set; if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) { goto badframe; } if (__get_user(target_set.sig[0], &frame->sc.oldmask[0])) { goto badframe; } target_to_host_sigset_internal(&set, &target_set); sigprocmask(SIG_SETMASK, &set, NULL); /* ~_BLOCKABLE? */ if (restore_sigregs(env, &frame->sregs)) { goto badframe; } unlock_user_struct(frame, frame_addr, 0); return env->regs[2]; badframe: unlock_user_struct(frame, frame_addr, 0); force_sig(TARGET_SIGSEGV); return 0; }


void ListenerImpl::listenCallback(evconnlistener*, evutil_socket_t fd, sockaddr* remote_addr,
                                  int remote_addr_len, void* arg) {
  ListenerImpl* listener = static_cast<ListenerImpl*>(arg);

  // Wrap raw socket fd in IoHandle.
  IoHandlePtr io_handle = SocketInterfaceSingleton::get().socket(fd);

  // Get the local address from the new socket if the listener is listening on IP ANY
  // (e.g., 0.0.0.0 for IPv4) (local_address_ is nullptr in this case).
  const Address::InstanceConstSharedPtr& local_address =
      listener->local_address_ ? listener->local_address_ : io_handle->localAddress();

  // The accept() call that filled in remote_addr doesn't fill in more than the sa_family field
  // for Unix domain sockets; apparently there isn't a mechanism in the kernel to get the
  // `sockaddr_un` associated with the client socket when starting from the server socket.
  // We work around this by using our own name for the socket in this case.
  // Pass the 'v6only' parameter as true if the local_address is an IPv6 address. This has no effect
  // if the socket is a v4 socket, but for v6 sockets this will create an IPv4 remote address if an
  // IPv4 local_address was created from an IPv6 mapped IPv4 address.
  const Address::InstanceConstSharedPtr& remote_address =
      (remote_addr->sa_family == AF_UNIX)
          ? io_handle->peerAddress()
          : Address::addressFromSockAddr(*reinterpret_cast<const sockaddr_storage*>(remote_addr),
                                         remote_addr_len,
                                         local_address->ip()->version() == Address::IpVersion::v6);
  listener->cb_.onAccept(
      std::make_unique<AcceptedSocketImpl>(std::move(io_handle), local_address, remote_address));
}


pci_set_cfgdata32(struct pci_vdev *dev, int offset, uint32_t val)
{
	assert(offset <= (PCI_REGMAX - 3) && (offset & 3) == 0);
	*(uint32_t *)(dev->cfgdata + offset) = val;
}


static void pty_chr_update_read_handler(CharDriverState *chr) { PtyCharDriver *s = chr->opaque; GPollFD pfd; pfd.fd = g_io_channel_unix_get_fd(s->fd); pfd.events = G_IO_OUT; pfd.revents = 0; g_poll(&pfd, 1, 0); if (pfd.revents & G_IO_HUP) { pty_chr_state(chr, 0); } else { pty_chr_state(chr, 1); } }


static int dissect_diameter_subscription_id ( tvbuff_t * tvb _U_ , packet_info * pinfo _U_ , proto_tree * tree _U_ , void * data _U_ ) {
 subscription_id_type = SUBSCRIPTION_ID_TYPE_UNKNOWN ;
 return 0 ;
 }


int sqlite3CheckObjectName(
  Parse *pParse,            /* Parsing context */
  const char *zName,        /* Name of the object to check */
  const char *zType,        /* Type of this object */
  const char *zTblName      /* Parent table name for triggers and indexes */
){
  sqlite3 *db = pParse->db;
  if( sqlite3WritableSchema(db) || db->init.imposterTable ){
    /* Skip these error checks for writable_schema=ON */
    return SQLITE_OK;
  }
  if( db->init.busy ){
    if( sqlite3_stricmp(zType, db->init.azInit[0])
     || sqlite3_stricmp(zName, db->init.azInit[1])
     || sqlite3_stricmp(zTblName, db->init.azInit[2])
    ){
      if( sqlite3Config.bExtraSchemaChecks ){
        sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
        return SQLITE_ERROR;
      }
    }
  }else{
    if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
     || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
    ){
      sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
                      zName);
      return SQLITE_ERROR;
    }

  }
  return SQLITE_OK;
}


TEST_F(OwnedImplTest, AddEmptyFragment) {
  char input[] = "hello world";
  BufferFragmentImpl frag1(input, 11, [](const void*, size_t, const BufferFragmentImpl*) {});
  BufferFragmentImpl frag2("", 0, [this](const void*, size_t, const BufferFragmentImpl*) {
    release_callback_called_ = true;
  });
  Buffer::OwnedImpl buffer;
  buffer.addBufferFragment(frag1);
  EXPECT_EQ(11, buffer.length());

  buffer.addBufferFragment(frag2);
  EXPECT_EQ(11, buffer.length());

  buffer.drain(11);
  EXPECT_EQ(0, buffer.length());
  EXPECT_TRUE(release_callback_called_);
}


static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; unsigned char *vqa_header; int i, j, codebook_index; s->avctx = avctx; avctx->pix_fmt = PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, " VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE); return -1; } /* load up the VQA parameters from the header */ vqa_header = (unsigned char *)s->avctx->extradata; s->vqa_version = vqa_header[0]; s->width = AV_RL16(&vqa_header[6]); s->height = AV_RL16(&vqa_header[8]); if(av_image_check_size(s->width, s->height, 0, avctx)){ s->width= s->height= 0; return -1; } s->vector_width = vqa_header[10]; s->vector_height = vqa_header[11]; s->partial_count = s->partial_countdown = vqa_header[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return -1; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); s->next_codebook_buffer = av_malloc(s->codebook_size); /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_malloc(s->decode_buffer_size); s->frame.data[0] = NULL; return 0; }