void FileAPIMessageFilter::OnOpenFile(
    int request_id, const GURL& path, int file_flags) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  base::PlatformFileError error;
  const int open_permissions = base::PLATFORM_FILE_OPEN |
                               (file_flags & kOpenFilePermissions);
  FileSystemURL url(path);
  if (!HasPermissionsForFile(url, open_permissions, &error)) {
    Send(new FileSystemMsg_DidFail(request_id, error));
    return;
  }

  FileSystemOperation* operation = GetNewOperation(url, request_id);
  if (!operation)
    return;
  operation->OpenFile(
      url, file_flags, peer_handle(),
      base::Bind(&FileAPIMessageFilter::DidOpenFile, this, request_id, path));
}


  bool UpdateAndCheckUniqueness(v8::Local<v8::Object> handle) {
    typedef HashToHandleMap::const_iterator Iterator;
    int hash = avoid_identity_hash_for_testing_ ? 0 : handle->GetIdentityHash();
    std::pair<Iterator, Iterator> range = unique_map_.equal_range(hash);
    for (Iterator it = range.first; it != range.second; ++it) {
      if (it->second == handle)
        return false;
    }
    unique_map_.insert(std::make_pair(hash, handle));
    return true;
  }


TfLiteStatus EvalMean(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0);
  const TfLiteEvalTensor* axis = tflite::micro::GetEvalInput(context, node, 1);
  TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, 0);
  TfLiteReducerParams* params =
      reinterpret_cast<TfLiteReducerParams*>(node->builtin_data);
  OpData* op_data = reinterpret_cast<OpData*>(node->user_data);

  int num_axis = static_cast<int>(ElementCount(*axis->dims));
  int temp_index[kMaxNumberOfAxis];
  int resolved_axis[kMaxNumberOfReducedAxis];

  tflite::MeanParams op_params;
  ResolveAxis(tflite::micro::GetTensorData<int>(axis), num_axis, &op_params);
  // TODO(b/146571391): Support only 4D Input and 2D Axis for Mean until
  // scratch tensor allocation has been implemented in (b/132070898)
  bool is_valid_inputs = (input->dims->size == 4 && op_params.axis_count == 2 &&
                          ((op_params.axis[0] == 1 && op_params.axis[1] == 2) ||
                           (op_params.axis[0] == 2 && op_params.axis[1] == 1)));
  TF_LITE_ENSURE_MSG(
      context, is_valid_inputs == true,
      "Number of Input "
      "dimensions != 4 OR the Axis is not either [1, 2] or [2, 1]");
  switch (input->type) {
    case kTfLiteFloat32: {
      // TODO(b/139102329): Handle the below special case in the combined
      // reference method.
      // Defer to specialized implementation for 4D Mean across axes 1 & 2.
      if (params->keep_dims) {
        reference_ops::Mean(op_params, tflite::micro::GetTensorShape(input),
                            tflite::micro::GetTensorData<float>(input),
                            tflite::micro::GetTensorShape(output),
                            tflite::micro::GetTensorData<float>(output));
      } else {
        TF_LITE_ENSURE(
            context,
            reference_ops::Mean(
                tflite::micro::GetTensorData<float>(input), input->dims->data,
                input->dims->size, tflite::micro::GetTensorData<float>(output),
                output->dims->data, output->dims->size,
                tflite::micro::GetTensorData<int>(axis), num_axis,
                params->keep_dims, temp_index, resolved_axis,
                tflite::micro::GetTensorData<float>(output)));
      }
    } break;
    case kTfLiteInt8: {
      if (params->keep_dims) {
        reference_integer_ops::Mean(
            op_params, op_data->multiplier, op_data->shift,
            tflite::micro::GetTensorShape(input),
            tflite::micro::GetTensorData<int8_t>(input), op_data->input_zp,
            tflite::micro::GetTensorShape(output),
            tflite::micro::GetTensorData<int8_t>(output), op_data->output_zp);
      } else if (op_data->input_zp == op_data->output_zp &&
                 op_data->input_scale == op_data->output_scale) {
        int32_t* temp_buffer = static_cast<int32_t*>(
            context->GetScratchBuffer(context, op_data->temp_buffer_idx));
        TF_LITE_ENSURE(
            context,
            reference_ops::Mean(
                tflite::micro::GetTensorData<int8_t>(input), input->dims->data,
                input->dims->size, tflite::micro::GetTensorData<int8_t>(output),
                output->dims->data, output->dims->size,
                tflite::micro::GetTensorData<int>(axis), num_axis,
                params->keep_dims, temp_index, resolved_axis, temp_buffer));
      } else {
        int32_t* temp_buffer = static_cast<int32_t*>(
            context->GetScratchBuffer(context, op_data->temp_buffer_idx));
        TF_LITE_ENSURE(
            context,
            reference_ops::QuantizedMeanOrSum(
                tflite::micro::GetTensorData<int8_t>(input), op_data->input_zp,
                op_data->input_scale, input->dims->data, input->dims->size,
                tflite::micro::GetTensorData<int8_t>(output),
                op_data->output_zp, op_data->output_scale, output->dims->data,
                output->dims->size, tflite::micro::GetTensorData<int>(axis),
                num_axis, params->keep_dims, temp_index, resolved_axis,
                temp_buffer, false));
      }
    } break;
    case kTfLiteUInt8: {
      if (params->keep_dims) {
        reference_ops::Mean(op_params, tflite::micro::GetTensorShape(input),
                            tflite::micro::GetTensorData<uint8_t>(input),
                            op_data->input_zp, op_data->input_scale,
                            tflite::micro::GetTensorShape(output),
                            tflite::micro::GetTensorData<uint8_t>(output),
                            op_data->output_zp, op_data->output_scale);
      } else if (op_data->input_zp == op_data->output_zp &&
                 op_data->input_scale == op_data->output_scale) {
        uint32_t* temp_buffer = static_cast<uint32_t*>(
            context->GetScratchBuffer(context, op_data->temp_buffer_idx));
        TF_LITE_ENSURE(
            context,
            reference_ops::Mean(tflite::micro::GetTensorData<uint8_t>(input),
                                input->dims->data, input->dims->size,
                                tflite::micro::GetTensorData<uint8_t>(output),
                                output->dims->data, output->dims->size,
                                tflite::micro::GetTensorData<int>(axis),
                                num_axis, params->keep_dims, temp_index,
                                resolved_axis, temp_buffer));
      } else {
        uint32_t* temp_buffer = static_cast<uint32_t*>(
            context->GetScratchBuffer(context, op_data->temp_buffer_idx));
        TF_LITE_ENSURE(
            context,
            reference_ops::QuantizedMeanOrSum(
                tflite::micro::GetTensorData<uint8_t>(input), op_data->input_zp,
                op_data->input_scale, input->dims->data, input->dims->size,
                tflite::micro::GetTensorData<uint8_t>(output),
                op_data->output_zp, op_data->output_scale, output->dims->data,
                output->dims->size, tflite::micro::GetTensorData<int>(axis),
                num_axis, params->keep_dims, temp_index, resolved_axis,
                temp_buffer, false));
      }
    } break;
    default:
      // TODO(b/144955155): Support uint8_t(b/144955155) and int8_t(b/144955018)
      TF_LITE_ENSURE_MSG(context, false,
                         "Currently, only float32, int8 or uint8 input type "
                         "is supported.");
  }
  return kTfLiteOk;
}


static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress TSRMLS_DC) /* {{{ */
{
	php_session_initialize(TSRMLS_C);
	PS(session_status) = php_session_active;
	IF_SESSION_VARS() {
		zend_hash_del(Z_ARRVAL_P(PS(http_session_vars)), progress->key.c, progress->key.len+1);
	}
	php_session_flush(TSRMLS_C);
} /* }}} */


    //! Convert pixel values from RGB to YCbCr color spaces.
    CImg<T>& YCbCrtoRGB() {
      if (_spectrum!=3)
        throw CImgInstanceException(_cimg_instance
                                    "YCbCrtoRGB(): Instance is not a YCbCr image.",
                                    cimg_instance);

      T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2);
      const longT whd = (longT)width()*height()*depth();
      cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,512))
      for (longT N = 0; N<whd; ++N) {
        const Tfloat
          Y = (Tfloat)p1[N] - 16,
          Cb = (Tfloat)p2[N] - 128,
          Cr = (Tfloat)p3[N] - 128,
          R = (298*Y + 409*Cr + 128)/256,
          G = (298*Y - 100*Cb - 208*Cr + 128)/256,
          B = (298*Y + 516*Cb + 128)/256;
        p1[N] = (T)cimg::cut(R,0,255),
        p2[N] = (T)cimg::cut(G,0,255),
        p3[N] = (T)cimg::cut(B,0,255);
      }
      return *this;


bool JSTestInterfaceOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)
{
    JSTestInterface* jsTestInterface = jsCast<JSTestInterface*>(handle.get().asCell());
    if (jsTestInterface->impl()->hasPendingActivity())
        return true;
    if (!isObservable(jsTestInterface))
        return false;
    UNUSED_PARAM(visitor);
    return false;
}


int snd_seq_port_disconnect(struct snd_seq_client *connector,
			    struct snd_seq_client *src_client,
			    struct snd_seq_client_port *src_port,
			    struct snd_seq_client *dest_client,
			    struct snd_seq_client_port *dest_port,
			    struct snd_seq_port_subscribe *info)
{
	struct snd_seq_port_subs_info *src = &src_port->c_src;
	struct snd_seq_subscribers *subs;
	int err = -ENOENT;

	down_write(&src->list_mutex);
	/* look for the connection */
	list_for_each_entry(subs, &src->list_head, src_list) {
		if (match_subs_info(info, &subs->info)) {
			atomic_dec(&subs->ref_count); /* mark as not ready */
			err = 0;
			break;
		}
	}
	up_write(&src->list_mutex);
	if (err < 0)
		return err;

	delete_and_unsubscribe_port(src_client, src_port, subs, true,
				    connector->number != src_client->number);
	delete_and_unsubscribe_port(dest_client, dest_port, subs, false,
				    connector->number != dest_client->number);
	kfree(subs);
	return 0;
}


void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
{
	__this_cpu_write(current_vcpu, vcpu);
}


static int dissect_h245_SET_SIZE_1_256_OF_TerminalLabel ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_set_of ( tvb , offset , actx , tree , hf_index , ett_h245_SET_SIZE_1_256_OF_TerminalLabel , SET_SIZE_1_256_OF_TerminalLabel_set_of , 1 , 256 , FALSE ) ;
 return offset ;
 }


UrlData::UrlData(const GURL& url, CORSMode cors_mode, UrlIndex* url_index)
    : url_(url),
      have_data_origin_(false),
      cors_mode_(cors_mode),
      url_index_(url_index),
       length_(kPositionNotSpecified),
       range_supported_(false),
       cacheable_(false),
       last_used_(),
       multibuffer_(this, url_index_->block_shift_) {}


static void test_decode ( struct stream_state * stream , enum TestDecodeFatality fatal , const VpxInterface * codec ) {
 vpx_image_t enc_img , dec_img ;
 if ( stream -> mismatch_seen ) return ;
 if ( strcmp ( codec -> name , "vp8" ) == 0 ) {
 struct vpx_ref_frame ref_enc , ref_dec ;
 int width , height ;
 width = ( stream -> config . cfg . g_w + 15 ) & ~ 15 ;
 height = ( stream -> config . cfg . g_h + 15 ) & ~ 15 ;
 vpx_img_alloc ( & ref_enc . img , VPX_IMG_FMT_I420 , width , height , 1 ) ;
 enc_img = ref_enc . img ;
 vpx_img_alloc ( & ref_dec . img , VPX_IMG_FMT_I420 , width , height , 1 ) ;
 dec_img = ref_dec . img ;
 ref_enc . frame_type = VP8_LAST_FRAME ;
 ref_dec . frame_type = VP8_LAST_FRAME ;
 vpx_codec_control ( & stream -> encoder , VP8_COPY_REFERENCE , & ref_enc ) ;
 vpx_codec_control ( & stream -> decoder , VP8_COPY_REFERENCE , & ref_dec ) ;
 }
 else {
 struct vp9_ref_frame ref_enc , ref_dec ;
 ref_enc . idx = 0 ;
 ref_dec . idx = 0 ;
 vpx_codec_control ( & stream -> encoder , VP9_GET_REFERENCE , & ref_enc ) ;
 enc_img = ref_enc . img ;
 vpx_codec_control ( & stream -> decoder , VP9_GET_REFERENCE , & ref_dec ) ;
 dec_img = ref_dec . img ;
 # if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH if ( ( enc_img . fmt & VPX_IMG_FMT_HIGHBITDEPTH ) != ( dec_img . fmt & VPX_IMG_FMT_HIGHBITDEPTH ) ) {
 if ( enc_img . fmt & VPX_IMG_FMT_HIGHBITDEPTH ) {
 vpx_img_alloc ( & enc_img , enc_img . fmt - VPX_IMG_FMT_HIGHBITDEPTH , enc_img . d_w , enc_img . d_h , 16 ) ;
 img_cast_16_to_8 ( & enc_img , & ref_enc . img ) ;
 }
 if ( dec_img . fmt & VPX_IMG_FMT_HIGHBITDEPTH ) {
 vpx_img_alloc ( & dec_img , dec_img . fmt - VPX_IMG_FMT_HIGHBITDEPTH , dec_img . d_w , dec_img . d_h , 16 ) ;
 img_cast_16_to_8 ( & dec_img , & ref_dec . img ) ;
 }
 }
 # endif }
 ctx_exit_on_error ( & stream -> encoder , "Failed to get encoder reference frame" ) ;
 ctx_exit_on_error ( & stream -> decoder , "Failed to get decoder reference frame" ) ;
 if ( ! compare_img ( & enc_img , & dec_img ) ) {
 int y [ 4 ] , u [ 4 ] , v [ 4 ] ;
 # if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH if ( enc_img . fmt & VPX_IMG_FMT_HIGHBITDEPTH ) {
 find_mismatch_high ( & enc_img , & dec_img , y , u , v ) ;
 }
 else {
 find_mismatch ( & enc_img , & dec_img , y , u , v ) ;
 }
 # else find_mismatch ( & enc_img , & dec_img , y , u , v ) ;
 # endif stream -> decoder . err = 1 ;
 warn_or_exit_on_error ( & stream -> decoder , fatal == TEST_DECODE_FATAL , "Stream %d: Encode/decode mismatch on frame %d at" " Y[%d, %d] {
%d/%d}
," " U[%d, %d] {
%d/%d}
," " V[%d, %d] {
%d/%d}
" , stream -> index , stream -> frames_out , y [ 0 ] , y [ 1 ] , y [ 2 ] , y [ 3 ] , u [ 0 ] , u [ 1 ] , u [ 2 ] , u [ 3 ] , v [ 0 ] , v [ 1 ] , v [ 2 ] , v [ 3 ] ) ;
 stream -> mismatch_seen = stream -> frames_out ;
 }
 vpx_img_free ( & enc_img ) ;
 vpx_img_free ( & dec_img ) ;
 }


