base::string16 GetExpectedAppId(const base::CommandLine& command_line,
                                bool is_per_user_install) {
  base::FilePath user_data_dir;
  if (command_line.HasSwitch(switches::kUserDataDir))
    user_data_dir = command_line.GetSwitchValuePath(switches::kUserDataDir);
  else
    chrome::GetDefaultUserDataDirectory(&user_data_dir);
  policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
  DCHECK(!user_data_dir.empty());

  base::FilePath profile_subdir;
  if (command_line.HasSwitch(switches::kProfileDirectory)) {
    profile_subdir =
        command_line.GetSwitchValuePath(switches::kProfileDirectory);
  } else {
    profile_subdir =
        base::FilePath(base::ASCIIToUTF16(chrome::kInitialProfile));
  }
  DCHECK(!profile_subdir.empty());

  base::FilePath profile_path = user_data_dir.Append(profile_subdir);
  base::string16 app_name;
  if (command_line.HasSwitch(switches::kApp)) {
    app_name = base::UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
        GURL(command_line.GetSwitchValueASCII(switches::kApp))));
  } else if (command_line.HasSwitch(switches::kAppId)) {
    app_name = base::UTF8ToUTF16(web_app::GenerateApplicationNameFromAppId(
        command_line.GetSwitchValueASCII(switches::kAppId)));
  } else if (command_line.HasSwitch(switches::kShowAppList)) {
    app_name = GetAppListAppName();
  } else {
    app_name = ShellUtil::GetBrowserModelId(is_per_user_install);
  }
  DCHECK(!app_name.empty());

  return win::GetAppModelIdForProfile(app_name, profile_path);
}


static void pit_load_count(struct kvm *kvm, int channel, u32 val)
{
	struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;

	WARN_ON(!mutex_is_locked(&ps->lock));

	pr_debug("load_count val is %d, channel is %d\n", val, channel);

	/*
	 * The largest possible initial count is 0; this is equivalent
	 * to 216 for binary counting and 104 for BCD counting.
	 */
	if (val == 0)
		val = 0x10000;

	ps->channels[channel].count = val;

	if (channel != 0) {
		ps->channels[channel].count_load_time = ktime_get();
		return;
	}

	/* Two types of timer
	 * mode 1 is one shot, mode 2 is period, otherwise del timer */
	switch (ps->channels[0].mode) {
	case 0:
	case 1:
        /* FIXME: enhance mode 4 precision */
	case 4:
		create_pit_timer(kvm, val, 0);
		break;
	case 2:
	case 3:
		create_pit_timer(kvm, val, 1);
		break;
	default:
		destroy_pit_timer(kvm->arch.vpit);
	}
}


static int lexcount(struct cstate *g)
{
	g->yychar = *g->source++;

	g->yymin = dec(g, g->yychar);
	g->yychar = *g->source++;
	while (g->yychar != ',' && g->yychar != '}') {
		g->yymin = g->yymin * 10 + dec(g, g->yychar);
		g->yychar = *g->source++;
		if (g->yymin >= REPINF)
			die(g, "numeric overflow");
	}

	if (g->yychar == ',') {
		g->yychar = *g->source++;
		if (g->yychar == '}') {
			g->yymax = REPINF;
		} else {
			g->yymax = dec(g, g->yychar);
			g->yychar = *g->source++;
			while (g->yychar != '}') {
				g->yymax = g->yymax * 10 + dec(g, g->yychar);
				g->yychar = *g->source++;
				if (g->yymax >= REPINF)
					die(g, "numeric overflow");
			}
		}
	} else {
		g->yymax = g->yymin;
	}

	return L_COUNT;
}


bool DesktopWindowTreeHostX11::IsVisibleOnAllWorkspaces() const {
  return GetWorkspace() == base::NumberToString(kAllDesktops);
}


static inline void ipmi_si_set_not_busy(struct timespec64 *ts)
{
	ts->tv_nsec = -1;
}


void FrameLoaderClient::dispatchDidCancelAuthenticationChallenge(WebCore::DocumentLoader*, unsigned long  identifier, const AuthenticationChallenge&)
{
    notImplemented();
}


PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf)
{
    const HashSet<Page*>& pages = page->group().pages();

    HashSet<Page*>::const_iterator end = pages.end();
    for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) {
        Page* otherPage = *it;
        if ((deferSelf || otherPage != page)) {
             if (!otherPage->defersLoading()) {
                 m_deferredFrames.append(otherPage->mainFrame());

                // Ensure that we notify the client if the initial empty document is accessed before showing anything
                // modal, to prevent spoofs while the modal window or sheet is visible.
                otherPage->mainFrame()->loader()->notifyIfInitialDocumentAccessed();

                 for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext())
                    frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading);
            }
        }
    }

    size_t count = m_deferredFrames.size();
    for (size_t i = 0; i < count; ++i)
        if (Page* page = m_deferredFrames[i]->page())
            page->setDefersLoading(true);
}


static void TIFFTagExtender(TIFF *tiff)
{
  static const TIFFFieldInfo
    TIFFExtensions[] =
    {
      { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
        (char *) "PhotoshopLayerData" },
      { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
        (char *) "Microscope" }
    };

  TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
    sizeof(*TIFFExtensions));
  if (tag_extender != (TIFFExtendProc) NULL)
    (*tag_extender)(tiff);
  TIFFIgnoreTags(tiff);
}


static void json_delete_integer(json_integer_t *integer)
{
    jsonp_free(integer);
}


circle_contained(PG_FUNCTION_ARGS)
{
	CIRCLE	   *circle1 = PG_GETARG_CIRCLE_P(0);
	CIRCLE	   *circle2 = PG_GETARG_CIRCLE_P(1);

	PG_RETURN_BOOL(FPle((point_dt(&circle1->center, &circle2->center) + circle1->radius), circle2->radius));
}


gboolean
mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass)
{
	MonoObject *res, *exc;
	void *params [1];
	static MonoClass *System_Reflection_Emit_TypeBuilder = NULL;
	static MonoMethod *method = NULL;

	if (!System_Reflection_Emit_TypeBuilder) {
		System_Reflection_Emit_TypeBuilder = mono_class_from_name (mono_defaults.corlib, "System.Reflection.Emit", "TypeBuilder");
		g_assert (System_Reflection_Emit_TypeBuilder);
	}
	if (method == NULL) {
		method = mono_class_get_method_from_name (System_Reflection_Emit_TypeBuilder, "IsAssignableTo", 1);
		g_assert (method);
	}

	/*
	 * The result of mono_type_get_object () might be a System.MonoType but we
	 * need a TypeBuilder so use mono_class_get_ref_info (klass).
	 */
	g_assert (mono_class_get_ref_info (klass));
	g_assert (!strcmp (((MonoObject*)(mono_class_get_ref_info (klass)))->vtable->klass->name, "TypeBuilder"));

	params [0] = mono_type_get_object (mono_domain_get (), &oklass->byval_arg);

	res = mono_runtime_invoke (method, (MonoObject*)(mono_class_get_ref_info (klass)), params, &exc);
	if (exc)
		return FALSE;
	else
		return *(MonoBoolean*)mono_object_unbox (res);


postmaster_forkexec(int argc, char *argv[])
{
	Port		port;

	/* This entry point passes dummy values for the Port variables */
	memset(&port, 0, sizeof(port));
	return internal_forkexec(argc, argv, &port);
}


static void dsputil_init_mmx2(DSPContext *c, AVCodecContext *avctx,

                              int mm_flags)

{

    const int bit_depth      = avctx->bits_per_raw_sample;

    const int high_bit_depth = bit_depth > 8;

    c->prefetch = prefetch_mmx2;

    if (!high_bit_depth) {

        c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2;

        c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2;

        c->avg_pixels_tab[0][0] = avg_pixels16_mmx2;

        c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2;

        c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2;

        c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2;

        c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2;

        c->avg_pixels_tab[1][0] = avg_pixels8_mmx2;

        c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2;

        c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2;

    }

    if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {

        if (!high_bit_depth) {

            c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2;

            c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2;

            c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2;

            c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2;

            c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2;

            c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2;

        }

        if (CONFIG_VP3_DECODER && HAVE_YASM) {

            c->vp3_v_loop_filter = ff_vp3_v_loop_filter_mmx2;

            c->vp3_h_loop_filter = ff_vp3_h_loop_filter_mmx2;

        }

    }

    if (CONFIG_VP3_DECODER && HAVE_YASM)

        c->vp3_idct_dc_add = ff_vp3_idct_dc_add_mmx2;

    if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 ||

                               avctx->codec_id == CODEC_ID_THEORA)) {

        c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmx2;

        c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmx2;

    }

    if (CONFIG_H264QPEL) {

        SET_QPEL_FUNCS(put_qpel,        0, 16, mmx2, );

        SET_QPEL_FUNCS(put_qpel,        1,  8, mmx2, );

        SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2, );

        SET_QPEL_FUNCS(put_no_rnd_qpel, 1,  8, mmx2, );

        SET_QPEL_FUNCS(avg_qpel,        0, 16, mmx2, );

        SET_QPEL_FUNCS(avg_qpel,        1,  8, mmx2, );

        if (!high_bit_depth) {

            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2, );

            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, mmx2, );

            SET_QPEL_FUNCS(put_h264_qpel, 2,  4, mmx2, );

            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2, );

            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, mmx2, );

            SET_QPEL_FUNCS(avg_h264_qpel, 2,  4, mmx2, );

        } else if (bit_depth == 10) {

#if HAVE_YASM

#if !ARCH_X86_64

            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 10_mmxext, ff_);

            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 10_mmxext, ff_);

            SET_QPEL_FUNCS(put_h264_qpel, 1,  8, 10_mmxext, ff_);

            SET_QPEL_FUNCS(avg_h264_qpel, 1,  8, 10_mmxext, ff_);

#endif

            SET_QPEL_FUNCS(put_h264_qpel, 2, 4,  10_mmxext, ff_);

            SET_QPEL_FUNCS(avg_h264_qpel, 2, 4,  10_mmxext, ff_);

#endif

        }

        SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2, );

        SET_QPEL_FUNCS(put_2tap_qpel, 1,  8, mmx2, );

        SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2, );

        SET_QPEL_FUNCS(avg_2tap_qpel, 1,  8, mmx2, );

    }

#if HAVE_YASM

    if (!high_bit_depth && CONFIG_H264CHROMA) {

        c->avg_h264_chroma_pixels_tab[0] = ff_avg_h264_chroma_mc8_mmx2_rnd;

        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_mmx2;

        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_mmx2;

        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_mmx2;

    }

    if (bit_depth == 10 && CONFIG_H264CHROMA) {

        c->put_h264_chroma_pixels_tab[2] = ff_put_h264_chroma_mc2_10_mmxext;

        c->avg_h264_chroma_pixels_tab[2] = ff_avg_h264_chroma_mc2_10_mmxext;

        c->put_h264_chroma_pixels_tab[1] = ff_put_h264_chroma_mc4_10_mmxext;

        c->avg_h264_chroma_pixels_tab[1] = ff_avg_h264_chroma_mc4_10_mmxext;

    }

    c->add_hfyu_median_prediction   = ff_add_hfyu_median_prediction_mmx2;

    c->scalarproduct_int16          = ff_scalarproduct_int16_mmx2;

    c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2;

    if (avctx->flags & CODEC_FLAG_BITEXACT) {

        c->apply_window_int16 = ff_apply_window_int16_mmxext_ba;

    } else {

        c->apply_window_int16 = ff_apply_window_int16_mmxext;

    }

