  void operator()(OpKernelContext* context, const Tensor& y_backprop_input,
                  const Tensor& x_input, const Tensor& scale_input,
                  const Tensor& mean_input, const Tensor& variance_input,
                  U epsilon, Tensor* x_backprop_output,
                  Tensor* scale_backprop_output, Tensor* offset_backprop_output,
                  bool use_reserved_space, TensorFormat tensor_format) {
    Tensor transformed_y_backprop_input;
    Tensor transformed_x_input;
    Tensor transformed_x_backprop_output;
    if (tensor_format == FORMAT_NCHW) {
      const int64 in_batch = GetTensorDim(x_input, tensor_format, 'N');
      const int64 in_rows = GetTensorDim(x_input, tensor_format, 'H');
      const int64 in_cols = GetTensorDim(x_input, tensor_format, 'W');
      const int64 in_depths = GetTensorDim(x_input, tensor_format, 'C');
      OP_REQUIRES_OK(context, context->allocate_temp(
                                  DataTypeToEnum<T>::value,
                                  ShapeFromFormat(FORMAT_NHWC, in_batch,
                                                  in_rows, in_cols, in_depths),
                                  &transformed_y_backprop_input));
      OP_REQUIRES_OK(context, context->allocate_temp(
                                  DataTypeToEnum<T>::value,
                                  ShapeFromFormat(FORMAT_NHWC, in_batch,
                                                  in_rows, in_cols, in_depths),
                                  &transformed_x_input));
      OP_REQUIRES_OK(context, context->allocate_temp(
                                  DataTypeToEnum<T>::value,
                                  ShapeFromFormat(FORMAT_NHWC, in_batch,
                                                  in_rows, in_cols, in_depths),
                                  &transformed_x_backprop_output));
      // Perform NCHW to NHWC
      std::vector<int32> perm = {0, 2, 3, 1};
      OP_REQUIRES_OK(
          context, ::tensorflow::DoTranspose(context->eigen_device<CPUDevice>(),
                                             y_backprop_input, perm,
                                             &transformed_y_backprop_input));
      OP_REQUIRES_OK(context, ::tensorflow::DoTranspose(
                                  context->eigen_device<CPUDevice>(), x_input,
                                  perm, &transformed_x_input));
    } else {
      transformed_y_backprop_input = y_backprop_input;
      transformed_x_input = x_input;
      transformed_x_backprop_output = *x_backprop_output;
    }
    typename TTypes<T, 4>::Tensor y_backprop(
        transformed_y_backprop_input.tensor<T, 4>());
    typename TTypes<T, 4>::Tensor x(transformed_x_input.tensor<T, 4>());
    typename TTypes<U>::ConstVec scale(scale_input.vec<U>());
    typename TTypes<U>::ConstVec mean(mean_input.vec<U>());
    typename TTypes<U>::ConstVec variance(variance_input.vec<U>());
    typename TTypes<T, 4>::Tensor x_backprop(
        transformed_x_backprop_output.tensor<T, 4>());
    typename TTypes<U>::Vec offset_backprop(offset_backprop_output->vec<U>());

    // Note: the following formulas are used to compute the gradients for
    // back propagation.
    // x_backprop = scale * rsqrt(variance + epsilon) *
    //              [y_backprop - mean(y_backprop) - (x - mean(x)) *
    //              mean(y_backprop * (x - mean(x))) / (variance + epsilon)]
    // scale_backprop = sum(y_backprop *
    //                  (x - mean(x)) * rsqrt(variance + epsilon))
    // offset_backprop = sum(y_backprop)

    const CPUDevice& d = context->eigen_device<CPUDevice>();
    const int depth = x.dimension(3);
    const int size = x.size();
    const int rest_size = size / depth;
    Eigen::DSizes<Eigen::Index, 2> rest_by_depth(rest_size, depth);

#if !defined(EIGEN_HAS_INDEX_LIST)
    Eigen::DSizes<Eigen::Index, 2> one_by_depth(1, depth);
    Eigen::array<int, 2> bcast_spec({rest_size, 1});
#else
    Eigen::IndexList<Eigen::type2index<1>, Eigen::Index> one_by_depth;
    one_by_depth.set(1, depth);
    Eigen::IndexList<Eigen::Index, Eigen::type2index<1>> bcast_spec;
    bcast_spec.set(0, rest_size);
#endif

    auto x_rest_by_depth = x.reshape(rest_by_depth).template cast<U>();
    U rest_size_inv = static_cast<U>(1.0f / static_cast<U>(rest_size));

    // Eigen is notoriously bad at reducing outer dimension, so we materialize
    // all temporary tensors that require reduction, and then use Eigen redux
    // functor, that is optimized for this particular task.
    //
    // All reductions are of this type: [rest_size, depth] -> [depth].
    using ScalarSum = Eigen::internal::scalar_sum_op<U>;
    const functor::ReduceOuterDimensions<T, U, U, ScalarSum> redux_sum_t;
    const functor::ReduceOuterDimensions<U, U, U, ScalarSum> redux_sum_u;

    auto scratch_dtype = DataTypeToEnum<U>::value;

    // Allocate a temporary workspace of [depth] shape.
    Tensor scratch_one_by_depth;
    OP_REQUIRES_OK(context, context->allocate_temp(scratch_dtype, {depth},
                                                   &scratch_one_by_depth));

    // Maybe allocate a temporary workspace of [rest_size, depth] shape.
    Tensor scratch_rest_by_depth;
    if (std::is_same<T, U>::value) {
      OP_REQUIRES(context,
                  scratch_rest_by_depth.CopyFrom(transformed_x_backprop_output,
                                                 {rest_size, depth}),
                  errors::Internal("Failed to copy a tensor"));
    } else {
      OP_REQUIRES_OK(context,
                     context->allocate_temp(scratch_dtype, {rest_size, depth},
                                            &scratch_rest_by_depth));
    }

    typename TTypes<U, 2>::Tensor scratch_tensor(
        scratch_rest_by_depth.tensor<U, 2>());
    typename TTypes<U>::Vec scratch_vector(scratch_one_by_depth.vec<U>());

    auto x_mean_rest_by_depth =
        mean.reshape(one_by_depth).broadcast(bcast_spec);
    auto x_centered = (x_rest_by_depth - x_mean_rest_by_depth);
    auto coef0_one_by_depth =
        (variance.reshape(one_by_depth) + epsilon).rsqrt();
    auto coef0_rest_by_depth = coef0_one_by_depth.broadcast(bcast_spec);
    auto x_scaled = x_centered * coef0_rest_by_depth;

    auto y_backprop_rest_by_depth =
        y_backprop.reshape(rest_by_depth).template cast<U>();

    // Compute `scale_backprop_output`:
    //   scale_backprop =
    //     (y_backprop_rest_by_depth * x_scaled).sum(reduce_dims)
    scratch_tensor.device(d) = y_backprop_rest_by_depth * x_scaled;
    redux_sum_u(d, rest_by_depth, scratch_rest_by_depth, scale_backprop_output);

    // Compute 'offset_backprop_output':
    //   offset_backprop =
    //     y_backprop_rest_by_depth.sum(reduce_dims)
    redux_sum_t(d, rest_by_depth, transformed_y_backprop_input,
                offset_backprop_output);
    auto y_backprop_sum = offset_backprop;

    auto y_backprop_sum_one_by_depth = y_backprop_sum.reshape(one_by_depth);
    auto y_backprop_mean_one_by_depth =
        y_backprop_sum_one_by_depth * rest_size_inv;
    auto y_backprop_mean_rest_by_depth =
        y_backprop_mean_one_by_depth.broadcast(bcast_spec);
    auto y_backprop_centered =
        y_backprop_rest_by_depth - y_backprop_mean_rest_by_depth;

    // Compute expression:
    //   y_backprop_centered_mean =
    //     (y_backprop_rest_by_depth * x_centered).mean(reduce_dims)
    scratch_tensor.device(d) = y_backprop_rest_by_depth * x_centered;
    redux_sum_u(d, rest_by_depth, scratch_rest_by_depth, &scratch_one_by_depth);
    auto y_backprop_centered_mean =
        scratch_vector.reshape(one_by_depth) / static_cast<U>(rest_size);

    auto coef1 = (scale.reshape(one_by_depth) * coef0_one_by_depth)
                     .broadcast(bcast_spec);
    auto coef2 = (coef0_one_by_depth.square() * y_backprop_centered_mean)
                     .broadcast(bcast_spec);

    x_backprop.reshape(rest_by_depth).device(d) =
        (coef1 * (y_backprop_centered - x_centered * coef2)).template cast<T>();

    if (tensor_format == FORMAT_NCHW) {
      // Perform NHWC to NCHW
      std::vector<int32> perm = {0, 3, 1, 2};
      OP_REQUIRES_OK(
          context, ::tensorflow::DoTranspose(context->eigen_device<CPUDevice>(),
                                             transformed_x_backprop_output,
                                             perm, x_backprop_output));
    }
  }


static gint get_record ( k12_t * file_data , FILE_T fh , gint64 file_offset , gboolean is_random , int * err , gchar * * err_info ) {
 guint8 * buffer = is_random ? file_data -> rand_read_buff : file_data -> seq_read_buff ;
 guint buffer_len = is_random ? file_data -> rand_read_buff_len : file_data -> seq_read_buff_len ;
 guint total_read = 0 ;
 guint left ;
 guint8 * writep ;
 # ifdef DEBUG_K12 guint actual_len ;
 # endif guint junky_offset = 8192 - ( gint ) ( ( file_offset - K12_FILE_HDR_LEN ) % 8192 ) ;
 K12_DBG ( 6 , ( "get_record: ENTER: junky_offset=%" G_GINT64_MODIFIER "d, file_offset=%" G_GINT64_MODIFIER "d" , junky_offset , file_offset ) ) ;
 if ( buffer == NULL ) {
 buffer = ( guint8 * ) g_malloc ( 8192 ) ;
 buffer_len = 8192 ;
 if ( is_random ) {
 file_data -> rand_read_buff = buffer ;
 file_data -> rand_read_buff_len = buffer_len ;
 }
 else {
 file_data -> seq_read_buff = buffer ;
 file_data -> seq_read_buff_len = buffer_len ;
 }
 }
 if ( junky_offset == 8192 ) {
 if ( ! file_skip ( fh , K12_FILE_BLOB_LEN , err ) ) return - 1 ;
 total_read += K12_FILE_BLOB_LEN ;
 }
 if ( ! wtap_read_bytes ( fh , buffer , 4 , err , err_info ) ) return - 1 ;
 total_read += 4 ;
 left = pntoh32 ( buffer + K12_RECORD_LEN ) ;
 # ifdef DEBUG_K12 actual_len = left ;
 # endif junky_offset -= 4 ;
 K12_DBG ( 5 , ( "get_record: GET length=%u" , left ) ) ;
 if ( left < 8 ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup_printf ( "k12: Record length %u is less than 8 bytes long" , left ) ;
 return - 1 ;
 }
 if ( left > WTAP_MAX_PACKET_SIZE ) {
 * err = WTAP_ERR_BAD_FILE ;
 * err_info = g_strdup_printf ( "k12: Record length %u is greater than the maximum %u" , left , WTAP_MAX_PACKET_SIZE ) ;
 return - 1 ;
 }
 while ( left > buffer_len ) {
 buffer = ( guint8 * ) g_realloc ( buffer , buffer_len *= 2 ) ;
 if ( is_random ) {
 file_data -> rand_read_buff = buffer ;
 file_data -> rand_read_buff_len = buffer_len ;
 }
 else {
 file_data -> seq_read_buff = buffer ;
 file_data -> seq_read_buff_len = buffer_len ;
 }
 }
 writep = buffer + 4 ;
 left -= 4 ;
 do {
 K12_DBG ( 6 , ( "get_record: looping left=%d junky_offset=%" G_GINT64_MODIFIER "d" , left , junky_offset ) ) ;
 if ( junky_offset > left ) {
 if ( ! wtap_read_bytes ( fh , writep , left , err , err_info ) ) return - 1 ;
 total_read += left ;
 break ;
 }
 else {
 if ( ! wtap_read_bytes ( fh , writep , junky_offset , err , err_info ) ) return - 1 ;
 total_read += junky_offset ;
 writep += junky_offset ;
 if ( ! file_skip ( fh , K12_FILE_BLOB_LEN , err ) ) return - 1 ;
 total_read += K12_FILE_BLOB_LEN ;
 left -= junky_offset ;
 junky_offset = 8192 ;
 }
 }
 while ( left ) ;
 K12_HEX_ASCII_DUMP ( 5 , file_offset , "GOT record" , buffer , actual_len ) ;
 return total_read ;
 }


