__ip_vs_service_get(int af, __u16 protocol, const union nf_inet_addr *vaddr,
		    __be16 vport)
{
	unsigned hash;
	struct ip_vs_service *svc;

	/* Check for "full" addressed entries */
	hash = ip_vs_svc_hashkey(af, protocol, vaddr, vport);

	list_for_each_entry(svc, &ip_vs_svc_table[hash], s_list){
		if ((svc->af == af)
		    && ip_vs_addr_equal(af, &svc->addr, vaddr)
		    && (svc->port == vport)
		    && (svc->protocol == protocol)) {
			/* HIT */
			atomic_inc(&svc->usecnt);
			return svc;
		}
	}

	return NULL;
}


static void test_bug6761(void)
{
  const char *stmt_text;
  MYSQL_RES *res;
  int rc;
  myheader("test_bug6761");

  stmt_text= "CREATE TABLE t1 (a int, b char(255), c decimal)";
  rc= mysql_real_query(mysql, stmt_text, strlen(stmt_text));
  myquery(rc);

  res= mysql_list_fields(mysql, "t1", "%");
  DIE_UNLESS(res && mysql_num_fields(res) == 3);
  mysql_free_result(res);

  stmt_text= "DROP TABLE t1";
  rc= mysql_real_query(mysql, stmt_text, strlen(stmt_text));
  myquery(rc);
}


static BOOL license_read_preamble(wStream* s, BYTE* bMsgType, BYTE* flags, UINT16* wMsgSize)
{
	/* preamble (4 bytes) */
	if (Stream_GetRemainingLength(s) < 4)
		return FALSE;

	Stream_Read_UINT8(s, *bMsgType);  /* bMsgType (1 byte) */
	Stream_Read_UINT8(s, *flags);     /* flags (1 byte) */
	Stream_Read_UINT16(s, *wMsgSize); /* wMsgSize (2 bytes) */
	return TRUE;
}


void AwFeatureListCreator::SetUpFieldTrials() {
  auto* metrics_client = AwMetricsServiceClient::GetInstance();

  DCHECK(!field_trial_list_);
  field_trial_list_ = std::make_unique<base::FieldTrialList>(
      metrics_client->CreateLowEntropyProvider());

  std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed();
  base::Time null_time;
  base::Time seed_date =
      seed ? base::Time::FromJavaTime(seed->date) : null_time;
  variations::UIStringOverrider ui_string_overrider;
  client_ = std::make_unique<AwVariationsServiceClient>();
  auto seed_store = std::make_unique<variations::VariationsSeedStore>(
      local_state_.get(), /*initial_seed=*/std::move(seed),
      /*on_initial_seed_stored=*/base::DoNothing());

  if (!seed_date.is_null())
    seed_store->RecordLastFetchTime(seed_date);

  variations_field_trial_creator_ =
      std::make_unique<variations::VariationsFieldTrialCreator>(
          local_state_.get(), client_.get(), std::move(seed_store),
          ui_string_overrider);
  variations_field_trial_creator_->OverrideVariationsPlatform(
      variations::Study::PLATFORM_ANDROID_WEBVIEW);

  std::set<std::string> unforceable_field_trials;
  variations::SafeSeedManager ignored_safe_seed_manager(true,
                                                        local_state_.get());

  variations_field_trial_creator_->SetupFieldTrials(
      cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures,
      switches::kDisableFeatures, unforceable_field_trials,
      std::vector<std::string>(),
      content::GetSwitchDependentFeatureOverrides(
           *base::CommandLine::ForCurrentProcess()),
       /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(),
       aw_field_trials_.get(), &ignored_safe_seed_manager);

  CountOrRecordRestartsWithStaleSeed(local_state_.get(), IsSeedFresh());
 }


