int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *pkt)

{

    ASFContext *asf = s->priv_data;

    ASFStream *asf_st = 0;

    for (;;) {

        if(url_feof(pb))

            return AVERROR_EOF;

        if (asf->packet_size_left < FRAME_HEADER_SIZE

            || asf->packet_segments < 1) {

            //asf->packet_size_left <= asf->packet_padsize) {

            int ret = asf->packet_size_left + asf->packet_padsize;

            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));

            assert(ret>=0);

            /* fail safe */

            url_fskip(pb, ret);

            asf->packet_pos= url_ftell(pb);

            if (asf->data_object_size != (uint64_t)-1 &&

                (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))

                return AVERROR(EIO); /* Do not exceed the size of the data object */

            return 1;

        }

        if (asf->packet_time_start == 0) {

            if(asf_read_frame_header(s, pb) < 0){

                asf->packet_segments= 0;

                continue;

            }

            if (asf->stream_index < 0

                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL

                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)

                ) {

                asf->packet_time_start = 0;

                /* unhandled packet (should not happen) */

                url_fskip(pb, asf->packet_frag_size);

                asf->packet_size_left -= asf->packet_frag_size;

                if(asf->stream_index < 0)

                    av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);

                continue;

            }

            asf->asf_st = s->streams[asf->stream_index]->priv_data;

        }

        asf_st = asf->asf_st;

        if (asf->packet_replic_size == 1) {

            // frag_offset is here used as the beginning timestamp

            asf->packet_frag_timestamp = asf->packet_time_start;

            asf->packet_time_start += asf->packet_time_delta;

            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);

            asf->packet_size_left--;

            asf->packet_multi_size--;

            if (asf->packet_multi_size < asf->packet_obj_size)

            {

                asf->packet_time_start = 0;

                url_fskip(pb, asf->packet_multi_size);

                asf->packet_size_left -= asf->packet_multi_size;

                continue;

            }

            asf->packet_multi_size -= asf->packet_obj_size;

            //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);

        }

        if(   /*asf->packet_frag_size == asf->packet_obj_size*/

              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size

           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){

            av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",

                asf_st->frag_offset, asf->packet_frag_size,

                asf->packet_obj_size, asf_st->pkt.size);

            asf->packet_obj_size= asf_st->pkt.size;

        }

        if (   asf_st->pkt.size != asf->packet_obj_size

            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?

            if(asf_st->pkt.data){

                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);

                asf_st->frag_offset = 0;

                av_free_packet(&asf_st->pkt);

            }

            /* new packet */

            av_new_packet(&asf_st->pkt, asf->packet_obj_size);

            asf_st->seq = asf->packet_seq;

            asf_st->pkt.dts = asf->packet_frag_timestamp;

            asf_st->pkt.stream_index = asf->stream_index;

            asf_st->pkt.pos =

            asf_st->packet_pos= asf->packet_pos;

//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",

//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,

//s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);

            if (s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO)

                asf->packet_key_frame = 1;

            if (asf->packet_key_frame)

                asf_st->pkt.flags |= PKT_FLAG_KEY;

        }

        /* read data */

        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",

        //       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,

        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);

        asf->packet_size_left -= asf->packet_frag_size;

        if (asf->packet_size_left < 0)

            continue;

        if(   asf->packet_frag_offset >= asf_st->pkt.size

           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){

            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",

                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);

            continue;

        }

        get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,

                   asf->packet_frag_size);

        if (s->key && s->keylen == 20)

            ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,

                            asf->packet_frag_size);

        asf_st->frag_offset += asf->packet_frag_size;

        /* test if whole packet is read */

        if (asf_st->frag_offset == asf_st->pkt.size) {

            //workaround for macroshit radio DVR-MS files

            if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO

               && asf_st->pkt.size > 100){

                int i;

                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);

                if(i == asf_st->pkt.size){

                    av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");

                    asf_st->frag_offset = 0;

                    av_free_packet(&asf_st->pkt);

                    continue;

                }

            }

            /* return packet */

            if (asf_st->ds_span > 1) {

              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){

                    av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span);

              }else{

                /* packet descrambling */

                uint8_t *newdata = av_malloc(asf_st->pkt.size);

                if (newdata) {

                    int offset = 0;

                    while (offset < asf_st->pkt.size) {

                        int off = offset / asf_st->ds_chunk_size;

                        int row = off / asf_st->ds_span;

                        int col = off % asf_st->ds_span;

                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;

                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);

                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);

                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);

                        memcpy(newdata + offset,

                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,

                               asf_st->ds_chunk_size);

                        offset += asf_st->ds_chunk_size;

                    }

                    av_free(asf_st->pkt.data);

                    asf_st->pkt.data = newdata;

                }

              }

            }

            asf_st->frag_offset = 0;

            *pkt= asf_st->pkt;

            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);

            asf_st->pkt.size = 0;

            asf_st->pkt.data = 0;

            break; // packet completed

        }

    }

    return 0;

}


    void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
    {
        if (!Js::Configuration::Global.flags.ArrayValidate)
        {
            return;
        }
        int32 inspect;
        double inspectDouble;
        while (seg)
        {
            uint32 i = 0;
            for (i = 0; i < seg->length; i++)
            {
                if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
                {
                    continue;
                }
                if (TaggedInt::Is(seg->elements[i]))
                {
                    inspect = TaggedInt::ToInt32(seg->elements[i]);

                }
                else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
                {
                    inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
                }
                else
                {
                    AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
                }
            }
            ValidateSegment(seg);

            seg = (SparseArraySegment<Var>*)seg->next;
        }
    }


confFile(char *base)
{
    return expandPath(Strnew_m_charp(w3m_conf_dir(), "/", base, NULL)->ptr);
}


static int has_stopped_jobs(struct pid *pgrp)
{
	int retval = 0;
	struct task_struct *p;

	do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
		if (!task_is_stopped(p))
			continue;
		retval = 1;
		break;
	} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
	return retval;
}


static vpx_image_t *img_alloc_helper(vpx_image_t *img, vpx_img_fmt_t fmt,
 unsigned int d_w, unsigned int d_h,
 unsigned int buf_align,
 unsigned int stride_align,
 unsigned char *img_data) {
 unsigned int h, w, s, xcs, ycs, bps;
 unsigned int stride_in_bytes;
 int align;

 /* Treat align==0 like align==1 */
 if (!buf_align) buf_align = 1;

 /* Validate alignment (must be power of 2) */
 if (buf_align & (buf_align - 1)) goto fail;

 /* Treat align==0 like align==1 */
 if (!stride_align) stride_align = 1;

 /* Validate alignment (must be power of 2) */
 if (stride_align & (stride_align - 1)) goto fail;

 /* Get sample size for this format */
 switch (fmt) {
 case VPX_IMG_FMT_RGB32:
 case VPX_IMG_FMT_RGB32_LE:
 case VPX_IMG_FMT_ARGB:
 case VPX_IMG_FMT_ARGB_LE: bps = 32; break;
 case VPX_IMG_FMT_RGB24:
 case VPX_IMG_FMT_BGR24: bps = 24; break;
 case VPX_IMG_FMT_RGB565:
 case VPX_IMG_FMT_RGB565_LE:
 case VPX_IMG_FMT_RGB555:
 case VPX_IMG_FMT_RGB555_LE:
 case VPX_IMG_FMT_UYVY:
 case VPX_IMG_FMT_YUY2:
 case VPX_IMG_FMT_YVYU: bps = 16; break;
 case VPX_IMG_FMT_I420:
 case VPX_IMG_FMT_YV12:
 case VPX_IMG_FMT_VPXI420:
 case VPX_IMG_FMT_VPXYV12: bps = 12; break;
 case VPX_IMG_FMT_I422:
 case VPX_IMG_FMT_I440: bps = 16; break;
 case VPX_IMG_FMT_I444: bps = 24; break;
 case VPX_IMG_FMT_I42016: bps = 24; break;
 case VPX_IMG_FMT_I42216:
 case VPX_IMG_FMT_I44016: bps = 32; break;
 case VPX_IMG_FMT_I44416: bps = 48; break;
 default: bps = 16; break;
 }

 /* Get chroma shift values for this format */
 switch (fmt) {
 case VPX_IMG_FMT_I420:
 case VPX_IMG_FMT_YV12:
 case VPX_IMG_FMT_VPXI420:
 case VPX_IMG_FMT_VPXYV12:
 case VPX_IMG_FMT_I422:
 case VPX_IMG_FMT_I42016:
 case VPX_IMG_FMT_I42216: xcs = 1; break;
 default: xcs = 0; break;
 }

 switch (fmt) {
 case VPX_IMG_FMT_I420:
 case VPX_IMG_FMT_I440:
 case VPX_IMG_FMT_YV12:
 case VPX_IMG_FMT_VPXI420:
 case VPX_IMG_FMT_VPXYV12:
 case VPX_IMG_FMT_I42016:
 case VPX_IMG_FMT_I44016: ycs = 1; break;

     default: ycs = 0; break;
   }

  /* Calculate storage sizes. If the buffer was allocated externally, the width
   * and height shouldn't be adjusted. */
  w = d_w;
  h = d_h;
   s = (fmt & VPX_IMG_FMT_PLANAR) ? w : bps * w / 8;
   s = (s + stride_align - 1) & ~(stride_align - 1);
   stride_in_bytes = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? s * 2 : s;

 /* Allocate the new image */
 if (!img) {
    img = (vpx_image_t *)calloc(1, sizeof(vpx_image_t));

 if (!img) goto fail;

    img->self_allocd = 1;
 } else {
    memset(img, 0, sizeof(vpx_image_t));
 }

   img->img_data = img_data;

   if (!img_data) {
    uint64_t alloc_size;
    /* Calculate storage sizes given the chroma subsampling */
    align = (1 << xcs) - 1;
    w = (d_w + align) & ~align;
    align = (1 << ycs) - 1;
    h = (d_h + align) & ~align;

    s = (fmt & VPX_IMG_FMT_PLANAR) ? w : bps * w / 8;
    s = (s + stride_align - 1) & ~(stride_align - 1);
    stride_in_bytes = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? s * 2 : s;
    alloc_size = (fmt & VPX_IMG_FMT_PLANAR) ? (uint64_t)h * s * bps / 8
                                            : (uint64_t)h * s;

     if (alloc_size != (size_t)alloc_size) goto fail;

    img->img_data = (uint8_t *)vpx_memalign(buf_align, (size_t)alloc_size);
    img->img_data_owner = 1;
 }

 if (!img->img_data) goto fail;

  img->fmt = fmt;
  img->bit_depth = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? 16 : 8;
  img->w = w;
  img->h = h;
  img->x_chroma_shift = xcs;
  img->y_chroma_shift = ycs;
  img->bps = bps;

 /* Calculate strides */
  img->stride[VPX_PLANE_Y] = img->stride[VPX_PLANE_ALPHA] = stride_in_bytes;
  img->stride[VPX_PLANE_U] = img->stride[VPX_PLANE_V] = stride_in_bytes >> xcs;

 /* Default viewport to entire image */
 if (!vpx_img_set_rect(img, 0, 0, d_w, d_h)) return img;

fail:
  vpx_img_free(img);
 return NULL;
}


void Magick::Image::colorMap(const size_t index_,const Color &color_)
{
  MagickCore::Image
    *imageptr;

  imageptr=image();

  if (index_ > (MaxColormapSize-1))
    throwExceptionExplicit(MagickCore::OptionError,
      "Colormap index must be less than MaxColormapSize");

  if (!color_.isValid())
    throwExceptionExplicit(MagickCore::OptionError,
      "Color argument is invalid");

  modifyImage();

  // Ensure that colormap size is large enough
  if (colorMapSize() < (index_+1))
    colorMapSize(index_+1);

  // Set color at index in colormap
  (imageptr->colormap)[index_]=color_;
}


static void do_stop_capture(Monitor *mon, const QDict *qdict)

{

    int i;

    int n = qdict_get_int(qdict, "n");

    CaptureState *s;

    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {

        if (i == n) {

            s->ops.destroy (s->opaque);

            LIST_REMOVE (s, entries);

            qemu_free (s);

            return;

        }

    }

}


bool ReportingIsEnforcedByPolicy(bool* crash_reporting_enabled) {
  std::wstring policies_path = L"SOFTWARE\\Policies\\";
  AppendChromeInstallSubDirectory(InstallDetails::Get().mode(),
                                  false /* !include_suffix */, &policies_path);
  DWORD value = 0;

  if (nt::QueryRegValueDWORD(nt::HKLM, nt::NONE, policies_path.c_str(),
                             kMetricsReportingEnabled, &value)) {
    *crash_reporting_enabled = (value != 0);
    return true;
  }

  if (nt::QueryRegValueDWORD(nt::HKCU, nt::NONE, policies_path.c_str(),
                             kMetricsReportingEnabled, &value)) {
    *crash_reporting_enabled = (value != 0);
    return true;
  }

  return false;
}