void RenderView::OnPluginImeCompositionCompleted(const string16& text,
                                                 int plugin_id) {
  std::set<WebPluginDelegateProxy*>::iterator plugin_it;
  for (plugin_it = plugin_delegates_.begin();
       plugin_it != plugin_delegates_.end(); ++plugin_it) {
    (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
  }
}


error::Error GLES2DecoderPassthroughImpl::DoGetFramebufferAttachmentParameteriv(
    GLenum target,
    GLenum attachment,
    GLenum pname,
    GLsizei bufsize,
    GLsizei* length,
    GLint* params) {
  GLenum updated_attachment = attachment;
  if (IsEmulatedFramebufferBound(target)) {
    if (!ModifyAttachmentForEmulatedFramebuffer(&updated_attachment)) {
      InsertError(GL_INVALID_OPERATION, "Invalid attachment.");
      *length = 0;
      return error::kNoError;
    }

    switch (pname) {
      case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
      case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
      case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
      case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER:
        InsertError(GL_INVALID_ENUM, "Invalid parameter name.");
        *length = 0;
        return error::kNoError;
    }
  }

  CheckErrorCallbackState();

  GLint* scratch_params = GetTypedScratchMemory<GLint>(bufsize);
  api()->glGetFramebufferAttachmentParameterivRobustANGLEFn(
      target, updated_attachment, pname, bufsize, length, scratch_params);

  if (CheckErrorCallbackState()) {
    DCHECK(*length == 0);
    return error::kNoError;
  }

  error::Error error = PatchGetFramebufferAttachmentParameter(
      target, updated_attachment, pname, *length, scratch_params);
  if (error != error::kNoError) {
    *length = 0;
    return error;
  }

  DCHECK(*length < bufsize);
  std::copy(scratch_params, scratch_params + *length, params);

  return error::kNoError;
}


static hb_bool_t _try_make_writable_inplace_unix ( hb_blob_t * blob ) {
 # if defined ( HAVE_SYS_MMAN_H ) && defined ( HAVE_MPROTECT ) uintptr_t pagesize = - 1 , mask , length ;
 const char * addr ;
 # if defined ( HAVE_SYSCONF ) && defined ( _SC_PAGE_SIZE ) pagesize = ( uintptr_t ) sysconf ( _SC_PAGE_SIZE ) ;
 # elif defined ( HAVE_SYSCONF ) && defined ( _SC_PAGESIZE ) pagesize = ( uintptr_t ) sysconf ( _SC_PAGESIZE ) ;
 # elif defined ( HAVE_GETPAGESIZE ) pagesize = ( uintptr_t ) getpagesize ( ) ;
 # endif if ( ( uintptr_t ) - 1L == pagesize ) {
 DEBUG_MSG_FUNC ( BLOB , blob , "failed to get pagesize: %s" , strerror ( errno ) ) ;
 return false ;
 }
 DEBUG_MSG_FUNC ( BLOB , blob , "pagesize is %lu" , ( unsigned long ) pagesize ) ;
 mask = ~ ( pagesize - 1 ) ;
 addr = ( const char * ) ( ( ( uintptr_t ) blob -> data ) & mask ) ;
 length = ( const char * ) ( ( ( uintptr_t ) blob -> data + blob -> length + pagesize - 1 ) & mask ) - addr ;
 DEBUG_MSG_FUNC ( BLOB , blob , "calling mprotect on [%p..%p] (%lu bytes)" , addr , addr + length , ( unsigned long ) length ) ;
 if ( - 1 == mprotect ( ( void * ) addr , length , PROT_READ | PROT_WRITE ) ) {
 DEBUG_MSG_FUNC ( BLOB , blob , "mprotect failed: %s" , strerror ( errno ) ) ;
 return false ;
 }
 blob -> mode = HB_MEMORY_MODE_WRITABLE ;
 DEBUG_MSG_FUNC ( BLOB , blob , "successfully made [%p..%p] (%lu bytes) writable\n" , addr , addr + length , ( unsigned long ) length ) ;
 return true ;
 # else return false ;
 # endif }


static inline int parse_nal_units(AVCodecParserContext *s,

                                  AVCodecContext *avctx,

                                  const uint8_t * const buf, int buf_size)

{

    H264ParseContext *p = s->priv_data;

    H2645NAL nal = { NULL };

    int buf_index, next_avc;

    unsigned int pps_id;

    unsigned int slice_type;

    int state = -1, got_reset = 0;

    int q264 = buf_size >=4 && !memcmp("Q264", buf, 4);

    int field_poc[2];

    int ret;

    /* set some sane default values */

    s->pict_type         = AV_PICTURE_TYPE_I;

    s->key_frame         = 0;

    s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;

    ff_h264_sei_uninit(&p->sei);

    p->sei.frame_packing.frame_packing_arrangement_cancel_flag = -1;

    if (!buf_size)

        return 0;

    buf_index     = 0;

    next_avc      = p->is_avc ? 0 : buf_size;

    for (;;) {

        const SPS *sps;

        int src_length, consumed, nalsize = 0;

        if (buf_index >= next_avc) {

            nalsize = get_nalsize(p->nal_length_size, buf, buf_size, &buf_index, avctx);

            if (nalsize < 0)

                break;

            next_avc = buf_index + nalsize;

        } else {

            buf_index = find_start_code(buf, buf_size, buf_index, next_avc);

            if (buf_index >= buf_size)

                break;

            if (buf_index >= next_avc)

                continue;

        }

        src_length = next_avc - buf_index;

        state = buf[buf_index];

        switch (state & 0x1f) {

        case H264_NAL_SLICE:

        case H264_NAL_IDR_SLICE:

            // Do not walk the whole buffer just to decode slice header

            if ((state & 0x1f) == H264_NAL_IDR_SLICE || ((state >> 5) & 0x3) == 0) {

                /* IDR or disposable slice

                 * No need to decode many bytes because MMCOs shall not be present. */

                if (src_length > 60)

                    src_length = 60;

            } else {

                /* To decode up to MMCOs */

                if (src_length > 1000)

                    src_length = 1000;

            }

            break;

        }

        consumed = ff_h2645_extract_rbsp(buf + buf_index, src_length, &nal, 1);

        if (consumed < 0)

            break;

        buf_index += consumed;

        ret = init_get_bits8(&nal.gb, nal.data, nal.size);

        if (ret < 0)

            goto fail;

        get_bits1(&nal.gb);

        nal.ref_idc = get_bits(&nal.gb, 2);

        nal.type    = get_bits(&nal.gb, 5);

        switch (nal.type) {

        case H264_NAL_SPS:

            ff_h264_decode_seq_parameter_set(&nal.gb, avctx, &p->ps, 0);

            break;

        case H264_NAL_PPS:

            ff_h264_decode_picture_parameter_set(&nal.gb, avctx, &p->ps,

                                                 nal.size_bits);

            break;

        case H264_NAL_SEI:

            ff_h264_sei_decode(&p->sei, &nal.gb, &p->ps, avctx);

            break;

        case H264_NAL_IDR_SLICE:

            s->key_frame = 1;

            p->poc.prev_frame_num        = 0;

            p->poc.prev_frame_num_offset = 0;

            p->poc.prev_poc_msb          =

            p->poc.prev_poc_lsb          = 0;

        /* fall through */

        case H264_NAL_SLICE:

            get_ue_golomb_long(&nal.gb);  // skip first_mb_in_slice

            slice_type   = get_ue_golomb_31(&nal.gb);

            s->pict_type = ff_h264_golomb_to_pict_type[slice_type % 5];

            if (p->sei.recovery_point.recovery_frame_cnt >= 0) {

                /* key frame, since recovery_frame_cnt is set */

                s->key_frame = 1;

            }

            pps_id = get_ue_golomb(&nal.gb);

            if (pps_id >= MAX_PPS_COUNT) {

                av_log(avctx, AV_LOG_ERROR,

                       "pps_id %u out of range\n", pps_id);

                goto fail;

            }

            if (!p->ps.pps_list[pps_id]) {

                av_log(avctx, AV_LOG_ERROR,

                       "non-existing PPS %u referenced\n", pps_id);

                goto fail;

            }

            av_buffer_unref(&p->ps.pps_ref);

            av_buffer_unref(&p->ps.sps_ref);

            p->ps.pps = NULL;

            p->ps.sps = NULL;

            p->ps.pps_ref = av_buffer_ref(p->ps.pps_list[pps_id]);

            if (!p->ps.pps_ref)

                goto fail;

            p->ps.pps = (const PPS*)p->ps.pps_ref->data;

            if (!p->ps.sps_list[p->ps.pps->sps_id]) {

                av_log(avctx, AV_LOG_ERROR,

                       "non-existing SPS %u referenced\n", p->ps.pps->sps_id);

                goto fail;

            }

            p->ps.sps_ref = av_buffer_ref(p->ps.sps_list[p->ps.pps->sps_id]);

            if (!p->ps.sps_ref)

                goto fail;

            p->ps.sps = (const SPS*)p->ps.sps_ref->data;

            sps = p->ps.sps;

            // heuristic to detect non marked keyframes

            if (p->ps.sps->ref_frame_count <= 1 && p->ps.pps->ref_count[0] <= 1 && s->pict_type == AV_PICTURE_TYPE_I)

                s->key_frame = 1;

            p->poc.frame_num = get_bits(&nal.gb, sps->log2_max_frame_num);

            s->coded_width  = 16 * sps->mb_width;

            s->coded_height = 16 * sps->mb_height;

            s->width        = s->coded_width  - (sps->crop_right + sps->crop_left);

            s->height       = s->coded_height - (sps->crop_top   + sps->crop_bottom);

            if (s->width <= 0 || s->height <= 0) {

                s->width  = s->coded_width;

                s->height = s->coded_height;

            }

            switch (sps->bit_depth_luma) {

            case 9:

                if (sps->chroma_format_idc == 3)      s->format = AV_PIX_FMT_YUV444P9;

                else if (sps->chroma_format_idc == 2) s->format = AV_PIX_FMT_YUV422P9;

                else                                  s->format = AV_PIX_FMT_YUV420P9;

                break;

            case 10:

                if (sps->chroma_format_idc == 3)      s->format = AV_PIX_FMT_YUV444P10;

                else if (sps->chroma_format_idc == 2) s->format = AV_PIX_FMT_YUV422P10;

                else                                  s->format = AV_PIX_FMT_YUV420P10;

                break;

            case 8:

                if (sps->chroma_format_idc == 3)      s->format = AV_PIX_FMT_YUV444P;

                else if (sps->chroma_format_idc == 2) s->format = AV_PIX_FMT_YUV422P;

                else                                  s->format = AV_PIX_FMT_YUV420P;

                break;

            default:

                s->format = AV_PIX_FMT_NONE;

            }

            avctx->profile = ff_h264_get_profile(sps);

            avctx->level   = sps->level_idc;

            if (sps->frame_mbs_only_flag) {

                p->picture_structure = PICT_FRAME;

            } else {

                if (get_bits1(&nal.gb)) { // field_pic_flag

                    p->picture_structure = PICT_TOP_FIELD + get_bits1(&nal.gb); // bottom_field_flag

                } else {

                    p->picture_structure = PICT_FRAME;

                }

            }

            if (nal.type == H264_NAL_IDR_SLICE)

                get_ue_golomb_long(&nal.gb); /* idr_pic_id */

            if (sps->poc_type == 0) {

                p->poc.poc_lsb = get_bits(&nal.gb, sps->log2_max_poc_lsb);

                if (p->ps.pps->pic_order_present == 1 &&

                    p->picture_structure == PICT_FRAME)

                    p->poc.delta_poc_bottom = get_se_golomb(&nal.gb);

            }

            if (sps->poc_type == 1 &&

                !sps->delta_pic_order_always_zero_flag) {

                p->poc.delta_poc[0] = get_se_golomb(&nal.gb);

                if (p->ps.pps->pic_order_present == 1 &&

                    p->picture_structure == PICT_FRAME)

                    p->poc.delta_poc[1] = get_se_golomb(&nal.gb);

            }

            /* Decode POC of this picture.

             * The prev_ values needed for decoding POC of the next picture are not set here. */

            field_poc[0] = field_poc[1] = INT_MAX;

            ff_h264_init_poc(field_poc, &s->output_picture_number, sps,

                             &p->poc, p->picture_structure, nal.ref_idc);

            /* Continue parsing to check if MMCO_RESET is present.

             * FIXME: MMCO_RESET could appear in non-first slice.

             *        Maybe, we should parse all undisposable non-IDR slice of this

             *        picture until encountering MMCO_RESET in a slice of it. */

            if (nal.ref_idc && nal.type != H264_NAL_IDR_SLICE) {

                got_reset = scan_mmco_reset(s, &nal.gb, avctx);

                if (got_reset < 0)

                    goto fail;

            }

            /* Set up the prev_ values for decoding POC of the next picture. */

            p->poc.prev_frame_num        = got_reset ? 0 : p->poc.frame_num;

            p->poc.prev_frame_num_offset = got_reset ? 0 : p->poc.frame_num_offset;

            if (nal.ref_idc != 0) {

                if (!got_reset) {

                    p->poc.prev_poc_msb = p->poc.poc_msb;

                    p->poc.prev_poc_lsb = p->poc.poc_lsb;

                } else {

                    p->poc.prev_poc_msb = 0;

                    p->poc.prev_poc_lsb =

                        p->picture_structure == PICT_BOTTOM_FIELD ? 0 : field_poc[0];

                }

            }

            if (sps->pic_struct_present_flag) {

                switch (p->sei.picture_timing.pic_struct) {

                case SEI_PIC_STRUCT_TOP_FIELD:

                case SEI_PIC_STRUCT_BOTTOM_FIELD:

                    s->repeat_pict = 0;

                    break;

                case SEI_PIC_STRUCT_FRAME:

                case SEI_PIC_STRUCT_TOP_BOTTOM:

                case SEI_PIC_STRUCT_BOTTOM_TOP:

                    s->repeat_pict = 1;

                    break;

                case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:

                case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:

                    s->repeat_pict = 2;

                    break;

                case SEI_PIC_STRUCT_FRAME_DOUBLING:

                    s->repeat_pict = 3;

                    break;

                case SEI_PIC_STRUCT_FRAME_TRIPLING:

                    s->repeat_pict = 5;

                    break;

                default:

                    s->repeat_pict = p->picture_structure == PICT_FRAME ? 1 : 0;

                    break;

                }

            } else {

                s->repeat_pict = p->picture_structure == PICT_FRAME ? 1 : 0;

            }

            if (p->picture_structure == PICT_FRAME) {

                s->picture_structure = AV_PICTURE_STRUCTURE_FRAME;

                if (sps->pic_struct_present_flag) {

                    switch (p->sei.picture_timing.pic_struct) {

                    case SEI_PIC_STRUCT_TOP_BOTTOM:

                    case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:

                        s->field_order = AV_FIELD_TT;

                        break;

                    case SEI_PIC_STRUCT_BOTTOM_TOP:

                    case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:

                        s->field_order = AV_FIELD_BB;

                        break;

                    default:

                        s->field_order = AV_FIELD_PROGRESSIVE;

                        break;

                    }

                } else {

                    if (field_poc[0] < field_poc[1])

                        s->field_order = AV_FIELD_TT;

                    else if (field_poc[0] > field_poc[1])

                        s->field_order = AV_FIELD_BB;

                    else

                        s->field_order = AV_FIELD_PROGRESSIVE;

                }

            } else {

                if (p->picture_structure == PICT_TOP_FIELD)

                    s->picture_structure = AV_PICTURE_STRUCTURE_TOP_FIELD;

                else

                    s->picture_structure = AV_PICTURE_STRUCTURE_BOTTOM_FIELD;

                if (p->poc.frame_num == p->last_frame_num &&

                    p->last_picture_structure != AV_PICTURE_STRUCTURE_UNKNOWN &&

                    p->last_picture_structure != AV_PICTURE_STRUCTURE_FRAME &&

                    p->last_picture_structure != s->picture_structure) {

                    if (p->last_picture_structure == AV_PICTURE_STRUCTURE_TOP_FIELD)

                        s->field_order = AV_FIELD_TT;

                    else

                        s->field_order = AV_FIELD_BB;

                } else {

                    s->field_order = AV_FIELD_UNKNOWN;

                }

                p->last_picture_structure = s->picture_structure;

                p->last_frame_num = p->poc.frame_num;

            }

            av_freep(&nal.rbsp_buffer);

            return 0; /* no need to evaluate the rest */

        }

    }

    if (q264) {

        av_freep(&nal.rbsp_buffer);

        return 0;

    }

    /* didn't find a picture! */

    av_log(avctx, AV_LOG_ERROR, "missing picture in access unit with size %d\n", buf_size);

fail:

    av_freep(&nal.rbsp_buffer);

    return -1;

}


void ssl_set_session_cache( ssl_context *ssl,
        int (*f_get_cache)(void *, ssl_session *), void *p_get_cache,
        int (*f_set_cache)(void *, const ssl_session *), void *p_set_cache )
{
    ssl->f_get_cache = f_get_cache;
    ssl->p_get_cache = p_get_cache;
    ssl->f_set_cache = f_set_cache;
    ssl->p_set_cache = p_set_cache;
}


static void handle_transaction_done(struct smi_info *smi_info)
{
	struct ipmi_smi_msg *msg;

	debug_timestamp("Done");
	switch (smi_info->si_state) {
	case SI_NORMAL:
		if (!smi_info->curr_msg)
			break;

		smi_info->curr_msg->rsp_size
			= smi_info->handlers->get_result(
				smi_info->si_sm,
				smi_info->curr_msg->rsp,
				IPMI_MAX_MSG_LENGTH);

		/*
		 * Do this here becase deliver_recv_msg() releases the
		 * lock, and a new message can be put in during the
		 * time the lock is released.
		 */
		msg = smi_info->curr_msg;
		smi_info->curr_msg = NULL;
		deliver_recv_msg(smi_info, msg);
		break;

	case SI_GETTING_FLAGS:
	{
		unsigned char msg[4];
		unsigned int  len;

		/* We got the flags from the SMI, now handle them. */
		len = smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
		if (msg[2] != 0) {
			/* Error fetching flags, just give up for now. */
			smi_info->si_state = SI_NORMAL;
		} else if (len < 4) {
			/*
			 * Hmm, no flags.  That's technically illegal, but
			 * don't use uninitialized data.
			 */
			smi_info->si_state = SI_NORMAL;
		} else {
			smi_info->msg_flags = msg[3];
			handle_flags(smi_info);
		}
		break;
	}

	case SI_CLEARING_FLAGS:
	{
		unsigned char msg[3];

		/* We cleared the flags. */
		smi_info->handlers->get_result(smi_info->si_sm, msg, 3);
		if (msg[2] != 0) {
			/* Error clearing flags */
			dev_warn(smi_info->io.dev,
				 "Error clearing flags: %2.2x\n", msg[2]);
		}
		smi_info->si_state = SI_NORMAL;
		break;
	}

	case SI_GETTING_EVENTS:
	{
		smi_info->curr_msg->rsp_size
			= smi_info->handlers->get_result(
				smi_info->si_sm,
				smi_info->curr_msg->rsp,
				IPMI_MAX_MSG_LENGTH);

		/*
		 * Do this here becase deliver_recv_msg() releases the
		 * lock, and a new message can be put in during the
		 * time the lock is released.
		 */
		msg = smi_info->curr_msg;
		smi_info->curr_msg = NULL;
		if (msg->rsp[2] != 0) {
			/* Error getting event, probably done. */
			msg->done(msg);

			/* Take off the event flag. */
			smi_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL;
			handle_flags(smi_info);
		} else {
			smi_inc_stat(smi_info, events);

			/*
			 * Do this before we deliver the message
			 * because delivering the message releases the
			 * lock and something else can mess with the
			 * state.
			 */
			handle_flags(smi_info);

			deliver_recv_msg(smi_info, msg);
		}
		break;
	}

	case SI_GETTING_MESSAGES:
	{
		smi_info->curr_msg->rsp_size
			= smi_info->handlers->get_result(
				smi_info->si_sm,
				smi_info->curr_msg->rsp,
				IPMI_MAX_MSG_LENGTH);

		/*
		 * Do this here becase deliver_recv_msg() releases the
		 * lock, and a new message can be put in during the
		 * time the lock is released.
		 */
		msg = smi_info->curr_msg;
		smi_info->curr_msg = NULL;
		if (msg->rsp[2] != 0) {
			/* Error getting event, probably done. */
			msg->done(msg);

			/* Take off the msg flag. */
			smi_info->msg_flags &= ~RECEIVE_MSG_AVAIL;
			handle_flags(smi_info);
		} else {
			smi_inc_stat(smi_info, incoming_messages);

			/*
			 * Do this before we deliver the message
			 * because delivering the message releases the
			 * lock and something else can mess with the
			 * state.
			 */
			handle_flags(smi_info);

			deliver_recv_msg(smi_info, msg);
		}
		break;
	}

	case SI_CHECKING_ENABLES:
	{
		unsigned char msg[4];
		u8 enables;
		bool irq_on;

		/* We got the flags from the SMI, now handle them. */
		smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
		if (msg[2] != 0) {
			dev_warn(smi_info->io.dev,
				 "Couldn't get irq info: %x.\n", msg[2]);
			dev_warn(smi_info->io.dev,
				 "Maybe ok, but ipmi might run very slowly.\n");
			smi_info->si_state = SI_NORMAL;
			break;
		}
		enables = current_global_enables(smi_info, 0, &irq_on);
		if (smi_info->io.si_type == SI_BT)
			/* BT has its own interrupt enable bit. */
			check_bt_irq(smi_info, irq_on);
		if (enables != (msg[3] & GLOBAL_ENABLES_MASK)) {
			/* Enables are not correct, fix them. */
			msg[0] = (IPMI_NETFN_APP_REQUEST << 2);
			msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD;
			msg[2] = enables | (msg[3] & ~GLOBAL_ENABLES_MASK);
			smi_info->handlers->start_transaction(
				smi_info->si_sm, msg, 3);
			smi_info->si_state = SI_SETTING_ENABLES;
		} else if (smi_info->supports_event_msg_buff) {
			smi_info->curr_msg = ipmi_alloc_smi_msg();
			if (!smi_info->curr_msg) {
				smi_info->si_state = SI_NORMAL;
				break;
			}
			start_getting_events(smi_info);
		} else {
			smi_info->si_state = SI_NORMAL;
		}
		break;
	}

	case SI_SETTING_ENABLES:
	{
		unsigned char msg[4];

		smi_info->handlers->get_result(smi_info->si_sm, msg, 4);
		if (msg[2] != 0)
			dev_warn(smi_info->io.dev,
				 "Could not set the global enables: 0x%x.\n",
				 msg[2]);

		if (smi_info->supports_event_msg_buff) {
			smi_info->curr_msg = ipmi_alloc_smi_msg();
			if (!smi_info->curr_msg) {
				smi_info->si_state = SI_NORMAL;
				break;
			}
			start_getting_events(smi_info);
		} else {
			smi_info->si_state = SI_NORMAL;
		}
		break;
	}
	}
}


static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
                                    size_t* pos, size_t inlength, unsigned btype)
{
  unsigned error = 0;
  HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
  HuffmanTree tree_d; /*the huffman tree for distance codes*/
  size_t inbitlength = inlength * 8;

  HuffmanTree_init(&tree_ll);
  HuffmanTree_init(&tree_d);

  if(btype == 1)
  {
     error = getTreeInflateFixed(&tree_ll, &tree_d);
     if (error)
     {
       HuffmanTree_cleanup(&tree_ll);
       HuffmanTree_cleanup(&tree_d);
       return error;
     }
  }
  else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);

  while(!error) /*decode all symbols until end reached, breaks at end code*/
  {
    /*code_ll is literal, length or end code*/
    unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
    if(code_ll <= 255) /*literal symbol*/
    {
      /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
      if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
      out->data[*pos] = (unsigned char)code_ll;
      (*pos)++;
    }
    else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/
    {
      unsigned code_d, distance;
      unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
      size_t start, forward, backward, length;

      /*part 1: get length base*/
      length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];

      /*part 2: get extra bits and add the value of that to length*/
      numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
      if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
      length += readBitsFromStream(bp, in, numextrabits_l);

      /*part 3: get distance code*/
      code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
      if(code_d > 29)
      {
        if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
        {
          /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
          (10=no endcode, 11=wrong jump outside of tree)*/
          error = (*bp) > inlength * 8 ? 10 : 11;
        }
        else error = 18; /*error: invalid distance code (30-31 are never used)*/
        break;
      }
      distance = DISTANCEBASE[code_d];

      /*part 4: get extra bits from distance*/
      numextrabits_d = DISTANCEEXTRA[code_d];
      if(*bp >= inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/

      distance += readBitsFromStream(bp, in, numextrabits_d);

      /*part 5: fill in all the out[n] values based on the length and dist*/
      start = (*pos);
      if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
      backward = start - distance;

      if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
      for(forward = 0; forward < length; forward++)
      {
        out->data[(*pos)] = out->data[backward];
        (*pos)++;
        backward++;
        if(backward >= start) backward = start - distance;
      }
    }
    else if(code_ll == 256)
    {
      break; /*end code, break the loop*/
    }
    else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
    {
      /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
      (10=no endcode, 11=wrong jump outside of tree)*/
      error = (*bp) > inlength * 8 ? 10 : 11;
      break;
    }
  }

  HuffmanTree_cleanup(&tree_ll);
  HuffmanTree_cleanup(&tree_d);

  return error;
}