#endif

}


static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
					   struct userfaultfd_wake_range *range)
{
	unsigned seq;
	bool need_wakeup;

	/*
	 * To be sure waitqueue_active() is not reordered by the CPU
	 * before the pagetable update, use an explicit SMP memory
	 * barrier here. PT lock release or up_read(mmap_sem) still
	 * have release semantics that can allow the
	 * waitqueue_active() to be reordered before the pte update.
	 */
	smp_mb();

	/*
	 * Use waitqueue_active because it's very frequent to
	 * change the address space atomically even if there are no
	 * userfaults yet. So we take the spinlock only when we're
	 * sure we've userfaults to wake.
	 */
	do {
		seq = read_seqcount_begin(&ctx->refile_seq);
		need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
			waitqueue_active(&ctx->fault_wqh);
		cond_resched();
	} while (read_seqcount_retry(&ctx->refile_seq, seq));
	if (need_wakeup)
		__wake_userfault(ctx, range);
}


void ContextState::UpdateUnpackParameters() const {
  if (!feature_info_->IsES3Capable())
    return;
  if (bound_pixel_unpack_buffer.get()) {
    api()->glPixelStoreiFn(GL_UNPACK_ROW_LENGTH, unpack_row_length);
    api()->glPixelStoreiFn(GL_UNPACK_IMAGE_HEIGHT, unpack_image_height);
  } else {
    api()->glPixelStoreiFn(GL_UNPACK_ROW_LENGTH, 0);
    api()->glPixelStoreiFn(GL_UNPACK_IMAGE_HEIGHT, 0);
  }
}


static v8::Handle<v8::Value> methodWithCallbackArgCallback(const v8::Arguments& args)
 {
     INC_STATS("DOM.TestObj.methodWithCallbackArg");
     if (args.Length() < 1)
        return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
     TestObj* imp = V8TestObj::toNative(args.Holder());
     if (args.Length() <= 0 || !args[0]->IsFunction())
         return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
    RefPtr<TestCallback> callback = V8TestCallback::create(args[0], getScriptExecutionContext());
    imp->methodWithCallbackArg(callback);
    return v8::Handle<v8::Value>();
}


bool pcre_literal_data::matches(const StringData* subject,
                                int pos,
                                int* offsets) const {
  assertx(isLiteral());
  assertx(pos >= 0);

  // Subject must be at least as long as the literal pattern
  // for a match to occur.
  if (subject->size() < literal_str->length() + pos) {
    return false;
  }

  size_t literal_strlen = literal_str->length();
  auto const subject_c = subject->data();
  auto const literal_c = literal_str->c_str();
  if (match_start) {
    // Make sure an exact match has the right length.
    if (pos || (match_end && subject->size() != literal_strlen)) {
      return false;
    }
    // If only matching the start (^), compare the strings
    // for the length of the literal pattern.
    if (case_insensitive ?
        bstrcaseeq(subject_c, literal_c, literal_strlen) :
        memcmp(subject_c, literal_c, literal_strlen) == 0) {
      offsets[0] = 0;
      offsets[1] = literal_strlen * sizeof(char);
      return true;
    }
  } else if (match_end) {
    // Compare the literal pattern against the tail end of the subject.
    auto const subject_tail = subject_c + (subject->size() - literal_strlen);
    if (case_insensitive ?
        bstrcaseeq(subject_tail, literal_c, literal_strlen) :
        memcmp(subject_tail, literal_c, literal_strlen) == 0) {
      offsets[0] = (subject->size() - literal_strlen) * sizeof(char);
      offsets[1] = subject->size() * sizeof(char);
      return true;
    }
  } else {
    if (!literal_strlen) {
      offsets[0] = offsets[1] = pos;
      return true;
    }
    // Check if the literal pattern occurs as a substring of the subject.
    auto const subject_str = StrNR(subject);
    auto const find_response = subject_str.asString().find(
      *literal_str, pos, !case_insensitive);
    if (find_response >= 0) {
      offsets[0] = find_response * sizeof(char);
      offsets[1] = offsets[0] + literal_strlen * sizeof(char);
      return true;
    }
  }
  return false;
}


int addrconf_sysctl_forward(struct ctl_table *ctl, int write,
			   void __user *buffer, size_t *lenp, loff_t *ppos)
{
	int *valp = ctl->data;
	int val = *valp;
	loff_t pos = *ppos;
	struct ctl_table lctl;
	int ret;

	/*
	 * ctl->data points to idev->cnf.forwarding, we should
	 * not modify it until we get the rtnl lock.
	 */
	lctl = *ctl;
	lctl.data = &val;

	ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);

	if (write)
		ret = addrconf_fixup_forwarding(ctl, valp, val);
	if (ret)
		*ppos = pos;
	return ret;
}


Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, Node* pastEnd, NodeTraversalMode traversalMode)
{
    const bool shouldEmit = traversalMode == EmitString;
    Vector<Node*> ancestorsToClose;
    Node* next;
    Node* lastClosed = 0;
    for (Node* n = startNode; n != pastEnd; n = next) {
        ASSERT(n);
        if (!n)
            break;

        next = n->traverseNextNode();
        bool openedTag = false;

        if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
            continue;

        if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) {
            next = n->traverseNextSibling();
            if (pastEnd && pastEnd->isDescendantOf(n))
                next = pastEnd;
        } else {
            if (shouldEmit)
                appendStartTag(n);

            if (!n->childNodeCount()) {
                if (shouldEmit)
                    appendEndTag(n);
                lastClosed = n;
            } else {
                openedTag = true;
                ancestorsToClose.append(n);
            }
        }

        if (!openedTag && (!n->nextSibling() || next == pastEnd)) {
            while (!ancestorsToClose.isEmpty()) {
                Node* ancestor = ancestorsToClose.last();
                if (next != pastEnd && next->isDescendantOf(ancestor))
                    break;
                if (shouldEmit)
                    appendEndTag(ancestor);
                lastClosed = ancestor;
                ancestorsToClose.removeLast();
            }

            ContainerNode* nextParent = next ? next->parentNode() : 0;
            if (next != pastEnd && n != nextParent) {
                Node* lastAncestorClosedOrSelf = n->isDescendantOf(lastClosed) ? lastClosed : n;
                for (ContainerNode* parent = lastAncestorClosedOrSelf->parentNode(); parent && parent != nextParent; parent = parent->parentNode()) {
                    if (!parent->renderer())
                        continue;
                    ASSERT(startNode->isDescendantOf(parent));
                    if (shouldEmit)
                        wrapWithNode(parent);
                    lastClosed = parent;
                }
            }
        }
    }

    return lastClosed;
}


static void qemu_tcg_wait_io_event ( void ) {
 CPUArchState * env ;
 while ( all_cpu_threads_idle ( ) ) {
 qemu_clock_warp ( vm_clock ) ;
 qemu_cond_wait ( tcg_halt_cond , & qemu_global_mutex ) ;
 }
 while ( iothread_requesting_mutex ) {
 qemu_cond_wait ( & qemu_io_proceeded_cond , & qemu_global_mutex ) ;
 }
 for ( env = first_cpu ;
 env != NULL ;
 env = env -> next_cpu ) {
 qemu_wait_io_event_common ( ENV_GET_CPU ( env ) ) ;
 }
 }


static void tg3_tx_timeout(struct net_device *dev)
{
	struct tg3 *tp = netdev_priv(dev);

	if (netif_msg_tx_err(tp)) {
		netdev_err(dev, "transmit timed out, resetting\n");
		tg3_dump_state(tp);
	}

	tg3_reset_task_schedule(tp);
}


double ewk_view_setting_minimum_timer_interval_get(const Evas_Object* ewkView)
{
    EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData, false);
    EWK_VIEW_PRIV_GET_OR_RETURN(smartData, priv, false);
    return priv->settings.domTimerInterval;
}


static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
	switch (cmd) {
	case SC_CARDCTL_TCOS_SETPERM:
		return tcos_setperm(card, !!ptr);
	case SC_CARDCTL_GET_SERIALNR:
		return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
	}
	return SC_ERROR_NOT_SUPPORTED;
}


njs_generate_assignment_end(njs_vm_t *vm, njs_generator_t *generator,
    njs_parser_node_t *node)
{
    njs_int_t              ret;
    njs_parser_node_t      *lvalue, *expr, *object, *property;
    njs_vmcode_prop_set_t  *prop_set;

    lvalue = node->left;
    expr = node->right;

    object = lvalue->left;
    property = lvalue->right;

    switch (lvalue->token_type) {
    case NJS_TOKEN_PROPERTY_INIT:
        njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
                          NJS_VMCODE_PROPERTY_INIT, 3, expr);
        break;

    case NJS_TOKEN_PROTO_INIT:
        njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
                          NJS_VMCODE_PROTO_INIT, 3, expr);
        break;

    default:
        /* NJS_VMCODE_PROPERTY_SET */
        njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
                          NJS_VMCODE_PROPERTY_SET, 3, expr);
    }

    prop_set->value = expr->index;
    prop_set->object = object->index;
    prop_set->property = property->index;

    node->index = expr->index;
    node->temporary = expr->temporary;

    ret = njs_generate_children_indexes_release(vm, generator, lvalue);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    return njs_generator_stack_pop(vm, generator, NULL);
}


ctrl_body_print(netdissect_options *ndo,
                uint16_t fc, const u_char *p)
{
	ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc))));
	switch (FC_SUBTYPE(fc)) {
	case CTRL_CONTROL_WRAPPER:
		/* XXX - requires special handling */
		break;
	case CTRL_BAR:
		if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
			    etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
			    etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
			    EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
			    EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
		break;
	case CTRL_BA:
		if (!ND_TTEST2(*p, CTRL_BA_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " RA:%s ",
			    etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
		break;
	case CTRL_PS_POLL:
		if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN))
			return 0;
		ND_PRINT((ndo, " AID(%x)",
		    EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid))));
		break;
	case CTRL_RTS:
		if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " TA:%s ",
			    etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
		break;
	case CTRL_CTS:
		if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " RA:%s ",
			    etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
		break;
	case CTRL_ACK:
		if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " RA:%s ",
			    etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
		break;
	case CTRL_CF_END:
		if (!ND_TTEST2(*p, CTRL_END_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " RA:%s ",
			    etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra)));
		break;
	case CTRL_END_ACK:
		if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN))
			return 0;
		if (!ndo->ndo_eflag)
			ND_PRINT((ndo, " RA:%s ",
			    etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra)));
		break;
	}
	return 1;
}


void ChildProcessSecurityPolicyImpl::GrantScheme(int child_id,
                                                 const std::string& scheme) {
  base::AutoLock lock(lock_);

  SecurityStateMap::iterator state = security_state_.find(child_id);
  if (state == security_state_.end())
    return;

  state->second->GrantScheme(scheme);
}


xfs_buf_unlock(
	struct xfs_buf		*bp)
{
	XB_CLEAR_OWNER(bp);
	up(&bp->b_sema);

	trace_xfs_buf_unlock(bp, _RET_IP_);
}


skipObject(ParseCtx *parseCtx) {
    int end = parseCtx->tokenArray[parseCtx->index].end;
    do {
        parseCtx->index++;
    } while(parseCtx->index < parseCtx->tokenCount &&
            parseCtx->tokenArray[parseCtx->index].start < end);
}