void exit_mmap(struct mm_struct *mm)
{
	struct mmu_gather tlb;
	struct vm_area_struct *vma;
	unsigned long nr_accounted = 0;

	/* mm's last user has gone, and its about to be pulled down */
	mmu_notifier_release(mm);

	if (unlikely(mm_is_oom_victim(mm))) {
		/*
		 * Manually reap the mm to free as much memory as possible.
		 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
		 * this mm from further consideration.  Taking mm->mmap_sem for
		 * write after setting MMF_OOM_SKIP will guarantee that the oom
		 * reaper will not run on this mm again after mmap_sem is
		 * dropped.
		 *
		 * Nothing can be holding mm->mmap_sem here and the above call
		 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
		 * __oom_reap_task_mm() will not block.
		 *
		 * This needs to be done before calling munlock_vma_pages_all(),
		 * which clears VM_LOCKED, otherwise the oom reaper cannot
		 * reliably test it.
		 */
		(void)__oom_reap_task_mm(mm);

		set_bit(MMF_OOM_SKIP, &mm->flags);
		down_write(&mm->mmap_sem);
		up_write(&mm->mmap_sem);
	}

	if (mm->locked_vm) {
		vma = mm->mmap;
		while (vma) {
			if (vma->vm_flags & VM_LOCKED)
				munlock_vma_pages_all(vma);
			vma = vma->vm_next;
		}
	}

	arch_exit_mmap(mm);

	vma = mm->mmap;
	if (!vma)	/* Can happen if dup_mmap() received an OOM */
		return;

	lru_add_drain();
	flush_cache_mm(mm);
	tlb_gather_mmu(&tlb, mm, 0, -1);
	/* update_hiwater_rss(mm) here? but nobody should be looking */
	/* Use -1 here to ensure all VMAs in the mm are unmapped */
	unmap_vmas(&tlb, vma, 0, -1);
	free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
	tlb_finish_mmu(&tlb, 0, -1);

	/*
	 * Walk the list again, actually closing and freeing it,
	 * with preemption enabled, without holding any MM locks.
	 */
	while (vma) {
		if (vma->vm_flags & VM_ACCOUNT)
			nr_accounted += vma_pages(vma);
		vma = remove_vma(vma);
	}
	vm_unacct_memory(nr_accounted);
}


device_local_get_native_path (Device *device)
{
  return device->priv->native_path;
}


static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    MOVFragment *frag = &c->fragment;

    AVStream *st = NULL;

    MOVStreamContext *sc;

    MOVStts *ctts_data;

    uint64_t offset;

    int64_t dts;

    int data_offset = 0;

    unsigned entries, first_sample_flags = frag->flags;

    int flags, distance, i, found_keyframe = 0, err;

    for (i = 0; i < c->fc->nb_streams; i++) {

        if (c->fc->streams[i]->id == frag->track_id) {

            st = c->fc->streams[i];

            break;

        }

    }

    if (!st) {

        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);

        return AVERROR_INVALIDDATA;

    }

    sc = st->priv_data;

    if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)

        return 0;

    avio_r8(pb); /* version */

    flags = avio_rb24(pb);

    entries = avio_rb32(pb);

    av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);

    /* Always assume the presence of composition time offsets.

     * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.

     *  1) in the initial movie, there are no samples.

     *  2) in the first movie fragment, there is only one sample without composition time offset.

     *  3) in the subsequent movie fragments, there are samples with composition time offset. */

    if (!sc->ctts_count && sc->sample_count)

    {

        /* Complement ctts table if moov atom doesn't have ctts atom. */

        ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));

        if (!ctts_data)

            return AVERROR(ENOMEM);

        sc->ctts_data = ctts_data;

        sc->ctts_data[sc->ctts_count].count = sc->sample_count;

        sc->ctts_data[sc->ctts_count].duration = 0;

        sc->ctts_count++;

    }

    if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))

        return AVERROR_INVALIDDATA;

    if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,

                                 sizeof(*sc->ctts_data))) < 0) {

        sc->ctts_count = 0;

        return err;

    }

    if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);

    if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);

    dts    = sc->track_end - sc->time_offset;

    offset = frag->base_data_offset + data_offset;

    distance = 0;

    av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);

    for (i = 0; i < entries && !pb->eof_reached; i++) {

        unsigned sample_size = frag->size;

        int sample_flags = i ? frag->flags : first_sample_flags;

        unsigned sample_duration = frag->duration;

        int keyframe = 0;

        int sample_cts = 0;

        int64_t cts;

        if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);

        if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);

        if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);

        if (flags & MOV_TRUN_SAMPLE_CTS)      sample_cts      = avio_rb32(pb);

        sc->ctts_data[sc->ctts_count].count    = 1;

        sc->ctts_data[sc->ctts_count].duration = sample_cts;

        mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);

        if (frag->time != AV_NOPTS_VALUE) {

            if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {

                int64_t pts = frag->time;

                av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64

                        " sc->dts_shift %d ctts.duration %d"

                        " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,

                        sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,

                        sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);

                dts = pts - sc->dts_shift;

                if (flags & MOV_TRUN_SAMPLE_CTS) {

                    dts -= sc->ctts_data[sc->ctts_count].duration;

                } else {

                    dts -= sc->time_offset;

                }

                av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);

            } else {

                dts = frag->time;

                av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64

                        ", using it for dts\n", dts);

            }

            frag->time = AV_NOPTS_VALUE;

        }

        cts = dts + sample_cts;

        sc->ctts_count++;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

            keyframe = 1;

        else if (!found_keyframe)

            keyframe = found_keyframe =

                !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |

                                  MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));

        if (keyframe)

            distance = 0;

        err = av_add_index_entry(st, offset, INT64_MAX/2, sample_size, distance,

                                 keyframe ? AVINDEX_KEYFRAME : 0);

        if (err < 0) {

            av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");

        } else

            st->index_entries[st->nb_index_entries - 1].timestamp = cts;

        av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", cts %"PRId64", "

                "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,

                offset, cts, sample_size, distance, keyframe);

        distance++;

        dts += sample_duration;

        offset += sample_size;

        sc->data_size += sample_size;

        sc->duration_for_fps += sample_duration;

        sc->nb_frames_for_fps ++;

    }

    if (pb->eof_reached)

        return AVERROR_EOF;

    frag->implicit_offset = offset;

    st->duration = sc->track_end = dts + sc->time_offset;

    return 0;

}


virDomainDefineXML(virConnectPtr conn, const char *xml)
{
    VIR_DEBUG("conn=%p, xml=%s", conn, NULLSTR(xml));

    virResetLastError();

    virCheckConnectReturn(conn, NULL);
    virCheckReadOnlyGoto(conn->flags, error);
    virCheckNonNullArgGoto(xml, error);

    if (conn->driver->domainDefineXML) {
        virDomainPtr ret;
        ret = conn->driver->domainDefineXML(conn, xml);
        if (!ret)
            goto error;
        return ret;
    }

    virReportUnsupportedError();

 error:
    virDispatchError(conn);
    return NULL;
}


RSA * d2i_RSA_PUBKEY_fp ( FILE * fp , RSA * * rsa ) {
 return ASN1_d2i_fp ( ( void * ( * ) ( void ) ) RSA_new , ( D2I_OF ( void ) ) d2i_RSA_PUBKEY , fp , ( void * * ) rsa ) ;
 }


SECURITY_STATUS SEC_ENTRY ApplyControlToken(PCtxtHandle phContext, PSecBufferDesc pInput)
{
	return SEC_E_OK;
}


char *curl_easy_escape(CURL *handle, const char *string, int inlength)
{
  size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;
  char *ns;
  char *testing_ptr = NULL;
  unsigned char in; /* we need to treat the characters unsigned */
  size_t newlen = alloc;
  size_t strindex=0;
  size_t length;
  CURLcode res;

  ns = malloc(alloc);
  if(!ns)
    return NULL;

  length = alloc-1;
  while(length--) {
    in = *string;

    if(Curl_isunreserved(in))
      /* just copy this */
      ns[strindex++]=in;
    else {
      /* encode it */
      newlen += 2; /* the size grows with two, since this'll become a %XX */
      if(newlen > alloc) {
        alloc *= 2;
        testing_ptr = realloc(ns, alloc);
        if(!testing_ptr) {
          free( ns );
          return NULL;
        }
        else {
          ns = testing_ptr;
        }
      }

      res = Curl_convert_to_network(handle, &in, 1);
      if(res) {
        /* Curl_convert_to_network calls failf if unsuccessful */
        free(ns);
        return NULL;
      }

      snprintf(&ns[strindex], 4, "%%%02X", in);

      strindex+=3;
    }
    string++;
  }
  ns[strindex]=0; /* terminate it */
  return ns;
}


  std::string GetUrlPath(const std::string& url) const {
    GURL gurl(url);
    return gurl.path();
  }


void seq_printf(struct seq_file *m, const char *f, ...)
{
	va_list args;

	va_start(args, f);
	seq_vprintf(m, f, args);
	va_end(args);
}


gfx::AcceleratedWidget Compositor::widget() const {
  DCHECK(widget_valid_);
  return widget_;
}


GF_Err gf_isom_set_timescale(GF_ISOFile *movie, u32 timeScale)
{
	GF_TrackBox *trak;
	u32 i;
	GF_Err e;
	if (!timeScale) return GF_BAD_PARAM;
	e = CanAccessMovie(movie, GF_ISOM_OPEN_WRITE);
	if (e) return e;
	e = gf_isom_insert_moov(movie);
	if (e) return e;

	if (movie->moov->mvhd->timeScale == timeScale) return GF_OK;

	/*rewrite all durations and edit lists*/
	movie->moov->mvhd->duration *= timeScale;
	movie->moov->mvhd->duration /= movie->moov->mvhd->timeScale;
	if (movie->moov->mvex && movie->moov->mvex->mehd) {
		movie->moov->mvex->mehd->fragment_duration *= timeScale;
		movie->moov->mvex->mehd->fragment_duration /= movie->moov->mvhd->timeScale;
	}

	i=0;
	while ((trak = (GF_TrackBox*)gf_list_enum(movie->moov->trackList, &i))) {
		trak->Header->duration *= timeScale;
		trak->Header->duration /= movie->moov->mvhd->timeScale;

		if (trak->editBox && trak->editBox->editList) {
			u32 j, count = gf_list_count(trak->editBox->editList->entryList);
			for (j=0; j<count; j++) {
				GF_EdtsEntry *ent = (GF_EdtsEntry *)gf_list_get(trak->editBox->editList->entryList, j);
				ent->segmentDuration *= timeScale;
				ent->segmentDuration /= movie->moov->mvhd->timeScale;
			}
		}
	}
	if (movie->moov->mvex && movie->moov->mvex->mehd) {
		movie->moov->mvex->mehd->fragment_duration *= timeScale;
		movie->moov->mvex->mehd->fragment_duration /= movie->moov->mvhd->timeScale;
	}
	movie->moov->mvhd->timeScale = timeScale;
	movie->interleavingTime = timeScale;
	return GF_OK;
}


void mem_cgroup_replace_page_cache(struct page *oldpage,
				  struct page *newpage)
{
	struct mem_cgroup *memcg;
	struct page_cgroup *pc;
	enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;

	if (mem_cgroup_disabled())
		return;

	pc = lookup_page_cgroup(oldpage);
	/* fix accounting on old pages */
	lock_page_cgroup(pc);
	memcg = pc->mem_cgroup;
	mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -1);
	ClearPageCgroupUsed(pc);
	unlock_page_cgroup(pc);

	if (PageSwapBacked(oldpage))
		type = MEM_CGROUP_CHARGE_TYPE_SHMEM;

	/*
	 * Even if newpage->mapping was NULL before starting replacement,
	 * the newpage may be on LRU(or pagevec for LRU) already. We lock
	 * LRU while we overwrite pc->mem_cgroup.
	 */
	__mem_cgroup_commit_charge(memcg, newpage, 1, pc, type, true);
}


PHP_FUNCTION(openssl_private_decrypt)
{
	zval **key, *crypted;
	EVP_PKEY *pkey;
	int cryptedlen;
	unsigned char *cryptedbuf = NULL;
	unsigned char *crypttemp;
	int successful = 0;
	long padding = RSA_PKCS1_PADDING;
	long keyresource = -1;
	char * data;
	int data_len;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szZ|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
		return;
	}
	RETVAL_FALSE;

	pkey = php_openssl_evp_from_zval(key, 0, "", 0, &keyresource TSRMLS_CC);
	if (pkey == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "key parameter is not a valid private key");
		RETURN_FALSE;
	}

	cryptedlen = EVP_PKEY_size(pkey);
	crypttemp = emalloc(cryptedlen + 1);

	switch (pkey->type) {
		case EVP_PKEY_RSA:
		case EVP_PKEY_RSA2:
			cryptedlen = RSA_private_decrypt(data_len,
					(unsigned char *)data,
					crypttemp,
					pkey->pkey.rsa,
					padding);
			if (cryptedlen != -1) {
				cryptedbuf = emalloc(cryptedlen + 1);
				memcpy(cryptedbuf, crypttemp, cryptedlen);
				successful = 1;
			}
			break;
		default:
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "key type not supported in this PHP build!");
	}

	efree(crypttemp);

	if (successful) {
		zval_dtor(crypted);
		cryptedbuf[cryptedlen] = '\0';
		ZVAL_STRINGL(crypted, (char *)cryptedbuf, cryptedlen, 0);
		cryptedbuf = NULL;
		RETVAL_TRUE;
	}

	if (keyresource == -1) {
		EVP_PKEY_free(pkey);
	}
	if (cryptedbuf) {
		efree(cryptedbuf);
	}
}


