jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
	jas_matrix_t *matrix;
	int i;

	if (numrows < 0 || numcols < 0) {
		return 0;
	}

	if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
		return 0;
	}
	matrix->flags_ = 0;
	matrix->numrows_ = numrows;
	matrix->numcols_ = numcols;
	matrix->rows_ = 0;
	matrix->maxrows_ = numrows;
	matrix->data_ = 0;
	matrix->datasize_ = numrows * numcols;

	if (matrix->maxrows_ > 0) {
		if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
		  sizeof(jas_seqent_t *)))) {
			jas_matrix_destroy(matrix);
			return 0;
		}
	}

	if (matrix->datasize_ > 0) {
		if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
		  sizeof(jas_seqent_t)))) {
			jas_matrix_destroy(matrix);
			return 0;
		}
	}

	for (i = 0; i < numrows; ++i) {
		matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
	}

	for (i = 0; i < matrix->datasize_; ++i) {
		matrix->data_[i] = 0;
	}

	matrix->xstart_ = 0;
	matrix->ystart_ = 0;
	matrix->xend_ = matrix->numcols_;
	matrix->yend_ = matrix->numrows_;

	return matrix;
}


void AppLauncherHandler::HandleReorderApps(const base::ListValue* args) {
  CHECK(args->GetSize() == 2);

  std::string dragged_app_id;
  const base::ListValue* app_order;
  CHECK(args->GetString(0, &dragged_app_id));
  CHECK(args->GetList(1, &app_order));

  std::string predecessor_to_moved_ext;
  std::string successor_to_moved_ext;
  for (size_t i = 0; i < app_order->GetSize(); ++i) {
    std::string value;
    if (app_order->GetString(i, &value) && value == dragged_app_id) {
      if (i > 0)
        CHECK(app_order->GetString(i - 1, &predecessor_to_moved_ext));
      if (i + 1 < app_order->GetSize())
        CHECK(app_order->GetString(i + 1, &successor_to_moved_ext));
      break;
    }
  }

  base::AutoReset<bool> auto_reset(&ignore_changes_, true);
  ExtensionPrefs* extension_prefs =
      ExtensionPrefs::Get(extension_service_->GetBrowserContext());
  extension_prefs->SetAppDraggedByUser(dragged_app_id);
  extension_prefs->app_sorting()->OnExtensionMoved(
      dragged_app_id, predecessor_to_moved_ext, successor_to_moved_ext);
}


Network::Address::InstanceConstSharedPtr getSslAddress(const Network::Address::IpVersion& version,
                                                       int port) {
  std::string url =
      "tcp://" + Network::Test::getLoopbackAddressUrlString(version) + ":" + std::to_string(port);
  return Network::Utility::resolveUrl(url);
}


static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
{
	struct ffs_data *ffs = file->private_data;
	unsigned int mask = POLLWRNORM;
	int ret;

	poll_wait(file, &ffs->ev.waitq, wait);

	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
	if (unlikely(ret < 0))
		return mask;

	switch (ffs->state) {
	case FFS_READ_DESCRIPTORS:
	case FFS_READ_STRINGS:
		mask |= POLLOUT;
		break;

	case FFS_ACTIVE:
		switch (ffs->setup_state) {
		case FFS_NO_SETUP:
			if (ffs->ev.count)
				mask |= POLLIN;
			break;

		case FFS_SETUP_PENDING:
		case FFS_SETUP_CANCELLED:
			mask |= (POLLIN | POLLOUT);
			break;
		}
	case FFS_CLOSING:
		break;
	case FFS_DEACTIVATED:
		break;
	}

	mutex_unlock(&ffs->mutex);

	return mask;
}


xmlLinkPtr xmlListFront ( xmlListPtr l ) {
 if ( l == NULL ) return ( NULL ) ;
 return ( l -> sentinel -> next ) ;
 }


ListValue* TestingAutomationProvider::GetListFromAutofillProfiles(
    const std::vector<AutofillProfile*>& autofill_profiles) {
  ListValue* profiles = new ListValue;

  std::map<AutofillFieldType, std::string> autofill_type_to_string
      = GetAutofillFieldToStringMap();

  for (std::vector<AutofillProfile*>::const_iterator it =
           autofill_profiles.begin();
       it != autofill_profiles.end(); ++it) {
    AutofillProfile* profile = *it;
    DictionaryValue* profile_info = new DictionaryValue;
    for (std::map<AutofillFieldType, std::string>::iterator
         type_it = autofill_type_to_string.begin();
         type_it != autofill_type_to_string.end(); ++type_it) {
      std::vector<string16> value_list;
      profile->GetMultiInfo(type_it->first, &value_list);
      ListValue* values_to_return = new ListValue;
      for (std::vector<string16>::iterator value_it = value_list.begin();
           value_it != value_list.end(); ++value_it) {
        string16 value = *value_it;
        if (value.length())  // If there was something stored for that value.
          values_to_return->Append(new StringValue(value));
      }
      if (!values_to_return->empty())
        profile_info->Set(type_it->second, values_to_return);
    }
    profiles->Append(profile_info);
  }
  return profiles;
}


map_engine_on_render(script_t* script)
{
	script_unref(s_render_script);
	s_render_script = script_ref(script);
}


    JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
    {
        return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
    }


float64 float64_muladd(float64 a, float64 b, float64 c, int flags STATUS_PARAM)

{

    flag aSign, bSign, cSign, zSign;

    int_fast16_t aExp, bExp, cExp, pExp, zExp, expDiff;

    uint64_t aSig, bSig, cSig;

    flag pInf, pZero, pSign;

    uint64_t pSig0, pSig1, cSig0, cSig1, zSig0, zSig1;

    int shiftcount;

    flag signflip, infzero;

    a = float64_squash_input_denormal(a STATUS_VAR);

    b = float64_squash_input_denormal(b STATUS_VAR);

    c = float64_squash_input_denormal(c STATUS_VAR);

    aSig = extractFloat64Frac(a);

    aExp = extractFloat64Exp(a);

    aSign = extractFloat64Sign(a);

    bSig = extractFloat64Frac(b);

    bExp = extractFloat64Exp(b);

    bSign = extractFloat64Sign(b);

    cSig = extractFloat64Frac(c);

    cExp = extractFloat64Exp(c);

    cSign = extractFloat64Sign(c);

    infzero = ((aExp == 0 && aSig == 0 && bExp == 0x7ff && bSig == 0) ||

               (aExp == 0x7ff && aSig == 0 && bExp == 0 && bSig == 0));

    /* It is implementation-defined whether the cases of (0,inf,qnan)

     * and (inf,0,qnan) raise InvalidOperation or not (and what QNaN

     * they return if they do), so we have to hand this information

     * off to the target-specific pick-a-NaN routine.

     */

    if (((aExp == 0x7ff) && aSig) ||

        ((bExp == 0x7ff) && bSig) ||

        ((cExp == 0x7ff) && cSig)) {

        return propagateFloat64MulAddNaN(a, b, c, infzero STATUS_VAR);

    }

    if (infzero) {

        float_raise(float_flag_invalid STATUS_VAR);

        return float64_default_nan;

    }

    if (flags & float_muladd_negate_c) {

        cSign ^= 1;

    }

    signflip = (flags & float_muladd_negate_result) ? 1 : 0;

    /* Work out the sign and type of the product */

    pSign = aSign ^ bSign;

    if (flags & float_muladd_negate_product) {

        pSign ^= 1;

    }

    pInf = (aExp == 0x7ff) || (bExp == 0x7ff);

    pZero = ((aExp | aSig) == 0) || ((bExp | bSig) == 0);

    if (cExp == 0x7ff) {

        if (pInf && (pSign ^ cSign)) {

            /* addition of opposite-signed infinities => InvalidOperation */

            float_raise(float_flag_invalid STATUS_VAR);

            return float64_default_nan;

        }

        /* Otherwise generate an infinity of the same sign */

        return packFloat64(cSign ^ signflip, 0x7ff, 0);

    }

    if (pInf) {

        return packFloat64(pSign ^ signflip, 0x7ff, 0);

    }

    if (pZero) {

        if (cExp == 0) {

            if (cSig == 0) {

                /* Adding two exact zeroes */

                if (pSign == cSign) {

                    zSign = pSign;

                } else if (STATUS(float_rounding_mode) == float_round_down) {

                    zSign = 1;

                } else {

                    zSign = 0;

                }

                return packFloat64(zSign ^ signflip, 0, 0);

            }

            /* Exact zero plus a denorm */

            if (STATUS(flush_to_zero)) {

                float_raise(float_flag_output_denormal STATUS_VAR);

                return packFloat64(cSign ^ signflip, 0, 0);

            }

        }

        /* Zero plus something non-zero : just return the something */

        return packFloat64(cSign ^ signflip, cExp, cSig);

    }

    if (aExp == 0) {

        normalizeFloat64Subnormal(aSig, &aExp, &aSig);

    }

    if (bExp == 0) {

        normalizeFloat64Subnormal(bSig, &bExp, &bSig);

    }

    /* Calculate the actual result a * b + c */

    /* Multiply first; this is easy. */

    /* NB: we subtract 0x3fe where float64_mul() subtracts 0x3ff

     * because we want the true exponent, not the "one-less-than"

     * flavour that roundAndPackFloat64() takes.

     */

    pExp = aExp + bExp - 0x3fe;

    aSig = (aSig | LIT64(0x0010000000000000))<<10;

    bSig = (bSig | LIT64(0x0010000000000000))<<11;

    mul64To128(aSig, bSig, &pSig0, &pSig1);

    if ((int64_t)(pSig0 << 1) >= 0) {

        shortShift128Left(pSig0, pSig1, 1, &pSig0, &pSig1);

        pExp--;

    }

    zSign = pSign ^ signflip;

    /* Now [pSig0:pSig1] is the significand of the multiply, with the explicit

     * bit in position 126.

     */

    if (cExp == 0) {

        if (!cSig) {

            /* Throw out the special case of c being an exact zero now */

            shift128RightJamming(pSig0, pSig1, 64, &pSig0, &pSig1);

            return roundAndPackFloat64(zSign, pExp - 1,

                                       pSig1 STATUS_VAR);

        }

        normalizeFloat64Subnormal(cSig, &cExp, &cSig);

    }

    /* Shift cSig and add the explicit bit so [cSig0:cSig1] is the

     * significand of the addend, with the explicit bit in position 126.

     */

    cSig0 = cSig << (126 - 64 - 52);

    cSig1 = 0;

    cSig0 |= LIT64(0x4000000000000000);

    expDiff = pExp - cExp;

    if (pSign == cSign) {

        /* Addition */

        if (expDiff > 0) {

            /* scale c to match p */

            shift128RightJamming(cSig0, cSig1, expDiff, &cSig0, &cSig1);

            zExp = pExp;

        } else if (expDiff < 0) {

            /* scale p to match c */

            shift128RightJamming(pSig0, pSig1, -expDiff, &pSig0, &pSig1);

            zExp = cExp;

        } else {

            /* no scaling needed */

            zExp = cExp;

        }

        /* Add significands and make sure explicit bit ends up in posn 126 */

        add128(pSig0, pSig1, cSig0, cSig1, &zSig0, &zSig1);

        if ((int64_t)zSig0 < 0) {

            shift128RightJamming(zSig0, zSig1, 1, &zSig0, &zSig1);

        } else {

            zExp--;

        }

        shift128RightJamming(zSig0, zSig1, 64, &zSig0, &zSig1);

        return roundAndPackFloat64(zSign, zExp, zSig1 STATUS_VAR);

    } else {

        /* Subtraction */

        if (expDiff > 0) {

            shift128RightJamming(cSig0, cSig1, expDiff, &cSig0, &cSig1);

            sub128(pSig0, pSig1, cSig0, cSig1, &zSig0, &zSig1);

            zExp = pExp;

        } else if (expDiff < 0) {

            shift128RightJamming(pSig0, pSig1, -expDiff, &pSig0, &pSig1);

            sub128(cSig0, cSig1, pSig0, pSig1, &zSig0, &zSig1);

            zExp = cExp;

            zSign ^= 1;

        } else {

            zExp = pExp;

            if (lt128(cSig0, cSig1, pSig0, pSig1)) {

                sub128(pSig0, pSig1, cSig0, cSig1, &zSig0, &zSig1);

            } else if (lt128(pSig0, pSig1, cSig0, cSig1)) {

                sub128(cSig0, cSig1, pSig0, pSig1, &zSig0, &zSig1);

                zSign ^= 1;

            } else {

                /* Exact zero */

                zSign = signflip;

                if (STATUS(float_rounding_mode) == float_round_down) {

                    zSign ^= 1;

                }

                return packFloat64(zSign, 0, 0);

            }

        }

        --zExp;

        /* Do the equivalent of normalizeRoundAndPackFloat64() but

         * starting with the significand in a pair of uint64_t.

         */

        if (zSig0) {

            shiftcount = countLeadingZeros64(zSig0) - 1;

            shortShift128Left(zSig0, zSig1, shiftcount, &zSig0, &zSig1);

            if (zSig1) {

                zSig0 |= 1;

            }

            zExp -= shiftcount;

        } else {

            shiftcount = countLeadingZeros64(zSig1) - 1;

            zSig0 = zSig1 << shiftcount;

            zExp -= (shiftcount + 64);

        }

        return roundAndPackFloat64(zSign, zExp, zSig0 STATUS_VAR);

    }

}