HHVM_METHOD(Memcache, get, const Variant& key, VRefParam /*flags*/ /*= null*/) {
  auto data = Native::data<MemcacheData>(this_);

  if (!hasAvailableServers(data)) {
    return false;
  }

  if (key.isArray()) {
    std::vector<const char *> real_keys;
    std::vector<size_t> key_len;
    Array keyArr = key.toArray();

    real_keys.reserve(keyArr.size());
    key_len.reserve(keyArr.size());

    for (ArrayIter iter(keyArr); iter; ++iter) {
      auto key = iter.second().toString();
      String serializedKey = memcache_prepare_key(key);
      char *k = new char[serializedKey.length()+1];
      memcpy(k, serializedKey.c_str(), serializedKey.length() + 1);
      real_keys.push_back(k);
      key_len.push_back(serializedKey.length());
    }

    if (!real_keys.empty()) {
      const char *payload = nullptr;
      size_t payload_len = 0;
      uint32_t flags = 0;
      const char *res_key = nullptr;
      size_t res_key_len = 0;

      memcached_result_st result;

      memcached_return_t ret = memcached_mget(&data->m_memcache, &real_keys[0],
                                              &key_len[0], real_keys.size());
      memcached_result_create(&data->m_memcache, &result);

      // To mimic PHP5 should return empty array at failure.
      Array return_val = Array::Create();

      while ((memcached_fetch_result(&data->m_memcache, &result, &ret))
             != nullptr) {
        if (ret != MEMCACHED_SUCCESS) {
          // should probably notify about errors
          continue;
        }

        payload     = memcached_result_value(&result);
        payload_len = memcached_result_length(&result);
        flags       = memcached_result_flags(&result);
        res_key     = memcached_result_key_value(&result);
        res_key_len = memcached_result_key_length(&result);

        return_val.set(String(res_key, res_key_len, CopyString),
                       memcache_fetch_from_storage(payload,
                                                   payload_len, flags));
      }
      memcached_result_free(&result);
      for ( size_t i = 0 ; i < real_keys.size() ; i++ ) {
        delete [] real_keys[i];
      }

      return return_val;
    }
  } else {
    char *payload = nullptr;
    size_t payload_len = 0;
    uint32_t flags = 0;

    memcached_return_t ret;
    String serializedKey = memcache_prepare_key(key.toString());

    if (serializedKey.length() == 0) {
      return false;
    }

    payload = memcached_get(&data->m_memcache, serializedKey.c_str(),
                            serializedKey.length(), &payload_len, &flags, &ret);

    /* This is for historical reasons from libmemcached*/
    if (ret == MEMCACHED_END) {
      ret = MEMCACHED_NOTFOUND;
    }

    if (ret == MEMCACHED_NOTFOUND) {
      return false;
    }

    if (ret != MEMCACHED_SUCCESS) {
      return false;
    }

    Variant retval = memcache_fetch_from_storage(payload, payload_len, flags);
    free(payload);

    return retval;
  }
  return false;
}


  AccessType GetExtensionAccess(const Extension* extension,
                                const GURL& url,
                                 int tab_id) {
     bool allowed_script = IsAllowedScript(extension, url, tab_id);
     bool allowed_capture = extension->permissions_data()->CanCaptureVisiblePage(
        url, tab_id, nullptr);

     if (allowed_script && allowed_capture)
       return ALLOWED_SCRIPT_AND_CAPTURE;
    if (allowed_script)
      return ALLOWED_SCRIPT_ONLY;
    if (allowed_capture)
      return ALLOWED_CAPTURE_ONLY;
    return DISALLOWED;
  }


WM_SYMBOL const char *WildMidi_GetString(uint16_t info) {
    static char WM_Version[] = "WildMidi Processing Library " PACKAGE_VERSION;
    switch (info) {
    case WM_GS_VERSION:
        return WM_Version;
    }
    return NULL;
}


void Editor::reappliedEditing(UndoStep* cmd) {
  EventQueueScope scope;

  dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(),
                                       cmd->endingRootEditableElement());
  dispatchInputEventEditableContentChanged(
      cmd->startingRootEditableElement(), cmd->endingRootEditableElement(),
      InputEvent::InputType::HistoryRedo, nullAtom,
      InputEvent::EventIsComposing::NotComposing);

  frame().document()->updateStyleAndLayoutIgnorePendingStylesheets();
  const VisibleSelection& newSelection =
      correctedVisibleSelection(cmd->endingSelection());
  DCHECK(newSelection.isValidFor(*frame().document())) << newSelection;
  changeSelectionAfterCommand(
      newSelection.asSelection(),
      FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);

  m_lastEditCommand = nullptr;
  m_undoStack->registerUndoStep(cmd);
  respondToChangedContents(newSelection.start());
}


static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
{
	struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root;
	struct btrfs_ioctl_qgroup_assign_args *sa;
	struct btrfs_trans_handle *trans;
	int ret;
	int err;

	if (!capable(CAP_SYS_ADMIN))
		return -EPERM;

	ret = mnt_want_write_file(file);
	if (ret)
		return ret;

	sa = memdup_user(arg, sizeof(*sa));
	if (IS_ERR(sa)) {
		ret = PTR_ERR(sa);
		goto drop_write;
	}

	trans = btrfs_join_transaction(root);
	if (IS_ERR(trans)) {
		ret = PTR_ERR(trans);
		goto out;
	}

	/* FIXME: check if the IDs really exist */
	if (sa->assign) {
		ret = btrfs_add_qgroup_relation(trans, root->fs_info,
						sa->src, sa->dst);
	} else {
		ret = btrfs_del_qgroup_relation(trans, root->fs_info,
						sa->src, sa->dst);
	}

	err = btrfs_end_transaction(trans, root);
	if (err && !ret)
		ret = err;

out:
	kfree(sa);
drop_write:
	mnt_drop_write_file(file);
	return ret;
}


static int insert_entry(struct ctl_table_header *head, struct ctl_table *entry)
{
	struct rb_node *node = &head->node[entry - head->ctl_table].node;
	struct rb_node **p = &head->parent->root.rb_node;
	struct rb_node *parent = NULL;
	const char *name = entry->procname;
	int namelen = strlen(name);

	while (*p) {
		struct ctl_table_header *parent_head;
		struct ctl_table *parent_entry;
		struct ctl_node *parent_node;
		const char *parent_name;
		int cmp;

		parent = *p;
		parent_node = rb_entry(parent, struct ctl_node, node);
		parent_head = parent_node->header;
		parent_entry = &parent_head->ctl_table[parent_node - parent_head->node];
		parent_name = parent_entry->procname;

		cmp = namecmp(name, namelen, parent_name, strlen(parent_name));
		if (cmp < 0)
			p = &(*p)->rb_left;
		else if (cmp > 0)
			p = &(*p)->rb_right;
		else {
			pr_err("sysctl duplicate entry: ");
			sysctl_print_dir(head->parent);
			pr_cont("/%s\n", entry->procname);
			return -EEXIST;
		}
	}

	rb_link_node(node, parent, p);
	rb_insert_color(node, &head->parent->root);
	return 0;
}


static int nbd_receive_list(QIOChannel *ioc, char **name, Error **errp)

{

    uint64_t magic;

    uint32_t opt;

    uint32_t type;

    uint32_t len;

    uint32_t namelen;

    int error;

    *name = NULL;

    if (read_sync(ioc, &magic, sizeof(magic)) != sizeof(magic)) {

        error_setg(errp, "failed to read list option magic");

        return -1;

    }

    magic = be64_to_cpu(magic);

    if (magic != NBD_REP_MAGIC) {

        error_setg(errp, "Unexpected option list magic");

        return -1;

    }

    if (read_sync(ioc, &opt, sizeof(opt)) != sizeof(opt)) {

        error_setg(errp, "failed to read list option");

        return -1;

    }

    opt = be32_to_cpu(opt);

    if (opt != NBD_OPT_LIST) {

        error_setg(errp, "Unexpected option type %" PRIx32 " expected %x",

                   opt, NBD_OPT_LIST);

        return -1;

    }

    if (read_sync(ioc, &type, sizeof(type)) != sizeof(type)) {

        error_setg(errp, "failed to read list option type");

        return -1;

    }

    type = be32_to_cpu(type);

    error = nbd_handle_reply_err(ioc, opt, type, errp);

    if (error <= 0) {

        return error;

    }

    if (read_sync(ioc, &len, sizeof(len)) != sizeof(len)) {

        error_setg(errp, "failed to read option length");

        return -1;

    }

    len = be32_to_cpu(len);

    if (type == NBD_REP_ACK) {

        if (len != 0) {

            error_setg(errp, "length too long for option end");

            return -1;

        }

    } else if (type == NBD_REP_SERVER) {

        if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {

            error_setg(errp, "incorrect option length");

            return -1;

        }

        if (read_sync(ioc, &namelen, sizeof(namelen)) != sizeof(namelen)) {

            error_setg(errp, "failed to read option name length");

            return -1;

        }

        namelen = be32_to_cpu(namelen);

        len -= sizeof(namelen);

        if (len < namelen) {

            error_setg(errp, "incorrect option name length");

            return -1;

        }

        if (namelen > 255) {

            error_setg(errp, "export name length too long %" PRIu32, namelen);

            return -1;

        }

        *name = g_new0(char, namelen + 1);

        if (read_sync(ioc, *name, namelen) != namelen) {

            error_setg(errp, "failed to read export name");

            g_free(*name);

            *name = NULL;

            return -1;

        }

        (*name)[namelen] = '\0';

        len -= namelen;

        if (len) {

            char *buf = g_malloc(len + 1);

            if (read_sync(ioc, buf, len) != len) {

                error_setg(errp, "failed to read export description");

                g_free(*name);

                g_free(buf);

                *name = NULL;

                return -1;

            }

            buf[len] = '\0';

            TRACE("Ignoring export description: %s", buf);

            g_free(buf);

        }

    } else {

        error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",

                   type, NBD_REP_SERVER);

        return -1;

    }

    return 1;

}


BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags)
{
	BOOL rc = FALSE;
	UINT16 length;
	UINT32 pad;

	if (!s)
		return FALSE;

	if (!rdp)
		goto fail;

	length = Stream_GetPosition(s);
	Stream_SetPosition(s, 0);
	rdp_write_header(rdp, s, length, rdp->mcs->messageChannelId);

	if (!rdp_security_stream_out(rdp, s, length, sec_flags, &pad))
		goto fail;

	length += pad;
	Stream_SetPosition(s, length);
	Stream_SealLength(s);

	if (transport_write(rdp->transport, s) < 0)
		goto fail;

	rc = TRUE;
fail:
	Stream_Release(s);
	return rc;
}


BubbleReference BubbleManager::ShowBubble(
    std::unique_ptr<BubbleDelegate> bubble) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK_NE(manager_state_, ITERATING_BUBBLES);
  DCHECK(bubble);

  std::unique_ptr<BubbleController> controller(
      new BubbleController(this, std::move(bubble)));

  BubbleReference bubble_ref = controller->AsWeakPtr();

  switch (manager_state_) {
    case SHOW_BUBBLES:
      controller->Show();
      controllers_.push_back(std::move(controller));
      break;
    case NO_MORE_BUBBLES:
      for (auto& observer : observers_)
        observer.OnBubbleNeverShown(controller->AsWeakPtr());
      break;
    default:
      NOTREACHED();
      break;
  }

  return bubble_ref;
}


static int unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
			       struct msghdr *msg, size_t len)
{
	struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
	struct sock *sk = sock->sk;
	struct sock *other = NULL;
	int err, size;
	struct sk_buff *skb;
	int sent = 0;
	struct scm_cookie tmp_scm;
	bool fds_sent = false;
	int max_level;
	int data_len;