static int jp2_getcs(jp2_colr_t *colr)
{
	if (colr->method == JP2_COLR_ENUM) {
		switch (colr->csid) {
		case JP2_COLR_SRGB:
			return JAS_CLRSPC_SRGB;
			break;
		case JP2_COLR_SYCC:
			return JAS_CLRSPC_SYCBCR;
			break;
		case JP2_COLR_SGRAY:
			return JAS_CLRSPC_SGRAY;
			break;
		}
	}
	return JAS_CLRSPC_UNKNOWN;
}


expand_idref(xmlNode * input, xmlNode * top)
{
    const char *tag = NULL;
    const char *ref = NULL;
    xmlNode *result = input;
    char *xpath_string = NULL;

    if (result == NULL) {
        return NULL;

    } else if (top == NULL) {
        top = input;
    }

    tag = crm_element_name(result);
    ref = crm_element_value(result, XML_ATTR_IDREF);

    if (ref != NULL) {
        int xpath_max = 512, offset = 0;

        xpath_string = calloc(1, xpath_max);

        offset += snprintf(xpath_string + offset, xpath_max - offset, "//%s[@id='%s']", tag, ref);
        CRM_LOG_ASSERT(offset > 0);

        result = get_xpath_object(xpath_string, top, LOG_ERR);
        if (result == NULL) {
            char *nodePath = (char *)xmlGetNodePath(top);

            crm_err("No match for %s found in %s: Invalid configuration", xpath_string,
                    crm_str(nodePath));
            free(nodePath);
        }
    }

    free(xpath_string);
    return result;
}


static enum TIFFReadDirEntryErr TIFFReadDirEntrySlongArray(TIFF* tif, TIFFDirEntry* direntry, int32** value)
{
	enum TIFFReadDirEntryErr err;
	uint32 count;
	void* origdata;
	int32* data;
	switch (direntry->tdir_type)
	{
		case TIFF_BYTE:
		case TIFF_SBYTE:
		case TIFF_SHORT:
		case TIFF_SSHORT:
		case TIFF_LONG:
		case TIFF_SLONG:
		case TIFF_LONG8:
		case TIFF_SLONG8:
			break;
		default:
			return(TIFFReadDirEntryErrType);
	}
	err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata);
	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
	{
		*value=0;
		return(err);
	}
	switch (direntry->tdir_type)
	{
		case TIFF_LONG:
			{
				uint32* m;
				uint32 n;
				m=(uint32*)origdata;
				for (n=0; n<count; n++)
				{
					if (tif->tif_flags&TIFF_SWAB)
						TIFFSwabLong((uint32*)m);
					err=TIFFReadDirEntryCheckRangeSlongLong(*m);
					if (err!=TIFFReadDirEntryErrOk)
					{
						_TIFFfree(origdata);
						return(err);
					}
					m++;
				}
				*value=(int32*)origdata;
				return(TIFFReadDirEntryErrOk);
			}
		case TIFF_SLONG:
			*value=(int32*)origdata;
			if (tif->tif_flags&TIFF_SWAB)
				TIFFSwabArrayOfLong((uint32*)(*value),count);
			return(TIFFReadDirEntryErrOk);
	}
	data=(int32*)_TIFFmalloc(count*4);
	if (data==0)
	{
		_TIFFfree(origdata);
		return(TIFFReadDirEntryErrAlloc);
	}
	switch (direntry->tdir_type)
	{
		case TIFF_BYTE:
			{
				uint8* ma;
				int32* mb;
				uint32 n;
				ma=(uint8*)origdata;
				mb=data;
				for (n=0; n<count; n++)
					*mb++=(int32)(*ma++);
			}
			break;
		case TIFF_SBYTE:
			{
				int8* ma;
				int32* mb;
				uint32 n;
				ma=(int8*)origdata;
				mb=data;
				for (n=0; n<count; n++)
					*mb++=(int32)(*ma++);
			}
			break;
		case TIFF_SHORT:
			{
				uint16* ma;
				int32* mb;
				uint32 n;
				ma=(uint16*)origdata;
				mb=data;
				for (n=0; n<count; n++)
				{
					if (tif->tif_flags&TIFF_SWAB)
						TIFFSwabShort(ma);
					*mb++=(int32)(*ma++);
				}
			}
			break;
		case TIFF_SSHORT:
			{
				int16* ma;
				int32* mb;
				uint32 n;
				ma=(int16*)origdata;
				mb=data;
				for (n=0; n<count; n++)
				{
					if (tif->tif_flags&TIFF_SWAB)
						TIFFSwabShort((uint16*)ma);
					*mb++=(int32)(*ma++);
				}
			}
			break;
		case TIFF_LONG8:
			{
				uint64* ma;
				int32* mb;
				uint32 n;
				ma=(uint64*)origdata;
				mb=data;
				for (n=0; n<count; n++)
				{
					if (tif->tif_flags&TIFF_SWAB)
						TIFFSwabLong8(ma);
					err=TIFFReadDirEntryCheckRangeSlongLong8(*ma);
					if (err!=TIFFReadDirEntryErrOk)
						break;
					*mb++=(int32)(*ma++);
				}
			}
			break;
		case TIFF_SLONG8:
			{
				int64* ma;
				int32* mb;
				uint32 n;
				ma=(int64*)origdata;
				mb=data;
				for (n=0; n<count; n++)
				{
					if (tif->tif_flags&TIFF_SWAB)
						TIFFSwabLong8((uint64*)ma);
					err=TIFFReadDirEntryCheckRangeSlongSlong8(*ma);
					if (err!=TIFFReadDirEntryErrOk)
						break;
					*mb++=(int32)(*ma++);
				}
			}
			break;
	}
	_TIFFfree(origdata);
	if (err!=TIFFReadDirEntryErrOk)
	{
		_TIFFfree(data);
		return(err);
	}
	*value=data;
	return(TIFFReadDirEntryErrOk);
}


 static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
 Object* value, WriteBarrierMode mode) {
 BackingStore::cast(backing_store)->SetValue(entry, value);
 }


int enc_untrusted_link(const char *oldpath, const char *newpath) {
  return EnsureInitializedAndDispatchSyscall(asylo::system_call::kSYS_link,
                                             oldpath, newpath);
}


ProxyChannelDelegate::ProxyChannelDelegate()
    : shutdown_event_(true, false) {
}


bool RenderFrameImpl::HandleCurrentKeyboardEvent() {
  bool did_execute_command = false;
  for (auto command : GetLocalRootRenderWidget()->edit_commands()) {
    if (!frame_->ExecuteCommand(blink::WebString::FromUTF8(command.name),
                                blink::WebString::FromUTF8(command.value)))
      break;
    did_execute_command = true;
  }

  return did_execute_command;
}


void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
	int i, c, d;

	Cmd_TokenizeString( pakSums );

	c = Cmd_Argc();
	if ( c > MAX_SEARCH_PATHS ) {
		c = MAX_SEARCH_PATHS;
	}

	fs_numServerPaks = c;

	for ( i = 0 ; i < c ; i++ ) {
		fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
	}

	if ( fs_numServerPaks ) {
		Com_DPrintf( "Connected to a pure server.\n" );
	} else
	{
		if ( fs_reordered ) {
			// show_bug.cgi?id=540
			// force a restart to make sure the search order will be correct
			Com_DPrintf( "FS search reorder is required\n" );
			FS_Restart( fs_checksumFeed );
			return;
		}
	}

	for ( i = 0 ; i < c ; i++ ) {
		if ( fs_serverPakNames[i] ) {
			Z_Free( fs_serverPakNames[i] );
		}
		fs_serverPakNames[i] = NULL;
	}
	if ( pakNames && *pakNames ) {
		Cmd_TokenizeString( pakNames );

		d = Cmd_Argc();
		if ( d > MAX_SEARCH_PATHS ) {
			d = MAX_SEARCH_PATHS;
		}

		for ( i = 0 ; i < d ; i++ ) {
			fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
		}
	}
}


static void rdp_print_bitmap_codec_guid(const GUID* guid)
{
	WLog_INFO(TAG,
	          "%08" PRIX32 "%04" PRIX16 "%04" PRIX16 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8
	          "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "%02" PRIX8 "",
	          guid->Data1, guid->Data2, guid->Data3, guid->Data4[0], guid->Data4[1], guid->Data4[2],
	          guid->Data4[3], guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
}


static void DestroyQuantumPixels(QuantumInfo *quantum_info)
{
  register ssize_t
    i;

  ssize_t
    extent;

  assert(quantum_info != (QuantumInfo *) NULL);
  assert(quantum_info->signature == MagickCoreSignature);
  assert(quantum_info->pixels != (unsigned char **) NULL);
  extent=(ssize_t) quantum_info->extent;
  for (i=0; i < (ssize_t) quantum_info->number_threads; i++)
    if (quantum_info->pixels[i] != (unsigned char *) NULL)
      {
        /*
          Did we overrun our quantum buffer?
        */
        assert(quantum_info->pixels[i][extent] == QuantumSignature);
        quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory(
          quantum_info->pixels[i]);
      }
  quantum_info->pixels=(unsigned char **) RelinquishMagickMemory(
    quantum_info->pixels);
}


static void kernel_mna_trap_fault(struct pt_regs *regs, unsigned int insn)
{
	unsigned long g2 = regs->u_regs [UREG_G2];
	unsigned long fixup = search_extables_range(regs->pc, &g2);

	if (!fixup) {
		unsigned long address = compute_effective_address(regs, insn);
        	if(address < PAGE_SIZE) {
                	printk(KERN_ALERT "Unable to handle kernel NULL pointer dereference in mna handler");
        	} else
                	printk(KERN_ALERT "Unable to handle kernel paging request in mna handler");
	        printk(KERN_ALERT " at virtual address %08lx\n",address);
		printk(KERN_ALERT "current->{mm,active_mm}->context = %08lx\n",
			(current->mm ? current->mm->context :
			current->active_mm->context));
		printk(KERN_ALERT "current->{mm,active_mm}->pgd = %08lx\n",
			(current->mm ? (unsigned long) current->mm->pgd :
			(unsigned long) current->active_mm->pgd));
	        die_if_kernel("Oops", regs);
		/* Not reached */
	}
	regs->pc = fixup;
	regs->npc = regs->pc + 4;
	regs->u_regs [UREG_G2] = g2;
}


void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)

{

    if (ch != 0 || !is_zero_range(host, size)) {

        memset(host, ch, size);

#ifndef _WIN32

        if (ch == 0 && (!kvm_enabled() || kvm_has_sync_mmu())) {

            size = size & ~(getpagesize() - 1);

            if (size > 0) {

                qemu_madvise(host, size, QEMU_MADV_DONTNEED);

            }

        }

#endif

    }

}


  MockDownloadFileManager& GetMockDownloadFileManager() {
    return *mock_download_file_manager_;
  }


int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
{
	unsigned long inactive_ratio;
	int nid = zone_to_nid(zone);
	int zid = zone_idx(zone);
	unsigned long inactive;
	unsigned long active;
	unsigned long gb;

	inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
						BIT(LRU_INACTIVE_ANON));
	active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
					      BIT(LRU_ACTIVE_ANON));

	gb = (inactive + active) >> (30 - PAGE_SHIFT);
	if (gb)
		inactive_ratio = int_sqrt(10 * gb);
	else
		inactive_ratio = 1;

	return inactive * inactive_ratio < active;
}


void GLES2DecoderPassthroughImpl::SetIgnoreCachedStateForTest(bool ignore) {}


struct sock *__udp6_lib_lookup(struct net *net,
				      const struct in6_addr *saddr, __be16 sport,
				      const struct in6_addr *daddr, __be16 dport,
				      int dif, struct udp_table *udptable)
{
	struct sock *sk, *result;
	struct hlist_nulls_node *node;
	unsigned short hnum = ntohs(dport);
	unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask);
	struct udp_hslot *hslot2, *hslot = &udptable->hash[slot];
	int score, badness, matches = 0, reuseport = 0;
	u32 hash = 0;

	rcu_read_lock();
	if (hslot->count > 10) {
		hash2 = udp6_portaddr_hash(net, daddr, hnum);
		slot2 = hash2 & udptable->mask;
		hslot2 = &udptable->hash2[slot2];
		if (hslot->count < hslot2->count)
			goto begin;

		result = udp6_lib_lookup2(net, saddr, sport,
					  daddr, hnum, dif,
					  hslot2, slot2);
		if (!result) {
			hash2 = udp6_portaddr_hash(net, &in6addr_any, hnum);
			slot2 = hash2 & udptable->mask;
			hslot2 = &udptable->hash2[slot2];
			if (hslot->count < hslot2->count)
				goto begin;

			result = udp6_lib_lookup2(net, saddr, sport,
						  &in6addr_any, hnum, dif,
						  hslot2, slot2);
		}
		rcu_read_unlock();
		return result;
	}
