static void pred_spatial_direct_motion(const H264Context *const h, H264SliceContext *sl,

                                       int *mb_type)

{

    int b8_stride = 2;

    int b4_stride = h->b_stride;

    int mb_xy = sl->mb_xy, mb_y = sl->mb_y;

    int mb_type_col[2];

    const int16_t (*l1mv0)[2], (*l1mv1)[2];

    const int8_t *l1ref0, *l1ref1;

    const int is_b8x8 = IS_8X8(*mb_type);

    unsigned int sub_mb_type = MB_TYPE_L0L1;

    int i8, i4;

    int ref[2];

    int mv[2];

    int list;

    assert(sl->ref_list[1][0].reference & 3);

    await_reference_mb_row(h, sl->ref_list[1][0].parent,

                           sl->mb_y + !!IS_INTERLACED(*mb_type));

#define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16 | MB_TYPE_INTRA4x4 | \

                                MB_TYPE_INTRA16x16 | MB_TYPE_INTRA_PCM)

    /* ref = min(neighbors) */

    for (list = 0; list < 2; list++) {

        int left_ref     = sl->ref_cache[list][scan8[0] - 1];

        int top_ref      = sl->ref_cache[list][scan8[0] - 8];

        int refc         = sl->ref_cache[list][scan8[0] - 8 + 4];

        const int16_t *C = sl->mv_cache[list][scan8[0]  - 8 + 4];

        if (refc == PART_NOT_AVAILABLE) {

            refc = sl->ref_cache[list][scan8[0] - 8 - 1];

            C    = sl->mv_cache[list][scan8[0]  - 8 - 1];

        }

        ref[list] = FFMIN3((unsigned)left_ref,

                           (unsigned)top_ref,

                           (unsigned)refc);

        if (ref[list] >= 0) {

            /* This is just pred_motion() but with the cases removed that

             * cannot happen for direct blocks. */

            const int16_t *const A = sl->mv_cache[list][scan8[0] - 1];

            const int16_t *const B = sl->mv_cache[list][scan8[0] - 8];

            int match_count = (left_ref == ref[list]) +

                              (top_ref  == ref[list]) +

                              (refc     == ref[list]);

            if (match_count > 1) { // most common

                mv[list] = pack16to32(mid_pred(A[0], B[0], C[0]),

                                      mid_pred(A[1], B[1], C[1]));

            } else {

                assert(match_count == 1);

                if (left_ref == ref[list])

                    mv[list] = AV_RN32A(A);

                else if (top_ref == ref[list])

                    mv[list] = AV_RN32A(B);

                else

                    mv[list] = AV_RN32A(C);

            }

        } else {

            int mask = ~(MB_TYPE_L0 << (2 * list));

            mv[list]  = 0;

            ref[list] = -1;

            if (!is_b8x8)

                *mb_type &= mask;

            sub_mb_type &= mask;

        }

    }

    if (ref[0] < 0 && ref[1] < 0) {

        ref[0] = ref[1] = 0;

        if (!is_b8x8)

            *mb_type |= MB_TYPE_L0L1;

        sub_mb_type |= MB_TYPE_L0L1;

    }

    if (!(is_b8x8 | mv[0] | mv[1])) {

        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);

        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);

        *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                 MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                   MB_TYPE_16x16 | MB_TYPE_DIRECT2;

        return;

    }

    if (IS_INTERLACED(sl->ref_list[1][0].parent->mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL

        if (!IS_INTERLACED(*mb_type)) {                    //     AFR/FR    -> AFL/FL

            mb_y  = (sl->mb_y & ~1) + sl->col_parity;

            mb_xy = sl->mb_x +

                    ((sl->mb_y & ~1) + sl->col_parity) * h->mb_stride;

            b8_stride = 0;

        } else {

            mb_y  += sl->col_fieldoff;

            mb_xy += h->mb_stride * sl->col_fieldoff; // non-zero for FL -> FL & differ parity

        }

        goto single_col;

    } else {                                             // AFL/AFR/FR/FL -> AFR/FR

        if (IS_INTERLACED(*mb_type)) {                   // AFL       /FL -> AFR/FR

            mb_y           =  sl->mb_y & ~1;

            mb_xy          = (sl->mb_y & ~1) * h->mb_stride + sl->mb_x;

            mb_type_col[0] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy + h->mb_stride];

            b8_stride      = 2 + 4 * h->mb_stride;

            b4_stride     *= 6;

            if (IS_INTERLACED(mb_type_col[0]) !=

                IS_INTERLACED(mb_type_col[1])) {

                mb_type_col[0] &= ~MB_TYPE_INTERLACED;

                mb_type_col[1] &= ~MB_TYPE_INTERLACED;

            }

            sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if ((mb_type_col[0] & MB_TYPE_16x16_OR_INTRA) &&

                (mb_type_col[1] & MB_TYPE_16x16_OR_INTRA) &&

                !is_b8x8) {

                *mb_type |= MB_TYPE_16x8 | MB_TYPE_DIRECT2;  /* B_16x8 */

            } else {

                *mb_type |= MB_TYPE_8x8;

            }

        } else {                                         //     AFR/FR    -> AFR/FR

single_col:

            mb_type_col[0] =

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if (!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)) {

                *mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_16x16 */

            } else if (!is_b8x8 &&

                       (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16))) {

                *mb_type |= MB_TYPE_DIRECT2 |

                            (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16));

            } else {

                if (!h->sps.direct_8x8_inference_flag) {

                    /* FIXME: Save sub mb types from previous frames (or derive

                     * from MVs) so we know exactly what block size to use. */

                    sub_mb_type += (MB_TYPE_8x8 - MB_TYPE_16x16); /* B_SUB_4x4 */

                }

                *mb_type |= MB_TYPE_8x8;

            }

        }

    }

    await_reference_mb_row(h, sl->ref_list[1][0].parent, mb_y);

    l1mv0  = &sl->ref_list[1][0].parent->motion_val[0][h->mb2b_xy[mb_xy]];

    l1mv1  = &sl->ref_list[1][0].parent->motion_val[1][h->mb2b_xy[mb_xy]];

    l1ref0 = &sl->ref_list[1][0].parent->ref_index[0][4 * mb_xy];

    l1ref1 = &sl->ref_list[1][0].parent->ref_index[1][4 * mb_xy];

    if (!b8_stride) {

        if (sl->mb_y & 1) {

            l1ref0 += 2;

            l1ref1 += 2;

            l1mv0  += 2 * b4_stride;

            l1mv1  += 2 * b4_stride;

        }

    }

    if (IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])) {

        int n = 0;

        for (i8 = 0; i8 < 4; i8++) {

            int x8  = i8 & 1;

            int y8  = i8 >> 1;

            int xy8 = x8     + y8 * b8_stride;

            int xy4 = x8 * 3 + y8 * b4_stride;

            int a, b;

            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                continue;

            sl->sub_mb_type[i8] = sub_mb_type;

            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[0], 1);

            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[1], 1);

            if (!IS_INTRA(mb_type_col[y8]) && !sl->ref_list[1][0].parent->long_ref &&

                ((l1ref0[xy8] == 0 &&

                  FFABS(l1mv0[xy4][0]) <= 1 &&

                  FFABS(l1mv0[xy4][1]) <= 1) ||

                 (l1ref0[xy8] < 0 &&

                  l1ref1[xy8] == 0 &&

                  FFABS(l1mv1[xy4][0]) <= 1 &&

                  FFABS(l1mv1[xy4][1]) <= 1))) {

                a =

                b = 0;

                if (ref[0] > 0)

                    a = mv[0];

                if (ref[1] > 0)

                    b = mv[1];

                n++;

            } else {

                a = mv[0];

                b = mv[1];

            }

            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, a, 4);

            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, b, 4);

        }

        if (!is_b8x8 && !(n & 3))

            *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                     MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                       MB_TYPE_16x16 | MB_TYPE_DIRECT2;

    } else if (IS_16X16(*mb_type)) {

        int a, b;

        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&

            ((l1ref0[0] == 0 &&

              FFABS(l1mv0[0][0]) <= 1 &&

              FFABS(l1mv0[0][1]) <= 1) ||

             (l1ref0[0] < 0 && !l1ref1[0] &&

              FFABS(l1mv1[0][0]) <= 1 &&

              FFABS(l1mv1[0][1]) <= 1 &&

              h->x264_build > 33U))) {

            a = b = 0;

            if (ref[0] > 0)

                a = mv[0];

            if (ref[1] > 0)

                b = mv[1];

        } else {

            a = mv[0];

            b = mv[1];

        }

        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);

        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);

    } else {

        int n = 0;

        for (i8 = 0; i8 < 4; i8++) {

            const int x8 = i8 & 1;

            const int y8 = i8 >> 1;

            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                continue;

            sl->sub_mb_type[i8] = sub_mb_type;

            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, mv[0], 4);

            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, mv[1], 4);

            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[0], 1);

            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[1], 1);

            assert(b8_stride == 2);

            /* col_zero_flag */

            if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&

                (l1ref0[i8] == 0 ||

                 (l1ref0[i8] < 0 &&

                  l1ref1[i8] == 0 &&

                  h->x264_build > 33U))) {

                const int16_t (*l1mv)[2] = l1ref0[i8] == 0 ? l1mv0 : l1mv1;

                if (IS_SUB_8X8(sub_mb_type)) {

                    const int16_t *mv_col = l1mv[x8 * 3 + y8 * 3 * b4_stride];

                    if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {

                        if (ref[0] == 0)

                            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2,

                                           8, 0, 4);

                        if (ref[1] == 0)

                            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2,

                                           8, 0, 4);

                        n += 4;

                    }

                } else {

                    int m = 0;

                    for (i4 = 0; i4 < 4; i4++) {

                        const int16_t *mv_col = l1mv[x8 * 2 + (i4 & 1) +

                                                     (y8 * 2 + (i4 >> 1)) * b4_stride];

                        if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {

                            if (ref[0] == 0)

                                AV_ZERO32(sl->mv_cache[0][scan8[i8 * 4 + i4]]);

                            if (ref[1] == 0)

                                AV_ZERO32(sl->mv_cache[1][scan8[i8 * 4 + i4]]);

                            m++;

                        }

                    }

                    if (!(m & 3))

                        sl->sub_mb_type[i8] += MB_TYPE_16x16 - MB_TYPE_8x8;

                    n += m;

                }

            }

        }

        if (!is_b8x8 && !(n & 15))

            *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                     MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                       MB_TYPE_16x16 | MB_TYPE_DIRECT2;

    }

}


static void VoidMethodElementSequenceOrByteStringDoubleOrStringRecordMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
  ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodElementSequenceOrByteStringDoubleOrStringRecord");

  TestObject* impl = V8TestObject::ToImpl(info.Holder());

  if (UNLIKELY(info.Length() < 1)) {
    exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length()));
    return;
  }

  ElementSequenceOrByteStringDoubleOrStringRecord arg;
  V8ElementSequenceOrByteStringDoubleOrStringRecord::ToImpl(info.GetIsolate(), info[0], arg, UnionTypeConversionMode::kNotNullable, exception_state);
  if (exception_state.HadException())
    return;

  impl->voidMethodElementSequenceOrByteStringDoubleOrStringRecord(arg);
}


f_sinh(typval_T *argvars, typval_T *rettv)
{
    float_T	f = 0.0;

    rettv->v_type = VAR_FLOAT;
    if (get_float_arg(argvars, &f) == OK)
	rettv->vval.v_float = sinh(f);
    else
	rettv->vval.v_float = 0.0;
}


static int process_cmd_sock(int h)

 {
     sock_cmd_t cmd = {-1, 0, 0, 0, 0};
     int fd = ts[h].cmd_fdr;
    if(recv(fd, &cmd, sizeof(cmd), MSG_WAITALL) != sizeof(cmd))
     {
         APPL_TRACE_ERROR("recv cmd errno:%d", errno);
         return FALSE;
 }
    APPL_TRACE_DEBUG("cmd.id:%d", cmd.id);
 switch(cmd.id)
 {
 case CMD_ADD_FD:
            add_poll(h, cmd.fd, cmd.type, cmd.flags, cmd.user_id);
 break;
 case CMD_REMOVE_FD:
 for (int i = 1; i < MAX_POLL; ++i)
 {
 poll_slot_t *poll_slot = &ts[h].ps[i];
 if (poll_slot->pfd.fd == cmd.fd)
 {
                    remove_poll(h, poll_slot, poll_slot->flags);
 break;
 }
 }
            close(cmd.fd);
 break;
 case CMD_WAKEUP:
 break;
 case CMD_USER_PRIVATE:
            asrt(ts[h].cmd_callback);
 if(ts[h].cmd_callback)
                ts[h].cmd_callback(fd, cmd.type, cmd.flags, cmd.user_id);
 break;
 case CMD_EXIT:
 return FALSE;
 default:
            APPL_TRACE_DEBUG("unknown cmd: %d", cmd.id);
 break;
 }
 return TRUE;
}


static int get_eff_addr_reg(struct insn *insn, struct pt_regs *regs,
			    int *regoff, long *eff_addr)
{
	insn_get_modrm(insn);

	if (!insn->modrm.nbytes)
		return -EINVAL;

	if (X86_MODRM_MOD(insn->modrm.value) != 3)
		return -EINVAL;

	*regoff = get_reg_offset(insn, regs, REG_TYPE_RM);
	if (*regoff < 0)
		return -EINVAL;

	/* Ignore bytes that are outside the address size. */
	if (insn->addr_bytes == 2)
		*eff_addr = regs_get_register(regs, *regoff) & 0xffff;
	else if (insn->addr_bytes == 4)
		*eff_addr = regs_get_register(regs, *regoff) & 0xffffffff;
	else /* 64-bit address */
		*eff_addr = regs_get_register(regs, *regoff);

	return 0;
}