void init_revisions(struct rev_info *revs, const char *prefix)
{
	memset(revs, 0, sizeof(*revs));

	revs->abbrev = DEFAULT_ABBREV;
	revs->ignore_merges = 1;
	revs->simplify_history = 1;
	DIFF_OPT_SET(&revs->pruning, RECURSIVE);
	DIFF_OPT_SET(&revs->pruning, QUICK);
	revs->pruning.add_remove = file_add_remove;
	revs->pruning.change = file_change;
	revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
	revs->dense = 1;
	revs->prefix = prefix;
	revs->max_age = -1;
	revs->min_age = -1;
	revs->skip_count = -1;
	revs->max_count = -1;
	revs->max_parents = -1;

	revs->commit_format = CMIT_FMT_DEFAULT;

	init_grep_defaults();
	grep_init(&revs->grep_filter, prefix);
	revs->grep_filter.status_only = 1;
	revs->grep_filter.regflags = REG_NEWLINE;

	diff_setup(&revs->diffopt);
	if (prefix && !revs->diffopt.prefix) {
		revs->diffopt.prefix = prefix;
		revs->diffopt.prefix_length = strlen(prefix);
	}

	revs->notes_opt.use_default_notes = -1;
}


static int load_dh_params(SSL_CTX *ctx, char *file)
{
    DH *ret = 0;
    BIO *bio;

    if ((bio = BIO_new_file(file, "r")) == NULL) {
        spice_warning("Could not open DH file");
        return -1;
    }

    ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    BIO_free(bio);
    if (ret == 0) {
        spice_warning("Could not read DH params");
        return -1;
    }

    if (SSL_CTX_set_tmp_dh(ctx, ret) < 0) {
        spice_warning("Could not set DH params");
        return -1;
    }

    return 0;
}


static int encode_apng(AVCodecContext *avctx, AVPacket *pkt,
                       const AVFrame *pict, int *got_packet)
{
    PNGEncContext *s = avctx->priv_data;
    int ret;
    int enc_row_size;
    size_t max_packet_size;
    APNGFctlChunk fctl_chunk = {0};
    if (pict && avctx->codec_id == AV_CODEC_ID_APNG && s->color_type == PNG_COLOR_TYPE_PALETTE) {
        uint32_t checksum = ~av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), ~0U, pict->data[1], 256 * sizeof(uint32_t));
        if (avctx->frame_number == 0) {
            s->palette_checksum = checksum;
        } else if (checksum != s->palette_checksum) {
            av_log(avctx, AV_LOG_ERROR,
                   "Input contains more than one unique palette. APNG does not support multiple palettes.\n");
            return -1;
        }
    }
    enc_row_size    = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
    max_packet_size =
        AV_INPUT_BUFFER_MIN_SIZE + // headers
        avctx->height * (
            enc_row_size +
            (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE)
        );
    if (max_packet_size > INT_MAX)
        return AVERROR(ENOMEM);
    if (avctx->frame_number == 0) {
        s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE);
        if (!avctx->extradata)
            return AVERROR(ENOMEM);
        ret = encode_headers(avctx, pict);
        if (ret < 0)
            return ret;
        avctx->extradata_size = s->bytestream - avctx->extradata;
        s->last_frame_packet = av_malloc(max_packet_size);
        if (!s->last_frame_packet)
            return AVERROR(ENOMEM);
    } else if (s->last_frame) {
        ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
        if (ret < 0)
            return ret;
        memcpy(pkt->data, s->last_frame_packet, s->last_frame_packet_size);
        pkt->size = s->last_frame_packet_size;
        pkt->pts = pkt->dts = s->last_frame->pts;
    }
    if (pict) {
        s->bytestream_start =
        s->bytestream       = s->last_frame_packet;
        s->bytestream_end   = s->bytestream + max_packet_size;
        // We're encoding the frame first, so we have to do a bit of shuffling around
        // to have the image data write to the correct place in the buffer
        fctl_chunk.sequence_number = s->sequence_number;
        ++s->sequence_number;
        s->bytestream += 26 + 12;
        ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl);
        if (ret < 0)
            return ret;
        fctl_chunk.delay_num = 0; // delay filled in during muxing
        fctl_chunk.delay_den = 0;
    } else {
        s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE;
    }
    if (s->last_frame) {
        uint8_t* last_fctl_chunk_start = pkt->data;
        uint8_t buf[26];
        AV_WB32(buf + 0, s->last_frame_fctl.sequence_number);
        AV_WB32(buf + 4, s->last_frame_fctl.width);
        AV_WB32(buf + 8, s->last_frame_fctl.height);
        AV_WB32(buf + 12, s->last_frame_fctl.x_offset);
        AV_WB32(buf + 16, s->last_frame_fctl.y_offset);
        AV_WB16(buf + 20, s->last_frame_fctl.delay_num);
        AV_WB16(buf + 22, s->last_frame_fctl.delay_den);
        buf[24] = s->last_frame_fctl.dispose_op;
        buf[25] = s->last_frame_fctl.blend_op;
        png_write_chunk(&last_fctl_chunk_start, MKTAG('f', 'c', 'T', 'L'), buf, 26);
        *got_packet = 1;
    }
    if (pict) {
        if (!s->last_frame) {
            s->last_frame = av_frame_alloc();
            if (!s->last_frame)
                return AVERROR(ENOMEM);
        } else if (s->last_frame_fctl.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
            if (!s->prev_frame) {
                s->prev_frame = av_frame_alloc();
                if (!s->prev_frame)
                    return AVERROR(ENOMEM);
                s->prev_frame->format = pict->format;
                s->prev_frame->width = pict->width;
                s->prev_frame->height = pict->height;
                if ((ret = av_frame_get_buffer(s->prev_frame, 32)) < 0)
                    return ret;
            }
            // Do disposal, but not blending
            memcpy(s->prev_frame->data[0], s->last_frame->data[0],
                   s->last_frame->linesize[0] * s->last_frame->height);
            if (s->last_frame_fctl.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
                uint32_t y;
                uint8_t bpp = (s->bits_per_pixel + 7) >> 3;
                for (y = s->last_frame_fctl.y_offset; y < s->last_frame_fctl.y_offset + s->last_frame_fctl.height; ++y) {
                    size_t row_start = s->last_frame->linesize[0] * y + bpp * s->last_frame_fctl.x_offset;
                    memset(s->prev_frame->data[0] + row_start, 0, bpp * s->last_frame_fctl.width);
                }
            }
        }
        av_frame_unref(s->last_frame);
        ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
        if (ret < 0)
            return ret;
        s->last_frame_fctl = fctl_chunk;
        s->last_frame_packet_size = s->bytestream - s->bytestream_start;
    } else {
        av_frame_free(&s->last_frame);
    }
    return 0;
}


void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,

                         unsigned int pts_num, unsigned int pts_den)

{

    AVRational new_tb;

    if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){

        if(new_tb.num != pts_num)

            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);

    }else

        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);

    if(new_tb.num <= 0 || new_tb.den <= 0) {

        av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);

        return;

    }

    s->time_base = new_tb;

    s->pts_wrap_bits = pts_wrap_bits;

}


const char *bdrv_get_format_name(BlockDriverState *bs)

{

    return bs->drv ? bs->drv->format_name : NULL;

}


static int rv20_decode_picture_header(MpegEncContext *s)

{

    int seq, mb_pos, i;

    if(s->avctx->sub_id == 0x30202002 || s->avctx->sub_id == 0x30203002){

        if (get_bits(&s->gb, 3)){

            av_log(s->avctx, AV_LOG_ERROR, "unknown triplet set\n");

            return -1;

        }

    }

    i= get_bits(&s->gb, 2);

    switch(i){

    case 0: s->pict_type= I_TYPE; break;

    case 1: s->pict_type= I_TYPE; break; //hmm ...

    case 2: s->pict_type= P_TYPE; break;

    case 3: s->pict_type= B_TYPE; break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "unknown frame type\n");

        return -1;

    }

    if (get_bits(&s->gb, 1)){

        av_log(s->avctx, AV_LOG_ERROR, "unknown bit set\n");

        return -1;

    }

    s->qscale = get_bits(&s->gb, 5);

    if(s->qscale==0){

        av_log(s->avctx, AV_LOG_ERROR, "error, qscale:0\n");

        return -1;

    }

    if(s->avctx->sub_id == 0x30203002){

        if (get_bits(&s->gb, 1)){

            av_log(s->avctx, AV_LOG_ERROR, "unknown bit2 set\n");

            return -1;

        }

    }

    if(s->avctx->has_b_frames){

        if (get_bits(&s->gb, 1)){

            av_log(s->avctx, AV_LOG_ERROR, "unknown bit3 set\n");

            return -1;

        }

        seq= get_bits(&s->gb, 15);

    }else

        seq= get_bits(&s->gb, 8)*128;

//printf("%d\n", seq);

    seq |= s->time &~0x7FFF;

    if(seq - s->time >  0x4000) seq -= 0x8000;

    if(seq - s->time < -0x4000) seq += 0x8000;

    if(seq != s->time){

        if(s->pict_type!=B_TYPE){

            s->time= seq;

            s->pp_time= s->time - s->last_non_b_time;

            s->last_non_b_time= s->time;

        }else{

            s->time= seq;

            s->pb_time= s->pp_time - (s->last_non_b_time - s->time);

            if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){

                printf("messed up order, seeking?, skiping current b frame\n");

                return FRAME_SKIPED;

            }

        }

    }

//    printf("%d %d %d %d %d\n", seq, (int)s->time, (int)s->last_non_b_time, s->pp_time, s->pb_time);

    mb_pos= ff_h263_decode_mba(s);

    s->no_rounding= get_bits1(&s->gb);

    s->f_code = 1;

    s->unrestricted_mv = 1;

    s->h263_aic= s->pict_type == I_TYPE;

//    s->alt_inter_vlc=1;

//    s->obmc=1;

//    s->umvplus=1;

    s->modified_quant=1;

    s->loop_filter=1;

    if(s->avctx->debug & FF_DEBUG_PICT_INFO){

            av_log(s->avctx, AV_LOG_INFO, "num:%5d x:%2d y:%2d type:%d qscale:%2d rnd:%d\n",

                   seq, s->mb_x, s->mb_y, s->pict_type, s->qscale, s->no_rounding);

    }

    assert(s->pict_type != B_TYPE || !s->low_delay);

    return s->mb_width*s->mb_height - mb_pos;

}


void chpl_del(GF_Box *s)
{
	GF_ChapterListBox *ptr = (GF_ChapterListBox *) s;
	if (ptr == NULL) return;
	while (gf_list_count(ptr->list)) {
		GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, 0);
		if (ce->name) gf_free(ce->name);
		gf_free(ce);
		gf_list_rem(ptr->list, 0);
	}
	gf_list_del(ptr->list);
	gf_free(ptr);
}


asn1_get_octet_der (const unsigned char *der, int der_len,
		    int *ret_len, unsigned char *str, int str_size,
		    int *str_len)
{
  int len_len = 0;

  if (der_len <= 0)
    return ASN1_GENERIC_ERROR;

  *str_len = asn1_get_length_der (der, der_len, &len_len);

  if (*str_len < 0)
    return ASN1_DER_ERROR;

  *ret_len = *str_len + len_len;
  if (str_size >= *str_len)
    {
      if (*str_len > 0 && str != NULL)
        memcpy (str, der + len_len, *str_len);
    }
  else
    {
      return ASN1_MEM_ERROR;
    }

  return ASN1_SUCCESS;
}


static int32_t parse_gain(const char *gain)

{

    char *fraction;

    int  scale = 10000;

    int32_t mb = 0;

    int db;

    if (!gain)

        return INT32_MIN;

    gain += strspn(gain, " \t");

    db = strtol(gain, &fraction, 0);

    if (*fraction++ == '.') {

        while (av_isdigit(*fraction) && scale) {

            mb += scale * (*fraction - '0');

            scale /= 10;

            fraction++;

        }

    }

    if (abs(db) > (INT32_MAX - mb) / 100000)

        return INT32_MIN;

    return db * 100000 + FFSIGN(db) * mb;

}