begin:
	result = NULL;
	badness = -1;
	sk_nulls_for_each_rcu(sk, node, &hslot->head) {
		score = compute_score(sk, net, hnum, saddr, sport, daddr, dport, dif);
		if (score > badness) {
			result = sk;
			badness = score;
			reuseport = sk->sk_reuseport;
			if (reuseport) {
				hash = inet6_ehashfn(net, daddr, hnum,
						     saddr, sport);
				matches = 1;
			}
		} else if (score == badness && reuseport) {
			matches++;
			if (((u64)hash * matches) >> 32 == 0)
				result = sk;
			hash = next_pseudo_random32(hash);
		}
	}
	/*
	 * if the nulls value we got at the end of this lookup is
	 * not the expected one, we must restart lookup.
	 * We probably met an item that was moved to another chain.
	 */
	if (get_nulls_value(node) != slot)
		goto begin;

	if (result) {
		if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
			result = NULL;
		else if (unlikely(compute_score(result, net, hnum, saddr, sport,
					daddr, dport, dif) < badness)) {
			sock_put(result);
			goto begin;
		}
	}
	rcu_read_unlock();
	return result;
}


static inline int handle_cpu_signal ( uintptr_t pc , unsigned long address , int is_write , sigset_t * old_set , void * puc ) {
 int ret ;
 # if defined ( DEBUG_SIGNAL ) qemu_printf ( "qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n" , pc , address , is_write , * ( unsigned long * ) old_set ) ;
 # endif if ( is_write && h2g_valid ( address ) && page_unprotect ( h2g ( address ) , pc , puc ) ) {
 return 1 ;
 }
 ret = cpu_handle_mmu_fault ( cpu_single_env , address , is_write , MMU_USER_IDX ) ;
 if ( ret < 0 ) {
 return 0 ;
 }
 if ( ret == 0 ) {
 return 1 ;
 }
 cpu_restore_state ( cpu_single_env , pc ) ;
 sigprocmask ( SIG_SETMASK , old_set , NULL ) ;
 exception_action ( cpu_single_env ) ;
 return 1 ;
 }


void CSoundFile::ExtendedMODCommands(CHANNELINDEX nChn, ModCommand::PARAM param)
{
	ModChannel *pChn = &m_PlayState.Chn[nChn];
	uint8 command = param & 0xF0;
	param &= 0x0F;
	switch(command)
	{
	// E0x: Set Filter
	case 0x00:
		for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
		{
			m_PlayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1));
		}
		break;
	// E1x: Fine Portamento Up
	case 0x10:	if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoUp(pChn, param); break;
	// E2x: Fine Portamento Down
	case 0x20:	if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoDown(pChn, param); break;
	// E3x: Set Glissando Control
	case 0x30:	pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break;
	// E4x: Set Vibrato WaveForm
	case 0x40:	pChn->nVibratoType = param & 0x07; break;
	// E5x: Set FineTune
	case 0x50:	if(!m_SongFlags[SONG_FIRSTTICK])
				{
					break;
				}
				if(GetType() & (MOD_TYPE_MOD | MOD_TYPE_DIGI | MOD_TYPE_AMF0 | MOD_TYPE_MED))
				{
					pChn->nFineTune = MOD2XMFineTune(param);
					if(pChn->nPeriod && pChn->rowCommand.IsNote()) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed);
				} else if(pChn->rowCommand.IsNote())
				{
					pChn->nFineTune = MOD2XMFineTune(param - 8);
					if(pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed);
				}
				break;
	// E6x: Pattern Loop
	// E7x: Set Tremolo WaveForm
	case 0x70:	pChn->nTremoloType = param & 0x07; break;
	// E8x: Set 4-bit Panning
	case 0x80:
		if(m_SongFlags[SONG_FIRSTTICK])
		{
			Panning(pChn, param, Pan4bit);
		}
		break;
	// E9x: Retrig
	case 0x90:	RetrigNote(nChn, param); break;
	// EAx: Fine Volume Up
	case 0xA0:	if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeUp(pChn, param, false); break;
	// EBx: Fine Volume Down
	case 0xB0:	if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeDown(pChn, param, false); break;
	// ECx: Note Cut
	case 0xC0:	NoteCut(nChn, param, false); break;
	// EDx: Note Delay
	// EEx: Pattern Delay
	case 0xF0:
		if(GetType() == MOD_TYPE_MOD) // MOD: Invert Loop
		{
			pChn->nEFxSpeed = param;
			if(m_SongFlags[SONG_FIRSTTICK]) InvertLoop(pChn);
		} else // XM: Set Active Midi Macro
		{
			pChn->nActiveMacro = param;
		}
		break;
	}
}


static void *cfg_wait_thread(void *arg)
{
	struct calling_instance *inst = arg;

	(void)arg;

	debug("wcall(%p): starting config wait\n", inst);
	while (inst->call_config == NULL && inst->thread_run) {
		sys_msleep(500);
	}
	if (inst->call_config)
		debug("wcall(%p): config ready!\n", inst);

	inst->thread_run = false;

	return NULL;
}


gs_malloc_wrap(gs_memory_t **wrapped, gs_malloc_memory_t *contents)
{
#  ifdef USE_RETRY_MEMORY_WRAPPER
    /*
     * This is deprecated since 'retry' for clist reversion/cycling
     * will ONLY work for monochrome, simple PS or PCL, not for a
     * color device and not for PDF or XPS with transparency
     */
    {
        gs_memory_retrying_t *rmem;
        rmem = (gs_memory_retrying_t *)
            gs_alloc_bytes_immovable((gs_memory_t *)lmem,
                                     sizeof(gs_memory_retrying_t),
                                     "gs_malloc_wrap(retrying)");
        if (rmem == 0) {
            gs_memory_locked_release(lmem);
            gs_free_object(cmem, lmem, "gs_malloc_wrap(locked)");
            return_error(gs_error_VMerror);
        }
        code = gs_memory_retrying_init(rmem, (gs_memory_t *)lmem);
        if (code < 0) {
            gs_free_object((gs_memory_t *)lmem, rmem, "gs_malloc_wrap(retrying)");
            gs_memory_locked_release(lmem);
            gs_free_object(cmem, lmem, "gs_malloc_wrap(locked)");
            return code;
        }

        *wrapped = (gs_memory_t *)rmem;
    }
#  endif /* retrying */
    return 0;
}


static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start)
{
	struct super_block *sb = inode->i_sb;
	int depth = ext_depth(inode);
	struct ext4_ext_path *path;
	handle_t *handle;
	int i = 0, err = 0;

	ext_debug("truncate since %u\n", start);

	/* probably first extent we're gonna free will be last in block */
	handle = ext4_journal_start(inode, depth + 1);
	if (IS_ERR(handle))
		return PTR_ERR(handle);

	ext4_ext_invalidate_cache(inode);

	/*
	 * We start scanning from right side, freeing all the blocks
	 * after i_size and walking into the tree depth-wise.
	 */
	path = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1), GFP_NOFS);
	if (path == NULL) {
		ext4_journal_stop(handle);
		return -ENOMEM;
	}
	path[0].p_hdr = ext_inode_hdr(inode);
	if (ext4_ext_check(inode, path[0].p_hdr, depth)) {
		err = -EIO;
		goto out;
	}
	path[0].p_depth = depth;

	while (i >= 0 && err == 0) {
		if (i == depth) {
			/* this is leaf block */
			err = ext4_ext_rm_leaf(handle, inode, path, start);
			/* root level has p_bh == NULL, brelse() eats this */
			brelse(path[i].p_bh);
			path[i].p_bh = NULL;
			i--;
			continue;
		}

		/* this is index block */
		if (!path[i].p_hdr) {
			ext_debug("initialize header\n");
			path[i].p_hdr = ext_block_hdr(path[i].p_bh);
		}

		if (!path[i].p_idx) {
			/* this level hasn't been touched yet */
			path[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);
			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;
			ext_debug("init index ptr: hdr 0x%p, num %d\n",
				  path[i].p_hdr,
				  le16_to_cpu(path[i].p_hdr->eh_entries));
		} else {
			/* we were already here, see at next index */
			path[i].p_idx--;
		}

		ext_debug("level %d - index, first 0x%p, cur 0x%p\n",
				i, EXT_FIRST_INDEX(path[i].p_hdr),
				path[i].p_idx);
		if (ext4_ext_more_to_rm(path + i)) {
			struct buffer_head *bh;
			/* go to the next level */
			ext_debug("move to level %d (block %llu)\n",
				  i + 1, idx_pblock(path[i].p_idx));
			memset(path + i + 1, 0, sizeof(*path));
			bh = sb_bread(sb, idx_pblock(path[i].p_idx));
			if (!bh) {
				/* should we reset i_size? */
				err = -EIO;
				break;
			}
			if (WARN_ON(i + 1 > depth)) {
				err = -EIO;
				break;
			}
			if (ext4_ext_check(inode, ext_block_hdr(bh),
							depth - i - 1)) {
				err = -EIO;
				break;
			}
			path[i + 1].p_bh = bh;

			/* save actual number of indexes since this
			 * number is changed at the next iteration */
			path[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);
			i++;
		} else {
			/* we finished processing this index, go up */
			if (path[i].p_hdr->eh_entries == 0 && i > 0) {
				/* index is empty, remove it;
				 * handle must be already prepared by the
				 * truncatei_leaf() */
				err = ext4_ext_rm_idx(handle, inode, path + i);
			}
			/* root level has p_bh == NULL, brelse() eats this */
			brelse(path[i].p_bh);
			path[i].p_bh = NULL;
			i--;
			ext_debug("return to level %d\n", i);
		}
	}

	/* TODO: flexible tree reduction should be here */
	if (path->p_hdr->eh_entries == 0) {
		/*
		 * truncate to zero freed all the tree,
		 * so we need to correct eh_depth
		 */
		err = ext4_ext_get_access(handle, inode, path);
		if (err == 0) {
			ext_inode_hdr(inode)->eh_depth = 0;
			ext_inode_hdr(inode)->eh_max =
				cpu_to_le16(ext4_ext_space_root(inode, 0));
			err = ext4_ext_dirty(handle, inode, path);
		}
	}
out:
	ext4_ext_drop_refs(path);
	kfree(path);
	ext4_journal_stop(handle);

	return err;
}


static void prune_init_slice(char *cg)
{
	char *point;
	point = cg + strlen(cg) - strlen(INITSCOPE);
	if (point < cg)
		 return;
	if (strcmp(point, INITSCOPE) == 0) {
		if (point == cg)
			*(point+1) = '\0';
		else
			*point = '\0';
	}
}


set_chars_option(char_u **varp)
{
    int		round, i, len, entries;
    char_u	*p, *s;
    int		c1, c2 = 0;
    struct charstab
    {
	int	*cp;
	char	*name;
    };
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
    static struct charstab filltab[] =
    {
	{&fill_stl,	"stl"},
	{&fill_stlnc,	"stlnc"},
	{&fill_vert,	"vert"},
	{&fill_fold,	"fold"},
	{&fill_diff,	"diff"},
    };
#endif
    static struct charstab lcstab[] =
    {
	{&lcs_eol,	"eol"},
	{&lcs_ext,	"extends"},
	{&lcs_nbsp,	"nbsp"},
	{&lcs_prec,	"precedes"},
	{&lcs_space,	"space"},
	{&lcs_tab2,	"tab"},
	{&lcs_trail,	"trail"},
#ifdef FEAT_CONCEAL
	{&lcs_conceal,	"conceal"},
#else
	{NULL,		"conceal"},
#endif
    };
    struct charstab *tab;

#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
    if (varp == &p_lcs)
#endif
    {
	tab = lcstab;
	entries = sizeof(lcstab) / sizeof(struct charstab);
    }
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
    else
    {
	tab = filltab;
	entries = sizeof(filltab) / sizeof(struct charstab);
    }
#endif

    /* first round: check for valid value, second round: assign values */
    for (round = 0; round <= 1; ++round)
    {
	if (round > 0)
	{
	    /* After checking that the value is valid: set defaults: space for
	     * 'fillchars', NUL for 'listchars' */
	    for (i = 0; i < entries; ++i)
		if (tab[i].cp != NULL)
		    *(tab[i].cp) = (varp == &p_lcs ? NUL : ' ');
	    if (varp == &p_lcs)
		lcs_tab1 = NUL;
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
	    else
		fill_diff = '-';
#endif
	}
	p = *varp;
	while (*p)
	{
	    for (i = 0; i < entries; ++i)
	    {
		len = (int)STRLEN(tab[i].name);
		if (STRNCMP(p, tab[i].name, len) == 0
			&& p[len] == ':'
			&& p[len + 1] != NUL)
		{
		    s = p + len + 1;
#ifdef FEAT_MBYTE
		    c1 = mb_ptr2char_adv(&s);
		    if (mb_char2cells(c1) > 1)
			continue;
#else
		    c1 = *s++;
#endif
		    if (tab[i].cp == &lcs_tab2)
		    {
			if (*s == NUL)
			    continue;
#ifdef FEAT_MBYTE
			c2 = mb_ptr2char_adv(&s);
			if (mb_char2cells(c2) > 1)
			    continue;
#else
			c2 = *s++;
#endif
		    }
		    if (*s == ',' || *s == NUL)
		    {
			if (round)
			{
			    if (tab[i].cp == &lcs_tab2)
			    {
				lcs_tab1 = c1;
				lcs_tab2 = c2;
			    }
			    else if (tab[i].cp != NULL)
				*(tab[i].cp) = c1;

			}
			p = s;
			break;
		    }
		}
	    }

	    if (i == entries)
		return e_invarg;
	    if (*p == ',')
		++p;
	}
    }

    return NULL;	/* no error */
}