	if (NULL == siocb->scm)
		siocb->scm = &tmp_scm;
	wait_for_unix_gc();
	err = scm_send(sock, msg, siocb->scm, false);
	if (err < 0)
		return err;

	err = -EOPNOTSUPP;
	if (msg->msg_flags&MSG_OOB)
		goto out_err;

	if (msg->msg_namelen) {
		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
		goto out_err;
	} else {
		err = -ENOTCONN;
		other = unix_peer(sk);
		if (!other)
			goto out_err;
	}

	if (sk->sk_shutdown & SEND_SHUTDOWN)
		goto pipe_err;

	while (sent < len) {
		size = len - sent;

		/* Keep two messages in the pipe so it schedules better */
		size = min_t(int, size, (sk->sk_sndbuf >> 1) - 64);

		/* allow fallback to order-0 allocations */
		size = min_t(int, size, SKB_MAX_HEAD(0) + UNIX_SKB_FRAGS_SZ);

		data_len = max_t(int, 0, size - SKB_MAX_HEAD(0));

		skb = sock_alloc_send_pskb(sk, size - data_len, data_len,
					   msg->msg_flags & MSG_DONTWAIT, &err,
					   get_order(UNIX_SKB_FRAGS_SZ));
		if (!skb)
			goto out_err;

		/* Only send the fds in the first buffer */
		err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
		if (err < 0) {
			kfree_skb(skb);
			goto out_err;
		}
		max_level = err + 1;
		fds_sent = true;

		skb_put(skb, size - data_len);
		skb->data_len = data_len;
		skb->len = size;
		err = skb_copy_datagram_from_iovec(skb, 0, msg->msg_iov,
						   sent, size);
		if (err) {
			kfree_skb(skb);
			goto out_err;
		}

		unix_state_lock(other);

		if (sock_flag(other, SOCK_DEAD) ||
		    (other->sk_shutdown & RCV_SHUTDOWN))
			goto pipe_err_free;

		maybe_add_creds(skb, sock, other);
		skb_queue_tail(&other->sk_receive_queue, skb);
		if (max_level > unix_sk(other)->recursion_level)
			unix_sk(other)->recursion_level = max_level;
		unix_state_unlock(other);
		other->sk_data_ready(other, size);
		sent += size;
	}

	scm_destroy(siocb->scm);
	siocb->scm = NULL;

	return sent;

pipe_err_free:
	unix_state_unlock(other);
	kfree_skb(skb);
pipe_err:
	if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
		send_sig(SIGPIPE, current, 0);
	err = -EPIPE;
out_err:
	scm_destroy(siocb->scm);
	siocb->scm = NULL;
	return sent ? : err;
}


static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
  ExceptionInfo *exception)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
  char
    value[MagickPathExtent];

  register ssize_t
    i;

  tdir_t
    directory;

#if defined(TIFF_VERSION_BIG)
  uint64
#else
  uint32
#endif
    offset;

  void
    *sans[2] = { NULL, NULL };

  /*
    Read EXIF properties.
  */
  offset=0;
  if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
    return;
  directory=TIFFCurrentDirectory(tiff);
  if (TIFFReadEXIFDirectory(tiff,offset) != 1)
    {
      TIFFSetDirectory(tiff,directory);
      return;
    }
  for (i=0; exif_info[i].tag != 0; i++)
  {
    *value='\0';
    switch (exif_info[i].type)
    {
      case TIFF_ASCII:
      {
        char
          *ascii;

        ascii=(char *) NULL;
        if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,sans) == 1) &&
            (ascii != (char *) NULL) && (*ascii != '\0'))
          (void) CopyMagickString(value,ascii,MagickPathExtent);
        break;
      }
      case TIFF_SHORT:
      {
        if (exif_info[i].variable_length == 0)
          {
            uint16
              shorty;

            shorty=0;
            if (TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1)
              (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty);
          }
        else if (exif_info[i].variable_length == 2)
        {
          uint16
            *shorty;

          shorty=0;
          if ((TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1) &&
              (shorty != (uint16 *) NULL))
            (void) FormatLocaleString(value,MagickPathExtent,"%d",*shorty);
        }
        else
          {
            int
              tiff_status;

            uint16
              *shorty;

            uint16
              shorty_num;

            tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
              sans);
            if (tiff_status == 1)
              (void) FormatLocaleString(value,MagickPathExtent,"%d",
                shorty_num != 0 ? shorty[0] : 0);
          }
        break;
      }
      case TIFF_LONG:
      {
        uint32
          longy;

        longy=0;
        if (TIFFGetField(tiff,exif_info[i].tag,&longy,sans) == 1)
          (void) FormatLocaleString(value,MagickPathExtent,"%d",longy);
        break;
      }
#if defined(TIFF_VERSION_BIG)
      case TIFF_LONG8:
      {
        uint64
          long8y;

        long8y=0;
        if (TIFFGetField(tiff,exif_info[i].tag,&long8y,sans) == 1)
          (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
            ((MagickOffsetType) long8y));
        break;
      }
#endif
      case TIFF_RATIONAL:
      case TIFF_SRATIONAL:
      case TIFF_FLOAT:
      {
        float
          floaty;

        floaty=0.0;
        if (TIFFGetField(tiff,exif_info[i].tag,&floaty,sans) == 1)
          (void) FormatLocaleString(value,MagickPathExtent,"%g",(double)
            floaty);
        break;
      }
      case TIFF_DOUBLE:
      {
        double
          doubley;

        doubley=0.0;
        if (TIFFGetField(tiff,exif_info[i].tag,&doubley,sans) == 1)
          (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley);
        break;
      }
      default:
        break;
    }
    if (*value != '\0')
      (void) SetImageProperty(image,exif_info[i].property,value,exception);
  }
  TIFFSetDirectory(tiff,directory);
#else
  (void) tiff;
  (void) image;
#endif
}


int net_client_init(Monitor *mon, const char *device, const char *p)

{

    static const char * const fd_params[] = {

        "vlan", "name", "fd", NULL

    };

    char buf[1024];

    int vlan_id, ret;

    VLANState *vlan;

    char *name = NULL;

    vlan_id = 0;

    if (get_param_value(buf, sizeof(buf), "vlan", p)) {

        vlan_id = strtol(buf, NULL, 0);

    }

    vlan = qemu_find_vlan(vlan_id);

    if (get_param_value(buf, sizeof(buf), "name", p)) {

        name = qemu_strdup(buf);

    }

    if (!strcmp(device, "nic")) {

        static const char * const nic_params[] = {

            "vlan", "name", "macaddr", "model", "addr", NULL

        };

        NICInfo *nd;

        uint8_t *macaddr;

        int idx = nic_get_free_idx();

        if (check_params(buf, sizeof(buf), nic_params, p) < 0) {

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

        if (idx == -1 || nb_nics >= MAX_NICS) {

            config_error(mon, "Too Many NICs\n");

            ret = -1;

            goto out;

        }

        nd = &nd_table[idx];

        macaddr = nd->macaddr;

        macaddr[0] = 0x52;

        macaddr[1] = 0x54;

        macaddr[2] = 0x00;

        macaddr[3] = 0x12;

        macaddr[4] = 0x34;

        macaddr[5] = 0x56 + idx;

        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {

            if (parse_macaddr(macaddr, buf) < 0) {

                config_error(mon, "invalid syntax for ethernet address\n");

                ret = -1;

                goto out;

            }

        }

        if (get_param_value(buf, sizeof(buf), "model", p)) {

            nd->model = strdup(buf);

        }

        if (get_param_value(buf, sizeof(buf), "addr", p)) {

            nd->devaddr = strdup(buf);

        }

        nd->vlan = vlan;

        nd->name = name;

        nd->used = 1;

        name = NULL;

        nb_nics++;

        vlan->nb_guest_devs++;

        ret = idx;

    } else

    if (!strcmp(device, "none")) {

        if (*p != '\0') {

            config_error(mon, "'none' takes no parameters\n");

            ret = -1;

            goto out;

        }

        /* does nothing. It is needed to signal that no network cards

           are wanted */

        ret = 0;

    } else

#ifdef CONFIG_SLIRP

    if (!strcmp(device, "user")) {

        static const char * const slirp_params[] = {

            "vlan", "name", "hostname", "restrict", "ip", NULL

        };

        int restricted = 0;

        char *ip = NULL;

        if (check_params(buf, sizeof(buf), slirp_params, p) < 0) {

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

        if (get_param_value(buf, sizeof(buf), "hostname", p)) {

            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);

        }

        if (get_param_value(buf, sizeof(buf), "restrict", p)) {

            restricted = (buf[0] == 'y') ? 1 : 0;

        }

        if (get_param_value(buf, sizeof(buf), "ip", p)) {

            ip = qemu_strdup(buf);

        }

        vlan->nb_host_devs++;

        ret = net_slirp_init(vlan, device, name, restricted, ip);

        qemu_free(ip);

    } else if (!strcmp(device, "channel")) {

        long port;

        char name[20], *devname;

        struct VMChannel *vmc;

        port = strtol(p, &devname, 10);

        devname++;

        if (port < 1 || port > 65535) {

            config_error(mon, "vmchannel wrong port number\n");

            ret = -1;

            goto out;

        }

        vmc = malloc(sizeof(struct VMChannel));

        snprintf(name, 20, "vmchannel%ld", port);

        vmc->hd = qemu_chr_open(name, devname, NULL);

        if (!vmc->hd) {

            config_error(mon, "could not open vmchannel device '%s'\n",

                         devname);

            ret = -1;

            goto out;

        }

        vmc->port = port;

        slirp_add_exec(3, vmc->hd, 4, port);

        qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,

                NULL, vmc);

        ret = 0;

    } else

#endif

#ifdef _WIN32

    if (!strcmp(device, "tap")) {

        static const char * const tap_params[] = {

            "vlan", "name", "ifname", NULL

        };

        char ifname[64];

        if (check_params(buf, sizeof(buf), tap_params, p) < 0) {

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

            config_error(mon, "tap: no interface name\n");

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

        ret = tap_win32_init(vlan, device, name, ifname);

    } else

#elif defined (_AIX)

#else

    if (!strcmp(device, "tap")) {

        char ifname[64], chkbuf[64];

        char setup_script[1024], down_script[1024];

        TAPState *s;

        int fd;

        vlan->nb_host_devs++;

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            fd = strtol(buf, NULL, 0);

            fcntl(fd, F_SETFL, O_NONBLOCK);

            s = net_tap_fd_init(vlan, device, name, fd);

        } else {

            static const char * const tap_params[] = {

                "vlan", "name", "ifname", "script", "downscript", NULL

            };

            if (check_params(chkbuf, sizeof(chkbuf), tap_params, p) < 0) {

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

                ifname[0] = '\0';

            }

            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {

                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);

            }

            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {

                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);

            }

            s = net_tap_init(vlan, device, name, ifname, setup_script, down_script);

        }

        if (s != NULL) {

            ret = 0;

        } else {

            ret = -1;

        }

    } else