static int xt_match_seq_show(struct seq_file *seq, void *v)
{
	const struct nf_mttg_trav *trav = seq->private;
	const struct xt_match *match;

	switch (trav->class) {
	case MTTG_TRAV_NFP_UNSPEC:
	case MTTG_TRAV_NFP_SPEC:
		if (trav->curr == trav->head)
			return 0;
		match = list_entry(trav->curr, struct xt_match, list);
		if (*match->name)
			seq_printf(seq, "%s\n", match->name);
	}
	return 0;
}


static jobject android_net_wifi_getScanResults(
 JNIEnv *env, jclass cls, jint iface, jboolean flush) {

 JNIHelper helper(env);
    wifi_cached_scan_results scan_data[64];
 int num_scan_data = 64;

    wifi_interface_handle handle = getIfaceHandle(helper, cls, iface);

    byte b = flush ? 0xFF : 0;
 int result = hal_fn.wifi_get_cached_gscan_results(handle, b, num_scan_data, scan_data, &num_scan_data);
 if (result == WIFI_SUCCESS) {
 JNIObject<jobjectArray> scanData = helper.createObjectArray(
 "android/net/wifi/WifiScanner$ScanData", num_scan_data);
 if (scanData == NULL) {
            ALOGE("Error in allocating array of scanData");
 return NULL;
 }

 for (int i = 0; i < num_scan_data; i++) {

 JNIObject<jobject> data = helper.createObject("android/net/wifi/WifiScanner$ScanData");
 if (data == NULL) {
                ALOGE("Error in allocating scanData");
 return NULL;
 }

            helper.setIntField(data, "mId", scan_data[i].scan_id);
            helper.setIntField(data, "mFlags", scan_data[i].flags);

 /* sort all scan results by timestamp */
            qsort(scan_data[i].results, scan_data[i].num_results,
 sizeof(wifi_scan_result), compare_scan_result_timestamp);

 JNIObject<jobjectArray> scanResults = helper.createObjectArray(
 "android/net/wifi/ScanResult", scan_data[i].num_results);
 if (scanResults == NULL) {
                ALOGE("Error in allocating scanResult array");
 return NULL;
 }

            wifi_scan_result *results = scan_data[i].results;
 for (int j = 0; j < scan_data[i].num_results; j++) {

 JNIObject<jobject> scanResult = createScanResult(helper, &results[j]);
 if (scanResult == NULL) {
                    ALOGE("Error in creating scan result");
 return NULL;
 }

                helper.setObjectArrayElement(scanResults, j, scanResult);
 }

            helper.setObjectField(data, "mResults", "[Landroid/net/wifi/ScanResult;", scanResults);
            helper.setObjectArrayElement(scanData, i, data);
 }

 return scanData.detach();
 } else {
 return NULL;
 }
}


static indic_position_t consonant_position_from_face ( const indic_shape_plan_t * indic_plan , const hb_codepoint_t consonant , const hb_codepoint_t virama , hb_face_t * face ) {
 hb_codepoint_t glyphs [ 3 ] = {
 virama , consonant , virama }
 ;
 if ( indic_plan -> blwf . would_substitute ( glyphs , 2 , face ) || indic_plan -> blwf . would_substitute ( glyphs + 1 , 2 , face ) ) return POS_BELOW_C ;
 if ( indic_plan -> pstf . would_substitute ( glyphs , 2 , face ) || indic_plan -> pstf . would_substitute ( glyphs + 1 , 2 , face ) ) return POS_POST_C ;
 unsigned int pref_len = indic_plan -> config -> pref_len ;
 if ( ( pref_len == PREF_LEN_2 && ( indic_plan -> pref . would_substitute ( glyphs , 2 , face ) || indic_plan -> pref . would_substitute ( glyphs + 1 , 2 , face ) ) ) || ( pref_len == PREF_LEN_1 && indic_plan -> pref . would_substitute ( glyphs + 1 , 1 , face ) ) ) return POS_POST_C ;
 return POS_BASE_C ;
 }


static bool valid_rep(cs_struct *h, unsigned int opcode)
{
	unsigned int id;
	int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache);
	if (i != 0) {
		id = insns[i].mapid;
		switch(id) {
			default:
				return false;

			case X86_INS_MOVSB:
			case X86_INS_MOVSW:
			case X86_INS_MOVSQ:

			case X86_INS_LODSB:
			case X86_INS_LODSW:
			case X86_INS_LODSQ:

			case X86_INS_STOSB:
			case X86_INS_STOSW:
			case X86_INS_STOSQ:

			case X86_INS_INSB:
			case X86_INS_INSW:
			case X86_INS_INSD:

			case X86_INS_OUTSB:
			case X86_INS_OUTSW:
			case X86_INS_OUTSD:
				return true;

			// following are some confused instructions, which have the same
			// mnemonics in 128bit media instructions. Intel is horribly crazy!
			case X86_INS_MOVSD:
				if (opcode == X86_MOVSL) // REP MOVSD
					return true;
				return false;

			case X86_INS_LODSD:
				if (opcode == X86_LODSL) // REP LODSD
					return true;
				return false;

			case X86_INS_STOSD:
				if (opcode == X86_STOSL) // REP STOSD
					return true;
				return false;
		}
	}

	// not found
	return false;
}


String FrameLoader::UserAgent() const {
  String user_agent = Client()->UserAgent();
  probe::applyUserAgentOverride(frame_->GetDocument(), &user_agent);
  return user_agent;
}


static uint32_t vmsvga_value_read ( void * opaque , uint32_t address ) {
 uint32_t caps ;
 struct vmsvga_state_s * s = opaque ;
 DisplaySurface * surface = qemu_console_surface ( s -> vga . con ) ;
 PixelFormat pf ;
 uint32_t ret ;
 switch ( s -> index ) {
 case SVGA_REG_ID : ret = s -> svgaid ;
 break ;
 case SVGA_REG_ENABLE : ret = s -> enable ;
 break ;
 case SVGA_REG_WIDTH : ret = s -> new_width ? s -> new_width : surface_width ( surface ) ;
 break ;
 case SVGA_REG_HEIGHT : ret = s -> new_height ? s -> new_height : surface_height ( surface ) ;
 break ;
 case SVGA_REG_MAX_WIDTH : ret = SVGA_MAX_WIDTH ;
 break ;
 case SVGA_REG_MAX_HEIGHT : ret = SVGA_MAX_HEIGHT ;
 break ;
 case SVGA_REG_DEPTH : ret = ( s -> new_depth == 32 ) ? 24 : s -> new_depth ;
 break ;
 case SVGA_REG_BITS_PER_PIXEL : case SVGA_REG_HOST_BITS_PER_PIXEL : ret = s -> new_depth ;
 break ;
 case SVGA_REG_PSEUDOCOLOR : ret = 0x0 ;
 break ;
 case SVGA_REG_RED_MASK : pf = qemu_default_pixelformat ( s -> new_depth ) ;
 ret = pf . rmask ;
 break ;
 case SVGA_REG_GREEN_MASK : pf = qemu_default_pixelformat ( s -> new_depth ) ;
 ret = pf . gmask ;
 break ;
 case SVGA_REG_BLUE_MASK : pf = qemu_default_pixelformat ( s -> new_depth ) ;
 ret = pf . bmask ;
 break ;
 case SVGA_REG_BYTES_PER_LINE : if ( s -> new_width ) {
 ret = ( s -> new_depth * s -> new_width ) / 8 ;
 }
 else {
 ret = surface_stride ( surface ) ;
 }
 break ;
 case SVGA_REG_FB_START : {
 struct pci_vmsvga_state_s * pci_vmsvga = container_of ( s , struct pci_vmsvga_state_s , chip ) ;
 ret = pci_get_bar_addr ( PCI_DEVICE ( pci_vmsvga ) , 1 ) ;
 break ;
 }
 case SVGA_REG_FB_OFFSET : ret = 0x0 ;
 break ;
 case SVGA_REG_VRAM_SIZE : ret = s -> vga . vram_size ;
 break ;
 case SVGA_REG_FB_SIZE : ret = s -> vga . vram_size ;
 break ;
 case SVGA_REG_CAPABILITIES : caps = SVGA_CAP_NONE ;
 # ifdef HW_RECT_ACCEL caps |= SVGA_CAP_RECT_COPY ;
 # endif # ifdef HW_FILL_ACCEL caps |= SVGA_CAP_RECT_FILL ;
 # endif # ifdef HW_MOUSE_ACCEL if ( dpy_cursor_define_supported ( s -> vga . con ) ) {
 caps |= SVGA_CAP_CURSOR | SVGA_CAP_CURSOR_BYPASS_2 | SVGA_CAP_CURSOR_BYPASS ;
 }
 # endif ret = caps ;
 break ;
 case SVGA_REG_MEM_START : {
 struct pci_vmsvga_state_s * pci_vmsvga = container_of ( s , struct pci_vmsvga_state_s , chip ) ;
 ret = pci_get_bar_addr ( PCI_DEVICE ( pci_vmsvga ) , 2 ) ;
 break ;
 }
 case SVGA_REG_MEM_SIZE : ret = s -> fifo_size ;
 break ;
 case SVGA_REG_CONFIG_DONE : ret = s -> config ;
 break ;
 case SVGA_REG_SYNC : case SVGA_REG_BUSY : ret = s -> syncing ;
 break ;
 case SVGA_REG_GUEST_ID : ret = s -> guest ;
 break ;
 case SVGA_REG_CURSOR_ID : ret = s -> cursor . id ;
 break ;
 case SVGA_REG_CURSOR_X : ret = s -> cursor . x ;
 break ;
 case SVGA_REG_CURSOR_Y : ret = s -> cursor . y ;
 break ;
 case SVGA_REG_CURSOR_ON : ret = s -> cursor . on ;
 break ;
 case SVGA_REG_SCRATCH_SIZE : ret = s -> scratch_size ;
 break ;
 case SVGA_REG_MEM_REGS : case SVGA_REG_NUM_DISPLAYS : case SVGA_REG_PITCHLOCK : case SVGA_PALETTE_BASE ... SVGA_PALETTE_END : ret = 0 ;
 break ;
 default : if ( s -> index >= SVGA_SCRATCH_BASE && s -> index < SVGA_SCRATCH_BASE + s -> scratch_size ) {
 ret = s -> scratch [ s -> index - SVGA_SCRATCH_BASE ] ;
 break ;
 }
 printf ( "%s: Bad register %02x\n" , __func__ , s -> index ) ;
 ret = 0 ;
 break ;
 }
 if ( s -> index >= SVGA_SCRATCH_BASE ) {
 trace_vmware_scratch_read ( s -> index , ret ) ;
 }
 else if ( s -> index >= SVGA_PALETTE_BASE ) {
 trace_vmware_palette_read ( s -> index , ret ) ;
 }
 else {
 trace_vmware_value_read ( s -> index , ret ) ;
 }
 return ret ;
 }


SkColor TestRenderWidgetHostView::background_color() const {
  return background_color_;
}


 int MockRenderThread::GenerateRoutingID() {
  NOTREACHED();
  return MSG_ROUTING_NONE;
}


static int bochs_open(BlockDriverState *bs, QDict *options, int flags,

                      Error **errp)

{

    BDRVBochsState *s = bs->opaque;

    int i;

    struct bochs_header bochs;

    struct bochs_header_v1 header_v1;

    int ret;

    bs->read_only = 1; // no write support yet

    ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));

    if (ret < 0) {

        return ret;

    }

    if (strcmp(bochs.magic, HEADER_MAGIC) ||

        strcmp(bochs.type, REDOLOG_TYPE) ||

        strcmp(bochs.subtype, GROWING_TYPE) ||

	((le32_to_cpu(bochs.version) != HEADER_VERSION) &&

	(le32_to_cpu(bochs.version) != HEADER_V1))) {

        error_setg(errp, "Image not in Bochs format");

        return -EINVAL;

    }

    if (le32_to_cpu(bochs.version) == HEADER_V1) {

      memcpy(&header_v1, &bochs, sizeof(bochs));

      bs->total_sectors = le64_to_cpu(header_v1.extra.redolog.disk) / 512;

    } else {

      bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;

    }

    s->catalog_size = le32_to_cpu(bochs.extra.redolog.catalog);

    s->catalog_bitmap = g_malloc(s->catalog_size * 4);

    ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,

                     s->catalog_size * 4);

    if (ret < 0) {

        goto fail;

    }

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

	le32_to_cpus(&s->catalog_bitmap[i]);

    s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);

    s->bitmap_blocks = 1 + (le32_to_cpu(bochs.extra.redolog.bitmap) - 1) / 512;

    s->extent_blocks = 1 + (le32_to_cpu(bochs.extra.redolog.extent) - 1) / 512;

    s->extent_size = le32_to_cpu(bochs.extra.redolog.extent);

    qemu_co_mutex_init(&s->lock);

    return 0;

fail:

    g_free(s->catalog_bitmap);

    return ret;

}