GF_Err ssix_dump(GF_Box *a, FILE * trace)
{
	u32 i, j;
	GF_SubsegmentIndexBox *p = (GF_SubsegmentIndexBox *)a;
	gf_isom_box_dump_start(a, "SubsegmentIndexBox", trace);

	fprintf(trace, "subsegment_count=\"%d\" >\n", p->subsegment_count);
	for (i = 0; i < p->subsegment_count; i++) {
		fprintf(trace, "<Subsegment range_count=\"%d\">\n", p->subsegments[i].range_count);
		for (j = 0; j < p->subsegments[i].range_count; j++) {
			fprintf(trace, "<Range level=\"%d\" range_size=\"%d\"/>\n", p->subsegments[i].levels[j], p->subsegments[i].range_sizes[j]);
		}
		fprintf(trace, "</Subsegment>\n");
	}
	if (!p->size) {
		fprintf(trace, "<Subsegment range_count=\"\">\n");
		fprintf(trace, "<Range level=\"\" range_size=\"\"/>\n");
		fprintf(trace, "</Subsegment>\n");
	}
	gf_isom_box_dump_done("SubsegmentIndexBox", a, trace);
	return GF_OK;
}


Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
        sp<StatusTracker> statusTracker,
 camera3_device_t *hal3Device,
 bool aeLockAvailable) :
 Thread(/*canCallJava*/false),
        mParent(parent),
        mStatusTracker(statusTracker),
        mHal3Device(hal3Device),
        mId(getId(parent)),
        mReconfigured(false),
        mDoPause(false),
        mPaused(true),
        mFrameNumber(0),
        mLatestRequestId(NAME_NOT_FOUND),
        mCurrentAfTriggerId(0),
        mCurrentPreCaptureTriggerId(0),
        mRepeatingLastFrameNumber(NO_IN_FLIGHT_REPEATING_FRAMES),
        mAeLockAvailable(aeLockAvailable) {
    mStatusId = statusTracker->addComponent();
}