int PDFiumEngine::GetMostVisiblePage() {
   if (in_flight_visible_page_)
     return *in_flight_visible_page_;

  // We can call GetMostVisiblePage through a callback from PDFium. We have
  // to defer the page deletion otherwise we could potentially delete the page
  // that originated the calling JS request and destroy the objects that are
  // currently being used.
  defer_page_unload_ = true;
   CalculateVisiblePages();
  defer_page_unload_ = false;
   return most_visible_page_;
 }


void Range::nodeChildrenWillBeRemoved(ContainerNode* container)
{
    ASSERT(container);
    ASSERT(container->document() == m_ownerDocument);
    boundaryNodeChildrenWillBeRemoved(m_start, container);
    boundaryNodeChildrenWillBeRemoved(m_end, container);
}


static long region_count(struct resv_map *resv, long f, long t)
{
	struct list_head *head = &resv->regions;
	struct file_region *rg;
	long chg = 0;

	spin_lock(&resv->lock);
	/* Locate each segment we overlap with, and count that overlap. */
	list_for_each_entry(rg, head, link) {
		long seg_from;
		long seg_to;

		if (rg->to <= f)
			continue;
		if (rg->from >= t)
			break;

		seg_from = max(rg->from, f);
		seg_to = min(rg->to, t);

		chg += seg_to - seg_from;
	}
	spin_unlock(&resv->lock);

	return chg;
}


int l2tp_packet_send(int sock, struct l2tp_packet_t *pack)
{
	uint8_t *buf = mempool_alloc(buf_pool);
	struct l2tp_avp_t *avp;
	struct l2tp_attr_t *attr;
	uint8_t *ptr;
	int n;
	int len = sizeof(pack->hdr);

	if (!buf) {
		log_emerg("l2tp: out of memory\n");
		return -1;
	}

	memset(buf, 0, L2TP_MAX_PACKET_SIZE);

	ptr = buf + sizeof(pack->hdr);

	list_for_each_entry(attr, &pack->attrs, entry) {
		if (len + sizeof(*avp) + attr->length >= L2TP_MAX_PACKET_SIZE) {
			log_error("l2tp: cann't send packet (exceeds maximum size)\n");
			mempool_free(buf);
			return -1;
		}
		avp = (struct l2tp_avp_t *)ptr;
		avp->type = htons(attr->attr->id);
		avp->M = attr->M;
		avp->H = attr->H;
		avp->length = sizeof(*avp) + attr->length;
		*(uint16_t *)ptr = htons(*(uint16_t *)ptr);
		if (attr->H)
			memcpy(avp->val, attr->val.octets, attr->length);
		else
			switch (attr->attr->type) {
			case ATTR_TYPE_INT16:
				*(int16_t *)avp->val = htons(attr->val.int16);
				break;
			case ATTR_TYPE_INT32:
				*(int32_t *)avp->val = htonl(attr->val.int32);
				break;
			case ATTR_TYPE_INT64:
				*(uint64_t *)avp->val = htobe64(attr->val.uint64);
				break;
			case ATTR_TYPE_STRING:
			case ATTR_TYPE_OCTETS:
				memcpy(avp->val, attr->val.string, attr->length);
				break;
			}
		ptr += sizeof(*avp) + attr->length;
		len += sizeof(*avp) + attr->length;
	}

	pack->hdr.length = htons(len);
	memcpy(buf, &pack->hdr, sizeof(pack->hdr));

	n = sendto(sock, buf, ntohs(pack->hdr.length), 0,
		   &pack->addr, sizeof(pack->addr));
	mempool_free(buf);

	if (n < 0) {
		if (errno == EAGAIN) {
			if (conf_verbose)
				log_warn("l2tp: buffer overflow (packet lost)\n");
		} else {
			if (conf_verbose)
				log_warn("l2tp: sendto: %s\n", strerror(errno));
			return -1;
		}
	}

	if (n != ntohs(pack->hdr.length)) {
		if (conf_verbose)
			log_warn("l2tp: short write (%i/%i)\n", n, ntohs(pack->hdr.length));
	}

	return 0;
}


TEST_F(StaticClusterImplTest, OutlierDetector) {
  const std::string yaml = R"EOF(
    name: addressportconfig
    connect_timeout: 0.25s
    type: static
    lb_policy: random
    load_assignment:
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 11001
            - endpoint:
                address:
                  socket_address:
                    address: 10.0.0.1
                    port_value: 11002
  )EOF";

  envoy::config::cluster::v3::Cluster cluster_config = parseClusterFromV3Yaml(yaml);
  Envoy::Stats::ScopePtr scope = stats_.createScope(fmt::format(
      "cluster.{}.", cluster_config.alt_stat_name().empty() ? cluster_config.name()
                                                            : cluster_config.alt_stat_name()));
  Envoy::Server::Configuration::TransportSocketFactoryContextImpl factory_context(
      admin_, ssl_context_manager_, *scope, cm_, local_info_, dispatcher_, stats_,
      singleton_manager_, tls_, validation_visitor_, *api_, options_);
  StaticClusterImpl cluster(cluster_config, runtime_, factory_context, std::move(scope), false);

  Outlier::MockDetector* detector = new Outlier::MockDetector();
  EXPECT_CALL(*detector, addChangedStateCb(_));
  cluster.setOutlierDetector(Outlier::DetectorSharedPtr{detector});
  cluster.initialize([] {});

  EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size());
  EXPECT_EQ(2UL, cluster.info()->stats().membership_healthy_.value());

  // Set a single host as having failed and fire outlier detector callbacks. This should result
  // in only a single healthy host.
  cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]->outlierDetector().putHttpResponseCode(
      503);
  cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]->healthFlagSet(
      Host::HealthFlag::FAILED_OUTLIER_CHECK);
  detector->runCallbacks(cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]);
  EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size());
  EXPECT_EQ(1UL, cluster.info()->stats().membership_healthy_.value());
  EXPECT_NE(cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts()[0],
            cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]);

  // Bring the host back online.
  cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]->healthFlagClear(
      Host::HealthFlag::FAILED_OUTLIER_CHECK);
  detector->runCallbacks(cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]);
  EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size());
  EXPECT_EQ(2UL, cluster.info()->stats().membership_healthy_.value());
}


SchedulerObject::setAttribute(std::string key,
							  std::string name,
							  std::string value,
                                                          std::string &text)
 {
        PROC_ID id = getProcByString(key.c_str());
       if (id.cluster <= 0 || id.proc < 0) {
                dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str());
                text = "Invalid Id";
                return false;
	}

	if (isSubmissionChange(name.c_str())) {
		text = "Changes to submission name not allowed";
		return false;
	}

	if (isKeyword(name.c_str())) {
		text = "Attribute name is reserved: " + name;
		return false;
	}

	if (!isValidAttributeName(name,text)) {
		return false;
	}

	if (::SetAttribute(id.cluster,
					   id.proc,
					   name.c_str(),
					   value.c_str())) {
		text = "Failed to set attribute " + name + " to " + value;
		return false;
	}

	return true;
}


static char *fgets_extending(char **buf, int *buflen, FILE *stream)
{
	char *rc;
	char endchar;
	int offset = 0;
	char *newbuf;

	do{
		rc = fgets(&((*buf)[offset]), *buflen-offset, stream);
		if(feof(stream)){
			return rc;
		}

		endchar = (*buf)[strlen(*buf)-1];
		if(endchar == '\n'){
			return rc;
		}
		/* No EOL char found, so extend buffer */
		offset = *buflen-1;
		*buflen += 1000;
		newbuf = realloc(*buf, *buflen);
		if(!newbuf){
			return NULL;
		}
		*buf = newbuf;
	}while(1);
}


 SynchronousCompositorImpl* SynchronousCompositorImpl::FromID(int process_id,
                                                              int routing_id) {
  if (g_factory == nullptr)
    return nullptr;
   RenderViewHost* rvh = RenderViewHost::FromID(process_id, routing_id);
   if (!rvh)
    return nullptr;
   WebContents* contents = WebContents::FromRenderViewHost(rvh);
   if (!contents)
    return nullptr;
   return FromWebContents(contents);
 }


ipmi_fru_oemkontron_edit( int argc, char ** argv,uint8_t * fru_data,
												int off,int len,
												struct fru_multirec_header *h,
												struct fru_multirec_oem_header *oh)
{
	static bool badParams=false;
	bool hasChanged = false;
	int start = off;
	int offset = start;
	int length = len;
	int i;
	uint8_t record_id = 0;
	offset += sizeof(struct fru_multirec_oem_header);

	if(!badParams){
		/* the 'OEM' field is already checked in caller */
		if( argc > OEM_KONTRON_SUBCOMMAND_ARG_POS ){
			if(strncmp("oem", argv[OEM_KONTRON_SUBCOMMAND_ARG_POS],3)){
				printf("usage: fru edit <id> <oem> <args...>\n");
				badParams = true;
				return hasChanged;
			}
		}
		if( argc<EDIT_OEM_KONTRON_COMPLETE_ARG_COUNT ){
			printf("usage: oem <iana> <recordid> <format> <args...>\n");
			printf("usage: oem 15000 3 0 <name> <instance> <field1>"\
					" <field2> <field3> <crc32>\n");
			badParams = true;
			return hasChanged;
		}
		if (str2uchar(argv[OEM_KONTRON_RECORDID_ARG_POS], &record_id) != 0) {
			lprintf(LOG_ERR,
					"Record ID argument '%s' is either invalid or out of range.",
					argv[OEM_KONTRON_RECORDID_ARG_POS]);
			badParams = true;
			return hasChanged;
		}
		if (record_id == OEM_KONTRON_INFORMATION_RECORD) {
			for(i=OEM_KONTRON_VERSION_ARG_POS;i<=OEM_KONTRON_CRC32_ARG_POS;i++){
				if( (strlen(argv[i]) != OEM_KONTRON_FIELD_SIZE) &&
					(strlen(argv[i]) != OEM_KONTRON_VERSION_FIELD_SIZE)) {
					printf("error: version fields must have %d characters\n",
										OEM_KONTRON_FIELD_SIZE);
					badParams = true;
					return hasChanged;
				}
			}
		}
	}