#endif

    if (!strcmp(device, "socket")) {

        char chkbuf[64];

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            int fd;

            if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            fd = strtol(buf, NULL, 0);

            ret = -1;

            if (net_socket_fd_init(vlan, device, name, fd, 1))

                ret = 0;

        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {

            static const char * const listen_params[] = {

                "vlan", "name", "listen", NULL

            };

            if (check_params(chkbuf, sizeof(chkbuf), listen_params, p) < 0) {

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            ret = net_socket_listen_init(vlan, device, name, buf);

        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {

            static const char * const connect_params[] = {

                "vlan", "name", "connect", NULL

            };

            if (check_params(chkbuf, sizeof(chkbuf), connect_params, p) < 0) {

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            ret = net_socket_connect_init(vlan, device, name, buf);

        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {

            static const char * const mcast_params[] = {

                "vlan", "name", "mcast", NULL

            };

            if (check_params(chkbuf, sizeof(chkbuf), mcast_params, p) < 0) {

                config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);

                ret = -1;

                goto out;

            }

            ret = net_socket_mcast_init(vlan, device, name, buf);

        } else {

            config_error(mon, "Unknown socket options: %s\n", p);

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

    } else

#ifdef CONFIG_VDE

    if (!strcmp(device, "vde")) {

        static const char * const vde_params[] = {

            "vlan", "name", "sock", "port", "group", "mode", NULL

        };

        char vde_sock[1024], vde_group[512];

	int vde_port, vde_mode;

        if (check_params(buf, sizeof(buf), vde_params, p) < 0) {

            config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);

            ret = -1;

            goto out;

        }

        vlan->nb_host_devs++;

        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {

	    vde_sock[0] = '\0';

	}

	if (get_param_value(buf, sizeof(buf), "port", p) > 0) {

	    vde_port = strtol(buf, NULL, 10);

	} else {

	    vde_port = 0;

	}

	if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {

	    vde_group[0] = '\0';

	}

	if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {

	    vde_mode = strtol(buf, NULL, 8);

	} else {

	    vde_mode = 0700;

	}

	ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);

    } else

#endif

    if (!strcmp(device, "dump")) {

        int len = 65536;

        if (get_param_value(buf, sizeof(buf), "len", p) > 0) {

            len = strtol(buf, NULL, 0);

        }

        if (!get_param_value(buf, sizeof(buf), "file", p)) {

            snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);

        }

        ret = net_dump_init(mon, vlan, device, name, buf, len);

    } else {

        config_error(mon, "Unknown network device: %s\n", device);

        ret = -1;

        goto out;

    }

    if (ret < 0) {

        config_error(mon, "Could not initialize device '%s'\n", device);

    }

out:

    qemu_free(name);

    return ret;

}


size_t SharedMemory::GetHandleLimit() {
  return base::GetMaxFds();
}


png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
{
   png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
   if (num_to_check > 8)
      num_to_check = 8;
   else if (num_to_check < 1)
      return (-1);

   if (start > 7)
      return (-1);

   if (start + num_to_check > 8)
      num_to_check = 8 - start;

   return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
}


ldns_rr2canonical(ldns_rr *rr)
{
	uint16_t i;

	if (!rr) {
	  return;
        }

        ldns_dname2canonical(ldns_rr_owner(rr));

	/*
	 * lowercase the rdata dnames if the rr type is one
	 * of the list in chapter 7 of RFC3597
	 * Also added RRSIG, because a "Signer's Name" should be canonicalized
	 * too. See dnssec-bis-updates-16. We can add it to this list because
	 * the "Signer's Name"  is the only dname type rdata field in a RRSIG.
	 */
	switch(ldns_rr_get_type(rr)) {
        	case LDNS_RR_TYPE_NS:
        	case LDNS_RR_TYPE_MD:
        	case LDNS_RR_TYPE_MF:
        	case LDNS_RR_TYPE_CNAME:
        	case LDNS_RR_TYPE_SOA:
        	case LDNS_RR_TYPE_MB:
        	case LDNS_RR_TYPE_MG:
        	case LDNS_RR_TYPE_MR:
        	case LDNS_RR_TYPE_PTR:
        	case LDNS_RR_TYPE_MINFO:
        	case LDNS_RR_TYPE_MX:
        	case LDNS_RR_TYPE_RP:
        	case LDNS_RR_TYPE_AFSDB:
        	case LDNS_RR_TYPE_RT:
        	case LDNS_RR_TYPE_SIG:
        	case LDNS_RR_TYPE_PX:
        	case LDNS_RR_TYPE_NXT:
        	case LDNS_RR_TYPE_NAPTR:
        	case LDNS_RR_TYPE_KX:
        	case LDNS_RR_TYPE_SRV:
        	case LDNS_RR_TYPE_DNAME:
        	case LDNS_RR_TYPE_A6:
        	case LDNS_RR_TYPE_RRSIG:
			for (i = 0; i < ldns_rr_rd_count(rr); i++) {
				ldns_dname2canonical(ldns_rr_rdf(rr, i));
			}
			return;
		default:
			/* do nothing */
			return;
	}
}


unix_sck_send_conn(hsm_com_client_hdl_t *hdl, int timeout)
{
	hsm_com_con_data_t	msg;

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

	msg.header.cmd = HSM_COM_CMD_CONN;
	msg.header.ver = HSM_COM_VER;
	msg.header.trans_id = hdl->trans_id++;
	msg.header.payload_len = sizeof(msg.key);

	msg.key = HSM_COM_KEY;

	if(unix_sck_send_msg(hdl, (char*)&msg, sizeof(msg), (char*)&msg,
						 sizeof(msg), timeout) != sizeof(msg))
	{
		close(hdl->client_fd);
		hdl->client_state = HSM_COM_C_STATE_IN;

		return HSM_COM_BAD;
	}

	if(msg.header.resp_code == HSM_COM_RESP_OK){
		return HSM_COM_OK;
	}

	return HSM_COM_BAD;
}


    void writeReferenceCount(uint32_t numberOfReferences)
    {
        append(ReferenceCountTag);
        doWriteUint32(numberOfReferences);
    }


apr_byte_t oidc_util_file_read(request_rec *r, const char *path,
		apr_pool_t *pool, char **result) {
	apr_file_t *fd = NULL;
	apr_status_t rc = APR_SUCCESS;
	char s_err[128];
	apr_finfo_t finfo;

	/* open the file if it exists */
	if ((rc = apr_file_open(&fd, path, APR_FOPEN_READ | APR_FOPEN_BUFFERED,
			APR_OS_DEFAULT, r->pool)) != APR_SUCCESS) {
		oidc_warn(r, "no file found at: \"%s\"", path);
		return FALSE;
	}

	/* the file exists, now lock it */
	apr_file_lock(fd, APR_FLOCK_EXCLUSIVE);

	/* move the read pointer to the very start of the cache file */
	apr_off_t begin = 0;
	apr_file_seek(fd, APR_SET, &begin);

	/* get the file info so we know its size */
	if ((rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, fd)) != APR_SUCCESS) {
		oidc_error(r, "error calling apr_file_info_get on file: \"%s\" (%s)",
				path, apr_strerror(rc, s_err, sizeof(s_err)));
		goto error_close;
	}

	/* now that we have the size of the file, allocate a buffer that can contain its contents */
	*result = apr_palloc(pool, finfo.size + 1);

	/* read the file in to the buffer */
	apr_size_t bytes_read = 0;
	if ((rc = apr_file_read_full(fd, *result, finfo.size, &bytes_read))
			!= APR_SUCCESS) {
		oidc_error(r, "apr_file_read_full on (%s) returned an error: %s", path,
				apr_strerror(rc, s_err, sizeof(s_err)));
		goto error_close;
	}

	/* just to be sure, we set a \0 (we allocated space for it anyway) */
	(*result)[bytes_read] = '\0';

	/* check that we've got all of it */
	if (bytes_read != finfo.size) {
		oidc_error(r,
				"apr_file_read_full on (%s) returned less bytes (%" APR_SIZE_T_FMT ") than expected: (%" APR_OFF_T_FMT ")",
				path, bytes_read, finfo.size);
		goto error_close;
	}

	/* we're done, unlock and close the file */
	apr_file_unlock(fd);
	apr_file_close(fd);

	/* log successful content retrieval */
	oidc_debug(r, "file read successfully \"%s\"", path);

	return TRUE;

error_close:

	apr_file_unlock(fd);
	apr_file_close(fd);

	oidc_error(r, "return error");

	return FALSE;
}


static bool ndp_msg_check_valid(struct ndp_msg *msg)
{
	size_t len = ndp_msg_payload_len(msg);
	enum ndp_msg_type msg_type = ndp_msg_type(msg);

	if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
		return false;

	if (ndp_msg_type_info(msg_type)->addrto_validate)
		return ndp_msg_type_info(msg_type)->addrto_validate(&msg->addrto);
	else
		return true;
}


    template<typename T>
    inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6) {
      T tmp = std::min(val0,val5);
      val5 = std::max(val0,val5); val0 = tmp; tmp = std::min(val0,val3); val3 = std::max(val0,val3); val0 = tmp;
      tmp = std::min(val1,val6); val6 = std::max(val1,val6); val1 = tmp; tmp = std::min(val2,val4);
      val4 = std::max(val2,val4); val2 = tmp; val1 = std::max(val0,val1); tmp = std::min(val3,val5);
      val5 = std::max(val3,val5); val3 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6);
      val3 = std::max(tmp,val3); val3 = std::min(val3,val6); tmp = std::min(val4,val5); val4 = std::max(val1,tmp);
      tmp = std::min(val1,tmp); val3 = std::max(tmp,val3);
      return std::min(val3,val4);


ConfirmEmailDialogDelegate::ConfirmEmailDialogDelegate(
    content::WebContents* contents,
    const std::string& last_email,
    const std::string& email,
    Callback callback)
  : TabModalConfirmDialogDelegate(contents),
    last_email_(last_email),
    email_(email),
    callback_(callback) {
}


static v8::Local<v8::Value> compileAndRunPrivateScript(ScriptState* scriptState,
                                                       String scriptClassName,
                                                       const char* source,
                                                       size_t size) {
  v8::Isolate* isolate = scriptState->isolate();
  v8::TryCatch block(isolate);
  String sourceString(source, size);
  String fileName = scriptClassName + ".js";

   v8::Local<v8::Context> context = scriptState->context();
   v8::Local<v8::Object> global = context->Global();
  v8::Local<v8::Value> privateScriptController =
      global->Get(context, v8String(isolate, "privateScriptController"))
          .ToLocalChecked();
  RELEASE_ASSERT(privateScriptController->IsUndefined() ||
                 privateScriptController->IsObject());
  if (privateScriptController->IsObject()) {
     v8::Local<v8::Object> privateScriptControllerObject =
         privateScriptController.As<v8::Object>();
     v8::Local<v8::Value> importFunctionValue =
        privateScriptControllerObject->Get(context, v8String(isolate, "import"))
            .ToLocalChecked();
    if (importFunctionValue->IsUndefined()) {
      v8::Local<v8::Function> function;
      if (!v8::FunctionTemplate::New(isolate, importFunction)
               ->GetFunction(context)
               .ToLocal(&function) ||
          !v8CallBoolean(privateScriptControllerObject->Set(
              context, v8String(isolate, "import"), function))) {
        dumpV8Message(context, block.Message());
        LOG(FATAL)
            << "Private script error: Setting import function failed. (Class "
               "name = "
            << scriptClassName.utf8().data() << ")";
      }
    }
  }

  v8::Local<v8::Script> script;
  if (!v8Call(V8ScriptRunner::compileScript(
                  v8String(isolate, sourceString), fileName, String(),
                  TextPosition::minimumPosition(), isolate, nullptr, nullptr,
                  nullptr, NotSharableCrossOrigin),
              script, block)) {
    dumpV8Message(context, block.Message());
    LOG(FATAL) << "Private script error: Compile failed. (Class name = "
               << scriptClassName.utf8().data() << ")";
  }

  v8::Local<v8::Value> result;
  if (!v8Call(V8ScriptRunner::runCompiledInternalScript(isolate, script),
              result, block)) {
    dumpV8Message(context, block.Message());
    LOG(FATAL) << "Private script error: installClass() failed. (Class name = "
               << scriptClassName.utf8().data() << ")";
  }
  return result;
}