void GLES2Implementation::SetActiveURLCHROMIUM(const char* url) {
  DCHECK(url);
  GPU_CLIENT_SINGLE_THREAD_CHECK();
  GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glSetActiveURLCHROMIUM(" << url);

  if (last_active_url_ == url)
    return;

  last_active_url_ = url;
  static constexpr uint32_t kMaxStrLen = 1024;
  size_t len = strlen(url);
  if (len == 0)
    return;

  SetBucketContents(kResultBucketId, url,
                    base::CheckMin(len, kMaxStrLen).ValueOrDie());
  helper_->SetActiveURLCHROMIUM(kResultBucketId);
  helper_->SetBucketSize(kResultBucketId, 0);
}


void OutOfProcessInstance::DidOpenPreview(int32_t result) {
  if (result == PP_OK) {
    preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
    preview_engine_->HandleDocumentLoad(embed_preview_loader_);
  } else {
    NOTREACHED();
  }
}


static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,

                              int nb_sectors)

{

    if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {

        return -EIO;

    }

    return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,

                                   nb_sectors * BDRV_SECTOR_SIZE);

}


static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
{
	kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);
	wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));
	kfree(ubufs);
}


static void *cluster_hash_alloc(void *p)
{
	const struct cluster_list *val = (const struct cluster_list *)p;
	struct cluster_list *cluster;

	cluster = XMALLOC(MTYPE_CLUSTER, sizeof(struct cluster_list));
	cluster->length = val->length;

	if (cluster->length) {
		cluster->list = XMALLOC(MTYPE_CLUSTER_VAL, val->length);
		memcpy(cluster->list, val->list, val->length);
	} else
		cluster->list = NULL;

	cluster->refcnt = 0;

	return cluster;
}


ast_for_suite(struct compiling *c, const node *n)
{
    /* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
    asdl_seq *seq;
    stmt_ty s;
    int i, total, num, end, pos = 0;
    node *ch;

    REQ(n, suite);

    total = num_stmts(n);
    seq = _Ta3_asdl_seq_new(total, c->c_arena);
    if (!seq)
        return NULL;
    if (TYPE(CHILD(n, 0)) == simple_stmt) {
        n = CHILD(n, 0);
        /* simple_stmt always ends with a NEWLINE,
           and may have a trailing SEMI
        */
        end = NCH(n) - 1;
        if (TYPE(CHILD(n, end - 1)) == SEMI)
            end--;
        /* loop by 2 to skip semi-colons */
        for (i = 0; i < end; i += 2) {
            ch = CHILD(n, i);
            s = ast_for_stmt(c, ch);
            if (!s)
                return NULL;
            asdl_seq_SET(seq, pos++, s);
        }
    }
    else {
        i = 2;
        if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
            i += 2;

        for (; i < (NCH(n) - 1); i++) {
            ch = CHILD(n, i);
            REQ(ch, stmt);
            num = num_stmts(ch);
            if (num == 1) {
                /* small_stmt or compound_stmt with only one child */
                s = ast_for_stmt(c, ch);
                if (!s)
                    return NULL;
                asdl_seq_SET(seq, pos++, s);
            }
            else {
                int j;
                ch = CHILD(ch, 0);
                REQ(ch, simple_stmt);
                for (j = 0; j < NCH(ch); j += 2) {
                    /* statement terminates with a semi-colon ';' */
                    if (NCH(CHILD(ch, j)) == 0) {
                        assert((j + 1) == NCH(ch));
                        break;
                    }
                    s = ast_for_stmt(c, CHILD(ch, j));
                    if (!s)
                        return NULL;
                    asdl_seq_SET(seq, pos++, s);
                }
            }
        }
    }
    assert(pos == seq->size);
    return seq;
}


void GLES2DecoderImpl::DoBindRenderbuffer(GLenum target, GLuint client_id) {
  RenderbufferManager::RenderbufferInfo* info = NULL;
  GLuint service_id = 0;
  if (client_id != 0) {
    info = GetRenderbufferInfo(client_id);
    if (!info) {
      if (!group_->bind_generates_resource()) {
        SetGLError(
            GL_INVALID_VALUE,
            "glBindRenderbuffer: id not generated by glGenRenderbuffers");
        return;
      }

      glGenRenderbuffersEXT(1, &service_id);
      CreateRenderbufferInfo(client_id, service_id);
      info = GetRenderbufferInfo(client_id);
      IdAllocatorInterface* id_allocator =
          group_->GetIdAllocator(id_namespaces::kRenderbuffers);
      id_allocator->MarkAsUsed(client_id);
    } else {
      service_id = info->service_id();
    }
    info->MarkAsValid();
  }
  bound_renderbuffer_ = info;
  glBindRenderbufferEXT(target, service_id);
}


static int aa_read_close(AVFormatContext *s)
{
    AADemuxContext *c = s->priv_data;

    av_freep(&c->tea_ctx);

    return 0;
}


_SSL_set_verify (SSL_CTX *ctx, void *verify_callback, char *cacert)
{
	if (!SSL_CTX_set_default_verify_paths (ctx))
	{
		__SSL_fill_err_buf ("SSL_CTX_set_default_verify_paths");
		return (err_buf);
	}
/*
	if (cacert)
	{
		if (!SSL_CTX_load_verify_locations (ctx, cacert, NULL))
		{
			__SSL_fill_err_buf ("SSL_CTX_load_verify_locations");
			return (err_buf);
		}
	}
*/
	SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER, verify_callback);

	return (NULL);
}


xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs) {
    xmlChar *tokens;
    xmlNodeSetPtr ret;
    xmlXPathObjectPtr obj;

    CHECK_ARITY(1);
    obj = valuePop(ctxt);
    if (obj == NULL) XP_ERROR(XPATH_INVALID_OPERAND);
    if ((obj->type == XPATH_NODESET) || (obj->type == XPATH_XSLT_TREE)) {
	xmlNodeSetPtr ns;
	int i;

	ret = xmlXPathNodeSetCreate(NULL);
        /*
         * FIXME -- in an out-of-memory condition this will behave badly.
         * The solution is not clear -- we already popped an item from
         * ctxt, so the object is in a corrupt state.
         */

	if (obj->nodesetval != NULL) {
	    for (i = 0; i < obj->nodesetval->nodeNr; i++) {
		tokens =
		    xmlXPathCastNodeToString(obj->nodesetval->nodeTab[i]);
		ns = xmlXPathGetElementsByIds(ctxt->context->doc, tokens);
		ret = xmlXPathNodeSetMerge(ret, ns);
		xmlXPathFreeNodeSet(ns);
		if (tokens != NULL)
		    xmlFree(tokens);
	    }
	}
	xmlXPathReleaseObject(ctxt->context, obj);
	valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, ret));
	return;
    }
    obj = xmlXPathCacheConvertString(ctxt->context, obj);
    ret = xmlXPathGetElementsByIds(ctxt->context->doc, obj->stringval);
    valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, ret));
    xmlXPathReleaseObject(ctxt->context, obj);
    return;
}


void ContextState::PushTextureUnpackState() const {
  api()->glPixelStoreiFn(GL_UNPACK_ALIGNMENT, 1);

  if (bound_pixel_unpack_buffer.get()) {
    api()->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, 0);
    api()->glPixelStoreiFn(GL_UNPACK_ROW_LENGTH, 0);
    api()->glPixelStoreiFn(GL_UNPACK_IMAGE_HEIGHT, 0);
    DCHECK_EQ(0, unpack_skip_pixels);
    DCHECK_EQ(0, unpack_skip_rows);
    DCHECK_EQ(0, unpack_skip_images);
  }
}


int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  Vdbe *v = pFrame->v;
  closeCursorsInFrame(v);
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  v->anExec = pFrame->anExec;
#endif
  v->aOp = pFrame->aOp;
  v->nOp = pFrame->nOp;
  v->aMem = pFrame->aMem;
  v->nMem = pFrame->nMem;
  v->apCsr = pFrame->apCsr;
  v->nCursor = pFrame->nCursor;
  v->db->lastRowid = pFrame->lastRowid;
  v->nChange = pFrame->nChange;
  v->db->nChange = pFrame->nDbChange;
  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  v->pAuxData = pFrame->pAuxData;
  pFrame->pAuxData = 0;
  return pFrame->pc;
}


void BrowserView::ProcessFullscreen(bool fullscreen,
                                    const GURL& url,
                                    ExclusiveAccessBubbleType bubble_type) {
  if (in_process_fullscreen_)
    return;
  in_process_fullscreen_ = true;

  if (fullscreen) {
    views::FocusManager* focus_manager = GetFocusManager();
    DCHECK(focus_manager);
    if (GetLocationBarView()->Contains(focus_manager->GetFocusedView()))
      focus_manager->ClearFocus();

    if (FullscreenControlHost::IsFullscreenExitUIEnabled()) {
#if defined(USE_AURA)
      frame_->GetNativeView()->AddPreTargetHandler(
          GetFullscreenControlHost(), ui::EventTarget::Priority::kSystem);
#else
      fullscreen_control_host_event_monitor_ =
          views::EventMonitor::CreateWindowMonitor(GetFullscreenControlHost(),
                                                   GetNativeWindow());
#endif
    }
  } else {
    exclusive_access_bubble_.reset();

    if (fullscreen_control_host_) {
      fullscreen_control_host_->Hide(false);
#if defined(USE_AURA)
      auto* native_view = frame_->GetNativeView();
      if (native_view)
        native_view->RemovePreTargetHandler(fullscreen_control_host_.get());
#else
      fullscreen_control_host_event_monitor_.reset();
#endif
    }
  }

  frame_->SetFullscreen(fullscreen);

  const bool should_stay_in_immersive =
      !fullscreen &&
      immersive_mode_controller_->ShouldStayImmersiveAfterExitingFullscreen();
  if (ShouldUseImmersiveFullscreenForUrl(url) && !should_stay_in_immersive)
    immersive_mode_controller_->SetEnabled(fullscreen);

  browser_->WindowFullscreenStateWillChange();
  browser_->WindowFullscreenStateChanged();

  if (fullscreen && !chrome::IsRunningInAppMode()) {
    UpdateExclusiveAccessExitBubbleContent(url, bubble_type,
                                           ExclusiveAccessBubbleHideCallback(),
                                           /*force_update=*/false);
  }

  in_process_fullscreen_ = false;
  ToolbarSizeChanged(false);

  WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
  if (contents && PermissionRequestManager::FromWebContents(contents))
    PermissionRequestManager::FromWebContents(contents)->UpdateAnchorPosition();
}


static unsigned uivector_resize(uivector* p, size_t size)
{
  if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
  p->size = size;
  return 1; /*success*/
}


bfad_im_get_host_port_id(struct Scsi_Host *shost)
{
	struct bfad_im_port_s *im_port =
			(struct bfad_im_port_s *) shost->hostdata[0];
	struct bfad_port_s    *port = im_port->port;

	fc_host_port_id(shost) =
			bfa_hton3b(bfa_fcs_lport_get_fcid(port->fcs_port));
}


put_line(FILE *fd, char *s)
{
    if (fputs(s, fd) < 0 || put_eol(fd) == FAIL)
	return FAIL;
    return OK;
}


GLvoid StubGLGenTextures(GLsizei n, GLuint* textures) {
  glGenTextures(n, textures);
}


scoped_refptr<const Extension> GetExtensionWithHostPermission(
    const std::string& id,
    const std::string& host_permissions,
    Manifest::Location location) {
  ListBuilder permissions;
  if (!host_permissions.empty())
    permissions.Append(host_permissions);

  return ExtensionBuilder()
      .SetManifest(
          DictionaryBuilder()
              .Set("name", id)
              .Set("description", "an extension")
              .Set("manifest_version", 2)
              .Set("version", "1.0.0")
              .Set("permissions", permissions.Pass())
              .Build())
      .SetLocation(location)
      .SetID(id)
      .Build();
}


void cpu_save(QEMUFile *f, void *opaque)

{

    CPUState *env = (CPUState *)opaque;

    unsigned int i, j;

    cpu_synchronize_state(env);

    for (i = 0; i < 32; i++)

        qemu_put_betls(f, &env->gpr[i]);

#if !defined(TARGET_PPC64)

    for (i = 0; i < 32; i++)

        qemu_put_betls(f, &env->gprh[i]);

#endif

    qemu_put_betls(f, &env->lr);

    qemu_put_betls(f, &env->ctr);

    for (i = 0; i < 8; i++)

        qemu_put_be32s(f, &env->crf[i]);

    qemu_put_betls(f, &env->xer);

    qemu_put_betls(f, &env->reserve_addr);

    qemu_put_betls(f, &env->msr);

    for (i = 0; i < 4; i++)

        qemu_put_betls(f, &env->tgpr[i]);

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

        union {

            float64 d;

            uint64_t l;

        } u;

        u.d = env->fpr[i];

        qemu_put_be64(f, u.l);

    }

    qemu_put_be32s(f, &env->fpscr);

    qemu_put_sbe32s(f, &env->access_type);

#if !defined(CONFIG_USER_ONLY)

#if defined(TARGET_PPC64)

    qemu_put_betls(f, &env->asr);

    qemu_put_sbe32s(f, &env->slb_nr);