	if(!badParams){

		if(oh->record_id == OEM_KONTRON_INFORMATION_RECORD ) {
			uint8_t formatVersion = 0;
			uint8_t version;

			if (str2uchar(argv[OEM_KONTRON_FORMAT_ARG_POS], &formatVersion) != 0) {
				lprintf(LOG_ERR,
						"Format argument '%s' is either invalid or out of range.",
						argv[OEM_KONTRON_FORMAT_ARG_POS]);
				badParams = true;
				return hasChanged;
			}

			printf("   Kontron OEM Information Record\n");
			version = oh->record_version;

			if( version == formatVersion  ){
				uint8_t blockCount;
				uint8_t blockIndex=0;

				uint8_t matchInstance = 0;
				uint8_t instance = 0;

				if (str2uchar(argv[OEM_KONTRON_INSTANCE_ARG_POS], &instance) != 0) {
					lprintf(LOG_ERR,
							"Instance argument '%s' is either invalid or out of range.",
							argv[OEM_KONTRON_INSTANCE_ARG_POS]);
					badParams = true;
					return hasChanged;
				}

				blockCount = fru_data[offset++];
				printf("   blockCount: %d\n",blockCount);

				for(blockIndex=0;blockIndex<blockCount;blockIndex++){
					void * pRecordData;
					uint8_t nameLen;

					nameLen = ( fru_data[offset++] & 0x3F );

					if( version == 0 || version == 1 )
					{
						if(!strncmp((char *)argv[OEM_KONTRON_NAME_ARG_POS],
						(const char *)(fru_data+offset),nameLen)&& (matchInstance == instance)){

							printf ("Found : %s\n",argv[OEM_KONTRON_NAME_ARG_POS]);
							offset+=nameLen;

							pRecordData =  &fru_data[offset];

							if( version == 0 )
							{
								memcpy( ((tOemKontronInformationRecordV0 *)
															pRecordData)->field1 ,
								argv[OEM_KONTRON_VERSION_ARG_POS] ,
								OEM_KONTRON_FIELD_SIZE);
								memcpy( ((tOemKontronInformationRecordV0 *)
															pRecordData)->field2 ,
								argv[OEM_KONTRON_BUILDDATE_ARG_POS],
								OEM_KONTRON_FIELD_SIZE);
								memcpy( ((tOemKontronInformationRecordV0 *)
															pRecordData)->field3 ,
								argv[OEM_KONTRON_UPDATEDATE_ARG_POS],
								OEM_KONTRON_FIELD_SIZE);
								memcpy( ((tOemKontronInformationRecordV0 *)
															pRecordData)->crc32 ,
							argv[OEM_KONTRON_CRC32_ARG_POS] ,
							OEM_KONTRON_FIELD_SIZE);
							}
							else
							{
								memcpy( ((tOemKontronInformationRecordV1 *)
															pRecordData)->field1 ,
								argv[OEM_KONTRON_VERSION_ARG_POS] ,
								OEM_KONTRON_VERSION_FIELD_SIZE);
								memcpy( ((tOemKontronInformationRecordV1 *)
															pRecordData)->field2 ,
								argv[OEM_KONTRON_BUILDDATE_ARG_POS],
								OEM_KONTRON_FIELD_SIZE);
								memcpy( ((tOemKontronInformationRecordV1 *)
															pRecordData)->field3 ,
								argv[OEM_KONTRON_UPDATEDATE_ARG_POS],
								OEM_KONTRON_FIELD_SIZE);
								memcpy( ((tOemKontronInformationRecordV1 *)
															pRecordData)->crc32 ,
							argv[OEM_KONTRON_CRC32_ARG_POS] ,
							OEM_KONTRON_FIELD_SIZE);
							}

							matchInstance++;
							hasChanged = true;
						}
						else if(!strncmp((char *)argv[OEM_KONTRON_NAME_ARG_POS],
							(const char *)(fru_data+offset), nameLen)){
							printf ("Skipped : %s  [instance %d]\n",argv[OEM_KONTRON_NAME_ARG_POS],
									(unsigned int)matchInstance);
							matchInstance++;
							offset+=nameLen;
						}
						else {
							offset+=nameLen;
						}

						if( version == 0 )
						{
							offset+= sizeof(tOemKontronInformationRecordV0);
						}
						else
						{
							offset+= sizeof(tOemKontronInformationRecordV1);
						}
						offset++;
					}
					else
					{
						printf ("  Unsupported version %d\n",version);
					}
				}
			}
			else{
				printf("   Version: %d\n",version);
			}
		}
		if( hasChanged ){

			uint8_t record_checksum =0;
			uint8_t header_checksum =0;
			int index;

			lprintf(LOG_DEBUG,"Initial record checksum : %x",h->record_checksum);
			lprintf(LOG_DEBUG,"Initial header checksum : %x",h->header_checksum);
			for(index=0;index<length;index++){
				record_checksum+=  fru_data[start+index];
			}
			/* Update Record checksum */
			h->record_checksum =  ~record_checksum + 1;

			for(index=0;index<(sizeof(struct fru_multirec_header) -1);index++){
				uint8_t data= *( (uint8_t *)h+ index);
				header_checksum+=data;
			}
			/* Update header checksum */
			h->header_checksum =  ~header_checksum + 1;

			lprintf(LOG_DEBUG,"Final record checksum : %x",h->record_checksum);
			lprintf(LOG_DEBUG,"Final header checksum : %x",h->header_checksum);

			/* write back data */
		}
	}

	return hasChanged;
}


static bool CalculateReachability(SCNetworkConnectionFlags flags) {
  bool reachable = flags & kSCNetworkFlagsReachable;
  bool connection_required = flags & kSCNetworkFlagsConnectionRequired;
  return reachable && !connection_required;
}


static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd,
				unsigned long addr, unsigned long end,
				unsigned long floor, unsigned long ceiling)
{
	pud_t *pud;
	unsigned long next;
	unsigned long start;

	start = addr;
	pud = pud_offset(pgd, addr);
	do {
		next = pud_addr_end(addr, end);
		if (pud_none_or_clear_bad(pud))
			continue;
		free_pmd_range(tlb, pud, addr, next, floor, ceiling);
	} while (pud++, addr = next, addr != end);

	start &= PGDIR_MASK;
	if (start < floor)
		return;
	if (ceiling) {
		ceiling &= PGDIR_MASK;
		if (!ceiling)
			return;
	}
	if (end - 1 > ceiling - 1)
		return;

	pud = pud_offset(pgd, start);
	pgd_clear(pgd);
	pud_free_tlb(tlb, pud, start);
}


static void av1dmx_finalize(GF_Filter *filter)
{
	GF_AV1DmxCtx *ctx = gf_filter_get_udta(filter);
	if (ctx->bs) gf_bs_del(ctx->bs);
	if (ctx->indexes) gf_free(ctx->indexes);

	gf_av1_reset_state(&ctx->state, GF_TRUE);
	if (ctx->state.config) gf_odf_av1_cfg_del(ctx->state.config);
	if (ctx->state.bs) gf_bs_del(ctx->state.bs);
	if (ctx->state.frame_obus) gf_free(ctx->state.frame_obus);
	if (ctx->buffer) gf_free(ctx->buffer);

	if (ctx->vp_cfg) gf_odf_vp_cfg_del(ctx->vp_cfg);
}


static int __init key_proc_init(void)
{
	struct proc_dir_entry *p;

	p = proc_create("keys", 0, NULL, &proc_keys_fops);
	if (!p)
		panic("Cannot create /proc/keys\n");

	p = proc_create("key-users", 0, NULL, &proc_key_users_fops);
	if (!p)
		panic("Cannot create /proc/key-users\n");

	return 0;
}


static int spapr_fixup_cpu_dt(void *fdt, sPAPREnvironment *spapr)

{

    int ret = 0, offset, cpus_offset;

    CPUState *cs;

    char cpu_model[32];

    int smt = kvmppc_smt_threads();

    uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)};

    CPU_FOREACH(cs) {

        PowerPCCPU *cpu = POWERPC_CPU(cs);

        DeviceClass *dc = DEVICE_GET_CLASS(cs);

        int index = ppc_get_vcpu_dt_id(cpu);

        uint32_t associativity[] = {cpu_to_be32(0x5),

                                    cpu_to_be32(0x0),

                                    cpu_to_be32(0x0),

                                    cpu_to_be32(0x0),

                                    cpu_to_be32(cs->numa_node),

                                    cpu_to_be32(index)};

        if ((index % smt) != 0) {

            continue;

        }

        snprintf(cpu_model, 32, "%s@%x", dc->fw_name, index);

        cpus_offset = fdt_path_offset(fdt, "/cpus");

        if (cpus_offset < 0) {

            cpus_offset = fdt_add_subnode(fdt, fdt_path_offset(fdt, "/"),

                                          "cpus");

            if (cpus_offset < 0) {

                return cpus_offset;

            }

        }

        offset = fdt_subnode_offset(fdt, cpus_offset, cpu_model);

        if (offset < 0) {

            offset = fdt_add_subnode(fdt, cpus_offset, cpu_model);

            if (offset < 0) {

                return offset;

            }

        }

        if (nb_numa_nodes > 1) {

            ret = fdt_setprop(fdt, offset, "ibm,associativity", associativity,

                              sizeof(associativity));

            if (ret < 0) {

                return ret;

            }

        }

        ret = fdt_setprop(fdt, offset, "ibm,pft-size",

                          pft_size_prop, sizeof(pft_size_prop));

        if (ret < 0) {

            return ret;

        }

        ret = spapr_fixup_cpu_smt_dt(fdt, offset, cpu,

                                     smp_threads);

        if (ret < 0) {

            return ret;

        }

    }

    return ret;

}


static const EVP_MD *rsa_mgf1_to_md(X509_ALGOR *alg, X509_ALGOR *maskHash)
{
    const EVP_MD *md;
    if (!alg)
        return EVP_sha1();
    /* Check mask and lookup mask hash algorithm */
    if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) {
        RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_ALGORITHM);
        return NULL;
    }
    if (!maskHash) {
        RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_PARAMETER);
        return NULL;
    }
    md = EVP_get_digestbyobj(maskHash->algorithm);
    if (md == NULL) {
        RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNKNOWN_MASK_DIGEST);
        return NULL;
    }
    return md;
}


bool AppCacheDatabase::InsertCache(const CacheRecord* record) {
  if (!LazyOpen(kCreateIfNeeded))
    return false;

   static const char kSql[] =
       "INSERT INTO Caches (cache_id, group_id, online_wildcard,"
      "                    update_time, cache_size)"
      "  VALUES(?, ?, ?, ?, ?)";

   sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
   statement.BindInt64(0, record->cache_id);
   statement.BindInt64(1, record->group_id);
   statement.BindBool(2, record->online_wildcard);
   statement.BindInt64(3, record->update_time.ToInternalValue());
   statement.BindInt64(4, record->cache_size);

   return statement.Run();
 }


static void test_iterators()
{
    json_t *object, *foo, *bar, *baz;
    void *iter;

    if(json_object_iter(NULL))
        fail("able to iterate over NULL");

    if(json_object_iter_next(NULL, NULL))
        fail("able to increment an iterator on a NULL object");

    object = json_object();
    foo = json_string("foo");
    bar = json_string("bar");
    baz = json_string("baz");
    if(!object || !foo || !bar || !bar)
        fail("unable to create values");

    if(json_object_iter_next(object, NULL))
        fail("able to increment a NULL iterator");

    if(json_object_set(object, "a", foo) ||
       json_object_set(object, "b", bar) ||
       json_object_set(object, "c", baz))
        fail("unable to populate object");

    iter = json_object_iter(object);
    if(!iter)
        fail("unable to get iterator");
    if(strcmp(json_object_iter_key(iter), "a"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != foo)
        fail("iterating failed: wrong value");

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    if(strcmp(json_object_iter_key(iter), "b"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != bar)
        fail("iterating failed: wrong value");

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    if(strcmp(json_object_iter_key(iter), "c"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != baz)
        fail("iterating failed: wrong value");

    if(json_object_iter_next(object, iter) != NULL)
        fail("able to iterate over the end");

    if(json_object_iter_at(object, "foo"))
        fail("json_object_iter_at() succeeds for non-existent key");

    iter = json_object_iter_at(object, "b");
    if(!iter)
        fail("json_object_iter_at() fails for an existing key");

    if(strcmp(json_object_iter_key(iter), "b"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != bar)
        fail("iterating failed: wrong value");

    iter = json_object_iter_next(object, iter);
    if(!iter)
        fail("unable to increment iterator");
    if(strcmp(json_object_iter_key(iter), "c"))
        fail("iterating failed: wrong key");
    if(json_object_iter_value(iter) != baz)
        fail("iterating failed: wrong value");

    if(json_object_iter_set(object, iter, bar))
        fail("unable to set value at iterator");

    if(strcmp(json_object_iter_key(iter), "c"))
        fail("json_object_iter_key() fails after json_object_iter_set()");
    if(json_object_iter_value(iter) != bar)
        fail("json_object_iter_value() fails after json_object_iter_set()");
    if(json_object_get(object, "c") != bar)
        fail("json_object_get() fails after json_object_iter_set()");

    json_decref(object);
    json_decref(foo);
    json_decref(bar);
    json_decref(baz);
}


dissect_fach_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
                          int offset, struct fp_info *p_fp_info, void *data)
{
    gboolean is_control_frame;
    guint16 header_crc = 0;
    proto_item * header_crc_pi = NULL;
    guint header_length = 0;

    /* Header CRC */
    header_crc = tvb_get_bits8(tvb, 0, 7);
    header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN);

    /* Frame Type */
    is_control_frame = tvb_get_guint8(tvb, offset) & 0x01;
    proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN);
    offset++;

    col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] ");

    if (is_control_frame) {
        dissect_common_control(tvb, pinfo, tree, offset, p_fp_info);
        /* For control frame the header CRC is actually frame CRC covering all
         * bytes except the first */
        if (preferences_header_checksum) {
            verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc);
        }
    }
    else {
        guint8 cfn;
        /* DATA */

        /* CFN */
        cfn = tvb_get_guint8(tvb, offset);
        proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN);
        offset++;

        col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn);

        /* TFI */
        proto_tree_add_item(tree, hf_fp_fach_tfi, tvb, offset, 1, ENC_BIG_ENDIAN);
        offset++;

        /* Transmit power level */
        proto_tree_add_float(tree, hf_fp_transmit_power_level, tvb, offset, 1,
                             (float)(int)(tvb_get_guint8(tvb, offset)) / 10);
        offset++;
        header_length = offset;

        /* TB data */
        offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, &mac_fdd_fach_handle, data);

        /* New IE flags (if it looks as though they are present) */
        if ((p_fp_info->release == 7) &&
            (tvb_reported_length_remaining(tvb, offset) > 2)) {

            guint8 flags = tvb_get_guint8(tvb, offset);
            guint8 aoa_present = flags & 0x01;
            offset++;

            if (aoa_present) {
                proto_tree_add_item(tree, hf_fp_angle_of_arrival, tvb, offset, 2, ENC_BIG_ENDIAN);
                offset += 2;
            }
        }
        if (preferences_header_checksum) {
            verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length);
        }
        /* Spare Extension and Payload CRC */
        dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length);
    }
}