TRIO_PUBLIC_STRING char* trio_string_extract TRIO_ARGS1((self), trio_string_t* self)
{
	char* result;

	assert(self);

	result = self->content;
	/* FIXME: Allocate new empty buffer? */
	self->content = NULL;
	self->length = self->allocated = 0;
	return result;
}


pdf_copy_pattern_gstate(fz_context *ctx, pdf_gstate *gs, const pdf_gstate *old)
{
	gs->ctm = old->ctm;

	pdf_drop_font(ctx, gs->text.font);
	gs->text.font = pdf_keep_font(ctx, old->text.font);

	pdf_drop_xobject(ctx, gs->softmask);
	gs->softmask = pdf_keep_xobject(ctx, old->softmask);

	fz_drop_stroke_state(ctx, gs->stroke_state);
	gs->stroke_state = fz_keep_stroke_state(ctx, old->stroke_state);
}


void fx_TypedArray_prototype_set(txMachine* the)
{
	mxMutableTypedArrayDeclarations;
	txSlot* data = buffer->value.reference->next;
	txInteger delta = dispatch->value.typedArray.dispatch->size;
	txSlot* source = fxArgToInstance(the, 0);
	txInteger target = fxArgToByteLength(the, 1, 0);
	txInteger offset = view->value.dataView.offset + (target * delta);
	if (source->next && (source->next->kind == XS_TYPED_ARRAY_KIND)) {
		txSlot* sourceDispatch = source->next;
		txSlot* sourceView = sourceDispatch->next;
		txSlot* sourceBuffer = sourceView->next;
		txU2 shift = sourceDispatch->value.typedArray.dispatch->shift;
		txInteger sourceLength = fxCheckDataViewSize(the, sourceView, sourceBuffer, XS_IMMUTABLE) >> shift;
		txInteger sourceOffset = sourceView->value.dataView.offset;
		txSlot* sourceData = sourceBuffer->value.reference->next;
		txInteger limit = offset + (sourceLength * delta);
		if ((target < 0) || (length - sourceLength < target))
			mxRangeError("invalid offset");
		if (data == sourceData) {
			txSlot* resultBuffer;
			mxPush(mxArrayBufferConstructor);
			mxNew();
			mxPushInteger(sourceLength << shift);
			mxRunCount(1);
			resultBuffer = the->stack->value.reference->next;
			c_memcpy(resultBuffer->value.arrayBuffer.address, sourceData->value.arrayBuffer.address + sourceOffset, sourceLength << shift);
			sourceData = resultBuffer;
			sourceOffset = 0;
		}
		else
			mxPushUndefined();
		if (dispatch == sourceDispatch) {
			c_memcpy(data->value.arrayBuffer.address + offset, sourceData->value.arrayBuffer.address + sourceOffset, limit - offset);
			mxMeterSome(((txU4)(limit - offset)) * 2);
		}
		else {
			txInteger sourceDelta = 1 << shift;
			mxPushUndefined();
			while (offset < limit) {
				(*sourceDispatch->value.typedArray.dispatch->getter)(the, sourceData, sourceOffset, the->stack, EndianNative);
				(*dispatch->value.typedArray.dispatch->coerce)(the, the->stack);
                if (data->value.arrayBuffer.address == C_NULL)
                    mxTypeError("detached buffer");
				(*dispatch->value.typedArray.dispatch->setter)(the, data, offset, the->stack, EndianNative);
				sourceOffset += sourceDelta;
				offset += delta;
			}
			mxPop();
		}
		mxPop();
	}
	else {
		txInteger count, index;
		mxPushSlot(mxArgv(0));
		mxGetID(mxID(_length));
		count = fxToInteger(the, the->stack);
		mxPop();
		if ((target < 0) || (length - count < target))
			mxRangeError("invalid offset");
		index = 0;
		while (index < count) {
			mxPushSlot(mxArgv(0));
			mxGetIndex(index);
			(*dispatch->value.typedArray.dispatch->coerce)(the, the->stack);
			if (data->value.arrayBuffer.address == C_NULL)
				mxTypeError("detached buffer");
			(*dispatch->value.typedArray.dispatch->setter)(the, data, offset, the->stack, EndianNative);
			mxPop();
			offset += delta;
			index++;
		}
	}
}


dir_of_file_exists(char_u *fname)
{
    char_u	*p;
    int		c;
    int		retval;

    p = gettail_sep(fname);
    if (p == fname)
	return TRUE;
    c = *p;
    *p = NUL;
    retval = mch_isdir(fname);
    *p = c;
    return retval;
}


static void dummy_signal ( int sig ) {
 }


static struct rtable *__mkroute_output(const struct fib_result *res,
				       const struct flowi4 *fl4, int orig_oif,
				       struct net_device *dev_out,
				       unsigned int flags)
{
	struct fib_info *fi = res->fi;
	struct fib_nh_exception *fnhe;
	struct in_device *in_dev;
	u16 type = res->type;
	struct rtable *rth;
	bool do_cache;

	in_dev = __in_dev_get_rcu(dev_out);
	if (!in_dev)
		return ERR_PTR(-EINVAL);

	if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev)))
		if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK))
			return ERR_PTR(-EINVAL);

	if (ipv4_is_lbcast(fl4->daddr))
		type = RTN_BROADCAST;
	else if (ipv4_is_multicast(fl4->daddr))
		type = RTN_MULTICAST;
	else if (ipv4_is_zeronet(fl4->daddr))
		return ERR_PTR(-EINVAL);

	if (dev_out->flags & IFF_LOOPBACK)
		flags |= RTCF_LOCAL;

	do_cache = true;
	if (type == RTN_BROADCAST) {
		flags |= RTCF_BROADCAST | RTCF_LOCAL;
		fi = NULL;
	} else if (type == RTN_MULTICAST) {
		flags |= RTCF_MULTICAST | RTCF_LOCAL;
		if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr,
				     fl4->flowi4_proto))
			flags &= ~RTCF_LOCAL;
		else
			do_cache = false;
		/* If multicast route do not exist use
		 * default one, but do not gateway in this case.
		 * Yes, it is hack.
		 */
		if (fi && res->prefixlen < 4)
			fi = NULL;
	}

	fnhe = NULL;
	do_cache &= fi != NULL;
	if (do_cache) {
		struct rtable __rcu **prth;
		struct fib_nh *nh = &FIB_RES_NH(*res);

		fnhe = find_exception(nh, fl4->daddr);
		if (fnhe)
			prth = &fnhe->fnhe_rth_output;
		else {
			if (unlikely(fl4->flowi4_flags &
				     FLOWI_FLAG_KNOWN_NH &&
				     !(nh->nh_gw &&
				       nh->nh_scope == RT_SCOPE_LINK))) {
				do_cache = false;
				goto add;
			}
			prth = raw_cpu_ptr(nh->nh_pcpu_rth_output);
		}
		rth = rcu_dereference(*prth);
		if (rt_cache_valid(rth)) {
			dst_hold(&rth->dst);
			return rth;
		}
	}

add:
	rth = rt_dst_alloc(dev_out,
			   IN_DEV_CONF_GET(in_dev, NOPOLICY),
			   IN_DEV_CONF_GET(in_dev, NOXFRM),
			   do_cache);
	if (!rth)
		return ERR_PTR(-ENOBUFS);

	rth->dst.output = ip_output;

	rth->rt_genid = rt_genid_ipv4(dev_net(dev_out));
	rth->rt_flags	= flags;
	rth->rt_type	= type;
	rth->rt_is_input = 0;
	rth->rt_iif	= orig_oif ? : 0;
	rth->rt_pmtu	= 0;
	rth->rt_gateway = 0;
	rth->rt_uses_gateway = 0;
	INIT_LIST_HEAD(&rth->rt_uncached);

	RT_CACHE_STAT_INC(out_slow_tot);

	if (flags & RTCF_LOCAL)
		rth->dst.input = ip_local_deliver;
	if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
		if (flags & RTCF_LOCAL &&
		    !(dev_out->flags & IFF_LOOPBACK)) {
			rth->dst.output = ip_mc_output;
			RT_CACHE_STAT_INC(out_slow_mc);
		}
#ifdef CONFIG_IP_MROUTE
		if (type == RTN_MULTICAST) {
			if (IN_DEV_MFORWARD(in_dev) &&
			    !ipv4_is_local_multicast(fl4->daddr)) {
				rth->dst.input = ip_mr_input;
				rth->dst.output = ip_mc_output;
			}
		}
#endif
	}

	rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0);

	return rth;
}


static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
	struct sock *sk = sock->sk;
	long amount = 0;
	int err;

	switch (cmd) {
	case SIOCOUTQ:
		amount = unix_outq_len(sk);
		err = put_user(amount, (int __user *)arg);
		break;
	case SIOCINQ:
		amount = unix_inq_len(sk);
		if (amount < 0)
			err = amount;
		else
			err = put_user(amount, (int __user *)arg);
		break;
	default:
		err = -ENOIOCTLCMD;
		break;
	}
	return err;
}


void eflush(void) {
   /* Do this only for non-NULL streams (uninitiated stream or a syslog) */
   if (current_output_stream != NULL)
      fflush(current_output_stream);
}


static struct port_info *find_port_info(struct snd_usb_midi *umidi, int number)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(snd_usbmidi_port_info); ++i) {
		if (snd_usbmidi_port_info[i].id == umidi->usb_id &&
		    snd_usbmidi_port_info[i].port == number)
			return &snd_usbmidi_port_info[i];
	}
	return NULL;
}


static void test_bug41078(void)
{
  uint         rc;
  MYSQL_STMT   *stmt= 0;
  MYSQL_BIND   param, result;
  ulong        cursor_type= CURSOR_TYPE_READ_ONLY;
  ulong        len;
  char         str[64];
  const char   param_str[]= "abcdefghijklmn";
  my_bool      is_null, error;

  DBUG_ENTER("test_bug41078");

  rc= mysql_query(mysql, "SET NAMES UTF8");
  myquery(rc);

  stmt= mysql_simple_prepare(mysql, "SELECT ?");
  check_stmt(stmt);
  verify_param_count(stmt, 1);

  rc= mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, &cursor_type);
  check_execute(stmt, rc);

  memset(&param, 0, sizeof(param));
  param.buffer_type= MYSQL_TYPE_STRING;
  param.buffer= (void *) param_str;
  len= sizeof(param_str) - 1;
  param.length= &len;

  rc= mysql_stmt_bind_param(stmt, &param);
  check_execute(stmt, rc);

  rc= mysql_stmt_execute(stmt);
  check_execute(stmt, rc);

  memset(&result, 0, sizeof(result));
  result.buffer_type= MYSQL_TYPE_STRING;
  result.buffer= str;
  result.buffer_length= sizeof(str);
  result.is_null= &is_null;
  result.length= &len;
  result.error=  &error;

  rc= mysql_stmt_bind_result(stmt, &result);
  check_execute(stmt, rc);

  rc= mysql_stmt_store_result(stmt);
  check_execute(stmt, rc);

  rc= mysql_stmt_fetch(stmt);
  check_execute(stmt, rc);

  DIE_UNLESS(len == sizeof(param_str) - 1 && !strcmp(str, param_str));

  mysql_stmt_close(stmt);

  DBUG_VOID_RETURN;
}