static PHP_FUNCTION(gzopen)
{
	char *filename;
	char *mode;
	int filename_len, mode_len;
	int flags = REPORT_ERRORS;
        php_stream *stream;
        long use_include_path = 0;

       if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) {
                return;
        }

	if (use_include_path) {
		flags |= USE_PATH;
	}

	stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC);

	if (!stream) {
		RETURN_FALSE;
	}
	php_stream_to_zval(stream, return_value);
}


static long double max() { return LDBL_MAX; }


cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst)
{
	cdf_catalog_t *cat;
	cdf_unpack_catalog(h, sst, &cat);
	const cdf_catalog_entry_t *ce = cat->cat_e;
	struct timespec ts;
	char tbuf[64], sbuf[256];
	size_t i;

	printf("Catalog:\n");
	for (i = 0; i < cat->cat_num; i++) {
		cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp);
		printf("\t%d %s %s", ce[i].ce_num,
		    cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name),
		    cdf_ctime(&ts.tv_sec, tbuf));
	}
	free(cat);
}


pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image)
{
	pdf_gstate *gstate = pr->gstate + pr->gtop;
	fz_matrix image_ctm;
	fz_rect bbox;
	softmask_save softmask = { NULL };

	if (pr->super.hidden)
		return;

	/* PDF has images bottom-up, so flip them right side up here */
	image_ctm = gstate->ctm;
	fz_pre_scale(fz_pre_translate(&image_ctm, 0, 1), 1, -1);

	bbox = fz_unit_rect;
	fz_transform_rect(&bbox, &image_ctm);

	if (image->mask)
	{
		/* apply blend group even though we skip the soft mask */
		if (gstate->blendmode)
			fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1);
		fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox);
	}
	else
		gstate = pdf_begin_group(ctx, pr, &bbox, &softmask);

	if (!image->colorspace)
	{
		switch (gstate->fill.kind)
		{
		case PDF_MAT_NONE:
			break;
		case PDF_MAT_COLOR:
			fz_fill_image_mask(ctx, pr->dev, image, &image_ctm,
				gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params);
			break;
		case PDF_MAT_PATTERN:
			if (gstate->fill.pattern)
			{
				fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
				pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL);
				fz_pop_clip(ctx, pr->dev);
			}
			break;
		case PDF_MAT_SHADE:
			if (gstate->fill.shade)
			{
				fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox);
				fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params);
				fz_pop_clip(ctx, pr->dev);
			}
			break;
		}
	}
	else
	{
		fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params);
	}

	if (image->mask)
	{
		fz_pop_clip(ctx, pr->dev);
		if (gstate->blendmode)
			fz_end_group(ctx, pr->dev);
	}
	else
		pdf_end_group(ctx, pr, &softmask);
}


static void pc_dimm_check_memdev_is_busy(Object *obj, const char *name,

                                      Object *val, Error **errp)

{

    MemoryRegion *mr;

    mr = host_memory_backend_get_memory(MEMORY_BACKEND(val), errp);

    if (memory_region_is_mapped(mr)) {

        char *path = object_get_canonical_path_component(val);

        error_setg(errp, "can't use already busy memdev: %s", path);

        g_free(path);

    } else {

        qdev_prop_allow_set_link_before_realize(obj, name, val, errp);

    }

}


gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
    const gfx::Rect& bounds) const {
  RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
      render_view_host_->GetWidget()->GetView());
  if (view)
    return view->AccessibilityOriginInScreen(bounds);
  return gfx::Point();
}


int input_open_device(struct input_handle *handle)
{
	struct input_dev *dev = handle->dev;
	int retval;

	retval = mutex_lock_interruptible(&dev->mutex);
	if (retval)
		return retval;

	if (dev->going_away) {
		retval = -ENODEV;
		goto out;
	}

	handle->open++;

	if (dev->users++) {
		/*
		 * Device is already opened, so we can exit immediately and
		 * report success.
		 */
		goto out;
	}

	if (dev->open) {
		retval = dev->open(dev);
		if (retval) {
			dev->users--;
			handle->open--;
			/*
			 * Make sure we are not delivering any more events
			 * through this handle
			 */
			synchronize_rcu();
			goto out;
		}
	}

	if (dev->poller)
		input_dev_poller_start(dev->poller);

 out:
	mutex_unlock(&dev->mutex);
	return retval;
}


static void nfs4_xdr_enc_server_caps(struct rpc_rqst *req,
				     struct xdr_stream *xdr,
				     struct nfs4_server_caps_arg *args)
{
	struct compound_hdr hdr = {
		.minorversion = nfs4_xdr_minorversion(&args->seq_args),
	};

	encode_compound_hdr(xdr, req, &hdr);
	encode_sequence(xdr, &args->seq_args, &hdr);
	encode_putfh(xdr, args->fhandle, &hdr);
	encode_getattr_one(xdr, FATTR4_WORD0_SUPPORTED_ATTRS|
			   FATTR4_WORD0_LINK_SUPPORT|
			   FATTR4_WORD0_SYMLINK_SUPPORT|
			   FATTR4_WORD0_ACLSUPPORT, &hdr);
	encode_nops(&hdr);
}


int ff_wmv2_decode_mb ( MpegEncContext * s , int16_t block [ 6 ] [ 64 ] ) {
 Wmv2Context * const w = ( Wmv2Context * ) s ;
 int cbp , code , i ;
 uint8_t * coded_val ;
 if ( w -> j_type ) return 0 ;
 if ( s -> pict_type == AV_PICTURE_TYPE_P ) {
 if ( IS_SKIP ( s -> current_picture . f . mb_type [ s -> mb_y * s -> mb_stride + s -> mb_x ] ) ) {
 s -> mb_intra = 0 ;
 for ( i = 0 ;
 i < 6 ;
 i ++ ) s -> block_last_index [ i ] = - 1 ;
 s -> mv_dir = MV_DIR_FORWARD ;
 s -> mv_type = MV_TYPE_16X16 ;
 s -> mv [ 0 ] [ 0 ] [ 0 ] = 0 ;
 s -> mv [ 0 ] [ 0 ] [ 1 ] = 0 ;
 s -> mb_skipped = 1 ;
 w -> hshift = 0 ;
 return 0 ;
 }
 code = get_vlc2 ( & s -> gb , ff_mb_non_intra_vlc [ w -> cbp_table_index ] . table , MB_NON_INTRA_VLC_BITS , 3 ) ;
 if ( code < 0 ) return - 1 ;
 s -> mb_intra = ( ~ code & 0x40 ) >> 6 ;
 cbp = code & 0x3f ;
 }
 else {
 s -> mb_intra = 1 ;
 code = get_vlc2 ( & s -> gb , ff_msmp4_mb_i_vlc . table , MB_INTRA_VLC_BITS , 2 ) ;
 if ( code < 0 ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "II-cbp illegal at %d %d\n" , s -> mb_x , s -> mb_y ) ;
 return - 1 ;
 }
 cbp = 0 ;
 for ( i = 0 ;
 i < 6 ;
 i ++ ) {
 int val = ( ( code >> ( 5 - i ) ) & 1 ) ;
 if ( i < 4 ) {
 int pred = ff_msmpeg4_coded_block_pred ( s , i , & coded_val ) ;
 val = val ^ pred ;
 * coded_val = val ;
 }
 cbp |= val << ( 5 - i ) ;
 }
 }
 if ( ! s -> mb_intra ) {
 int mx , my ;
 wmv2_pred_motion ( w , & mx , & my ) ;
 if ( cbp ) {
 s -> dsp . clear_blocks ( s -> block [ 0 ] ) ;
 if ( s -> per_mb_rl_table ) {
 s -> rl_table_index = decode012 ( & s -> gb ) ;
 s -> rl_chroma_table_index = s -> rl_table_index ;
 }
 if ( w -> abt_flag && w -> per_mb_abt ) {
 w -> per_block_abt = get_bits1 ( & s -> gb ) ;
 if ( ! w -> per_block_abt ) w -> abt_type = decode012 ( & s -> gb ) ;
 }
 else w -> per_block_abt = 0 ;
 }
 if ( wmv2_decode_motion ( w , & mx , & my ) < 0 ) return - 1 ;
 s -> mv_dir = MV_DIR_FORWARD ;
 s -> mv_type = MV_TYPE_16X16 ;
 s -> mv [ 0 ] [ 0 ] [ 0 ] = mx ;
 s -> mv [ 0 ] [ 0 ] [ 1 ] = my ;
 for ( i = 0 ;
 i < 6 ;
 i ++ ) {
 if ( wmv2_decode_inter_block ( w , block [ i ] , i , ( cbp >> ( 5 - i ) ) & 1 ) < 0 ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "\nerror while decoding inter block: %d x %d (%d)\n" , s -> mb_x , s -> mb_y , i ) ;
 return - 1 ;
 }
 }
 }
 else {
 if ( s -> pict_type == AV_PICTURE_TYPE_P ) av_dlog ( s -> avctx , "%d%d " , s -> inter_intra_pred , cbp ) ;
 av_dlog ( s -> avctx , "I at %d %d %d %06X\n" , s -> mb_x , s -> mb_y , ( ( cbp & 3 ) ? 1 : 0 ) + ( ( cbp & 0x3C ) ? 2 : 0 ) , show_bits ( & s -> gb , 24 ) ) ;
 s -> ac_pred = get_bits1 ( & s -> gb ) ;
 if ( s -> inter_intra_pred ) {
 s -> h263_aic_dir = get_vlc2 ( & s -> gb , ff_inter_intra_vlc . table , INTER_INTRA_VLC_BITS , 1 ) ;
 av_dlog ( s -> avctx , "%d%d %d %d/" , s -> ac_pred , s -> h263_aic_dir , s -> mb_x , s -> mb_y ) ;
 }
 if ( s -> per_mb_rl_table && cbp ) {
 s -> rl_table_index = decode012 ( & s -> gb ) ;
 s -> rl_chroma_table_index = s -> rl_table_index ;
 }
 s -> dsp . clear_blocks ( s -> block [ 0 ] ) ;
 for ( i = 0 ;
 i < 6 ;
 i ++ ) {
 if ( ff_msmpeg4_decode_block ( s , block [ i ] , i , ( cbp >> ( 5 - i ) ) & 1 , NULL ) < 0 ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "\nerror while decoding intra block: %d x %d (%d)\n" , s -> mb_x , s -> mb_y , i ) ;
 return - 1 ;
 }
 }
 }
 return 0 ;
 }


iperf_json_printf(const char *format, ...)
{
    cJSON* o;
    va_list argp;
    const char *cp;
    char name[100];
    char* np;
    cJSON* j;

    o = cJSON_CreateObject();
    if (o == NULL)
        return NULL;
    va_start(argp, format);
    np = name;
    for (cp = format; *cp != '\0'; ++cp) {
	switch (*cp) {
	    case ' ':
	    break;
	    case ':':
	    *np = '\0';
	    break;
	    case '%':
	    ++cp;
	    switch (*cp) {
		case 'b':
		j = cJSON_CreateBool(va_arg(argp, int));
		break;
		case 'd':
		j = cJSON_CreateNumber(va_arg(argp, int64_t));
		break;
		case 'f':
		j = cJSON_CreateNumber(va_arg(argp, double));
		break;
		case 's':
		j = cJSON_CreateString(va_arg(argp, char *));
		break;
		default:
		return NULL;
	    }
	    if (j == NULL)
		return NULL;
	    cJSON_AddItemToObject(o, name, j);
	    np = name;
	    break;
	    default:
	    *np++ = *cp;
	    break;
	}
    }
    va_end(argp);
    return o;
}


static void ehci_trace_qtd(EHCIQueue *q, hwaddr addr, EHCIqtd *qtd)
{
    /* need three here due to argument count limits */
    trace_usb_ehci_qtd_ptrs(q, addr, qtd->next, qtd->altnext);
    trace_usb_ehci_qtd_fields(addr,
                              get_field(qtd->token, QTD_TOKEN_TBYTES),
                              get_field(qtd->token, QTD_TOKEN_CPAGE),
                              get_field(qtd->token, QTD_TOKEN_CERR),
                              get_field(qtd->token, QTD_TOKEN_PID));
    trace_usb_ehci_qtd_bits(addr,
                            (bool)(qtd->token & QTD_TOKEN_IOC),
                            (bool)(qtd->token & QTD_TOKEN_ACTIVE),
                            (bool)(qtd->token & QTD_TOKEN_HALT),
                            (bool)(qtd->token & QTD_TOKEN_BABBLE),
                            (bool)(qtd->token & QTD_TOKEN_XACTERR));
}


AutofillManager::~AutofillManager() {
  download_manager_.SetObserver(NULL);
}


static void ForSelfAndInstances(SVGElement* element, T callback) {
  SVGElement::InstanceUpdateBlocker blocker(element);
  callback(element);
  for (SVGElement* instance : element->InstancesForElement())
    callback(instance);
}