GF_Err stts_box_read(GF_Box *s, GF_BitStream *bs)
{
	u32 i;
	GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s;

#ifndef GPAC_DISABLE_ISOM_WRITE
	ptr->w_LastDTS = 0;
#endif

	ISOM_DECREASE_SIZE(ptr, 4);
	ptr->nb_entries = gf_bs_read_u32(bs);
	if (ptr->size / 8 < ptr->nb_entries || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_SttsEntry)) {
		GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stts\n", ptr->nb_entries));
		return GF_ISOM_INVALID_FILE;
	}

	ptr->alloc_size = ptr->nb_entries;
	ptr->entries = gf_malloc(sizeof(GF_SttsEntry)*ptr->alloc_size);
	if (!ptr->entries) return GF_OUT_OF_MEM;

	for (i=0; i<ptr->nb_entries; i++) {
		ptr->entries[i].sampleCount = gf_bs_read_u32(bs);
		ptr->entries[i].sampleDelta = gf_bs_read_u32(bs);
#ifndef GPAC_DISABLE_ISOM_WRITE
		ptr->w_currentSampleNum += ptr->entries[i].sampleCount;
		ptr->w_LastDTS += (u64)ptr->entries[i].sampleCount * ptr->entries[i].sampleDelta;
#endif
		if (ptr->max_ts_delta<ptr->entries[i].sampleDelta)
			ptr->max_ts_delta = ptr->entries[i].sampleDelta;

		if (!ptr->entries[i].sampleDelta) {
			if ((i+1<ptr->nb_entries) ) {
				GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Found stts entry with sample_delta=0 - forbidden ! Fixing to 1\n" ));
				ptr->entries[i].sampleDelta = 1;
			} else if (ptr->entries[i].sampleCount>1) {
				GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] more than one stts entry at the end of the track with sample_delta=0 - forbidden ! Fixing to 1\n" ));
				ptr->entries[i].sampleDelta = 1;
			}
		}
		//cf issue 1644: some media streams may have sample duration > 2^31 (ttml mostly), we cannot patch this
		//for now we disable the check, one opt could be to have the check only for some media types, or only for the first entry
#if 0
		else if ((s32) ptr->entries[i].sampleDelta < 0) {
			GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] stts entry %d has negative duration %d - forbidden ! Fixing to 1, sync may get lost (consider reimport raw media)\n", i, (s32) ptr->entries[i].sampleDelta ));
			ptr->entries[i].sampleDelta = 1;
		}
#endif

	}
	ISOM_DECREASE_SIZE(ptr, ptr->nb_entries*8);

	//remove the last sample delta.
#ifndef GPAC_DISABLE_ISOM_WRITE
	if (ptr->nb_entries) ptr->w_LastDTS -= ptr->entries[ptr->nb_entries-1].sampleDelta;
#endif
	return GF_OK;
}


void machine_check_exception(struct pt_regs *regs)
{
	int recover = 0;
	unsigned long reason = get_mc_reason(regs);

	/* See if any machine dependent calls */
	if (ppc_md.machine_check_exception)
		recover = ppc_md.machine_check_exception(regs);

	if (recover)
		return;

	if (user_mode(regs)) {
		regs->msr |= MSR_RI;
		_exception(SIGBUS, regs, BUS_ADRERR, regs->nip);
		return;
	}

#if defined(CONFIG_8xx) && defined(CONFIG_PCI)
	/* the qspan pci read routines can cause machine checks -- Cort */
	bad_page_fault(regs, regs->dar, SIGBUS);
	return;
#endif

	if (debugger_fault_handler(regs)) {
		regs->msr |= MSR_RI;
		return;
	}

	if (check_io_access(regs))
		return;

#if defined(CONFIG_4xx) && !defined(CONFIG_440A)
	if (reason & ESR_IMCP) {
		printk("Instruction");
		mtspr(SPRN_ESR, reason & ~ESR_IMCP);
	} else
		printk("Data");
	printk(" machine check in kernel mode.\n");
#elif defined(CONFIG_440A)
	printk("Machine check in kernel mode.\n");
	if (reason & ESR_IMCP){
		printk("Instruction Synchronous Machine Check exception\n");
		mtspr(SPRN_ESR, reason & ~ESR_IMCP);
	}
	else {
		u32 mcsr = mfspr(SPRN_MCSR);
		if (mcsr & MCSR_IB)
			printk("Instruction Read PLB Error\n");
		if (mcsr & MCSR_DRB)
			printk("Data Read PLB Error\n");
		if (mcsr & MCSR_DWB)
			printk("Data Write PLB Error\n");
		if (mcsr & MCSR_TLBP)
			printk("TLB Parity Error\n");
		if (mcsr & MCSR_ICP){
			flush_instruction_cache();
			printk("I-Cache Parity Error\n");
		}
		if (mcsr & MCSR_DCSP)
			printk("D-Cache Search Parity Error\n");
		if (mcsr & MCSR_DCFP)
			printk("D-Cache Flush Parity Error\n");
		if (mcsr & MCSR_IMPE)
			printk("Machine Check exception is imprecise\n");

		/* Clear MCSR */
		mtspr(SPRN_MCSR, mcsr);
	}
#elif defined (CONFIG_E500)
	printk("Machine check in kernel mode.\n");
	printk("Caused by (from MCSR=%lx): ", reason);

	if (reason & MCSR_MCP)
		printk("Machine Check Signal\n");
	if (reason & MCSR_ICPERR)
		printk("Instruction Cache Parity Error\n");
	if (reason & MCSR_DCP_PERR)
		printk("Data Cache Push Parity Error\n");
	if (reason & MCSR_DCPERR)
		printk("Data Cache Parity Error\n");
	if (reason & MCSR_GL_CI)
		printk("Guarded Load or Cache-Inhibited stwcx.\n");
	if (reason & MCSR_BUS_IAERR)
		printk("Bus - Instruction Address Error\n");
	if (reason & MCSR_BUS_RAERR)
		printk("Bus - Read Address Error\n");
	if (reason & MCSR_BUS_WAERR)
		printk("Bus - Write Address Error\n");
	if (reason & MCSR_BUS_IBERR)
		printk("Bus - Instruction Data Error\n");
	if (reason & MCSR_BUS_RBERR)
		printk("Bus - Read Data Bus Error\n");
	if (reason & MCSR_BUS_WBERR)
		printk("Bus - Read Data Bus Error\n");
	if (reason & MCSR_BUS_IPERR)
		printk("Bus - Instruction Parity Error\n");
	if (reason & MCSR_BUS_RPERR)
		printk("Bus - Read Parity Error\n");
#elif defined (CONFIG_E200)
	printk("Machine check in kernel mode.\n");
	printk("Caused by (from MCSR=%lx): ", reason);

	if (reason & MCSR_MCP)
		printk("Machine Check Signal\n");
	if (reason & MCSR_CP_PERR)
		printk("Cache Push Parity Error\n");
	if (reason & MCSR_CPERR)
		printk("Cache Parity Error\n");
	if (reason & MCSR_EXCP_ERR)
		printk("ISI, ITLB, or Bus Error on first instruction fetch for an exception handler\n");
	if (reason & MCSR_BUS_IRERR)
		printk("Bus - Read Bus Error on instruction fetch\n");
	if (reason & MCSR_BUS_DRERR)
		printk("Bus - Read Bus Error on data load\n");
	if (reason & MCSR_BUS_WRERR)
		printk("Bus - Write Bus Error on buffered store or cache line push\n");
#else /* !CONFIG_4xx && !CONFIG_E500 && !CONFIG_E200 */
	printk("Machine check in kernel mode.\n");
	printk("Caused by (from SRR1=%lx): ", reason);
	switch (reason & 0x601F0000) {
	case 0x80000:
		printk("Machine check signal\n");
		break;
	case 0:		/* for 601 */
	case 0x40000:
	case 0x140000:	/* 7450 MSS error and TEA */
		printk("Transfer error ack signal\n");
		break;
	case 0x20000:
		printk("Data parity error signal\n");
		break;
	case 0x10000:
		printk("Address parity error signal\n");
		break;
	case 0x20000000:
		printk("L1 Data Cache error\n");
		break;
	case 0x40000000:
		printk("L1 Instruction Cache error\n");
		break;
	case 0x00100000:
		printk("L2 data cache parity error\n");
		break;
	default:
		printk("Unknown values in msr\n");
	}
#endif /* CONFIG_4xx */

	/*
	 * Optional platform-provided routine to print out
	 * additional info, e.g. bus error registers.
	 */
	platform_machine_check(regs);

	if (debugger_fault_handler(regs))
		return;
	die("Machine check", regs, SIGBUS);

	/* Must die if the interrupt is not recoverable */
	if (!(regs->msr & MSR_RI))
		panic("Unrecoverable Machine check");
}


archive_read_format_7zip_read_header(struct archive_read *a,
	struct archive_entry *entry)
{
	struct _7zip *zip = (struct _7zip *)a->format->data;
	struct _7zip_entry *zip_entry;
	int r, ret = ARCHIVE_OK;
	struct _7z_folder *folder = 0;
	uint64_t fidx = 0;