#endif

    qemu_put_betls(f, &env->sdr1);

    for (i = 0; i < 32; i++)

        qemu_put_betls(f, &env->sr[i]);

    for (i = 0; i < 2; i++)

        for (j = 0; j < 8; j++)

            qemu_put_betls(f, &env->DBAT[i][j]);

    for (i = 0; i < 2; i++)

        for (j = 0; j < 8; j++)

            qemu_put_betls(f, &env->IBAT[i][j]);

    qemu_put_sbe32s(f, &env->nb_tlb);

    qemu_put_sbe32s(f, &env->tlb_per_way);

    qemu_put_sbe32s(f, &env->nb_ways);

    qemu_put_sbe32s(f, &env->last_way);

    qemu_put_sbe32s(f, &env->id_tlbs);

    qemu_put_sbe32s(f, &env->nb_pids);

    if (env->tlb) {

        // XXX assumes 6xx

        for (i = 0; i < env->nb_tlb; i++) {

            qemu_put_betls(f, &env->tlb[i].tlb6.pte0);

            qemu_put_betls(f, &env->tlb[i].tlb6.pte1);

            qemu_put_betls(f, &env->tlb[i].tlb6.EPN);

        }

    }

    for (i = 0; i < 4; i++)

        qemu_put_betls(f, &env->pb[i]);

#endif

    for (i = 0; i < 1024; i++)

        qemu_put_betls(f, &env->spr[i]);

    qemu_put_be32s(f, &env->vscr);

    qemu_put_be64s(f, &env->spe_acc);

    qemu_put_be32s(f, &env->spe_fscr);

    qemu_put_betls(f, &env->msr_mask);

    qemu_put_be32s(f, &env->flags);

    qemu_put_sbe32s(f, &env->error_code);

    qemu_put_be32s(f, &env->pending_interrupts);

#if !defined(CONFIG_USER_ONLY)

    qemu_put_be32s(f, &env->irq_input_state);

    for (i = 0; i < POWERPC_EXCP_NB; i++)

        qemu_put_betls(f, &env->excp_vectors[i]);

    qemu_put_betls(f, &env->excp_prefix);

    qemu_put_betls(f, &env->hreset_excp_prefix);

    qemu_put_betls(f, &env->ivor_mask);

    qemu_put_betls(f, &env->ivpr_mask);

    qemu_put_betls(f, &env->hreset_vector);

#endif

    qemu_put_betls(f, &env->nip);

    qemu_put_betls(f, &env->hflags);

    qemu_put_betls(f, &env->hflags_nmsr);

    qemu_put_sbe32s(f, &env->mmu_idx);

    qemu_put_sbe32s(f, &env->power_mode);

}


static ssize_t regulator_min_uA_show(struct device *dev,
				    struct device_attribute *attr, char *buf)
{
	struct regulator_dev *rdev = dev_get_drvdata(dev);

	if (!rdev->constraints)
		return sprintf(buf, "constraint not defined\n");

	return sprintf(buf, "%d\n", rdev->constraints->min_uA);
}


static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,
			      struct ext4_ext_path *path,
			      ext4_lblk_t block)
{
	if (path) {
		int depth = path->p_depth;
		struct ext4_extent *ex;

		/*
		 * Try to predict block placement assuming that we are
		 * filling in a file which will eventually be
		 * non-sparse --- i.e., in the case of libbfd writing
		 * an ELF object sections out-of-order but in a way
		 * the eventually results in a contiguous object or
		 * executable file, or some database extending a table
		 * space file.  However, this is actually somewhat
		 * non-ideal if we are writing a sparse file such as
		 * qemu or KVM writing a raw image file that is going
		 * to stay fairly sparse, since it will end up
		 * fragmenting the file system's free space.  Maybe we
		 * should have some hueristics or some way to allow
		 * userspace to pass a hint to file system,
		 * especially if the latter case turns out to be
		 * common.
		 */
		ex = path[depth].p_ext;
		if (ex) {
			ext4_fsblk_t ext_pblk = ext4_ext_pblock(ex);
			ext4_lblk_t ext_block = le32_to_cpu(ex->ee_block);

			if (block > ext_block)
				return ext_pblk + (block - ext_block);
			else
				return ext_pblk - (ext_block - block);
		}

		/* it looks like index is empty;
		 * try to find starting block from index itself */
		if (path[depth].p_bh)
			return path[depth].p_bh->b_blocknr;
	}

	/* OK. use inode's group */
	return ext4_inode_to_goal_block(inode);
}


person_get_spriteset(const person_t* person)
{
	return person->sprite;
}


struct perf_event *perf_event_get(unsigned int fd)
{
	int err;
	struct fd f;
	struct perf_event *event;

	err = perf_fget_light(fd, &f);
	if (err)
		return ERR_PTR(err);

	event = f.file->private_data;
	atomic_long_inc(&event->refcount);
	fdput(f);

	return event;
}


  void GetTouchActionsForChild(
      RenderWidgetHostInputEventRouter* router,
      RenderWidgetHostViewBase* rwhv_root,
      RenderWidgetHostViewBase* rwhv_child,
      const gfx::Point& event_position,
      base::Optional<cc::TouchAction>& effective_touch_action,
      base::Optional<cc::TouchAction>& whitelisted_touch_action) {
    InputEventAckWaiter ack_observer(
        rwhv_child->GetRenderWidgetHost(),
        base::BindRepeating([](content::InputEventAckSource source,
                               content::InputEventAckState state,
                               const blink::WebInputEvent& event) {
          return event.GetType() == blink::WebGestureEvent::kTouchStart ||
                 event.GetType() == blink::WebGestureEvent::kTouchMove ||
                 event.GetType() == blink::WebGestureEvent::kTouchEnd;
        }));

    InputRouterImpl* input_router = static_cast<InputRouterImpl*>(
        static_cast<RenderWidgetHostImpl*>(rwhv_child->GetRenderWidgetHost())
            ->input_router());
    input_router->touch_action_filter_.allowed_touch_action_.reset();
    input_router->touch_action_filter_.white_listed_touch_action_.reset();
    ack_observer.Reset();
    SyntheticWebTouchEvent touch_event;
    int index = touch_event.PressPoint(event_position.x(), event_position.y());
    router->RouteTouchEvent(rwhv_root, &touch_event,
                            ui::LatencyInfo(ui::SourceEventType::TOUCH));
    ack_observer.Wait();
    effective_touch_action =
        input_router->touch_action_filter_.allowed_touch_action_;
    whitelisted_touch_action =
        input_router->touch_action_filter_.white_listed_touch_action_;

    ack_observer.Reset();
    touch_event.MovePoint(index, 1, 1);
    router->RouteTouchEvent(rwhv_root, &touch_event,
                            ui::LatencyInfo(ui::SourceEventType::TOUCH));
    ack_observer.Wait();

    ack_observer.Reset();
    touch_event.ReleasePoint(index);
    router->RouteTouchEvent(rwhv_root, &touch_event,
                            ui::LatencyInfo(ui::SourceEventType::TOUCH));
    ack_observer.Wait();
  }


bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
  if (!completed_handshake_)
    return false;
  if (user_read_buf_.get() || user_write_buf_.get())
    return false;
  if (BIO_ctrl_pending(transport_bio_) > 0 ||
      BIO_ctrl_wpending(transport_bio_) > 0) {
    return false;
  }

  return transport_->socket()->IsConnectedAndIdle();
}


void ChromeInvalidationClient::EmitStateChange() {
  DCHECK(CalledOnValidThread());
  if (GetState() == NO_NOTIFICATION_ERROR) {
    listener_->OnNotificationsEnabled();
  } else {
    listener_->OnNotificationsDisabled(GetState());
  }
}


search_memslots(struct kvm_memslots *slots, gfn_t gfn)
{
	struct kvm_memory_slot *memslot;

	kvm_for_each_memslot(memslot, slots)
		if (gfn >= memslot->base_gfn &&
		      gfn < memslot->base_gfn + memslot->npages)
			return memslot;

	return NULL;
}


AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
{
    int status = HTTP_OK;

    r->unparsed_uri = apr_pstrdup(r->pool, uri);

    /* http://issues.apache.org/bugzilla/show_bug.cgi?id=31875
     * http://issues.apache.org/bugzilla/show_bug.cgi?id=28450
     *
     * This is not in fact a URI, it's a path.  That matters in the
     * case of a leading double-slash.  We need to resolve the issue
     * by normalising that out before treating it as a URI.
     */
    while ((uri[0] == '/') && (uri[1] == '/')) {
        ++uri ;
    }
    if (r->method_number == M_CONNECT) {
        status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
    }
    else {
        status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
    }

    if (status == APR_SUCCESS) {
        /* if it has a scheme we may need to do absoluteURI vhost stuff */
        if (r->parsed_uri.scheme
            && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r))) {
            r->hostname = r->parsed_uri.hostname;
        }
        else if (r->method_number == M_CONNECT) {
            r->hostname = r->parsed_uri.hostname;
        }

        r->args = r->parsed_uri.query;
        r->uri = r->parsed_uri.path ? r->parsed_uri.path
                 : apr_pstrdup(r->pool, "/");

#if defined(OS2) || defined(WIN32)
        /* Handle path translations for OS/2 and plug security hole.
         * This will prevent "http://www.wherever.com/..\..\/" from
         * returning a directory for the root drive.
         */
        {
            char *x;

            for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
                *x = '/';
        }
#endif /* OS2 || WIN32 */
    }
    else {
        r->args = NULL;
        r->hostname = NULL;
        r->status = HTTP_BAD_REQUEST;             /* set error status */
        r->uri = apr_pstrdup(r->pool, uri);
    }
}


static void disconnectWindow(const sp<ANativeWindow>& window) {
 if (window != 0) {
 status_t result = native_window_api_disconnect(window.get(),
                NATIVE_WINDOW_API_CAMERA);
 if (result != NO_ERROR) {
            ALOGW("native_window_api_disconnect failed: %s (%d)", strerror(-result),
                    result);
 }
 }
}


  void WaitUntilProxyLookedUp(const GURL& url) {
    wait_event_ = WaitEvent::kProxy;
    DCHECK(waiting_on_proxy_.is_empty());
    waiting_on_proxy_ = url;
    Wait();
  }


clock_gettime_with_res(clockid_t clock_id, struct timespec *tp, struct timespec *res)
{
  int ret;

  if ((!tp) || (!res))
    return -1;

  ret = clock_gettime(clock_id, tp);
  /* this will only work for sub-second resolutions. */
  if (ret == 0 && res->tv_nsec > 1)
    tp->tv_nsec = (tp->tv_nsec/res->tv_nsec)*res->tv_nsec;

  return ret;
}


selftest_encr_2048 (gcry_sexp_t pkey, gcry_sexp_t skey)
{
  const char *errtxt = NULL;
  gcry_error_t err;
  static const char plaintext[] =
    "Jim quickly realized that the beautiful gowns are expensive.";
  gcry_sexp_t plain = NULL;
  gcry_sexp_t encr  = NULL;
  gcry_mpi_t  ciphertext = NULL;
  gcry_sexp_t decr  = NULL;
  char *decr_plaintext = NULL;
  gcry_sexp_t tmplist = NULL;
  /* expected result of encrypting the plaintext with sample_secret_key */
  static const char ref_data[] =
    "18022e2593a402a737caaa93b4c7e750e20ca265452980e1d6b7710fbd3e"
    "7dce72be5c2110fb47691cb38f42170ee3b4a37f2498d4a51567d762585e"
    "4cb81d04fbc7df4144f8e5eac2d4b8688521b64011f11d7ad53f4c874004"
    "819856f2e2a6f83d1c9c4e73ac26089789c14482b0b8d44139133c88c4a5"
    "2dba9dd6d6ffc622666b7d129168333d999706af30a2d7d272db7734e5ed"
    "fb8c64ea3018af3ad20f4a013a5060cb0f5e72753967bebe294280a6ed0d"
    "dbd3c4f11d0a8696e9d32a0dc03deb0b5e49b2cbd1503392642d4e1211f3"
    "e8e2ee38abaa3671ccd57fcde8ca76e85fd2cb77c35706a970a213a27352"
    "cec92a9604d543ddb5fc478ff50e0622";
  gcry_mpi_t ref_mpi = NULL;

  /* Put the plaintext into an S-expression.  */
  err = sexp_build (&plain, NULL, "(data (flags raw) (value %s))", plaintext);
  if (err)
    {
      errtxt = "converting data failed";
      goto leave;
    }

  /* Encrypt.  */
  err = _gcry_pk_encrypt (&encr, plain, pkey);
  if (err)
    {
      errtxt = "encrypt failed";
      goto leave;
    }

  err = _gcry_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL);
  if (err)
    {
      errtxt = "converting encrydata to mpi failed";
      goto leave;
    }

  /* Extraxt the ciphertext from the returned S-expression.  */
  /*sexp_dump (encr);*/
  ciphertext = extract_a_from_sexp (encr);
  if (!ciphertext)
    {
      errtxt = "gcry_pk_decrypt returned garbage";
      goto leave;
    }

  /* Check that the ciphertext does no match the plaintext.  */
  /* _gcry_log_printmpi ("plaintext", plaintext); */
  /* _gcry_log_printmpi ("ciphertxt", ciphertext); */
  if (mpi_cmp (ref_mpi, ciphertext))
    {
      errtxt = "ciphertext doesn't match reference data";
      goto leave;
    }

  /* Decrypt.  */
  err = _gcry_pk_decrypt (&decr, encr, skey);
  if (err)
    {
      errtxt = "decrypt failed";
      goto leave;
    }

  /* Extract the decrypted data from the S-expression.  Note that the
     output of gcry_pk_decrypt depends on whether a flags lists occurs
     in its input data.  Because we passed the output of
     gcry_pk_encrypt directly to gcry_pk_decrypt, such a flag value
     won't be there as of today.  To be prepared for future changes we
     take care of it anyway.  */
  tmplist = sexp_find_token (decr, "value", 0);
  if (tmplist)
    decr_plaintext = sexp_nth_string (tmplist, 1);
  else
    decr_plaintext = sexp_nth_string (decr, 0);
  if (!decr_plaintext)
    {
      errtxt = "decrypt returned no plaintext";
      goto leave;
    }

  /* Check that the decrypted plaintext matches the original  plaintext.  */
  if (strcmp (plaintext, decr_plaintext))
    {
      errtxt = "mismatch";
      goto leave;
    }

 leave:
  sexp_release (tmplist);
  xfree (decr_plaintext);
  sexp_release (decr);
  _gcry_mpi_release (ciphertext);
  _gcry_mpi_release (ref_mpi);
  sexp_release (encr);
  sexp_release (plain);
  return errtxt;
}