static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx,
                              CodedBitstreamUnit *unit)
{
    GetBitContext gbc;
    int err;

    err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
    if (err < 0)
        return err;

    if (unit->type >= JPEG_MARKER_SOF0 &&
        unit->type <= JPEG_MARKER_SOF3) {
        err = ff_cbs_alloc_unit_content(ctx, unit,
                                        sizeof(JPEGRawFrameHeader),
                                        NULL);
        if (err < 0)
            return err;

        err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content);
        if (err < 0)
            return err;

    } else if (unit->type >= JPEG_MARKER_APPN &&
               unit->type <= JPEG_MARKER_APPN + 15) {
        err = ff_cbs_alloc_unit_content(ctx, unit,
                                        sizeof(JPEGRawApplicationData),
                                        &cbs_jpeg_free_application_data);
        if (err < 0)
            return err;

        err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content);
        if (err < 0)
            return err;

    } else if (unit->type == JPEG_MARKER_SOS) {
        JPEGRawScan *scan;
        int pos;

        err = ff_cbs_alloc_unit_content(ctx, unit,
                                        sizeof(JPEGRawScan),
                                        &cbs_jpeg_free_scan);
        if (err < 0)
            return err;
        scan = unit->content;

        err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header);
        if (err < 0)
            return err;

        pos = get_bits_count(&gbc);
        av_assert0(pos % 8 == 0);
        if (pos > 0) {
            scan->data_size = unit->data_size - pos / 8;
            scan->data_ref  = av_buffer_ref(unit->data_ref);
            if (!scan->data_ref)
                return AVERROR(ENOMEM);
            scan->data = unit->data + pos / 8;
        }

    } else {
        switch (unit->type) {
#define SEGMENT(marker, type, func, free) \
        case JPEG_MARKER_ ## marker: \
            { \
                err = ff_cbs_alloc_unit_content(ctx, unit, \
                                                sizeof(type), free); \
                if (err < 0) \
                    return err; \
                err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \
                if (err < 0) \
                    return err; \
            } \
            break
            SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL);
            SEGMENT(DHT, JPEGRawHuffmanTableSpecification,      dht, NULL);
            SEGMENT(COM, JPEGRawComment,  comment, &cbs_jpeg_free_comment);
#undef SEGMENT
        default:
            return AVERROR(ENOSYS);
        }
    }

    return 0;
}


vim_stat(const char *name, stat_T *stp)
{
    // On Solaris stat() accepts "file/" as if it was "file".  Return -1 if
    // the name ends in "/" and it's not a directory.
    return illegal_slash(name) ? -1 : stat(name, stp);
}


static int dissect_h245_VideoIndicateCompose ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_VideoIndicateCompose , VideoIndicateCompose_sequence ) ;
 return offset ;
 }


void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
{
    /* The requested range should fit in within the block range */
    g_assert((start + length) <= block->used_length);

#ifdef CONFIG_LIBPMEM
    /* The lack of support for pmem should not block the sync */
    if (ramblock_is_pmem(block)) {
        void *addr = ramblock_ptr(block, start);
        pmem_persist(addr, length);
        return;
    }
#endif
    if (block->fd >= 0) {
        /**
         * Case there is no support for PMEM or the memory has not been
         * specified as persistent (or is not one) - use the msync.
         * Less optimal but still achieves the same goal
         */
        void *addr = ramblock_ptr(block, start);
        if (qemu_msync(addr, length, block->fd)) {
            warn_report("%s: failed to sync memory range: start: "
                    RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
                    __func__, start, length);
        }
    }
}


void FrameLoader::didAccessInitialDocument()
{
    if (isLoadingMainFrame() && !m_didAccessInitialDocument) {
        m_didAccessInitialDocument = true;
        m_didAccessInitialDocumentTimer.startOneShot(0, BLINK_FROM_HERE);
    }
}


static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
	Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
	Stream_Write_UINT32(s, header->MessageType);
}


static inline struct shmid_kernel *shm_lock(struct ipc_namespace *ns, int id)
{
	struct kern_ipc_perm *ipcp = ipc_lock(&shm_ids(ns), id);

	/*
	 * Callers of shm_lock() must validate the status of the returned ipc
	 * object pointer (as returned by ipc_lock()), and error out as
	 * appropriate.
	 */
	if (IS_ERR(ipcp))
		return (void *)ipcp;
	return container_of(ipcp, struct shmid_kernel, shm_perm);
}


static void createPCPResponse(unsigned char *response, const pcp_info_t *pcp_msg_info)
{
	response[2] = 0;	/* reserved */
	memset(response + 12, 0, 12);	/* reserved */
	if (pcp_msg_info->result_code == PCP_ERR_UNSUPP_VERSION ) {
		/* highest supported version */
		response[0] = this_server_info.server_version;
	} else {
		response[0] = pcp_msg_info->version;
	}

	response[1] = pcp_msg_info->opcode | 0x80;	/* r_opcode */
	response[3] = pcp_msg_info->result_code;
	if(epoch_origin == 0) {
		epoch_origin = startup_time;
	}
	WRITENU32(response + 8, upnp_time() - epoch_origin); /* epochtime */
	switch (pcp_msg_info->result_code) {
	/*long lifetime errors*/
	case PCP_ERR_UNSUPP_VERSION:
	case PCP_ERR_NOT_AUTHORIZED:
	case PCP_ERR_MALFORMED_REQUEST:
	case PCP_ERR_UNSUPP_OPCODE:
	case PCP_ERR_UNSUPP_OPTION:
	case PCP_ERR_MALFORMED_OPTION:
	case PCP_ERR_UNSUPP_PROTOCOL:
	case PCP_ERR_ADDRESS_MISMATCH:
	case PCP_ERR_CANNOT_PROVIDE_EXTERNAL:
	case PCP_ERR_EXCESSIVE_REMOTE_PEERS:
		WRITENU32(response + 4, 0);	/* lifetime */
		break;

	case PCP_ERR_NETWORK_FAILURE:
	case PCP_ERR_NO_RESOURCES:
	case PCP_ERR_USER_EX_QUOTA:
		WRITENU32(response + 4, 30);	/* lifetime */
		break;

	case PCP_SUCCESS:
	default:
		WRITENU32(response + 4, pcp_msg_info->lifetime);	/* lifetime */
		break;
	}

	if (response[1] == 0x81) { /* MAP response */
		if (response[0] == 1) {	/* version */
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 4, pcp_msg_info->int_port);
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 6, pcp_msg_info->ext_port);
			copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 8,
			                    pcp_msg_info->ext_ip);
		}
		else if (response[0] == 2) {
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 16, pcp_msg_info->int_port);
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 18, pcp_msg_info->ext_port);
			copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 20,
			                    pcp_msg_info->ext_ip);
		}
	}
#ifdef PCP_PEER
	else if (response[1] == 0x82) { /* PEER response */
		if (response[0] == 1) {
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 4, pcp_msg_info->int_port);
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 6, pcp_msg_info->ext_port);
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 24, pcp_msg_info->peer_port);
			copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 8,
			                    pcp_msg_info->ext_ip);
		}
		else if (response[0] == 2) {
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 16, pcp_msg_info->int_port);
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 18, pcp_msg_info->ext_port);
			WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 36, pcp_msg_info->peer_port);
			copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 20,
			                    pcp_msg_info->ext_ip);
		}
	}
#endif /* PCP_PEER */

#ifdef PCP_SADSCP
	else if (response[1] == 0x83) { /*SADSCP response*/
		response[PCP_COMMON_RESPONSE_SIZE + 12]
			= ((pcp_msg_info->matched_name<<7) & ~(1<<6)) |
			  (pcp_msg_info->sadscp_dscp & PCP_SADSCP_MASK);
		memset(response + PCP_COMMON_RESPONSE_SIZE + 13, 0, 3);
	}
#endif /* PCP_SADSCP */
}


void NetworkChangeNotifierMac::Forwarder::Init()  {
  net_config_watcher_->SetInitialConnectionType();
}


BackendInitialize(Port *port)
{
	int			status;
	int			ret;
	char		remote_host[NI_MAXHOST];
	char		remote_port[NI_MAXSERV];
	StringInfoData ps_data;

	/* Save port etc. for ps status */
	MyProcPort = port;

	/* Tell fd.c about the long-lived FD associated with the port */
	ReserveExternalFD();

	/*
	 * PreAuthDelay is a debugging aid for investigating problems in the
	 * authentication cycle: it can be set in postgresql.conf to allow time to
	 * attach to the newly-forked backend with a debugger.  (See also
	 * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
	 * is not honored until after authentication.)
	 */
	if (PreAuthDelay > 0)
		pg_usleep(PreAuthDelay * 1000000L);

	/* This flag will remain set until InitPostgres finishes authentication */
	ClientAuthInProgress = true;	/* limit visibility of log messages */

	/* set these to empty in case they are needed before we set them up */
	port->remote_host = "";
	port->remote_port = "";

	/*
	 * Initialize libpq and enable reporting of ereport errors to the client.
	 * Must do this now because authentication uses libpq to send messages.
	 */
	pq_init();					/* initialize libpq to talk to client */
	whereToSendOutput = DestRemote; /* now safe to ereport to client */

	/*
	 * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
	 * to collect the startup packet; while SIGQUIT results in _exit(2).
	 * Otherwise the postmaster cannot shutdown the database FAST or IMMED
	 * cleanly if a buggy client fails to send the packet promptly.
	 *
	 * Exiting with _exit(1) is only possible because we have not yet touched
	 * shared memory; therefore no outside-the-process state needs to get
	 * cleaned up.
	 */
	pqsignal(SIGTERM, process_startup_packet_die);
	/* SIGQUIT handler was already set up by InitPostmasterChild */
	InitializeTimeouts();		/* establishes SIGALRM handler */
	PG_SETMASK(&StartupBlockSig);

	/*
	 * Get the remote host name and port for logging and status display.
	 */
	remote_host[0] = '\0';
	remote_port[0] = '\0';
	if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
								  remote_host, sizeof(remote_host),
								  remote_port, sizeof(remote_port),
								  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
		ereport(WARNING,
				(errmsg_internal("pg_getnameinfo_all() failed: %s",
								 gai_strerror(ret))));

	/*
	 * Save remote_host and remote_port in port structure (after this, they
	 * will appear in log_line_prefix data for log messages).
	 */
	port->remote_host = strdup(remote_host);
	port->remote_port = strdup(remote_port);

	/* And now we can issue the Log_connections message, if wanted */
	if (Log_connections)
	{
		if (remote_port[0])
			ereport(LOG,
					(errmsg("connection received: host=%s port=%s",
							remote_host,
							remote_port)));
		else
			ereport(LOG,
					(errmsg("connection received: host=%s",
							remote_host)));
	}

	/*
	 * If we did a reverse lookup to name, we might as well save the results
	 * rather than possibly repeating the lookup during authentication.
	 *
	 * Note that we don't want to specify NI_NAMEREQD above, because then we'd
	 * get nothing useful for a client without an rDNS entry.  Therefore, we
	 * must check whether we got a numeric IPv4 or IPv6 address, and not save
	 * it into remote_hostname if so.  (This test is conservative and might
	 * sometimes classify a hostname as numeric, but an error in that
	 * direction is safe; it only results in a possible extra lookup.)
	 */
	if (log_hostname &&
		ret == 0 &&
		strspn(remote_host, "0123456789.") < strlen(remote_host) &&
		strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
		port->remote_hostname = strdup(remote_host);

	/*
	 * Ready to begin client interaction.  We will give up and _exit(1) after
	 * a time delay, so that a broken client can't hog a connection
	 * indefinitely.  PreAuthDelay and any DNS interactions above don't count
	 * against the time limit.
	 *
	 * Note: AuthenticationTimeout is applied here while waiting for the
	 * startup packet, and then again in InitPostgres for the duration of any
	 * authentication operations.  So a hostile client could tie up the
	 * process for nearly twice AuthenticationTimeout before we kick him off.
	 *
	 * Note: because PostgresMain will call InitializeTimeouts again, the
	 * registration of STARTUP_PACKET_TIMEOUT will be lost.  This is okay
	 * since we never use it again after this function.
	 */
	RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
	enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);

	/*
	 * Receive the startup packet (which might turn out to be a cancel request
	 * packet).
	 */
	status = ProcessStartupPacket(port, false, false);

	/*
	 * Disable the timeout, and prevent SIGTERM again.
	 */
	disable_timeout(STARTUP_PACKET_TIMEOUT, false);
	PG_SETMASK(&BlockSig);

	/*
	 * As a safety check that nothing in startup has yet performed
	 * shared-memory modifications that would need to be undone if we had
	 * exited through SIGTERM or timeout above, check that no on_shmem_exit
	 * handlers have been registered yet.  (This isn't terribly bulletproof,
	 * since someone might misuse an on_proc_exit handler for shmem cleanup,
	 * but it's a cheap and helpful check.  We cannot disallow on_proc_exit
	 * handlers unfortunately, since pq_init() already registered one.)
	 */
	check_on_shmem_exit_lists_are_empty();

	/*
	 * Stop here if it was bad or a cancel packet.  ProcessStartupPacket
	 * already did any appropriate error reporting.
	 */
	if (status != STATUS_OK)
		proc_exit(0);

	/*
	 * Now that we have the user and database name, we can set the process
	 * title for ps.  It's good to do this as early as possible in startup.
	 */
	initStringInfo(&ps_data);
	if (am_walsender)
		appendStringInfo(&ps_data, "%s ", GetBackendTypeDesc(B_WAL_SENDER));
	appendStringInfo(&ps_data, "%s ", port->user_name);
	if (!am_walsender)
		appendStringInfo(&ps_data, "%s ", port->database_name);
	appendStringInfo(&ps_data, "%s", port->remote_host);
	if (port->remote_port[0] != '\0')
		appendStringInfo(&ps_data, "(%s)", port->remote_port);

	init_ps_display(ps_data.data);
	pfree(ps_data.data);

	set_ps_display("initializing");
}