WORD32 ih264d_parse_sps(dec_struct_t *ps_dec, dec_bit_stream_t *ps_bitstrm)

 {
     UWORD8 i;
     dec_seq_params_t *ps_seq = NULL;
    UWORD8 u1_profile_idc, u1_level_idc, u1_seq_parameter_set_id, u1_mb_aff_flag = 0;
     UWORD16 i2_max_frm_num;
     UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
     UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
    UWORD8 u1_frm, uc_constraint_set0_flag, uc_constraint_set1_flag;
    WORD32 i4_cropped_ht, i4_cropped_wd;
    UWORD32 u4_temp;
    WORD32 pic_height_in_map_units_minus1 = 0;
    UWORD32 u2_pic_wd = 0;
    UWORD32 u2_pic_ht = 0;
    UWORD32 u2_frm_wd_y = 0;
    UWORD32 u2_frm_ht_y = 0;
    UWORD32 u2_frm_wd_uv = 0;
    UWORD32 u2_frm_ht_uv = 0;
    UWORD32 u2_crop_offset_y = 0;
    UWORD32 u2_crop_offset_uv = 0;
    WORD32 ret;
    UWORD32 u4_num_reorder_frames;
 /* High profile related syntax element */
    WORD32 i4_i;
 /* G050 */
    UWORD8 u1_frame_cropping_flag, u1_frame_cropping_rect_left_ofst,
                    u1_frame_cropping_rect_right_ofst,
                    u1_frame_cropping_rect_top_ofst,
                    u1_frame_cropping_rect_bottom_ofst;
 /* G050 */
 /*--------------------------------------------------------------------*/
 /* Decode seq_parameter_set_id and profile and level values           */
 /*--------------------------------------------------------------------*/
    SWITCHONTRACE;
    u1_profile_idc = ih264d_get_bits_h264(ps_bitstrm, 8);
    COPYTHECONTEXT("SPS: profile_idc",u1_profile_idc);

 /* G050 */
    uc_constraint_set0_flag = ih264d_get_bit_h264(ps_bitstrm);
    uc_constraint_set1_flag = ih264d_get_bit_h264(ps_bitstrm);
    ih264d_get_bit_h264(ps_bitstrm);

 /*****************************************************/
 /* Read 5 bits for uc_constraint_set3_flag (1 bit)   */
 /* and reserved_zero_4bits (4 bits) - Sushant        */
 /*****************************************************/
    ih264d_get_bits_h264(ps_bitstrm, 5);
 /* G050 */

 /* Check whether particular profile is suported or not */
 /* Check whether particular profile is suported or not */
 if((u1_profile_idc != MAIN_PROFILE_IDC) &&

 (u1_profile_idc != BASE_PROFILE_IDC) &&

 (u1_profile_idc != HIGH_PROFILE_IDC)

 )
 {

 /* Apart from Baseline, main and high profile,
         * only extended profile is supported provided
         * uc_constraint_set0_flag or uc_constraint_set1_flag are set to 1
         */
 if((u1_profile_idc != EXTENDED_PROFILE_IDC) ||
 ((uc_constraint_set1_flag != 1) && (uc_constraint_set0_flag != 1)))
 {
 return (ERROR_FEATURE_UNAVAIL);
 }
 }

    u1_level_idc = ih264d_get_bits_h264(ps_bitstrm, 8);

    COPYTHECONTEXT("SPS: u4_level_idc",u1_level_idc);

    u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
 if(u4_temp & MASK_ERR_SEQ_SET_ID)
 return ERROR_INV_SPS_PPS_T;
    u1_seq_parameter_set_id = u4_temp;
    COPYTHECONTEXT("SPS: seq_parameter_set_id",
                    u1_seq_parameter_set_id);

 /*--------------------------------------------------------------------*/
 /* Find an seq param entry in seqparam array of decStruct             */
 /*--------------------------------------------------------------------*/

    ps_seq = ps_dec->pv_scratch_sps_pps;
 if(ps_dec->i4_header_decoded & 1)
 {
 *ps_seq = *ps_dec->ps_cur_sps;
 }

 if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_profile_idc != u1_profile_idc))
 {
        ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }

 if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_level_idc != u1_level_idc))
 {
        ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }

    ps_seq->u1_profile_idc = u1_profile_idc;
    ps_seq->u1_level_idc = u1_level_idc;
    ps_seq->u1_seq_parameter_set_id = u1_seq_parameter_set_id;

 /*******************************************************************/
 /* Initializations for high profile - Sushant                      */
 /*******************************************************************/
    ps_seq->i4_chroma_format_idc = 1;
    ps_seq->i4_bit_depth_luma_minus8 = 0;
    ps_seq->i4_bit_depth_chroma_minus8 = 0;
    ps_seq->i4_qpprime_y_zero_transform_bypass_flag = 0;
    ps_seq->i4_seq_scaling_matrix_present_flag = 0;
 if(u1_profile_idc == HIGH_PROFILE_IDC)
 {

 /* reading chroma_format_idc   */
        ps_seq->i4_chroma_format_idc = ih264d_uev(pu4_bitstrm_ofst,
                                                  pu4_bitstrm_buf);

 /* Monochrome is not supported */
 if(ps_seq->i4_chroma_format_idc != 1)
 {
 return ERROR_INV_SPS_PPS_T;
 }

 /* reading bit_depth_luma_minus8   */
        ps_seq->i4_bit_depth_luma_minus8 = ih264d_uev(pu4_bitstrm_ofst,
                                                      pu4_bitstrm_buf);

 if(ps_seq->i4_bit_depth_luma_minus8 != 0)
 {
 return ERROR_INV_SPS_PPS_T;
 }

 /* reading bit_depth_chroma_minus8   */
        ps_seq->i4_bit_depth_chroma_minus8 = ih264d_uev(pu4_bitstrm_ofst,
                                                        pu4_bitstrm_buf);

 if(ps_seq->i4_bit_depth_chroma_minus8 != 0)
 {
 return ERROR_INV_SPS_PPS_T;
 }

 /* reading qpprime_y_zero_transform_bypass_flag   */
        ps_seq->i4_qpprime_y_zero_transform_bypass_flag =
 (WORD32)ih264d_get_bit_h264(ps_bitstrm);

 if(ps_seq->i4_qpprime_y_zero_transform_bypass_flag != 0)
 {
 return ERROR_INV_SPS_PPS_T;
 }

 /* reading seq_scaling_matrix_present_flag   */
        ps_seq->i4_seq_scaling_matrix_present_flag =
 (WORD32)ih264d_get_bit_h264(ps_bitstrm);

 if(ps_seq->i4_seq_scaling_matrix_present_flag)
 {
 for(i4_i = 0; i4_i < 8; i4_i++)
 {
                ps_seq->u1_seq_scaling_list_present_flag[i4_i] =
                                ih264d_get_bit_h264(ps_bitstrm);

 /* initialize u1_use_default_scaling_matrix_flag[i4_i] to zero */
 /* before calling scaling list                             */
                ps_seq->u1_use_default_scaling_matrix_flag[i4_i] = 0;

 if(ps_seq->u1_seq_scaling_list_present_flag[i4_i])
 {
 if(i4_i < 6)
 {
                        ih264d_scaling_list(
                                        ps_seq->i2_scalinglist4x4[i4_i],
 16,
 &ps_seq->u1_use_default_scaling_matrix_flag[i4_i],
                                        ps_bitstrm);
 }
 else
 {
                        ih264d_scaling_list(
                                        ps_seq->i2_scalinglist8x8[i4_i - 6],
 64,
 &ps_seq->u1_use_default_scaling_matrix_flag[i4_i],
                                        ps_bitstrm);
 }
 }
 }
 }
 }
 /*--------------------------------------------------------------------*/
 /* Decode MaxFrameNum                                                 */
 /*--------------------------------------------------------------------*/
    u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
 if(u4_temp > MAX_BITS_IN_FRAME_NUM)
 {
 return ERROR_INV_SPS_PPS_T;
 }
    ps_seq->u1_bits_in_frm_num = u4_temp;
    COPYTHECONTEXT("SPS: log2_max_frame_num_minus4",
 (ps_seq->u1_bits_in_frm_num - 4));

    i2_max_frm_num = (1 << (ps_seq->u1_bits_in_frm_num));
    ps_seq->u2_u4_max_pic_num_minus1 = i2_max_frm_num - 1;
 /*--------------------------------------------------------------------*/
 /* Decode picture order count and related values                      */
 /*--------------------------------------------------------------------*/
    u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);

 if(u4_temp > MAX_PIC_ORDER_CNT_TYPE)
 {
 return ERROR_INV_POC_TYPE_T;
 }
    ps_seq->u1_pic_order_cnt_type = u4_temp;
    COPYTHECONTEXT("SPS: pic_order_cnt_type",ps_seq->u1_pic_order_cnt_type);

    ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = 1;
 if(ps_seq->u1_pic_order_cnt_type == 0)
 {
        u4_temp = 4 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
 if(u4_temp > MAX_BITS_IN_POC_LSB)
 {
 return ERROR_INV_SPS_PPS_T;
 }
        ps_seq->u1_log2_max_pic_order_cnt_lsb_minus = u4_temp;
        ps_seq->i4_max_pic_order_cntLsb = (1 << u4_temp);
        COPYTHECONTEXT("SPS: log2_max_pic_order_cnt_lsb_minus4",(u4_temp - 4));
 }
 else if(ps_seq->u1_pic_order_cnt_type == 1)
 {
        ps_seq->u1_delta_pic_order_always_zero_flag = ih264d_get_bit_h264(
                        ps_bitstrm);
        COPYTHECONTEXT("SPS: delta_pic_order_always_zero_flag",
                        ps_seq->u1_delta_pic_order_always_zero_flag);

        ps_seq->i4_ofst_for_non_ref_pic = ih264d_sev(pu4_bitstrm_ofst,
                                                     pu4_bitstrm_buf);
        COPYTHECONTEXT("SPS: offset_for_non_ref_pic",
                        ps_seq->i4_ofst_for_non_ref_pic);

        ps_seq->i4_ofst_for_top_to_bottom_field = ih264d_sev(
                        pu4_bitstrm_ofst, pu4_bitstrm_buf);
        COPYTHECONTEXT("SPS: offset_for_top_to_bottom_field",
                        ps_seq->i4_ofst_for_top_to_bottom_field);

        u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
 if(u4_temp > 255)
 return ERROR_INV_SPS_PPS_T;
        ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle = u4_temp;
        COPYTHECONTEXT("SPS: num_ref_frames_in_pic_order_cnt_cycle",
                        ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle);

 for(i = 0; i < ps_seq->u1_num_ref_frames_in_pic_order_cnt_cycle; i++)
 {
            ps_seq->i4_ofst_for_ref_frame[i] = ih264d_sev(
                            pu4_bitstrm_ofst, pu4_bitstrm_buf);
            COPYTHECONTEXT("SPS: offset_for_ref_frame",
                            ps_seq->i4_ofst_for_ref_frame[i]);
 }
 }

    u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);

 if((u4_temp > H264_MAX_REF_PICS))
 {
 return ERROR_NUM_REF;
 }

 /* Compare with older num_ref_frames is header is already once */
 if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_num_ref_frames != u4_temp))
 {
        ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }

    ps_seq->u1_num_ref_frames = u4_temp;
    COPYTHECONTEXT("SPS: num_ref_frames",ps_seq->u1_num_ref_frames);

    ps_seq->u1_gaps_in_frame_num_value_allowed_flag = ih264d_get_bit_h264(
                    ps_bitstrm);
    COPYTHECONTEXT("SPS: gaps_in_frame_num_value_allowed_flag",
                    ps_seq->u1_gaps_in_frame_num_value_allowed_flag);

 /*--------------------------------------------------------------------*/
 /* Decode FrameWidth and FrameHeight and related values               */
 /*--------------------------------------------------------------------*/
    ps_seq->u2_frm_wd_in_mbs = 1
 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
    COPYTHECONTEXT("SPS: pic_width_in_mbs_minus1",
                    ps_seq->u2_frm_wd_in_mbs - 1);
    u2_pic_wd = (ps_seq->u2_frm_wd_in_mbs << 4);

    pic_height_in_map_units_minus1 = ih264d_uev(pu4_bitstrm_ofst,
                                                pu4_bitstrm_buf);
    ps_seq->u2_frm_ht_in_mbs = 1 + pic_height_in_map_units_minus1;

    u2_pic_ht = (ps_seq->u2_frm_ht_in_mbs << 4);

 /*--------------------------------------------------------------------*/
 /* Get the value of MaxMbAddress and Number of bits needed for it     */
 /*--------------------------------------------------------------------*/
    ps_seq->u2_max_mb_addr = (ps_seq->u2_frm_wd_in_mbs
 * ps_seq->u2_frm_ht_in_mbs) - 1;

    ps_seq->u2_total_num_of_mbs = ps_seq->u2_max_mb_addr + 1;

    ps_seq->u1_level_idc = ih264d_correct_level_idc(
                    u1_level_idc, ps_seq->u2_total_num_of_mbs);

    u1_frm = ih264d_get_bit_h264(ps_bitstrm);
 if((ps_dec->i4_header_decoded & 1) && (ps_seq->u1_frame_mbs_only_flag != u1_frm))
 {
        ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }

    ps_seq->u1_frame_mbs_only_flag = u1_frm;

     COPYTHECONTEXT("SPS: frame_mbs_only_flag", u1_frm);

     if(!u1_frm)
        u1_mb_aff_flag = ih264d_get_bit_h264(ps_bitstrm);

    if((ps_dec->i4_header_decoded & 1)
                    && (ps_seq->u1_mb_aff_flag != u1_mb_aff_flag))
    {
        ps_dec->u1_res_changed = 1;
        return IVD_RES_CHANGED;
    }

    if(!u1_frm)
     {
         u2_pic_ht <<= 1;
        ps_seq->u1_mb_aff_flag = u1_mb_aff_flag;
         COPYTHECONTEXT("SPS: mb_adaptive_frame_field_flag",
                         ps_seq->u1_mb_aff_flag);

 }
 else
        ps_seq->u1_mb_aff_flag = 0;

    ps_seq->u1_direct_8x8_inference_flag = ih264d_get_bit_h264(ps_bitstrm);

    COPYTHECONTEXT("SPS: direct_8x8_inference_flag",
                    ps_seq->u1_direct_8x8_inference_flag);

 /* G050 */
    u1_frame_cropping_flag = ih264d_get_bit_h264(ps_bitstrm);
    COPYTHECONTEXT("SPS: frame_cropping_flag",u1_frame_cropping_flag);

 if(u1_frame_cropping_flag)
 {
        u1_frame_cropping_rect_left_ofst = ih264d_uev(pu4_bitstrm_ofst,
                                                      pu4_bitstrm_buf);
        COPYTHECONTEXT("SPS: frame_cropping_rect_left_offset",
                        u1_frame_cropping_rect_left_ofst);
        u1_frame_cropping_rect_right_ofst = ih264d_uev(pu4_bitstrm_ofst,
                                                       pu4_bitstrm_buf);
        COPYTHECONTEXT("SPS: frame_cropping_rect_right_offset",
                        u1_frame_cropping_rect_right_ofst);
        u1_frame_cropping_rect_top_ofst = ih264d_uev(pu4_bitstrm_ofst,
                                                     pu4_bitstrm_buf);
        COPYTHECONTEXT("SPS: frame_cropping_rect_top_offset",
                        u1_frame_cropping_rect_top_ofst);
        u1_frame_cropping_rect_bottom_ofst = ih264d_uev(pu4_bitstrm_ofst,
                                                        pu4_bitstrm_buf);
        COPYTHECONTEXT("SPS: frame_cropping_rect_bottom_offset",
                        u1_frame_cropping_rect_bottom_ofst);
 }
 /* G050 */

    ps_seq->u1_vui_parameters_present_flag = ih264d_get_bit_h264(ps_bitstrm);
    COPYTHECONTEXT("SPS: vui_parameters_present_flag",
                    ps_seq->u1_vui_parameters_present_flag);

    u2_frm_wd_y = u2_pic_wd + (UWORD8)(PAD_LEN_Y_H << 1);
 if(1 == ps_dec->u4_share_disp_buf)
 {
 if(ps_dec->u4_app_disp_width > u2_frm_wd_y)
            u2_frm_wd_y = ps_dec->u4_app_disp_width;
 }

    u2_frm_ht_y = u2_pic_ht + (UWORD8)(PAD_LEN_Y_V << 2);
    u2_frm_wd_uv = u2_pic_wd + (UWORD8)(PAD_LEN_UV_H << 2);
    u2_frm_wd_uv = MAX(u2_frm_wd_uv, u2_frm_wd_y);

    u2_frm_ht_uv = (u2_pic_ht >> 1) + (UWORD8)(PAD_LEN_UV_V << 2);
    u2_frm_ht_uv = MAX(u2_frm_ht_uv, (u2_frm_ht_y >> 1));

 /* Calculate display picture width, height and start u4_ofst from YUV420 */
 /* pictute buffers as per cropping information parsed above             */
 {
        UWORD16 u2_rgt_ofst = 0;
        UWORD16 u2_lft_ofst = 0;
        UWORD16 u2_top_ofst = 0;
        UWORD16 u2_btm_ofst = 0;
        UWORD8 u1_frm_mbs_flag;
        UWORD8 u1_vert_mult_factor;

 if(u1_frame_cropping_flag)
 {
 /* Calculate right and left u4_ofst for cropped picture           */
            u2_rgt_ofst = u1_frame_cropping_rect_right_ofst << 1;
            u2_lft_ofst = u1_frame_cropping_rect_left_ofst << 1;

 /* Know frame MBs only u4_flag                                      */
            u1_frm_mbs_flag = (1 == ps_seq->u1_frame_mbs_only_flag);

 /* Simplify the vertical u4_ofst calculation from field/frame     */
            u1_vert_mult_factor = (2 - u1_frm_mbs_flag);

 /* Calculate bottom and top u4_ofst for cropped  picture          */
            u2_btm_ofst = (u1_frame_cropping_rect_bottom_ofst
 << u1_vert_mult_factor);
            u2_top_ofst = (u1_frame_cropping_rect_top_ofst
 << u1_vert_mult_factor);
 }

 /* Calculate u4_ofst from start of YUV 420 picture buffer to start of*/
 /* cropped picture buffer                                           */
        u2_crop_offset_y = (u2_frm_wd_y * u2_top_ofst) + (u2_lft_ofst);
        u2_crop_offset_uv = (u2_frm_wd_uv * (u2_top_ofst >> 1))
 + (u2_lft_ofst >> 1) * YUV420SP_FACTOR;
 /* Calculate the display picture width and height based on crop      */
 /* information                                                       */
        i4_cropped_ht = u2_pic_ht - (u2_btm_ofst + u2_top_ofst);
        i4_cropped_wd = u2_pic_wd - (u2_rgt_ofst + u2_lft_ofst);

 if((i4_cropped_ht < MB_SIZE) || (i4_cropped_wd < MB_SIZE))
 {
 return ERROR_INV_SPS_PPS_T;
 }

 if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_wd != u2_pic_wd))
 {
            ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }
 if((ps_dec->i4_header_decoded & 1) && (ps_dec->u2_pic_ht != u2_pic_ht))
 {
            ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }

 /* Check for unsupported resolutions */
 if((u2_pic_wd > H264_MAX_FRAME_WIDTH) || (u2_pic_ht > H264_MAX_FRAME_HEIGHT)
 || (u2_pic_wd < H264_MIN_FRAME_WIDTH) || (u2_pic_ht < H264_MIN_FRAME_HEIGHT)
 || (u2_pic_wd * (UWORD32)u2_pic_ht > H264_MAX_FRAME_SIZE))
 {
 return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED;
 }

 /* If MBAff is enabled, decoder support is limited to streams with
         * width less than half of H264_MAX_FRAME_WIDTH.
         * In case of MBAff decoder processes two rows at a time
         */
 if((u2_pic_wd << ps_seq->u1_mb_aff_flag) > H264_MAX_FRAME_WIDTH)
 {
 return IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED;
 }

 }

 /* Backup u4_num_reorder_frames if header is already decoded */
 if((ps_dec->i4_header_decoded & 1) &&
 (1 == ps_seq->u1_vui_parameters_present_flag) &&
 (1 == ps_seq->s_vui.u1_bitstream_restriction_flag))
 {
        u4_num_reorder_frames =  ps_seq->s_vui.u4_num_reorder_frames;
 }
 else
 {
        u4_num_reorder_frames = -1;
 }
 if(1 == ps_seq->u1_vui_parameters_present_flag)
 {
        ret = ih264d_parse_vui_parametres(&ps_seq->s_vui, ps_bitstrm);
 if(ret != OK)
 return ret;
 }

 /* Compare older u4_num_reorder_frames with the new one if header is already decoded */
 if((ps_dec->i4_header_decoded & 1) &&
 (-1 != (WORD32)u4_num_reorder_frames) &&
 (1 == ps_seq->u1_vui_parameters_present_flag) &&
 (1 == ps_seq->s_vui.u1_bitstream_restriction_flag) &&
 (ps_seq->s_vui.u4_num_reorder_frames != u4_num_reorder_frames))
 {
        ps_dec->u1_res_changed = 1;
 return IVD_RES_CHANGED;
 }

 /* In case bitstream read has exceeded the filled size, then
     return an error */
 if (ps_bitstrm->u4_ofst > ps_bitstrm->u4_max_ofst)
 {
 return ERROR_INV_SPS_PPS_T;
 }

 /*--------------------------------------------------------------------*/
 /* All initializations to ps_dec are beyond this point                */
 /*--------------------------------------------------------------------*/
    ps_dec->u2_disp_height = i4_cropped_ht;
    ps_dec->u2_disp_width = i4_cropped_wd;

    ps_dec->u2_pic_wd = u2_pic_wd;
    ps_dec->u2_pic_ht = u2_pic_ht;

 /* Determining the Width and Height of Frame from that of Picture */
    ps_dec->u2_frm_wd_y = u2_frm_wd_y;
    ps_dec->u2_frm_ht_y = u2_frm_ht_y;

    ps_dec->u2_frm_wd_uv = u2_frm_wd_uv;
    ps_dec->u2_frm_ht_uv = u2_frm_ht_uv;
    ps_dec->s_pad_mgr.u1_pad_len_y_v = (UWORD8)(PAD_LEN_Y_V << (1 - u1_frm));
    ps_dec->s_pad_mgr.u1_pad_len_cr_v = (UWORD8)(PAD_LEN_UV_V << (1 - u1_frm));

    ps_dec->u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs;
    ps_dec->u2_frm_ht_in_mbs = ps_seq->u2_frm_ht_in_mbs;

    ps_dec->u2_crop_offset_y = u2_crop_offset_y;
    ps_dec->u2_crop_offset_uv = u2_crop_offset_uv;

    ps_seq->u1_is_valid = TRUE;
    ps_dec->ps_sps[u1_seq_parameter_set_id] = *ps_seq;
    ps_dec->ps_cur_sps = &ps_dec->ps_sps[u1_seq_parameter_set_id];

 return OK;
}


PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp)
{
    if (dt_table[Elf32_Dyn::DT_NULL]) {
        return;  // not 1st time; do not change upx_dt_init
    }
    Elf32_Dyn const *const dynp0 = dynp;
    unsigned ndx = 1+ 0;
    if (dynp)
    for (; ; ++ndx, ++dynp) {
        unsigned const d_tag = get_te32(&dynp->d_tag);
        if (d_tag < DT_NUM) {
            if (Elf32_Dyn::DT_NEEDED != d_tag
            &&  dt_table[d_tag]
            &&    get_te32(&dynp->d_val)
               != get_te32(&dynp0[-1+ dt_table[d_tag]].d_val)) {
                char msg[50]; snprintf(msg, sizeof(msg),
                    "duplicate DT_%#x: [%#x] [%#x]",
                    d_tag, -1+ dt_table[d_tag], -1+ ndx);
                throwCantPack(msg);
            }
            dt_table[d_tag] = ndx;
        }
        if (Elf32_Dyn::DT_NULL == d_tag) {
            break;  // check here so that dt_table[DT_NULL] is set
        }
    }
    upx_dt_init = 0;
         if (dt_table[Elf32_Dyn::DT_INIT])          upx_dt_init = Elf32_Dyn::DT_INIT;
    else if (dt_table[Elf32_Dyn::DT_PREINIT_ARRAY]) upx_dt_init = Elf32_Dyn::DT_PREINIT_ARRAY;
    else if (dt_table[Elf32_Dyn::DT_INIT_ARRAY])    upx_dt_init = Elf32_Dyn::DT_INIT_ARRAY;

    unsigned const z_str = dt_table[Elf32_Dyn::DT_STRSZ];
    if (z_str) {
        strtab_end = get_te32(&dynp0[-1+ z_str].d_val);
        if ((u32_t)file_size <= strtab_end) { // FIXME: weak
            char msg[50]; snprintf(msg, sizeof(msg),
                "bad DT_STRSZ %#x", strtab_end);
            throwCantPack(msg);
        }
    }
    unsigned const x_sym = dt_table[Elf32_Dyn::DT_SYMTAB];
    unsigned const x_str = dt_table[Elf32_Dyn::DT_STRTAB];
    if (x_sym && x_str) {
        upx_uint32_t const v_sym = get_te32(&dynp0[-1+ x_sym].d_val);
        upx_uint32_t const v_str = get_te32(&dynp0[-1+ x_str].d_val);
        unsigned const  z_sym = dt_table[Elf32_Dyn::DT_SYMENT];
        unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym)
            : get_te32(&dynp0[-1+ z_sym].d_val);
        if (sz_sym < sizeof(Elf32_Sym)) {
            char msg[50]; snprintf(msg, sizeof(msg),
                "bad DT_SYMENT %x", sz_sym);
            throwCantPack(msg);
        }
        if (v_sym < v_str) {
            symnum_end = (v_str - v_sym) / sz_sym;
        }
        if (symnum_end < 1) {
            throwCantPack("bad DT_SYMTAB");
        }
    }
    // DT_HASH often ends at DT_SYMTAB
    unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);
    if (v_hsh && file_image) {
        hashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_HASH);
        if (!hashtab) {
            char msg[40]; snprintf(msg, sizeof(msg),
               "bad DT_HASH %#x", v_hsh);
            throwCantPack(msg);
        }
        unsigned const nbucket = get_te32(&hashtab[0]);
        unsigned const *const buckets = &hashtab[2];
        unsigned const *const chains = &buckets[nbucket]; (void)chains;

        unsigned const v_sym = !x_sym ? 0 : get_te32(&dynp0[-1+ x_sym].d_val);
        if (!nbucket || !v_sym
        || (nbucket>>31) || (file_size/sizeof(unsigned)) <= (2*nbucket)  // FIXME: weak
        || ((v_hsh < v_sym) && (v_sym - v_hsh) < (sizeof(unsigned)*2  // headers
                + sizeof(*buckets)*nbucket  // buckets
                + sizeof(*chains) *nbucket  // chains
           ))
        ) {
            char msg[90]; snprintf(msg, sizeof(msg),
                "bad DT_HASH nbucket=%#x  len=%#x",
                nbucket, (v_sym - v_hsh));
            throwCantPack(msg);
        }
    }
    // DT_GNU_HASH often ends at DT_SYMTAB;  FIXME: not for Android?
    unsigned const v_gsh = elf_unsigned_dynamic(Elf32_Dyn::DT_GNU_HASH);
    if (v_gsh && file_image) {
        gashtab = (unsigned const *)elf_find_dynamic(Elf32_Dyn::DT_GNU_HASH);
        if (!gashtab) {
            char msg[40]; snprintf(msg, sizeof(msg),
               "bad DT_GNU_HASH %#x", v_gsh);
            throwCantPack(msg);
        }
        unsigned const n_bucket = get_te32(&gashtab[0]);
        unsigned const n_bitmask = get_te32(&gashtab[2]);
        unsigned const gnu_shift = get_te32(&gashtab[3]);
        unsigned const *const bitmask = (unsigned const *)(void const *)&gashtab[4];
        unsigned     const *const buckets = (unsigned const *)&bitmask[n_bitmask];
        unsigned     const *const hasharr = &buckets[n_bucket]; (void)hasharr;
      //unsigned     const *const gashend = &hasharr[n_bucket];  // minimum

        unsigned const v_sym = !x_sym ? 0 : get_te32(&dynp0[-1+ x_sym].d_val);
        if (!n_bucket || !n_bitmask || !v_sym
        || (-1+ n_bitmask) & n_bitmask  // not a power of 2
        || 8*sizeof(unsigned) <= gnu_shift  // shifted result always == 0
        || (n_bucket>>30)  // fie on fuzzers
        || (n_bitmask>>30)
        || (file_size / sizeof(unsigned)) <= (n_bitmask + 2*n_bucket)  // FIXME: weak
        // FIXME: next test does work for Android?
        || ((v_gsh < v_sym) && (v_sym - v_gsh) < (sizeof(unsigned)*4  // headers
                + sizeof(*bitmask)*n_bitmask  // bitmask
                + sizeof(*buckets)*n_bucket  // buckets
                + sizeof(*hasharr)*n_bucket  // hasharr
            ))
        ) {
            char msg[90]; snprintf(msg, sizeof(msg),
                "bad DT_GNU_HASH n_bucket=%#x  n_bitmask=%#x  len=%#x",
                n_bucket, n_bitmask, v_sym - v_gsh);
            throwCantPack(msg);
        }
    }
    unsigned const e_shstrndx = get_te16(&ehdri.e_shstrndx);
    if (e_shnum <= e_shstrndx
    &&  !(0==e_shnum && 0==e_shstrndx) ) {
        char msg[40]; snprintf(msg, sizeof(msg),
            "bad .e_shstrndx %d >= .e_shnum %d", e_shstrndx, e_shnum);
        throwCantPack(msg);
    }
}


static int __usbnet_read_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
			     u16 value, u16 index, void *data, u16 size)
{
	void *buf = NULL;
	int err = -ENOMEM;

	netdev_dbg(dev->net, "usbnet_read_cmd cmd=0x%02x reqtype=%02x"
		   " value=0x%04x index=0x%04x size=%d\n",
		   cmd, reqtype, value, index, size);

	if (data) {
		buf = kmalloc(size, GFP_KERNEL);
		if (!buf)
			goto out;
	}

	err = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
			      cmd, reqtype, value, index, buf, size,
			      USB_CTRL_GET_TIMEOUT);
	if (err > 0 && err <= size)
		memcpy(data, buf, err);
	kfree(buf);
out:
	return err;
}


bool DelegatedFrameHost::ShouldSkipFrame(gfx::Size size_in_dip) const {
  if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
      can_lock_compositor_ == NO_PENDING_COMMIT ||
      !resize_lock_.get())
    return false;

  return size_in_dip != resize_lock_->expected_size();
}


static unsigned int decode_ftime(uint8_t *buf)
{
	int raw;
	struct tm datetime;

	raw = (int) lha_decode_uint32(buf);

	if (raw == 0) {
		return 0;
	}

	// Deconstruct the contents of the MS-DOS time value and populate the
	// 'datetime' structure. Note that 'mktime' generates a timestamp for
	// the local time zone: this is unfortunate, but probably the best
	// that can be done, due to the limited data stored in MS-DOS time
	// values.

	memset(&datetime, 0, sizeof(struct tm));

	datetime.tm_sec = (raw << 1) & 0x3e;
	datetime.tm_min = (raw >> 5) & 0x3f;
	datetime.tm_hour = (raw >> 11) & 0x1f;
	datetime.tm_mday = (raw >> 16) & 0x1f;
	datetime.tm_mon = ((raw >> 21) & 0xf) - 1;
	datetime.tm_year = 80 + ((raw >> 25) & 0x7f);
	datetime.tm_wday = 0;
	datetime.tm_yday = 0;
	datetime.tm_isdst = -1;

	return (unsigned int) mktime(&datetime);
}


int LibRaw::thumbOK(INT64 maxsz)
{
  if (!ID.input)
    return 0;
  if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 &&
                       load_raw == &LibRaw::broadcom_load_raw) // RPi
  )
    return 0;
  INT64 fsize = ID.input->size();
  if (fsize > 0x7fffffffU)
    return 0; // No thumb for raw > 2Gb
  int tsize = 0;
  int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3;
  if (write_thumb == &LibRaw::jpeg_thumb)
    tsize = T.tlength;
  else if (write_thumb == &LibRaw::ppm_thumb)
    tsize = tcol * T.twidth * T.theight;
  else if (write_thumb == &LibRaw::ppm16_thumb)
    tsize = tcol * T.twidth * T.theight *
            ((imgdata.params.raw_processing_options &
              LIBRAW_PROCESSING_USE_PPM16_THUMBS)
                 ? 2
                 : 1);
#ifdef USE_X3FTOOLS
  else if (write_thumb == &LibRaw::x3f_thumb_loader)
  {
    tsize = x3f_thumb_size();
  }
#endif
  else // Kodak => no check
    tsize = 1;
  if (tsize < 0)
    return 0;
  if (maxsz > 0 && tsize > maxsz)
    return 0;
  return (tsize + ID.toffset <= fsize) ? 1 : 0;
}


static void ActivityLoggingAccessForAllWorldsMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
  TestObject* impl = V8TestObject::ToImpl(info.Holder());

  impl->activityLoggingAccessForAllWorldsMethod();
}


int CommandData::IsProcessFile(FileHeader &FileHead,bool *ExactMatch,int MatchType,
                               wchar *MatchedArg,uint MatchedArgSize)
{
  if (MatchedArg!=NULL && MatchedArgSize>0)
    *MatchedArg=0;
  if (wcslen(FileHead.FileName)>=NM)
    return 0;
  bool Dir=FileHead.Dir;
  if (ExclCheck(FileHead.FileName,Dir,false,true))
    return 0;
#ifndef SFX_MODULE
  if (TimeCheck(FileHead.mtime))
    return 0;
  if ((FileHead.FileAttr & ExclFileAttr)!=0 || InclAttrSet && (FileHead.FileAttr & InclFileAttr)==0)
    return 0;
  if (!Dir && SizeCheck(FileHead.UnpSize))
    return 0;
#endif
  wchar *ArgName;
  FileArgs.Rewind();
  for (int StringCount=1;(ArgName=FileArgs.GetString())!=NULL;StringCount++)
    if (CmpName(ArgName,FileHead.FileName,MatchType))
    {
      if (ExactMatch!=NULL)
        *ExactMatch=wcsicompc(ArgName,FileHead.FileName)==0;
      if (MatchedArg!=NULL)
        wcsncpyz(MatchedArg,ArgName,MatchedArgSize);
      return StringCount;
    }
  return 0;
}


std::string ChromeContentBrowserClient::GetGeolocationApiKey() {
  return google_apis::GetAPIKey();
}


static RRBNode *_rot_twice(RRBNode *root, int dir) {
	r_return_val_if_fail (root, NULL);

	_set_link (root, _rot_once (root->link[!dir], !dir), !dir);
	return _rot_once (root, dir);
}


  void RunMultipleWheelScroll() {
    DoSmoothWheelScroll(gfx::Vector2d(0, 100));
    while (!VerifyRecordedSamplesForHistogram(
        1, "Event.Latency.ScrollBegin.Wheel.TimeToScrollUpdateSwapBegin4")) {
      GiveItSomeTime();
      FetchHistogramsFromChildProcesses();
    }

    while (!VerifyRecordedSamplesForHistogram(
        1, "Event.Latency.ScrollUpdate.Wheel.TimeToScrollUpdateSwapBegin4")) {
      GiveItSomeTime();
      FetchHistogramsFromChildProcesses();
     }
   }