void pdf_clear_err(struct pdf_doc *pdf)
{
    if (!pdf)
        return;
    pdf->errstr[0] = '\0';
    pdf->errval = 0;
}


int jbig2_page_info ( Jbig2Ctx * ctx , Jbig2Segment * segment , const uint8_t * segment_data ) {
 Jbig2Page * page ;
 page = & ( ctx -> pages [ ctx -> current_page ] ) ;
 if ( ( page -> number != 0 ) && ( ( page -> state == JBIG2_PAGE_NEW ) || ( page -> state == JBIG2_PAGE_FREE ) ) ) {
 page -> state = JBIG2_PAGE_COMPLETE ;
 jbig2_error ( ctx , JBIG2_SEVERITY_WARNING , segment -> number , "unexpected page info segment, marking previous page finished" ) ;
 }
 {
 int index , j ;
 index = ctx -> current_page ;
 while ( ctx -> pages [ index ] . state != JBIG2_PAGE_FREE ) {
 index ++ ;
 if ( index >= ctx -> max_page_index ) {
 ctx -> pages = jbig2_renew ( ctx , ctx -> pages , Jbig2Page , ( ctx -> max_page_index <<= 2 ) ) ;
 for ( j = index ;
 j < ctx -> max_page_index ;
 j ++ ) {
 ctx -> pages [ j ] . state = JBIG2_PAGE_FREE ;
 ctx -> pages [ j ] . number = 0 ;
 ctx -> pages [ j ] . image = NULL ;
 }
 }
 }
 page = & ( ctx -> pages [ index ] ) ;
 ctx -> current_page = index ;
 page -> state = JBIG2_PAGE_NEW ;
 page -> number = segment -> page_association ;
 }
 if ( segment -> data_length < 19 ) {
 return jbig2_error ( ctx , JBIG2_SEVERITY_FATAL , segment -> number , "segment too short" ) ;
 }
 page -> width = jbig2_get_uint32 ( segment_data ) ;
 page -> height = jbig2_get_uint32 ( segment_data + 4 ) ;
 page -> x_resolution = jbig2_get_uint32 ( segment_data + 8 ) ;
 page -> y_resolution = jbig2_get_uint32 ( segment_data + 12 ) ;
 page -> flags = segment_data [ 16 ] ;
 {
 int16_t striping = jbig2_get_int16 ( segment_data + 17 ) ;
 if ( striping & 0x8000 ) {
 page -> striped = TRUE ;
 page -> stripe_size = striping & 0x7FFF ;
 }
 else {
 page -> striped = FALSE ;
 page -> stripe_size = 0 ;
 }
 }
 if ( page -> height == 0xFFFFFFFF && page -> striped == FALSE ) {
 jbig2_error ( ctx , JBIG2_SEVERITY_WARNING , segment -> number , "height is unspecified but page is not markes as striped" ) ;
 page -> striped = TRUE ;
 }
 page -> end_row = 0 ;
 if ( segment -> data_length > 19 ) {
 jbig2_error ( ctx , JBIG2_SEVERITY_WARNING , segment -> number , "extra data in segment" ) ;
 }
 dump_page_info ( ctx , segment , page ) ;
 if ( page -> height == 0xFFFFFFFF ) {
 page -> image = jbig2_image_new ( ctx , page -> width , page -> stripe_size ) ;
 }
 else {
 page -> image = jbig2_image_new ( ctx , page -> width , page -> height ) ;
 }
 if ( page -> image == NULL ) {
 return jbig2_error ( ctx , JBIG2_SEVERITY_FATAL , segment -> number , "failed to allocate buffer for page image" ) ;
 }
 else {
 jbig2_image_clear ( ctx , page -> image , ( page -> flags & 4 ) ) ;
 jbig2_error ( ctx , JBIG2_SEVERITY_DEBUG , segment -> number , "allocated %dx%d page image (%d bytes)" , page -> image -> width , page -> image -> height , page -> image -> stride * page -> image -> height ) ;
 }
 return 0 ;
 }


static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
{
    BDRVQcow2State *s = bs->opaque;
    uint64_t old_l2_offset;
    uint64_t *l2_table = NULL;
    int64_t l2_offset;
    int ret;
    old_l2_offset = s->l1_table[l1_index];
    trace_qcow2_l2_allocate(bs, l1_index);
    /* allocate a new l2 entry */
    l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
    if (l2_offset < 0) {
        ret = l2_offset;
    ret = qcow2_cache_flush(bs, s->refcount_block_cache);
    if (ret < 0) {
    /* allocate a new entry in the l2 cache */
    trace_qcow2_l2_allocate_get_empty(bs, l1_index);
    ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
    if (ret < 0) {
    l2_table = *table;
    if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
        /* if there was no old l2 table, clear the new table */
        memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
    } else {
        uint64_t* old_table;
        /* if there was an old l2 table, read it from the disk */
        BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
        ret = qcow2_cache_get(bs, s->l2_table_cache,
            old_l2_offset & L1E_OFFSET_MASK,
            (void**) &old_table);
        if (ret < 0) {
        memcpy(l2_table, old_table, s->cluster_size);
        qcow2_cache_put(bs, s->l2_table_cache, (void **) &old_table);
    /* write the l2 table to the file */
    BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
    trace_qcow2_l2_allocate_write_l2(bs, l1_index);
    qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
    ret = qcow2_cache_flush(bs, s->l2_table_cache);
    if (ret < 0) {
    /* update the L1 entry */
    trace_qcow2_l2_allocate_write_l1(bs, l1_index);
    s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
    ret = qcow2_write_l1_entry(bs, l1_index);
    if (ret < 0) {
    *table = l2_table;
    trace_qcow2_l2_allocate_done(bs, l1_index, 0);
    return 0;
fail:
    trace_qcow2_l2_allocate_done(bs, l1_index, ret);
    if (l2_table != NULL) {
        qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
    s->l1_table[l1_index] = old_l2_offset;
    if (l2_offset > 0) {
        qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
                            QCOW2_DISCARD_ALWAYS);
    return ret;


SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
{
	struct sched_param lp;
	struct task_struct *p;
	int retval;

	if (!param || pid < 0)
		return -EINVAL;

	rcu_read_lock();
	p = find_process_by_pid(pid);
	retval = -ESRCH;
	if (!p)
		goto out_unlock;

	retval = security_task_getscheduler(p);
	if (retval)
		goto out_unlock;

	lp.sched_priority = p->rt_priority;
	rcu_read_unlock();

	/*
	 * This one might sleep, we cannot do it with a spinlock held ...
	 */
	retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;

	return retval;

out_unlock:
	rcu_read_unlock();
	return retval;
}


static void bonito_cop_writel(void *opaque, hwaddr addr,
                              uint64_t val, unsigned size)
{
    PCIBonitoState *s = opaque;
    ((uint32_t *)(&s->boncop))[addr/sizeof(uint32_t)] = val & 0xffffffff;


static PyObject *__pyx_pf_17clickhouse_driver_7columns_12stringcolumn_create_string_column(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_spec, PyObject *__pyx_v_column_options) {
  PyObject *__pyx_v_client_settings = NULL;
  PyObject *__pyx_v_strings_as_bytes = NULL;
  PyObject *__pyx_v_encoding = NULL;
  PyObject *__pyx_v_cls = NULL;
  PyObject *__pyx_v_length = NULL;
  PyObject *__pyx_r = NULL;
  __Pyx_RefNannyDeclarations
  PyObject *__pyx_t_1 = NULL;
  PyObject *__pyx_t_2 = NULL;
  PyObject *__pyx_t_3 = NULL;
  PyObject *__pyx_t_4 = NULL;
  int __pyx_t_5;
  PyObject *__pyx_t_6 = NULL;
  int __pyx_t_7;
  int __pyx_lineno = 0;
  const char *__pyx_filename = NULL;
  int __pyx_clineno = 0;
  __Pyx_RefNannySetupContext("create_string_column", 0);

  /* "clickhouse_driver/columns/stringcolumn.pyx":159
 *
 * def create_string_column(spec, column_options):
 *     client_settings = column_options['context'].client_settings             # <<<<<<<<<<<<<<
 *     strings_as_bytes = client_settings['strings_as_bytes']
 *     encoding = client_settings.get('strings_encoding', String.default_encoding)
 */
  __pyx_t_1 = __Pyx_PyObject_Dict_GetItem(__pyx_v_column_options, __pyx_n_u_context); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 159, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_client_settings); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 159, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_v_client_settings = __pyx_t_2;
  __pyx_t_2 = 0;

  /* "clickhouse_driver/columns/stringcolumn.pyx":160
 * def create_string_column(spec, column_options):
 *     client_settings = column_options['context'].client_settings
 *     strings_as_bytes = client_settings['strings_as_bytes']             # <<<<<<<<<<<<<<
 *     encoding = client_settings.get('strings_encoding', String.default_encoding)
 *
 */
  __pyx_t_2 = __Pyx_PyObject_Dict_GetItem(__pyx_v_client_settings, __pyx_n_u_strings_as_bytes); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 160, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_v_strings_as_bytes = __pyx_t_2;
  __pyx_t_2 = 0;

  /* "clickhouse_driver/columns/stringcolumn.pyx":161
 *     client_settings = column_options['context'].client_settings
 *     strings_as_bytes = client_settings['strings_as_bytes']
 *     encoding = client_settings.get('strings_encoding', String.default_encoding)             # <<<<<<<<<<<<<<
 *
 *     if spec == 'String':
 */
  __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_client_settings, __pyx_n_s_get); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 161, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_String); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 161, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_3);
  __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_default_encoding); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 161, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
  __pyx_t_3 = NULL;
  __pyx_t_5 = 0;
  if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_1))) {
    __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_1);
    if (likely(__pyx_t_3)) {
      PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1);
      __Pyx_INCREF(__pyx_t_3);
      __Pyx_INCREF(function);
      __Pyx_DECREF_SET(__pyx_t_1, function);
      __pyx_t_5 = 1;
    }
  }
  #if CYTHON_FAST_PYCALL
  if (PyFunction_Check(__pyx_t_1)) {
    PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_n_u_strings_encoding, __pyx_t_4};
    __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 161, __pyx_L1_error)
    __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
    __Pyx_GOTREF(__pyx_t_2);
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  } else
  #endif
  #if CYTHON_FAST_PYCCALL
  if (__Pyx_PyFastCFunction_Check(__pyx_t_1)) {
    PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_n_u_strings_encoding, __pyx_t_4};
    __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_1, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 161, __pyx_L1_error)
    __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
    __Pyx_GOTREF(__pyx_t_2);
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  } else
  #endif
  {
    __pyx_t_6 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 161, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_6);
    if (__pyx_t_3) {
      __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_3); __pyx_t_3 = NULL;
    }
    __Pyx_INCREF(__pyx_n_u_strings_encoding);
    __Pyx_GIVEREF(__pyx_n_u_strings_encoding);
    PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, __pyx_n_u_strings_encoding);
    __Pyx_GIVEREF(__pyx_t_4);
    PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_t_4);
    __pyx_t_4 = 0;
    __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 161, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_2);
    __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
  }
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_v_encoding = __pyx_t_2;
  __pyx_t_2 = 0;

  /* "clickhouse_driver/columns/stringcolumn.pyx":163
 *     encoding = client_settings.get('strings_encoding', String.default_encoding)
 *
 *     if spec == 'String':             # <<<<<<<<<<<<<<
 *         cls = ByteString if strings_as_bytes else String
 *         return cls(encoding=encoding, **column_options)
 */
  __pyx_t_7 = (__Pyx_PyUnicode_Equals(__pyx_v_spec, __pyx_n_u_String, Py_EQ)); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 163, __pyx_L1_error)
  if (__pyx_t_7) {

    /* "clickhouse_driver/columns/stringcolumn.pyx":164
 *
 *     if spec == 'String':
 *         cls = ByteString if strings_as_bytes else String             # <<<<<<<<<<<<<<
 *         return cls(encoding=encoding, **column_options)
 *     else:
 */
    __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_v_strings_as_bytes); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 164, __pyx_L1_error)
    if (__pyx_t_7) {
      __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_ByteString); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 164, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __pyx_t_2 = __pyx_t_1;
      __pyx_t_1 = 0;
    } else {
      __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_String); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 164, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __pyx_t_2 = __pyx_t_1;
      __pyx_t_1 = 0;
    }
    __pyx_v_cls = __pyx_t_2;
    __pyx_t_2 = 0;

    /* "clickhouse_driver/columns/stringcolumn.pyx":165
 *     if spec == 'String':
 *         cls = ByteString if strings_as_bytes else String
 *         return cls(encoding=encoding, **column_options)             # <<<<<<<<<<<<<<
 *     else:
 *         length = int(spec[12:-1])
 */
    __Pyx_XDECREF(__pyx_r);
    __pyx_t_1 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 165, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
    if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_encoding, __pyx_v_encoding) < 0) __PYX_ERR(0, 165, __pyx_L1_error)
    __pyx_t_2 = __pyx_t_1;
    __pyx_t_1 = 0;
    if (unlikely(__pyx_v_column_options == Py_None)) {
      PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType");
      __PYX_ERR(0, 165, __pyx_L1_error)
    }
    if (__Pyx_MergeKeywords(__pyx_t_2, __pyx_v_column_options) < 0) __PYX_ERR(0, 165, __pyx_L1_error)
    __pyx_t_1 = __Pyx_PyObject_Call(__pyx_v_cls, __pyx_empty_tuple, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 165, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
    __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
    __pyx_r = __pyx_t_1;
    __pyx_t_1 = 0;
    goto __pyx_L0;

    /* "clickhouse_driver/columns/stringcolumn.pyx":163
 *     encoding = client_settings.get('strings_encoding', String.default_encoding)
 *
 *     if spec == 'String':             # <<<<<<<<<<<<<<
 *         cls = ByteString if strings_as_bytes else String
 *         return cls(encoding=encoding, **column_options)
 */
  }

  /* "clickhouse_driver/columns/stringcolumn.pyx":167
 *         return cls(encoding=encoding, **column_options)
 *     else:
 *         length = int(spec[12:-1])             # <<<<<<<<<<<<<<
 *         cls = ByteFixedString if strings_as_bytes else FixedString
 *         return cls(length, encoding=encoding, **column_options)
 */
  /*else*/ {
    __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_spec, 12, -1L, NULL, NULL, &__pyx_slice_, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_1);
    __pyx_t_2 = __Pyx_PyNumber_Int(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_2);
    __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
    __pyx_v_length = __pyx_t_2;
    __pyx_t_2 = 0;

    /* "clickhouse_driver/columns/stringcolumn.pyx":168
 *     else:
 *         length = int(spec[12:-1])
 *         cls = ByteFixedString if strings_as_bytes else FixedString             # <<<<<<<<<<<<<<
 *         return cls(length, encoding=encoding, **column_options)
 */
    __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_v_strings_as_bytes); if (unlikely(__pyx_t_7 < 0)) __PYX_ERR(0, 168, __pyx_L1_error)
    if (__pyx_t_7) {
      __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_ByteFixedString); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __pyx_t_2 = __pyx_t_1;
      __pyx_t_1 = 0;
    } else {
      __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_FixedString); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error)
      __Pyx_GOTREF(__pyx_t_1);
      __pyx_t_2 = __pyx_t_1;
      __pyx_t_1 = 0;
    }
    __pyx_v_cls = __pyx_t_2;
    __pyx_t_2 = 0;

    /* "clickhouse_driver/columns/stringcolumn.pyx":169
 *         length = int(spec[12:-1])
 *         cls = ByteFixedString if strings_as_bytes else FixedString
 *         return cls(length, encoding=encoding, **column_options)             # <<<<<<<<<<<<<<
 */
    __Pyx_XDECREF(__pyx_r);
    __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 169, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_2);
    __Pyx_INCREF(__pyx_v_length);
    __Pyx_GIVEREF(__pyx_v_length);
    PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_length);
    __pyx_t_6 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 169, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_6);
    if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_encoding, __pyx_v_encoding) < 0) __PYX_ERR(0, 169, __pyx_L1_error)
    __pyx_t_1 = __pyx_t_6;
    __pyx_t_6 = 0;
    if (unlikely(__pyx_v_column_options == Py_None)) {
      PyErr_SetString(PyExc_TypeError, "argument after ** must be a mapping, not NoneType");
      __PYX_ERR(0, 169, __pyx_L1_error)
    }
    if (__Pyx_MergeKeywords(__pyx_t_1, __pyx_v_column_options) < 0) __PYX_ERR(0, 169, __pyx_L1_error)
    __pyx_t_6 = __Pyx_PyObject_Call(__pyx_v_cls, __pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 169, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_6);
    __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
    __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
    __pyx_r = __pyx_t_6;
    __pyx_t_6 = 0;
    goto __pyx_L0;
  }

  /* "clickhouse_driver/columns/stringcolumn.pyx":158
 *
 *
 * def create_string_column(spec, column_options):             # <<<<<<<<<<<<<<
 *     client_settings = column_options['context'].client_settings
 *     strings_as_bytes = client_settings['strings_as_bytes']
 */

  /* function exit code */
  __pyx_L1_error:;
  __Pyx_XDECREF(__pyx_t_1);
  __Pyx_XDECREF(__pyx_t_2);
  __Pyx_XDECREF(__pyx_t_3);
  __Pyx_XDECREF(__pyx_t_4);
  __Pyx_XDECREF(__pyx_t_6);
  __Pyx_AddTraceback("clickhouse_driver.columns.stringcolumn.create_string_column", __pyx_clineno, __pyx_lineno, __pyx_filename);
  __pyx_r = NULL;
  __pyx_L0:;
  __Pyx_XDECREF(__pyx_v_client_settings);
  __Pyx_XDECREF(__pyx_v_strings_as_bytes);
  __Pyx_XDECREF(__pyx_v_encoding);
  __Pyx_XDECREF(__pyx_v_cls);
  __Pyx_XDECREF(__pyx_v_length);
  __Pyx_XGIVEREF(__pyx_r);
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}