R_API ut64 r_bin_java_class_cp_calc_size(RBinJavaCPTypeObj *obj) {
	ut64 size = 0;
	// ut8 tag = buffer[0];
	size += 1;
	// obj->info.cp_class.name_idx = R_BIN_JAVA_USHORT (buffer, 1);
	size += 2;
	return size;
}


 void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped(
     const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
     int gpu_host_id) {
  ImageTransportFactoryAndroid* factory =
      ImageTransportFactoryAndroid::GetInstance();

  // need to delay the ACK until after commit and use more than a single
  // texture.
   DCHECK(!CompositorImpl::IsThreadingEnabled());

  uint64 previous_buffer = current_buffer_id_;
  if (previous_buffer && texture_id_in_layer_) {
    DCHECK(id_to_mailbox_.find(previous_buffer) != id_to_mailbox_.end());
    ImageTransportFactoryAndroid::GetInstance()->ReleaseTexture(
        texture_id_in_layer_,
        reinterpret_cast<const signed char*>(
            id_to_mailbox_[previous_buffer].c_str()));
  }

  current_buffer_id_ = params.surface_handle;
  if (!texture_id_in_layer_) {
    texture_id_in_layer_ = factory->CreateTexture();
    texture_layer_->setTextureId(texture_id_in_layer_);
  }

  DCHECK(id_to_mailbox_.find(current_buffer_id_) != id_to_mailbox_.end());
  ImageTransportFactoryAndroid::GetInstance()->AcquireTexture(
      texture_id_in_layer_,
      reinterpret_cast<const signed char*>(
          id_to_mailbox_[current_buffer_id_].c_str()));
  texture_layer_->setNeedsDisplay();
  texture_layer_->setBounds(params.size);
  texture_size_in_layer_ = params.size;

   uint32 sync_point =
       ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint();
   RenderWidgetHostImpl::AcknowledgeBufferPresent(
      params.route_id, gpu_host_id, previous_buffer, sync_point);
 }


static int nl80211_authenticate(struct sk_buff *skb, struct genl_info *info)
{
	struct cfg80211_registered_device *rdev = info->user_ptr[0];
	struct net_device *dev = info->user_ptr[1];
	struct ieee80211_channel *chan;
	const u8 *bssid, *ssid, *ie = NULL;
	int err, ssid_len, ie_len = 0;
	enum nl80211_auth_type auth_type;
	struct key_parse key;
	bool local_state_change;

	if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
		return -EINVAL;

	if (!info->attrs[NL80211_ATTR_MAC])
		return -EINVAL;

	if (!info->attrs[NL80211_ATTR_AUTH_TYPE])
		return -EINVAL;

	if (!info->attrs[NL80211_ATTR_SSID])
		return -EINVAL;

	if (!info->attrs[NL80211_ATTR_WIPHY_FREQ])
		return -EINVAL;

	err = nl80211_parse_key(info, &key);
	if (err)
		return err;

	if (key.idx >= 0) {
		if (key.type != -1 && key.type != NL80211_KEYTYPE_GROUP)
			return -EINVAL;
		if (!key.p.key || !key.p.key_len)
			return -EINVAL;
		if ((key.p.cipher != WLAN_CIPHER_SUITE_WEP40 ||
		     key.p.key_len != WLAN_KEY_LEN_WEP40) &&
		    (key.p.cipher != WLAN_CIPHER_SUITE_WEP104 ||
		     key.p.key_len != WLAN_KEY_LEN_WEP104))
			return -EINVAL;
		if (key.idx > 4)
			return -EINVAL;
	} else {
		key.p.key_len = 0;
		key.p.key = NULL;
	}

	if (key.idx >= 0) {
		int i;
		bool ok = false;
		for (i = 0; i < rdev->wiphy.n_cipher_suites; i++) {
			if (key.p.cipher == rdev->wiphy.cipher_suites[i]) {
				ok = true;
				break;
			}
		}
		if (!ok)
			return -EINVAL;
	}

	if (!rdev->ops->auth)
		return -EOPNOTSUPP;

	if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
	    dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
		return -EOPNOTSUPP;

	bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
	chan = ieee80211_get_channel(&rdev->wiphy,
		nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]));
	if (!chan || (chan->flags & IEEE80211_CHAN_DISABLED))
		return -EINVAL;

	ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
	ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);

	if (info->attrs[NL80211_ATTR_IE]) {
		ie = nla_data(info->attrs[NL80211_ATTR_IE]);
		ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
	}

	auth_type = nla_get_u32(info->attrs[NL80211_ATTR_AUTH_TYPE]);
	if (!nl80211_valid_auth_type(auth_type))
		return -EINVAL;

	local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];

	return cfg80211_mlme_auth(rdev, dev, chan, auth_type, bssid,
				  ssid, ssid_len, ie, ie_len,
				  key.p.key, key.p.key_len, key.idx,
				  local_state_change);


void Con_DrawConsole( void ) {
	// check for console width changes from a vid mode change
	Con_CheckResize();

	// if disconnected, render console full screen
	if ( clc.state == CA_DISCONNECTED ) {
		if ( !( Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME)) ) {
			Con_DrawSolidConsole( 1.0 );
			return;
		}
	}

	if ( con.displayFrac ) {
		Con_DrawSolidConsole( con.displayFrac );
	} else {
		// draw notify lines
		if ( clc.state == CA_ACTIVE ) {
			Con_DrawNotify();
		}
	}
}


void d_exchange(struct dentry *dentry1, struct dentry *dentry2)
{
	write_seqlock(&rename_lock);

	WARN_ON(!dentry1->d_inode);
	WARN_ON(!dentry2->d_inode);
	WARN_ON(IS_ROOT(dentry1));
	WARN_ON(IS_ROOT(dentry2));

	__d_move(dentry1, dentry2, true);

	write_sequnlock(&rename_lock);
}


channel_register_status_confirm(int id, channel_confirm_cb *cb,
    channel_confirm_abandon_cb *abandon_cb, void *ctx)
{
	struct channel_confirm *cc;
	Channel *c;

	if ((c = channel_lookup(id)) == NULL)
		fatal("channel_register_expect: %d: bad id", id);

	cc = xcalloc(1, sizeof(*cc));
	cc->cb = cb;
	cc->abandon_cb = abandon_cb;
	cc->ctx = ctx;
	TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
}


int WebRTCTransportImpl::SendPacket(int channel, const void* data, int len) {
  return network_->ReceivedRTPPacket(channel, data, len);
}


GF_Box *stsc_box_new()
{
	ISOM_DECL_BOX_ALLOC(GF_SampleToChunkBox, GF_ISOM_BOX_TYPE_STSC);
	return (GF_Box *)tmp;
}


std::vector<uint8_t> GetOutput() { return ExtractVector<uint8_t>(output_); }


static unsigned int dec_addi_r(DisasContext *dc)

{

	TCGv t0;

	DIS(fprintf (logfile, "addi.%c $r%u, $r%u\n",

		    memsize_char(memsize_zz(dc)), dc->op2, dc->op1));

	cris_cc_mask(dc, 0);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_shl_tl(t0, cpu_R[dc->op2], tcg_const_tl(dc->zzsize));

	tcg_gen_add_tl(cpu_R[dc->op1], cpu_R[dc->op1], t0);

	tcg_temp_free(t0);

	return 2;

}


static int64_t encode_inter_mb_segment ( VP9_COMP * cpi , MACROBLOCK * x , int64_t best_yrd , int i , int * labelyrate , int64_t * distortion , int64_t * sse , ENTROPY_CONTEXT * ta , ENTROPY_CONTEXT * tl , int mi_row , int mi_col ) {
 int k ;
 MACROBLOCKD * xd = & x -> e_mbd ;
 struct macroblockd_plane * const pd = & xd -> plane [ 0 ] ;
 struct macroblock_plane * const p = & x -> plane [ 0 ] ;
 MODE_INFO * const mi = xd -> mi [ 0 ] ;
 const BLOCK_SIZE plane_bsize = get_plane_block_size ( mi -> mbmi . sb_type , pd ) ;
 const int width = 4 * num_4x4_blocks_wide_lookup [ plane_bsize ] ;
 const int height = 4 * num_4x4_blocks_high_lookup [ plane_bsize ] ;
 int idx , idy ;
 const uint8_t * const src = & p -> src . buf [ raster_block_offset ( BLOCK_8X8 , i , p -> src . stride ) ] ;
 uint8_t * const dst = & pd -> dst . buf [ raster_block_offset ( BLOCK_8X8 , i , pd -> dst . stride ) ] ;
 int64_t thisdistortion = 0 , thissse = 0 ;
 int thisrate = 0 , ref ;
 const scan_order * so = & vp9_default_scan_orders [ TX_4X4 ] ;
 const int is_compound = has_second_ref ( & mi -> mbmi ) ;
 const InterpKernel * kernel = vp9_get_interp_kernel ( mi -> mbmi . interp_filter ) ;
 for ( ref = 0 ;
 ref < 1 + is_compound ;
 ++ ref ) {
 const uint8_t * pre = & pd -> pre [ ref ] . buf [ raster_block_offset ( BLOCK_8X8 , i , pd -> pre [ ref ] . stride ) ] ;
 vp9_build_inter_predictor ( pre , pd -> pre [ ref ] . stride , dst , pd -> dst . stride , & mi -> bmi [ i ] . as_mv [ ref ] . as_mv , & xd -> block_refs [ ref ] -> sf , width , height , ref , kernel , MV_PRECISION_Q3 , mi_col * MI_SIZE + 4 * ( i % 2 ) , mi_row * MI_SIZE + 4 * ( i / 2 ) ) ;
 }
 vp9_subtract_block ( height , width , raster_block_offset_int16 ( BLOCK_8X8 , i , p -> src_diff ) , 8 , src , p -> src . stride , dst , pd -> dst . stride ) ;
 k = i ;
 for ( idy = 0 ;
 idy < height / 4 ;
 ++ idy ) {
 for ( idx = 0 ;
 idx < width / 4 ;
 ++ idx ) {
 int64_t ssz , rd , rd1 , rd2 ;
 int16_t * coeff ;
 k += ( idy * 2 + idx ) ;
 coeff = BLOCK_OFFSET ( p -> coeff , k ) ;
 x -> fwd_txm4x4 ( raster_block_offset_int16 ( BLOCK_8X8 , k , p -> src_diff ) , coeff , 8 ) ;
 vp9_regular_quantize_b_4x4 ( x , 0 , k , so -> scan , so -> iscan ) ;
 thisdistortion += vp9_block_error ( coeff , BLOCK_OFFSET ( pd -> dqcoeff , k ) , 16 , & ssz ) ;
 thissse += ssz ;
 thisrate += cost_coeffs ( x , 0 , k , ta + ( k & 1 ) , tl + ( k >> 1 ) , TX_4X4 , so -> scan , so -> neighbors , cpi -> sf . use_fast_coef_costing ) ;
 rd1 = RDCOST ( x -> rdmult , x -> rddiv , thisrate , thisdistortion >> 2 ) ;
 rd2 = RDCOST ( x -> rdmult , x -> rddiv , 0 , thissse >> 2 ) ;
 rd = MIN ( rd1 , rd2 ) ;
 if ( rd >= best_yrd ) return INT64_MAX ;
 }
 }
 * distortion = thisdistortion >> 2 ;
 * labelyrate = thisrate ;
 * sse = thissse >> 2 ;
 return RDCOST ( x -> rdmult , x -> rddiv , * labelyrate , * distortion ) ;
 }