static void setup_buffer_inter ( VP9_COMP * cpi , MACROBLOCK * x , const TileInfo * const tile , MV_REFERENCE_FRAME ref_frame , BLOCK_SIZE block_size , int mi_row , int mi_col , int_mv frame_nearest_mv [ MAX_REF_FRAMES ] , int_mv frame_near_mv [ MAX_REF_FRAMES ] , struct buf_2d yv12_mb [ 4 ] [ MAX_MB_PLANE ] ) {
 const VP9_COMMON * cm = & cpi -> common ;
 const YV12_BUFFER_CONFIG * yv12 = get_ref_frame_buffer ( cpi , ref_frame ) ;
 MACROBLOCKD * const xd = & x -> e_mbd ;
 MODE_INFO * const mi = xd -> mi [ 0 ] . src_mi ;
 int_mv * const candidates = mi -> mbmi . ref_mvs [ ref_frame ] ;
 const struct scale_factors * const sf = & cm -> frame_refs [ ref_frame - 1 ] . sf ;
 vp9_setup_pred_block ( xd , yv12_mb [ ref_frame ] , yv12 , mi_row , mi_col , sf , sf ) ;
 vp9_find_mv_refs ( cm , xd , tile , mi , ref_frame , candidates , mi_row , mi_col ) ;
 vp9_find_best_ref_mvs ( xd , cm -> allow_high_precision_mv , candidates , & frame_nearest_mv [ ref_frame ] , & frame_near_mv [ ref_frame ] ) ;
 if ( ! vp9_is_scaled ( sf ) && block_size >= BLOCK_8X8 ) vp9_mv_pred ( cpi , x , yv12_mb [ ref_frame ] [ 0 ] . buf , yv12 -> y_stride , ref_frame , block_size ) ;
 }


static bool is_orphaned_event(struct perf_event *event)
{
	return event->state == PERF_EVENT_STATE_DEAD;
}


void PaymentRequestState::SetDefaultProfileSelections() {
  if (!contact_profiles().empty() &&
      profile_comparator()->IsContactInfoComplete(contact_profiles_[0]))
    selected_contact_profile_ = contact_profiles()[0];

  const std::vector<std::unique_ptr<PaymentInstrument>>& instruments =
      available_instruments();
  auto first_complete_instrument =
      std::find_if(instruments.begin(), instruments.end(),
                   [](const std::unique_ptr<PaymentInstrument>& instrument) {
                     return instrument->IsCompleteForPayment() &&
                            instrument->IsExactlyMatchingMerchantRequest();
                   });
  selected_instrument_ = first_complete_instrument == instruments.end()
                             ? nullptr
                             : first_complete_instrument->get();

  SelectDefaultShippingAddressAndNotifyObservers();

  bool has_complete_instrument =
      available_instruments().empty()
          ? false
          : available_instruments()[0]->IsCompleteForPayment();

  journey_logger_->SetNumberOfSuggestionsShown(
      JourneyLogger::Section::SECTION_PAYMENT_METHOD,
      available_instruments().size(), has_complete_instrument);
}


free_StreamsInfo(struct _7z_stream_info *si)
{
	free_PackInfo(&(si->pi));
	free_CodersInfo(&(si->ci));
	free_SubStreamsInfo(&(si->ss));
}


int kvm_deassign_device(struct kvm *kvm,
			struct kvm_assigned_dev_kernel *assigned_dev)
{
	struct iommu_domain *domain = kvm->arch.iommu_domain;
	struct pci_dev *pdev = NULL;

	/* check if iommu exists and in use */
	if (!domain)
		return 0;

	pdev = assigned_dev->dev;
	if (pdev == NULL)
		return -ENODEV;

	iommu_detach_device(domain, &pdev->dev);

	pdev->dev_flags &= ~PCI_DEV_FLAGS_ASSIGNED;

	dev_info(&pdev->dev, "kvm deassign device\n");

	return 0;
}


void FrameView::forceLayout(bool allowSubtree)
{
    layout(allowSubtree);
}


void ProfileSyncService::OnDisableDatatype(
    syncable::ModelType type,
    const tracked_objects::Location& from_here,
    std::string message) {
  DeactivateDataType(type);

  SyncError error(from_here, message, type);

  std::list<SyncError> errors;
  errors.push_back(error);

  failed_datatypes_handler_.UpdateFailedDatatypes(errors,
      FailedDatatypesHandler::RUNTIME);

  MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&ProfileSyncService::ReconfigureDatatypeManager,
                 weak_factory_.GetWeakPtr()));
}


void kvm_set_page_dirty(struct page *page)
{
	kvm_set_pfn_dirty(page_to_pfn(page));
}


static int zipfileUpdate(
  sqlite3_vtab *pVtab,
  int nVal,
  sqlite3_value **apVal,
  sqlite_int64 *pRowid
){
  ZipfileTab *pTab = (ZipfileTab*)pVtab;
  int rc = SQLITE_OK;             /* Return Code */
  ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */

  u32 mode = 0;                   /* Mode for new entry */
  u32 mTime = 0;                  /* Modification time for new entry */
  i64 sz = 0;                     /* Uncompressed size */
  const char *zPath = 0;          /* Path for new entry */
  int nPath = 0;                  /* strlen(zPath) */
  const u8 *pData = 0;            /* Pointer to buffer containing content */
  int nData = 0;                  /* Size of pData buffer in bytes */
  int iMethod = 0;                /* Compression method for new entry */
  u8 *pFree = 0;                  /* Free this */
  char *zFree = 0;                /* Also free this */
  ZipfileEntry *pOld = 0;
  ZipfileEntry *pOld2 = 0;
  int bUpdate = 0;                /* True for an update that modifies "name" */
  int bIsDir = 0;
  u32 iCrc32 = 0;

  if( pTab->pWriteFd==0 ){
    rc = zipfileBegin(pVtab);
    if( rc!=SQLITE_OK ) return rc;
  }

  /* If this is a DELETE or UPDATE, find the archive entry to delete. */
  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
    const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
    int nDelete = (int)strlen(zDelete);
    if( nVal>1 ){
      const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
      if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
        bUpdate = 1;
      }
    }
    for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
      if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
        break;
      }
      assert( pOld->pNext );
    }
  }

  if( nVal>1 ){
    /* Check that "sz" and "rawdata" are both NULL: */
    if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
      zipfileTableErr(pTab, "sz must be NULL");
      rc = SQLITE_CONSTRAINT;
    }
    if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
      zipfileTableErr(pTab, "rawdata must be NULL");
      rc = SQLITE_CONSTRAINT;
    }

    if( rc==SQLITE_OK ){
      if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
        /* data=NULL. A directory */
        bIsDir = 1;
      }else{
        /* Value specified for "data", and possibly "method". This must be
        ** a regular file or a symlink. */
        const u8 *aIn = sqlite3_value_blob(apVal[7]);
        int nIn = sqlite3_value_bytes(apVal[7]);
        int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;

        iMethod = sqlite3_value_int(apVal[8]);
        sz = nIn;
        pData = aIn;
        nData = nIn;
        if( iMethod!=0 && iMethod!=8 ){
          zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
          rc = SQLITE_CONSTRAINT;
        }else{
          if( bAuto || iMethod ){
            int nCmp;
            rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
            if( rc==SQLITE_OK ){
              if( iMethod || nCmp<nIn ){
                iMethod = 8;
                pData = pFree;
                nData = nCmp;
              }
            }
          }
          iCrc32 = crc32(0, aIn, nIn);
        }
      }
    }

    if( rc==SQLITE_OK ){
      rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
    }

    if( rc==SQLITE_OK ){
      zPath = (const char*)sqlite3_value_text(apVal[2]);
      if( zPath==0 ) zPath = "";
      nPath = (int)strlen(zPath);
      mTime = zipfileGetTime(apVal[4]);
    }

    if( rc==SQLITE_OK && bIsDir ){
      /* For a directory, check that the last character in the path is a
      ** '/'. This appears to be required for compatibility with info-zip
      ** (the unzip command on unix). It does not create directories
      ** otherwise.  */
      if( zPath[nPath-1]!='/' ){
        zFree = sqlite3_mprintf("%s/", zPath);
        if( zFree==0 ){ rc = SQLITE_NOMEM; }
        zPath = (const char*)zFree;
        nPath = (int)strlen(zPath);
      }
    }

    /* Check that we're not inserting a duplicate entry -OR- updating an
    ** entry with a path, thereby making it into a duplicate. */
    if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
      ZipfileEntry *p;
      for(p=pTab->pFirstEntry; p; p=p->pNext){
        if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
          switch( sqlite3_vtab_on_conflict(pTab->db) ){
            case SQLITE_IGNORE: {
              goto zipfile_update_done;
            }
            case SQLITE_REPLACE: {
              pOld2 = p;
              break;
            }
            default: {
              zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
              rc = SQLITE_CONSTRAINT;
              break;
            }
          }
          break;
        }
      }
    }

    if( rc==SQLITE_OK ){
      /* Create the new CDS record. */
      pNew = zipfileNewEntry(zPath);
      if( pNew==0 ){
        rc = SQLITE_NOMEM;
      }else{
        pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
        pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
        pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
        pNew->cds.iCompression = (u16)iMethod;
        zipfileMtimeToDos(&pNew->cds, mTime);
        pNew->cds.crc32 = iCrc32;
        pNew->cds.szCompressed = nData;
        pNew->cds.szUncompressed = (u32)sz;
        pNew->cds.iExternalAttr = (mode<<16);
        pNew->cds.iOffset = (u32)pTab->szCurrent;
        pNew->cds.nFile = (u16)nPath;
        pNew->mUnixTime = (u32)mTime;
        rc = zipfileAppendEntry(pTab, pNew, pData, nData);
        zipfileAddEntry(pTab, pOld, pNew);
      }
    }
  }

  if( rc==SQLITE_OK && (pOld || pOld2) ){
    ZipfileCsr *pCsr;
    for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
      if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
        pCsr->pCurrent = pCsr->pCurrent->pNext;
        pCsr->bNoop = 1;
      }
    }

    zipfileRemoveEntryFromList(pTab, pOld);
    zipfileRemoveEntryFromList(pTab, pOld2);
  }

zipfile_update_done:
  sqlite3_free(pFree);
  sqlite3_free(zFree);
  return rc;
}


ext4_xattr_put_super(struct super_block *sb)
{
	mb_cache_shrink(sb->s_bdev);
}


static void evdns_resolv_set_defaults ( int flags ) {
 if ( flags & DNS_OPTION_SEARCH ) search_set_from_hostname ( ) ;
 if ( flags & DNS_OPTION_NAMESERVERS ) evdns_nameserver_ip_add ( "127.0.0.1" ) ;
 }


SWFShape_getFills(SWFShape shape, SWFFillStyle** fills, int* nFills)
{
	*fills = shape->fills;
	*nFills = shape->nFills;
}


uc_split_args(char_u *arg, size_t *lenp)
{
    char_u *buf;
    char_u *p;
    char_u *q;
    int len;

    // Precalculate length
    p = arg;
    len = 2; // Initial and final quotes

    while (*p)
    {
	if (p[0] == '\\' && p[1] == '\\')
	{
	    len += 2;
	    p += 2;
	}
	else if (p[0] == '\\' && VIM_ISWHITE(p[1]))
	{
	    len += 1;
	    p += 2;
	}
	else if (*p == '\\' || *p == '"')
	{
	    len += 2;
	    p += 1;
	}
	else if (VIM_ISWHITE(*p))
	{
	    p = skipwhite(p);
	    if (*p == NUL)
		break;
	    len += 4; // ", "
	}
	else
	{
	    int charlen = (*mb_ptr2len)(p);

	    len += charlen;
	    p += charlen;
	}
    }

    buf = alloc(len + 1);
    if (buf == NULL)
    {
	*lenp = 0;
	return buf;
    }

    p = arg;
    q = buf;
    *q++ = '"';
    while (*p)
    {
	if (p[0] == '\\' && p[1] == '\\')
	{
	    *q++ = '\\';
	    *q++ = '\\';
	    p += 2;
	}
	else if (p[0] == '\\' && VIM_ISWHITE(p[1]))
	{
	    *q++ = p[1];
	    p += 2;
	}
	else if (*p == '\\' || *p == '"')
	{
	    *q++ = '\\';
	    *q++ = *p++;
	}
	else if (VIM_ISWHITE(*p))
	{
	    p = skipwhite(p);
	    if (*p == NUL)
		break;
	    *q++ = '"';
	    *q++ = ',';
	    *q++ = ' ';
	    *q++ = '"';
	}
	else
	{
	    MB_COPY_CHAR(p, q);
	}
    }
    *q++ = '"';
    *q = 0;

    *lenp = len;
    return buf;
}


void PrepareFrameAndViewForPrint::UpdatePrintParams(
    const PrintMsg_Print_Params& print_params) {
  DCHECK(!finished_);
  WebKit::WebPrintParams webkit_print_params;
  ComputeWebKitPrintParamsInDesiredDpi(print_params, &webkit_print_params);

  if (webkit_print_params.printContentArea ==
          web_print_params_.printContentArea &&
      webkit_print_params.printableArea == web_print_params_.printableArea &&
      webkit_print_params.paperSize == web_print_params_.paperSize &&
      webkit_print_params.printScalingOption ==
          web_print_params_.printScalingOption) {
    return;
  }

  frame_->printEnd();
  StartPrinting(webkit_print_params);
}