GF_Err metx_on_child_box(GF_Box *s, GF_Box *a, Bool is_rem)
{
	GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s;
	switch (a->type) {
	case GF_ISOM_BOX_TYPE_TXTC:
		//we allow the config box on metx
		BOX_FIELD_ASSIGN(config, GF_TextConfigBox)
		break;
	}
	return GF_OK;


ppp_hdlc(netdissect_options *ndo,
         const u_char *p, int length)
{
	u_int caplen = ndo->ndo_snapend - p;
	u_char *b, *t, c;
	const u_char *s;
	u_int i;
	int proto;
	const void *se;

	if (caplen == 0)
		return;

        if (length <= 0)
                return;

	b = (u_char *)malloc(caplen);
	if (b == NULL)
		return;

	/*
	 * Unescape all the data into a temporary, private, buffer.
	 * Do this so that we dont overwrite the original packet
	 * contents.
	 */
	for (s = p, t = b, i = caplen; i != 0; i--) {
		c = *s++;
		if (c == 0x7d) {
			if (i <= 1)
				break;
			i--;
			c = *s++ ^ 0x20;
		}
		*t++ = c;
	}

	se = ndo->ndo_snapend;
	ndo->ndo_snapend = t;
	length = t - b;

        /* now lets guess about the payload codepoint format */
        if (length < 1)
                goto trunc;
        proto = *b; /* start with a one-octet codepoint guess */

        switch (proto) {
        case PPP_IP:
		ip_print(ndo, b + 1, length - 1);
		goto cleanup;
        case PPP_IPV6:
		ip6_print(ndo, b + 1, length - 1);
		goto cleanup;
        default: /* no luck - try next guess */
		break;
        }

        if (length < 2)
                goto trunc;
        proto = EXTRACT_16BITS(b); /* next guess - load two octets */

        switch (proto) {
        case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */
            if (length < 4)
                goto trunc;
            proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */
            handle_ppp(ndo, proto, b + 4, length - 4);
            break;
        default: /* last guess - proto must be a PPP proto-id */
            handle_ppp(ndo, proto, b + 2, length - 2);
            break;
        }

cleanup:
	ndo->ndo_snapend = se;
	free(b);
        return;

trunc:
	ndo->ndo_snapend = se;
	free(b);
	ND_PRINT((ndo, "[|ppp]"));
}


uint32_t GetCompressedFormatRowPitch(const CompressedFormatInfo& info,
                                     uint32_t width) {
  uint32_t num_blocks_wide = (width + info.block_size - 1) / info.block_size;
  return num_blocks_wide * info.bytes_per_block;
}


static int handlePoll(zloop_t __attribute__((unused)) * loop, zmq_pollitem_t *poller, void* pd) {
    smsg_t* pMsg;
    poller_data* pollerData = (poller_data*)pd;

    char* buf = zstr_recv(poller->socket);
    if (msgConstruct(&pMsg) == RS_RET_OK) {
        MsgSetRawMsg(pMsg, buf, strlen(buf));
        MsgSetInputName(pMsg, s_namep);
        MsgSetHOSTNAME(pMsg, glbl.GetLocalHostName(), ustrlen(glbl.GetLocalHostName()));
        MsgSetRcvFrom(pMsg, glbl.GetLocalHostNameProp());
        MsgSetRcvFromIP(pMsg, glbl.GetLocalHostIP());
        MsgSetMSGoffs(pMsg, 0);
        MsgSetFlowControlType(pMsg, eFLOWCTL_NO_DELAY);
        MsgSetRuleset(pMsg, pollerData->ruleset);
        pMsg->msgFlags = NEEDS_PARSING | PARSE_HOSTNAME;
        submitMsg2(pMsg);
    }

    /* gotta free the string returned from zstr_recv() */
    free(buf);

    if( pollerData->thread->bShallStop == TRUE) {
        /* a handler that returns -1 will terminate the
           czmq reactor loop
        */
        return -1;
    }

    return 0;
}


__iommu_alloc_remap(struct page **pages, size_t size, gfp_t gfp, pgprot_t prot,
		    const void *caller)
{
	unsigned int i, nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
	struct vm_struct *area;
	unsigned long p;

	area = get_vm_area_caller(size, VM_ARM_DMA_CONSISTENT | VM_USERMAP,
				  caller);
	if (!area)
		return NULL;

	area->pages = pages;
	area->nr_pages = nr_pages;
	p = (unsigned long)area->addr;

	for (i = 0; i < nr_pages; i++) {
		phys_addr_t phys = __pfn_to_phys(page_to_pfn(pages[i]));
		if (ioremap_page_range(p, p + PAGE_SIZE, phys, prot))
			goto err;
		p += PAGE_SIZE;
	}
	return area->addr;
err:
	unmap_kernel_range((unsigned long)area->addr, size);
	vunmap(area->addr);
	return NULL;
}


static unsigned int tun_chr_poll(struct file *file, poll_table * wait)
{
	struct tun_file *tfile = file->private_data;
	struct tun_struct *tun = __tun_get(tfile);
	struct sock *sk;
	unsigned int mask = 0;

	if (!tun)
		return POLLERR;

	sk = tun->socket.sk;

	tun_debug(KERN_INFO, tun, "tun_chr_poll\n");

	poll_wait(file, &tun->wq.wait, wait);

	if (!skb_queue_empty(&sk->sk_receive_queue))
		mask |= POLLIN | POLLRDNORM;

	if (sock_writeable(sk) ||
	    (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
	     sock_writeable(sk)))
		mask |= POLLOUT | POLLWRNORM;

	if (tun->dev->reg_state != NETREG_REGISTERED)
		mask = POLLERR;

	tun_put(tun);
	return mask;
}


static unsigned long load_elf_interp(struct elfhdr *interp_elf_ex,
		struct file *interpreter, unsigned long *interp_map_addr,
		unsigned long no_base, struct elf_phdr *interp_elf_phdata)
{
	struct elf_phdr *eppnt;
	unsigned long load_addr = 0;
	int load_addr_set = 0;
	unsigned long last_bss = 0, elf_bss = 0;
	unsigned long error = ~0UL;
	unsigned long total_size;
	int i;

	/* First of all, some simple consistency checks */
	if (interp_elf_ex->e_type != ET_EXEC &&
	    interp_elf_ex->e_type != ET_DYN)
		goto out;
	if (!elf_check_arch(interp_elf_ex))
		goto out;
	if (!interpreter->f_op->mmap)
		goto out;

	total_size = total_mapping_size(interp_elf_phdata,
					interp_elf_ex->e_phnum);
	if (!total_size) {
		error = -EINVAL;
		goto out;
	}

	eppnt = interp_elf_phdata;
	for (i = 0; i < interp_elf_ex->e_phnum; i++, eppnt++) {
		if (eppnt->p_type == PT_LOAD) {
			int elf_type = MAP_PRIVATE | MAP_DENYWRITE;
			int elf_prot = 0;
			unsigned long vaddr = 0;
			unsigned long k, map_addr;

			if (eppnt->p_flags & PF_R)
		    		elf_prot = PROT_READ;
			if (eppnt->p_flags & PF_W)
				elf_prot |= PROT_WRITE;
			if (eppnt->p_flags & PF_X)
				elf_prot |= PROT_EXEC;
			vaddr = eppnt->p_vaddr;
			if (interp_elf_ex->e_type == ET_EXEC || load_addr_set)
				elf_type |= MAP_FIXED;
			else if (no_base && interp_elf_ex->e_type == ET_DYN)
				load_addr = -vaddr;

			map_addr = elf_map(interpreter, load_addr + vaddr,
					eppnt, elf_prot, elf_type, total_size);
			total_size = 0;
			if (!*interp_map_addr)
				*interp_map_addr = map_addr;
			error = map_addr;
			if (BAD_ADDR(map_addr))
				goto out;

			if (!load_addr_set &&
			    interp_elf_ex->e_type == ET_DYN) {
				load_addr = map_addr - ELF_PAGESTART(vaddr);
				load_addr_set = 1;
			}

			/*
			 * Check to see if the section's size will overflow the
			 * allowed task size. Note that p_filesz must always be
			 * <= p_memsize so it's only necessary to check p_memsz.
			 */
			k = load_addr + eppnt->p_vaddr;
			if (BAD_ADDR(k) ||
			    eppnt->p_filesz > eppnt->p_memsz ||
			    eppnt->p_memsz > TASK_SIZE ||
			    TASK_SIZE - eppnt->p_memsz < k) {
				error = -ENOMEM;
				goto out;
			}

			/*
			 * Find the end of the file mapping for this phdr, and
			 * keep track of the largest address we see for this.
			 */
			k = load_addr + eppnt->p_vaddr + eppnt->p_filesz;
			if (k > elf_bss)
				elf_bss = k;

			/*
			 * Do the same thing for the memory mapping - between
			 * elf_bss and last_bss is the bss section.
			 */
			k = load_addr + eppnt->p_memsz + eppnt->p_vaddr;
			if (k > last_bss)
				last_bss = k;
		}
	}

	if (last_bss > elf_bss) {
		/*
		 * Now fill out the bss section.  First pad the last page up
		 * to the page boundary, and then perform a mmap to make sure
		 * that there are zero-mapped pages up to and including the
		 * last bss page.
		 */
		if (padzero(elf_bss)) {
			error = -EFAULT;
			goto out;
		}

		/* What we have mapped so far */
		elf_bss = ELF_PAGESTART(elf_bss + ELF_MIN_ALIGN - 1);

		/* Map the last of the bss segment */
		error = vm_brk(elf_bss, last_bss - elf_bss);
		if (BAD_ADDR(error))
			goto out;
	}

	error = load_addr;
out:
	return error;
}


int write_to_syslog(char *buffer, unsigned long data_type) {

	if(buffer == NULL)
		return ERROR;

	/* don't log anything if we're not actually running... */
	if(verify_config || test_scheduling == TRUE)
		return OK;

	/* bail out if we shouldn't write to syslog */
	if(use_syslog == FALSE)
		return OK;

	/* make sure we should log this type of entry */
	if(!(data_type & syslog_options))
		return OK;

	/* write the buffer to the syslog facility */
	syslog(LOG_USER | LOG_INFO, "%s", buffer);

	return OK;
	}


void push(const NodeDef* n) { queue_.emplace(n, topo_order_.at(n)); }


SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
		unsigned int, flags, struct sockaddr __user *, addr,
		int, addr_len)
{
	struct socket *sock;
	struct sockaddr_storage address;
	int err;
	struct msghdr msg;
	struct iovec iov;
	int fput_needed;

	if (len > INT_MAX)
		len = INT_MAX;
	sock = sockfd_lookup_light(fd, &err, &fput_needed);
	if (!sock)
		goto out;

	iov.iov_base = buff;
	iov.iov_len = len;
	msg.msg_name = NULL;
	iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len);
	msg.msg_control = NULL;
	msg.msg_controllen = 0;
	msg.msg_namelen = 0;
	if (addr) {
		err = move_addr_to_kernel(addr, addr_len, &address);
		if (err < 0)
			goto out_put;
		msg.msg_name = (struct sockaddr *)&address;
		msg.msg_namelen = addr_len;
	}
	if (sock->file->f_flags & O_NONBLOCK)
		flags |= MSG_DONTWAIT;
	msg.msg_flags = flags;
	err = sock_sendmsg(sock, &msg, len);