void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key,
                          uint8_t *encryptedPrivateKey, uint32_t *enc_len) {
    LOG_INFO(__FUNCTION__);

    *errString = 0;
    *errStatus = UNKNOWN_ERROR;

    CHECK_STATE(key);
    CHECK_STATE(encryptedPrivateKey);

    *errStatus = UNKNOWN_ERROR;

    int status = AES_encrypt_DH((char *)key, encryptedPrivateKey, BUF_LEN);

    CHECK_STATUS2("AES encrypt failed with status %d");

    *enc_len = strlen(key) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;

    SAFE_CHAR_BUF(decryptedKey, BUF_LEN);

    status = AES_decrypt_DH(encryptedPrivateKey, *enc_len, decryptedKey, BUF_LEN);

    CHECK_STATUS2("trustedDecryptKey failed with status %d");

    uint64_t decryptedKeyLen = strnlen(decryptedKey, MAX_KEY_LENGTH);

    if (decryptedKeyLen == MAX_KEY_LENGTH) {
        snprintf(errString, BUF_LEN, "Decrypted key is not null terminated");
        LOG_ERROR(errString);
        goto clean;
    }

    *errStatus = -8;

    if (strncmp(key, decryptedKey, MAX_KEY_LENGTH) != 0) {
        snprintf(errString, BUF_LEN, "Decrypted key does not match original key");
        LOG_ERROR(errString);
        goto clean;
    }

    SET_SUCCESS
    clean:
    ;
    LOG_INFO(__FUNCTION__ );
    LOG_INFO("SGX call completed");
}


static void end_frame(AVFilterLink *link)

{

    DeshakeContext *deshake = link->dst->priv;

    AVFilterBufferRef *in  = link->cur_buf;

    AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;

    Transform t;

    float matrix[9];

    float alpha = 2.0 / deshake->refcount;

    char tmp[256];

    Transform orig;

    if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {

        // Find the most likely global motion for the current frame

        find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);

    } else {

        uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];

        uint8_t *src2 = in->data[0];

        deshake->cx = FFMIN(deshake->cx, link->w);

        deshake->cy = FFMIN(deshake->cy, link->h);

        if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;

        if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;

        // Quadword align right margin

        deshake->cw &= ~15;

        src1 += deshake->cy * in->linesize[0] + deshake->cx;

        src2 += deshake->cy * in->linesize[0] + deshake->cx;

        find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);

    }

    // Copy transform so we can output it later to compare to the smoothed value

    orig.vector.x = t.vector.x;

    orig.vector.y = t.vector.y;

    orig.angle = t.angle;

    orig.zoom = t.zoom;

    // Generate a one-sided moving exponential average

    deshake->avg.vector.x = alpha * t.vector.x + (1.0 - alpha) * deshake->avg.vector.x;

    deshake->avg.vector.y = alpha * t.vector.y + (1.0 - alpha) * deshake->avg.vector.y;

    deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;

    deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;

    // Remove the average from the current motion to detect the motion that

    // is not on purpose, just as jitter from bumping the camera

    t.vector.x -= deshake->avg.vector.x;

    t.vector.y -= deshake->avg.vector.y;

    t.angle -= deshake->avg.angle;

    t.zoom -= deshake->avg.zoom;

    // Invert the motion to undo it

    t.vector.x *= -1;

    t.vector.y *= -1;

    t.angle *= -1;

    // Write statistics to file

    if (deshake->fp) {

        snprintf(tmp, 256, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n", orig.vector.x, deshake->avg.vector.x, t.vector.x, orig.vector.y, deshake->avg.vector.y, t.vector.y, orig.angle, deshake->avg.angle, t.angle, orig.zoom, deshake->avg.zoom, t.zoom);

        fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);

    }

    // Turn relative current frame motion into absolute by adding it to the

    // last absolute motion

    t.vector.x += deshake->last.vector.x;

    t.vector.y += deshake->last.vector.y;

    t.angle += deshake->last.angle;

    t.zoom += deshake->last.zoom;

    // Shrink motion by 10% to keep things centered in the camera frame

    t.vector.x *= 0.9;

    t.vector.y *= 0.9;

    t.angle *= 0.9;

    // Store the last absolute motion information

    deshake->last.vector.x = t.vector.x;

    deshake->last.vector.y = t.vector.y;

    deshake->last.angle = t.angle;

    deshake->last.zoom = t.zoom;

    // Generate a luma transformation matrix

    avfilter_get_matrix(t.vector.x, t.vector.y, t.angle, 1.0 + t.zoom / 100.0, matrix);

    // Transform the luma plane

    avfilter_transform(in->data[0], out->data[0], in->linesize[0], out->linesize[0], link->w, link->h, matrix, INTERPOLATE_BILINEAR, deshake->edge);

    // Generate a chroma transformation matrix

    avfilter_get_matrix(t.vector.x / (link->w / CHROMA_WIDTH(link)), t.vector.y / (link->h / CHROMA_HEIGHT(link)), t.angle, 1.0 + t.zoom / 100.0, matrix);

    // Transform the chroma planes

    avfilter_transform(in->data[1], out->data[1], in->linesize[1], out->linesize[1], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), matrix, INTERPOLATE_BILINEAR, deshake->edge);

    avfilter_transform(in->data[2], out->data[2], in->linesize[2], out->linesize[2], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), matrix, INTERPOLATE_BILINEAR, deshake->edge);

    // Store the current frame as the reference frame for calculating the

    // motion of the next frame

    if (deshake->ref != NULL)

        avfilter_unref_buffer(deshake->ref);

    // Cleanup the old reference frame

    deshake->ref = in;

    // Draw the transformed frame information

    avfilter_draw_slice(link->dst->outputs[0], 0, link->h, 1);

    avfilter_end_frame(link->dst->outputs[0]);

    avfilter_unref_buffer(out);

}


static int nl80211_associate(struct sk_buff *skb, struct genl_info *info)
{
	struct cfg80211_registered_device *rdev = info->user_ptr[0];
	struct net_device *dev = info->user_ptr[1];
	struct cfg80211_crypto_settings crypto;
	struct ieee80211_channel *chan;
	const u8 *bssid, *ssid, *ie = NULL, *prev_bssid = NULL;
	int err, ssid_len, ie_len = 0;
	bool use_mfp = false;

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

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

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

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

	bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);

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

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

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

	if (info->attrs[NL80211_ATTR_USE_MFP]) {
		enum nl80211_mfp mfp =
			nla_get_u32(info->attrs[NL80211_ATTR_USE_MFP]);
		if (mfp == NL80211_MFP_REQUIRED)
			use_mfp = true;
		else if (mfp != NL80211_MFP_NO)
			return -EINVAL;
	}

	if (info->attrs[NL80211_ATTR_PREV_BSSID])
		prev_bssid = nla_data(info->attrs[NL80211_ATTR_PREV_BSSID]);

	err = nl80211_crypto_settings(rdev, info, &crypto, 1);
	if (!err)
		err = cfg80211_mlme_assoc(rdev, dev, chan, bssid, prev_bssid,
					  ssid, ssid_len, ie, ie_len, use_mfp,
					  &crypto);

	return err;


static void aux_slave_dev_print(Monitor *mon, DeviceState *dev, int indent)

{

    AUXBus *bus = AUX_BUS(qdev_get_parent_bus(dev));

    AUXSlave *s;

    /* Don't print anything if the device is I2C "bridge". */

    if (aux_bus_is_bridge(bus, dev)) {

        return;

    }

    s = AUX_SLAVE(dev);

    monitor_printf(mon, "%*smemory " TARGET_FMT_plx "/" TARGET_FMT_plx "\n",

                   indent, "",

                   object_property_get_int(OBJECT(s->mmio), "addr", NULL),

                   memory_region_size(s->mmio));

}


int secure_decrypt(void *data, unsigned int data_length, int is_signed)
{
	at91_aes_key_size_t key_size;
	unsigned int cmac_key[8], cipher_key[8];
	unsigned int iv[AT91_AES_IV_SIZE_WORD];
	unsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];
	unsigned int fixed_length;
	const unsigned int *cmac;
	int rc = -1;

	/* Init keys */
	init_keys(&key_size, cipher_key, cmac_key, iv);

	/* Init periph */
	at91_aes_init();

	/* Check signature if required */
	if (is_signed) {
		/* Compute the CMAC */
		if (at91_aes_cmac(data_length, data, computed_cmac,
				  key_size, cmac_key))
			goto exit;

		/* Check the CMAC */
		fixed_length = at91_aes_roundup(data_length);
		cmac = (const unsigned int *)((char *)data + fixed_length);
		if (!consttime_memequal(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))
			goto exit;
	}

	/* Decrypt the whole file */
	if (at91_aes_cbc(data_length, data, data, 0,
			 key_size, cipher_key, iv))
		goto exit;

	rc = 0;
exit:
	/* Reset periph */
	at91_aes_cleanup();

	/* Reset keys */
	memset(cmac_key, 0, sizeof(cmac_key));
	memset(cipher_key, 0, sizeof(cipher_key));
	memset(iv, 0, sizeof(iv));

	return rc;
}


xsltValueOfComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
    xsltStyleItemValueOfPtr comp;
#else
    xsltStylePreCompPtr comp;
#endif
    const xmlChar *prop;

    if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
	return;

#ifdef XSLT_REFACTORED
    comp = (xsltStyleItemValueOfPtr) xsltNewStylePreComp(style, XSLT_FUNC_VALUEOF);
#else
    comp = xsltNewStylePreComp(style, XSLT_FUNC_VALUEOF);
#endif

    if (comp == NULL)
	return;
    inst->psvi = comp;
    comp->inst = inst;

    prop = xsltGetCNsProp(style, inst,
	    (const xmlChar *)"disable-output-escaping",
			XSLT_NAMESPACE);
    if (prop != NULL) {
	if (xmlStrEqual(prop, (const xmlChar *)"yes")) {
	    comp->noescape = 1;
	} else if (!xmlStrEqual(prop,
				(const xmlChar *)"no")){
	    xsltTransformError(NULL, style, inst,
"xsl:value-of : disable-output-escaping allows only yes or no\n");
	    if (style != NULL) style->warnings++;
	}
    }
    comp->select = xsltGetCNsProp(style, inst, (const xmlChar *)"select",
	                        XSLT_NAMESPACE);
    if (comp->select == NULL) {
	xsltTransformError(NULL, style, inst,
	     "xsl:value-of : select is missing\n");
	if (style != NULL) style->errors++;
	return;
    }
    comp->comp = xsltXPathCompile(style, comp->select);
    if (comp->comp == NULL) {
	xsltTransformError(NULL, style, inst,
	     "xsl:value-of : could not compile select expression '%s'\n",
	                 comp->select);
	if (style != NULL) style->errors++;
    }
}


int ip6mr_get_route(struct net *net, struct sk_buff *skb, struct rtmsg *rtm,
		    u32 portid)
{
	int err;
	struct mr6_table *mrt;
	struct mfc6_cache *cache;
	struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);

	mrt = ip6mr_get_table(net, RT6_TABLE_DFLT);
	if (!mrt)
		return -ENOENT;

	read_lock(&mrt_lock);
	cache = ip6mr_cache_find(mrt, &rt->rt6i_src.addr, &rt->rt6i_dst.addr);
	if (!cache && skb->dev) {
		int vif = ip6mr_find_vif(mrt, skb->dev);

		if (vif >= 0)
			cache = ip6mr_cache_find_any(mrt, &rt->rt6i_dst.addr,
						     vif);
	}

	if (!cache) {
		struct sk_buff *skb2;
		struct ipv6hdr *iph;
		struct net_device *dev;
		int vif;

		dev = skb->dev;
		if (!dev || (vif = ip6mr_find_vif(mrt, dev)) < 0) {
			read_unlock(&mrt_lock);
			return -ENODEV;
		}

		/* really correct? */
		skb2 = alloc_skb(sizeof(struct ipv6hdr), GFP_ATOMIC);
		if (!skb2) {
			read_unlock(&mrt_lock);
			return -ENOMEM;
		}

		NETLINK_CB(skb2).portid = portid;
		skb_reset_transport_header(skb2);

		skb_put(skb2, sizeof(struct ipv6hdr));
		skb_reset_network_header(skb2);

		iph = ipv6_hdr(skb2);
		iph->version = 0;
		iph->priority = 0;
		iph->flow_lbl[0] = 0;
		iph->flow_lbl[1] = 0;
		iph->flow_lbl[2] = 0;
		iph->payload_len = 0;
		iph->nexthdr = IPPROTO_NONE;
		iph->hop_limit = 0;
		iph->saddr = rt->rt6i_src.addr;
		iph->daddr = rt->rt6i_dst.addr;

		err = ip6mr_cache_unresolved(mrt, vif, skb2);
		read_unlock(&mrt_lock);

		return err;
	}

	if (rtm->rtm_flags & RTM_F_NOTIFY)
		cache->mfc_flags |= MFC_NOTIFY;

	err = __ip6mr_fill_mroute(mrt, skb, cache, rtm);
	read_unlock(&mrt_lock);
	return err;
}