static void finalize_hmac_key(char *K, HashEnginePtr ops, void *context,
                              char *digest) {
  /* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
  for (int i = 0; i < ops->block_size; i++) {
    K[i] ^= 0x6A;
  }

  /* Feed this result into the outter hash */
  ops->hash_init(context);
  ops->hash_update(context, (unsigned char *)K, ops->block_size);
  ops->hash_update(context, (unsigned char *)digest, ops->digest_size);
  ops->hash_final((unsigned char *)digest, context);

  /* Zero the key */
  memset(K, 0, ops->block_size);
  free(K);
}


String string_escape_shell_cmd(const char *str) {
  register int x, y, l;
  char *cmd;
  char *p = nullptr;

  l = strlen(str);
  String ret(safe_address(l, 2, 1), ReserveString);
  cmd = ret.bufferSlice().ptr;

  for (x = 0, y = 0; x < l; x++) {
    switch (str[x]) {
    case '"':
    case '\'':
      if (!p && (p = (char *)memchr(str + x + 1, str[x], l - x - 1))) {
        /* noop */
      } else if (p && *p == str[x]) {
        p = nullptr;
      } else {
        cmd[y++] = '\\';
      }
      cmd[y++] = str[x];
      break;
    case '#': /* This is character-set independent */
    case '&':
    case ';':
    case '`':
    case '|':
    case '*':
    case '?':
    case '~':
    case '<':
    case '>':
    case '^':
    case '(':
    case ')':
    case '[':
    case ']':
    case '{':
    case '}':
    case '$':
    case '\\':
    case '\x0A': /* excluding these two */
    case '\xFF':
      cmd[y++] = '\\';
      /* fall-through */
    default:
      cmd[y++] = str[x];
    }
  }
  ret.setSize(y);
  return ret;
}


  void ResetObserver() {
    suppressed_ = false;
    notified_ = false;
  }


PCIBus *pci_pmac_init(qemu_irq *pic)

{

    DeviceState *dev;

    SysBusDevice *s;

    UNINState *d;

    /* Use values found on a real PowerMac */

    /* Uninorth main bus */

    dev = qdev_create(NULL, "Uni-north main");

    qdev_init_nofail(dev);

    s = sysbus_from_qdev(dev);

    d = FROM_SYSBUS(UNINState, s);

    d->host_state.bus = pci_register_bus(&d->busdev.qdev, "pci",

                                         pci_unin_set_irq, pci_unin_map_irq,

                                         pic, 11 << 3, 4);

    pci_create_simple(d->host_state.bus, 11 << 3, "Uni-north main");

    sysbus_mmio_map(s, 0, 0xf2800000);

    sysbus_mmio_map(s, 1, 0xf2c00000);

    /* DEC 21154 bridge */

#if 0

    /* XXX: not activated as PPC BIOS doesn't handle multiple buses properly */

    pci_create_simple(d->host_state.bus, 12 << 3, "DEC 21154");

#endif

    /* Uninorth AGP bus */

    pci_create_simple(d->host_state.bus, 13 << 3, "Uni-north AGP");

    /* Uninorth internal bus */

#if 0

    /* XXX: not needed for now */

    pci_create_simple(d->host_state.bus, 14 << 3, "Uni-north internal");

#endif

    return d->host_state.bus;

}


void Editor::ReplaceSelection(const String& text) {
  DCHECK(!GetFrame().GetDocument()->NeedsLayoutTreeUpdate());
  bool select_replacement = Behavior().ShouldSelectReplacement();
  bool smart_replace = true;
  ReplaceSelectionWithText(text, select_replacement, smart_replace,
                           InputEvent::InputType::kInsertReplacementText);
}


bool WebPage::selectionContainsDocumentPoint(const Platform::IntPoint& point)
{
    return d->m_selectionHandler->selectionContains(point);
}


struct drm_property *drm_property_create(struct drm_device *dev, int flags,
					 const char *name, int num_values)
{
	struct drm_property *property = NULL;

	property = kzalloc(sizeof(struct drm_property), GFP_KERNEL);
	if (!property)
		return NULL;

	if (num_values) {
		property->values = kzalloc(sizeof(uint64_t)*num_values, GFP_KERNEL);
		if (!property->values)
			goto fail;
	}

	drm_mode_object_get(dev, &property->base, DRM_MODE_OBJECT_PROPERTY);
	property->flags = flags;
	property->num_values = num_values;
	INIT_LIST_HEAD(&property->enum_blob_list);

	if (name) {
		strncpy(property->name, name, DRM_PROP_NAME_LEN);
		property->name[DRM_PROP_NAME_LEN-1] = '\0';
	}

	list_add_tail(&property->head, &dev->mode_config.property_list);
	return property;
fail:
	kfree(property);
	return NULL;
}


action_pool_changed (PolkitBackendActionPool *action_pool,
                     PolkitBackendInteractiveAuthority *authority)
{
  g_signal_emit_by_name (authority, "changed");
}


vim_isprintc_strict(int c)
{
    if (enc_dbcs != 0 && c < 0x100 && MB_BYTE2LEN(c) > 1)
	return FALSE;
    if (enc_utf8 && c >= 0x100)
	return utf_printable(c);
    return (c >= 0x100 || (c > 0 && (g_chartab[c] & CT_PRINT_CHAR)));
}


static int new_socket(struct addrinfo *ai) {
    int sfd;
    int flags;

    if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
        return -1;
    }

    if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
        fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
        perror("setting O_NONBLOCK");
        close(sfd);
        return -1;
    }
    return sfd;
}


size_t Camera2Client::calculateBufferSize(int width, int height,
 int format, int stride) {
 switch (format) {
 case HAL_PIXEL_FORMAT_YCbCr_422_SP: // NV16
 return width * height * 2;
 case HAL_PIXEL_FORMAT_YCrCb_420_SP: // NV21
 return width * height * 3 / 2;
 case HAL_PIXEL_FORMAT_YCbCr_422_I: // YUY2
 return width * height * 2;
 case HAL_PIXEL_FORMAT_YV12: { // YV12
 size_t ySize = stride * height;
 size_t uvStride = (stride / 2 + 0xF) & ~0xF;
 size_t uvSize = uvStride * height / 2;
 return ySize + uvSize * 2;
 }
 case HAL_PIXEL_FORMAT_RGB_565:
 return width * height * 2;
 case HAL_PIXEL_FORMAT_RGBA_8888:
 return width * height * 4;
 case HAL_PIXEL_FORMAT_RAW_SENSOR:
 return width * height * 2;
 default:
            ALOGE("%s: Unknown preview format: %x",
                    __FUNCTION__,  format);
 return 0;
 }
}


bool CIRCNetwork::SetNextServer(const CServer* pServer) {
    for (unsigned int a = 0; a < m_vServers.size(); a++) {
        if (m_vServers[a] == pServer) {
            m_uServerIdx = a;
            return true;
        }
    }

    return false;
}


int build_subst_list(LOGBOOK *lbs, char list[][NAME_LENGTH], char value[][NAME_LENGTH],
                     char attrib[][NAME_LENGTH], BOOL format_date) {
   int i;
   char str[NAME_LENGTH], format[256], full_name[256], user_email[256];
   time_t t;
   struct tm *ts;

   /* copy attribute list */
   i = 0;
   if (attrib != NULL)
      for (; i < lbs->n_attr; i++) {
         strcpy(list[i], attr_list[i]);
         if (attrib) {
            if ((attr_flags[i] & AF_DATE) && format_date) {

               t = (time_t) atoi(attrib[i]);
               ts = localtime(&t);
               assert(ts);

               sprintf(str, "Date format %s", attr_list[i]);
               if (!getcfg(lbs->name, str, format, sizeof(format)))
                  if (!getcfg(lbs->name, "Date format", format, sizeof(format)))
                     strcpy(format, DEFAULT_DATE_FORMAT);

               my_strftime(value[i], NAME_LENGTH, format, ts);

            } else if ((attr_flags[i] & AF_DATETIME) && format_date) {

               t = (time_t) atoi(attrib[i]);
               ts = localtime(&t);
               assert(ts);

               sprintf(str, "Time format %s", attr_list[i]);
               if (!getcfg(lbs->name, str, format, sizeof(format)))
                  if (!getcfg(lbs->name, "Time format", format, sizeof(format)))
                     strcpy(format, DEFAULT_TIME_FORMAT);

               my_strftime(value[i], NAME_LENGTH, format, ts);

            } else
               strcpy(value[i], attrib[i]);
         } else
            strlcpy(value[i], isparam(attr_list[i]) ? getparam(attr_list[i]) : "", NAME_LENGTH);
      }

   /* add remote host */
   strcpy(list[i], "remote_host");
   strlcpy(value[i++], rem_host, NAME_LENGTH);

   /* add local host */
   strcpy(list[i], "host");
   strlcpy(value[i++], host_name, NAME_LENGTH);

   /* add forwarded user */
   strcpy(list[i], "http_user");
   strlcpy(value[i++], http_user, NAME_LENGTH);

   /* add user names */
   strcpy(list[i], "short_name");
   if (isparam("unm")) {
      strlcpy(value[i++], getparam("unm"), NAME_LENGTH);
      get_user_line(lbs, getparam("unm"), NULL, full_name, user_email, NULL, NULL, NULL);
   } else {
      strlcpy(value[i++], loc("Anonymous"), NAME_LENGTH);
      strcpy(full_name, loc("Anonymous"));
      user_email[0] = 0;
   }

   strcpy(list[i], "long_name");
   strlcpy(value[i++], full_name, NAME_LENGTH);

   /* add email */
   if (user_email[0]) {
      strcpy(list[i], "user_email");
      strcpy(value[i], "mailto:");
      strlcat(value[i++], user_email, NAME_LENGTH);
   }

   /* add logbook */
   if (lbs) {
      strcpy(list[i], "logbook");
      strlcpy(value[i++], lbs->name, NAME_LENGTH);

      /* add logbook */
      strcpy(list[i], "elogbook");
      strlcpy(value[i++], lbs->name_enc, NAME_LENGTH);
   }

   /* add date */
   strcpy(list[i], "date");
   time(&t);
   if (format_date) {
      ts = localtime(&t);
      assert(ts);
      if (!getcfg(lbs->name, "Time format", format, sizeof(format)))
         strcpy(format, DEFAULT_TIME_FORMAT);

      my_strftime(str, sizeof(str), format, ts);
   } else
      sprintf(str, "%d", (int) t);
   strcpy(value[i++], str);

   /* add UTC date */
   strcpy(list[i], "utcdate");
   time(&t);
   if (format_date) {
      ts = gmtime(&t);
      if (!getcfg(lbs->name, "Time format", format, sizeof(format)))
         strcpy(format, DEFAULT_TIME_FORMAT);

      my_strftime(str, sizeof(str), format, ts);
   } else
      sprintf(str, "%d", (int) t);
   strcpy(value[i++], str);

   /* add ELOG version and revision */
   strcpy(list[i], "version");
   strcpy(value[i++], VERSION);

   strcpy(list[i], "revision");
   sprintf(value[i++], "%s", git_revision());

   return i;
}


int web_server_set_alias ( const char * alias_name , const char * alias_content , size_t alias_content_length , time_t last_modified ) {
 int ret_code ;
 struct xml_alias_t alias ;
 alias_release ( & gAliasDoc ) ;
 if ( alias_name == NULL ) {
 return 0 ;
 }
 assert ( alias_content != NULL ) ;
 membuffer_init ( & alias . doc ) ;
 membuffer_init ( & alias . name ) ;
 alias . ct = NULL ;
 do {
 if ( * alias_name != '/' ) if ( membuffer_assign_str ( & alias . name , "/" ) != 0 ) break ;
 ret_code = membuffer_append_str ( & alias . name , alias_name ) ;
 if ( ret_code != 0 ) break ;
 if ( ( alias . ct = ( int * ) malloc ( sizeof ( int ) ) ) == NULL ) break ;
 * alias . ct = 1 ;
 membuffer_attach ( & alias . doc , ( char * ) alias_content , alias_content_length ) ;
 alias . last_modified = last_modified ;
 ithread_mutex_lock ( & gWebMutex ) ;
 gAliasDoc = alias ;
 ithread_mutex_unlock ( & gWebMutex ) ;
 return 0 ;
 }
 while ( FALSE ) ;
 membuffer_destroy ( & alias . name ) ;
 membuffer_destroy ( & alias . doc ) ;
 free ( alias . ct ) ;
 return UPNP_E_OUTOF_MEMORY ;
 }


void ber_free ( BerElement * ber , int freebuf ) {
 if ( ber == NULL ) {
 LDAP_MEMORY_DEBUG_ASSERT ( ber != NULL ) ;
 return ;
 }
 if ( freebuf ) ber_free_buf ( ber ) ;
 ber_memfree_x ( ( char * ) ber , ber -> ber_memctx ) ;
 }