out_put:
	fput_light(sock->file, fput_needed);
out:
	return err;
}


ProcXvShmPutImage(ClientPtr client)
{
    ShmDescPtr shmdesc;
    DrawablePtr pDraw;
    XvPortPtr pPort;
    XvImagePtr pImage = NULL;
    GCPtr pGC;
    int status, size_needed, i;
    CARD16 width, height;

    REQUEST(xvShmPutImageReq);
    REQUEST_SIZE_MATCH(xvShmPutImageReq);

    VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess);
    VALIDATE_XV_PORT(stuff->port, pPort, DixReadAccess);

    if (!(pPort->pAdaptor->type & XvImageMask) ||
        !(pPort->pAdaptor->type & XvInputMask)) {
        client->errorValue = stuff->port;
        return BadMatch;
    }

    status = XvdiMatchPort(pPort, pDraw);
    if (status != Success) {
        return status;
    }

    for (i = 0; i < pPort->pAdaptor->nImages; i++) {
        if (pPort->pAdaptor->pImages[i].id == stuff->id) {
            pImage = &(pPort->pAdaptor->pImages[i]);
            break;
        }
    }

    if (!pImage)
        return BadMatch;

    status = dixLookupResourceByType((void **) &shmdesc, stuff->shmseg,
                                     ShmSegType, serverClient, DixReadAccess);
    if (status != Success)
        return status;

    width = stuff->width;
    height = stuff->height;
    size_needed = (*pPort->pAdaptor->ddQueryImageAttributes) (pPort, pImage,
                                                              &width, &height,
                                                              NULL, NULL);
    if ((size_needed + stuff->offset) > shmdesc->size)
        return BadAccess;

    if ((width < stuff->width) || (height < stuff->height))
        return BadValue;

    status = XvdiPutImage(client, pDraw, pPort, pGC, stuff->src_x, stuff->src_y,
                          stuff->src_w, stuff->src_h, stuff->drw_x,
                          stuff->drw_y, stuff->drw_w, stuff->drw_h, pImage,
                          (unsigned char *) shmdesc->addr + stuff->offset,
                          stuff->send_event, stuff->width, stuff->height);

    if ((status == Success) && stuff->send_event) {
        xShmCompletionEvent ev = {
            .type = ShmCompletionCode,
            .drawable = stuff->drawable,
            .minorEvent = xv_ShmPutImage,
            .majorEvent = XvReqCode,
            .shmseg = stuff->shmseg,
            .offset = stuff->offset
        };
        WriteEventsToClient(client, 1, (xEvent *) &ev);
    }

    return status;
}


void linuxOvercommitMemoryWarning(void) {
    if (linuxOvercommitMemoryValue() == 0) {
        redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
    }
}


opj_j2k_t* opj_j2k_create_compress(void)
{
        opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1,sizeof(opj_j2k_t));
        if (!l_j2k) {
                return NULL;
        }

        l_j2k->m_is_decoder = 0;
        l_j2k->m_cp.m_is_decoder = 0;

        l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(OPJ_J2K_DEFAULT_HEADER_SIZE);
        if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
                opj_j2k_destroy(l_j2k);
                return NULL;
        }

        l_j2k->m_specific_param.m_encoder.m_header_tile_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE;

        /* validation list creation*/
        l_j2k->m_validation_list = opj_procedure_list_create();
        if (! l_j2k->m_validation_list) {
                opj_j2k_destroy(l_j2k);
                return NULL;
        }

        /* execution list creation*/
        l_j2k->m_procedure_list = opj_procedure_list_create();
        if (! l_j2k->m_procedure_list) {
                opj_j2k_destroy(l_j2k);
                return NULL;
        }

        return l_j2k;
}


static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

	    "movq	%1, %%mm6\n\t"

	    ::"m"(red_15mask),"m"(green_15mask));

	mm_end = end - 11;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

		"movd	%1, %%mm0\n\t"

		"movd	3%1, %%mm3\n\t"

		"punpckldq 6%1, %%mm0\n\t"

		"punpckldq 9%1, %%mm3\n\t"

		"movq	%%mm0, %%mm1\n\t"

		"movq	%%mm0, %%mm2\n\t"

		"movq	%%mm3, %%mm4\n\t"

		"movq	%%mm3, %%mm5\n\t"

		"psrlq	$3, %%mm0\n\t"

		"psrlq	$3, %%mm3\n\t"

		"pand	%2, %%mm0\n\t"

		"pand	%2, %%mm3\n\t"

		"psrlq	$6, %%mm1\n\t"

		"psrlq	$6, %%mm4\n\t"

		"pand	%%mm6, %%mm1\n\t"

		"pand	%%mm6, %%mm4\n\t"

		"psrlq	$9, %%mm2\n\t"

		"psrlq	$9, %%mm5\n\t"

		"pand	%%mm7, %%mm2\n\t"

		"pand	%%mm7, %%mm5\n\t"

		"por	%%mm1, %%mm0\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

		"por	%%mm5, %%mm3\n\t"

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

		d += 4;

		s += 12;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		const int b= *s++;

		const int g= *s++;

		const int r= *s++;

		*d++ = (b>>3) | ((g&0xF8)<<2) | ((r&0xF8)<<7);

	}

}


des_cipher(const char *in, char *out, uint32_t salt, int count,
	struct php_crypt_extended_data *data)
{
	uint32_t	l_out, r_out, rawl, rawr;
	int	retval;

	setup_salt(salt, data);

	rawl =
		(uint32_t)(u_char)in[3] |
		((uint32_t)(u_char)in[2] << 8) |
		((uint32_t)(u_char)in[1] << 16) |
		((uint32_t)(u_char)in[0] << 24);
	rawr =
		(uint32_t)(u_char)in[7] |
		((uint32_t)(u_char)in[6] << 8) |
		((uint32_t)(u_char)in[5] << 16) |
		((uint32_t)(u_char)in[4] << 24);

	retval = do_des(rawl, rawr, &l_out, &r_out, count, data);

	out[0] = l_out >> 24;
	out[1] = l_out >> 16;
	out[2] = l_out >> 8;
	out[3] = l_out;
	out[4] = r_out >> 24;
	out[5] = r_out >> 16;
	out[6] = r_out >> 8;
	out[7] = r_out;

	return(retval);
}


static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __be32 state,
				  const char *mcast_ifn, __be32 syncid,
				  struct netlink_callback *cb)
{
	void *hdr;
	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq,
			  &ip_vs_genl_family, NLM_F_MULTI,
			  IPVS_CMD_NEW_DAEMON);
	if (!hdr)
		return -EMSGSIZE;

	if (ip_vs_genl_fill_daemon(skb, state, mcast_ifn, syncid))
		goto nla_put_failure;

	return genlmsg_end(skb, hdr);

nla_put_failure:
	genlmsg_cancel(skb, hdr);
	return -EMSGSIZE;
}


zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
	spl_filesystem_iterator *iterator;
	spl_filesystem_object *dir_object;

	if (by_ref) {
		zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
	}
	dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);
	iterator   = spl_filesystem_object_to_iterator(dir_object);

	/* initialize iterator if wasn't gotten before */
	if (iterator->intern.data == NULL) {
		iterator->intern.data = object;
		iterator->intern.funcs = &spl_filesystem_tree_it_funcs;
	}
	zval_add_ref(&object);

	return (zend_object_iterator*)iterator;
}


static void gen_tlbsx_440(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    gen_helper_440_tlbsx(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

    if (Rc(ctx->opcode)) {

        TCGLabel *l1 = gen_new_label();

        tcg_gen_trunc_tl_i32(cpu_crf[0], cpu_so);

        tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_gpr[rD(ctx->opcode)], -1, l1);

        tcg_gen_ori_i32(cpu_crf[0], cpu_crf[0], 0x02);

        gen_set_label(l1);

    }

#endif

}


static void __balloon_append(struct page *page)
{
	/* Lowmem is re-populated first, so highmem pages go at list tail. */
	if (PageHighMem(page)) {
		list_add_tail(&page->lru, &ballooned_pages);
		balloon_stats.balloon_high++;
	} else {
		list_add(&page->lru, &ballooned_pages);
		balloon_stats.balloon_low++;
	}
	wake_up(&balloon_wq);
}


void WebContentsImpl::ResumeLoadingCreatedWebContents() {
  if (delayed_open_url_params_.get()) {
    OpenURL(*delayed_open_url_params_.get());
    delayed_open_url_params_.reset(nullptr);
    return;
  }

  if (is_resume_pending_) {
    is_resume_pending_ = false;
    GetRenderViewHost()->GetWidget()->Init();
    GetMainFrame()->Init();
  }
}