static ut32 adrp(ArmOp *op, ut64 addr, ut32 k) { //, int reg, ut64 dst) {
	ut64 at = 0LL;
	ut32 data = k;
	if (op->operands[0].type == ARM_GPR) {
		data += ((op->operands[0].reg & 0xff) << 24);
	} else {
		eprintf ("Usage: adrp x0, addr\n");
		return UT32_MAX;
	}
	if (op->operands[1].type == ARM_CONSTANT) {
		// XXX what about negative values?
		at = op->operands[1].immediate - addr;
		at /= 4;
	} else {
		eprintf ("Usage: adrp, x0, addr\n");
		return UT32_MAX;
	}
	ut8 b0 = at;
	ut8 b1 = (at >> 3) & 0xff;

#if 0
	ut8 b2 = (at >> (8 + 7)) & 0xff;
	data += b0 << 29;
	data += b1 << 16;
	data += b2 << 24;
#endif
	data += b0 << 16;
	data += b1 << 8;
	return data;
}


int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
  autohide_factory_.InvalidateWeakPtrs();
  return Appbar::instance()->GetAutohideEdges(
      monitor,
      base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
                 autohide_factory_.GetWeakPtr()));
}


static void model2_update ( Model2 * m , int bit ) {
 unsigned scale ;
 if ( ! bit ) m -> zero_weight ++ ;
 m -> till_rescale -- ;
 if ( m -> till_rescale ) return ;
 m -> total_weight += m -> upd_val ;
 if ( m -> total_weight > 0x2000 ) {
 m -> total_weight = ( m -> total_weight + 1 ) >> 1 ;
 m -> zero_weight = ( m -> zero_weight + 1 ) >> 1 ;
 if ( m -> total_weight == m -> zero_weight ) m -> total_weight = m -> zero_weight + 1 ;
 }
 m -> upd_val = m -> upd_val * 5 >> 2 ;
 if ( m -> upd_val > 64 ) m -> upd_val = 64 ;
 scale = 0x80000000u / m -> total_weight ;
 m -> zero_freq = m -> zero_weight * scale >> 18 ;
 m -> total_freq = m -> total_weight * scale >> 18 ;
 m -> till_rescale = m -> upd_val ;
 }


virtual void Acknowledge(const invalidation::AckHandle& handle) {}


static inline int gic_get_current_cpu ( GICState * s ) {
 if ( s -> num_cpu > 1 ) {
 CPUState * cpu = ENV_GET_CPU ( cpu_single_env ) ;
 return cpu -> cpu_index ;
 }
 return 0 ;
 }


ssize_t vb2_fop_read(struct file *file, char __user *buf,
		size_t count, loff_t *ppos)
{
	struct video_device *vdev = video_devdata(file);
	struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
	int err = -EBUSY;

	if (!(vdev->queue->io_modes & VB2_READ))
		return -EINVAL;
	if (lock && mutex_lock_interruptible(lock))
		return -ERESTARTSYS;
	if (vb2_queue_is_busy(vdev, file))
		goto exit;
	err = vb2_read(vdev->queue, buf, count, ppos,
		       file->f_flags & O_NONBLOCK);
	if (vdev->queue->fileio)
		vdev->queue->owner = file->private_data;
exit:
	if (lock)
		mutex_unlock(lock);
	return err;
}


static void x8_get_prediction ( IntraX8Context * const w ) {
 MpegEncContext * const s = w -> s ;
 int a , b , c , i ;
 w -> edges = 1 * ( ! s -> mb_x ) ;
 w -> edges |= 2 * ( ! s -> mb_y ) ;
 w -> edges |= 4 * ( s -> mb_x >= ( 2 * s -> mb_width - 1 ) ) ;
 switch ( w -> edges & 3 ) {
 case 0 : break ;
 case 1 : w -> est_run = w -> prediction_table [ ! ( s -> mb_y & 1 ) ] >> 2 ;
 w -> orient = 1 ;
 return ;
 case 2 : w -> est_run = w -> prediction_table [ 2 * s -> mb_x - 2 ] >> 2 ;
 w -> orient = 2 ;
 return ;
 case 3 : w -> est_run = 16 ;
 w -> orient = 0 ;
 return ;
 }
 / o edge cases b = w -> prediction_table [ 2 * s -> mb_x + ! ( s -> mb_y & 1 ) ] ;
 a = w -> prediction_table [ 2 * s -> mb_x - 2 + ( s -> mb_y & 1 ) ] ;
 c = w -> prediction_table [ 2 * s -> mb_x - 2 + ! ( s -> mb_y & 1 ) ] ;
 w -> est_run = FFMIN ( b , a ) ;
 if ( ( s -> mb_x & s -> mb_y ) != 0 ) w -> est_run = FFMIN ( c , w -> est_run ) ;
 w -> est_run >>= 2 ;
 a &= 3 ;
 b &= 3 ;
 c &= 3 ;
 i = ( 0xFFEAF4C4 >> ( 2 * b + 8 * a ) ) & 3 ;
 if ( i != 3 ) w -> orient = i ;
 else w -> orient = ( 0xFFEAD8 >> ( 2 * c + 8 * ( w -> quant > 12 ) ) ) & 3 ;
 }


static void xhci_intr_raise(XHCIState *xhci, int v)
{
    PCIDevice *pci_dev = PCI_DEVICE(xhci);

    xhci->intr[v].erdp_low |= ERDP_EHB;
    xhci->intr[v].iman |= IMAN_IP;
    xhci->usbsts |= USBSTS_EINT;

    if (!(xhci->intr[v].iman & IMAN_IE)) {
        return;
    }

    if (!(xhci->usbcmd & USBCMD_INTE)) {
        return;
    }

    if (msix_enabled(pci_dev)) {
        trace_usb_xhci_irq_msix(v);
        msix_notify(pci_dev, v);
        return;
    }

    if (msi_enabled(pci_dev)) {
        trace_usb_xhci_irq_msi(v);
        msi_notify(pci_dev, v);
        return;
    }

    if (v == 0) {
        trace_usb_xhci_irq_intx(1);
        pci_irq_assert(pci_dev);
    }
}


PGTYPESdate_to_asc(date dDate)
{
	struct tm	tt,
			   *tm = &tt;
	char		buf[MAXDATELEN + 1];
	int			DateStyle = 1;
	bool		EuroDates = FALSE;

	j2date(dDate + date2j(2000, 1, 1), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
	EncodeDateOnly(tm, DateStyle, buf, EuroDates);
	return pgtypes_strdup(buf);
}


bool Shell::CanAcceptEvent(const ui::Event& event) {
  return true;
}


qemuProcessFindDomainDiskByAliasOrQOM(virDomainObjPtr vm,
                                      const char *alias,
                                      const char *qomid)
{
    size_t i;

    if (alias && *alias == '\0')
        alias = NULL;

    if (alias)
        alias = qemuAliasDiskDriveSkipPrefix(alias);

    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

        if ((disk->info.alias && STREQ_NULLABLE(disk->info.alias, alias)) ||
            (diskPriv->qomName && STREQ_NULLABLE(diskPriv->qomName, qomid)))
            return disk;
    }

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("no disk found with alias '%s' or id '%s'"),
                   NULLSTR(alias), NULLSTR(qomid));
    return NULL;
}


void xmlInitGlobals ( void ) {
 if ( xmlThrDefMutex == NULL ) xmlThrDefMutex = xmlNewMutex ( ) ;
 }


static void pmao_restore_workaround(bool ebb) { }


void WebGLObject::detach()
{
    m_attachmentCount = 0; // Make sure OpenGL resource is deleted.
    }


SWFShape_addSolidFillStyle(SWFShape shape, byte r, byte g, byte b, byte a)
{
	int  ret;

	SWFFillStyle fill = newSWFSolidFillStyle(r, g, b, a);

	ret = addFillStyle(shape, fill);
	if(ret < 0) /* error */
	{
		destroySWFFillStyle(fill);
		return NULL;
	}
	else if(ret == shape->nFills)  /* new fill */
	{
		return fill;
	}
	else /* fill is known */
	{
		destroySWFFillStyle(fill);
		return shape->fills[ret];
	}
}


static PassRefPtr<CSSPrimitiveValue> fontSizeFromStyle(RenderStyle* style)
{
    return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), style);
}


int Jsi_AddAutoFiles(Jsi_Interp *interp, const char *dir) {
    Jsi_DString dStr = {};
    Jsi_StatBuf stat;
    int i, cnt = 0;
    for (i=0; i<2; i++) {
        Jsi_DSAppend(&dStr, dir, (i==0?"/lib":""),"/autoload.jsi", NULL);
        Jsi_Value *v = Jsi_ValueNewStringKey(interp, Jsi_DSValue(&dStr));
        if (Jsi_Stat(interp, v, &stat) != 0)
            Jsi_ValueFree(interp, v);
        else {
            if (!interp->autoFiles) {
                interp->autoFiles = Jsi_ValueNewArray(interp, 0, 0);
                Jsi_IncrRefCount(interp, interp->autoFiles);
            }
            Jsi_ObjArrayAdd(interp, interp->autoFiles->d.obj, v);
            cnt++;
            interp->autoLoaded = 0;
        }
        Jsi_DSSetLength(&dStr, 0);
    }
    Jsi_DSFree(&dStr);
    return cnt;
}


static inline int tcp_checksum_complete_user(struct sock *sk,
					     struct sk_buff *skb)
{
	return !skb_csum_unnecessary(skb) &&
	       __tcp_checksum_complete_user(sk, skb);
}


RenderFrameHostImpl* RenderFrameHostImpl::FromAXTreeID(
    ui::AXTreeID ax_tree_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  ui::AXTreeIDRegistry::FrameID frame_id =
      ui::AXTreeIDRegistry::GetInstance()->GetFrameID(ax_tree_id);
  return RenderFrameHostImpl::FromID(frame_id.first, frame_id.second);
}


void BackendIO::FlushQueue() {
  operation_ = OP_FLUSH_QUEUE;
}


 void TestResizeBuffers(int32_t* attribs) {
   PP_Resource graphics3d_id = PPBGraphics3D()->
       Create(pp_instance(), kInvalidResource, attribs);
  EXPECT(graphics3d_id != kInvalidResource);
  int32_t success = PPBInstance()->BindGraphics(pp_instance(), graphics3d_id);
  EXPECT(success == PP_TRUE);
  int32_t result;
  result = PPBGraphics3D()->ResizeBuffers(graphics3d_id, -1000, 0);
  EXPECT(result == PP_ERROR_BADARGUMENT);
  result = PPBGraphics3D()->ResizeBuffers(graphics3d_id, 100, -1);
  EXPECT(result == PP_ERROR_BADARGUMENT);
  result = PPBGraphics3D()->ResizeBuffers(graphics3d_id, -1, -1);
  EXPECT(result == PP_ERROR_BADARGUMENT);
  RenderInfo* render_info = new RenderInfo;
  render_info->graphics3d_id = graphics3d_id;
  render_info->frame_counter = 0;
  render_info->frame_end = 256;
  render_info->frame_increment = 8;
  PP_CompletionCallback cc = PP_MakeCompletionCallback(
      TestResizeAndSwapCallback, render_info);
   PPBCore()->CallOnMainThread(0, cc, PP_OK);
 }


Tensor Tensor::SubSlice(int64_t index) const {
  CHECK_GE(dims(), 1);  // Crash ok.
  CHECK_LE(0, index);   // Crash ok.
  int64_t dim0_size = shape_.dim_size(0);
  CHECK_LE(index, dim0_size);  // Crash ok.
  Tensor ret;
  ret.shape_ = shape_;
  ret.shape_.RemoveDim(0);
  ret.set_dtype(dtype());
  ret.buf_ = nullptr;
  if (dim0_size > 0) {
    const int64_t elems_per_dim0 = NumElements() / dim0_size;
    const int64_t delta = index * elems_per_dim0;
    const int64_t num_elems = elems_per_dim0;
    if (buf_) {
      DataType dt = dtype();
      CASES(dt, ret.buf_ = new SubBuffer<T>(buf_, delta, num_elems));
    }
  }
  return ret;
}


int ptrace_get_reg(struct task_struct *task, int regno, unsigned long *data)
{
	if ((task->thread.regs == NULL) || !data)
		return -EIO;

	if (regno == PT_MSR) {
		*data = get_user_msr(task);
		return 0;
	}

	if (regno == PT_DSCR)
		return get_user_dscr(task, data);

	if (regno < (sizeof(struct pt_regs) / sizeof(unsigned long))) {
		*data = ((unsigned long *)task->thread.regs)[regno];
		return 0;
	}

	return -EIO;
}


void LayerTreeHostImpl::SetLayerTreeMutator(
    std::unique_ptr<LayerTreeMutator> mutator) {
  if (mutator == mutator_)
    return;
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("compositor-worker"),
               "LayerTreeHostImpl::SetLayerTreeMutator");
  mutator_ = std::move(mutator);
  mutator_->SetClient(this);
}