	/*
	 * It should be sufficient to call archive_read_next_header() for
	 * a reader to determine if an entry is encrypted or not. If the
	 * encryption of an entry is only detectable when calling
	 * archive_read_data(), so be it. We'll do the same check there
	 * as well.
	 */
	if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
		zip->has_encrypted_entries = 0;
	}

	a->archive.archive_format = ARCHIVE_FORMAT_7ZIP;
	if (a->archive.archive_format_name == NULL)
		a->archive.archive_format_name = "7-Zip";

	if (zip->entries == NULL) {
		struct _7z_header_info header;

		memset(&header, 0, sizeof(header));
		r = slurp_central_directory(a, zip, &header);
		free_Header(&header);
		if (r != ARCHIVE_OK)
			return (r);
		zip->entries_remaining = (size_t)zip->numFiles;
		zip->entry = zip->entries;
	} else {
		++zip->entry;
	}
	zip_entry = zip->entry;

	if (zip->entries_remaining <= 0 || zip_entry == NULL)
		return ARCHIVE_EOF;
	--zip->entries_remaining;

	zip->entry_offset = 0;
	zip->end_of_entry = 0;
	zip->entry_crc32 = crc32(0, NULL, 0);

	/* Setup a string conversion for a filename. */
	if (zip->sconv == NULL) {
		zip->sconv = archive_string_conversion_from_charset(
		    &a->archive, "UTF-16LE", 1);
		if (zip->sconv == NULL)
			return (ARCHIVE_FATAL);
	}

	/* Figure out if the entry is encrypted by looking at the folder
	   that is associated to the current 7zip entry. If the folder
	   has a coder with a _7Z_CRYPTO codec then the folder is encrypted.
	   Hence the entry must also be encrypted. */
	if (zip_entry && zip_entry->folderIndex < zip->si.ci.numFolders) {
		folder = &(zip->si.ci.folders[zip_entry->folderIndex]);
		for (fidx=0; folder && fidx<folder->numCoders; fidx++) {
			switch(folder->coders[fidx].codec) {
				case _7Z_CRYPTO_MAIN_ZIP:
				case _7Z_CRYPTO_RAR_29:
				case _7Z_CRYPTO_AES_256_SHA_256: {
					archive_entry_set_is_data_encrypted(entry, 1);
					zip->has_encrypted_entries = 1;
					break;
				}
			}
		}
	}

	/* Now that we've checked for encryption, if there were still no
	 * encrypted entries found we can say for sure that there are none.
	 */
	if (zip->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
		zip->has_encrypted_entries = 0;
	}

	if (archive_entry_copy_pathname_l(entry,
	    (const char *)zip_entry->utf16name,
	    zip_entry->name_len, zip->sconv) != 0) {
		if (errno == ENOMEM) {
			archive_set_error(&a->archive, ENOMEM,
			    "Can't allocate memory for Pathname");
			return (ARCHIVE_FATAL);
		}
		archive_set_error(&a->archive,
		    ARCHIVE_ERRNO_FILE_FORMAT,
		    "Pathname cannot be converted "
		    "from %s to current locale.",
		    archive_string_conversion_charset_name(zip->sconv));
		ret = ARCHIVE_WARN;
	}

	/* Populate some additional entry fields: */
	archive_entry_set_mode(entry, zip_entry->mode);
	if (zip_entry->flg & MTIME_IS_SET)
		archive_entry_set_mtime(entry, zip_entry->mtime,
			zip_entry->mtime_ns);
	if (zip_entry->flg & CTIME_IS_SET)
		archive_entry_set_ctime(entry, zip_entry->ctime,
		    zip_entry->ctime_ns);
	if (zip_entry->flg & ATIME_IS_SET)
		archive_entry_set_atime(entry, zip_entry->atime,
		    zip_entry->atime_ns);
	if (zip_entry->ssIndex != (uint32_t)-1) {
		zip->entry_bytes_remaining =
		    zip->si.ss.unpackSizes[zip_entry->ssIndex];
		archive_entry_set_size(entry, zip->entry_bytes_remaining);
	} else {
		zip->entry_bytes_remaining = 0;
		archive_entry_set_size(entry, 0);
	}

	/* If there's no body, force read_data() to return EOF immediately. */
	if (zip->entry_bytes_remaining < 1)
		zip->end_of_entry = 1;

	if ((zip_entry->mode & AE_IFMT) == AE_IFLNK) {
		unsigned char *symname = NULL;
		size_t symsize = 0;

		/*
		 * Symbolic-name is recorded as its contents. We have to
		 * read the contents at this time.
		 */
		while (zip->entry_bytes_remaining > 0) {
			const void *buff;
			unsigned char *mem;
			size_t size;
			int64_t offset;

			r = archive_read_format_7zip_read_data(a, &buff,
				&size, &offset);
			if (r < ARCHIVE_WARN) {
				free(symname);
				return (r);
			}
			mem = realloc(symname, symsize + size + 1);
			if (mem == NULL) {
				free(symname);
				archive_set_error(&a->archive, ENOMEM,
				    "Can't allocate memory for Symname");
				return (ARCHIVE_FATAL);
			}
			symname = mem;
			memcpy(symname+symsize, buff, size);
			symsize += size;
		}
		if (symsize == 0) {
			/* If there is no synname, handle it as a regular
			 * file. */
			zip_entry->mode &= ~AE_IFMT;
			zip_entry->mode |= AE_IFREG;
			archive_entry_set_mode(entry, zip_entry->mode);
		} else {
			symname[symsize] = '\0';
			archive_entry_copy_symlink(entry,
			    (const char *)symname);
		}
		free(symname);
		archive_entry_set_size(entry, 0);
	}

	/* Set up a more descriptive format name. */
	sprintf(zip->format_name, "7-Zip");
	a->archive.archive_format_name = zip->format_name;

	return (ret);
}


ChromeContentBrowserClient::DetermineCommittedPreviewsForURL(
    const GURL& url,
    data_reduction_proxy::DataReductionProxyData* drp_data,
    previews::PreviewsUserData* previews_user_data,
    const previews::PreviewsDecider* previews_decider,
    content::PreviewsState initial_state) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (!previews::HasEnabledPreviews(initial_state))
    return content::PREVIEWS_OFF;

  content::PreviewsState previews_state =
      data_reduction_proxy::ContentLoFiDecider::
          DetermineCommittedServerPreviewsState(drp_data, initial_state);

  return previews::DetermineCommittedClientPreviewsState(
      previews_user_data, url, previews_state, previews_decider);
}


 PreconnectRequest::PreconnectRequest(
    const url::Origin& origin,
     int num_sockets,
     const net::NetworkIsolationKey& network_isolation_key)
     : origin(origin),
      num_sockets(num_sockets),
      network_isolation_key(network_isolation_key) {
  DCHECK_GE(num_sockets, 0);
}


static int tm2_build_huff_table(TM2Context *ctx, TM2Codes *code)

{

    TM2Huff huff;

    int res = 0;

    huff.val_bits = get_bits(&ctx->gb, 5);

    huff.max_bits = get_bits(&ctx->gb, 5);

    huff.min_bits = get_bits(&ctx->gb, 5);

    huff.nodes = get_bits_long(&ctx->gb, 17);

    huff.num = 0;

    /* check for correct codes parameters */

    if((huff.val_bits < 1) || (huff.val_bits > 32) ||

       (huff.max_bits < 0) || (huff.max_bits > 32)) {

        av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect tree parameters - literal length: %i, max code length: %i\n",

               huff.val_bits, huff.max_bits);

        return -1;

    }

    if((huff.nodes <= 0) || (huff.nodes > 0x10000)) {

        av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of Huffman tree nodes: %i\n", huff.nodes);

        return -1;

    }

    /* one-node tree */

    if(huff.max_bits == 0)

        huff.max_bits = 1;

    /* allocate space for codes - it is exactly ceil(nodes / 2) entries */

    huff.max_num = (huff.nodes + 1) >> 1;

    huff.nums = av_mallocz(huff.max_num * sizeof(int));

    huff.bits = av_mallocz(huff.max_num * sizeof(uint32_t));

    huff.lens = av_mallocz(huff.max_num * sizeof(int));

    if(tm2_read_tree(ctx, 0, 0, &huff) == -1)

        res = -1;

    if(huff.num != huff.max_num) {

        av_log(ctx->avctx, AV_LOG_ERROR, "Got less codes than expected: %i of %i\n",

               huff.num, huff.max_num);

        res = -1;

    }

    /* convert codes to vlc_table */

    if(res != -1) {

        int i;

        res = init_vlc(&code->vlc, huff.max_bits, huff.max_num,

                    huff.lens, sizeof(int), sizeof(int),

                    huff.bits, sizeof(uint32_t), sizeof(uint32_t), 0);

        if(res < 0) {

            av_log(ctx->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");

            res = -1;

        } else

            res = 0;

        if(res != -1) {

            code->bits = huff.max_bits;

            code->length = huff.max_num;

            code->recode = av_malloc(code->length * sizeof(int));

            for(i = 0; i < code->length; i++)

                code->recode[i] = huff.nums[i];

        }

    }

    /* free allocated memory */

    av_free(huff.nums);

    av_free(huff.bits);

    av_free(huff.lens);

    return res;

}


ZEND_API void ZEND_FASTCALL zend_hash_clean(HashTable *ht)
{
	Bucket *p, *end;

	IS_CONSISTENT(ht);
	HT_ASSERT(GC_REFCOUNT(ht) == 1);

	if (ht->nNumUsed) {
		p = ht->arData;
		end = p + ht->nNumUsed;
		if (ht->pDestructor) {
			if (ht->u.flags & (HASH_FLAG_PACKED|HASH_FLAG_STATIC_KEYS)) {
				if (ht->nNumUsed == ht->nNumOfElements) {
					do {
						ht->pDestructor(&p->val);
					} while (++p != end);
				} else {
					do {
						if (EXPECTED(Z_TYPE(p->val) != IS_UNDEF)) {
							ht->pDestructor(&p->val);
						}
					} while (++p != end);
				}
			} else if (ht->nNumUsed == ht->nNumOfElements) {
				do {
					ht->pDestructor(&p->val);
					if (EXPECTED(p->key)) {
						zend_string_release(p->key);
					}
				} while (++p != end);
			} else {
				do {
					if (EXPECTED(Z_TYPE(p->val) != IS_UNDEF)) {
						ht->pDestructor(&p->val);
						if (EXPECTED(p->key)) {
							zend_string_release(p->key);
						}
					}
				} while (++p != end);
			}
		} else {
			if (!(ht->u.flags & (HASH_FLAG_PACKED|HASH_FLAG_STATIC_KEYS))) {
				if (ht->nNumUsed == ht->nNumOfElements) {
					do {
						if (EXPECTED(p->key)) {
							zend_string_release(p->key);
						}
					} while (++p != end);
				} else {
					do {
						if (EXPECTED(Z_TYPE(p->val) != IS_UNDEF)) {
							if (EXPECTED(p->key)) {
								zend_string_release(p->key);
							}
						}
					} while (++p != end);
				}
			}
		}
		if (!(ht->u.flags & HASH_FLAG_PACKED)) {
			HT_HASH_RESET(ht);
		}
	}
	ht->nNumUsed = 0;
	ht->nNumOfElements = 0;
	ht->nNextFreeElement = 0;
	ht->nInternalPointer = HT_INVALID_IDX;
}


void RTCPeerConnectionHandler::OnIceGatheringChange(
    webrtc::PeerConnectionInterface::IceGatheringState new_state) {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::OnIceGatheringChange");

  if (new_state == webrtc::PeerConnectionInterface::kIceGatheringComplete) {
    UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv4LocalCandidates",
                             num_local_candidates_ipv4_);

    UMA_HISTOGRAM_COUNTS_100("WebRTC.PeerConnection.IPv6LocalCandidates",
                             num_local_candidates_ipv6_);
  } else if (new_state ==
             webrtc::PeerConnectionInterface::kIceGatheringGathering) {
    ResetUMAStats();
  }

  if (peer_connection_tracker_)
    peer_connection_tracker_->TrackIceGatheringStateChange(this, new_state);
  if (!is_closed_)
    client_->DidChangeIceGatheringState(new_state);
}


static void appendImageIfNotNull(Vector<ImageResource*>& imageResources, const StyleImage* styleImage)
{
    if (styleImage && styleImage->cachedImage()) {
        ImageResource* imageResource = styleImage->cachedImage();
        if (imageResource && !imageResource->isLoaded())
            imageResources.append(styleImage->cachedImage());
    }
}


PHP_FUNCTION(imagecolorresolve)
{
	zval *IM;
	zend_long red, green, blue;
	gdImagePtr im;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlll", &IM, &red, &green, &blue) == FAILURE) {
		return;
	}

	if ((im = (gdImagePtr)zend_fetch_resource(Z_RES_P(IM), "Image", le_gd)) == NULL) {
		RETURN_FALSE;
	}

	RETURN_LONG(gdImageColorResolve(im, red, green, blue));
}