void FrameView::addViewportConstrainedObject(RenderObject* object)
{
    if (!m_viewportConstrainedObjects)
        m_viewportConstrainedObjects = adoptPtr(new ViewportConstrainedObjectSet);

    if (!m_viewportConstrainedObjects->contains(object)) {
        m_viewportConstrainedObjects->add(object);

        if (Page* page = m_frame->page()) {
            if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
                scrollingCoordinator->frameViewFixedObjectsDidChange(this);
        }
    }
}


status_t Camera2Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) {
    ATRACE_CALL();
 Mutex::Autolock icl(mBinderSerializationLock);
 status_t res;
 if ( (res = checkPid(__FUNCTION__) ) != OK) return res;

    ALOGV("%s: Camera %d: Command %d (%d, %d)", __FUNCTION__, mCameraId,
            cmd, arg1, arg2);

 switch (cmd) {
 case CAMERA_CMD_START_SMOOTH_ZOOM:
 return commandStartSmoothZoomL();
 case CAMERA_CMD_STOP_SMOOTH_ZOOM:
 return commandStopSmoothZoomL();
 case CAMERA_CMD_SET_DISPLAY_ORIENTATION:
 return commandSetDisplayOrientationL(arg1);
 case CAMERA_CMD_ENABLE_SHUTTER_SOUND:
 return commandEnableShutterSoundL(arg1 == 1);
 case CAMERA_CMD_PLAY_RECORDING_SOUND:
 return commandPlayRecordingSoundL();
 case CAMERA_CMD_START_FACE_DETECTION:
 return commandStartFaceDetectionL(arg1);
 case CAMERA_CMD_STOP_FACE_DETECTION: {
 SharedParameters::Lock l(mParameters);
 return commandStopFaceDetectionL(l.mParameters);
 }
 case CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG:
 return commandEnableFocusMoveMsgL(arg1 == 1);
 case CAMERA_CMD_PING:
 return commandPingL();
 case CAMERA_CMD_SET_VIDEO_BUFFER_COUNT:
 return commandSetVideoBufferCountL(arg1);
 default:
            ALOGE("%s: Unknown command %d (arguments %d, %d)",
                    __FUNCTION__, cmd, arg1, arg2);
 return BAD_VALUE;
 }
}


bool ShellContentClient::GetSandboxProfileForSandboxType(
    int sandbox_type,
    int* sandbox_profile_resource_id) const {
  return false;
}


fixExec2Error(int action,
             u_char * var_val,
             u_char var_val_type,
             size_t var_val_len,
             u_char * statP, oid * name, size_t name_len)
{
    netsnmp_old_extend *exten = NULL;
    unsigned int idx;

    idx = name[name_len-1] -1;
    exten = &compatability_entries[ idx ];

#if !defined(NETSNMP_NO_WRITE_SUPPORT) && ENABLE_EXTEND_WRITE_ACCESS
    switch (action) {
    case MODE_SET_RESERVE1:
        if (var_val_type != ASN_INTEGER) {
            snmp_log(LOG_ERR, "Wrong type != int\n");
            return SNMP_ERR_WRONGTYPE;
        }
        idx = *((long *) var_val);
        if (idx != 1) {
            snmp_log(LOG_ERR, "Wrong value != 1\n");
            return SNMP_ERR_WRONGVALUE;
        }
        if (!exten || !exten->efix_entry) {
            snmp_log(LOG_ERR, "No command to run\n");
            return SNMP_ERR_GENERR;
        }
        return SNMP_ERR_NOERROR;

    case MODE_SET_COMMIT:
        netsnmp_cache_check_and_reload( exten->efix_entry->cache );
    }
#endif /* !NETSNMP_NO_WRITE_SUPPORT && ENABLE_EXTEND_WRITE_ACCESS */
    return SNMP_ERR_NOERROR;
}


bool WallpaperManager::GetUserWallpaperInfo(const AccountId& account_id,
                                            WallpaperInfo* info) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (user_manager::UserManager::Get()->IsUserNonCryptohomeDataEphemeral(
          account_id)) {
    *info = current_user_wallpaper_info_;

    return true;
  }

  const base::DictionaryValue* info_dict;
  if (!g_browser_process->local_state()
           ->GetDictionary(wallpaper::kUsersWallpaperInfo)
           ->GetDictionaryWithoutPathExpansion(account_id.GetUserEmail(),
                                               &info_dict)) {
    return false;
  }

  std::string location;
  if (!info_dict->GetString(kNewWallpaperLocationNodeName, &location))
    return false;
  int layout;
  if (!info_dict->GetInteger(kNewWallpaperLayoutNodeName, &layout))
    return false;
  int type;
  if (!info_dict->GetInteger(kNewWallpaperTypeNodeName, &type))
    return false;
  std::string date_string;
  if (!info_dict->GetString(kNewWallpaperDateNodeName, &date_string))
    return false;
  int64_t date_val;
  if (!base::StringToInt64(date_string, &date_val))
    return false;

  info->location = location;
  info->layout = static_cast<wallpaper::WallpaperLayout>(layout);
  info->type = static_cast<wallpaper::WallpaperType>(type);
  info->date = base::Time::FromInternalValue(date_val);
  return true;
}


static void parse_cat_blob(const char *p)
{
	struct object_entry *oe = oe;
	unsigned char sha1[20];

	/* cat-blob SP <object> LF */
	if (*p == ':') {
		oe = find_mark(parse_mark_ref_eol(p));
		if (!oe)
			die("Unknown mark: %s", command_buf.buf);
		hashcpy(sha1, oe->idx.sha1);
	} else {
		if (get_sha1_hex(p, sha1))
			die("Invalid dataref: %s", command_buf.buf);
		if (p[40])
			die("Garbage after SHA1: %s", command_buf.buf);
		oe = find_object(sha1);
	}

	cat_blob(oe, sha1);
}


bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
    pb_istream_t substream;
    bool status;

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

    status = pb_decode_noinit(&substream, fields, dest_struct);

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


error::Error GLES2DecoderPassthroughImpl::DoStencilStrokePathCHROMIUM(
    GLuint path,
    GLint reference,
    GLuint mask) {
  NOTIMPLEMENTED();
  return error::kNoError;
}


void set_dumpable(struct mm_struct *mm, int value)
{
	switch (value) {
	case SUID_DUMPABLE_DISABLED:
		clear_bit(MMF_DUMPABLE, &mm->flags);
		smp_wmb();
		clear_bit(MMF_DUMP_SECURELY, &mm->flags);
		break;
	case SUID_DUMPABLE_ENABLED:
		set_bit(MMF_DUMPABLE, &mm->flags);
		smp_wmb();
		clear_bit(MMF_DUMP_SECURELY, &mm->flags);
		break;
	case SUID_DUMPABLE_SAFE:
		set_bit(MMF_DUMP_SECURELY, &mm->flags);
		smp_wmb();
		set_bit(MMF_DUMPABLE, &mm->flags);
		break;
	}
}


static void i_free_all ( gs_memory_t * mem , uint free_mask , client_name_t cname ) {
 gs_ref_memory_t * imem = ( gs_ref_memory_t * ) mem ;
 struct free_data fd ;
 fd . imem = imem ;
 fd . allocator = NULL ;
 if ( free_mask & FREE_ALL_DATA && imem -> root != NULL ) {
 clump_splay_app ( imem -> root , imem , free_all_not_allocator , & fd ) ;
 imem -> root = fd . allocator ;
 if ( fd . allocator ) fd . allocator -> parent = fd . allocator -> left = fd . allocator -> right = NULL ;
 }
 if ( free_mask & FREE_ALL_ALLOCATOR ) {
 clump_splay_app ( imem -> root , imem , free_all_allocator , & fd ) ;
 }
 }


meta_grammar(void)
{
    return &_Ta3Parser_Grammar;
}


MPEG4Source::MPEG4Source(
 const sp<MPEG4Extractor> &owner,
 const sp<MetaData> &format,
 const sp<DataSource> &dataSource,
 int32_t timeScale,
 const sp<SampleTable> &sampleTable,
 Vector<SidxEntry> &sidx,
 const Trex *trex,
 off64_t firstMoofOffset)
 : mOwner(owner),
      mFormat(format),
      mDataSource(dataSource),
      mTimescale(timeScale),
      mSampleTable(sampleTable),
      mCurrentSampleIndex(0),
      mCurrentFragmentIndex(0),
      mSegments(sidx),
      mTrex(trex),
      mFirstMoofOffset(firstMoofOffset),
      mCurrentMoofOffset(firstMoofOffset),
      mCurrentTime(0),
      mCurrentSampleInfoAllocSize(0),
      mCurrentSampleInfoSizes(NULL),
      mCurrentSampleInfoOffsetsAllocSize(0),
      mCurrentSampleInfoOffsets(NULL),
      mIsAVC(false),
      mIsHEVC(false),
      mNALLengthSize(0),
      mStarted(false),
      mGroup(NULL),
      mBuffer(NULL),
      mWantsNALFragments(false),
      mSrcBuffer(NULL) {

    memset(&mTrackFragmentHeaderInfo, 0, sizeof(mTrackFragmentHeaderInfo));

    mFormat->findInt32(kKeyCryptoMode, &mCryptoMode);
    mDefaultIVSize = 0;
    mFormat->findInt32(kKeyCryptoDefaultIVSize, &mDefaultIVSize);
 uint32_t keytype;
 const void *key;
 size_t keysize;
 if (mFormat->findData(kKeyCryptoKey, &keytype, &key, &keysize)) {
        CHECK(keysize <= 16);
        memset(mCryptoKey, 0, 16);
        memcpy(mCryptoKey, key, keysize);
 }

 const char *mime;
 bool success = mFormat->findCString(kKeyMIMEType, &mime);
    CHECK(success);

    mIsAVC = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
    mIsHEVC = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC);

 if (mIsAVC) {
 uint32_t type;
 const void *data;
 size_t size;
        CHECK(format->findData(kKeyAVCC, &type, &data, &size));

 const uint8_t *ptr = (const uint8_t *)data;

        CHECK(size >= 7);
        CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1

        mNALLengthSize = 1 + (ptr[4] & 3);
 } else if (mIsHEVC) {
 uint32_t type;
 const void *data;
 size_t size;
        CHECK(format->findData(kKeyHVCC, &type, &data, &size));

 const uint8_t *ptr = (const uint8_t *)data;

        CHECK(size >= 7);
        CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1

        mNALLengthSize = 1 + (ptr[14 + 7] & 3);
 }

    CHECK(format->findInt32(kKeyTrackID, &mTrackId));

 if (mFirstMoofOffset != 0) {
 off64_t offset = mFirstMoofOffset;
        parseChunk(&offset);
 }
}


copy_func(char_u *lambda, char_u *global, ectx_T *ectx)
{
    ufunc_T *ufunc = find_func_even_dead(lambda, FFED_IS_GLOBAL);
    ufunc_T *fp = NULL;

    if (ufunc == NULL)
    {
	semsg(_(e_lambda_function_not_found_str), lambda);
	return FAIL;
    }

    fp = find_func(global, TRUE);
    if (fp != NULL)
    {
	// TODO: handle ! to overwrite
	semsg(_(e_function_str_already_exists_add_bang_to_replace), global);
	return FAIL;
    }

    fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1);
    if (fp == NULL)
	return FAIL;

    fp->uf_varargs = ufunc->uf_varargs;
    fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY;
    fp->uf_def_status = ufunc->uf_def_status;
    fp->uf_dfunc_idx = ufunc->uf_dfunc_idx;
    if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL
	    || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args)
								    == FAIL
	    || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL)
	goto failed;

    fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL
					 : vim_strsave(ufunc->uf_name_exp);
    if (ufunc->uf_arg_types != NULL)
    {
	fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len);
	if (fp->uf_arg_types == NULL)
	    goto failed;
	mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types,
				    sizeof(type_T *) * fp->uf_args.ga_len);
    }
    if (ufunc->uf_va_name != NULL)
    {
	fp->uf_va_name = vim_strsave(ufunc->uf_va_name);
	if (fp->uf_va_name == NULL)
	    goto failed;
    }
    fp->uf_ret_type = ufunc->uf_ret_type;

    fp->uf_refcount = 1;
    STRCPY(fp->uf_name, global);
    hash_add(&func_hashtab, UF2HIKEY(fp));

    // the referenced dfunc_T is now used one more time
    link_def_function(fp);

    // Create a partial to store the context of the function where it was
    // instantiated.  Only needs to be done once.  Do this on the original
    // function, "dfunc->df_ufunc" will point to it.
    if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL)
    {
	partial_T   *pt = ALLOC_CLEAR_ONE(partial_T);

	if (pt == NULL)
	    goto failed;
	if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL)
	{
	    vim_free(pt);
	    goto failed;
	}
	ufunc->uf_partial = pt;
	--pt->pt_refcount;  // not actually referenced here
    }

    return OK;