void NavigationController::RemoveEntryAtIndex(int index,
void NavigationController::RemoveEntryAtIndex(int index) {
  if (index == last_committed_entry_index_)
    return;

   RemoveEntryAtIndexInternal(index);
 }


WebViewPlugin* WebViewPlugin::Create(WebViewPlugin::Delegate* delegate,
                                     const WebPreferences& preferences,
                                     const std::string& html_data,
                                     const GURL& url) {
  WebViewPlugin* plugin = new WebViewPlugin(delegate);
  WebView* web_view = plugin->web_view();
  preferences.Apply(web_view);
  web_view->mainFrame()->loadHTMLString(html_data, url);
  return plugin;
}


static BOOL ntlm_md5_update_uint32_be(WINPR_DIGEST_CTX* md5, UINT32 num)
{
	BYTE be32[4];
	be32[0] = (num >> 0) & 0xFF;
	be32[1] = (num >> 8) & 0xFF;
	be32[2] = (num >> 16) & 0xFF;
	be32[3] = (num >> 24) & 0xFF;
	return winpr_Digest_Update(md5, be32, 4);
}


static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)
{
	int k, l = path->p_depth;

	ext_debug("path:");
	for (k = 0; k <= l; k++, path++) {
		if (path->p_idx) {
		  ext_debug("  %d->%llu", le32_to_cpu(path->p_idx->ei_block),
			    ext4_idx_pblock(path->p_idx));
		} else if (path->p_ext) {
			ext_debug("  %d:[%d]%d:%llu ",
				  le32_to_cpu(path->p_ext->ee_block),
				  ext4_ext_is_uninitialized(path->p_ext),
				  ext4_ext_get_actual_len(path->p_ext),
				  ext4_ext_pblock(path->p_ext));
		} else
			ext_debug("  []");
	}
	ext_debug("\n");
}


 std::string MasterPreferences::GetVariationsSeedSignature() const {
  return ExtractPrefString(chrome_variations::prefs::kVariationsSeedSignature);
 }


WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
    WebNavigationPolicy policy) {
  switch (policy) {
    case blink::kWebNavigationPolicyIgnore:
      return WindowOpenDisposition::IGNORE_ACTION;
    case blink::kWebNavigationPolicyDownload:
      return WindowOpenDisposition::SAVE_TO_DISK;
    case blink::kWebNavigationPolicyCurrentTab:
      return WindowOpenDisposition::CURRENT_TAB;
    case blink::kWebNavigationPolicyNewBackgroundTab:
      return WindowOpenDisposition::NEW_BACKGROUND_TAB;
    case blink::kWebNavigationPolicyNewForegroundTab:
      return WindowOpenDisposition::NEW_FOREGROUND_TAB;
    case blink::kWebNavigationPolicyNewWindow:
      return WindowOpenDisposition::NEW_WINDOW;
    case blink::kWebNavigationPolicyNewPopup:
      return WindowOpenDisposition::NEW_POPUP;
  default:
    NOTREACHED() << "Unexpected WebNavigationPolicy";
    return WindowOpenDisposition::IGNORE_ACTION;
  }
}


void SupervisedUserService::AddURLAccessRequest(const GURL& url,
                                                SuccessCallback callback) {
  GURL effective_url = policy::url_util::GetEmbeddedURL(url);
  if (!effective_url.is_valid())
    effective_url = url;
  AddPermissionRequestInternal(
      base::BindRepeating(CreateURLAccessRequest,
                          policy::url_util::Normalize(effective_url)),
      std::move(callback), 0);
}


static int parse_multipart(
        ogs_sbi_message_t *message, ogs_sbi_http_message_t *http)
{
    char *boundary = NULL;
    int i;

    multipart_parser_settings settings;
    multipart_parser_data_t data;

    multipart_parser *parser = NULL;

    ogs_assert(message);
    ogs_assert(http);

    memset(&settings, 0, sizeof(settings));
    settings.on_header_field = &on_header_field;
    settings.on_header_value = &on_header_value;
    settings.on_part_data = &on_part_data;
    settings.on_part_data_end = &on_part_data_end;

    for (i = 0; i < http->content_length; i++) {
        if (http->content[i] == '\r' && http->content[i+1] == '\n')
            break;
    }

    if (i >= http->content_length) {
        ogs_error("Invalid HTTP content [%d]", i);
        ogs_log_hexdump(OGS_LOG_ERROR,
                (unsigned char *)http->content, http->content_length);
        return OGS_ERROR;
    }

    boundary = ogs_strndup(http->content, i);
    ogs_assert(boundary);

    parser = multipart_parser_init(boundary, &settings);
    ogs_assert(parser);

    memset(&data, 0, sizeof(data));
    multipart_parser_set_data(parser, &data);
    multipart_parser_execute(parser, http->content, http->content_length);

    multipart_parser_free(parser);
    ogs_free(boundary);

    for (i = 0; i < data.num_of_part; i++) {
        SWITCH(data.part[i].content_type)
        CASE(OGS_SBI_CONTENT_JSON_TYPE)
            parse_json(message,
                    data.part[i].content_type, data.part[i].content);

            if (data.part[i].content_id)
                ogs_free(data.part[i].content_id);
            if (data.part[i].content_type)
                ogs_free(data.part[i].content_type);
            if (data.part[i].content)
                ogs_free(data.part[i].content);

            break;

        CASE(OGS_SBI_CONTENT_5GNAS_TYPE)
        CASE(OGS_SBI_CONTENT_NGAP_TYPE)
            http->part[http->num_of_part].content_id =
                data.part[i].content_id;
            http->part[http->num_of_part].content_type =
                data.part[i].content_type;
            http->part[http->num_of_part].pkbuf =
                ogs_pkbuf_alloc(NULL, data.part[i].content_length);
            ogs_expect_or_return_val(
                http->part[http->num_of_part].pkbuf, OGS_ERROR);
            ogs_pkbuf_put_data(http->part[http->num_of_part].pkbuf,
                data.part[i].content, data.part[i].content_length);

            message->part[message->num_of_part].content_id =
                http->part[http->num_of_part].content_id;
            message->part[message->num_of_part].content_type =
                http->part[http->num_of_part].content_type;
            message->part[message->num_of_part].pkbuf =
                ogs_pkbuf_copy(http->part[http->num_of_part].pkbuf);
            ogs_expect_or_return_val(
                message->part[message->num_of_part].pkbuf, OGS_ERROR);

            http->num_of_part++;
            message->num_of_part++;

            if (data.part[i].content)
                ogs_free(data.part[i].content);
            break;

        DEFAULT
            ogs_error("Unknown content-type[%s]", data.part[i].content_type);
        END
    }

    if (data.part[i].content_id)
        ogs_free(data.part[i].content_id);
    if (data.part[i].content_type)
        ogs_free(data.part[i].content_type);

    if (data.header_field)
        ogs_free(data.header_field);

    return OGS_OK;
}


  bool agent_is_active_oid(const hobject_t& oid) {
    Mutex::Locker l(agent_lock);
    return agent_oids.count(oid);
  }


WriterGetInfoPtr(WriterSock *curPtr, Tcl_HashTable *pools)
{
    NS_NONNULL_ASSERT(curPtr != NULL);
    NS_NONNULL_ASSERT(pools != NULL);

    if (curPtr->infoPtr == NULL) {
        int            isNew;
        Tcl_HashEntry  *hPtr;

        hPtr = Tcl_CreateHashEntry(pools, (void*)curPtr->poolPtr, &isNew);
        if (isNew == 1) {
            /*
             * This is a pool that we have not seen yet.
             */
            curPtr->infoPtr = ns_malloc(sizeof(ConnPoolInfo));
            curPtr->infoPtr->currentPoolRate = 0;
            curPtr->infoPtr->threadSlot =
                NsPoolAllocateThreadSlot(curPtr->poolPtr, Ns_ThreadId());
            Tcl_SetHashValue(hPtr, curPtr->infoPtr);
            Ns_Log(DriverDebug, "poollimit: pool '%s' allocate infoPtr with slot %lu poolLimit %d",
                   curPtr->poolPtr->pool,
                   curPtr->infoPtr->threadSlot,
                   curPtr->poolPtr->rate.poolLimit);
        } else {
            curPtr->infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr);
        }
    }

    return curPtr->infoPtr;
}


save_last_search_pattern(void)
{
    if (++did_save_last_search_spat != 1)
	// nested call, nothing to do
	return;

    saved_last_search_spat = spats[RE_SEARCH];
    if (spats[RE_SEARCH].pat != NULL)
	saved_last_search_spat.pat = vim_strsave(spats[RE_SEARCH].pat);
    saved_last_idx = last_idx;
    saved_no_hlsearch = no_hlsearch;
}


static void vmxnet3_get_tx_stats_from_file(QEMUFile *f,
    struct UPT1_TxStats *tx_stat)
{
    tx_stat->TSOPktsTxOK = qemu_get_be64(f);
    tx_stat->TSOBytesTxOK = qemu_get_be64(f);
    tx_stat->ucastPktsTxOK = qemu_get_be64(f);
    tx_stat->ucastBytesTxOK = qemu_get_be64(f);
    tx_stat->mcastPktsTxOK = qemu_get_be64(f);
    tx_stat->mcastBytesTxOK = qemu_get_be64(f);
    tx_stat->bcastPktsTxOK = qemu_get_be64(f);
    tx_stat->bcastBytesTxOK = qemu_get_be64(f);
    tx_stat->pktsTxError = qemu_get_be64(f);
    tx_stat->pktsTxDiscard = qemu_get_be64(f);
}


void MockRenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
  filter->OnFilterAdded(&sink());
}


  std::unique_ptr<content::TestNavigationManager> NavigateToURLAsync(
      const GURL& url) {
    chrome::NewTab(browser());
    content::WebContents* tab =
        browser()->tab_strip_model()->GetActiveWebContents();
    DCHECK(tab);
    auto observer = std::make_unique<content::TestNavigationManager>(tab, url);
    tab->GetController().LoadURL(url, content::Referrer(),
                                 ui::PAGE_TRANSITION_TYPED, std::string());
    return observer;
  }


static unsigned char *pep_get_sb(struct sk_buff *skb, u8 *ptype, u8 *plen,
					void *buf)
{
	void *data = NULL;
	struct {
		u8 sb_type;
		u8 sb_len;
	} *ph, h;
	int buflen = *plen;

	ph = skb_header_pointer(skb, 0, 2, &h);
	if (ph == NULL || ph->sb_len < 2 || !pskb_may_pull(skb, ph->sb_len))
		return NULL;
	ph->sb_len -= 2;
	*ptype = ph->sb_type;
	*plen = ph->sb_len;

	if (buflen > ph->sb_len)
		buflen = ph->sb_len;
	data = skb_header_pointer(skb, 2, buflen, buf);
	__skb_pull(skb, 2 + ph->sb_len);
	return data;
}


NPObject* WebPluginProxy::GetPluginElement() {
  if (plugin_element_)
    return plugin_element_;

  int npobject_route_id = channel_->GenerateRouteID();
  bool success = false;
  Send(new PluginHostMsg_GetPluginElement(route_id_, npobject_route_id,
                                          &success));
  if (!success)
    return NULL;

  plugin_element_ = NPObjectProxy::Create(
      channel_, npobject_route_id, containing_window_, page_url_);

  return plugin_element_;
}


static int sox_read_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    unsigned header_size, comment_size;

    double sample_rate, sample_rate_frac;

    AVStream *st;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;

    if (avio_rl32(pb) == SOX_TAG) {

        st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;

        header_size         = avio_rl32(pb);

        avio_skip(pb, 8); /* sample count */

        sample_rate         = av_int2double(avio_rl64(pb));

        st->codecpar->channels = avio_rl32(pb);

        comment_size        = avio_rl32(pb);

    } else {

        st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE;

        header_size         = avio_rb32(pb);

        avio_skip(pb, 8); /* sample count */

        sample_rate         = av_int2double(avio_rb64(pb));

        st->codecpar->channels = avio_rb32(pb);

        comment_size        = avio_rb32(pb);

    }

    if (comment_size > 0xFFFFFFFFU - SOX_FIXED_HDR - 4U) {

        av_log(s, AV_LOG_ERROR, "invalid comment size (%u)\n", comment_size);

        return AVERROR_INVALIDDATA;

    }

    if (sample_rate <= 0 || sample_rate > INT_MAX) {

        av_log(s, AV_LOG_ERROR, "invalid sample rate (%f)\n", sample_rate);

        return AVERROR_INVALIDDATA;

    }

    sample_rate_frac = sample_rate - floor(sample_rate);

    if (sample_rate_frac)

        av_log(s, AV_LOG_WARNING,

               "truncating fractional part of sample rate (%f)\n",

               sample_rate_frac);

    if ((header_size + 4) & 7 || header_size < SOX_FIXED_HDR + comment_size

        || st->codecpar->channels > 65535) /* Reserve top 16 bits */ {

        av_log(s, AV_LOG_ERROR, "invalid header\n");

        return AVERROR_INVALIDDATA;

    }

    if (comment_size && comment_size < UINT_MAX) {

        char *comment = av_malloc(comment_size+1);

        if(!comment)

            return AVERROR(ENOMEM);

        if (avio_read(pb, comment, comment_size) != comment_size) {

            av_freep(&comment);

            return AVERROR(EIO);

        }

        comment[comment_size] = 0;

        av_dict_set(&s->metadata, "comment", comment,

                               AV_DICT_DONT_STRDUP_VAL);

    }

    avio_skip(pb, header_size - SOX_FIXED_HDR - comment_size);

    st->codecpar->sample_rate           = sample_rate;

    st->codecpar->bits_per_coded_sample = 32;

    st->codecpar->bit_rate              = st->codecpar->sample_rate *

                                          st->codecpar->bits_per_coded_sample *

                                          st->codecpar->channels;

    st->codecpar->block_align           = st->codecpar->bits_per_coded_sample *

                                          st->codecpar->channels / 8;

    avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

    return 0;

}