static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
		apr_hash_t *scrub) {

	const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;

	/* get an array representation of the incoming HTTP headers */
	const apr_array_header_t * const h = apr_table_elts(r->headers_in);

	/* table to keep the non-suspicious headers */
	apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);

	/* loop over the incoming HTTP headers */
	const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
	int i;
	for (i = 0; i < h->nelts; i++) {
		const char * const k = e[i].key;

		/* is this header's name equivalent to a header that needs scrubbing? */
		const char *hdr =
				(k != NULL) && (scrub != NULL) ?
						apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
		const int header_matches = (hdr != NULL)
						&& (oidc_strnenvcmp(k, hdr, -1) == 0);

		/*
		 * would this header be interpreted as a mod_auth_openidc attribute? Note
		 * that prefix_len will be zero if no attr_prefix is defined,
		 * so this will always be false. Also note that we do not
		 * scrub headers if the prefix is empty because every header
		 * would match.
		 */
		const int prefix_matches = (k != NULL) && prefix_len
				&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);

		/* add to the clean_headers if non-suspicious, skip and report otherwise */
		if (!prefix_matches && !header_matches) {
			apr_table_addn(clean_headers, k, e[i].val);
		} else {
			oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
					e[i].val);
		}
	}

	/* overwrite the incoming headers with the cleaned result */
	r->headers_in = clean_headers;
}


mrb_define_singleton_method_id(mrb_state *mrb, struct RObject *o, mrb_sym name, mrb_func_t func, mrb_aspec aspec)
{
  prepare_singleton_class(mrb, (struct RBasic*)o);
  mrb_define_method_id(mrb, o->c, name, func, aspec);
}


static int tipc_skb_tailroom(struct sk_buff *skb)
{
	int tailroom;
	int limit;

	tailroom = skb_tailroom(skb);
	limit = TIPC_SKB_MAX - skb->len;

	if (tailroom < limit)
		return tailroom;

	return limit;
}


static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,

                          int nb_sectors, QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster;

    uint64_t cluster_offset;

    int ret = 0, n;

    struct iovec hd_iov;

    QEMUIOVector hd_qiov;

    uint8_t *buf;

    void *orig_buf;

    s->cluster_cache_offset = -1; /* disable compressed cache */

    /* We must always copy the iov when encrypting, so we

     * don't modify the original data buffer during encryption */

    if (bs->encrypted || qiov->niov > 1) {

        buf = orig_buf = qemu_try_blockalign(bs, qiov->size);

        if (buf == NULL) {

            return -ENOMEM;

        }

        qemu_iovec_to_buf(qiov, 0, buf, qiov->size);

    } else {

        orig_buf = NULL;

        buf = (uint8_t *)qiov->iov->iov_base;

    }

    qemu_co_mutex_lock(&s->lock);

    while (nb_sectors != 0) {

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        n = s->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,

                                            index_in_cluster,

                                            index_in_cluster + n);

        if (!cluster_offset || (cluster_offset & 511) != 0) {

            ret = -EIO;

            break;

        }

        if (bs->encrypted) {

            Error *err = NULL;

            assert(s->cipher);

            if (encrypt_sectors(s, sector_num, buf, n, true, &err) < 0) {

                error_free(err);

                ret = -EIO;

                break;

            }

        }

        hd_iov.iov_base = (void *)buf;

        hd_iov.iov_len = n * 512;

        qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);

        qemu_co_mutex_unlock(&s->lock);

        ret = bdrv_co_writev(bs->file,

                             (cluster_offset >> 9) + index_in_cluster,

                             n, &hd_qiov);

        qemu_co_mutex_lock(&s->lock);

        if (ret < 0) {

            break;

        }

        ret = 0;

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

    qemu_co_mutex_unlock(&s->lock);

    qemu_vfree(orig_buf);

    return ret;

}


static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,

                                     const uint8_t *buf, int len)

{

    unsigned int ssrc, h;

    int payload_type, seq, ret, flags = 0;

    int ext;

    AVStream *st;

    uint32_t timestamp;

    int rv = 0;

    ext          = buf[0] & 0x10;

    payload_type = buf[1] & 0x7f;

    if (buf[1] & 0x80)

        flags |= RTP_FLAG_MARKER;

    seq       = AV_RB16(buf + 2);

    timestamp = AV_RB32(buf + 4);

    ssrc      = AV_RB32(buf + 8);

    /* store the ssrc in the RTPDemuxContext */

    s->ssrc = ssrc;

    /* NOTE: we can handle only one payload type */

    if (s->payload_type != payload_type)

        return -1;

    st = s->st;

    // only do something with this if all the rtp checks pass...

    if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {

        av_log(st ? st->codec : NULL, AV_LOG_ERROR,

               "RTP: PT=%02x: bad cseq %04x expected=%04x\n",

               payload_type, seq, ((s->seq + 1) & 0xffff));

        return -1;

    }

    if (buf[0] & 0x20) {

        int padding = buf[len - 1];

        if (len >= 12 + padding)

            len -= padding;

    }

    s->seq = seq;

    len   -= 12;

    buf   += 12;

    /* RFC 3550 Section 5.3.1 RTP Header Extension handling */

    if (ext) {

        if (len < 4)

            return -1;

        /* calculate the header extension length (stored as number

         * of 32-bit words) */

        ext = (AV_RB16(buf + 2) + 1) << 2;

        if (len < ext)

            return -1;

        // skip past RTP header extension

        len -= ext;

        buf += ext;

    }

    if (!st) {

        /* specific MPEG2-TS demux support */

        ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);

        /* The only error that can be returned from ff_mpegts_parse_packet

         * is "no more data to return from the provided buffer", so return

         * AVERROR(EAGAIN) for all errors */

        if (ret < 0)

            return AVERROR(EAGAIN);

        if (ret < len) {

            s->read_buf_size = len - ret;

            memcpy(s->buf, buf + ret, s->read_buf_size);

            s->read_buf_index = 0;

            return 1;

        }

        return 0;

    } else if (s->parse_packet) {

        rv = s->parse_packet(s->ic, s->dynamic_protocol_context,

                             s->st, pkt, &timestamp, buf, len, flags);

    } else {

        /* At this point, the RTP header has been stripped;

         * This is ASSUMING that there is only 1 CSRC, which isn't wise. */

        switch (st->codec->codec_id) {

        case AV_CODEC_ID_MP2:

        case AV_CODEC_ID_MP3:

            /* better than nothing: skip MPEG audio RTP header */

            if (len <= 4)

                return -1;

            h    = AV_RB32(buf);

            len -= 4;

            buf += 4;

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        case AV_CODEC_ID_MPEG1VIDEO:

        case AV_CODEC_ID_MPEG2VIDEO:

            /* better than nothing: skip MPEG video RTP header */

            if (len <= 4)

                return -1;

            h    = AV_RB32(buf);

            buf += 4;

            len -= 4;

            if (h & (1 << 26)) {

                /* MPEG-2 */

                if (len <= 4)

                    return -1;

                buf += 4;

                len -= 4;

            }

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        default:

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        }

        pkt->stream_index = st->index;

    }

    // now perform timestamp things....

    finalize_packet(s, pkt, timestamp);

    return rv;

}


v8::Local<v8::Object> V8InjectedScriptHost::create(v8::Local<v8::Context> context, V8InspectorImpl* inspector)
 {
     v8::Isolate* isolate = inspector->isolate();
     v8::Local<v8::Object> injectedScriptHost = v8::Object::New(isolate);
    bool success = injectedScriptHost->SetPrototype(context, v8::Null(isolate)).FromMaybe(false);
    DCHECK(success);
     v8::Local<v8::External> debuggerExternal = v8::External::New(isolate, inspector);
     setFunctionProperty(context, injectedScriptHost, "internalConstructorName", V8InjectedScriptHost::internalConstructorNameCallback, debuggerExternal);
     setFunctionProperty(context, injectedScriptHost, "formatAccessorsAsProperties", V8InjectedScriptHost::formatAccessorsAsProperties, debuggerExternal);
    setFunctionProperty(context, injectedScriptHost, "subtype", V8InjectedScriptHost::subtypeCallback, debuggerExternal);
    setFunctionProperty(context, injectedScriptHost, "getInternalProperties", V8InjectedScriptHost::getInternalPropertiesCallback, debuggerExternal);
    setFunctionProperty(context, injectedScriptHost, "objectHasOwnProperty", V8InjectedScriptHost::objectHasOwnPropertyCallback, debuggerExternal);
    setFunctionProperty(context, injectedScriptHost, "bind", V8InjectedScriptHost::bindCallback, debuggerExternal);
    setFunctionProperty(context, injectedScriptHost, "proxyTargetValue", V8InjectedScriptHost::proxyTargetValueCallback, debuggerExternal);
    return injectedScriptHost;
}


  UsageAndQuotaDispatcherTaskForTemporaryGlobal(
      QuotaManager* manager, const HostAndType& host_and_type)
      : UsageAndQuotaDispatcherTask(manager, host_and_type) {}


static int pfpu_decode_insn(MilkymistPFPUState *s)