decompile5Action(int n, SWF_ACTION *actions,int indent)
{
	int j;
	if( !n  )
		return NULL;

	pool = NULL;
	poolcounter = 0;

	dcinit();

	for(j=0;j<256;j++) regs[j]=0;
	regs[1] = newVar("R1");
	regs[2] = newVar("R2");
	regs[3] = newVar("R3");
	regs[4] = newVar("R4");

	decompileActions(n, actions, indent);
#ifdef DEBUGSTACK
	if( Stack != NULL && *dcstr)
	{
		int i=0;
		println("/* -----------------------------------------------------------------");
		println("NOTE: some stuff left on the stack at the end of a block of actions:");
		while (Stack)
		{
			i++;
			printf("%d.:\t%s",i, getString(pop()));
			println("");
		}
		println("*/");
	}
#else
	if( Stack != NULL )
		fprintf(stderr,
		"Stuff left on the stack at the end of a block of actions!?!?!?\n");
	while (Stack)
	{
		pop();
	}
#endif
	return dcgetstr();
}


static int CompareEdges(const void *x,const void *y)
{
  register const EdgeInfo
    *p,
    *q;

  /*
    Compare two edges.
  */
  p=(const EdgeInfo *) x;
  q=(const EdgeInfo *) y;
  if ((p->points[0].y-DrawEpsilon) > q->points[0].y)
    return(1);
  if ((p->points[0].y+DrawEpsilon) < q->points[0].y)
    return(-1);
  if ((p->points[0].x-DrawEpsilon) > q->points[0].x)
    return(1);
  if ((p->points[0].x+DrawEpsilon) < q->points[0].x)
    return(-1);
  if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
       (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
    return(1);
  return(-1);
}


static bool php_ldap_do_modify(const Resource& link, const String& dn, const Array& entry,
                               int oper) {
  bool is_full_add = false; /* flag for full add operation so ldap_mod_add
                               can be put back into oper, gerrit THomson */

  auto ld = get_valid_ldap_link_resource(link);
  if (!ld) {
    return false;
  }

  int num_attribs = entry.size();
  LDAPMod **ldap_mods =
    (LDAPMod **)malloc((num_attribs+1) * sizeof(LDAPMod *));
  int *num_berval = (int*)malloc(num_attribs * sizeof(int));

  ArrayIter iter(entry);
  int num_values;

  /* added by gerrit thomson to fix ldap_add using ldap_mod_add */
  if (oper == PHP_LD_FULL_ADD) {
    oper = LDAP_MOD_ADD;
    is_full_add = true;
  }
  /* end additional , gerrit thomson */

  bool ret = false;
  Array stringHolder = Array::CreateVec();
  for (int i = 0; i < num_attribs; i++) {
    ldap_mods[i] = (LDAPMod*)malloc(sizeof(LDAPMod));
    ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
    ldap_mods[i]->mod_type = nullptr;

    Variant key = iter.first();
    Variant value = iter.second();
    if (key.isString()) {
      ldap_mods[i]->mod_type = strdup(key.toString().data());
    } else {
      raise_warning("Unknown attribute in the data");
      /* Free allocated memory */
      while (i >= 0) {
        if (ldap_mods[i]->mod_type) {
          free(ldap_mods[i]->mod_type);
        }
        free(ldap_mods[i]);
        i--;
      }
      free(num_berval);
      free(ldap_mods);
      return false;
    }

    if (!value.isArray()) {
      num_values = 1;
    } else {
      num_values = value.toArray().size();
    }

    num_berval[i] = num_values;
    ldap_mods[i]->mod_bvalues =
      (struct berval**)malloc((num_values + 1) * sizeof(struct berval *));

    /* allow for arrays with one element, no allowance for arrays with
       none but probably not required, gerrit thomson. */
    if (num_values == 1 && !value.isArray()) {
      String svalue = value.toString();
      stringHolder.append(svalue);
      ldap_mods[i]->mod_bvalues[0] = (berval *)malloc(sizeof(struct berval));
      ldap_mods[i]->mod_bvalues[0]->bv_len = svalue.size();
      ldap_mods[i]->mod_bvalues[0]->bv_val = (char*)svalue.data();
    } else {
      Array arr = value.toArray();
      for (int j = 0; j < num_values; j++) {
        if (!arr.exists(j)) {
          raise_warning("Value array must have consecutive indices 0, 1, ...");
          num_berval[i] = j;
          num_attribs = i + 1;
          goto errexit;
        }
        String ivalue = arr[j].toString();
        ldap_mods[i]->mod_bvalues[j] = (berval *)malloc(sizeof(struct berval));
        ldap_mods[i]->mod_bvalues[j]->bv_len = ivalue.size();
        ldap_mods[i]->mod_bvalues[j]->bv_val = (char*)ivalue.data();
      }
    }
    ldap_mods[i]->mod_bvalues[num_values] = nullptr;
    ++iter;
  }
  ldap_mods[num_attribs] = nullptr;

  /* check flag to see if do_mod was called to perform full add,
     gerrit thomson */
  int rc;
  if (is_full_add) {
    if ((rc = ldap_add_s(ld->link, (char*)dn.data(), ldap_mods))
        != LDAP_SUCCESS) {
      raise_warning("Add: %s", ldap_err2string(rc));
    } else {
      ret = true;
    }
  } else {
    if ((rc = ldap_modify_s(ld->link, (char*)dn.data(), ldap_mods))
        != LDAP_SUCCESS) {
      raise_warning("Modify: %s", ldap_err2string(rc));
    } else {
      ret = true;
    }
  }

errexit:
  for (int i = 0; i < num_attribs; i++) {
    free(ldap_mods[i]->mod_type);
    for (int j = 0; j < num_berval[i]; j++) {
      free(ldap_mods[i]->mod_bvalues[j]);
    }
    free(ldap_mods[i]->mod_bvalues);
    free(ldap_mods[i]);
  }
  free(num_berval);
  free(ldap_mods);

  return ret;
}


static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
		unsigned long end, int write, struct page **pages, int *nr)
{
	struct page *head, *page;
	int refs;

	if (!pud_access_permitted(orig, write))
		return 0;

	if (pud_devmap(orig))
		return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);

	refs = 0;
	page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
	do {
		pages[*nr] = page;
		(*nr)++;
		page++;
 		refs++;
 	} while (addr += PAGE_SIZE, addr != end);

	head = try_get_compound_head(pud_page(orig), refs);
	if (!head) {
 		*nr -= refs;
 		return 0;
 	}

	if (unlikely(pud_val(orig) != pud_val(*pudp))) {
		*nr -= refs;
		while (refs--)
			put_page(head);
		return 0;
	}

	SetPageReferenced(head);
	return 1;
}


AppResult::AppResult(Profile* profile,
                     const std::string& app_id,
                     AppListControllerDelegate* controller,
                     bool is_recommendation)
    : profile_(profile),
      app_id_(app_id),
      controller_(controller),
      extension_registry_(NULL) {
  set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id_).spec());
  if (app_list::switches::IsExperimentalAppListEnabled())
     set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE);

   const extensions::Extension* extension =
      extensions::ExtensionSystem::Get(profile_)->extension_service()
          ->GetInstalledExtension(app_id_);
   DCHECK(extension);

   is_platform_app_ = extension->is_platform_app();

  icon_.reset(
      new extensions::IconImage(profile_,
                                extension,
                                extensions::IconsInfo::GetIcons(extension),
                                GetPreferredIconDimension(),
                                extensions::util::GetDefaultAppIcon(),
                                this));
  UpdateIcon();

  StartObservingExtensionRegistry();
}


  HtmlDialogWithoutContextMenuView(Profile* profile,
                                   HtmlDialogUIDelegate* delegate)
      : HtmlDialogView(profile, delegate) {}


ldbm_config_read_instance_entries(struct ldbminfo *li, const char *backend_type)
{
    Slapi_PBlock *tmp_pb;
    Slapi_Entry **entries = NULL;
    char *basedn = NULL;
    int rc = 0;

    /* Construct the base dn of the subtree that holds the instance entries. */
    basedn = slapi_create_dn_string("cn=%s,cn=plugins,cn=config", backend_type);
    if (NULL == basedn) {
        slapi_log_err(SLAPI_LOG_ERR,
                      "ldbm_config_read_instance_entries",
                      "failed to create backend dn for %s\n", backend_type);
        return 1;
    }

    /* Do a search of the subtree containing the instance entries */
    tmp_pb = slapi_pblock_new();
    slapi_search_internal_set_pb(tmp_pb, basedn, LDAP_SCOPE_SUBTREE, "(objectclass=nsBackendInstance)", NULL, 0, NULL, NULL, li->li_identity, 0);
    slapi_search_internal_pb(tmp_pb);
    slapi_pblock_get(tmp_pb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &entries);
    if (entries != NULL) {
        int i;
        for (i = 0; entries[i] != NULL; i++) {
            rc = ldbm_instance_add_instance_entry_callback(NULL,
                                                           entries[i], NULL, NULL, NULL, li);
            if (SLAPI_DSE_CALLBACK_ERROR == rc) {
                slapi_log_err(SLAPI_LOG_ERR,
                              "ldbm_config_read_instance_entries",
                              "Failed to add instance entry %s\n",
                              slapi_entry_get_dn_const(entries[i]));
                break;
            }
            rc = 0;
        }
    }

    slapi_free_search_results_internal(tmp_pb);
    slapi_pblock_destroy(tmp_pb);
    slapi_ch_free_string(&basedn);

    return rc;
}


GF_Err ccst_Size(GF_Box *s)
{
	GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s;
	ptr->size += 4;
	return GF_OK;
}


av_cold void ff_dsputil_init_alpha(DSPContext *c, AVCodecContext *avctx)

{

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

    /* amask clears all bits that correspond to present features.  */

    if (amask(AMASK_MVI) == 0) {

        c->put_pixels_clamped = put_pixels_clamped_mvi_asm;

        c->add_pixels_clamped = add_pixels_clamped_mvi_asm;

        if (!high_bit_depth)

            c->get_pixels   = get_pixels_mvi;

        c->diff_pixels      = diff_pixels_mvi;

        c->sad[0]           = pix_abs16x16_mvi_asm;

        c->sad[1]           = pix_abs8x8_mvi;

        c->pix_abs[0][0]    = pix_abs16x16_mvi_asm;

        c->pix_abs[1][0]    = pix_abs8x8_mvi;

        c->pix_abs[0][1]    = pix_abs16x16_x2_mvi;

        c->pix_abs[0][2]    = pix_abs16x16_y2_mvi;

        c->pix_abs[0][3]    = pix_abs16x16_xy2_mvi;

    }

    put_pixels_clamped_axp_p = c->put_pixels_clamped;

    add_pixels_clamped_axp_p = c->add_pixels_clamped;

    if (!avctx->lowres && avctx->bits_per_raw_sample <= 8 &&

        (avctx->idct_algo == FF_IDCT_AUTO ||

         avctx->idct_algo == FF_IDCT_SIMPLEALPHA)) {

        c->idct_put = ff_simple_idct_put_axp;

        c->idct_add = ff_simple_idct_add_axp;

        c->idct =     ff_simple_idct_axp;

    }

}


void WorkerFetchContext::DispatchWillSendRequest(
     unsigned long identifier,
     ResourceRequest& request,
     const ResourceResponse& redirect_response,
    Resource::Type resource_type,
     const FetchInitiatorInfo& initiator_info) {
   probe::willSendRequest(global_scope_, identifier, nullptr, request,
                         redirect_response, initiator_info, resource_type);
 }


static int arcmsr_abort_one_cmd(struct AdapterControlBlock *acb,
		struct CommandControlBlock *ccb)
{
	int rtn;
	rtn = arcmsr_polling_ccbdone(acb, ccb);
	return rtn;
}


CListener* CZNC::FindListener(u_short uPort, const CString& sBindHost,
                              EAddrType eAddr) {
    for (CListener* pListener : m_vpListeners) {
        if (pListener->GetPort() != uPort) continue;
        if (pListener->GetBindHost() != sBindHost) continue;
        if (pListener->GetAddrType() != eAddr) continue;
        return pListener;
    }
    return nullptr;
}


static void PPC_io_writew ( target_phys_addr_t addr , uint32_t value ) {
 if ( ( addr < 0x800001f0 || addr > 0x800001f7 ) && ( addr < 0x80000170 || addr > 0x80000177 ) ) {
 PPC_IO_DPRINTF ( "0x%08x => 0x%04x\n" , addr - PPC_IO_BASE , value ) ;
 }
 # ifdef TARGET_WORDS_BIGENDIAN value = bswap16 ( value ) ;
 # endif cpu_outw ( NULL , addr - PPC_IO_BASE , value ) ;
 }