static unsigned emulator_get_hflags(struct x86_emulate_ctxt *ctxt)
{
	return emul_to_vcpu(ctxt)->arch.hflags;
}


void memory_region_add_eventfd(MemoryRegion *mr,
                               hwaddr addr,
                               unsigned size,
                               bool match_data,
                               uint64_t data,
                               EventNotifier *e)
{
    MemoryRegionIoeventfd mrfd = {
        .addr.start = int128_make64(addr),
        .addr.size = int128_make64(size),
        .match_data = match_data,
        .data = data,
        .e = e,
    };
    unsigned i;
    if (size) {
        adjust_endianness(mr, &mrfd.data, size);
    memory_region_transaction_begin();
    for (i = 0; i < mr->ioeventfd_nb; ++i) {
        if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
            break;
    ++mr->ioeventfd_nb;
    mr->ioeventfds = g_realloc(mr->ioeventfds,
                                  sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
    memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
            sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
    mr->ioeventfds[i] = mrfd;
    ioeventfd_update_pending |= mr->enabled;
    memory_region_transaction_commit();


static int SpoolssGetPrinterData_q ( tvbuff_t * tvb , int offset , packet_info * pinfo , proto_tree * tree , dcerpc_info * di , guint8 * drep _U_ ) {
 dcerpc_call_value * dcv = ( dcerpc_call_value * ) di -> call_data ;
 char * value_name ;
 proto_item * hidden_item ;
 hidden_item = proto_tree_add_uint ( tree , hf_printerdata , tvb , offset , 0 , 1 ) ;
 PROTO_ITEM_SET_HIDDEN ( hidden_item ) ;
 offset = dissect_nt_policy_hnd ( tvb , offset , pinfo , tree , di , drep , hf_hnd , NULL , NULL , FALSE , FALSE ) ;
 value_name = NULL ;
 offset = dissect_ndr_cvstring ( tvb , offset , pinfo , tree , di , drep , sizeof ( guint16 ) , hf_printerdata_value , TRUE , value_name ? NULL : & value_name ) ;
 if ( ! pinfo -> fd -> flags . visited ) {
 if ( ! dcv -> se_data ) {
 if ( value_name ) {
 dcv -> se_data = wmem_strdup ( wmem_file_scope ( ) , value_name ) ;
 }
 }
 }
 col_append_fstr ( pinfo -> cinfo , COL_INFO , ", %s" , value_name ) ;
 offset = dissect_ndr_uint32 ( tvb , offset , pinfo , tree , di , drep , hf_offered , NULL ) ;
 return offset ;
 }


void Document::ScheduleUseShadowTreeUpdate(SVGUseElement& element) {
  use_elements_needing_update_.insert(&element);
  ScheduleLayoutTreeUpdateIfNeeded();
}


 static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
 {
 	spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
 	*data = &iterator->current;
 }


void CairoImageOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
				    int width, int height, GfxImageColorMap *colorMap,
				    int *maskColors, GBool inlineImg)
{
  cairo_t *cr;
  cairo_surface_t *surface;
  double x1, y1, x2, y2;
  double *ctm;
  double mat[6];
  CairoImage *image;

  ctm = state->getCTM();

  mat[0] = ctm[0];
  mat[1] = ctm[1];
  mat[2] = -ctm[2];
  mat[3] = -ctm[3];
  mat[4] = ctm[2] + ctm[4];
  mat[5] = ctm[3] + ctm[5];
  x1 = mat[4];
  y1 = mat[5];
  x2 = x1 + width;
  y2 = y1 + height;

  image = new CairoImage (x1, y1, x2, y2);
  saveImage (image);

  if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) {
    surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
    cr = cairo_create (surface);
    setCairo (cr);
    cairo_translate (cr, 0, height);
    cairo_scale (cr, width, -height);

    CairoOutputDev::drawImage(state, ref, str, width, height, colorMap, maskColors, inlineImg);
    image->setImage (surface);

    setCairo (NULL);
    cairo_surface_destroy (surface);
    cairo_destroy (cr);
  }
}


static void clamp_output_samples(struct iw_context *ctx, iw_tmpsample *out_pix, int num_out_pix)
{
	int i;

	for(i=0;i<num_out_pix;i++) {
		if(out_pix[i]<0.0) out_pix[i]=0.0;
		else if(out_pix[i]>1.0) out_pix[i]=1.0;
	}
}


void HandleMagnifyScreen(int delta_index) {
  if (Shell::GetInstance()->magnification_controller()->IsEnabled()) {
    float scale = Shell::GetInstance()->magnification_controller()->GetScale();
    int scale_index =
        std::floor(std::log(scale) / std::log(kMagnificationScaleFactor) + 0.5);

    int new_scale_index = std::max(0, std::min(8, scale_index + delta_index));

     Shell::GetInstance()->magnification_controller()->SetScale(
         std::pow(kMagnificationScaleFactor, new_scale_index), true);
   }
 }


static inline int get_duration(AVIStream *ast, int len)
{
    if (ast->sample_size)
        return len;
    else if (ast->dshow_block_align)
        return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
    else
        return 1;


static inline void yuv2rgbXinC(int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

				    int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

				    uint8_t *dest, int dstW, int dstbpp)

{

	if(dstbpp==32)

	{

		int i;

		for(i=0; i<(dstW>>1); i++){

			int j;

			int Y1=0;

			int Y2=0;

			int U=0;

			int V=0;

			int Cb, Cr, Cg;

			for(j=0; j<lumFilterSize; j++)

			{

				Y1 += lumSrc[j][2*i] * lumFilter[j];

				Y2 += lumSrc[j][2*i+1] * lumFilter[j];

			}

			for(j=0; j<chrFilterSize; j++)

			{

				U += chrSrc[j][i] * chrFilter[j];

				V += chrSrc[j][i+2048] * chrFilter[j];

			}

			Y1= clip_yuvtab_2568[ (Y1>>19) + 256 ];

			Y2= clip_yuvtab_2568[ (Y2>>19) + 256 ];

			U >>= 19;

			V >>= 19;

			Cb= clip_yuvtab_40cf[U+ 256];

			Cg= clip_yuvtab_1a1e[V+ 256] + yuvtab_0c92[U+ 256];

			Cr= clip_yuvtab_3343[V+ 256];

			dest[8*i+0]=clip_table[((Y1 + Cb) >>13)];

			dest[8*i+1]=clip_table[((Y1 + Cg) >>13)];

			dest[8*i+2]=clip_table[((Y1 + Cr) >>13)];

			dest[8*i+4]=clip_table[((Y2 + Cb) >>13)];

			dest[8*i+5]=clip_table[((Y2 + Cg) >>13)];

			dest[8*i+6]=clip_table[((Y2 + Cr) >>13)];

		}

	}

	else if(dstbpp==24)

	{

		int i;

		for(i=0; i<(dstW>>1); i++){

			int j;

			int Y1=0;

			int Y2=0;

			int U=0;

			int V=0;

			int Cb, Cr, Cg;

			for(j=0; j<lumFilterSize; j++)

			{

				Y1 += lumSrc[j][2*i] * lumFilter[j];

				Y2 += lumSrc[j][2*i+1] * lumFilter[j];

			}

			for(j=0; j<chrFilterSize; j++)

			{

				U += chrSrc[j][i] * chrFilter[j];

				V += chrSrc[j][i+2048] * chrFilter[j];

			}

			Y1= clip_yuvtab_2568[ (Y1>>19) + 256 ];

			Y2= clip_yuvtab_2568[ (Y2>>19) + 256 ];

			U >>= 19;

			V >>= 19;

			Cb= clip_yuvtab_40cf[U+ 256];

			Cg= clip_yuvtab_1a1e[V+ 256] + yuvtab_0c92[U+ 256];

			Cr= clip_yuvtab_3343[V+ 256];

			dest[0]=clip_table[((Y1 + Cb) >>13)];

			dest[1]=clip_table[((Y1 + Cg) >>13)];

			dest[2]=clip_table[((Y1 + Cr) >>13)];

			dest[3]=clip_table[((Y2 + Cb) >>13)];

			dest[4]=clip_table[((Y2 + Cg) >>13)];

			dest[5]=clip_table[((Y2 + Cr) >>13)];

			dest+=6;

		}

	}

	else if(dstbpp==16)

	{

		int i;

		for(i=0; i<(dstW>>1); i++){

			int j;

			int Y1=0;

			int Y2=0;

			int U=0;

			int V=0;

			int Cb, Cr, Cg;

			for(j=0; j<lumFilterSize; j++)

			{

				Y1 += lumSrc[j][2*i] * lumFilter[j];

				Y2 += lumSrc[j][2*i+1] * lumFilter[j];

			}

			for(j=0; j<chrFilterSize; j++)

			{

				U += chrSrc[j][i] * chrFilter[j];

				V += chrSrc[j][i+2048] * chrFilter[j];

			}

			Y1= clip_yuvtab_2568[ (Y1>>19) + 256 ];

			Y2= clip_yuvtab_2568[ (Y2>>19) + 256 ];

			U >>= 19;

			V >>= 19;

			Cb= clip_yuvtab_40cf[U+ 256];

			Cg= clip_yuvtab_1a1e[V+ 256] + yuvtab_0c92[U+ 256];

			Cr= clip_yuvtab_3343[V+ 256];

			((uint16_t*)dest)[2*i] =

				clip_table16b[(Y1 + Cb) >>13] |

				clip_table16g[(Y1 + Cg) >>13] |

				clip_table16r[(Y1 + Cr) >>13];

			((uint16_t*)dest)[2*i+1] =

				clip_table16b[(Y2 + Cb) >>13] |

				clip_table16g[(Y2 + Cg) >>13] |

				clip_table16r[(Y2 + Cr) >>13];

		}

	}

	else if(dstbpp==15)

	{

		int i;

		for(i=0; i<(dstW>>1); i++){

			int j;

			int Y1=0;

			int Y2=0;

			int U=0;

			int V=0;

			int Cb, Cr, Cg;

			for(j=0; j<lumFilterSize; j++)

			{

				Y1 += lumSrc[j][2*i] * lumFilter[j];

				Y2 += lumSrc[j][2*i+1] * lumFilter[j];

			}

			for(j=0; j<chrFilterSize; j++)

			{

				U += chrSrc[j][i] * chrFilter[j];

				V += chrSrc[j][i+2048] * chrFilter[j];

			}

			Y1= clip_yuvtab_2568[ (Y1>>19) + 256 ];

			Y2= clip_yuvtab_2568[ (Y2>>19) + 256 ];

			U >>= 19;

			V >>= 19;

			Cb= clip_yuvtab_40cf[U+ 256];

			Cg= clip_yuvtab_1a1e[V+ 256] + yuvtab_0c92[U+ 256];

			Cr= clip_yuvtab_3343[V+ 256];

			((uint16_t*)dest)[2*i] =

				clip_table15b[(Y1 + Cb) >>13] |

				clip_table15g[(Y1 + Cg) >>13] |

				clip_table15r[(Y1 + Cr) >>13];

			((uint16_t*)dest)[2*i+1] =

				clip_table15b[(Y2 + Cb) >>13] |

				clip_table15g[(Y2 + Cg) >>13] |

				clip_table15r[(Y2 + Cr) >>13];

		}

	}

}


static void XmlAttributeAttributeSetter(
    v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Isolate* isolate = info.GetIsolate();
  ALLOW_UNUSED_LOCAL(isolate);

  v8::Local<v8::Object> holder = info.Holder();
  ALLOW_UNUSED_LOCAL(holder);

  TestObject* impl = V8TestObject::ToImpl(holder);

  ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "xmlAttribute");

  int32_t cpp_value = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), v8_value, exception_state);
  if (exception_state.HadException())
    return;

  impl->setXMLAttribute(cpp_value);
}


SVGAnimatedTypeAnimator* SVGAnimateElement::ensureAnimator()
{
    if (!m_animator)
        m_animator = SVGAnimatorFactory::create(this, targetElement(), m_animatedPropertyType);
    ASSERT(m_animatedPropertyType == m_animator->type());
    return m_animator.get();
}


bool jsvIsBasicVarEqual(JsVar *a, JsVar *b) {
  if (a==b) return true;
  if (!a || !b) return false; // one of them is undefined
  assert(jsvIsBasic(a) && jsvIsBasic(b));
  if (jsvIsNumeric(a) && jsvIsNumeric(b)) {
    if (jsvIsIntegerish(a)) {
      if (jsvIsIntegerish(b)) {
        return a->varData.integer == b->varData.integer;
      } else {
        assert(jsvIsFloat(b));
        return a->varData.integer == b->varData.floating;
      }
    } else {
      assert(jsvIsFloat(a));
      if (jsvIsIntegerish(b)) {
        return a->varData.floating == b->varData.integer;
      } else {
        assert(jsvIsFloat(b));
        return a->varData.floating == b->varData.floating;
      }
    }
  } else if (jsvIsString(a) && jsvIsString(b)) {
    JsvStringIterator ita, itb;
    jsvStringIteratorNew(&ita, a, 0);
    jsvStringIteratorNew(&itb, b, 0);
    while (true) {
      char a = jsvStringIteratorGetChar(&ita);
      char b = jsvStringIteratorGetChar(&itb);
      if (a != b) {
        jsvStringIteratorFree(&ita);
        jsvStringIteratorFree(&itb);
        return false;
      }
      if (!a) { // equal, but end of string
        jsvStringIteratorFree(&ita);
        jsvStringIteratorFree(&itb);
        return true;
      }
      jsvStringIteratorNext(&ita);
      jsvStringIteratorNext(&itb);
    }
    return false; // make compiler happy
  } else {
    return false;
  }
}