static int dumpcffhmtx ( struct alltabs * at , SplineFont * sf , int bitmaps ) {
 DBounds b ;
 SplineChar * sc ;
 int i , cnt ;
 int dovmetrics = sf -> hasvmetrics ;
 int width = at -> gi . fixed_width ;
 at -> gi . hmtx = tmpfile ( ) ;
 if ( dovmetrics ) at -> gi . vmtx = tmpfile ( ) ;
 FigureFullMetricsEnd ( sf , & at -> gi , bitmaps ) ;
 if ( at -> gi . bygid [ 0 ] != - 1 && ( sf -> glyphs [ at -> gi . bygid [ 0 ] ] -> width == width || width <= 0 ) ) {
 putshort ( at -> gi . hmtx , sf -> glyphs [ at -> gi . bygid [ 0 ] ] -> width ) ;
 SplineCharLayerFindBounds ( sf -> glyphs [ at -> gi . bygid [ 0 ] ] , at -> gi . layer , & b ) ;
 putshort ( at -> gi . hmtx , b . minx ) ;
 if ( dovmetrics ) {
 putshort ( at -> gi . vmtx , sf -> glyphs [ at -> gi . bygid [ 0 ] ] -> vwidth ) ;
 putshort ( at -> gi . vmtx , b . miny ) ;
 }
 }
 else {
 putshort ( at -> gi . hmtx , width <= 0 ? ( sf -> ascent + sf -> descent ) / 2 : width ) ;
 putshort ( at -> gi . hmtx , 0 ) ;
 if ( dovmetrics ) {
 putshort ( at -> gi . vmtx , sf -> ascent + sf -> descent ) ;
 putshort ( at -> gi . vmtx , 0 ) ;
 }
 }
 cnt = 1 ;
 if ( bitmaps ) {
 if ( width <= 0 ) width = ( sf -> ascent + sf -> descent ) / 3 ;
 putshort ( at -> gi . hmtx , width ) ;
 putshort ( at -> gi . hmtx , 0 ) ;
 if ( dovmetrics ) {
 putshort ( at -> gi . vmtx , sf -> ascent + sf -> descent ) ;
 putshort ( at -> gi . vmtx , 0 ) ;
 }
 putshort ( at -> gi . hmtx , width ) ;
 putshort ( at -> gi . hmtx , 0 ) ;
 if ( dovmetrics ) {
 putshort ( at -> gi . vmtx , sf -> ascent + sf -> descent ) ;
 putshort ( at -> gi . vmtx , 0 ) ;
 }
 cnt = 3 ;
 }
 for ( i = cnt ;
 i < at -> gi . gcnt ;
 ++ i ) if ( at -> gi . bygid [ i ] != - 1 ) {
 sc = sf -> glyphs [ at -> gi . bygid [ i ] ] ;
 if ( SCWorthOutputting ( sc ) ) {
 if ( i <= at -> gi . lasthwidth ) putshort ( at -> gi . hmtx , sc -> width ) ;
 SplineCharLayerFindBounds ( sc , at -> gi . layer , & b ) ;
 putshort ( at -> gi . hmtx , b . minx ) ;
 if ( dovmetrics ) {
 if ( i <= at -> gi . lastvwidth ) putshort ( at -> gi . vmtx , sc -> vwidth ) ;
 putshort ( at -> gi . vmtx , b . maxy ) ;
 }
 ++ cnt ;
 if ( i == at -> gi . lasthwidth ) at -> gi . hfullcnt = cnt ;
 if ( i == at -> gi . lastvwidth ) at -> gi . vfullcnt = cnt ;
 }
 }
 at -> gi . hmtxlen = ftell ( at -> gi . hmtx ) ;
 if ( at -> gi . hmtxlen & 2 ) putshort ( at -> gi . hmtx , 0 ) ;
 if ( dovmetrics ) {
 at -> gi . vmtxlen = ftell ( at -> gi . vmtx ) ;
 if ( at -> gi . vmtxlen & 2 ) putshort ( at -> gi . vmtx , 0 ) ;
 }
 at -> gi . maxp -> numGlyphs = cnt ;
 return ( true ) ;
 }


  void checkBuffer(struct iovec* iov, uint32_t count) const {
    uint32_t idx = 0;
    for (uint32_t n = 0; n < count; ++n) {
      size_t bytesLeft = bytesRead_ - idx;
      int rc = memcmp(
          buf_.get() + idx,
          iov[n].iov_base,
          std::min(iov[n].iov_len, bytesLeft));
      if (rc != 0) {
        FAIL() << "buffer mismatch at iovec " << n << "/" << count
               << ": rc=" << rc;
      }
      if (iov[n].iov_len > bytesLeft) {
        FAIL() << "server did not read enough data: "
               << "ended at byte " << bytesLeft << "/" << iov[n].iov_len
               << " in iovec " << n << "/" << count;
      }

      idx += iov[n].iov_len;
    }
    if (idx != bytesRead_) {
      ADD_FAILURE() << "server read extra data: " << bytesRead_
                    << " bytes read; expected " << idx;
    }
  }


static inline int rsvp_class_to_tree_type ( int classnum ) {
 switch ( classnum ) {
 case RSVP_CLASS_SESSION : return TT_SESSION ;
 case RSVP_CLASS_HOP : return TT_HOP ;
 case RSVP_CLASS_INTEGRITY : return TT_INTEGRITY ;
 case RSVP_CLASS_TIME_VALUES : return TT_TIME_VALUES ;
 case RSVP_CLASS_ERROR : return TT_ERROR ;
 case RSVP_CLASS_SCOPE : return TT_SCOPE ;
 case RSVP_CLASS_STYLE : return TT_STYLE ;
 case RSVP_CLASS_FLOWSPEC : return TT_FLOWSPEC ;
 case RSVP_CLASS_FILTER_SPEC : return TT_FILTER_SPEC ;
 case RSVP_CLASS_SENDER_TEMPLATE : return TT_SENDER_TEMPLATE ;
 case RSVP_CLASS_SENDER_TSPEC : return TT_TSPEC ;
 case RSVP_CLASS_ADSPEC : return TT_ADSPEC ;
 case RSVP_CLASS_POLICY : return TT_POLICY ;
 case RSVP_CLASS_CONFIRM : return TT_CONFIRM ;
 case RSVP_CLASS_RECOVERY_LABEL : case RSVP_CLASS_UPSTREAM_LABEL : case RSVP_CLASS_SUGGESTED_LABEL : case RSVP_CLASS_LABEL : return TT_LABEL ;
 case RSVP_CLASS_LABEL_REQUEST : return TT_LABEL_REQUEST ;
 case RSVP_CLASS_HELLO : return TT_HELLO_OBJ ;
 case RSVP_CLASS_EXPLICIT_ROUTE : return TT_EXPLICIT_ROUTE ;
 case RSVP_CLASS_RECORD_ROUTE : return TT_RECORD_ROUTE ;
 case RSVP_CLASS_MESSAGE_ID : return TT_MESSAGE_ID ;
 case RSVP_CLASS_MESSAGE_ID_ACK : return TT_MESSAGE_ID_ACK ;
 case RSVP_CLASS_MESSAGE_ID_LIST : return TT_MESSAGE_ID_LIST ;
 case RSVP_CLASS_LABEL_SET : return TT_LABEL_SET ;
 case RSVP_CLASS_PROTECTION : return TT_PROTECTION_INFO ;
 case RSVP_CLASS_ACCEPTABLE_LABEL_SET : return TT_UNKNOWN_CLASS ;
 case RSVP_CLASS_RESTART_CAP : return TT_RESTART_CAP ;
 case RSVP_CLASS_LINK_CAP : return TT_LINK_CAP ;
 case RSVP_CLASS_DIFFSERV : return TT_DIFFSERV ;
 case RSVP_CLASS_CLASSTYPE : return TT_CLASSTYPE ;
 case RSVP_CLASS_NOTIFY_REQUEST : return TT_UNKNOWN_CLASS ;
 case RSVP_CLASS_ADMIN_STATUS : return TT_ADMIN_STATUS ;
 case RSVP_CLASS_LSP_ATTRIBUTES : case RSVP_CLASS_LSP_REQUIRED_ATTRIBUTES : return TT_LSP_ATTRIBUTES ;
 case RSVP_CLASS_ASSOCIATION : return TT_ASSOCIATION ;
 case RSVP_CLASS_CALL_ATTRIBUTES : return RSVPF_CALL_ATTRIBUTES ;
 case RSVP_CLASS_JUNIPER_PROPERTIES : return TT_JUNIPER ;
 case RSVP_CLASS_SESSION_ATTRIBUTE : return TT_SESSION_ATTRIBUTE ;
 case RSVP_CLASS_GENERALIZED_UNI : return TT_GEN_UNI ;
 case RSVP_CLASS_CALL_ID : return TT_CALL_ID ;
 case RSVP_CLASS_3GPP2_OBJECT : return TT_3GPP2_OBJECT ;
 case RSVP_CLASS_DCLASS : return TT_DCLASS ;
 case RSVP_CLASS_LSP_TUNNEL_IF_ID : return TT_LSP_TUNNEL_IF_ID ;
 case RSVP_CLASS_EXCLUDE_ROUTE : return TT_EXCLUDE_ROUTE ;
 case RSVP_CLASS_VENDOR_PRIVATE_1 : case RSVP_CLASS_VENDOR_PRIVATE_2 : case RSVP_CLASS_VENDOR_PRIVATE_3 : case RSVP_CLASS_VENDOR_PRIVATE_4 : case RSVP_CLASS_VENDOR_PRIVATE_5 : case RSVP_CLASS_VENDOR_PRIVATE_6 : case RSVP_CLASS_VENDOR_PRIVATE_7 : case RSVP_CLASS_VENDOR_PRIVATE_8 : case RSVP_CLASS_VENDOR_PRIVATE_9 : case RSVP_CLASS_VENDOR_PRIVATE_10 : case RSVP_CLASS_VENDOR_PRIVATE_11 : case RSVP_CLASS_VENDOR_PRIVATE_12 : return TT_PRIVATE_CLASS ;
 default : return TT_UNKNOWN_CLASS ;
 }
 }


static vpx_codec_err_t set_encoder_config ( VP9EncoderConfig * oxcf , const vpx_codec_enc_cfg_t * cfg , const struct vp9_extracfg * extra_cfg ) {
 const int is_vbr = cfg -> rc_end_usage == VPX_VBR ;
 oxcf -> profile = cfg -> g_profile ;
 oxcf -> width = cfg -> g_w ;
 oxcf -> height = cfg -> g_h ;
 oxcf -> bit_depth = extra_cfg -> bit_depth ;
 oxcf -> input_bit_depth = cfg -> g_input_bit_depth ;
 oxcf -> init_framerate = ( double ) cfg -> g_timebase . den / cfg -> g_timebase . num ;
 if ( oxcf -> init_framerate > 180 ) oxcf -> init_framerate = 30 ;
 oxcf -> mode = GOOD ;
 switch ( cfg -> g_pass ) {
 case VPX_RC_ONE_PASS : oxcf -> pass = 0 ;
 break ;
 case VPX_RC_FIRST_PASS : oxcf -> pass = 1 ;
 break ;
 case VPX_RC_LAST_PASS : oxcf -> pass = 2 ;
 break ;
 }
 oxcf -> lag_in_frames = cfg -> g_pass == VPX_RC_FIRST_PASS ? 0 : cfg -> g_lag_in_frames ;
 oxcf -> rc_mode = cfg -> rc_end_usage ;
 oxcf -> target_bandwidth = 1000 * cfg -> rc_target_bitrate ;
 oxcf -> rc_max_intra_bitrate_pct = extra_cfg -> rc_max_intra_bitrate_pct ;
 oxcf -> best_allowed_q = extra_cfg -> lossless ? 0 : vp9_quantizer_to_qindex ( cfg -> rc_min_quantizer ) ;
 oxcf -> worst_allowed_q = extra_cfg -> lossless ? 0 : vp9_quantizer_to_qindex ( cfg -> rc_max_quantizer ) ;
 oxcf -> cq_level = vp9_quantizer_to_qindex ( extra_cfg -> cq_level ) ;
 oxcf -> fixed_q = - 1 ;
 oxcf -> under_shoot_pct = cfg -> rc_undershoot_pct ;
 oxcf -> over_shoot_pct = cfg -> rc_overshoot_pct ;
 oxcf -> allow_spatial_resampling = cfg -> rc_resize_allowed ;
 oxcf -> scaled_frame_width = cfg -> rc_scaled_width ;
 oxcf -> scaled_frame_height = cfg -> rc_scaled_height ;
 oxcf -> maximum_buffer_size_ms = is_vbr ? 240000 : cfg -> rc_buf_sz ;
 oxcf -> starting_buffer_level_ms = is_vbr ? 60000 : cfg -> rc_buf_initial_sz ;
 oxcf -> optimal_buffer_level_ms = is_vbr ? 60000 : cfg -> rc_buf_optimal_sz ;
 oxcf -> drop_frames_water_mark = cfg -> rc_dropframe_thresh ;
 oxcf -> two_pass_vbrbias = cfg -> rc_2pass_vbr_bias_pct ;
 oxcf -> two_pass_vbrmin_section = cfg -> rc_2pass_vbr_minsection_pct ;
 oxcf -> two_pass_vbrmax_section = cfg -> rc_2pass_vbr_maxsection_pct ;
 oxcf -> auto_key = cfg -> kf_mode == VPX_KF_AUTO && cfg -> kf_min_dist != cfg -> kf_max_dist ;
 oxcf -> key_freq = cfg -> kf_max_dist ;
 oxcf -> speed = abs ( extra_cfg -> cpu_used ) ;
 oxcf -> encode_breakout = extra_cfg -> static_thresh ;
 oxcf -> play_alternate = extra_cfg -> enable_auto_alt_ref ;
 oxcf -> noise_sensitivity = extra_cfg -> noise_sensitivity ;
 oxcf -> sharpness = extra_cfg -> sharpness ;
 oxcf -> two_pass_stats_in = cfg -> rc_twopass_stats_in ;
 # if CONFIG_FP_MB_STATS oxcf -> firstpass_mb_stats_in = cfg -> rc_firstpass_mb_stats_in ;
 # endif oxcf -> arnr_max_frames = extra_cfg -> arnr_max_frames ;
 oxcf -> arnr_strength = extra_cfg -> arnr_strength ;
 oxcf -> tuning = extra_cfg -> tuning ;
 oxcf -> content = extra_cfg -> content ;
 oxcf -> tile_columns = extra_cfg -> tile_columns ;
 oxcf -> tile_rows = extra_cfg -> tile_rows ;
 oxcf -> error_resilient_mode = cfg -> g_error_resilient ;
 oxcf -> frame_parallel_decoding_mode = extra_cfg -> frame_parallel_decoding_mode ;
 oxcf -> aq_mode = extra_cfg -> aq_mode ;
 oxcf -> frame_periodic_boost = extra_cfg -> frame_periodic_boost ;
 oxcf -> ss_number_layers = cfg -> ss_number_layers ;
 if ( oxcf -> ss_number_layers > 1 ) {
 int i ;
 for ( i = 0 ;
 i < VPX_SS_MAX_LAYERS ;
 ++ i ) {
 oxcf -> ss_target_bitrate [ i ] = 1000 * cfg -> ss_target_bitrate [ i ] ;
 # if CONFIG_SPATIAL_SVC oxcf -> ss_play_alternate [ i ] = cfg -> ss_enable_auto_alt_ref [ i ] ;
 # endif }
 }
 else if ( oxcf -> ss_number_layers == 1 ) {
 oxcf -> ss_target_bitrate [ 0 ] = ( int ) oxcf -> target_bandwidth ;
 # if CONFIG_SPATIAL_SVC oxcf -> ss_play_alternate [ 0 ] = extra_cfg -> enable_auto_alt_ref ;
 # endif }
 oxcf -> ts_number_layers = cfg -> ts_number_layers ;
 if ( oxcf -> ts_number_layers > 1 ) {
 int i ;
 for ( i = 0 ;
 i < VPX_TS_MAX_LAYERS ;
 ++ i ) {
 oxcf -> ts_target_bitrate [ i ] = 1000 * cfg -> ts_target_bitrate [ i ] ;
 oxcf -> ts_rate_decimator [ i ] = cfg -> ts_rate_decimator [ i ] ;
 }
 }
 else if ( oxcf -> ts_number_layers == 1 ) {
 oxcf -> ts_target_bitrate [ 0 ] = ( int ) oxcf -> target_bandwidth ;
 oxcf -> ts_rate_decimator [ 0 ] = 1 ;
 }
 return VPX_CODEC_OK ;
 }


_XcursorReadImage (XcursorFile		*file,
		   XcursorFileHeader	*fileHeader,
		   int			toc)
{
    XcursorChunkHeader	chunkHeader;
    XcursorImage	head;
    XcursorImage	*image;
    int			n;
    XcursorPixel	*p;

    if (!file || !fileHeader)
        return NULL;

    if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader))
	return NULL;
    if (!_XcursorReadUInt (file, &head.width))
	return NULL;
    if (!_XcursorReadUInt (file, &head.height))
	return NULL;
    if (!_XcursorReadUInt (file, &head.xhot))
	return NULL;
    if (!_XcursorReadUInt (file, &head.yhot))
	return NULL;
    if (!_XcursorReadUInt (file, &head.delay))
	return NULL;
    /* sanity check data */
    if (head.width >= 0x10000 || head.height > 0x10000)
	return NULL;
     if (!_XcursorReadUInt (file, &head.delay))
 	return NULL;
     /* sanity check data */
    if (head.width >= 0x10000 || head.height > 0x10000)
 	return NULL;
     if (head.width == 0 || head.height == 0)
 	return NULL;
	    return NULL;
    if (chunkHeader.version < image->version)
	image->version = chunkHeader.version;
    image->size = chunkHeader.subtype;
    image->xhot = head.xhot;
    image->yhot = head.yhot;
    image->delay = head.delay;
    n = image->width * image->height;
    p = image->pixels;
    while (n--)
    {
	if (!_XcursorReadUInt (file, p))
	{
	    XcursorImageDestroy (image);
	    return NULL;
	}
	p++;
    }
    return image;
}