bool decode(ArgumentDecoder* decoder, RetainPtr<CFArrayRef>& result)
{
    uint64_t size;
    if (!decoder->decodeUInt64(size))
        return false;

    RetainPtr<CFMutableArrayRef> array(AdoptCF, CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));

    for (size_t i = 0; i < size; ++i) {
        RetainPtr<CFTypeRef> element;
        if (!decode(decoder, element))
            return false;

        CFArrayAppendValue(array.get(), element.get());
    }

    result.adoptCF(array.leakRef());
    return true;
}


int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
		size_t len)
{
	struct inet_sock *inet = inet_sk(sk);
	struct udp_sock *up = udp_sk(sk);
	struct flowi4 fl4_stack;
	struct flowi4 *fl4;
	int ulen = len;
	struct ipcm_cookie ipc;
	struct rtable *rt = NULL;
	int free = 0;
	int connected = 0;
	__be32 daddr, faddr, saddr;
	__be16 dport;
	u8  tos;
	int err, is_udplite = IS_UDPLITE(sk);
	int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
	struct sk_buff *skb;
	struct ip_options_data opt_copy;

	if (len > 0xFFFF)
		return -EMSGSIZE;

	/*
	 *	Check the flags.
	 */

	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
		return -EOPNOTSUPP;

	ipc.opt = NULL;
	ipc.tx_flags = 0;
	ipc.ttl = 0;
	ipc.tos = -1;

	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;

	fl4 = &inet->cork.fl.u.ip4;
	if (up->pending) {
		/*
		 * There are pending frames.
		 * The socket lock must be held while it's corked.
		 */
		lock_sock(sk);
		if (likely(up->pending)) {
			if (unlikely(up->pending != AF_INET)) {
				release_sock(sk);
				return -EINVAL;
			}
			goto do_append_data;
		}
		release_sock(sk);
	}
	ulen += sizeof(struct udphdr);

	/*
	 *	Get and verify the address.
	 */
	if (msg->msg_name) {
		struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
		if (msg->msg_namelen < sizeof(*usin))
			return -EINVAL;
		if (usin->sin_family != AF_INET) {
			if (usin->sin_family != AF_UNSPEC)
				return -EAFNOSUPPORT;
		}

		daddr = usin->sin_addr.s_addr;
		dport = usin->sin_port;
		if (dport == 0)
			return -EINVAL;
	} else {
		if (sk->sk_state != TCP_ESTABLISHED)
			return -EDESTADDRREQ;
		daddr = inet->inet_daddr;
		dport = inet->inet_dport;
		/* Open fast path for connected socket.
		   Route will not be used, if at least one option is set.
		 */
		connected = 1;
	}
	ipc.addr = inet->inet_saddr;

	ipc.oif = sk->sk_bound_dev_if;

	sock_tx_timestamp(sk, &ipc.tx_flags);

	if (msg->msg_controllen) {
		err = ip_cmsg_send(sock_net(sk), msg, &ipc);
		if (err)
			return err;
		if (ipc.opt)
			free = 1;
		connected = 0;
	}
	if (!ipc.opt) {
		struct ip_options_rcu *inet_opt;

		rcu_read_lock();
		inet_opt = rcu_dereference(inet->inet_opt);
		if (inet_opt) {
			memcpy(&opt_copy, inet_opt,
			       sizeof(*inet_opt) + inet_opt->opt.optlen);
			ipc.opt = &opt_copy.opt;
		}
		rcu_read_unlock();
	}

	saddr = ipc.addr;
	ipc.addr = faddr = daddr;

	if (ipc.opt && ipc.opt->opt.srr) {
		if (!daddr)
			return -EINVAL;
		faddr = ipc.opt->opt.faddr;
		connected = 0;
	}
	tos = get_rttos(&ipc, inet);
	if (sock_flag(sk, SOCK_LOCALROUTE) ||
	    (msg->msg_flags & MSG_DONTROUTE) ||
	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
		tos |= RTO_ONLINK;
		connected = 0;
	}

	if (ipv4_is_multicast(daddr)) {
		if (!ipc.oif)
			ipc.oif = inet->mc_index;
		if (!saddr)
			saddr = inet->mc_addr;
		connected = 0;
	} else if (!ipc.oif)
		ipc.oif = inet->uc_index;

	if (connected)
		rt = (struct rtable *)sk_dst_check(sk, 0);

	if (rt == NULL) {
		struct net *net = sock_net(sk);

		fl4 = &fl4_stack;
		flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
				   RT_SCOPE_UNIVERSE, sk->sk_protocol,
				   inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP,
				   faddr, saddr, dport, inet->inet_sport);

		security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
		rt = ip_route_output_flow(net, fl4, sk);
		if (IS_ERR(rt)) {
			err = PTR_ERR(rt);
			rt = NULL;
			if (err == -ENETUNREACH)
				IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
			goto out;
		}

		err = -EACCES;
		if ((rt->rt_flags & RTCF_BROADCAST) &&
		    !sock_flag(sk, SOCK_BROADCAST))
			goto out;
		if (connected)
			sk_dst_set(sk, dst_clone(&rt->dst));
	}

	if (msg->msg_flags&MSG_CONFIRM)
		goto do_confirm;
back_from_confirm:

	saddr = fl4->saddr;
	if (!ipc.addr)
		daddr = ipc.addr = fl4->daddr;

	/* Lockless fast path for the non-corking case. */
	if (!corkreq) {
		skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen,
				  sizeof(struct udphdr), &ipc, &rt,
				  msg->msg_flags);
		err = PTR_ERR(skb);
		if (!IS_ERR_OR_NULL(skb))
			err = udp_send_skb(skb, fl4);
		goto out;
	}

	lock_sock(sk);
	if (unlikely(up->pending)) {
		/* The socket is already corked while preparing it. */
		/* ... which is an evident application bug. --ANK */
		release_sock(sk);

		LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n"));
		err = -EINVAL;
		goto out;
	}
	/*
	 *	Now cork the socket to pend data.
	 */
	fl4 = &inet->cork.fl.u.ip4;
	fl4->daddr = daddr;
	fl4->saddr = saddr;
	fl4->fl4_dport = dport;
	fl4->fl4_sport = inet->inet_sport;
	up->pending = AF_INET;

do_append_data:
	up->len += ulen;
	err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen,
			     sizeof(struct udphdr), &ipc, &rt,
			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
	if (err)
		udp_flush_pending_frames(sk);
	else if (!corkreq)
		err = udp_push_pending_frames(sk);
	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
		up->pending = 0;
	release_sock(sk);

out:
	ip_rt_put(rt);
	if (free)
		kfree(ipc.opt);
	if (!err)
		return len;
	/*
	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
	 * we don't have a good statistic (IpOutDiscards but it can be too many
	 * things).  We could add another new stat but at least for now that
	 * seems like overkill.
	 */
	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
		UDP_INC_STATS_USER(sock_net(sk),
				UDP_MIB_SNDBUFERRORS, is_udplite);
	}
	return err;

do_confirm:
	dst_confirm(&rt->dst);
	if (!(msg->msg_flags&MSG_PROBE) || len)
		goto back_from_confirm;
	err = 0;
	goto out;
}


void spapr_create_phb(sPAPREnvironment *spapr,

                      const char *busname, uint64_t buid,

                      uint64_t mem_win_addr, uint64_t mem_win_size,

                      uint64_t io_win_addr, uint64_t msi_win_addr)

{

    DeviceState *dev;

    dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);

    if (busname) {

        qdev_prop_set_string(dev, "busname", g_strdup(busname));

    }

    qdev_prop_set_uint64(dev, "buid", buid);

    qdev_prop_set_uint64(dev, "mem_win_addr", mem_win_addr);

    qdev_prop_set_uint64(dev, "mem_win_size", mem_win_size);

    qdev_prop_set_uint64(dev, "io_win_addr", io_win_addr);

    qdev_prop_set_uint64(dev, "msi_win_addr", msi_win_addr);

    qdev_init_nofail(dev);

}


static ut32 cmp(ArmOp *op) {
	ut32 data = UT32_MAX;
	int k = 0;
	if (op->operands[0].reg_type & ARM_REG64 && op->operands[1].reg_type & ARM_REG64) {
		k =  0x1f0000eb;
	} else if (op->operands[0].reg_type & ARM_REG32 && op->operands[1].reg_type & ARM_REG32) {
		if (op->operands[2].shift_amount > 31) {
			return UT32_MAX;
		}
		k =  0x1f00006b;
	} else {
		return UT32_MAX;
	}

	data = k | (op->operands[0].reg & 0x18) << 13 | op->operands[0].reg << 29 | op->operands[1].reg << 8;

	if (op->operands[2].shift != ARM_NO_SHIFT) {
		data |= op->operands[2].shift_amount << 18 | op->operands[2].shift << 14;
	}
	return data;
}


void PaintLayerScrollableArea::DelayScrollOffsetClampScope::SetNeedsClamp(
    PaintLayerScrollableArea* scrollable_area) {
  if (!scrollable_area->NeedsScrollOffsetClamp()) {
    scrollable_area->SetNeedsScrollOffsetClamp(true);
    NeedsClampList().push_back(scrollable_area);
  }
}


FileSystemOperation::~FileSystemOperation() {
  if (file_writer_delegate_.get()) {
    FileSystemOperationContext* c =
        new FileSystemOperationContext(operation_context_);
    base::FileUtilProxy::RelayClose(
        file_system_context()->file_task_runner(),
        base::Bind(&FileSystemFileUtil::Close,
                   base::Unretained(src_util_),
                   base::Owned(c)),
        file_writer_delegate_->file(),
        base::FileUtilProxy::StatusCallback());
  }
}


config_ntpdsim(
	config_tree *ptree
	)
{
	printf("Configuring Simulator...\n");
	printf("Some ntpd-specific commands in the configuration file will be ignored.\n");

	config_tos(ptree);
	config_monitor(ptree);
	config_tinker(ptree);
	config_system_opts(ptree);
	config_logconfig(ptree);
	config_vars(ptree);
	config_sim(ptree);
}


void FrameLoaderClient::didDisplayInsecureContent()
{
    notImplemented();
}


RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa)
	{
	return ASN1_item_d2i_bio(ASN1_ITEM_rptr(RSAPublicKey), bp, rsa);
	}


static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version)
{
	zval *oid, *value, *type;
	char *a1, *a2, *a3, *a4, *a5, *a6, *a7;
	size_t a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len;
	zend_bool use_orignames = 0, suffix_keys = 0;
	zend_long timeout = SNMP_DEFAULT_TIMEOUT;
	zend_long retries = SNMP_DEFAULT_RETRIES;
	int argc = ZEND_NUM_ARGS();
	struct objid_query objid_query;
	php_snmp_session *session;
	int session_less_mode = (getThis() == NULL);
	php_snmp_object *snmp_object;
	php_snmp_object glob_snmp_object;

	objid_query.max_repetitions = -1;
	objid_query.non_repeaters = 0;
	objid_query.valueretrieval = SNMP_G(valueretrieval);
	objid_query.oid_increasing_check = TRUE;

	if (session_less_mode) {
		if (version == SNMP_VERSION_3) {
			if (st & SNMP_CMD_SET) {
				if (zend_parse_parameters(argc, "ssssssszzz|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
					&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
					RETURN_FALSE;
				}
			} else {
				/* SNMP_CMD_GET
				 * SNMP_CMD_GETNEXT
				 * SNMP_CMD_WALK
				 */
				if (zend_parse_parameters(argc, "sssssssz|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
					&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) {
					RETURN_FALSE;
				}
			}
		} else {
			if (st & SNMP_CMD_SET) {
				if (zend_parse_parameters(argc, "sszzz|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
					RETURN_FALSE;
				}
			} else {
				/* SNMP_CMD_GET
				 * SNMP_CMD_GETNEXT
				 * SNMP_CMD_WALK
				 */
				if (zend_parse_parameters(argc, "ssz|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) {
					RETURN_FALSE;
				}
			}
		}
	} else {
		if (st & SNMP_CMD_SET) {
			if (zend_parse_parameters(argc, "zzz", &oid, &type, &value) == FAILURE) {
				RETURN_FALSE;
			}
		} else if (st & SNMP_CMD_WALK) {
			if (zend_parse_parameters(argc, "z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) {
				RETURN_FALSE;
			}
			if (suffix_keys) {
				st |= SNMP_USE_SUFFIX_AS_KEYS;
			}
		} else if (st & SNMP_CMD_GET) {
			if (zend_parse_parameters(argc, "z|b", &oid, &use_orignames) == FAILURE) {
				RETURN_FALSE;
			}
			if (use_orignames) {
				st |= SNMP_ORIGINAL_NAMES_AS_KEYS;
			}
		} else {
			/* SNMP_CMD_GETNEXT
			 */
			if (zend_parse_parameters(argc, "z", &oid) == FAILURE) {
				RETURN_FALSE;
			}
		}
	}

	if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value)) {
		RETURN_FALSE;
	}

	if (session_less_mode) {
		if (netsnmp_session_init(&session, version, a1, a2, timeout, retries)) {
			efree(objid_query.vars);
			netsnmp_session_free(&session);
			RETURN_FALSE;
		}
		if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL)) {
			efree(objid_query.vars);
			netsnmp_session_free(&session);
			/* Warning message sent already, just bail out */
			RETURN_FALSE;
		}
	} else {
		zval *object = getThis();
		snmp_object = Z_SNMP_P(object);
		session = snmp_object->session;
		if (!session) {
			php_error_docref(NULL, E_WARNING, "Invalid or uninitialized SNMP object");
			efree(objid_query.vars);
			RETURN_FALSE;
		}

		if (snmp_object->max_oids > 0) {
			objid_query.step = snmp_object->max_oids;
			if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */
				objid_query.max_repetitions = snmp_object->max_oids;
			}
		}
		objid_query.oid_increasing_check = snmp_object->oid_increasing_check;
		objid_query.valueretrieval = snmp_object->valueretrieval;
		glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
		netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print);
		glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
		netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print);
		glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
		netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format);
	}

	if (objid_query.max_repetitions < 0) {
		objid_query.max_repetitions = 20; /* provide correct default value */
	}

	php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query);

	efree(objid_query.vars);

	if (session_less_mode) {
		netsnmp_session_free(&session);
	} else {
		netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print);
		netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print);
		netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format);
	}
}