{

    uint32_t pc = s->regs[R_PC];

    uint32_t insn = s->microcode[pc];

    uint32_t reg_a = (insn >> 18) & 0x7f;

    uint32_t reg_b = (insn >> 11) & 0x7f;

    uint32_t op = (insn >> 7) & 0xf;

    uint32_t reg_d = insn & 0x7f;

    uint32_t r = 0;

    int latency = 0;

    switch (op) {

    case OP_NOP:

        break;

    case OP_FADD:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a + b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FADD;

        D_EXEC(qemu_log("ADD a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FSUB:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a - b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FSUB;

        D_EXEC(qemu_log("SUB a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FMUL:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a * b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FMUL;

        D_EXEC(qemu_log("MUL a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FABS:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float t = fabsf(a);

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FABS;

        D_EXEC(qemu_log("ABS a=%f t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_F2I:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        int32_t t = a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_F2I;

        D_EXEC(qemu_log("F2I a=%f t=%d, r=%08x\n", a, t, r));

    } break;

    case OP_I2F:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_I2F;

        D_EXEC(qemu_log("I2F a=%08x t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_VECTOUT:

    {

        uint32_t a = cpu_to_be32(s->gp_regs[reg_a]);

        uint32_t b = cpu_to_be32(s->gp_regs[reg_b]);

        target_phys_addr_t dma_ptr =

            get_dma_address(s->regs[R_MESHBASE],

                    s->gp_regs[GPR_X], s->gp_regs[GPR_Y]);

        cpu_physical_memory_write(dma_ptr, (uint8_t *)&a, 4);

        cpu_physical_memory_write(dma_ptr + 4, (uint8_t *)&b, 4);

        s->regs[R_LASTDMA] = dma_ptr + 4;

        D_EXEC(qemu_log("VECTOUT a=%08x b=%08x dma=%08x\n", a, b, dma_ptr));

        trace_milkymist_pfpu_vectout(a, b, dma_ptr);

    } break;

    case OP_SIN:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = sinf(a * (1.0f / (M_PI * 4096.0f)));

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_SIN;

        D_EXEC(qemu_log("SIN a=%d t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_COS:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = cosf(a * (1.0f / (M_PI * 4096.0f)));

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_COS;

        D_EXEC(qemu_log("COS a=%d t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_ABOVE:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (a > b) ? 1.0f : 0.0f;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_ABOVE;

        D_EXEC(qemu_log("ABOVE a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_EQUAL:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (a == b) ? 1.0f : 0.0f;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_EQUAL;

        D_EXEC(qemu_log("EQUAL a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_COPY:

    {

        r = s->gp_regs[reg_a];

        latency = LATENCY_COPY;

        D_EXEC(qemu_log("COPY"));

    } break;

    case OP_IF:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        uint32_t f = s->gp_regs[GPR_FLAGS];

        float t = (f != 0) ? a : b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_IF;

        D_EXEC(qemu_log("IF f=%u a=%f b=%f t=%f, r=%08x\n", f, a, b, t, r));

    } break;

    case OP_TSIGN:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (b < 0) ? -a : a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_TSIGN;

        D_EXEC(qemu_log("TSIGN a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_QUAKE:

    {

        uint32_t a = s->gp_regs[reg_a];

        r = 0x5f3759df - (a >> 1);

        latency = LATENCY_QUAKE;

        D_EXEC(qemu_log("QUAKE a=%d r=%08x\n", a, r));

    } break;

    default:

        error_report("milkymist_pfpu: unknown opcode %d", op);

        break;

    }

    if (!reg_d) {

        D_EXEC(qemu_log("%04d %8s R%03d, R%03d <L=%d, E=%04d>\n",

                    s->regs[R_PC], opcode_to_str[op], reg_a, reg_b, latency,

                    s->regs[R_PC] + latency));

    } else {

        D_EXEC(qemu_log("%04d %8s R%03d, R%03d <L=%d, E=%04d> -> R%03d\n",

                    s->regs[R_PC], opcode_to_str[op], reg_a, reg_b, latency,

                    s->regs[R_PC] + latency, reg_d));

    }

    if (op == OP_VECTOUT) {

        return 0;

    }

    /* store output for this cycle */

    if (reg_d) {

        uint32_t val = output_queue_remove(s);

        D_EXEC(qemu_log("R%03d <- 0x%08x\n", reg_d, val));

        s->gp_regs[reg_d] = val;

    }

    output_queue_advance(s);

    /* store op output */

    if (op != OP_NOP) {

        output_queue_insert(s, r, latency-1);

    }

    /* advance PC */

    s->regs[R_PC]++;

    return 1;

};


static int midi_setup_timesignature(struct _mdi *mdi, uint32_t setting) {
    MIDI_EVENT_DEBUG(__FUNCTION__,0, setting);
    _WM_CheckEventMemoryPool(mdi);
    mdi->events[mdi->event_count].do_event = *_WM_do_meta_timesignature;
    mdi->events[mdi->event_count].event_data.channel = 0;
    mdi->events[mdi->event_count].event_data.data.value = setting;
    mdi->events[mdi->event_count].samples_to_next = 0;
    mdi->event_count++;
    return (0);
}


static int decode_number(struct archive_read* a, struct decode_table* table,
    const uint8_t* p, uint16_t* num)
{
	int i, bits, dist;
	uint16_t bitfield;
	uint32_t pos;
	struct rar5* rar = get_context(a);

	if(ARCHIVE_OK != read_bits_16(rar, p, &bitfield)) {
		return ARCHIVE_EOF;
	}

	bitfield &= 0xfffe;

	if(bitfield < table->decode_len[table->quick_bits]) {
		int code = bitfield >> (16 - table->quick_bits);
		skip_bits(rar, table->quick_len[code]);
		*num = table->quick_num[code];
		return ARCHIVE_OK;
	}

	bits = 15;

	for(i = table->quick_bits + 1; i < 15; i++) {
		if(bitfield < table->decode_len[i]) {
			bits = i;
			break;
		}
	}

	skip_bits(rar, bits);

	dist = bitfield - table->decode_len[bits - 1];
	dist >>= (16 - bits);
	pos = table->decode_pos[bits] + dist;

	if(pos >= table->size)
		pos = 0;

	*num = table->decode_num[pos];
	return ARCHIVE_OK;
}


static void lsf2lsp_for_mode12k2 ( AMRContext * p , double lsp [ LP_FILTER_ORDER ] , const float lsf_no_r [ LP_FILTER_ORDER ] , const int16_t * lsf_quantizer [ 5 ] , const int quantizer_offset , const int sign , const int update ) {
 int16_t lsf_r [ LP_FILTER_ORDER ] ;
 float lsf_q [ LP_FILTER_ORDER ] ;
 int i ;
 for ( i = 0 ;
 i < LP_FILTER_ORDER >> 1 ;
 i ++ ) memcpy ( & lsf_r [ i << 1 ] , & lsf_quantizer [ i ] [ quantizer_offset ] , 2 * sizeof ( * lsf_r ) ) ;
 if ( sign ) {
 lsf_r [ 4 ] *= - 1 ;
 lsf_r [ 5 ] *= - 1 ;
 }
 if ( update ) memcpy ( p -> prev_lsf_r , lsf_r , LP_FILTER_ORDER * sizeof ( * lsf_r ) ) ;
 for ( i = 0 ;
 i < LP_FILTER_ORDER ;
 i ++ ) lsf_q [ i ] = lsf_r [ i ] * ( LSF_R_FAC / 8000.0 ) + lsf_no_r [ i ] * ( 1.0 / 8000.0 ) ;
 ff_set_min_dist_lsf ( lsf_q , MIN_LSF_SPACING , LP_FILTER_ORDER ) ;
 if ( update ) interpolate_lsf ( p -> lsf_q , lsf_q ) ;
 ff_acelp_lsf2lspd ( lsp , lsf_q , LP_FILTER_ORDER ) ;
 }


 static void array_cleanup( char* arr[] , int arr_size)
 {
 	int i=0;
	for( i=0; i< arr_size; i++ ){
 		if( arr[i*2] ){
 			efree( arr[i*2]);
 		}
	}
	efree(arr);
}


static int auth_session_timeout_cb(CALLBACK_FRAME) {
  pr_event_generate("core.timeout-session", NULL);
  pr_response_send_async(R_421,
    _("Session Timeout (%d seconds): closing control connection"),
    TimeoutSession);

  pr_log_pri(PR_LOG_NOTICE, "%s", "FTP session timed out, disconnected");
  pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT,
    "TimeoutSession");

  /* no need to restart the timer -- session's over */
  return 0;
}


XMLTokenizer::~XMLTokenizer()
{
    setCurrentNode(0);
    if (m_parsingFragment && m_doc)
        m_doc->deref();
    if (m_pendingScript)
        m_pendingScript->removeClient(this);
    if (m_context)
        xmlFreeParserCtxt(m_context);
}


get_list_range(char_u **str, int *num1, int *num2)
{
    int		len;
    int		first = FALSE;
    varnumber_T	num;

    *str = skipwhite(*str);
    if (**str == '-' || vim_isdigit(**str))  // parse "from" part of range
    {
	vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, FALSE);
	*str += len;
	*num1 = (int)num;
	first = TRUE;
    }
    *str = skipwhite(*str);
    if (**str == ',')			// parse "to" part of range
    {
	*str = skipwhite(*str + 1);
	vim_str2nr(*str, NULL, &len, 0, &num, NULL, 0, FALSE);
	if (len > 0)
	{
	    *num2 = (int)num;
	    *str = skipwhite(*str + len);
	}
	else if (!first)		// no number given at all
	    return FAIL;
    }
    else if (first)			// only one number given
	*num2 = *num1;
    return OK;
}


static JSValueRef touchCancelCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
    notImplemented();
    return JSValueMakeUndefined(context);
}


void fw_cfg_add_i64(FWCfgState *s, uint16_t key, uint64_t value)

{

    uint64_t *copy;

    copy = g_malloc(sizeof(value));

    *copy = cpu_to_le64(value);

    fw_cfg_add_bytes(s, key, (uint8_t *)copy, sizeof(value));

}


GF_Err gf_isom_avc_config_new(GF_ISOFile *the_file, u32 trackNumber, GF_AVCConfig *cfg, const char *URLname, const char *URNname, u32 *outDescriptionIndex)
{
	GF_TrackBox *trak;
	GF_Err e;
	GF_SampleDescriptionBox *stsd;
	u32 dataRefIndex;
	GF_MPEGVisualSampleEntryBox *entry;

	e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
	if (e) return e;

	trak = gf_isom_get_track_from_file(the_file, trackNumber);
	if (!trak || !trak->Media || !cfg) return GF_BAD_PARAM;

	//get or create the data ref
	e = Media_FindDataRef(trak->Media->information->dataInformation->dref, (char *)URLname, (char *)URNname, &dataRefIndex);
	if (e) return e;
	if (!dataRefIndex) {
		e = Media_CreateDataRef(the_file, trak->Media->information->dataInformation->dref, (char *)URLname, (char *)URNname, &dataRefIndex);
		if (e) return e;
	}
	if (!the_file->keep_utc && !gf_sys_is_test_mode() )
		trak->Media->mediaHeader->modificationTime = gf_isom_get_mp4time();

	stsd = trak->Media->information->sampleTable->SampleDescription;

	//create a new entry
	entry = (GF_MPEGVisualSampleEntryBox *) gf_isom_box_new_parent(&stsd->child_boxes, GF_ISOM_BOX_TYPE_AVC1);
	if (!entry) return GF_OUT_OF_MEM;
	*outDescriptionIndex = gf_list_count(stsd->child_boxes);

	entry->avc_config = (GF_AVCConfigurationBox*)gf_isom_box_new_parent(&entry->child_boxes, GF_ISOM_BOX_TYPE_AVCC);
	if (!entry->avc_config) return GF_OUT_OF_MEM;
	entry->avc_config->config = AVC_DuplicateConfig(cfg);
	if (!entry->avc_config->config) return GF_OUT_OF_MEM;
	entry->dataReferenceIndex = dataRefIndex;
	AVC_RewriteESDescriptor(entry);
	return e;
}


base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
  return last_active_time_;
}


static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu,
                                      struct kvm_run *run)
{
	u64 uninitialized_var(gpr);

	if (run->mmio.len > sizeof(gpr)) {
		printk(KERN_ERR "bad MMIO length: %d\n", run->mmio.len);
		return;
	}

	if (!vcpu->arch.mmio_host_swabbed) {
		switch (run->mmio.len) {
		case 8: gpr = *(u64 *)run->mmio.data; break;
		case 4: gpr = *(u32 *)run->mmio.data; break;
		case 2: gpr = *(u16 *)run->mmio.data; break;
		case 1: gpr = *(u8 *)run->mmio.data; break;
		}
	} else {
		switch (run->mmio.len) {
		case 8: gpr = swab64(*(u64 *)run->mmio.data); break;
		case 4: gpr = swab32(*(u32 *)run->mmio.data); break;
		case 2: gpr = swab16(*(u16 *)run->mmio.data); break;
		case 1: gpr = *(u8 *)run->mmio.data; break;
		}
	}

	/* conversion between single and double precision */
	if ((vcpu->arch.mmio_sp64_extend) && (run->mmio.len == 4))
		gpr = sp_to_dp(gpr);

	if (vcpu->arch.mmio_sign_extend) {
		switch (run->mmio.len) {
#ifdef CONFIG_PPC64
		case 4:
			gpr = (s64)(s32)gpr;
			break;
#endif
		case 2:
			gpr = (s64)(s16)gpr;
			break;
		case 1:
			gpr = (s64)(s8)gpr;
			break;
		}
	}

	switch (vcpu->arch.io_gpr & KVM_MMIO_REG_EXT_MASK) {
	case KVM_MMIO_REG_GPR:
		kvmppc_set_gpr(vcpu, vcpu->arch.io_gpr, gpr);
		break;
	case KVM_MMIO_REG_FPR:
		VCPU_FPR(vcpu, vcpu->arch.io_gpr & KVM_MMIO_REG_MASK) = gpr;
		break;
#ifdef CONFIG_PPC_BOOK3S
	case KVM_MMIO_REG_QPR:
		vcpu->arch.qpr[vcpu->arch.io_gpr & KVM_MMIO_REG_MASK] = gpr;
		break;
	case KVM_MMIO_REG_FQPR:
		VCPU_FPR(vcpu, vcpu->arch.io_gpr & KVM_MMIO_REG_MASK) = gpr;
		vcpu->arch.qpr[vcpu->arch.io_gpr & KVM_MMIO_REG_MASK] = gpr;
		break;
#endif
#ifdef CONFIG_VSX
	case KVM_MMIO_REG_VSX:
		if (vcpu->arch.mmio_vsx_copy_type == KVMPPC_VSX_COPY_DWORD)
			kvmppc_set_vsr_dword(vcpu, gpr);
		else if (vcpu->arch.mmio_vsx_copy_type == KVMPPC_VSX_COPY_WORD)
			kvmppc_set_vsr_word(vcpu, gpr);
		else if (vcpu->arch.mmio_vsx_copy_type ==
				KVMPPC_VSX_COPY_DWORD_LOAD_DUMP)
			kvmppc_set_vsr_dword_dump(vcpu, gpr);
		break;
#endif
	default:
		BUG();
	}
}


static void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
{
	if (sd->need_wakeup)
		wakeup_pipe_writers(pipe);
}


void RenderWidgetHostImpl::DecrementInFlightEventCount(
    InputEventAckSource ack_source) {
  --in_flight_event_count_;
  if (in_flight_event_count_ <= 0) {
    StopInputEventAckTimeout();
  } else {
    if (ack_source == InputEventAckSource::MAIN_THREAD)
      RestartInputEventAckTimeoutIfNecessary();
  }
}


mono_gc_out_of_memory (size_t size)
{
	/*
	 * we could allocate at program startup some memory that we could release
	 * back to the system at this point if we're really low on memory (ie, size is
	 * lower than the memory we set apart)
	 */
	mono_raise_exception (mono_domain_get ()->out_of_memory_ex);

	return NULL;
}


int mz_deflate(mz_streamp pStream, int flush) {
  size_t in_bytes, out_bytes;
  mz_ulong orig_total_in, orig_total_out;
  int mz_status = MZ_OK;

  if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
      (!pStream->next_out))
    return MZ_STREAM_ERROR;
  if (!pStream->avail_out) return MZ_BUF_ERROR;

  if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;

  if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
      TDEFL_STATUS_DONE)
    return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;

  orig_total_in = pStream->total_in;
  orig_total_out = pStream->total_out;
  for (;;) {
    tdefl_status defl_status;
    in_bytes = pStream->avail_in;
    out_bytes = pStream->avail_out;

    defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
                                 pStream->next_in, &in_bytes, pStream->next_out,
                                 &out_bytes, (tdefl_flush)flush);
    pStream->next_in += (mz_uint)in_bytes;
    pStream->avail_in -= (mz_uint)in_bytes;
    pStream->total_in += (mz_uint)in_bytes;
    pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);

    pStream->next_out += (mz_uint)out_bytes;
    pStream->avail_out -= (mz_uint)out_bytes;
    pStream->total_out += (mz_uint)out_bytes;

    if (defl_status < 0) {
      mz_status = MZ_STREAM_ERROR;
      break;
    } else if (defl_status == TDEFL_STATUS_DONE) {
      mz_status = MZ_STREAM_END;
      break;
    } else if (!pStream->avail_out)
      break;
    else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
      if ((flush) || (pStream->total_in != orig_total_in) ||
          (pStream->total_out != orig_total_out))
        break;
      return MZ_BUF_ERROR;  // Can't make forward progress without some input.
    }
  }
  return mz_status;
}


static void gf_m2ts_process_sdt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)
{
	u32 pos, evt_type;
	u32 nb_sections;
	u32 data_size;
	unsigned char *data;
	GF_M2TS_Section *section;

	/*wait for the last section */
	if (!(status&GF_M2TS_TABLE_END)) return;

	/*skip if already received*/
	if (status&GF_M2TS_TABLE_REPEAT) {
		if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_SDT_REPEAT, NULL);
		return;
	}

	if (table_id != GF_M2TS_TABLE_ID_SDT_ACTUAL) {
		return;
	}

	gf_m2ts_reset_sdt(ts);

	nb_sections = gf_list_count(sections);
	if (nb_sections > 1) {
		GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] SDT on multiple sections not supported\n"));
	}

	section = (GF_M2TS_Section *)gf_list_get(sections, 0);
	data = section->data;
	data_size = section->data_size;

	//orig_net_id = (data[0] << 8) | data[1];
	pos = 3;
	while (pos < data_size) {
		GF_M2TS_SDT *sdt;
		u32 descs_size, d_pos, ulen;

		GF_SAFEALLOC(sdt, GF_M2TS_SDT);
		if (!sdt) {
			GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[MPEG-2 TS] Fail to create SDT\n"));
			return;
		}
		gf_list_add(ts->SDTs, sdt);

		sdt->service_id = (data[pos]<<8) + data[pos+1];
		sdt->EIT_schedule = (data[pos+2] & 0x2) ? 1 : 0;
		sdt->EIT_present_following = (data[pos+2] & 0x1);
		sdt->running_status = (data[pos+3]>>5) & 0x7;
		sdt->free_CA_mode = (data[pos+3]>>4) & 0x1;
		descs_size = ((data[pos+3]&0xf)<<8) | data[pos+4];
		pos += 5;

		d_pos = 0;
		while (d_pos < descs_size) {
			u8 d_tag = data[pos+d_pos];
			u8 d_len = data[pos+d_pos+1];

			switch (d_tag) {
			case GF_M2TS_DVB_SERVICE_DESCRIPTOR:
				if (sdt->provider) gf_free(sdt->provider);
				sdt->provider = NULL;
				if (sdt->service) gf_free(sdt->service);
				sdt->service = NULL;

				d_pos+=2;
				sdt->service_type = data[pos+d_pos];
				ulen = data[pos+d_pos+1];
				d_pos += 2;
				sdt->provider = (char*)gf_malloc(sizeof(char)*(ulen+1));
				memcpy(sdt->provider, data+pos+d_pos, sizeof(char)*ulen);
				sdt->provider[ulen] = 0;
				d_pos += ulen;

				ulen = data[pos+d_pos];
				d_pos += 1;
				sdt->service = (char*)gf_malloc(sizeof(char)*(ulen+1));
				memcpy(sdt->service, data+pos+d_pos, sizeof(char)*ulen);
				sdt->service[ulen] = 0;
				d_pos += ulen;
				break;

			default:
				GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[MPEG-2 TS] Skipping descriptor (0x%x) not supported\n", d_tag));
				d_pos += d_len;
				if (d_len == 0) d_pos = descs_size;
				break;
			}
		}
		pos += descs_size;
	}
	evt_type = GF_M2TS_EVT_SDT_FOUND;
	if (ts->on_event) ts->on_event(ts, evt_type, NULL);
}


tar_create_dir (GsfInfileTar *dir, const char *name)
{
	TarChild c;

	c.offset = 0;
	c.length = 0;
	c.name = g_strdup (name);
	c.modtime = NULL;
	c.dir = g_object_new (GSF_INFILE_TAR_TYPE, NULL);

	/*
	 * We set the source here, so gsf_infile_tar_constructor doesn't
	 * start reading the tarfile recursively.
	 */
	gsf_infile_tar_set_source (c.dir, dir->source);

	gsf_input_set_name (GSF_INPUT (c.dir), name);

	g_array_append_val (dir->children, c);

	return c.dir;
}


bool HHVM_FUNCTION(imagesetbrush,
    const Resource& image, const Resource& brush) {
  gdImagePtr im = get_valid_image_resource(image);
  if (!im) return false;
  gdImagePtr tile = get_valid_image_resource(brush);
  if (!tile) return false;
  gdImageSetBrush(im, tile);
  return true;
}


void DefaultAudioDestinationHandler::Render(
    AudioBus* destination_bus,
    uint32_t number_of_frames,
    const AudioIOPosition& output_position,
    const AudioIOCallbackMetric& metric) {
  TRACE_EVENT0("webaudio", "DefaultAudioDestinationHandler::Render");

  DenormalDisabler denormal_disabler;

  DCHECK(Context());
  if (!Context()) {
    return;
  }

  Context()->GetDeferredTaskHandler().SetAudioThreadToCurrentThread();

  if (!IsInitialized()) {
    destination_bus->Zero();
    return;
  }

  Context()->HandlePreRenderTasks(output_position, metric);

  AudioBus* rendered_bus = Input(0).Pull(destination_bus, number_of_frames);

  DCHECK(rendered_bus);
  if (!rendered_bus) {
    destination_bus->Zero();
  } else if (rendered_bus != destination_bus) {
    destination_bus->CopyFrom(*rendered_bus);
  }

  Context()->GetDeferredTaskHandler().ProcessAutomaticPullNodes(
      number_of_frames);

  Context()->HandlePostRenderTasks(destination_bus);

  AdvanceCurrentSampleFrame(number_of_frames);

  Context()->UpdateWorkletGlobalScopeOnRenderingThread();
}


void jpc_ns_fwdlift_col ( jpc_fix_t * a , int numrows , int stride , int parity ) {
 jpc_fix_t * lptr ;
 jpc_fix_t * hptr ;
 register jpc_fix_t * lptr2 ;
 register jpc_fix_t * hptr2 ;
 register int n ;
 int llen ;
 llen = ( numrows + 1 - parity ) >> 1 ;
 if ( numrows > 1 ) {
 lptr = & a [ 0 ] ;
 hptr = & a [ llen * stride ] ;
 if ( parity ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( hptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * ALPHA ) , lptr2 [ 0 ] ) ) ;
 ++ hptr2 ;
 ++ lptr2 ;
 hptr += stride ;
 }
 n = numrows - llen - parity - ( parity == ( numrows & 1 ) ) ;
 while ( n -- > 0 ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( hptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( ALPHA ) , jpc_fix_add ( lptr2 [ 0 ] , lptr2 [ stride ] ) ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 hptr += stride ;
 lptr += stride ;
 }
 if ( parity == ( numrows & 1 ) ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( hptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * ALPHA ) , lptr2 [ 0 ] ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 }
 lptr = & a [ 0 ] ;
 hptr = & a [ llen * stride ] ;
 if ( ! parity ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( lptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * BETA ) , hptr2 [ 0 ] ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 lptr += stride ;
 }
 n = llen - ( ! parity ) - ( parity != ( numrows & 1 ) ) ;
 while ( n -- > 0 ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( lptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( BETA ) , jpc_fix_add ( hptr2 [ 0 ] , hptr2 [ stride ] ) ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 lptr += stride ;
 hptr += stride ;
 }
 if ( parity != ( numrows & 1 ) ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( lptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * BETA ) , hptr2 [ 0 ] ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 }
 lptr = & a [ 0 ] ;
 hptr = & a [ llen * stride ] ;
 if ( parity ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( hptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * GAMMA ) , lptr2 [ 0 ] ) ) ;
 ++ hptr2 ;
 ++ lptr2 ;
 hptr += stride ;
 }
 n = numrows - llen - parity - ( parity == ( numrows & 1 ) ) ;
 while ( n -- > 0 ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( hptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( GAMMA ) , jpc_fix_add ( lptr2 [ 0 ] , lptr2 [ stride ] ) ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 hptr += stride ;
 lptr += stride ;
 }
 if ( parity == ( numrows & 1 ) ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( hptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * GAMMA ) , lptr2 [ 0 ] ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 }
 lptr = & a [ 0 ] ;
 hptr = & a [ llen * stride ] ;
 if ( ! parity ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( lptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * DELTA ) , hptr2 [ 0 ] ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 lptr += stride ;
 }
 n = llen - ( ! parity ) - ( parity != ( numrows & 1 ) ) ;
 while ( n -- > 0 ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( lptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( DELTA ) , jpc_fix_add ( hptr2 [ 0 ] , hptr2 [ stride ] ) ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 lptr += stride ;
 hptr += stride ;
 }
 if ( parity != ( numrows & 1 ) ) {
 lptr2 = lptr ;
 hptr2 = hptr ;
 jpc_fix_pluseq ( lptr2 [ 0 ] , jpc_fix_mul ( jpc_dbltofix ( 2.0 * DELTA ) , hptr2 [ 0 ] ) ) ;
 ++ lptr2 ;
 ++ hptr2 ;
 }
 # if defined ( WT_DOSCALE ) lptr = & a [ 0 ] ;
 n = llen ;
 while ( n -- > 0 ) {
 lptr2 = lptr ;
 lptr2 [ 0 ] = jpc_fix_mul ( lptr2 [ 0 ] , jpc_dbltofix ( LGAIN ) ) ;
 ++ lptr2 ;
 lptr += stride ;
 }
 hptr = & a [ llen * stride ] ;
 n = numrows - llen ;
 while ( n -- > 0 ) {
 hptr2 = hptr ;
 hptr2 [ 0 ] = jpc_fix_mul ( hptr2 [ 0 ] , jpc_dbltofix ( HGAIN ) ) ;
 ++ hptr2 ;
 hptr += stride ;
 }
 # endif }
 else {
 # if defined ( WT_LENONE ) if ( parity ) {
 lptr2 = & a [ 0 ] ;
 lptr2 [ 0 ] = jpc_fix_asl ( lptr2 [ 0 ] , 1 ) ;
 ++ lptr2 ;
 }
 # endif }
 }


set_cursor_for_append_to_line(void)
{
    curwin->w_set_curswant = TRUE;
    if (get_ve_flags() == VE_ALL)
    {
	int save_State = State;

	// Pretend Insert mode here to allow the cursor on the
	// character past the end of the line
	State = MODE_INSERT;
	coladvance((colnr_T)MAXCOL);
	State = save_State;
    }
    else
	curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
}


static always_inline void dv_encode_ac(EncBlockInfo* bi, PutBitContext* pb_pool,

                                       int pb_size)

{

    int run;

    int bits_left;

    PutBitContext* pb = pb_pool;

    int size = bi->partial_bit_count;

    uint32_t vlc = bi->partial_bit_buffer;

    bi->partial_bit_count = bi->partial_bit_buffer = 0;

vlc_loop:

       /* Find suitable storage space */

       for (; size > (bits_left = put_bits_left(pb)); pb++) {

          if (bits_left) {

              size -= bits_left;

	      put_bits(pb, bits_left, vlc >> size);

	      vlc = vlc & ((1<<size)-1);

	  }

	  if (pb_size == 1) {

	      bi->partial_bit_count = size;

	      bi->partial_bit_buffer = vlc;

	      return;

	  }

	  --pb_size;

       }

       /* Store VLC */

       put_bits(pb, size, vlc);

       /* Construct the next VLC */

       run = 0;

       for (; bi->cur_ac < 64; bi->cur_ac++, run++) {

           if (bi->mb[bi->cur_ac]) {

	       size = dv_rl2vlc(run, bi->mb[bi->cur_ac], &vlc);

	       bi->cur_ac++;

	       goto vlc_loop;

	   }

       }

       if (bi->cur_ac == 64) {

           size = 4; vlc = 6; /* End Of Block stamp */

	   bi->cur_ac++;

	   goto vlc_loop;

       }

}