static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines)
{
    if (clauses.isEmpty()) {
        underlines.clear();
        return;
    }

    size_t numBoundaries = clauses.size() - 1;
    underlines.resize(numBoundaries);
    for (unsigned i = 0; i < numBoundaries; ++i) {
        underlines[i].startOffset = clauses[i];
        underlines[i].endOffset = clauses[i + 1];
        BYTE attribute = attributes[clauses[i]];
        underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED;
        underlines[i].color = Color::black;
    }
}


static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk)
{
  Image
    *image;

  /* The unknown chunk structure contains the chunk data:
     png_byte name[5];
     png_byte *data;
     png_size_t size;

     Note that libpng has already taken care of the CRC handling.

     Returns one of the following:
         return(-n);  chunk had an error
         return(0);  did not recognize
         return(n);  success
  */

  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
     "    read_user_chunk: found %c%c%c%c chunk",
       chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]);

#if defined(zxIf_SUPPORTED)
  if ((chunk->name[0]  == 122 || chunk->name[0] == 117 ) &&
      (chunk->name[1] ==   88 || chunk->name[1] == 120 ) &&
      chunk->name[2] ==   73 &&
      chunk-> name[3] == 102)
    {
      /* process uxIf or zxIf chunk */
      StringInfo *
        profile;

      PNGErrorInfo
        *error_info;

      unsigned char
        *p;

      png_byte
        *s;

      size_t
        i;

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        "     recognized uxIf|zxIf chunk");

      image=(Image *) png_get_user_chunk_ptr(ping);

      error_info=(PNGErrorInfo *) png_get_error_ptr(ping);

      profile=BlobToStringInfo((const void *) NULL,chunk->size+6);

      if (profile == (StringInfo *) NULL)
        {
          (void) ThrowMagickException(error_info->exception,GetMagickModule(),
            ResourceLimitError,"MemoryAllocationFailed","`%s'",
            image->filename);
          return(-1);
        }
      p=GetStringInfoDatum(profile);

      /* Initialize profile with "Exif\0\0" */
      *p++ ='E';
      *p++ ='x';
      *p++ ='i';
      *p++ ='f';
      *p++ ='\0';
      *p++ ='\0';

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        "     initialized uxIf|zxIf chunk");

      switch (chunk->data[0])
        {
          PNGErrorInfo
            *error_info;
          case 'E':
          case 'I':
          {
            /* Uncompressed */
            /* copy chunk->data to profile */
            s=chunk->data;
            for (i=0; i<chunk->size; i++)
              *p++ = *s++;

            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
               "     SetImageProfile with %lu bytes",
               (unsigned long) chunk->size+6);
            error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
            (void) SetImageProfile(image,"exif",profile,
              error_info->exception);
            return(1);
          }
          case '\0':
          {
            /* Zlib compressed */

            unsigned char *
              temp;

            png_uint_32 inflated_size;

            png_free(ping,profile);

            if (chunk->size < 5)
               return(-1);

            s=chunk->data;
            s++;  // skip compression byte

            inflated_size = (png_uint_32)
               (((s[0] & 0xff) << 24) | ((s[1] & 0xff) << 16) |
                ((s[2] & 0xff) <<  8) | ((s[3] & 0xff)      ));

            s+=4;

            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
               "     inflated_size = %lu bytes",inflated_size);

            /* uncompress chunk->data to temporary profile */
            inflated_size=exif_inf(ping,s,&temp,chunk->size-1,inflated_size);

            if (inflated_size <= 0)
            {
               (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  "     inflated_size = %lu bytes",inflated_size);
               return(-1);
            }
           error_info=(PNGErrorInfo *) png_get_error_ptr(ping);

           profile=BlobToStringInfo((const void *) NULL,inflated_size+6);

           if (profile == (StringInfo *) NULL)
             {
               (void) ThrowMagickException(error_info->exception,
                 GetMagickModule(),
                 ResourceLimitError,"MemoryAllocationFailed","`%s'",
                 image->filename);
               return(-1);
             }
           p=GetStringInfoDatum(profile);
           /* Initialize profile with "Exif\0\0" */
           *p++ ='E';
           *p++ ='x';
           *p++ ='i';
           *p++ ='f';
           *p++ ='\0';
           *p++ ='\0';

           for (i=0; i<inflated_size; i++)
              *p++=temp[i];

            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
               "     SetImageProfile with %lu bytes",
               (unsigned long) inflated_size+6);
            error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
            (void) SetImageProfile(image,"exif",profile,
              error_info->exception);

            png_free(ping,temp);

            return(1);
          }
       }
    }
#endif /* zxIf_SUPPORTED */

  if (chunk->name[0]  == 101 &&
      (chunk->name[1] ==  88 || chunk->name[1] == 120 ) &&
      chunk->name[2] ==   73 &&
      chunk-> name[3] == 102)
    {
      /* process eXIf or exIf chunk */

      PNGErrorInfo
        *error_info;

      StringInfo
        *profile;

      unsigned char
        *p;

      png_byte
        *s;

      size_t
        i;

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        " recognized eXIf|exIf chunk");

      image=(Image *) png_get_user_chunk_ptr(ping);

      error_info=(PNGErrorInfo *) png_get_error_ptr(ping);

      profile=BlobToStringInfo((const void *) NULL,chunk->size+6);

      if (profile == (StringInfo *) NULL)
        {
          (void) ThrowMagickException(error_info->exception,GetMagickModule(),
            ResourceLimitError,"MemoryAllocationFailed","`%s'",
            image->filename);
          return(-1);
        }
      p=GetStringInfoDatum(profile);

      /* Initialize profile with "Exif\0\0" */
      *p++ ='E';
      *p++ ='x';
      *p++ ='i';
      *p++ ='f';
      *p++ ='\0';
      *p++ ='\0';

      /* copy chunk->data to profile */
      s=chunk->data;
      for (i=0; i<chunk->size; i++)
        *p++ = *s++;

      error_info=(PNGErrorInfo *) png_get_error_ptr(ping);
      (void) SetImageProfile(image,"exif",profile,
        error_info->exception);

      return(1);
    }

  /* vpAg (deprecated, replaced by caNv) */
  if (chunk->name[0] == 118 &&
      chunk->name[1] == 112 &&
      chunk->name[2] ==  65 &&
      chunk->name[3] == 103)
    {
     /* recognized vpAg */

     if (chunk->size != 9)
       return(-1); /* Error return */

     if (chunk->data[8] != 0)
       return(0);  /* ImageMagick requires pixel units */

     image=(Image *) png_get_user_chunk_ptr(ping);

     image->page.width=(size_t) ((chunk->data[0] << 24) |
        (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);

     image->page.height=(size_t) ((chunk->data[4] << 24) |
        (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);

     return(1);
    }

  /* caNv */
  if (chunk->name[0] ==  99 &&
      chunk->name[1] ==  97 &&
      chunk->name[2] ==  78 &&
      chunk->name[3] == 118)
    {
     /* recognized caNv */

     if (chunk->size != 16)
       return(-1); /* Error return */

     image=(Image *) png_get_user_chunk_ptr(ping);

     image->page.width=(size_t) ((chunk->data[0] << 24) |
        (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]);

     image->page.height=(size_t) ((chunk->data[4] << 24) |
        (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]);

     image->page.x=(size_t) ((chunk->data[8] << 24) |
        (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]);

     image->page.y=(size_t) ((chunk->data[12] << 24) |
        (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]);

     return(1);
    }

  return(0); /* Did not recognize */
}


bool RenderBlock::isSelfCollapsingBlock() const
{
    ASSERT(!needsLayout() || (node() && node()->isElementNode() && toElement(node())->shadowPseudoId() == "-webkit-input-placeholder"));

    if (createsBlockFormattingContext())
        return false;

    if (logicalHeight() > 0
        || isTable() || borderAndPaddingLogicalHeight()
        || style()->logicalMinHeight().isPositive()
        || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
        return false;

    Length logicalHeightLength = style()->logicalHeight();
    bool hasAutoHeight = logicalHeightLength.isAuto();
    if (logicalHeightLength.isPercent() && !document().inQuirksMode()) {
        hasAutoHeight = true;
        for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
            if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
                hasAutoHeight = false;
        }
    }

    if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
        if (childrenInline())
            return !firstLineBox();

        if (m_hasOnlySelfCollapsingChildren)
            return true;
        for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
            if (child->isFloatingOrOutOfFlowPositioned())
                continue;
            if (!child->isSelfCollapsingBlock())
                return false;
        }
        return true;
    }
    return false;
}


static void curlfile_set_property(char *name, INTERNAL_FUNCTION_PARAMETERS)
{
	char *arg = NULL;
	int arg_len;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
		return;
	}
	zend_update_property_string(curl_CURLFile_class, getThis(), name, strlen(name), arg TSRMLS_CC);
}


void InspectorOverlay::paint(GraphicsContext& context)
{
    if (isEmpty())
        return;
    GraphicsContextStateSaver stateSaver(context);
    FrameView* view = overlayPage()->mainFrame()->view();
    ASSERT(!view->needsLayout());
    view->paint(&context, IntRect(0, 0, view->width(), view->height()));
}


  ps_parser_done( PS_Parser  parser )
  {
    FT_UNUSED( parser );
  }


static int dbGetIntBool(Jsi_Interp *interp, Jsi_Value* v)
{
    if (Jsi_ValueIsNumber(interp, v)) {
        Jsi_Number d;
        Jsi_ValueGetNumber(interp, v, &d);
        return (int)d;
    }
    if (Jsi_ValueIsBoolean(interp, v)) {
        bool n;
        Jsi_ValueGetBoolean(interp, v, &n);
        return n;
    }
    return 0;
}