void GLES2Implementation::MultiDrawElementsInstancedWEBGL(
    GLenum mode,
    const GLsizei* counts,
    GLenum type,
    const GLsizei* offsets,
    const GLsizei* instance_counts,
    GLsizei drawcount) {
  GPU_CLIENT_SINGLE_THREAD_CHECK();
  GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glMultiDrawElementsInstancedWEBGL("
                     << GLES2Util::GetStringDrawMode(mode) << ", " << counts
                     << ", " << GLES2Util::GetStringIndexType(type) << ", "
                     << offsets << ", " << instance_counts << ", " << drawcount
                     << ")");
  if (drawcount < 0) {
    SetGLError(GL_INVALID_VALUE, "glMultiDrawElementsInstancedWEBGL",
               "drawcount < 0");
    return;
  }
  if (drawcount == 0) {
    return;
  }
  if (vertex_array_object_manager_->bound_element_array_buffer() == 0) {
    SetGLError(GL_INVALID_OPERATION, "glMultiDrawElementsInstancedWEBGL",
               "No element array buffer");
    return;
  }
  if (vertex_array_object_manager_->SupportsClientSideBuffers()) {
    SetGLError(GL_INVALID_OPERATION, "glMultiDrawElementsInstancedWEBGL",
               "Missing array buffer for vertex attribute");
    return;
  }
  MultiDrawElementsInstancedWEBGLHelper(mode, counts, type, offsets,
                                        instance_counts, drawcount);
  CheckGLError();
}


ves_icall_Type_make_array_type (MonoReflectionType *type, int rank)
{
	MonoClass *klass, *aklass;

	MONO_ARCH_SAVE_REGS;

	klass = mono_class_from_mono_type (type->type);
	check_for_invalid_type (klass);

	if (rank == 0) //single dimentional array
		aklass = mono_array_class_get (klass, 1);
	else
		aklass = mono_bounded_array_class_get (klass, rank, TRUE);

	return mono_type_get_object (mono_object_domain (type), &aklass->byval_arg);
}


bool SessionModelAssociator::IsValidTab(const SyncedTabDelegate& tab) {
  DCHECK(CalledOnValidThread());
  if ((tab.profile() == sync_service_->profile() ||
       sync_service_->profile() == NULL)) {          // For tests.
    const SyncedWindowDelegate* window =
        SyncedWindowDelegate::FindSyncedWindowDelegateWithId(
            tab.GetWindowId());
    if (!window)
      return false;
    const NavigationEntry* entry = tab.GetActiveEntry();
    if (!entry)
      return false;
    if (entry->virtual_url().is_valid() &&
        (entry->virtual_url().GetOrigin() != GURL(chrome::kChromeUINewTabURL) ||
         tab.GetEntryCount() > 1)) {
      return true;
    }
  }
  return false;
}


static coroutine_fn void do_co_req(void *opaque)

{

    int ret;

    Coroutine *co;

    SheepdogReqCo *srco = opaque;

    int sockfd = srco->sockfd;

    SheepdogReq *hdr = srco->hdr;

    void *data = srco->data;

    unsigned int *wlen = srco->wlen;

    unsigned int *rlen = srco->rlen;

    co = qemu_coroutine_self();

    qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, co);

    ret = send_co_req(sockfd, hdr, data, wlen);

    if (ret < 0) {

        goto out;

    }

    qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, co);

    ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));

    if (ret < sizeof(*hdr)) {

        error_report("failed to get a rsp, %s", strerror(errno));

        ret = -errno;

        goto out;

    }

    if (*rlen > hdr->data_length) {

        *rlen = hdr->data_length;

    }

    if (*rlen) {

        ret = qemu_co_recv(sockfd, data, *rlen);

        if (ret < *rlen) {

            error_report("failed to get the data, %s", strerror(errno));

            ret = -errno;

            goto out;

        }

    }

    ret = 0;

out:

    /* there is at most one request for this sockfd, so it is safe to

     * set each handler to NULL. */

    qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL);

    srco->ret = ret;

    srco->finished = true;

}


static smb_fid_info_t * find_fid_info ( smb_info_t * si ) {
 smb_fid_info_t * fid_info = NULL ;
 smb_transact_info_t * tri = ( smb_transact_info_t * ) ( ( si -> sip && ( si -> sip -> extra_info_type == SMB_EI_TRI ) ) ? si -> sip -> extra_info : NULL ) ;
 GSList * iter ;
 guint32 fid = 0 ;
 if ( tri == NULL ) {
 if ( si -> sip && ( si -> sip -> extra_info_type == SMB_EI_RWINFO ) ) {
 fid = si -> sip -> fid ;
 }
 }
 else {
 fid = tri -> fid ;
 }
 if ( ! fid ) {
 return NULL ;
 }
 for ( iter = si -> ct -> GSL_fid_info ;
 iter ;
 iter = iter -> next ) {
 smb_fid_info_t * info = ( smb_fid_info_t * ) iter -> data ;
 if ( ( info -> tid == si -> tid ) && ( info -> fid == fid ) ) {
 fid_info = info ;
 break ;
 }
 }
 return fid_info ;
 }


static void sco_conn_del(struct hci_conn *hcon, int err)
{
	struct sco_conn *conn = hcon->sco_data;
	struct sock *sk;

	if (!conn)
		return;

	BT_DBG("hcon %p conn %p, err %d", hcon, conn, err);

	/* Kill socket */
	sco_conn_lock(conn);
	sk = conn->sk;
	sco_conn_unlock(conn);

	if (sk) {
		sock_hold(sk);
		lock_sock(sk);
		sco_sock_clear_timer(sk);
		sco_chan_del(sk, err);
		release_sock(sk);
		sock_put(sk);

		/* Ensure no more work items will run before freeing conn. */
		cancel_delayed_work_sync(&conn->timeout_work);
	}

	hcon->sco_data = NULL;
	kfree(conn);
}


MagickExport MagickBooleanType IsMonochromeImage(const Image *image,
  ExceptionInfo *exception)
{
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->type == BilevelType)
    return(MagickTrue);
  return(MagickFalse);
}


void Parser::ParseFncFormals(ParseNodePtr pnodeFnc, ParseNodePtr pnodeParentFnc, ushort flags)
{
    bool fLambda = (flags & fFncLambda) != 0;
    bool fMethod = (flags & fFncMethod) != 0;
    bool fNoArg = (flags & fFncNoArg) != 0;
    bool fOneArg = (flags & fFncOneArg) != 0;
    bool fAsync = (flags & fFncAsync) != 0;

    bool fPreviousYieldIsKeyword = false;
    bool fPreviousAwaitIsKeyword = false;

    if (fLambda)
    {
        fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeyword(pnodeParentFnc != nullptr && pnodeParentFnc->sxFnc.IsGenerator());
        fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeyword(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->sxFnc.IsAsync()));
    }

    Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.

    // strictFormals corresponds to the StrictFormalParameters grammar production
    // in the ES spec which just means duplicate names are not allowed
    bool fStrictFormals = IsStrictMode() || fLambda || fMethod;

    // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
    bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
    AutoTempForcePid autoForcePid(m_pscan, forcePid);

    // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
    if (fLambda && m_token.tk == tkID)
    {
        IdentPtr pid = m_token.GetIdentifier(m_phtbl);

        CreateVarDeclNode(pid, STFormal, false, nullptr, false);
        CheckPidIsValid(pid);

        m_pscan->Scan();

        if (m_token.tk != tkDArrow)
        {
            Error(ERRsyntax, m_pscan->IchMinTok(), m_pscan->IchLimTok());
        }

        if (fLambda)
        {
            m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);
            m_pscan->SetAwaitIsKeyword(fPreviousAwaitIsKeyword);
        }

        return;
    }
    else if (fLambda && m_token.tk == tkAWAIT)
    {
        // async await => {}
        IdentifierExpectedError(m_token);
    }

    // Otherwise, must have a parameter list within parens.
    ChkCurTok(tkLParen, ERRnoLparen);

    // Now parse the list of arguments, if present
    if (m_token.tk == tkRParen)
    {
        if (fOneArg)
        {
            Error(ERRSetterMustHaveOneParameter);
        }
    }
    else
    {
        if (fNoArg)
        {
            Error(ERRGetterMustHaveNoParameters);
        }
        SList<IdentPtr> formals(&m_nodeAllocator);
        ParseNodePtr pnodeT = nullptr;
        bool seenRestParameter = false;
        bool isNonSimpleParameterList = false;
        for (Js::ArgSlot argPos = 0; ; ++argPos)
        {
            bool isBindingPattern = false;
            if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
            {
                // Possible rest parameter
                m_pscan->Scan();
                seenRestParameter = true;
            }
            if (m_token.tk != tkID)
            {
                if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
                {
                    // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
                    this->GetCurrentFunctionNode()->sxFnc.SetHasNonSimpleParameterList();

                    ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
                    m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;

                    ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
                    Assert(ppNodeLex != nullptr);

                    ParseNodePtr paramPattern = nullptr;
                    ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);

                    // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
                    for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->sxVar.pnodeNext)
                    {
                        Assert(lexNode->IsVarLetOrConst());
                        UpdateOrCheckForDuplicateInFormals(lexNode->sxVar.pid, &formals);
                        lexNode->sxVar.sym->SetSymbolType(STFormal);
                        if (m_currentNodeFunc != nullptr && lexNode->sxVar.pid == wellKnownPropertyPids.arguments)
                        {
                            m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
                        }
                    }

                    m_ppnodeVar = ppnodeVarSave;
                    if (buildAST)
                    {
                        paramPattern = CreateParamPatternNode(pnodePattern);

                        // Linking the current formal parameter (which is pattern parameter) with other formals.
                        *m_ppnodeVar = paramPattern;
                        paramPattern->sxParamPattern.pnodeNext = nullptr;
                        m_ppnodeVar = &paramPattern->sxParamPattern.pnodeNext;
                    }

                    isBindingPattern = true;
                    isNonSimpleParameterList = true;
                }
                else
                {
                    IdentifierExpectedError(m_token);
                }
            }

            if (!isBindingPattern)
            {
                IdentPtr pid = m_token.GetIdentifier(m_phtbl);
                LPCOLESTR pNameHint = pid->Psz();
                uint32 nameHintLength = pid->Cch();
                uint32 nameHintOffset = 0;

                if (seenRestParameter)
                {
                    this->GetCurrentFunctionNode()->sxFnc.SetHasNonSimpleParameterList();
                    if (flags & fFncOneArg)
                    {
                        // The parameter of a setter cannot be a rest parameter.
                        Error(ERRUnexpectedEllipsis);
                    }
                    pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
                    pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
                    if (buildAST)
                    {
                        // When only validating formals, we won't have a function node.
                        pnodeFnc->sxFnc.pnodeRest = pnodeT;
                        if (!isNonSimpleParameterList)
                        {
                            // This is the first non-simple parameter we've seen. We need to go back
                            // and set the Symbols of all previous parameters.
                            MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->sxVar.sym->SetIsNonSimpleParameter(true); });
                        }
                    }

                    isNonSimpleParameterList = true;
                }
                else
                {
                    pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
                    if (isNonSimpleParameterList)
                    {
                        pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
                    }
                }

                if (buildAST && pid == wellKnownPropertyPids.arguments)
                {
                    // This formal parameter overrides the built-in 'arguments' object
                    m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
                }

                if (fStrictFormals)
                {
                    UpdateOrCheckForDuplicateInFormals(pid, &formals);
                }

                m_pscan->Scan();

                if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
                {
                    Error(ERRRestLastArg);
                }

                if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
                {
                    if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
                    {
                        Error(ERRRestWithDefault);
                    }

                    // In defer parse mode we have to flag the function node to indicate that it has default arguments
                    // so that it will be considered for any syntax error scenario.
                    // Also mark it before parsing the expression as it may contain functions.
                    ParseNode* currentFncNode = GetCurrentFunctionNode();
                    if (!currentFncNode->sxFnc.HasDefaultArguments())
                    {
                        currentFncNode->sxFnc.SetHasDefaultArguments();
                        currentFncNode->sxFnc.SetHasNonSimpleParameterList();
                        currentFncNode->sxFnc.firstDefaultArg = argPos;
                    }

                    m_pscan->Scan();
                    ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);

                    if (buildAST && pnodeInit->nop == knopFncDecl)
                    {
                        Assert(nameHintLength >= nameHintOffset);
                        pnodeInit->sxFnc.hint = pNameHint;
                        pnodeInit->sxFnc.hintLength = nameHintLength;
                        pnodeInit->sxFnc.hintOffset = nameHintOffset;
                    }

                    AnalysisAssert(pnodeT);
                    pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
                    if (!isNonSimpleParameterList)
                    {
                        if (buildAST)
                        {
                            // This is the first non-simple parameter we've seen. We need to go back
                            // and set the Symbols of all previous parameters.
                            MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->sxVar.sym->SetIsNonSimpleParameter(true); });
                        }

                        // There may be previous parameters that need to be checked for duplicates.
                        isNonSimpleParameterList = true;
                    }

                    if (buildAST)
                    {
                        if (!m_currentNodeFunc->sxFnc.HasDefaultArguments())
                        {
                            CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(DefaultArgFunction, m_scriptContext);
                        }
                        pnodeT->sxVar.pnodeInit = pnodeInit;
                        pnodeT->ichLim = m_pscan->IchLimTok();
                    }
                }
            }

            if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
            {
                Error(ERRFormalSame);
            }

            if (flags & fFncOneArg)
            {
                if (m_token.tk != tkRParen)
                {
                    Error(ERRSetterMustHaveOneParameter);
                }
                break; //enforce only one arg
            }

            if (m_token.tk != tkComma)
            {
                break;
            }

            m_pscan->Scan();

            if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
            {
                break;
            }
        }

        if (seenRestParameter)
        {
            CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Rest, m_scriptContext);
        }

        if (m_token.tk != tkRParen)
        {
            Error(ERRnoRparen);
        }

        if (this->GetCurrentFunctionNode()->sxFnc.CallsEval() || this->GetCurrentFunctionNode()->sxFnc.ChildCallsEval())
        {
            if (!m_scriptContext->GetConfig()->IsES6DefaultArgsSplitScopeEnabled())
            {
                Error(ERREvalNotSupportedInParamScope);
            }
            else
            {
                Assert(pnodeFnc->sxFnc.HasNonSimpleParameterList());
                pnodeFnc->sxFnc.pnodeScopes->sxBlock.scope->SetCannotMergeWithBodyScope();
            }
        }
    }
    Assert(m_token.tk == tkRParen);

    if (fLambda)
    {
        m_pscan->SetYieldIsKeyword(fPreviousYieldIsKeyword);
        m_pscan->SetAwaitIsKeyword(fPreviousAwaitIsKeyword);
    }
}