failed:
    func_clear_free(fp, TRUE);
    return FAIL;
}


static TCGv_i64 read_fp_dreg(DisasContext *s, int reg)

{

    TCGv_i64 v = tcg_temp_new_i64();

    tcg_gen_ld_i64(v, cpu_env, fp_reg_offset(reg, MO_64));

    return v;

}


void FetchManager::Loader::Start() {

  if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
      !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
          fetch_request_data_->Url())) {
    PerformNetworkError(
        "Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
        "' because it violates the document's Content Security Policy.");
    return;
  }

  if ((SecurityOrigin::Create(fetch_request_data_->Url())
           ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
      (fetch_request_data_->Url().ProtocolIsData() &&
       fetch_request_data_->SameOriginDataURLFlag()) ||
      (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
    PerformSchemeFetch();
    return;
  }

  if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
    PerformNetworkError("Fetch API cannot load " +
                        fetch_request_data_->Url().GetString() +
                        ". Request mode is \"same-origin\" but the URL\'s "
                        "origin is not same as the request origin " +
                        fetch_request_data_->Origin()->ToString() + ".");
    return;
  }

   if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
     fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting);
    PerformSchemeFetch();
    return;
  }

  if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI(
          fetch_request_data_->Url().Protocol())) {
    PerformNetworkError(
        "Fetch API cannot load " + fetch_request_data_->Url().GetString() +
        ". URL scheme must be \"http\" or \"https\" for CORS request.");
    return;
  }

  fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);

  PerformHTTPFetch();
}


static inline void sub_left_prediction_bgr32 ( HYuvContext * s , uint8_t * dst , const uint8_t * src , int w , int * red , int * green , int * blue , int * alpha ) {
 int i ;
 int r , g , b , a ;
 r = * red ;
 g = * green ;
 b = * blue ;
 a = * alpha ;
 for ( i = 0 ;
 i < FFMIN ( w , 4 ) ;
 i ++ ) {
 const int rt = src [ i * 4 + R ] ;
 const int gt = src [ i * 4 + G ] ;
 const int bt = src [ i * 4 + B ] ;
 const int at = src [ i * 4 + A ] ;
 dst [ i * 4 + R ] = rt - r ;
 dst [ i * 4 + G ] = gt - g ;
 dst [ i * 4 + B ] = bt - b ;
 dst [ i * 4 + A ] = at - a ;
 r = rt ;
 g = gt ;
 b = bt ;
 a = at ;
 }
 s -> dsp . diff_bytes ( dst + 16 , src + 16 , src + 12 , w * 4 - 16 ) ;
 * red = src [ ( w - 1 ) * 4 + R ] ;
 * green = src [ ( w - 1 ) * 4 + G ] ;
 * blue = src [ ( w - 1 ) * 4 + B ] ;
 * alpha = src [ ( w - 1 ) * 4 + A ] ;
 }


receive_private_carbon(void **state)
{
    prof_input("/carbons on");

    prof_connect();
    assert_true(stbbr_received(
        "<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>"
    ));

    stbbr_send(
        "<presence to='stabber@localhost' from='buddy1@localhost/mobile'>"
            "<priority>10</priority>"
            "<status>On my mobile</status>"
        "</presence>"
    );
    assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\""));
    prof_input("/msg Buddy1");
    assert_true(prof_output_exact("unencrypted"));

    stbbr_send(
        "<message type='chat' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>"
            "<body>Private carbon</body>"
            "<private xmlns='urn:xmpp:carbons:2'/>"
        "</message>"
    );

    assert_true(prof_output_regex("Buddy1/mobile: .+Private carbon"));
}


static cmsBool Type_CrdInfo_Write ( struct _cms_typehandler_struct * self , cmsIOHANDLER * io , void * Ptr , cmsUInt32Number nItems ) {
 cmsMLU * mlu = ( cmsMLU * ) Ptr ;
 if ( ! WriteCountAndSting ( self , io , mlu , "nm" ) ) goto Error ;
 if ( ! WriteCountAndSting ( self , io , mlu , "#0" ) ) goto Error ;
 if ( ! WriteCountAndSting ( self , io , mlu , "#1" ) ) goto Error ;
 if ( ! WriteCountAndSting ( self , io , mlu , "#2" ) ) goto Error ;
 if ( ! WriteCountAndSting ( self , io , mlu , "#3" ) ) goto Error ;
 return TRUE ;
 Error : return FALSE ;
 cmsUNUSED_PARAMETER ( nItems ) ;
 }


static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
{
	vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
}


int vnc_server_fb_stride(VncDisplay *vd)
{
    return pixman_image_get_stride(vd->server);
}


int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
{
    size_t inPos = start;
    size_t outPos = 0;
    size_t inLen = 0;

    if (end < start || in == NULL || out == NULL) {
        return BAD_FUNC_ARG;
    }

    inLen = XSTRLEN(in);
    if (start > inLen || end > inLen) {
        return BAD_FUNC_ARG;
    }

    *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
                          DYNAMIC_TYPE_PKCS7);
    if (*out == NULL) {
        return MEMORY_E;
    }

    while (inPos <= end) {
        if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
            MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
            (*out)[outPos] = in[inPos];
            outPos++;
        }
        inPos++;
    }
    (*out)[outPos] = '\0';

    return 0;
}


SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev)
{
	return do_mknodat(AT_FDCWD, filename, mode, dev);
}


int iwl_fw_dbg_collect_desc(struct iwl_fw_runtime *fwrt,
			    const struct iwl_fw_dump_desc *desc,
			    bool monitor_only,
			    unsigned int delay)
{
	u32 trig_type = le32_to_cpu(desc->trig_desc.type);
	int ret;

	if (iwl_trans_dbg_ini_valid(fwrt->trans)) {
		ret = iwl_fw_dbg_ini_collect(fwrt, trig_type);
		if (!ret)
			iwl_fw_free_dump_desc(fwrt);

		return ret;
	}

	/* use wks[0] since dump flow prior to ini does not need to support
	 * consecutive triggers collection
	 */
	if (test_and_set_bit(fwrt->dump.wks[0].idx, &fwrt->dump.active_wks))
		return -EBUSY;

	if (WARN_ON(fwrt->dump.desc))
		iwl_fw_free_dump_desc(fwrt);

	IWL_WARN(fwrt, "Collecting data: trigger %d fired.\n",
		 le32_to_cpu(desc->trig_desc.type));

	fwrt->dump.desc = desc;
	fwrt->dump.monitor_only = monitor_only;

	schedule_delayed_work(&fwrt->dump.wks[0].wk, usecs_to_jiffies(delay));

	return 0;
}


 static void build_l4proto_tcp(const struct nf_conntrack *ct, struct nethdr *n)
 {
	ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
		      sizeof(struct nfct_attr_grp_port));
 	if (!nfct_attr_is_set(ct, ATTR_TCP_STATE))
 		return;

 	ct_build_u8(ct, ATTR_TCP_STATE, n, NTA_TCP_STATE);
 	if (CONFIG(sync).tcp_window_tracking) {
 		ct_build_u8(ct, ATTR_TCP_WSCALE_ORIG, n, NTA_TCP_WSCALE_ORIG);
		ct_build_u8(ct, ATTR_TCP_WSCALE_REPL, n, NTA_TCP_WSCALE_REPL);
	}
}


static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
				     struct vmx_msr_entry *e)
{
	if (e->index == MSR_FS_BASE ||
	    e->index == MSR_GS_BASE ||
	    e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
	    nested_vmx_msr_check_common(vcpu, e))
		return -EINVAL;
	return 0;
}


CIFSSMBSetCIFSACL(const int xid, struct cifs_tcon *tcon, __u16 fid,
			struct cifs_ntsd *pntsd, __u32 acllen)
{
	__u16 byte_count, param_count, data_count, param_offset, data_offset;
	int rc = 0;
	int bytes_returned = 0;
	SET_SEC_DESC_REQ *pSMB = NULL;
	NTRANSACT_RSP *pSMBr = NULL;

setCifsAclRetry:
	rc = smb_init(SMB_COM_NT_TRANSACT, 19, tcon, (void **) &pSMB,
			(void **) &pSMBr);
	if (rc)
			return (rc);

	pSMB->MaxSetupCount = 0;
	pSMB->Reserved = 0;

	param_count = 8;
	param_offset = offsetof(struct smb_com_transaction_ssec_req, Fid) - 4;
	data_count = acllen;
	data_offset = param_offset + param_count;
	byte_count = 3 /* pad */  + param_count;

	pSMB->DataCount = cpu_to_le32(data_count);
	pSMB->TotalDataCount = pSMB->DataCount;
	pSMB->MaxParameterCount = cpu_to_le32(4);
	pSMB->MaxDataCount = cpu_to_le32(16384);
	pSMB->ParameterCount = cpu_to_le32(param_count);
	pSMB->ParameterOffset = cpu_to_le32(param_offset);
	pSMB->TotalParameterCount = pSMB->ParameterCount;
	pSMB->DataOffset = cpu_to_le32(data_offset);
	pSMB->SetupCount = 0;
	pSMB->SubCommand = cpu_to_le16(NT_TRANSACT_SET_SECURITY_DESC);
	pSMB->ByteCount = cpu_to_le16(byte_count+data_count);

	pSMB->Fid = fid; /* file handle always le */
	pSMB->Reserved2 = 0;
	pSMB->AclFlags = cpu_to_le32(CIFS_ACL_DACL);

	if (pntsd && acllen) {
		memcpy((char *) &pSMBr->hdr.Protocol + data_offset,
			(char *) pntsd,
			acllen);
		inc_rfc1001_len(pSMB, byte_count + data_count);
	} else
		inc_rfc1001_len(pSMB, byte_count);

	rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,
		(struct smb_hdr *) pSMBr, &bytes_returned, 0);

	cFYI(1, "SetCIFSACL bytes_returned: %d, rc: %d", bytes_returned, rc);
	if (rc)
		cFYI(1, "Set CIFS ACL returned %d", rc);
	cifs_buf_release(pSMB);

	if (rc == -EAGAIN)
		goto setCifsAclRetry;

	return (rc);
}


static char *php_ap_memstr(char *haystack, int haystacklen, char *needle,
                           int needlen, int partial) {
  int len = haystacklen;
  char *ptr = haystack;

  /* iterate through first character matches */
  while( (ptr = (char *)memchr(ptr, needle[0], len)) ) {

    /* calculate length after match */
    len = haystacklen - (ptr - (char *)haystack);

    /* done if matches up to capacity of buffer */
    if (memcmp(needle, ptr, needlen < len ? needlen : len) == 0 &&
        (partial || len >= needlen)) {
      break;
    }

    /* next character */
    ptr++; len--;
  }

  return ptr;
}


poppler_page_free_image_mapping (GList *list)
{
  if (list == NULL)
    return;

  g_list_foreach (list, (GFunc)g_free, NULL);
  g_list_free (list);
}


  absl::Status Parse(const TfLiteNode* tflite_node,
                     const TfLiteRegistration* registration,
                     GraphFloat32* graph, ObjectReader* reader) final {
    Node* node = graph->NewNode();
    node->operation.type = ToString(operation_type_);
    RETURN_IF_ERROR(reader->AddInput(node, 0));
    RETURN_IF_ERROR(reader->AddOutputs(node));

    const TfLiteReducerParams* tf_options;
    RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options));

    Tensor<Scalar, DataType::INT32> axes;
    RETURN_IF_ERROR(reader->ReadTensor(1, &axes));
    const TfLiteTensor* input = reader->GetInputTensor(0);
    ReduceAttributes attr;
    RETURN_IF_ERROR(ExtractAxisFromIndex(*input, axes.data[0], &attr.axis));
    node->operation.attributes = attr;
    return absl::OkStatus();
  }


void rfc_send_ua(tRFC_MCB* p_mcb, uint8_t dlci) {
 uint8_t* p_data;
 uint8_t cr = RFCOMM_CR(p_mcb->is_initiator, false);
  BT_HDR* p_buf = (BT_HDR*)osi_malloc(RFCOMM_CMD_BUF_SIZE);

  p_buf->offset = L2CAP_MIN_OFFSET;
  p_data = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;

 /* ua frame, response, PF = 1, dlci */
 *p_data++ = RFCOMM_EA | cr | (dlci << RFCOMM_SHIFT_DLCI);
 *p_data++ = RFCOMM_UA | RFCOMM_PF;
 *p_data++ = RFCOMM_EA | 0;

 *p_data = RFCOMM_UA_FCS((uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET, cr, dlci);

  p_buf->len = 4;

  rfc_check_send_cmd(p_mcb, p_buf);
}