void __fastcall TRemoteMoveDialog::DoValidate()
{
  if (!IsFileNameMask(GetFileMask()) && FMulti)
  {
    UnicodeString Message =
      FormatMultiFilesToOneConfirmation(Combo->Text, true);
    if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE) == qaCancel)
    {
      Abort();
    }
  }

  TCustomDialog::DoValidate();
}


void vhost_disable_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq)
{
	int r;

	if (vq->used_flags & VRING_USED_F_NO_NOTIFY)
		return;
	vq->used_flags |= VRING_USED_F_NO_NOTIFY;
	if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) {
		r = vhost_update_used_flags(vq);
		if (r)
			vq_err(vq, "Failed to enable notification at %p: %d\n",
			       &vq->used->flags, r);
	}
}


gnutls_ocsp_req_get_nonce(gnutls_ocsp_req_t req,
			  unsigned int *critical, gnutls_datum_t * nonce)
{
	int ret;
	gnutls_datum_t tmp;

	if (req == NULL || nonce == NULL) {
		gnutls_assert();
		return GNUTLS_E_INVALID_REQUEST;
	}

	ret = _gnutls_get_extension(req->req, "tbsRequest.requestExtensions",
			    GNUTLS_OCSP_NONCE, 0, &tmp, critical);
	if (ret != GNUTLS_E_SUCCESS) {
		gnutls_assert();
		return ret;
	}

	ret =
	    _gnutls_x509_decode_string(ASN1_ETYPE_OCTET_STRING, tmp.data,
				       (size_t) tmp.size, nonce, 0);
	if (ret < 0) {
		gnutls_assert();
		gnutls_free(tmp.data);
		return ret;
	}

	gnutls_free(tmp.data);

	return GNUTLS_E_SUCCESS;
}


DownloadItemImplDelegate::DownloadItemImplDelegate()
    : count_(0) {}


void DatabaseMessageFilter::OnDatabaseSizeChanged(
    const string16& origin_identifier,
    const string16& database_name,
    int64 database_size) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  if (database_connections_.IsOriginUsed(origin_identifier)) {
    Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name,
                                    database_size));
  }
}


 static int kvm_iommu_unmap_memslots(struct kvm *kvm)
 {
 	int idx;
	struct kvm_memslots *slots;
	struct kvm_memory_slot *memslot;

	idx = srcu_read_lock(&kvm->srcu);
 	slots = kvm_memslots(kvm);

 	kvm_for_each_memslot(memslot, slots)
		kvm_iommu_unmap_pages(kvm, memslot);

 	srcu_read_unlock(&kvm->srcu, idx);

	return 0;
}


base::string16 BrowserView::GetAccessibleWindowTitle() const {
  return GetAccessibleWindowTitleForChannelAndProfile(chrome::GetChannel(),
                                                      browser_->profile());
}


bool CPlayListASX::LoadData(std::istream& stream)
{
  CLog::Log(LOGINFO, "Parsing ASX");

  if(stream.peek() == '[')
  {
    return LoadAsxIniInfo(stream);
  }
  else
  {
    CXBMCTinyXML xmlDoc;
    stream >> xmlDoc;

    if (xmlDoc.Error())
    {
      CLog::Log(LOGERROR, "Unable to parse ASX info Error: {}", xmlDoc.ErrorDesc());
      return false;
    }

    TiXmlElement *pRootElement = xmlDoc.RootElement();

    // lowercase every element
    TiXmlNode *pNode = pRootElement;
    TiXmlNode *pChild = NULL;
    std::string value;
    value = pNode->Value();
    StringUtils::ToLower(value);
    pNode->SetValue(value);
    while(pNode)
    {
      pChild = pNode->IterateChildren(pChild);
      if(pChild)
      {
        if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT)
        {
          value = pChild->Value();
          StringUtils::ToLower(value);
          pChild->SetValue(value);

          TiXmlAttribute* pAttr = pChild->ToElement()->FirstAttribute();
          while(pAttr)
          {
            value = pAttr->Name();
            StringUtils::ToLower(value);
            pAttr->SetName(value);
            pAttr = pAttr->Next();
          }
        }

        pNode = pChild;
        pChild = NULL;
        continue;
      }

      pChild = pNode;
      pNode = pNode->Parent();
    }
    std::string roottitle;
    TiXmlElement *pElement = pRootElement->FirstChildElement();
    while (pElement)
    {
      value = pElement->Value();
      if (value == "title" && !pElement->NoChildren())
      {
        roottitle = pElement->FirstChild()->ValueStr();
      }
      else if (value == "entry")
      {
        std::string title(roottitle);

        TiXmlElement *pRef = pElement->FirstChildElement("ref");
        TiXmlElement *pTitle = pElement->FirstChildElement("title");

        if(pTitle && !pTitle->NoChildren())
          title = pTitle->FirstChild()->ValueStr();

        while (pRef)
        { // multiple references may appear for one entry
          // duration may exist on this level too
          value = XMLUtils::GetAttribute(pRef, "href");
          if (!value.empty())
          {
            if(title.empty())
              title = value;

            CLog::Log(LOGINFO, "Adding element {}, {}", title, value);
            CFileItemPtr newItem(new CFileItem(title));
            newItem->SetPath(value);
            Add(newItem);
          }
          pRef = pRef->NextSiblingElement("ref");
        }
      }
      else if (value == "entryref")
      {
        value = XMLUtils::GetAttribute(pElement, "href");
        if (!value.empty())
        { // found an entryref, let's try loading that url
          std::unique_ptr<CPlayList> playlist(CPlayListFactory::Create(value));
          if (nullptr != playlist)
            if (playlist->Load(value))
              Add(*playlist);
        }
      }
      pElement = pElement->NextSiblingElement();
    }
  }

  return true;
}


void DevToolsSession::SetBrowserOnly(bool browser_only) {
  browser_only_ = browser_only;
  dispatcher_->setFallThroughForNotFound(!browser_only);
}


ofputil_decode_ofp13_table_stats(struct ofpbuf *msg,
                                 struct ofputil_table_stats *stats,
                                 struct ofputil_table_features *features)
{
    struct ofp13_table_stats *ots;

    ots = ofpbuf_try_pull(msg, sizeof *ots);
    if (!ots) {
        return OFPERR_OFPBRC_BAD_LEN;
    }

    features->table_id = ots->table_id;

    stats->table_id = ots->table_id;
    stats->active_count = ntohl(ots->active_count);
    stats->lookup_count = ntohll(ots->lookup_count);
    stats->matched_count = ntohll(ots->matched_count);

    return 0;
}


static int cypress_tiocmget(struct tty_struct *tty)
{
	struct usb_serial_port *port = tty->driver_data;
	struct cypress_private *priv = usb_get_serial_port_data(port);
	__u8 status, control;
	unsigned int result = 0;
	unsigned long flags;

	spin_lock_irqsave(&priv->lock, flags);
	control = priv->line_control;
	status = priv->current_status;
	spin_unlock_irqrestore(&priv->lock, flags);

	result = ((control & CONTROL_DTR)        ? TIOCM_DTR : 0)
		| ((control & CONTROL_RTS)       ? TIOCM_RTS : 0)
		| ((status & UART_CTS)        ? TIOCM_CTS : 0)
		| ((status & UART_DSR)        ? TIOCM_DSR : 0)
		| ((status & UART_RI)         ? TIOCM_RI  : 0)
		| ((status & UART_CD)         ? TIOCM_CD  : 0);

	dev_dbg(&port->dev, "%s - result = %x\n", __func__, result);

	return result;
}


void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
                                                const std::string& extension_id,
                                                const URLPatternSet& new_hosts,
                                                bool update_origin_whitelist,
                                                int tab_id) {
  const Extension* extension =
      RendererExtensionRegistry::Get()->GetByID(extension_id);
  if (!extension)
    return;

  URLPatternSet old_effective =
      extension->permissions_data()->GetEffectiveHostPermissions();
  extension->permissions_data()->UpdateTabSpecificPermissions(
      tab_id,
      extensions::PermissionSet(extensions::APIPermissionSet(),
                                extensions::ManifestPermissionSet(), new_hosts,
                                extensions::URLPatternSet()));

  if (update_origin_whitelist) {
    UpdateOriginPermissions(
        extension->url(),
        old_effective,
        extension->permissions_data()->GetEffectiveHostPermissions());
  }
}


get_array_element_start(void *state, bool isnull)
{
	GetState   *_state = (GetState *) state;
	bool		get_next = false;
	int			lex_level = _state->lex->lex_level;

	/* Update array element counter */
	if (lex_level <= _state->npath)
		_state->array_cur_index[lex_level - 1]++;

	if (lex_level <= _state->npath &&
		_state->pathok[lex_level - 1] &&
		_state->path_indexes != NULL &&
		_state->array_cur_index[lex_level - 1] == _state->path_indexes[lex_level - 1])
	{
		if (lex_level < _state->npath)
		{
			/* if not at end of path just mark path ok */
			_state->pathok[lex_level] = true;
		}
		else
		{
			/* end of path, so we want this value */
			get_next = true;
		}
	}

	/* same logic as for objects */
	if (get_next)
	{
		_state->tresult = NULL;
		_state->result_start = NULL;

		if (_state->normalize_results &&
			_state->lex->token_type == JSON_TOKEN_STRING)
		{
			_state->next_scalar = true;
		}
		else
		{
			_state->result_start = _state->lex->token_start;
		}
	}
}


  absl::Status CheckOptionsSupport(const TfLiteStridedSliceParams* tf_options) {
    if (tf_options->ellipsis_mask) {
      return absl::UnimplementedError("Slice does not support ellipsis_mask.");
    }
    if (tf_options->new_axis_mask) {
      return absl::UnimplementedError("Slice does not support new_axis_mask.");
    }
    if (tf_options->shrink_axis_mask) {
      return absl::UnimplementedError(
          "Slice does not support shrink_axis_mask parameter. ");
    }
    return absl::OkStatus();
  }


static ssize_t tun_get_user(struct tun_struct *tun,
			    const struct iovec *iv, size_t count,
			    int noblock)
{
	struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
	struct sk_buff *skb;
	size_t len = count, align = NET_SKB_PAD;
	struct virtio_net_hdr gso = { 0 };
	int offset = 0;

	if (!(tun->flags & TUN_NO_PI)) {
		if ((len -= sizeof(pi)) > count)
			return -EINVAL;

		if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi)))
			return -EFAULT;
		offset += sizeof(pi);
	}

	if (tun->flags & TUN_VNET_HDR) {
		if ((len -= tun->vnet_hdr_sz) > count)
			return -EINVAL;

		if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso)))
			return -EFAULT;

		if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
		    gso.csum_start + gso.csum_offset + 2 > gso.hdr_len)
			gso.hdr_len = gso.csum_start + gso.csum_offset + 2;

		if (gso.hdr_len > len)
			return -EINVAL;
		offset += tun->vnet_hdr_sz;
	}

	if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) {
		align += NET_IP_ALIGN;
		if (unlikely(len < ETH_HLEN ||
			     (gso.hdr_len && gso.hdr_len < ETH_HLEN)))
			return -EINVAL;
	}

	skb = tun_alloc_skb(tun, align, len, gso.hdr_len, noblock);
	if (IS_ERR(skb)) {
		if (PTR_ERR(skb) != -EAGAIN)
			tun->dev->stats.rx_dropped++;
		return PTR_ERR(skb);
	}

	if (skb_copy_datagram_from_iovec(skb, 0, iv, offset, len)) {
		tun->dev->stats.rx_dropped++;
		kfree_skb(skb);
		return -EFAULT;
	}

	if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
		if (!skb_partial_csum_set(skb, gso.csum_start,
					  gso.csum_offset)) {
			tun->dev->stats.rx_frame_errors++;
			kfree_skb(skb);
			return -EINVAL;
		}
	}

	switch (tun->flags & TUN_TYPE_MASK) {
	case TUN_TUN_DEV:
		if (tun->flags & TUN_NO_PI) {
			switch (skb->data[0] & 0xf0) {
			case 0x40:
				pi.proto = htons(ETH_P_IP);
				break;
			case 0x60:
				pi.proto = htons(ETH_P_IPV6);
				break;
			default:
				tun->dev->stats.rx_dropped++;
				kfree_skb(skb);
				return -EINVAL;
			}
		}

		skb_reset_mac_header(skb);
		skb->protocol = pi.proto;
		skb->dev = tun->dev;
		break;
	case TUN_TAP_DEV:
		skb->protocol = eth_type_trans(skb, tun->dev);
		break;
	}

	if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
		pr_debug("GSO!\n");
		switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
		case VIRTIO_NET_HDR_GSO_TCPV4:
			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
			break;
		case VIRTIO_NET_HDR_GSO_TCPV6:
			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
			break;
		case VIRTIO_NET_HDR_GSO_UDP:
			skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
			break;
		default:
			tun->dev->stats.rx_frame_errors++;
			kfree_skb(skb);
			return -EINVAL;
		}

		if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN)
			skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;

		skb_shinfo(skb)->gso_size = gso.gso_size;
		if (skb_shinfo(skb)->gso_size == 0) {
			tun->dev->stats.rx_frame_errors++;
			kfree_skb(skb);
			return -EINVAL;
		}

		/* Header must be checked, and gso_segs computed. */
		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
		skb_shinfo(skb)->gso_segs = 0;
	}

	netif_rx_ni(skb);

	tun->dev->stats.rx_packets++;
	tun->dev->stats.rx_bytes += len;

	return count;
}


static void openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) /* {{{ */
{
	add_next_index_string((zval*)arg, (char*)name->name, 1);
}
/* }}} */