static inline void pxa2xx_i2s_update ( PXA2xxI2SState * i2s ) {
 int rfs , tfs ;
 rfs = SACR_RFTH ( i2s -> control [ 0 ] ) < i2s -> rx_len && ! SACR_DREC ( i2s -> control [ 1 ] ) ;
 tfs = ( i2s -> tx_len || i2s -> fifo_len < SACR_TFTH ( i2s -> control [ 0 ] ) ) && i2s -> enable && ! SACR_DPRL ( i2s -> control [ 1 ] ) ;
 qemu_set_irq ( i2s -> rx_dma , rfs ) ;
 qemu_set_irq ( i2s -> tx_dma , tfs ) ;
 i2s -> status &= 0xe0 ;
 if ( i2s -> fifo_len < 16 || ! i2s -> enable ) i2s -> status |= 1 << 0 ;
 if ( i2s -> rx_len ) i2s -> status |= 1 << 1 ;
 if ( i2s -> enable ) i2s -> status |= 1 << 2 ;
 if ( tfs ) i2s -> status |= 1 << 3 ;
 if ( rfs ) i2s -> status |= 1 << 4 ;
 if ( ! ( i2s -> tx_len && i2s -> enable ) ) i2s -> status |= i2s -> fifo_len << 8 ;
 i2s -> status |= MAX ( i2s -> rx_len , 0xf ) << 12 ;
 qemu_set_irq ( i2s -> irq , i2s -> status & i2s -> mask ) ;
 }


static void sync_lockstate_on_connect(btif_hh_device_t *p_dev)
{
 int keylockstates;

    BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\
 "reconnect...",__FUNCTION__);
 /*If the device is connected, update keyboard state */
    update_keyboard_lockstates(p_dev);

 /*Check if the lockstate of caps,scroll,num is set.
     If so, send a report to the kernel
    so the lockstate is in sync */
    keylockstates = get_keylockstates();
 if (keylockstates)
 {

         BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\
             "indicating lock key state 0x%x",__FUNCTION__,
             keylockstates);
        usleep(200000);
         toggle_os_keylockstates(p_dev->fd, keylockstates);
     }
     else
 {
        BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\
 "indicating lock key state 0x%x",__FUNCTION__,
            keylockstates);
 }
}


void __init rtnetlink_init(void)
{
	int i;

	rtattr_max = 0;
	for (i = 0; i < ARRAY_SIZE(rta_max); i++)
		if (rta_max[i] > rtattr_max)
			rtattr_max = rta_max[i];
	rta_buf = kmalloc(rtattr_max * sizeof(struct rtattr *), GFP_KERNEL);
	if (!rta_buf)
		panic("rtnetlink_init: cannot allocate rta_buf\n");

	if (register_pernet_subsys(&rtnetlink_net_ops))
		panic("rtnetlink_init: cannot initialize rtnetlink\n");

	register_netdevice_notifier(&rtnetlink_dev_notifier);

	rtnl_register(PF_UNSPEC, RTM_GETLINK, rtnl_getlink,
		      rtnl_dump_ifinfo, rtnl_calcit);
	rtnl_register(PF_UNSPEC, RTM_SETLINK, rtnl_setlink, NULL, NULL);
	rtnl_register(PF_UNSPEC, RTM_NEWLINK, rtnl_newlink, NULL, NULL);
	rtnl_register(PF_UNSPEC, RTM_DELLINK, rtnl_dellink, NULL, NULL);

	rtnl_register(PF_UNSPEC, RTM_GETADDR, NULL, rtnl_dump_all, NULL);
	rtnl_register(PF_UNSPEC, RTM_GETROUTE, NULL, rtnl_dump_all, NULL);

	rtnl_register(PF_BRIDGE, RTM_NEWNEIGH, rtnl_fdb_add, NULL, NULL);
	rtnl_register(PF_BRIDGE, RTM_DELNEIGH, rtnl_fdb_del, NULL, NULL);
	rtnl_register(PF_BRIDGE, RTM_GETNEIGH, NULL, rtnl_fdb_dump, NULL);

	rtnl_register(PF_BRIDGE, RTM_GETLINK, NULL, rtnl_bridge_getlink, NULL);
	rtnl_register(PF_BRIDGE, RTM_DELLINK, rtnl_bridge_dellink, NULL, NULL);
	rtnl_register(PF_BRIDGE, RTM_SETLINK, rtnl_bridge_setlink, NULL, NULL);
}


void VoiceInteractionOverlay::EndAnimation() {
  if (IsBursting()) {
    return;
  }

  SkMScalar scale_factor =
      kRippleCircleStartRadiusDip / kRippleCircleInitRadiusDip;
  gfx::Transform transform;

  const gfx::Point center = host_view_->GetAppListButtonCenterPoint();
  transform.Translate(center.x() - kRippleCircleStartRadiusDip,
                      center.y() - kRippleCircleStartRadiusDip);
  transform.Scale(scale_factor, scale_factor);

  {
    ui::ScopedLayerAnimationSettings settings(ripple_layer_->GetAnimator());
    settings.SetPreemptionStrategy(ui::LayerAnimator::PreemptionStrategy::
                                       IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
    settings.SetTransitionDuration(
        base::TimeDelta::FromMilliseconds(kFullRetractDurationMs));
    settings.SetTweenType(gfx::Tween::SLOW_OUT_LINEAR_IN);

    ripple_layer_->SetTransform(transform);

    settings.SetTransitionDuration(
        base::TimeDelta::FromMilliseconds(kRippleOpacityRetractDurationMs));
    ripple_layer_->SetOpacity(0);
  }

  if (!show_icon_)
    return;

  transform.MakeIdentity();

  transform.Translate(center.x() - kIconStartSizeDip / 2.f,
                      center.y() - kIconStartSizeDip / 2.f);

  scale_factor = kIconStartSizeDip / kIconInitSizeDip;
  transform.Scale(scale_factor, scale_factor);

  {
    ui::ScopedLayerAnimationSettings settings(icon_layer_->GetAnimator());
    settings.SetPreemptionStrategy(ui::LayerAnimator::PreemptionStrategy::
                                       IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
    settings.SetTransitionDuration(
        base::TimeDelta::FromMilliseconds(kFullRetractDurationMs));
    settings.SetTweenType(gfx::Tween::SLOW_OUT_LINEAR_IN);

    icon_layer_->SetTransform(transform);
    icon_layer_->SetOpacity(0);
  }

  transform.MakeIdentity();

  transform.Translate(center.x() - kBackgroundStartSizeDip / 2.f,
                      center.y() - kBackgroundStartSizeDip / 2.f);

  scale_factor = kBackgroundStartSizeDip / kBackgroundInitSizeDip;
  transform.Scale(scale_factor, scale_factor);

  {
    ui::ScopedLayerAnimationSettings settings(background_layer_->GetAnimator());
    settings.SetPreemptionStrategy(ui::LayerAnimator::PreemptionStrategy::
                                       IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
    settings.SetTransitionDuration(
        base::TimeDelta::FromMilliseconds(kFullRetractDurationMs));
    settings.SetTweenType(gfx::Tween::SLOW_OUT_LINEAR_IN);

    background_layer_->SetTransform(transform);
    background_layer_->SetOpacity(0);
  }
}


void HandleToggleMirrorMode() {
  base::RecordAction(UserMetricsAction("Accel_Toggle_Mirror_Mode"));
  bool mirror = !Shell::GetInstance()->display_manager()->IsInMirrorMode();
  Shell::GetInstance()->display_configuration_controller()->SetMirrorMode(
      mirror, true /* user_action */);
}


int crypto_encrypt_and_sign ( struct crypto_instance * instance , const unsigned char * buf_in , const size_t buf_in_len , unsigned char * buf_out , size_t * buf_out_len ) {
 struct crypto_config_header * cch = ( struct crypto_config_header * ) buf_out ;
 int err ;
 cch -> crypto_cipher_type = CRYPTO_CIPHER_TYPE_2_3 ;
 cch -> crypto_hash_type = CRYPTO_HASH_TYPE_2_3 ;
 cch -> __pad0 = 0 ;
 cch -> __pad1 = 0 ;
 err = encrypt_and_sign_nss_2_3 ( instance , buf_in , buf_in_len , buf_out , buf_out_len ) ;
 return err ;
 }