int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
                                             uint8_t *buf, int buf_size,
                                             const short *samples)
{
    AVPacket pkt;
    AVFrame *frame;
    int ret, samples_size, got_packet;
    av_init_packet(&pkt);
    pkt.data = buf;
    pkt.size = buf_size;
    if (samples) {
        frame = av_frame_alloc();
        if (!frame)
            return AVERROR(ENOMEM);
        if (avctx->frame_size) {
            frame->nb_samples = avctx->frame_size;
        } else {
            /* if frame_size is not set, the number of samples must be
             * calculated from the buffer size */
            int64_t nb_samples;
            if (!av_get_bits_per_sample(avctx->codec_id)) {
                av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
                                            "support this codec\n");
                av_frame_free(&frame);
                return AVERROR(EINVAL);
            }
            nb_samples = (int64_t)buf_size * 8 /
                         (av_get_bits_per_sample(avctx->codec_id) *
                          avctx->channels);
            if (nb_samples >= INT_MAX) {
                av_frame_free(&frame);
                return AVERROR(EINVAL);
            }
            frame->nb_samples = nb_samples;
        }
        /* it is assumed that the samples buffer is large enough based on the
         * relevant parameters */
        samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
                                                  frame->nb_samples,
                                                  avctx->sample_fmt, 1);
        if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
                                            avctx->sample_fmt,
                                            (const uint8_t *)samples,
                                            samples_size, 1)) < 0) {
            av_frame_free(&frame);
            return ret;
        }
        /* fabricate frame pts from sample count.
         * this is needed because the avcodec_encode_audio() API does not have
         * a way for the user to provide pts */
        if (avctx->sample_rate && avctx->time_base.num)
            frame->pts = ff_samples_to_time_base(avctx,
                                                 avctx->internal->sample_count);
        else
            frame->pts = AV_NOPTS_VALUE;
        avctx->internal->sample_count += frame->nb_samples;
    } else {
        frame = NULL;
    }
    got_packet = 0;
    ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
    if (!ret && got_packet && avctx->coded_frame) {
        avctx->coded_frame->pts       = pkt.pts;
        avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
    }
    /* free any side data since we cannot return it */
    av_packet_free_side_data(&pkt);
    if (frame && frame->extended_data != frame->data)
        av_freep(&frame->extended_data);
    av_frame_free(&frame);
    return ret ? ret : pkt.size;
}


set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n)
{
    asdl_seq *s = NULL;

    /* The ast defines augmented store and load contexts, but the
       implementation here doesn't actually use them.  The code may be
       a little more complex than necessary as a result.  It also means
       that expressions in an augmented assignment have a Store context.
       Consider restructuring so that augmented assignment uses
       set_context(), too.
    */
    assert(ctx != AugStore && ctx != AugLoad);

    switch (e->kind) {
        case Attribute_kind:
            e->v.Attribute.ctx = ctx;
            if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1))
                return 0;
            break;
        case Subscript_kind:
            e->v.Subscript.ctx = ctx;
            break;
        case Starred_kind:
            e->v.Starred.ctx = ctx;
            if (!set_context(c, e->v.Starred.value, ctx, n))
                return 0;
            break;
        case Name_kind:
            if (ctx == Store) {
                if (forbidden_name(c, e->v.Name.id, n, 0))
                    return 0; /* forbidden_name() calls ast_error() */
            }
            e->v.Name.ctx = ctx;
            break;
        case List_kind:
            e->v.List.ctx = ctx;
            s = e->v.List.elts;
            break;
        case Tuple_kind:
            e->v.Tuple.ctx = ctx;
            s = e->v.Tuple.elts;
            break;
        default: {
            const char *expr_name = get_expr_name(e);
            if (expr_name != NULL) {
                ast_error(c, n, "cannot %s %s",
                          ctx == Store ? "assign to" : "delete",
                          expr_name);
            }
            return 0;
        }
    }

    /* If the LHS is a list or tuple, we need to set the assignment
       context for all the contained elements.
    */
    if (s) {
        Py_ssize_t i;

        for (i = 0; i < asdl_seq_LEN(s); i++) {
            if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n))
                return 0;
        }
    }
    return 1;
}


asmlinkage void user_unaligned_trap(struct pt_regs *regs, unsigned int insn)
{
	enum direction dir;

	if(!(current->thread.flags & SPARC_FLAG_UNALIGNED) ||
	   (((insn >> 30) & 3) != 3))
		goto kill_user;
	dir = decode_direction(insn);
	if(!ok_for_user(regs, insn, dir)) {
		goto kill_user;
	} else {
		int err, size = decode_access_size(insn);
		unsigned long addr;

		if(floating_point_load_or_store_p(insn)) {
			printk("User FPU load/store unaligned unsupported.\n");
			goto kill_user;
		}

		addr = compute_effective_address(regs, insn);
		perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr);
		switch(dir) {
		case load:
			err = do_int_load(fetch_reg_addr(((insn>>25)&0x1f),
							 regs),
					  size, (unsigned long *) addr,
					  decode_signedness(insn));
			break;

		case store:
			err = do_int_store(((insn>>25)&0x1f), size,
					   (unsigned long *) addr, regs);
			break;

		case both:
			/*
			 * This was supported in 2.4. However, we question
			 * the value of SWAP instruction across word boundaries.
			 */
			printk("Unaligned SWAP unsupported.\n");
			err = -EFAULT;
			break;

		default:
			unaligned_panic("Impossible user unaligned trap.");
			goto out;
		}
		if (err)
			goto kill_user;
		else
			advance(regs);
		goto out;
	}

kill_user:
	user_mna_trap_fault(regs, insn);
out:
	;
}


void genClientPeerId(client *client, char *peerid,
                            size_t peerid_len) {
    if (client->flags & CLIENT_UNIX_SOCKET) {
        /* Unix socket client. */
        snprintf(peerid,peerid_len,"%s:0",server.unixsocket);
    } else {
        /* TCP client. */
        anetFormatPeer(client->fd,peerid,peerid_len);
    }
}


void FileSystemOperationRunner::FinishOperation(OperationID id) {
  scoped_refptr<FileSystemContext> context(file_system_context_);

  auto found = write_target_urls_.find(id);
  if (found != write_target_urls_.end()) {
    const FileSystemURLSet& urls = found->second;
    for (const FileSystemURL& url : urls) {
      if (file_system_context_->GetUpdateObservers(url.type())) {
        file_system_context_->GetUpdateObservers(url.type())
            ->Notify(&FileUpdateObserver::OnEndUpdate, url);
      }
    }
    write_target_urls_.erase(found);
  }

  operations_.erase(id);
  finished_operations_.erase(id);

  auto found_cancel = stray_cancel_callbacks_.find(id);
  if (found_cancel != stray_cancel_callbacks_.end()) {
    std::move(found_cancel->second)
        .Run(base::File::FILE_ERROR_INVALID_OPERATION);
    stray_cancel_callbacks_.erase(found_cancel);
  }
}


void InterstitialPageImpl::SetFocusedFrame(FrameTreeNode* node,
                                           SiteInstance* source) {
  frame_tree_->SetFocusedFrame(node, source);

  if (web_contents_) {
    static_cast<WebContentsImpl*>(web_contents_)
        ->SetAsFocusedWebContentsIfNecessary();
  }
}


static long vbg_misc_device_ioctl(struct file *filp, unsigned int req,
				  unsigned long arg)
{
	struct vbg_session *session = filp->private_data;
	size_t returned_size, size;
	struct vbg_ioctl_hdr hdr;
	bool is_vmmdev_req;
	int ret = 0;
	void *buf;

	if (copy_from_user(&hdr, (void *)arg, sizeof(hdr)))
		return -EFAULT;

	if (hdr.version != VBG_IOCTL_HDR_VERSION)
		return -EINVAL;

	if (hdr.size_in < sizeof(hdr) ||
	    (hdr.size_out && hdr.size_out < sizeof(hdr)))
		return -EINVAL;

	size = max(hdr.size_in, hdr.size_out);
	if (_IOC_SIZE(req) && _IOC_SIZE(req) != size)
		return -EINVAL;
	if (size > SZ_16M)
		return -E2BIG;

	/*
	 * IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid
	 * the need for a bounce-buffer and another copy later on.
	 */
	is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) ||
			 req == VBG_IOCTL_VMMDEV_REQUEST_BIG;

	if (is_vmmdev_req)
		buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT);
	else
		buf = kmalloc(size, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	if (copy_from_user(buf, (void *)arg, hdr.size_in)) {
		ret = -EFAULT;
		goto out;
	}
	if (hdr.size_in < size)
		memset(buf + hdr.size_in, 0, size -  hdr.size_in);

	ret = vbg_core_ioctl(session, req, buf);
	if (ret)
		goto out;

	returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out;
	if (returned_size > size) {
		vbg_debug("%s: too much output data %zu > %zu\n",
			  __func__, returned_size, size);
		returned_size = size;
	}
	if (copy_to_user((void *)arg, buf, returned_size) != 0)
		ret = -EFAULT;

out:
	if (is_vmmdev_req)
		vbg_req_free(buf, size);
	else
		kfree(buf);

	return ret;
}


void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
    UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
                   StreamTcpTest01);
    UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
                   StreamTcpTest02);
    UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
                   StreamTcpTest03);
    UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
                   StreamTcpTest04);
    UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
                   StreamTcpTest05);
    UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
                   StreamTcpTest06);
    UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
                   StreamTcpTest07);
    UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
    UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
    UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
                   StreamTcpTest10);
    UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
                   StreamTcpTest11);
    UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
                   StreamTcpTest12);
    UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
                   StreamTcpTest13);
    UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
    UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
    UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
    UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
    UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
    UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
    UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
    UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
    UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
    UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
    UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
    UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
    UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
    UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
    UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
                   StreamTcpTest25);
    UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
                   StreamTcpTest26);
    UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
                   StreamTcpTest27);
    UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);

#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
       * right about blowing up. The checksum functions are not used properly
       * in the tests. */
    UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
    UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
    UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
    UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
    UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
    UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
    UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
    UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
    UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
                   StreamTcpTest37);

    UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
    UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);

    UtRegisterTest("StreamTcpTest40 -- pseudo setup", StreamTcpTest40);
    UtRegisterTest("StreamTcpTest41 -- pseudo setup", StreamTcpTest41);

    UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
    UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
    UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
    UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);

    /* set up the reassembly tests as well */
    StreamTcpReassembleRegisterTests();

    StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}


void Con_CheckResize (void)
{
	int		i, j, width, oldwidth, oldtotallines, numlines, numchars;
	short	tbuf[CON_TEXTSIZE];

	width = (SCREEN_WIDTH / SMALLCHAR_WIDTH) - 2;

	if (width == con.linewidth)
		return;

	if (width < 1)			// video hasn't been initialized yet
	{
		width = DEFAULT_CONSOLE_WIDTH;
		con.linewidth = width;
		con.totallines = CON_TEXTSIZE / con.linewidth;
		for(i=0; i<CON_TEXTSIZE; i++)

			con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';
	}
	else
	{
		oldwidth = con.linewidth;
		con.linewidth = width;
		oldtotallines = con.totallines;
		con.totallines = CON_TEXTSIZE / con.linewidth;
		numlines = oldtotallines;

		if (con.totallines < numlines)
			numlines = con.totallines;

		numchars = oldwidth;

		if (con.linewidth < numchars)
			numchars = con.linewidth;

		Com_Memcpy (tbuf, con.text, CON_TEXTSIZE * sizeof(short));
		for(i=0; i<CON_TEXTSIZE; i++)

			con.text[i] = (ColorIndex(COLOR_WHITE)<<8) | ' ';

		for (i=0 ; i<numlines ; i++)
		{
			for (j=0 ; j<numchars ; j++)
			{
				con.text[(con.totallines - 1 - i) * con.linewidth + j] =
						tbuf[((con.current - i + oldtotallines) %
							  oldtotallines) * oldwidth + j];
			}
		}

		Con_ClearNotify ();
	}

	con.current = con.totallines - 1;
	con.display = con.current;
}


static int free_fid(V9fsPDU *pdu, V9fsFidState *fidp)
{
    int retval = 0;

    if (fidp->fid_type == P9_FID_FILE) {
        /* If we reclaimed the fd no need to close */
        if (fidp->fs.fd != -1) {
            retval = v9fs_co_close(pdu, &fidp->fs);
        }
    } else if (fidp->fid_type == P9_FID_DIR) {
        if (fidp->fs.dir.stream != NULL) {
            retval = v9fs_co_closedir(pdu, &fidp->fs);
        }
    } else if (fidp->fid_type == P9_FID_XATTR) {
        retval = v9fs_xattr_fid_clunk(pdu, fidp);
    }
    v9fs_path_free(&fidp->path);
    g_free(fidp);
    return retval;
}