static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv,
					     int listener)
{
	struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL);

	if (!cma_xprt)
		return NULL;
	svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv);
	INIT_LIST_HEAD(&cma_xprt->sc_accept_q);
	INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q);
 	INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q);
 	INIT_LIST_HEAD(&cma_xprt->sc_frmr_q);
 	INIT_LIST_HEAD(&cma_xprt->sc_ctxts);
	INIT_LIST_HEAD(&cma_xprt->sc_rw_ctxts);
 	init_waitqueue_head(&cma_xprt->sc_send_wait);

 	spin_lock_init(&cma_xprt->sc_lock);
 	spin_lock_init(&cma_xprt->sc_rq_dto_lock);
 	spin_lock_init(&cma_xprt->sc_frmr_q_lock);
 	spin_lock_init(&cma_xprt->sc_ctxt_lock);
	spin_lock_init(&cma_xprt->sc_rw_ctxt_lock);

 	/*
 	 * Note that this implies that the underlying transport support
	 * has some form of congestion control (see RFC 7530 section 3.1
	 * paragraph 2). For now, we assume that all supported RDMA
	 * transports are suitable here.
	 */
	set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags);

	if (listener)
		set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags);

	return cma_xprt;
}


static inline bool cfs_bandwidth_used(void)
{
	return static_key_false(&__cfs_bandwidth_used);
}


bool CSPSourceList::parseHost(const UChar* begin, const UChar* end, String& host, CSPSource::WildcardDisposition& hostWildcard)
{
    ASSERT(begin <= end);
    ASSERT(host.isEmpty());
    ASSERT(hostWildcard == CSPSource::NoWildcard);

    if (begin == end)
        return false;

    const UChar* position = begin;

    if (skipExactly<UChar>(position, end, '*')) {
        hostWildcard = CSPSource::HasWildcard;

        if (position == end)
            return true;

        if (!skipExactly<UChar>(position, end, '.'))
            return false;
    }

    const UChar* hostBegin = position;

    while (position < end) {
        if (!skipExactly<UChar, isHostCharacter>(position, end))
            return false;

        skipWhile<UChar, isHostCharacter>(position, end);

        if (position < end && !skipExactly<UChar>(position, end, '.'))
            return false;
    }

    ASSERT(position == end);
    host = String(hostBegin, end - hostBegin);
    return true;
}


hook_add_to_infolist (struct t_infolist *infolist, const char *arguments)
{
    const char *pos_arguments;
    char *type;
    int i, type_int;

    if (!infolist)
        return 0;

    type = NULL;
    pos_arguments = NULL;

    if (arguments)
    {
        pos_arguments = strchr (arguments, ',');
        if (pos_arguments)
        {
            type = string_strndup (arguments, pos_arguments - arguments);
            pos_arguments++;
        }
        else
            type = strdup (arguments);
    }

    type_int = (type) ? hook_search_type (type) : -1;

    for (i = 0; i < HOOK_NUM_TYPES; i++)
    {
        if ((type_int < 0) || (type_int == i))
            hook_add_to_infolist_type (infolist, i, pos_arguments);
    }

    if (type)
        free (type);

    return 1;
}


static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_iter_t *field)
{
    bool status = true;
    pb_istream_t substream;

    if (!pb_make_string_substream(stream, &substream))
        return false;

    if (field->submsg_desc == NULL)
        PB_RETURN_ERROR(stream, "invalid field descriptor");

    /* New array entries need to be initialized, while required and optional
     * submessages have already been initialized in the top-level pb_decode. */
    if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED ||
        PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
    {
        pb_field_iter_t submsg_iter;
        if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, field->pData))
        {
            if (!pb_message_set_to_defaults(&submsg_iter))
                PB_RETURN_ERROR(stream, "failed to set defaults");
        }
    }

    /* Submessages can have a separate message-level callback that is called
     * before decoding the message. Typically it is used to set callback fields
     * inside oneofs. */
    if (PB_LTYPE(field->type) == PB_LTYPE_SUBMSG_W_CB && field->pSize != NULL)
    {
        /* Message callback is stored right before pSize. */
        pb_callback_t *callback = (pb_callback_t*)field->pSize - 1;
        if (callback->funcs.decode)
        {
            status = callback->funcs.decode(&substream, field, &callback->arg);
        }
    }

    /* Now decode the submessage contents */
    if (status)
    {
        status = pb_decode_inner(&substream, field->submsg_desc, field->pData, 0);
    }

    if (!pb_close_string_substream(stream, &substream))
        return false;

    return status;
}


nl80211_check_scan_flags(struct wiphy *wiphy, struct wireless_dev *wdev,
			 void *request, struct nlattr **attrs,
			 bool is_sched_scan)
{
	u8 *mac_addr, *mac_addr_mask;
	u32 *flags;
	enum nl80211_feature_flags randomness_flag;

	if (!attrs[NL80211_ATTR_SCAN_FLAGS])
		return 0;

	if (is_sched_scan) {
		struct cfg80211_sched_scan_request *req = request;

		randomness_flag = wdev ?
				  NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR :
				  NL80211_FEATURE_ND_RANDOM_MAC_ADDR;
		flags = &req->flags;
		mac_addr = req->mac_addr;
		mac_addr_mask = req->mac_addr_mask;
	} else {
		struct cfg80211_scan_request *req = request;

		randomness_flag = NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR;
		flags = &req->flags;
		mac_addr = req->mac_addr;
		mac_addr_mask = req->mac_addr_mask;
	}

	*flags = nla_get_u32(attrs[NL80211_ATTR_SCAN_FLAGS]);

	if (((*flags & NL80211_SCAN_FLAG_LOW_PRIORITY) &&
	     !(wiphy->features & NL80211_FEATURE_LOW_PRIORITY_SCAN)) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_LOW_SPAN,
				     NL80211_EXT_FEATURE_LOW_SPAN_SCAN) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_LOW_POWER,
				     NL80211_EXT_FEATURE_LOW_POWER_SCAN) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_HIGH_ACCURACY,
				     NL80211_EXT_FEATURE_HIGH_ACCURACY_SCAN) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_FILS_MAX_CHANNEL_TIME,
				     NL80211_EXT_FEATURE_FILS_MAX_CHANNEL_TIME) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_ACCEPT_BCAST_PROBE_RESP,
				     NL80211_EXT_FEATURE_ACCEPT_BCAST_PROBE_RESP) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION,
				     NL80211_EXT_FEATURE_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_OCE_PROBE_REQ_HIGH_TX_RATE,
				     NL80211_EXT_FEATURE_OCE_PROBE_REQ_HIGH_TX_RATE) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_RANDOM_SN,
				     NL80211_EXT_FEATURE_SCAN_RANDOM_SN) ||
	    !nl80211_check_scan_feat(wiphy, *flags,
				     NL80211_SCAN_FLAG_MIN_PREQ_CONTENT,
				     NL80211_EXT_FEATURE_SCAN_MIN_PREQ_CONTENT))
		return -EOPNOTSUPP;

	if (*flags & NL80211_SCAN_FLAG_RANDOM_ADDR) {
		int err;

		if (!(wiphy->features & randomness_flag) ||
		    (wdev && wdev->current_bss))
			return -EOPNOTSUPP;

		err = nl80211_parse_random_mac(attrs, mac_addr, mac_addr_mask);
		if (err)
			return err;
	}

	return 0;
}


bool StyleResolver::affectedByViewportChange() const
{
    for (unsigned i = 0; i < m_viewportDependentMediaQueryResults.size(); ++i) {
        if (m_medium->eval(&m_viewportDependentMediaQueryResults[i]->m_expression) != m_viewportDependentMediaQueryResults[i]->m_result)
            return true;
    }
    return false;
}


static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  Image *image, *image2=NULL,
   *rotated_image;
  PixelPacket *q;

  unsigned int status;
  MATHeader MATLAB_HDR;
  size_t size;
  size_t CellType;
  QuantumInfo *quantum_info;
  ImageInfo *clone_info;
  int i;
  ssize_t ldblk;
  unsigned char *BImgBuff = NULL;
  double MinVal, MaxVal;
  size_t Unknown6;
  unsigned z, z2;
  unsigned Frames;
  int logging;
  int sample_size;
  MagickOffsetType filepos=0x80;
  BlobInfo *blob;
  size_t one;

  unsigned int (*ReadBlobXXXLong)(Image *image);
  unsigned short (*ReadBlobXXXShort)(Image *image);
  void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
  void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);

  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");

  /*
     Open image file.
   */
  quantum_info=(QuantumInfo *) NULL;
  image = AcquireImage(image_info);

  status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
     Read MATLAB image.
   */
  clone_info=(ImageInfo *) NULL;
  if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
    {
      image2=ReadMATImageV4(image_info,image,exception);
      if (image2  == NULL)
        goto MATLAB_KO;
      image=image2;
      goto END_OF_READING;
    }
  MATLAB_HDR.Version = ReadBlobLSBShort(image);
  if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");

  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"  Endian %c%c",
        MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
  if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
  {
    ReadBlobXXXLong = ReadBlobLSBLong;
    ReadBlobXXXShort = ReadBlobLSBShort;
    ReadBlobDoublesXXX = ReadBlobDoublesLSB;
    ReadBlobFloatsXXX = ReadBlobFloatsLSB;
    image->endian = LSBEndian;
  }
  else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
  {
    ReadBlobXXXLong = ReadBlobMSBLong;
    ReadBlobXXXShort = ReadBlobMSBShort;
    ReadBlobDoublesXXX = ReadBlobDoublesMSB;
    ReadBlobFloatsXXX = ReadBlobFloatsMSB;
    image->endian = MSBEndian;
  }
  else
     goto MATLAB_KO;    /* unsupported endian */

   if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");

   filepos = TellBlob(image);
   while(!EOFBlob(image)) /* object parser loop */
  {
    Frames = 1;
    (void) SeekBlob(image,filepos,SEEK_SET);
    /* printf("pos=%X\n",TellBlob(image)); */

    MATLAB_HDR.DataType = ReadBlobXXXLong(image);
    if(EOFBlob(image)) break;
    MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
    if(EOFBlob(image)) break;
    if(MATLAB_HDR.ObjectSize+filepos > GetBlobSize(image))
      goto MATLAB_KO;
    filepos += MATLAB_HDR.ObjectSize + 4 + 4;

    clone_info=CloneImageInfo(image_info);
    image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
    if(MATLAB_HDR.DataType == miCOMPRESSED)
    {
      image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
      if(image2==NULL) continue;
      MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
    }
#endif

    if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */

    MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);

    MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
    MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;

    MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
    if(image!=image2)
      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */
    MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
    MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
    MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);

    switch(MATLAB_HDR.DimFlag)
    {
      case  8: z2=z=1; break;      /* 2D matrix*/
      case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/
           Unknown6 = ReadBlobXXXLong(image2);
           (void) Unknown6;
         if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
         break;
      case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */
         if(z!=3 && z!=1)
           ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
         Frames = ReadBlobXXXLong(image2);
         if (Frames == 0)
           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
         break;
      default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
    }

    MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
    MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);

    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
          "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */
        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */
        MATLAB_HDR.StructureClass != mxINT8_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */
        MATLAB_HDR.StructureClass != mxINT16_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */
        MATLAB_HDR.StructureClass != mxINT32_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */
        MATLAB_HDR.StructureClass != mxINT64_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */
      ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");

    switch (MATLAB_HDR.NameFlag)
    {
      case 0:
        size = ReadBlobXXXLong(image2);  /* Object name string size */
        size = 4 * (ssize_t) ((size + 3 + 1) / 4);
        (void) SeekBlob(image2, size, SEEK_CUR);
        break;
      case 1:
      case 2:
      case 3:
      case 4:
        (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
        break;
      default:
        goto MATLAB_KO;
    }

    CellType = ReadBlobXXXLong(image2);    /* Additional object type */
    if (logging)
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        "MATLAB_HDR.CellType: %.20g",(double) CellType);

    (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */

NEXT_FRAME:
    switch (CellType)
    {
      case miINT8:
      case miUINT8:
        sample_size = 8;
        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
          image->depth = 1;
        else
          image->depth = 8;         /* Byte type cell */
        ldblk = (ssize_t) MATLAB_HDR.SizeX;
        break;
      case miINT16:
      case miUINT16:
        sample_size = 16;
        image->depth = 16;        /* Word type cell */
        ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
        break;
      case miINT32:
      case miUINT32:
        sample_size = 32;
        image->depth = 32;        /* Dword type cell */
        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
        break;
      case miINT64:
      case miUINT64:
        sample_size = 64;
        image->depth = 64;        /* Qword type cell */
        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
        break;
      case miSINGLE:
        sample_size = 32;
        image->depth = 32;        /* double type cell */
        (void) SetImageOption(clone_info,"quantum:format","floating-point");
        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
  {              /* complex float type cell */
  }
        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
        break;
      case miDOUBLE:
        sample_size = 64;
        image->depth = 64;        /* double type cell */
        (void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
        if (sizeof(double) != 8)
RestoreMSCWarning
          ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
  {                         /* complex double type cell */
  }
        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
        break;
      default:
        ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
    }
    (void) sample_size;
    image->columns = MATLAB_HDR.SizeX;
    image->rows = MATLAB_HDR.SizeY;
    one=1;
    image->colors = one << image->depth;
    if (image->columns == 0 || image->rows == 0)
      goto MATLAB_KO;
    if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
      goto MATLAB_KO;
      /* Image is gray when no complex flag is set and 2D Matrix */
    if ((MATLAB_HDR.DimFlag == 8) &&
        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
      {
        SetImageColorspace(image,GRAYColorspace);
        image->type=GrayscaleType;
      }

    /*
      If ping is true, then only set image size and colors without
      reading any image data.
    */
    if (image_info->ping)
    {
      size_t temp = image->columns;
      image->columns = image->rows;
      image->rows = temp;
      goto done_reading; /* !!!!!! BAD  !!!! */
    }
    status=SetImageExtent(image,image->columns,image->rows);
    if (status == MagickFalse)
      {
        InheritException(exception,&image->exception);
        return(DestroyImageList(image));
      }
    quantum_info=AcquireQuantumInfo(clone_info,image);
    if (quantum_info == (QuantumInfo *) NULL)
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");

  /* ----- Load raster data ----- */
    BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */
    if (BImgBuff == NULL)
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double));

    MinVal = 0;
    MaxVal = 0;
    if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */
    {
      CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
    }

    /* Main loop for reading all scanlines */
    if(z==1) z=0; /* read grey scanlines */
    /* else read color scanlines */
    do
    {
      for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
      {
        q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
        if (q == (PixelPacket *) NULL)
  {
    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
              "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
    goto done_reading;    /* Skip image rotation, when cannot set image pixels    */
  }
        if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
  {
    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
             "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
    goto ExitLoop;
  }
        if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
        {
          FixLogical((unsigned char *)BImgBuff,ldblk);
          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
    {
ImportQuantumPixelsFailed:
      if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
              "  MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
      break;
    }
        }
        else
        {
          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
      goto ImportQuantumPixelsFailed;

          if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */
          (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
      FixSignedValues(q,MATLAB_HDR.SizeX);
        }

        if (!SyncAuthenticPixels(image,exception))
  {
    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
            "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
    goto ExitLoop;
  }
      }
    } while(z-- >= 2);
ExitLoop:

    /* Read complex part of numbers here */
    if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
    {        /* Find Min and Max Values for complex parts of floats */
      CellType = ReadBlobXXXLong(image2);    /* Additional object type */
      i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/

      if (CellType==miDOUBLE || CellType==miSINGLE)
      {
        CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
      }

      if (CellType==miDOUBLE)
        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
  {
          ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
          InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
  }

      if (CellType==miSINGLE)
        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
  {
          ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
          InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
  }
    }

      /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
    if ((MATLAB_HDR.DimFlag == 8) &&
        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
      image->type=GrayscaleType;
    if (image->depth == 1)
      image->type=BilevelType;

    if(image2==image)
        image2 = NULL;    /* Remove shadow copy to an image before rotation. */

      /*  Rotate image. */
    rotated_image = RotateImage(image, 90.0, exception);
    if (rotated_image != (Image *) NULL)
    {
        /* Remove page offsets added by RotateImage */
      rotated_image->page.x=0;
      rotated_image->page.y=0;

      blob = rotated_image->blob;
      rotated_image->blob = image->blob;
      rotated_image->colors = image->colors;
      image->blob = blob;
      AppendImageToList(&image,rotated_image);
      DeleteImageFromList(&image);
    }

done_reading:

    if(image2!=NULL)
      if(image2!=image)
      {
        DeleteImageFromList(&image2);
  if(clone_info)
  {
          if(clone_info->file)
    {
            fclose(clone_info->file);
            clone_info->file = NULL;
            (void) remove_utf8(clone_info->filename);
    }
        }
      }

      /* Allocate next image structure. */
    AcquireNextImage(image_info,image);
    if (image->next == (Image *) NULL) break;
    image=SyncNextImageInList(image);
    image->columns=image->rows=0;
    image->colors=0;

      /* row scan buffer is no longer needed */
    RelinquishMagickMemory(BImgBuff);
    BImgBuff = NULL;

    if(--Frames>0)
    {
      z = z2;
      if(image2==NULL) image2 = image;
      goto NEXT_FRAME;
    }

    if(image2!=NULL)
      if(image2!=image)   /* Does shadow temporary decompressed image exist? */
      {
/*  CloseBlob(image2); */
        DeleteImageFromList(&image2);
        if(clone_info)
        {
          if(clone_info->file)
          {
            fclose(clone_info->file);
            clone_info->file = NULL;
            (void) unlink(clone_info->filename);
          }
         }
       }
  }

  RelinquishMagickMemory(BImgBuff);
  if (quantum_info != (QuantumInfo *) NULL)
    quantum_info=DestroyQuantumInfo(quantum_info);
END_OF_READING:
  if (clone_info)
    clone_info=DestroyImageInfo(clone_info);
  CloseBlob(image);

  {
    Image *p;
    ssize_t scene=0;

    /*
      Rewind list, removing any empty images while rewinding.
    */
    p=image;
    image=NULL;
    while (p != (Image *) NULL)
      {
        Image *tmp=p;
        if ((p->rows == 0) || (p->columns == 0)) {
          p=p->previous;
          DeleteImageFromList(&tmp);
        } else {
          image=p;
          p=p->previous;
        }
      }

    /*
      Fix scene numbers
    */
    for (p=image; p != (Image *) NULL; p=p->next)
      p->scene=scene++;
  }

  if(clone_info != NULL)  /* cleanup garbage file from compression */
  {
    if(clone_info->file)
    {
      fclose(clone_info->file);
      clone_info->file = NULL;
      (void) remove_utf8(clone_info->filename);
    }
    DestroyImageInfo(clone_info);
    clone_info = NULL;
  }
  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
  if(image==NULL)
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  return (image);
}


static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
		      struct ctx_rq_wait *wait)
{
	struct kioctx_table *table;