static int fsmVerify(const char *path, rpmfi fi)
{
    int rc;
    int saveerrno = errno;
    struct stat dsb;
    mode_t mode = rpmfiFMode(fi);

    rc = fsmStat(path, 1, &dsb);
    if (rc)
	return rc;

    if (S_ISREG(mode)) {
	/* HP-UX (and other os'es) don't permit unlink on busy files. */
	char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL);
	rc = fsmRename(path, rmpath);
	/* XXX shouldn't we take unlink return code here? */
	if (!rc)
	    (void) fsmUnlink(rmpath);
	else
	    rc = RPMERR_UNLINK_FAILED;
	free(rmpath);
        return (rc ? rc : RPMERR_ENOENT);	/* XXX HACK */
    } else if (S_ISDIR(mode)) {
        if (S_ISDIR(dsb.st_mode)) return 0;
        if (S_ISLNK(dsb.st_mode)) {
            rc = fsmStat(path, 0, &dsb);
            if (rc == RPMERR_ENOENT) rc = 0;
            if (rc) return rc;
            errno = saveerrno;
            if (S_ISDIR(dsb.st_mode)) return 0;
        }
    } else if (S_ISLNK(mode)) {
        if (S_ISLNK(dsb.st_mode)) {
            char buf[8 * BUFSIZ];
            size_t len;
            rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len);
            errno = saveerrno;
            if (rc) return rc;
            if (rstreq(rpmfiFLink(fi), buf)) return 0;
        }
    } else if (S_ISFIFO(mode)) {
        if (S_ISFIFO(dsb.st_mode)) return 0;
    } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
        if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) &&
            (dsb.st_rdev == rpmfiFRdev(fi))) return 0;
    } else if (S_ISSOCK(mode)) {
        if (S_ISSOCK(dsb.st_mode)) return 0;
    }
    /* XXX shouldn't do this with commit/undo. */
    rc = fsmUnlink(path);
    if (rc == 0)	rc = RPMERR_ENOENT;
    return (rc ? rc : RPMERR_ENOENT);	/* XXX HACK */
}


      DSA_Signature_Operation(const DSA_PrivateKey& dsa,
                              const std::string& emsa,
                              RandomNumberGenerator& rng) :
         PK_Ops::Signature_with_EMSA(emsa),
         m_group(dsa.get_group()),
         m_x(dsa.get_x()),
         m_mod_q(dsa.group_q())
         {
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
         m_rfc6979_hash = hash_for_emsa(emsa);
#endif

         m_b = BigInt::random_integer(rng, 2, dsa.group_q());
         m_b_inv = inverse_mod(m_b, dsa.group_q());
         }


bool FunctionLibraryDefinition::Contains(const string& func) const {
  tf_shared_lock l(mu_);
  return function_defs_.find(func) != function_defs_.end();
}


BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)

{

    DriveInfo *dinfo;

    TAILQ_FOREACH(dinfo, &drives, next) {

        if (dinfo->bdrv == bdrv)

            return dinfo->onerror;

    }

    return BLOCK_ERR_STOP_ENOSPC;

}


static int gdbserver_open(int port)

{

    struct sockaddr_in sockaddr;

    int fd, ret;

    fd = socket(PF_INET, SOCK_STREAM, 0);

    if (fd < 0) {

        perror("socket");

        return -1;

    }

#ifndef _WIN32

    fcntl(fd, F_SETFD, FD_CLOEXEC);

#endif

    socket_set_fast_reuse(fd);

    sockaddr.sin_family = AF_INET;

    sockaddr.sin_port = htons(port);

    sockaddr.sin_addr.s_addr = 0;

    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));

    if (ret < 0) {

        perror("bind");

        close(fd);

        return -1;

    }

    ret = listen(fd, 0);

    if (ret < 0) {

        perror("listen");

        close(fd);

        return -1;

    }

    return fd;

}


archive_read_format_zip_cleanup(struct archive_read *a)
{
	struct zip *zip;
	struct zip_entry *zip_entry, *next_zip_entry;

	zip = (struct zip *)(a->format->data);
#ifdef HAVE_ZLIB_H
	if (zip->stream_valid)
		inflateEnd(&zip->stream);
	free(zip->uncompressed_buffer);
#endif
	if (zip->zip_entries) {
		zip_entry = zip->zip_entries;
		while (zip_entry != NULL) {
			next_zip_entry = zip_entry->next;
			archive_string_free(&zip_entry->rsrcname);
			free(zip_entry);
			zip_entry = next_zip_entry;
		}
	}
	free(zip->decrypted_buffer);
	if (zip->cctx_valid)
		archive_decrypto_aes_ctr_release(&zip->cctx);
	if (zip->hctx_valid)
		archive_hmac_sha1_cleanup(&zip->hctx);
	free(zip->iv);
	free(zip->erd);
	free(zip->v_data);
	archive_string_free(&zip->format_name);
	free(zip);
	(a->format->data) = NULL;
	return (ARCHIVE_OK);
}


int ha_myisam::index_next_same(uchar *buf,
			       const uchar *key __attribute__((unused)),
			       uint length __attribute__((unused)))
{
  int error;
  DBUG_ASSERT(inited==INDEX);
  MYSQL_INDEX_READ_ROW_START(table_share->db.str, table_share->table_name.str);
  ha_statistic_increment(&SSV::ha_read_next_count);
  do
  {
    error= mi_rnext_same(file,buf);
  } while (error == HA_ERR_RECORD_DELETED);
  table->status=error ? STATUS_NOT_FOUND: 0;
  MYSQL_INDEX_READ_ROW_DONE(error);
  return error;
}


int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
{
    RAMBlock *block;
    int ret = 0;

    RCU_READ_LOCK_GUARD();
    RAMBLOCK_FOREACH(block) {
        ret = func(block, opaque);
        if (ret) {
            break;
        }
    }
    return ret;
}


static double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
 {
    /* There is a serious error in the 2 and 4 bit grayscale transform because
     * the gamma table value (8 bits) is simply shifted, not rounded, so the
    * error in 4 bit grayscale gamma is up to the value below.  This is a hack
    * to allow pngvalid to succeed:
    *
    * TODO: fix this in libpng
    */
 if (out_depth == 2)
 return .73182-.5;

 if (out_depth == 4)
 return .90644-.5;

 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
 return pm->maxout16;

 /* This is the case where the value was calculated at 8-bit precision then
    * scaled to 16 bits.
    */
 else if (out_depth == 16)
 return pm->maxout8 * 257;

 else
 return pm->maxout8;
}


R_API void U(copy_type_info_to_stack_frame_list)(RList * type_list, RList * sf_list) {
	RListIter *iter, *iter_tmp;
	RBinJavaVerificationObj *ver_obj, *new_ver_obj;
	if (!type_list || !sf_list) {
		return;
	}
	r_list_foreach_safe (type_list, iter, iter_tmp, ver_obj) {
		new_ver_obj = (RBinJavaVerificationObj *) malloc (sizeof (RBinJavaVerificationObj));
		// FIXME: how to handle failed memory allocation?
		if (new_ver_obj && ver_obj) {
			memcpy (new_ver_obj, ver_obj, sizeof (RBinJavaVerificationObj));
			if (!r_list_append (sf_list, (void *) new_ver_obj)) {
				R_FREE (new_ver_obj);
			}
		} else {
			R_FREE (new_ver_obj);
		}
	}
}


static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt)
{
	ssize_t n;
	assert(cnt >= 0);
	assert(buf);

	JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt));
	jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
	n = m->len_ - m->pos_;
	cnt = JAS_MIN(n, cnt);
	memcpy(buf, &m->buf_[m->pos_], cnt);
	m->pos_ += cnt;
	return cnt;
}


const blink::WebView* RenderViewImpl::webview() const {
  return webview_;
}


static void spapr_rtc_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = spapr_rtc_realize;

    dc->vmsd = &vmstate_spapr_rtc;

    spapr_rtas_register(RTAS_GET_TIME_OF_DAY, "get-time-of-day",

                        rtas_get_time_of_day);

    spapr_rtas_register(RTAS_SET_TIME_OF_DAY, "set-time-of-day",

                        rtas_set_time_of_day);

}


void SupervisedUserService::ReportURL(const GURL& url,
                                      SuccessCallback callback) {
  if (url_reporter_)
    url_reporter_->ReportUrl(url, std::move(callback));
  else
    std::move(callback).Run(false);
}


void ieee80211_sta_ps_deliver_poll_response(struct sta_info *sta)
{
	u8 ignore_for_response = sta->sta.uapsd_queues;

	/*
	 * If all ACs are delivery-enabled then we should reply
	 * from any of them, if only some are enabled we reply
	 * only from the non-enabled ones.
	 */
	if (ignore_for_response == BIT(IEEE80211_NUM_ACS) - 1)
		ignore_for_response = 0;

	ieee80211_sta_ps_deliver_response(sta, 1, ignore_for_response,
					  IEEE80211_FRAME_RELEASE_PSPOLL);
}


MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception)
{
  RectangleInfo
    bounds;

  register Image
    *image,
    *next;

  assert((*images) != (const Image *) NULL);
  assert((*images)->signature == MagickCoreSignature);
  if ((*images)->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      (*images)->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=GetFirstImageInList(*images);
  for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next)
  {
    if ((image->columns != next->columns) || (image->rows != next->rows) ||
        (image->page.x != next->page.x) || (image->page.y != next->page.y))
      continue;
    bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception);
    if (bounds.x < 0)
      {
        /*
          Two images are the same, merge time delays and delete one.
        */
        size_t
          time;

        time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second);
        time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second);
        next->ticks_per_second=100L;
        next->delay=time*image->ticks_per_second/1000;
        next->iterations=image->iterations;
        *images=image;
        (void) DeleteImageFromList(images);
      }
  }
  *images=GetFirstImageInList(*images);
}


bool DrawingBuffer::SetupRGBEmulationForBlitFramebuffer() {

  if (want_alpha_channel_ || anti_aliasing_mode_ != kNone)
    return false;

  if (!(ShouldUseChromiumImage() &&
        ContextProvider()->GetCapabilities().chromium_image_rgb_emulation))
    return false;

  if (!back_color_buffer_)
    return false;

  if (!back_color_buffer_->image_id)
    return false;

  GLuint rgb_texture = back_color_buffer_->rgb_workaround_texture_id;
  GLenum target = GC3D_TEXTURE_RECTANGLE_ARB;
  if (!rgb_texture) {
    gl_->GenTextures(1, &rgb_texture);
    gl_->BindTexture(target, rgb_texture);
    gl_->TexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl_->TexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    gl_->TexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    gl_->TexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    gl_->BindTexImage2DWithInternalformatCHROMIUM(target, GL_RGB,
                                                  back_color_buffer_->image_id);
    back_color_buffer_->rgb_workaround_texture_id = rgb_texture;
  }

  gl_->FramebufferTexture2D(GL_DRAW_FRAMEBUFFER_ANGLE, GL_COLOR_ATTACHMENT0,
                            target, rgb_texture, 0);
  return true;
}