	spin_lock(&mm->ioctx_lock);
	if (atomic_xchg(&ctx->dead, 1)) {
		spin_unlock(&mm->ioctx_lock);
		return -EINVAL;
	}

	table = rcu_dereference_raw(mm->ioctx_table);
	WARN_ON(ctx != table->table[ctx->id]);
	table->table[ctx->id] = NULL;
	spin_unlock(&mm->ioctx_lock);

	/* percpu_ref_kill() will do the necessary call_rcu() */
	wake_up_all(&ctx->wait);

	/*
	 * It'd be more correct to do this in free_ioctx(), after all
	 * the outstanding kiocbs have finished - but by then io_destroy
	 * has already returned, so io_setup() could potentially return
	 * -EAGAIN with no ioctxs actually in use (as far as userspace
	 *  could tell).
	 */
	aio_nr_sub(ctx->max_reqs);

	if (ctx->mmap_size)
		vm_munmap(ctx->mmap_base, ctx->mmap_size);

	ctx->rq_wait = wait;
	percpu_ref_kill(&ctx->users);
	return 0;
}


update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
{
	unsigned long removed_load = 0, removed_util = 0, removed_runnable_sum = 0;
	struct sched_avg *sa = &cfs_rq->avg;
	int decayed = 0;

	if (cfs_rq->removed.nr) {
		unsigned long r;
		u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;

		raw_spin_lock(&cfs_rq->removed.lock);
		swap(cfs_rq->removed.util_avg, removed_util);
		swap(cfs_rq->removed.load_avg, removed_load);
		swap(cfs_rq->removed.runnable_sum, removed_runnable_sum);
		cfs_rq->removed.nr = 0;
		raw_spin_unlock(&cfs_rq->removed.lock);

		r = removed_load;
		sub_positive(&sa->load_avg, r);
		sub_positive(&sa->load_sum, r * divider);

		r = removed_util;
		sub_positive(&sa->util_avg, r);
		sub_positive(&sa->util_sum, r * divider);

		add_tg_cfs_propagate(cfs_rq, -(long)removed_runnable_sum);

		decayed = 1;
	}

	decayed |= __update_load_avg_cfs_rq(now, cpu_of(rq_of(cfs_rq)), cfs_rq);

#ifndef CONFIG_64BIT
	smp_wmb();
	cfs_rq->load_last_update_time_copy = sa->last_update_time;
#endif

	if (decayed)
		cfs_rq_util_change(cfs_rq, 0);

	return decayed;
}


views::View* ProfileChooserView::CreateGuestProfileView() {
  gfx::Image guest_icon =
      ui::ResourceBundle::GetSharedInstance().GetImageNamed(
          profiles::GetPlaceholderAvatarIconResourceID());
  AvatarMenu::Item guest_avatar_item(0, base::FilePath(), guest_icon);
  guest_avatar_item.active = true;
  guest_avatar_item.name = l10n_util::GetStringUTF16(
      IDS_PROFILES_GUEST_PROFILE_NAME);
  guest_avatar_item.signed_in = false;

  return CreateCurrentProfileView(guest_avatar_item, true);
}


  Message(PassRefPtr<BlobDataHandle> blobDataHandle)
      : type(MessageTypeBlob), blobDataHandle(blobDataHandle) {}


void PDFiumEngine::OnTouchTimerCallback(int id) {
  if (!touch_timers_.count(id))
    return;

  HandleLongPress(touch_timers_[id]);
  KillTouchTimer(id);
}


cmsUInt32Number uipow(cmsUInt32Number n, cmsUInt32Number a, cmsUInt32Number b)
{
    cmsUInt32Number rv = 1, rc;

    if (a == 0) return 0;
    if (n == 0) return 0;

    for (; b > 0; b--) {

        rv *= a;

        // Check for overflow
        if (rv > UINT_MAX / a) return (cmsUInt32Number) -1;

    }

    rc = rv * n;

    if (rv != rc / n) return (cmsUInt32Number) -1;
    return rc;
}


static void detach_task(struct task_struct *p, struct lb_env *env)
{
	lockdep_assert_held(&env->src_rq->lock);

	deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
	set_task_cpu(p, env->dst_cpu);
}


XMLNode::property(const string& name) const
{
	XMLPropertyConstIterator iter = _proplist.begin();

	while (iter != _proplist.end()) {
		if ((*iter)->name() == name) {
			return *iter;
		}
		++iter;
	}
	return 0;
}


data_sock_release(struct socket *sock)
{
	struct sock *sk = sock->sk;

	if (*debug & DEBUG_SOCKET)
		printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk);
	if (!sk)
		return 0;
	switch (sk->sk_protocol) {
	case ISDN_P_TE_S0:
	case ISDN_P_NT_S0:
	case ISDN_P_TE_E1:
	case ISDN_P_NT_E1:
		if (sk->sk_state == MISDN_BOUND)
			delete_channel(&_pms(sk)->ch);
		else
			mISDN_sock_unlink(&data_sockets, sk);
		break;
	case ISDN_P_LAPD_TE:
	case ISDN_P_LAPD_NT:
	case ISDN_P_B_RAW:
	case ISDN_P_B_HDLC:
	case ISDN_P_B_X75SLP:
	case ISDN_P_B_L2DTMF:
	case ISDN_P_B_L2DSP:
	case ISDN_P_B_L2DSPHDLC:
		delete_channel(&_pms(sk)->ch);
		mISDN_sock_unlink(&data_sockets, sk);
		break;
	}

	lock_sock(sk);

	sock_orphan(sk);
	skb_queue_purge(&sk->sk_receive_queue);

	release_sock(sk);
	sock_put(sk);

	return 0;
}


struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,
						 struct btrfs_path *path,
						 const char *name, int name_len)
{
	struct btrfs_dir_item *dir_item;
	unsigned long name_ptr;
	u32 total_len;
	u32 cur = 0;
	u32 this_len;
	struct extent_buffer *leaf;

	leaf = path->nodes[0];
	dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
	if (verify_dir_item(root, leaf, dir_item))
		return NULL;

	total_len = btrfs_item_size_nr(leaf, path->slots[0]);
	while (cur < total_len) {
		this_len = sizeof(*dir_item) +
			btrfs_dir_name_len(leaf, dir_item) +
			btrfs_dir_data_len(leaf, dir_item);
		name_ptr = (unsigned long)(dir_item + 1);

		if (btrfs_dir_name_len(leaf, dir_item) == name_len &&
		    memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0)
			return dir_item;

		cur += this_len;
		dir_item = (struct btrfs_dir_item *)((char *)dir_item +
						     this_len);
	}
	return NULL;
}


static void set_default_ppflags(vp8_postproc_cfg_t *cfg) {
  cfg->post_proc_flag = VP8_DEBLOCK | VP8_DEMACROBLOCK;
  cfg->deblocking_level = 4;
  cfg->noise_level = 0;
}


void MediaControlTimelineElement::defaultEventHandler(Event* event) {
  if (event->isMouseEvent() &&
      toMouseEvent(event)->button() !=
          static_cast<short>(WebPointerProperties::Button::Left))
    return;

  if (!isConnected() || !document().isActive())
    return;

  if (event->type() == EventTypeNames::mousedown) {
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.ScrubbingBegin"));
    mediaControls().beginScrubbing();
  }

  if (event->type() == EventTypeNames::mouseup) {
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.ScrubbingEnd"));
    mediaControls().endScrubbing();
  }

   MediaControlInputElement::defaultEventHandler(event);

  if (event->type() != EventTypeNames::input)
     return;

   double time = value().toDouble();

  // FIXME: This will need to take the timeline offset into consideration
  // once that concept is supported, see https://crbug.com/312699
  if (mediaElement().seekable()->contain(time))
    mediaElement().setCurrentTime(time);

   LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject()));
   if (!slider.isNull() && slider.inDragMode())
    mediaControls().updateCurrentTimeDisplay();
}