static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpointer)
{
    test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL);
    test->resizeView(200, 200);
    test->loadHtml("
WebKitGTK+ Inspector test
", 0);
    test->waitUntilLoadFinished();

    test->showAndWaitUntilFinished(false);
    test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webkit_web_inspector_get_web_view(test->m_inspector)));
    g_assert(!webkit_web_inspector_is_attached(test->m_inspector));
    Vector<InspectorTest::InspectorEvents>& events = test->m_events;
    g_assert_cmpint(events.size(), ==, 2);
    g_assert_cmpint(events[0], ==, InspectorTest::BringToFront);
    g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow);
    test->m_events.clear();

     test->resizeViewAndAttach();
     g_assert(webkit_web_inspector_is_attached(test->m_inspector));
     events = test->m_events;
     g_assert_cmpint(events.size(), ==, 1);
     g_assert_cmpint(events[0], ==, InspectorTest::Attach);
    test->m_events.clear();

    test->detachAndWaitUntilWindowOpened();
    g_assert(!webkit_web_inspector_is_attached(test->m_inspector));
    events = test->m_events;
    g_assert_cmpint(events.size(), ==, 2);
    g_assert_cmpint(events[0], ==, InspectorTest::Detach);
    g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow);
    test->m_events.clear();

    test->resizeViewAndAttach();
    g_assert(webkit_web_inspector_is_attached(test->m_inspector));
    test->m_events.clear();
    test->closeAndWaitUntilClosed();
    events = test->m_events;
    g_assert_cmpint(events.size(), ==, 2);
    g_assert_cmpint(events[0], ==, InspectorTest::Detach);
    g_assert_cmpint(events[1], ==, InspectorTest::Closed);
    test->m_events.clear();
}


_Pickler_FlushToFile(PicklerObject *self)
{
    PyObject *output, *result;

    assert(self->write != NULL);

    /* This will commit the frame first */
    output = _Pickler_GetString(self);
    if (output == NULL)
        return -1;

    result = _Pickle_FastCall(self->write, output);
    Py_XDECREF(result);
    return (result == NULL) ? -1 : 0;
}


static void fill_tone_level_array (QDM2Context *q, int flag)

{

    int i, sb, ch, sb_used;

    int tmp, tab;

    // This should never happen

    if (q->nb_channels <= 0)

        return;

    for (ch = 0; ch < q->nb_channels; ch++)

        for (sb = 0; sb < 30; sb++)

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

                if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))

                    tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+

                          q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];

                else

                    tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];

                if(tmp < 0)

                    tmp += 0xff;

                q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;

            }

    sb_used = QDM2_SB_USED(q->sub_sampling);

    if ((q->superblocktype_2_3 != 0) && !flag) {

        for (sb = 0; sb < sb_used; sb++)

            for (ch = 0; ch < q->nb_channels; ch++)

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

                    q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];

                    if (q->tone_level_idx[ch][sb][i] < 0)

                        q->tone_level[ch][sb][i] = 0;

                    else

                        q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];

                }

    } else {

        tab = q->superblocktype_2_3 ? 0 : 1;

        for (sb = 0; sb < sb_used; sb++) {

            if ((sb >= 4) && (sb <= 23)) {

                for (ch = 0; ch < q->nb_channels; ch++)

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

                        tmp = q->tone_level_idx_base[ch][sb][i / 8] -

                              q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -

                              q->tone_level_idx_mid[ch][sb - 4][i / 8] -

                              q->tone_level_idx_hi2[ch][sb - 4];

                        q->tone_level_idx[ch][sb][i] = tmp & 0xff;

                        if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))

                            q->tone_level[ch][sb][i] = 0;

                        else

                            q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];

                }

            } else {

                if (sb > 4) {

                    for (ch = 0; ch < q->nb_channels; ch++)

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

                            tmp = q->tone_level_idx_base[ch][sb][i / 8] -

                                  q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -

                                  q->tone_level_idx_hi2[ch][sb - 4];

                            q->tone_level_idx[ch][sb][i] = tmp & 0xff;

                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))

                                q->tone_level[ch][sb][i] = 0;

                            else

                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];

                    }

                } else {

                    for (ch = 0; ch < q->nb_channels; ch++)

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

                            tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];

                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))

                                q->tone_level[ch][sb][i] = 0;

                            else

                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];

                        }

                }

            }

        }

    }

    return;

}


char *PE_(r_bin_pe_get_cc)(RBinPEObj* pe) {
	if (pe && pe->nt_headers) {
		if (is_arm (pe)) {
			if (is_thumb (pe)) {
				return strdup ("arm16");
			}
			switch (pe->nt_headers->optional_header.Magic) {
			case PE_IMAGE_FILE_TYPE_PE32: return strdup ("arm32");
			case PE_IMAGE_FILE_TYPE_PE32PLUS: return strdup ("arm64");
			}
		} else {
			switch (pe->nt_headers->optional_header.Magic) {
			case PE_IMAGE_FILE_TYPE_PE32: return strdup ("cdecl");
			case PE_IMAGE_FILE_TYPE_PE32PLUS: return strdup ("ms");
			}
		}
	}
	return NULL;
}


bool SniffMPEG4(
 const sp<DataSource> &source, String8 *mimeType, float *confidence,
        sp<AMessage> *meta) {
 if (BetterSniffMPEG4(source, mimeType, confidence, meta)) {
 return true;
 }

 if (LegacySniffMPEG4(source, mimeType, confidence)) {
        ALOGW("Identified supported mpeg4 through LegacySniffMPEG4.");
 return true;
 }

 return false;
}


  Selector_List_Obj Parser::parse_selector_list(bool chroot)
  {
    bool reloop;
    bool had_linefeed = false;
    NESTING_GUARD(nestings);
    Complex_Selector_Obj sel;
    Selector_List_Obj group = SASS_MEMORY_NEW(Selector_List, pstate);
    group->media_block(last_media_block);

    if (peek_css< alternatives < end_of_file, exactly <'{'>, exactly <','> > >()) {
      css_error("Invalid CSS", " after ", ": expected selector, was ");
    }

    do {
      reloop = false;

      had_linefeed = had_linefeed || peek_newline();

      if (peek_css< alternatives < class_char < selector_list_delims > > >())
        break; // in case there are superfluous commas at the end

      // now parse the complex selector
      sel = parse_complex_selector(chroot);

      if (!sel) return group.detach();

      sel->has_line_feed(had_linefeed);

      had_linefeed = false;

      while (peek_css< exactly<','> >())
      {
        lex< css_comments >(false);
        // consume everything up and including the comma separator
        reloop = lex< exactly<','> >() != 0;
        // remember line break (also between some commas)
        had_linefeed = had_linefeed || peek_newline();
        // remember line break (also between some commas)
      }
      group->append(sel);
    }
    while (reloop);
    while (lex_css< kwd_optional >()) {
      group->is_optional(true);
    }
    // update for end position
    group->update_pstate(pstate);
    if (sel) sel->last()->has_line_break(false);
    return group.detach();
  }


static void GetConfigurationEntry(NDIS_HANDLE cfg, tConfigurationEntry *pEntry)
{
    NDIS_STATUS status;
    const char *statusName;
    NDIS_STRING name = {0};
    PNDIS_CONFIGURATION_PARAMETER pParam = NULL;
    NDIS_PARAMETER_TYPE ParameterType = NdisParameterInteger;
    NdisInitializeString(&name, (PUCHAR)pEntry->Name);
#pragma warning(push)
#pragma warning(disable:6102)
    NdisReadConfiguration(
        &status,
        &pParam,
        cfg,
        &name,
        ParameterType);
    if (status == NDIS_STATUS_SUCCESS)
    {
        ULONG ulValue = pParam->ParameterData.IntegerData;
        if (ulValue >= pEntry->ulMinimal && ulValue <= pEntry->ulMaximal)
        {
            pEntry->ulValue = ulValue;
            statusName = "value";
        }
        else
        {
            statusName = "out of range";
        }
    }
    else
    {
        statusName = "nothing";
    }
#pragma warning(pop)
    DPrintf(2, ("[%s] %s read for %s - 0x%x\n",
        __FUNCTION__,
        statusName,
        pEntry->Name,
        pEntry->ulValue));
    if (name.Buffer) NdisFreeString(name);
}


static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
	#define SIZEOF_FILE_NAME 255
	int i = 0;
	const char* basename;
	if (!dbg_data) {
		return 0;
	}
	switch (dbg_dir_entry->Type) {
	case IMAGE_DEBUG_TYPE_CODEVIEW:
		if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
			SCV_RSDS_HEADER rsds_hdr;
			init_rsdr_hdr (&rsds_hdr);
			if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
				bprintf ("Warning: Cannot read PE debug info\n");
				return 0;
			}
			snprintf (res->guidstr, GUIDSTR_LEN,
				"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
				rsds_hdr.guid.data1,
				rsds_hdr.guid.data2,
				rsds_hdr.guid.data3,
				rsds_hdr.guid.data4[0],
				rsds_hdr.guid.data4[1],
				rsds_hdr.guid.data4[2],
				rsds_hdr.guid.data4[3],
				rsds_hdr.guid.data4[4],
				rsds_hdr.guid.data4[5],
				rsds_hdr.guid.data4[6],
				rsds_hdr.guid.data4[7],
				rsds_hdr.age);
			basename = r_file_basename ((char*) rsds_hdr.file_name);
			strncpy (res->file_name, (const char*)
				basename, sizeof (res->file_name));
			res->file_name[sizeof (res->file_name) - 1] = 0;
			rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
		} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
			SCV_NB10_HEADER nb10_hdr;
			init_cv_nb10_header (&nb10_hdr);
			get_nb10 (dbg_data, &nb10_hdr);
			snprintf (res->guidstr, sizeof (res->guidstr),
				"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
			strncpy (res->file_name, (const char*)
				nb10_hdr.file_name, sizeof(res->file_name) - 1);
			res->file_name[sizeof (res->file_name) - 1] = 0;
			nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
		} else {
			bprintf ("CodeView section not NB10 or RSDS\n");
			return 0;
		}
		break;
	default:
		//bprintf("get_debug_info(): not supported type\n");
		return 0;
	}

	while (i < 33) {
		res->guidstr[i] = toupper ((int) res->guidstr[i]);
		i++;
	}

	return 1;
}


static void test_acpi_one(const char *params, test_data *data)

{

    char *args;

    uint8_t signature_low;

    uint8_t signature_high;

    uint16_t signature;

    int i;

    const char *device = "";

    if (!g_strcmp0(data->machine, MACHINE_Q35)) {

        device = ",id=hd -device ide-hd,drive=hd";

    }

    args = g_strdup_printf("-net none -display none %s -drive file=%s%s,",

                           params ? params : "", disk, device);

    qtest_start(args);

   /* Wait at most 1 minute */

#define TEST_DELAY (1 * G_USEC_PER_SEC / 10)

#define TEST_CYCLES MAX((60 * G_USEC_PER_SEC / TEST_DELAY), 1)

    /* Poll until code has run and modified memory.  Once it has we know BIOS

     * initialization is done.  TODO: check that IP reached the halt

     * instruction.

     */

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

        signature_low = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET);

        signature_high = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

        signature = (signature_high << 8) | signature_low;

        if (signature == SIGNATURE) {

            break;

        }

        g_usleep(TEST_DELAY);

    }

    g_assert_cmphex(signature, ==, SIGNATURE);

    test_acpi_rsdp_address(data);

    test_acpi_rsdp_table(data);

    test_acpi_rsdt_table(data);

    test_acpi_fadt_table(data);

    test_acpi_facs_table(data);

    test_acpi_dsdt_table(data);

    test_acpi_ssdt_tables(data);

    if (iasl) {

        test_acpi_asl(data);

    }

    qtest_quit(global_qtest);

    g_free(args);

}


static int jsi_FSTellProc(Jsi_Channel chan) { return ftell(_JSI_GETFP(chan,1));}


  UserGestureToken* GetUserGestureToken() const {
    return user_gesture_token_.get();
  }


static size_t fuse_send_read(struct fuse_req *req, struct fuse_io_priv *io,
			     loff_t pos, size_t count, fl_owner_t owner)
{
	struct file *file = io->file;
	struct fuse_file *ff = file->private_data;
	struct fuse_conn *fc = ff->fc;

	fuse_read_fill(req, file, pos, count, FUSE_READ);
	if (owner != NULL) {
		struct fuse_read_in *inarg = &req->misc.read.in;

		inarg->read_flags |= FUSE_READ_LOCKOWNER;
		inarg->lock_owner = fuse_lock_owner_id(fc, owner);
	}

	if (io->async)
		return fuse_async_req_send(fc, req, count, io);

	fuse_request_send(fc, req);
	return req->out.args[0].size;
}


    virtual void beginCommitOnCCThread(CCLayerTreeHostImpl* impl)
    {
        LayerChromium* root = m_layerTreeHost->rootLayer();
        if (!m_layerTreeHost->frameNumber())
            EXPECT_EQ(root->scrollPosition(), m_initialScroll);
        else {
            EXPECT_EQ(root->scrollPosition(), m_initialScroll + m_scrollAmount);

            root->setScrollPosition(m_secondScroll);
        }
    }


void rtl8xxxu_gen1_report_connect(struct rtl8xxxu_priv *priv,
				  u8 macid, bool connect)
{
	struct h2c_cmd h2c;

	memset(&h2c, 0, sizeof(struct h2c_cmd));

	h2c.joinbss.cmd = H2C_JOIN_BSS_REPORT;

	if (connect)
		h2c.joinbss.data = H2C_JOIN_BSS_CONNECT;
	else
		h2c.joinbss.data = H2C_JOIN_BSS_DISCONNECT;

	rtl8xxxu_gen1_h2c_cmd(priv, &h2c, sizeof(h2c.joinbss));
}