static int ffserver_parse_config_stream(FFServerConfig *config, const char *cmd, const char **p,

                                        int line_num, FFServerStream **pstream)

{

    char arg[1024], arg2[1024];

    FFServerStream *stream;

    int val;

    av_assert0(pstream);

    stream = *pstream;

    if (!av_strcasecmp(cmd, "<Stream")) {

        char *q;

        FFServerStream *s;

        stream = av_mallocz(sizeof(FFServerStream));

        if (!stream)

            return AVERROR(ENOMEM);

        config->dummy_actx = avcodec_alloc_context3(NULL);

        config->dummy_vctx = avcodec_alloc_context3(NULL);

        if (!config->dummy_vctx || !config->dummy_actx) {

            av_free(stream);

            avcodec_free_context(&config->dummy_vctx);

            avcodec_free_context(&config->dummy_actx);

            return AVERROR(ENOMEM);

        }

        config->dummy_actx->codec_type = AVMEDIA_TYPE_AUDIO;

        config->dummy_vctx->codec_type = AVMEDIA_TYPE_VIDEO;

        ffserver_get_arg(stream->filename, sizeof(stream->filename), p);

        q = strrchr(stream->filename, '>');

        if (q)

            *q = '\0';

        for (s = config->first_stream; s; s = s->next) {

            if (!strcmp(stream->filename, s->filename))

                ERROR("Stream '%s' already registered\n", s->filename);

        }

        stream->fmt = ffserver_guess_format(NULL, stream->filename, NULL);

        if (stream->fmt) {

            config->guessed_audio_codec_id = stream->fmt->audio_codec;

            config->guessed_video_codec_id = stream->fmt->video_codec;

        } else {

            config->guessed_audio_codec_id = AV_CODEC_ID_NONE;

            config->guessed_video_codec_id = AV_CODEC_ID_NONE;

        }

        *pstream = stream;

        return 0;

    }

    av_assert0(stream);

    if (!av_strcasecmp(cmd, "Feed")) {

        FFServerStream *sfeed;

        ffserver_get_arg(arg, sizeof(arg), p);

        sfeed = config->first_feed;

        while (sfeed) {

            if (!strcmp(sfeed->filename, arg))

                break;

            sfeed = sfeed->next_feed;

        }

        if (!sfeed)

            ERROR("Feed with name '%s' for stream '%s' is not defined\n", arg,

                    stream->filename);

        else

            stream->feed = sfeed;

    } else if (!av_strcasecmp(cmd, "Format")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (!strcmp(arg, "status")) {

            stream->stream_type = STREAM_TYPE_STATUS;

            stream->fmt = NULL;

        } else {

            stream->stream_type = STREAM_TYPE_LIVE;

            /* JPEG cannot be used here, so use single frame MJPEG */

            if (!strcmp(arg, "jpeg"))

                strcpy(arg, "mjpeg");

            stream->fmt = ffserver_guess_format(arg, NULL, NULL);

            if (!stream->fmt)

                ERROR("Unknown Format: %s\n", arg);

        }

        if (stream->fmt) {

            config->guessed_audio_codec_id = stream->fmt->audio_codec;

            config->guessed_video_codec_id = stream->fmt->video_codec;

        }

    } else if (!av_strcasecmp(cmd, "InputFormat")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        stream->ifmt = av_find_input_format(arg);

        if (!stream->ifmt)

            ERROR("Unknown input format: %s\n", arg);

    } else if (!av_strcasecmp(cmd, "FaviconURL")) {

        if (stream->stream_type == STREAM_TYPE_STATUS)

            ffserver_get_arg(stream->feed_filename,

                    sizeof(stream->feed_filename), p);

        else

            ERROR("FaviconURL only permitted for status streams\n");

    } else if (!av_strcasecmp(cmd, "Author")    ||

               !av_strcasecmp(cmd, "Comment")   ||

               !av_strcasecmp(cmd, "Copyright") ||

               !av_strcasecmp(cmd, "Title")) {

        char key[32];

        int i;

        ffserver_get_arg(arg, sizeof(arg), p);

        for (i = 0; i < strlen(cmd); i++)

            key[i] = av_tolower(cmd[i]);

        key[i] = 0;

        WARNING("'%s' option in configuration file is deprecated, "

                "use 'Metadata %s VALUE' instead\n", cmd, key);

        if (av_dict_set(&stream->metadata, key, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Metadata")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_get_arg(arg2, sizeof(arg2), p);

        if (av_dict_set(&stream->metadata, arg, arg2, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Preroll")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        stream->prebuffer = atof(arg) * 1000;

    } else if (!av_strcasecmp(cmd, "StartSendOnKey")) {

        stream->send_on_key = 1;

    } else if (!av_strcasecmp(cmd, "AudioCodec")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_codec(config->dummy_actx, arg, config, line_num);

    } else if (!av_strcasecmp(cmd, "VideoCodec")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_codec(config->dummy_vctx, arg, config, line_num);

    } else if (!av_strcasecmp(cmd, "MaxTime")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        stream->max_time = atof(arg) * 1000;

    } else if (!av_strcasecmp(cmd, "AudioBitRate")) {

        float f;

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_float_param(&f, arg, 1000, 0, FLT_MAX, config, line_num,

                "Invalid %s: %s\n", cmd, arg);

        if (av_dict_set_int(&config->audio_conf, cmd, lrintf(f), 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AudioChannels")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 8, config, line_num,

                "Invalid %s: %s, valid range is 1-8.", cmd, arg);

        if (av_dict_set(&config->audio_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AudioSampleRate")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 0, INT_MAX, config, line_num,

                "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->audio_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBitRateRange")) {

        int minrate, maxrate;

        ffserver_get_arg(arg, sizeof(arg), p);

        if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {

            if (av_dict_set_int(&config->video_conf, "VideoBitRateRangeMin", minrate, 0) < 0 ||

                av_dict_set_int(&config->video_conf, "VideoBitRateRangeMax", maxrate, 0) < 0)

                goto nomem;

        } else

            ERROR("Incorrect format for VideoBitRateRange -- should be "

                    "<min>-<max>: %s\n", arg);

    } else if (!av_strcasecmp(cmd, "Debug")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, INT_MIN, INT_MAX, config, line_num,

                "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Strict")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, INT_MIN, INT_MAX, config, line_num,

                "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBufferSize")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 8*1024, 0, INT_MAX, config, line_num,

                "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBitRateTolerance")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 1000, INT_MIN, INT_MAX, config,

                line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBitRate")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 1000, 0, INT_MAX, config, line_num,

                "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

           goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoSize")) {

        int ret, w, h;

        ffserver_get_arg(arg, sizeof(arg), p);

        ret = av_parse_video_size(&w, &h, arg);

        if (ret < 0)

            ERROR("Invalid video size '%s'\n", arg);

        else if ((w % 2) || (h % 2))

            WARNING("Image size is not a multiple of 2\n");

        if (av_dict_set_int(&config->video_conf, "VideoSizeWidth", w, 0) < 0 ||

            av_dict_set_int(&config->video_conf, "VideoSizeHeight", h, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoFrameRate")) {

        AVRational frame_rate;

        ffserver_get_arg(arg, sizeof(arg), p);

        if (av_parse_video_rate(&frame_rate, arg) < 0) {

            ERROR("Incorrect frame rate: %s\n", arg);

        } else {

            if (av_dict_set_int(&config->video_conf, "VideoFrameRateNum", frame_rate.num, 0) < 0 ||

                av_dict_set_int(&config->video_conf, "VideoFrameRateDen", frame_rate.den, 0) < 0)

                goto nomem;

        }

    } else if (!av_strcasecmp(cmd, "PixelFormat")) {

        enum AVPixelFormat pix_fmt;

        ffserver_get_arg(arg, sizeof(arg), p);

        pix_fmt = av_get_pix_fmt(arg);

        if (pix_fmt == AV_PIX_FMT_NONE)

            ERROR("Unknown pixel format: %s\n", arg);

        if (av_dict_set_int(&config->video_conf, cmd, pix_fmt, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoGopSize")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, INT_MIN, INT_MAX, config, line_num,

                "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoIntraOnly")) {

        if (av_dict_set(&config->video_conf, cmd, "1", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoHighQuality")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Video4MotionVector")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AVOptionVideo") ||

               !av_strcasecmp(cmd, "AVOptionAudio")) {

        int ret;

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_get_arg(arg2, sizeof(arg2), p);

        if (!av_strcasecmp(cmd, "AVOptionVideo"))

            ret = ffserver_save_avoption(config->dummy_vctx, arg, arg2, &config->video_opts,

                                         AV_OPT_FLAG_VIDEO_PARAM ,config, line_num);

        else

            ret = ffserver_save_avoption(config->dummy_actx, arg, arg2, &config->audio_opts,

                                         AV_OPT_FLAG_AUDIO_PARAM ,config, line_num);

        if (ret < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AVPresetVideo") ||

               !av_strcasecmp(cmd, "AVPresetAudio")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (!av_strcasecmp(cmd, "AVPresetVideo"))

            ffserver_opt_preset(arg, config->dummy_vctx, config, line_num);

        else

            ffserver_opt_preset(arg, config->dummy_actx, config, line_num);

    } else if (!av_strcasecmp(cmd, "VideoTag")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (strlen(arg) == 4) {

            if (av_dict_set(&config->video_conf, "VideoTag", "arg", 0) < 0)

                goto nomem;

        }

    } else if (!av_strcasecmp(cmd, "BitExact")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "DctFastint")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "IdctSimple")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Qscale")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoQDiff")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 31, config, line_num,

                "%s out of range\n", cmd);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoQMax")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 31, config, line_num,

                "%s out of range\n", cmd);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoQMin")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 31, config, line_num,

                "%s out of range\n", cmd);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "LumiMask")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_float_param(NULL, arg, 0, -FLT_MAX, FLT_MAX, config,

                line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "DarkMask")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_float_param(NULL, arg, 0, -FLT_MAX, FLT_MAX, config,

                line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "NoVideo")) {

        config->no_video = 1;

    } else if (!av_strcasecmp(cmd, "NoAudio")) {

        config->no_audio = 1;

    } else if (!av_strcasecmp(cmd, "ACL")) {

        ffserver_parse_acl_row(stream, NULL, NULL, *p, config->filename,

                line_num);

    } else if (!av_strcasecmp(cmd, "DynamicACL")) {

        ffserver_get_arg(stream->dynamic_acl, sizeof(stream->dynamic_acl), p);

    } else if (!av_strcasecmp(cmd, "RTSPOption")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        av_freep(&stream->rtsp_option);

        stream->rtsp_option = av_strdup(arg);

    } else if (!av_strcasecmp(cmd, "MulticastAddress")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (resolve_host(&stream->multicast_ip, arg))

            ERROR("Invalid host/IP address: %s\n", arg);

        stream->is_multicast = 1;

        stream->loop = 1; /* default is looping */

    } else if (!av_strcasecmp(cmd, "MulticastPort")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(&val, arg, 0, 1, 65535, config, line_num,

                "Invalid MulticastPort: %s\n", arg);

        stream->multicast_port = val;

    } else if (!av_strcasecmp(cmd, "MulticastTTL")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(&val, arg, 0, INT_MIN, INT_MAX, config,

                line_num, "Invalid MulticastTTL: %s\n", arg);

        stream->multicast_ttl = val;

    } else if (!av_strcasecmp(cmd, "NoLoop")) {

        stream->loop = 0;

    } else if (!av_strcasecmp(cmd, "</Stream>")) {

        if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm")) {

            if (config->dummy_actx->codec_id == AV_CODEC_ID_NONE)

                config->dummy_actx->codec_id = config->guessed_audio_codec_id;

            if (!config->no_audio && config->dummy_actx->codec_id != AV_CODEC_ID_NONE) {

                AVCodecContext *audio_enc = avcodec_alloc_context3(avcodec_find_encoder(config->dummy_actx->codec_id));

                ffserver_apply_stream_config(audio_enc, config->audio_conf, &config->audio_opts);

                add_codec(stream, audio_enc);

            }

            if (config->dummy_vctx->codec_id == AV_CODEC_ID_NONE)

                config->dummy_vctx->codec_id = config->guessed_video_codec_id;

            if (!config->no_video && config->dummy_vctx->codec_id != AV_CODEC_ID_NONE) {

                AVCodecContext *video_enc = avcodec_alloc_context3(avcodec_find_encoder(config->dummy_vctx->codec_id));

                ffserver_apply_stream_config(video_enc, config->video_conf, &config->video_opts);

                add_codec(stream, video_enc);

            }

        }

        av_dict_free(&config->video_opts);

        av_dict_free(&config->video_conf);

        av_dict_free(&config->audio_opts);

        av_dict_free(&config->audio_conf);

        avcodec_free_context(&config->dummy_vctx);

        avcodec_free_context(&config->dummy_actx);

        *pstream = NULL;

    } else if (!av_strcasecmp(cmd, "File") || !av_strcasecmp(cmd, "ReadOnlyFile")) {

        ffserver_get_arg(stream->feed_filename, sizeof(stream->feed_filename),

                p);

    } else {

        ERROR("Invalid entry '%s' inside <Stream></Stream>\n", cmd);

    }

    return 0;

  nomem:

    av_log(NULL, AV_LOG_ERROR, "Out of memory. Aborting.\n");

    av_dict_free(&config->video_opts);

    av_dict_free(&config->video_conf);

    av_dict_free(&config->audio_opts);

    av_dict_free(&config->audio_conf);

    avcodec_free_context(&config->dummy_vctx);

    avcodec_free_context(&config->dummy_actx);

    return AVERROR(ENOMEM);

}


static jboolean android_net_wifi_start_logging_ring_buffer(JNIEnv *env, jclass cls, jint iface,
        jint verbose_level,jint flags, jint max_interval,jint min_data_size, jstring ring_name) {

 JNIHelper helper(env);
    wifi_interface_handle handle = getIfaceHandle(helper, cls, iface);

    ALOGD("android_net_wifi_start_logging_ring_buffer = %p", handle);

 if (handle == 0) {
 return false;
 }

 ScopedUtfChars chars(env, ring_name);
 const char* ring_name_const_char = chars.c_str();
 int ret = hal_fn.wifi_start_logging(handle, verbose_level,
            flags, max_interval, min_data_size, const_cast<char *>(ring_name_const_char));

 if (ret != WIFI_SUCCESS) {
        ALOGE("Fail to start logging for ring %s", ring_name_const_char);
 } else {
        ALOGD("start logging for ring %s", ring_name_const_char);
 }

 return ret == WIFI_SUCCESS;
}


static int rtc_ioctl(unsigned fd, unsigned cmd, void __user *argp)
{
	mm_segment_t oldfs = get_fs();
	compat_ulong_t val32;
	unsigned long kval;
	int ret;

	switch (cmd) {
	case RTC_IRQP_READ32:
	case RTC_EPOCH_READ32:
		set_fs(KERNEL_DS);
		ret = sys_ioctl(fd, (cmd == RTC_IRQP_READ32) ?
					RTC_IRQP_READ : RTC_EPOCH_READ,
					(unsigned long)&kval);
		set_fs(oldfs);
		if (ret)
			return ret;
		val32 = kval;
		return put_user(val32, (unsigned int __user *)argp);
	case RTC_IRQP_SET32:
		return sys_ioctl(fd, RTC_IRQP_SET, (unsigned long)argp);
	case RTC_EPOCH_SET32:
		return sys_ioctl(fd, RTC_EPOCH_SET, (unsigned long)argp);
	}

	return -ENOIOCTLCMD;
}


static void doInsertionSort ( char * array , int32_t length , int32_t itemSize , UComparator * cmp , const void * context , void * pv ) {
 int32_t j ;
 for ( j = 1 ;
 j < length ;
 ++ j ) {
 char * item = array + j * itemSize ;
 int32_t insertionPoint = uprv_stableBinarySearch ( array , j , item , itemSize , cmp , context ) ;
 if ( insertionPoint < 0 ) {
 insertionPoint = ~ insertionPoint ;
 }
 else {
 ++ insertionPoint ;
 }
 if ( insertionPoint < j ) {
 char * dest = array + insertionPoint * itemSize ;
 uprv_memcpy ( pv , item , itemSize ) ;
 uprv_memmove ( dest + itemSize , dest , ( j - insertionPoint ) * ( size_t ) itemSize ) ;
 uprv_memcpy ( dest , pv , itemSize ) ;
 }
 }
 }


nv_next(cmdarg_T *cap)
{
    pos_T   old = curwin->w_cursor;
    int	    wrapped = FALSE;
    int	    i = normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, &wrapped);

    if (i == 1 && !wrapped && EQUAL_POS(old, curwin->w_cursor))
    {
	// Avoid getting stuck on the current cursor position, which can
	// happen when an offset is given and the cursor is on the last char
	// in the buffer: Repeat with count + 1.
	cap->count1 += 1;
	(void)normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, NULL);
	cap->count1 -= 1;
    }

#ifdef FEAT_SEARCH_EXTRA
    // Redraw the window to refresh the highlighted matches.
    if (i > 0 && p_hls && !no_hlsearch)
	redraw_later(SOME_VALID);
#endif
}


int TSMimeHdrFieldLengthGet ( TSMBuffer bufp , TSMLoc hdr , TSMLoc field ) {
 sdk_assert ( sdk_sanity_check_mbuffer ( bufp ) == TS_SUCCESS ) ;
 sdk_assert ( ( sdk_sanity_check_mime_hdr_handle ( hdr ) == TS_SUCCESS ) || ( sdk_sanity_check_http_hdr_handle ( hdr ) == TS_SUCCESS ) ) ;
 sdk_assert ( sdk_sanity_check_field_handle ( field , hdr ) == TS_SUCCESS ) ;
 MIMEFieldSDKHandle * handle = ( MIMEFieldSDKHandle * ) field ;
 return mime_field_length_get ( handle -> field_ptr ) ;
 }


static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len,
                           int *resp)
{
  struct smtp_conn *smtpc = &conn->proto.smtpc;
  bool result = FALSE;

  /* Nothing for us */
  if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2]))
    return FALSE;

  /* Do we have a command response? This should be the response code followed
     by a space and optionally some text as per RFC-5321 and as outlined in
     Section 4. Examples of RFC-4954 but some e-mail servers ignore this and
     only send the response code instead as per Section 4.2. */
  if(line[3] == ' ' || len == 5) {
    result = TRUE;
    *resp = curlx_sltosi(strtol(line, NULL, 10));

    /* Make sure real server never sends internal value */
    if(*resp == 1)
      *resp = 0;
  }
  /* Do we have a multiline (continuation) response? */
  else if(line[3] == '-' &&
          (smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) {
    result = TRUE;
    *resp = 1;  /* Internal response code */
  }

  return result;
}


static int dissect_dns_query ( tvbuff_t * tvb , int offset , int dns_data_offset , column_info * cinfo , proto_tree * dns_tree , gboolean is_mdns ) {
 int len ;
 const guchar * name ;
 gchar * name_out ;
 int name_len ;
 int type ;
 int dns_class ;
 int qu ;
 const char * type_name ;
 int data_start ;
 guint16 labels ;
 proto_tree * q_tree ;
 proto_item * tq ;
 data_start = offset ;
 len = get_dns_name_type_class ( tvb , offset , dns_data_offset , & name , & name_len , & type , & dns_class ) ;
 if ( is_mdns ) {
 qu = dns_class & C_QU ;
 dns_class &= ~ C_QU ;
 }
 else {
 qu = 0 ;
 }
 type_name = val_to_str_ext ( type , & dns_types_vals_ext , "Unknown (%d)" ) ;
 name_out = format_text ( name , strlen ( name ) ) ;
 if ( cinfo != NULL ) {
 col_append_fstr ( cinfo , COL_INFO , "%s %s" , type_name , name_out ) ;
 if ( is_mdns ) {
 col_append_fstr ( cinfo , COL_INFO , ", \"%s\" question" , qu ? "QU" : "QM" ) ;
 }
 }
 if ( dns_tree != NULL ) {
 q_tree = proto_tree_add_subtree_format ( dns_tree , tvb , offset , len , ett_dns_qd , & tq , "%s: type %s, class %s" , name_out , type_name , val_to_str_const ( dns_class , dns_classes , "Unknown" ) ) ;
 if ( is_mdns ) {
 proto_item_append_text ( tq , ", \"%s\" question" , qu ? "QU" : "QM" ) ;
 }
 proto_tree_add_string ( q_tree , hf_dns_qry_name , tvb , offset , name_len , name ) ;
 tq = proto_tree_add_uint ( q_tree , hf_dns_qry_name_len , tvb , offset , name_len , name_len > 1 ? ( guint32 ) strlen ( name ) : 0 ) ;
 PROTO_ITEM_SET_GENERATED ( tq ) ;
 labels = qname_labels_count ( name , name_len ) ;
 tq = proto_tree_add_uint ( q_tree , hf_dns_count_labels , tvb , offset , name_len , labels ) ;
 PROTO_ITEM_SET_GENERATED ( tq ) ;
 offset += name_len ;
 proto_tree_add_item ( q_tree , hf_dns_qry_type , tvb , offset , 2 , ENC_BIG_ENDIAN ) ;
 offset += 2 ;
 if ( is_mdns ) {
 proto_tree_add_uint ( q_tree , hf_dns_qry_class_mdns , tvb , offset , 2 , dns_class ) ;
 proto_tree_add_boolean ( q_tree , hf_dns_qry_qu , tvb , offset , 2 , qu ) ;
 }
 else {
 proto_tree_add_uint ( q_tree , hf_dns_qry_class , tvb , offset , 2 , dns_class ) ;
 }
 offset += 2 ;
 }
 if ( data_start + len != offset ) {
 }
 return len ;
 }


bool LayerTreeHost::supportsAcceleratedCompositing()
{
    return true;
}


static int __net_init unix_net_init(struct net *net)
{
	int error = -ENOMEM;

	net->unx.sysctl_max_dgram_qlen = 10;
	if (unix_sysctl_register(net))
		goto out;

#ifdef CONFIG_PROC_FS
	if (!proc_create("unix", 0, net->proc_net, &unix_seq_fops)) {
		unix_sysctl_unregister(net);
		goto out;
	}
#endif
	error = 0;
out:
	return error;
}


static uint32_t ffmpeg_CodecTag ( vlc_fourcc_t fcc ) {
 uint8_t * p = ( uint8_t * ) & fcc ;
 return p [ 0 ] | ( p [ 1 ] << 8 ) | ( p [ 2 ] << 16 ) | ( p [ 3 ] << 24 ) ;
 }


static NORETURN void die_initial_contact(int unexpected)
{
	/*
	 * A hang-up after seeing some response from the other end
	 * means that it is unexpected, as we know the other end is
	 * willing to talk to us.  A hang-up before seeing any
	 * response does not necessarily mean an ACL problem, though.
	 */
	if (unexpected)
		die(_("the remote end hung up upon initial contact"));
	else
		die(_("Could not read from remote repository.\n\n"
		      "Please make sure you have the correct access rights\n"
		      "and the repository exists."));
}


bool FileReaderLoader::isCompleted() const
{
    return m_bytesLoaded == m_totalBytes;
}


TfLiteRegistration* Register_MUL_NEON_OPT() {
  static TfLiteRegistration r = {mul::Init, mul::Free, mul::Prepare,
                                 mul::Eval<mul::kNeonOptimized>};
  return &r;
}


static int vpc_open(BlockDriverState *bs, QDict *options, int flags,

                    Error **errp)

{

    BDRVVPCState *s = bs->opaque;

    int i;

    VHDFooter *footer;

    VHDDynDiskHeader *dyndisk_header;

    uint8_t buf[HEADER_SIZE];

    uint32_t checksum;

    int disk_type = VHD_DYNAMIC;

    int ret;

    ret = bdrv_pread(bs->file, 0, s->footer_buf, HEADER_SIZE);

    if (ret < 0) {

        goto fail;

    }

    footer = (VHDFooter *) s->footer_buf;

    if (strncmp(footer->creator, "conectix", 8)) {

        int64_t offset = bdrv_getlength(bs->file);

        if (offset < 0) {

            ret = offset;

            goto fail;

        } else if (offset < HEADER_SIZE) {

            ret = -EINVAL;

            goto fail;

        }

        /* If a fixed disk, the footer is found only at the end of the file */

        ret = bdrv_pread(bs->file, offset-HEADER_SIZE, s->footer_buf,

                         HEADER_SIZE);

        if (ret < 0) {

            goto fail;

        }

        if (strncmp(footer->creator, "conectix", 8)) {

            ret = -EMEDIUMTYPE;

            goto fail;

        }

        disk_type = VHD_FIXED;

    }

    checksum = be32_to_cpu(footer->checksum);

    footer->checksum = 0;

    if (vpc_checksum(s->footer_buf, HEADER_SIZE) != checksum)

        fprintf(stderr, "block-vpc: The header checksum of '%s' is "

            "incorrect.\n", bs->filename);

    /* Write 'checksum' back to footer, or else will leave it with zero. */

    footer->checksum = be32_to_cpu(checksum);

    // The visible size of a image in Virtual PC depends on the geometry

    // rather than on the size stored in the footer (the size in the footer

    // is too large usually)

    bs->total_sectors = (int64_t)

        be16_to_cpu(footer->cyls) * footer->heads * footer->secs_per_cyl;

    /* images created with disk2vhd report a far higher virtual size

     * than expected with the cyls * heads * sectors_per_cyl formula.

     * use the footer->size instead if the image was created with

     * disk2vhd.

     */

    if (!strncmp(footer->creator_app, "d2v", 4)) {

        bs->total_sectors = be64_to_cpu(footer->size) / BDRV_SECTOR_SIZE;

    }

    /* Allow a maximum disk size of approximately 2 TB */

    if (bs->total_sectors >= 65535LL * 255 * 255) {

        ret = -EFBIG;

        goto fail;

    }

    if (disk_type == VHD_DYNAMIC) {

        ret = bdrv_pread(bs->file, be64_to_cpu(footer->data_offset), buf,

                         HEADER_SIZE);

        if (ret < 0) {

            goto fail;

        }

        dyndisk_header = (VHDDynDiskHeader *) buf;

        if (strncmp(dyndisk_header->magic, "cxsparse", 8)) {

            ret = -EINVAL;

            goto fail;

        }

        s->block_size = be32_to_cpu(dyndisk_header->block_size);

        s->bitmap_size = ((s->block_size / (8 * 512)) + 511) & ~511;

        s->max_table_entries = be32_to_cpu(dyndisk_header->max_table_entries);

        s->pagetable = g_malloc(s->max_table_entries * 4);

        s->bat_offset = be64_to_cpu(dyndisk_header->table_offset);

        ret = bdrv_pread(bs->file, s->bat_offset, s->pagetable,

                         s->max_table_entries * 4);

        if (ret < 0) {

            goto fail;

        }

        s->free_data_block_offset =

            (s->bat_offset + (s->max_table_entries * 4) + 511) & ~511;

        for (i = 0; i < s->max_table_entries; i++) {

            be32_to_cpus(&s->pagetable[i]);

            if (s->pagetable[i] != 0xFFFFFFFF) {

                int64_t next = (512 * (int64_t) s->pagetable[i]) +

                    s->bitmap_size + s->block_size;

                if (next > s->free_data_block_offset) {

                    s->free_data_block_offset = next;

                }

            }

        }

        if (s->free_data_block_offset > bdrv_getlength(bs->file)) {

            error_setg(errp, "block-vpc: free_data_block_offset points after "

                             "the end of file. The image has been truncated.");

            ret = -EINVAL;

            goto fail;

        }

        s->last_bitmap_offset = (int64_t) -1;

#ifdef CACHE

        s->pageentry_u8 = g_malloc(512);

        s->pageentry_u32 = s->pageentry_u8;

        s->pageentry_u16 = s->pageentry_u8;

        s->last_pagetable = -1;

#endif

    }

    qemu_co_mutex_init(&s->lock);

    /* Disable migration when VHD images are used */

    error_set(&s->migration_blocker,

              QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,

              "vpc", bs->device_name, "live migration");

    migrate_add_blocker(s->migration_blocker);

    return 0;

fail:

    g_free(s->pagetable);

#ifdef CACHE

    g_free(s->pageentry_u8);

#endif

    return ret;

}


bool ExtensionPrefs::DoesExtensionControlPref(const std::string& extension_id,
                                              const std::string& pref_key,
                                              bool incognito) {
  DCHECK(pref_service()->FindPreference(pref_key.c_str()))
      << "Extension controlled preference key " << pref_key
      << " not registered.";

  return extension_pref_value_map_->DoesExtensionControlPref(extension_id,
                                                             pref_key,
                                                             incognito);
}


static int check_owned_directory_mode(const char *path, mode_t expected_mode)
{
	struct stat stat;
	if (lstat(path, &stat))
		return -1;

	if (!S_ISDIR(stat.st_mode))
		return -1;

	if (stat.st_uid != getuid())
		return -1;

	if ((stat.st_mode & 07777) != expected_mode)
		return -1;

	return 0;
}


static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const LengthBox& box)
{
    RefPtr<CSSPrimitiveValue> top;
    RefPtr<CSSPrimitiveValue> right;
    RefPtr<CSSPrimitiveValue> bottom;
    RefPtr<CSSPrimitiveValue> left;

    if (box.top().isRelative())
        top = cssValuePool().createValue(box.top().value(), CSSPrimitiveValue::CSS_NUMBER);
    else
        top = cssValuePool().createValue(box.top());

    if (box.right() == box.top() && box.bottom() == box.top() && box.left() == box.top()) {
        right = top;
        bottom = top;
        left = top;
    } else {
        if (box.right().isRelative())
            right = cssValuePool().createValue(box.right().value(), CSSPrimitiveValue::CSS_NUMBER);
        else
            right = cssValuePool().createValue(box.right());

        if (box.bottom() == box.top() && box.right() == box.left()) {
            bottom = top;
            left = right;
        } else {
            if (box.bottom().isRelative())
                bottom = cssValuePool().createValue(box.bottom().value(), CSSPrimitiveValue::CSS_NUMBER);
            else
                bottom = cssValuePool().createValue(box.bottom());

            if (box.left() == box.right())
                left = right;
            else {
                if (box.left().isRelative())
                    left = cssValuePool().createValue(box.left().value(), CSSPrimitiveValue::CSS_NUMBER);
                else
                    left = cssValuePool().createValue(box.left());
            }
        }
    }

    RefPtr<Quad> quad = Quad::create();
    quad->setTop(top);
    quad->setRight(right);
    quad->setBottom(bottom);
    quad->setLeft(left);

    return cssValuePool().createValue(quad.release());
}


static void qbus_list_bus(DeviceState *dev, char *dest, int len)

{

    BusState *child;

    const char *sep = " ";

    int pos = 0;

    pos += snprintf(dest+pos, len-pos,"child busses at \"%s\":",

                    dev->id ? dev->id : dev->info->name);

    LIST_FOREACH(child, &dev->child_bus, sibling) {

        pos += snprintf(dest+pos, len-pos, "%s\"%s\"", sep, child->name);

        sep = ", ";

    }

}


void MainWindow::onMultitrackClosed()
{
    setAudioChannels(Settings.playerAudioChannels());
    closeProducer();
    setProfile(Settings.playerProfile());
    resetVideoModeMenu();
    setCurrentFile("");
    setWindowModified(false);
    m_undoStack->clear();
    MLT.resetURL();
    QMutexLocker locker(&m_autosaveMutex);
    m_autosaveFile.reset(new AutoSaveFile(untitledFileName()));
    if (!playlist() || playlist()->count() == 0)
        m_player->enableTab(Player::ProjectTabIndex, false);
}


GraphicsLayer* FrameView::layerForScrollCorner() const
{
    RenderView* renderView = this->renderView();
    if (!renderView)
        return 0;
    return renderView->compositor()->layerForScrollCorner();
}


ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */
{
	zval *tmp;
	size_t _len = strlen(str);

	if (UNEXPECTED(_len > INT_MAX)) {
		zend_error_noreturn(E_ERROR, "String overflow, max size is %d", INT_MAX);
	}

	MAKE_STD_ZVAL(tmp);
	ZVAL_STRINGL(tmp, str, _len, duplicate);

	return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest);
}
/* }}} */


static void xfrm_hash_resize(struct work_struct *work)
{
	struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
	int dir, total;

	mutex_lock(&hash_resize_mutex);

	total = 0;
	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
		if (xfrm_bydst_should_resize(net, dir, &total))
			xfrm_bydst_resize(net, dir);
	}
	if (xfrm_byidx_should_resize(net, total))
		xfrm_byidx_resize(net, total);

	mutex_unlock(&hash_resize_mutex);
}


int ghid_setup(struct usb_gadget *g, int count)
{
	int status;
	dev_t dev;

	hidg_class = class_create(THIS_MODULE, "hidg");
	if (IS_ERR(hidg_class)) {
		status = PTR_ERR(hidg_class);
		hidg_class = NULL;
		return status;
	}

	status = alloc_chrdev_region(&dev, 0, count, "hidg");
	if (status) {
		class_destroy(hidg_class);
		hidg_class = NULL;
		return status;
	}

	major = MAJOR(dev);
	minors = count;

	return 0;
}


bool Document::HaveImportsLoaded() const {
  if (!imports_controller_)
    return true;
  return !imports_controller_->ShouldBlockScriptExecution(*this);
}


array_param_list_read(array_param_list * plist, ref * bot, uint count,
                      const ref * ppolicies, bool require_all,
                      gs_ref_memory_t *imem)
{
    iparam_list *const iplist = (iparam_list *) plist;

    if (count & 1)
        return_error(gs_error_rangecheck);
    plist->u.r.read = array_param_read;
    plist->enumerate = array_param_enumerate;
    plist->bot = bot;
    plist->top = bot + count;
    return ref_param_read_init(iplist, count, ppolicies, require_all, imem);
}


       \param filename Filename to write data to.
       \param fps Number of desired frames per second.
       \param nb_loops Number of loops (\c 0 for infinite looping).
    **/
    const CImgList<T>& save_gif_external(const char *const filename, const float fps=25,
                                         const unsigned int nb_loops=0) {
      CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256);
      CImgList<charT> filenames;
      std::FILE *file = 0;

#ifdef cimg_use_png
#define _cimg_save_gif_ext "png"
#else
#define _cimg_save_gif_ext "ppm"
#endif

      do {
        cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s",
                      cimg::temporary_path(),cimg_file_separator,cimg::filenamerand());
        cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001." _cimg_save_gif_ext,filename_tmp._data);
        if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file);
      } while (file);
      cimglist_for(*this,l) {
        cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u." _cimg_save_gif_ext,filename_tmp._data,l + 1);
        CImg<charT>::string(filename_tmp2).move_to(filenames);
        if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save(filename_tmp2);
        else _data[l].save(filename_tmp2);
      }
      cimg_snprintf(command,command._width,"%s -delay %u -loop %u",
                    cimg::imagemagick_path(),(unsigned int)std::max(0.f,cimg::round(100/fps)),nb_loops);
      CImg<ucharT>::string(command).move_to(filenames,0);
      cimg_snprintf(command,command._width,"\"%s\"",
                    CImg<charT>::string(filename)._system_strescape().data());
      CImg<ucharT>::string(command).move_to(filenames);
      CImg<charT> _command = filenames>'x';
      cimg_for(_command,p,char) if (!*p) *p = ' ';
      _command.back() = 0;

      cimg::system(_command);
      file = cimg::std_fopen(filename,"rb");
      if (!file)
        throw CImgIOException(_cimglist_instance
                              "save_gif_external(): Failed to save file '%s' with external command 'magick/convert'.",
                              cimglist_instance,
                              filename);


GF_Err gf_isom_get_pcm_config(GF_ISOFile *movie, u32 trackNumber, u32 descriptionIndex, u32 *flags, u32 *pcm_size)
{
	GF_AudioSampleEntryBox *aent;
	GF_PCMConfigBox *pcmC;
	GF_TrackBox *trak;
	trak = gf_isom_get_track_from_file(movie, trackNumber);
	if (!trak || !descriptionIndex) return GF_BAD_PARAM;

	aent = (GF_AudioSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, descriptionIndex-1);
	if (!aent) return GF_BAD_PARAM;
	if ((aent->type != GF_ISOM_BOX_TYPE_IPCM) && (aent->type != GF_ISOM_BOX_TYPE_FPCM))
		return GF_BAD_PARAM;

	pcmC = (GF_PCMConfigBox *) gf_isom_box_find_child(aent->child_boxes, GF_ISOM_BOX_TYPE_PCMC);
	if (!pcmC) return GF_NON_COMPLIANT_BITSTREAM;

	if (flags) *flags = pcmC->format_flags;
	if (pcm_size) *pcm_size = pcmC->PCM_sample_size;
	return GF_OK;
}


inline void Conv(const float* input_data, const Dims<4>& input_dims,
                 const float* filter_data, const Dims<4>& filter_dims,
                 const float* bias_data, const Dims<4>& bias_dims,
                 int stride_width, int stride_height, int dilation_width_factor,
                 int dilation_height_factor, int pad_width, int pad_height,
                 float output_activation_min, float output_activation_max,
                 float* output_data, const Dims<4>& output_dims,
                 float* im2col_data, const Dims<4>& im2col_dims) {
  tflite::ConvParams op_params;
  // Padding type is ignored, but still set.
  op_params.padding_type = PaddingType::kSame;
  op_params.padding_values.width = pad_width;
  op_params.padding_values.height = pad_height;
  op_params.stride_width = stride_width;
  op_params.stride_height = stride_height;
  op_params.dilation_width_factor = dilation_width_factor;
  op_params.dilation_height_factor = dilation_height_factor;
  op_params.float_activation_min = output_activation_min;
  op_params.float_activation_max = output_activation_max;

  Conv(op_params, DimsToShape(input_dims), input_data, DimsToShape(filter_dims),
       filter_data, DimsToShape(bias_dims), bias_data, DimsToShape(output_dims),
       output_data, DimsToShape(im2col_dims), im2col_data);
}


static int dissect_h225_SEQUENCE_SIZE_1_256_OF_QOSCapability ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_sequence_of ( tvb , offset , actx , tree , hf_index , ett_h225_SEQUENCE_SIZE_1_256_OF_QOSCapability , SEQUENCE_SIZE_1_256_OF_QOSCapability_sequence_of , 1 , 256 , FALSE ) ;
 return offset ;
 }


  static void  Ins_MUL( INS_ARG )
  { (void)exc;
    args[0] = MulDiv_Round( args[0], args[1], 64L );
  }


void PlayerGeneric::resetOnStop(bool b)
{
	resetOnStopFlag = b;
	if (player)
		player->resetOnStop(b);
}


bool HTMLFormControlElement::willValidate() const {
  if (!m_willValidateInitialized || m_dataListAncestorState == Unknown) {
    const_cast<HTMLFormControlElement*>(this)->setNeedsWillValidateCheck();
  } else {
    DCHECK_EQ(m_willValidate, recalcWillValidate());
  }
  return m_willValidate;
}


static void nsc_rle_decompress_data(NSC_CONTEXT* context)
{
	UINT16 i;
	BYTE* rle;
	UINT32 planeSize;
	UINT32 originalSize;
	rle = context->Planes;

	for (i = 0; i < 4; i++)
	{
		originalSize = context->OrgByteCount[i];
		planeSize = context->PlaneByteCount[i];

		if (planeSize == 0)
			FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF);
		else if (planeSize < originalSize)
			nsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize);
		else
			CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize);

		rle += planeSize;
	}
}


static void qmp_output_end_struct(Visitor *v, void **obj)

{

    QmpOutputVisitor *qov = to_qov(v);

    QObject *value = qmp_output_pop(qov, obj);

    assert(qobject_type(value) == QTYPE_QDICT);

}


static PHP_NAMED_FUNCTION ( zif_zip_entry_filesize ) {
 php_zip_entry_get_info ( INTERNAL_FUNCTION_PARAM_PASSTHRU , 2 ) ;
 }


static char * suck_data ( char * data , int * store_len , Gif_Reader * grr ) {
 uint8_t len = gifgetbyte ( grr ) ;
 int total_len = 0 ;
 while ( len > 0 ) {
 Gif_ReArray ( data , char , total_len + len + 1 ) ;
 if ( ! data ) return 0 ;
 gifgetblock ( ( uint8_t * ) data + total_len , len , grr ) ;
 total_len += len ;
 data [ total_len ] = 0 ;
 len = gifgetbyte ( grr ) ;
 }
 if ( store_len ) * store_len = total_len ;
 return data ;
 }


IRC_PROTOCOL_CALLBACK(server_mode_reason)
{
    char *pos_mode, *pos_args;

    IRC_PROTOCOL_MIN_ARGS(3);

    /* skip nickname if at beginning of server message */
    if (irc_server_strcasecmp (server, server->nick, argv[2]) == 0)
    {
        pos_mode = argv[3];
        pos_args = (argc > 4) ?
            ((argv_eol[4][0] == ':') ? argv_eol[4] + 1 : argv_eol[4]) : NULL;
    }
    else
    {
        pos_mode = argv[2];
        pos_args = (argc > 3) ?
            ((argv_eol[3][0] == ':') ? argv_eol[3] + 1 : argv_eol[3]) : NULL;
    }

    weechat_printf_date_tags (
        irc_msgbuffer_get_target_buffer (server, NULL, command, NULL, NULL),
        date,
        irc_protocol_tags (command, "irc_numeric", NULL, NULL),
        "%s%s: %s",
        weechat_prefix ("network"),
        pos_mode,
        (pos_args) ? pos_args : "");

    return WEECHAT_RC_OK;
}


void tracing_reset_online_cpus(struct trace_buffer *buf)
{
	struct ring_buffer *buffer = buf->buffer;
	int cpu;

	if (!buffer)
		return;

	ring_buffer_record_disable(buffer);

	/* Make sure all commits have finished */
	synchronize_rcu();

	buf->time_start = buffer_ftrace_now(buf, buf->cpu);

	for_each_online_cpu(cpu)
		ring_buffer_reset_cpu(buffer, cpu);

	ring_buffer_record_enable(buffer);
}


BrowserActionButton::BrowserActionButton(Extension* extension,
                                         BrowserActionsContainer* panel)
    : MenuButton(this, L"", NULL, false),
      browser_action_(extension->browser_action()),
      extension_(extension),
      tracker_(NULL),
      showing_context_menu_(false),
      panel_(panel) {
  set_alignment(TextButton::ALIGN_CENTER);

  registrar_.Add(this, NotificationType::EXTENSION_BROWSER_ACTION_UPDATED,
                 Source<ExtensionAction>(browser_action_));

  std::string relative_path = browser_action_->default_icon_path();
  if (relative_path.empty())
    return;

  tracker_ = new ImageLoadingTracker(this, 1);
  tracker_->PostLoadImageTask(
      extension->GetResource(relative_path),
      gfx::Size(Extension::kBrowserActionIconMaxSize,
                Extension::kBrowserActionIconMaxSize));
}


static apr_byte_t oidc_util_hdr_in_contains(const request_rec *r,
		const char *name, const char *separator, const char postfix_separator,
		const char *needle) {
	char *ctx = NULL, *elem = NULL;
	const char *value = oidc_util_hdr_in_get(r, name);
	apr_byte_t rc = FALSE;
	if (value) {
		elem = apr_strtok(apr_pstrdup(r->pool, value), separator, &ctx);
		while (elem != NULL) {
			while (*elem == OIDC_CHAR_SPACE)
				elem++;
			if ((strncmp(elem, needle, strlen(needle)) == 0)
					&& ((elem[strlen(needle)] == '\0')
							|| (elem[strlen(needle)] == postfix_separator))) {
				rc = TRUE;
				break;
			}
			elem = apr_strtok(NULL, separator, &ctx);
		}
	}
	return rc;
}


static GF_Err gf_isom_set_sample_group_info_ex(GF_SampleTableBox *stbl, void *traf, u32 sample_number, u32 grouping_type, u32 grouping_type_parameter, void *udta, void *(*sg_create_entry)(void *udta), Bool (*sg_compare_entry)(void *udta, void *entry))
#endif /* GPAC_DISABLE_ISOM_FRAGMENTS */
{
	GF_List *groupList, *parent;
	void *entry;
	Bool is_traf_sgpd;
	GF_SampleGroupDescriptionBox *sgdesc = NULL;
	u32 i, entry_idx;

	if (!stbl && !traf) return GF_BAD_PARAM;

	sgdesc = get_sgdp(stbl, traf, grouping_type, &is_traf_sgpd);
	if (!sgdesc) return GF_OUT_OF_MEM;

	entry = NULL;
	if (sg_compare_entry) {
		for (i=0; i<gf_list_count(sgdesc->group_descriptions); i++) {
			entry = gf_list_get(sgdesc->group_descriptions, i);
			if (sg_compare_entry(udta, entry)) break;
			entry = NULL;
		}
	}
	if (!entry && sg_create_entry) {
		entry = sg_create_entry(udta);
		if (!entry) return GF_IO_ERR;
		if (traf && !is_traf_sgpd) {
			sgdesc = get_sgdp(NULL, traf, grouping_type, &is_traf_sgpd);
		}
		gf_list_add(sgdesc->group_descriptions, entry);
	}
	if (!entry)
		entry_idx = 0;
	else
		entry_idx = 1 + gf_list_find(sgdesc->group_descriptions, entry);

	/*look in stbl or traf for sample sampleGroups*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
	if (traf) {
		if (!traf->sampleGroups)
			traf->sampleGroups = gf_list_new();
		groupList = traf->sampleGroups;
		parent = traf->child_boxes;
		if (entry_idx && is_traf_sgpd)
			entry_idx |= 0x10000;
	} else
#endif
	{
		if (!stbl->sampleGroups)
			stbl->sampleGroups = gf_list_new();
		groupList = stbl->sampleGroups;
		parent = stbl->child_boxes;
	}

	return gf_isom_add_sample_group_entry(groupList, sample_number, grouping_type, grouping_type_parameter, entry_idx, parent, stbl);
}


int Monitor::scrub()
{
  assert(is_leader());
  assert(scrub_state);

  scrub_cancel_timeout();
  wait_for_paxos_write();
  scrub_version = paxos->get_version();

  // scrub all keys if we're the only monitor in the quorum
  int32_t num_keys =
    (quorum.size() == 1 ? -1 : cct->_conf->mon_scrub_max_keys);

  for (set<int>::iterator p = quorum.begin();
       p != quorum.end();
       ++p) {
    if (*p == rank)
      continue;
    MMonScrub *r = new MMonScrub(MMonScrub::OP_SCRUB, scrub_version,
                                 num_keys);
    r->key = scrub_state->last_key;
    messenger->send_message(r, monmap->get_inst(*p));
  }

  // scrub my keys
  bool r = _scrub(&scrub_result[rank],
                  &scrub_state->last_key,
                  &num_keys);

  scrub_state->finished = !r;

  // only after we got our scrub results do we really care whether the
  // other monitors are late on their results.  Also, this way we avoid
  // triggering the timeout if we end up getting stuck in _scrub() for
  // longer than the duration of the timeout.
  scrub_reset_timeout();

  if (quorum.size() == 1) {
    assert(scrub_state->finished == true);
    scrub_finish();
  }
  return 0;
}


PHP_FUNCTION(openssl_pkcs12_read)
{
	zval *zout = NULL, *zextracerts, *zcert, *zpkey;
	char *pass, *zp12;
	int pass_len, zp12_len;
	PKCS12 * p12 = NULL;
	EVP_PKEY * pkey = NULL;
	X509 * cert = NULL;
	STACK_OF(X509) * ca = NULL;
	BIO * bio_in = NULL;
	int i;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szs", &zp12, &zp12_len, &zout, &pass, &pass_len) == FAILURE)
		return;

	RETVAL_FALSE;

	bio_in = BIO_new(BIO_s_mem());

	if(!BIO_write(bio_in, zp12, zp12_len))
		goto cleanup;

	if(d2i_PKCS12_bio(bio_in, &p12)) {
		if(PKCS12_parse(p12, pass, &pkey, &cert, &ca)) {
			BIO * bio_out;

			zval_dtor(zout);
			array_init(zout);

			bio_out = BIO_new(BIO_s_mem());
			if (PEM_write_bio_X509(bio_out, cert)) {
				BUF_MEM *bio_buf;
				BIO_get_mem_ptr(bio_out, &bio_buf);
				MAKE_STD_ZVAL(zcert);
				ZVAL_STRINGL(zcert, bio_buf->data, bio_buf->length, 1);
				add_assoc_zval(zout, "cert", zcert);
			}
			BIO_free(bio_out);

			bio_out = BIO_new(BIO_s_mem());
			if (PEM_write_bio_PrivateKey(bio_out, pkey, NULL, NULL, 0, 0, NULL)) {
				BUF_MEM *bio_buf;
				BIO_get_mem_ptr(bio_out, &bio_buf);
				MAKE_STD_ZVAL(zpkey);
				ZVAL_STRINGL(zpkey, bio_buf->data, bio_buf->length, 1);
				add_assoc_zval(zout, "pkey", zpkey);
			}
			BIO_free(bio_out);

			MAKE_STD_ZVAL(zextracerts);
			array_init(zextracerts);

			for (i=0;;i++) {
				zval * zextracert;
				X509* aCA = sk_X509_pop(ca);
				if (!aCA) break;

				/* fix for bug 69882 */
				{
					int err = ERR_peek_error();
					if (err == OPENSSL_ERROR_X509_PRIVATE_KEY_VALUES_MISMATCH) {
						ERR_get_error();
					}
				}

				bio_out = BIO_new(BIO_s_mem());
				if (PEM_write_bio_X509(bio_out, aCA)) {
					BUF_MEM *bio_buf;
					BIO_get_mem_ptr(bio_out, &bio_buf);
					MAKE_STD_ZVAL(zextracert);
					ZVAL_STRINGL(zextracert, bio_buf->data, bio_buf->length, 1);
					add_index_zval(zextracerts, i, zextracert);

				}
				BIO_free(bio_out);

				X509_free(aCA);
			}
			if(ca) {
				sk_X509_free(ca);
				add_assoc_zval(zout, "extracerts", zextracerts);
			} else {
				zval_dtor(zextracerts);
			}

			RETVAL_TRUE;

			PKCS12_free(p12);
		}
	}

  cleanup:
	if (bio_in) {
		BIO_free(bio_in);
	}
	if (pkey) {
		EVP_PKEY_free(pkey);
	}
	if (cert) {
		X509_free(cert);
	}
}


ldns_rr_set_question(ldns_rr *rr, bool question)
{
   rr->_rr_question = question;
}


find_directory_in_path(
    char_u	*ptr,		// file name
    int		len,		// length of file name
    int		options,
    char_u	*rel_fname)	// file name searching relative to
{
    return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
				       FINDFILE_DIR, rel_fname, (char_u *)"");
}


static SLJIT_INLINE void compile_recurse_backtrackingpath(compiler_common *common, struct backtrack_common *current)
{
DEFINE_COMPILER;
recurse_entry *entry;

if (!CURRENT_AS(recurse_backtrack)->inlined_pattern)
  {
  entry = CURRENT_AS(recurse_backtrack)->entry;
  if (entry->backtrack_label == NULL)
    add_jump(compiler, &entry->backtrack_calls, JUMP(SLJIT_FAST_CALL));
  else
    JUMPTO(SLJIT_FAST_CALL, entry->backtrack_label);
  CMPTO(SLJIT_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, CURRENT_AS(recurse_backtrack)->matchingpath);
  }
else
  compile_backtrackingpath(common, current->top);

set_jumps(current->topbacktracks, LABEL());
}


BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
	UINT32 i;
	BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));

	if (!bitmapUpdate)
		goto fail;

	if (Stream_GetRemainingLength(s) < 2)
		goto fail;

	Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
	WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number);

	if (bitmapUpdate->number > bitmapUpdate->count)
	{
		UINT32 count = bitmapUpdate->number * 2;
		BITMAP_DATA* newdata =
		    (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count);

		if (!newdata)
			goto fail;

		bitmapUpdate->rectangles = newdata;
		ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
		           sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
		bitmapUpdate->count = count;
	}

	/* rectangles */
	for (i = 0; i < bitmapUpdate->number; i++)
	{
		if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
			goto fail;
	}

	return bitmapUpdate;
fail:
	free_bitmap_update(update->context, bitmapUpdate);
	return NULL;
}


int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
	return -EINVAL;
}


static int __packet_rcv_vnet(const struct sk_buff *skb,
			     struct virtio_net_hdr *vnet_hdr)
{
	*vnet_hdr = (const struct virtio_net_hdr) { 0 };

	if (virtio_net_hdr_from_skb(skb, vnet_hdr, vio_le()))
		BUG();

	return 0;
}


kg_unseal_v1_iov(krb5_context context,
                 OM_uint32 *minor_status,
                 krb5_gss_ctx_id_rec *ctx,
                 gss_iov_buffer_desc *iov,
                 int iov_count,
                 size_t token_wrapper_len,
                 int *conf_state,
                 gss_qop_t *qop_state,
                 int toktype)
{
    OM_uint32 code;
    gss_iov_buffer_t header;
    gss_iov_buffer_t trailer;
    unsigned char *ptr;
    int sealalg;
    int signalg;
    krb5_checksum cksum;
    krb5_checksum md5cksum;
    size_t cksum_len = 0;
    size_t conflen = 0;
    int direction;
    krb5_ui_4 seqnum;
    OM_uint32 retval;
    size_t sumlen;
    krb5_keyusage sign_usage = KG_USAGE_SIGN;

    md5cksum.length = cksum.length = 0;
    md5cksum.contents = cksum.contents = NULL;

    header = kg_locate_header_iov(iov, iov_count, toktype);
    assert(header != NULL);

    trailer = kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
    if (trailer != NULL && trailer->buffer.length != 0) {
        *minor_status = (OM_uint32)KRB5_BAD_MSIZE;
         return GSS_S_DEFECTIVE_TOKEN;
     }

    if (header->buffer.length < token_wrapper_len + 14) {
         *minor_status = 0;
         return GSS_S_DEFECTIVE_TOKEN;
     }

    ptr = (unsigned char *)header->buffer.value + token_wrapper_len;

    signalg  = ptr[0];
    signalg |= ptr[1] << 8;

    sealalg  = ptr[2];
    sealalg |= ptr[3] << 8;

    if (ptr[4] != 0xFF || ptr[5] != 0xFF) {
        *minor_status = 0;
        return GSS_S_DEFECTIVE_TOKEN;
    }

    if (toktype != KG_TOK_WRAP_MSG && sealalg != 0xFFFF) {
        *minor_status = 0;
        return GSS_S_DEFECTIVE_TOKEN;
    }

    if (toktype == KG_TOK_WRAP_MSG &&
        !(sealalg == 0xFFFF || sealalg == ctx->sealalg)) {
        *minor_status = 0;
        return GSS_S_DEFECTIVE_TOKEN;
    }

    if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) ||
        (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) ||
        (ctx->sealalg == SEAL_ALG_DES3KD &&
         signalg != SGN_ALG_HMAC_SHA1_DES3_KD)||
        (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 &&
         signalg != SGN_ALG_HMAC_MD5)) {
        *minor_status = 0;
        return GSS_S_DEFECTIVE_TOKEN;
    }

    switch (signalg) {
    case SGN_ALG_DES_MAC_MD5:
    case SGN_ALG_MD2_5:
    case SGN_ALG_HMAC_MD5:
        cksum_len = 8;
        if (toktype != KG_TOK_WRAP_MSG)
            sign_usage = 15;
        break;
    case SGN_ALG_3:
        cksum_len = 16;
        break;
    case SGN_ALG_HMAC_SHA1_DES3_KD:
        cksum_len = 20;
        break;
    default:
        *minor_status = 0;
        return GSS_S_DEFECTIVE_TOKEN;
    }

    /* get the token parameters */
    code = kg_get_seq_num(context, ctx->seq, ptr + 14, ptr + 6, &direction,
                          &seqnum);
    if (code != 0) {
        *minor_status = code;
        return GSS_S_BAD_SIG;
    }

    /* decode the message, if SEAL */
    if (toktype == KG_TOK_WRAP_MSG) {
        if (sealalg != 0xFFFF) {
            if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) {
                unsigned char bigend_seqnum[4];
                krb5_keyblock *enc_key;
                size_t i;

                store_32_be(seqnum, bigend_seqnum);

                code = krb5_k_key_keyblock(context, ctx->enc, &enc_key);
                if (code != 0) {
                    retval = GSS_S_FAILURE;
                    goto cleanup;
                }

                assert(enc_key->length == 16);

                for (i = 0; i < enc_key->length; i++)
                    ((char *)enc_key->contents)[i] ^= 0xF0;

                code = kg_arcfour_docrypt_iov(context, enc_key, 0,
                                              &bigend_seqnum[0], 4,
                                              iov, iov_count);
                krb5_free_keyblock(context, enc_key);
            } else {
                code = kg_decrypt_iov(context, 0,
                                      ((ctx->gss_flags & GSS_C_DCE_STYLE) != 0),
                                      0 /*EC*/, 0 /*RRC*/,
                                      ctx->enc, KG_USAGE_SEAL, NULL,
                                      iov, iov_count);
            }
            if (code != 0) {
                retval = GSS_S_FAILURE;
                goto cleanup;
            }
        }
        conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype);
    }

    if (header->buffer.length != token_wrapper_len + 14 + cksum_len + conflen) {
        retval = GSS_S_DEFECTIVE_TOKEN;
        goto cleanup;
    }

    /* compute the checksum of the message */

    /* initialize the checksum */

    switch (signalg) {
    case SGN_ALG_DES_MAC_MD5:
    case SGN_ALG_MD2_5:
    case SGN_ALG_DES_MAC:
    case SGN_ALG_3:
        md5cksum.checksum_type = CKSUMTYPE_RSA_MD5;
        break;
    case SGN_ALG_HMAC_MD5:
        md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR;
        break;
    case SGN_ALG_HMAC_SHA1_DES3_KD:
        md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3;
        break;
    default:
        abort();
    }

    code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen);
    if (code != 0) {
        retval = GSS_S_FAILURE;
        goto cleanup;
    }
    md5cksum.length = sumlen;

    /* compute the checksum of the message */
    code = kg_make_checksum_iov_v1(context, md5cksum.checksum_type,
                                   cksum_len, ctx->seq, ctx->enc,
                                   sign_usage, iov, iov_count, toktype,
                                   &md5cksum);
    if (code != 0) {
        retval = GSS_S_FAILURE;
        goto cleanup;
    }

    switch (signalg) {
    case SGN_ALG_DES_MAC_MD5:
    case SGN_ALG_3:
        code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL,
                                  (g_OID_equal(ctx->mech_used,
                                               gss_mech_krb5_old) ?
                                   ctx->seq->keyblock.contents : NULL),
                                  md5cksum.contents, 16);
        if (code != 0) {
            retval = GSS_S_FAILURE;
            goto cleanup;
        }

        cksum.length = cksum_len;
        cksum.contents = md5cksum.contents + 16 - cksum.length;

        code = k5_bcmp(cksum.contents, ptr + 14, cksum.length);
        break;
    case SGN_ALG_HMAC_SHA1_DES3_KD:
    case SGN_ALG_HMAC_MD5:
        code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len);
        break;
    default:
        code = 0;
        retval = GSS_S_DEFECTIVE_TOKEN;
        goto cleanup;
        break;
    }

    if (code != 0) {
        code = 0;
        retval = GSS_S_BAD_SIG;
        goto cleanup;
    }

    /*
     * For GSS_C_DCE_STYLE, the caller manages the padding, because the
     * pad length is in the RPC PDU. The value of the padding may be
     * uninitialized. For normal GSS, the last bytes of the decrypted
     * data contain the pad length. kg_fixup_padding_iov() will find
     * this and fixup the last data IOV appropriately.
     */
    if (toktype == KG_TOK_WRAP_MSG &&
        (ctx->gss_flags & GSS_C_DCE_STYLE) == 0) {
        retval = kg_fixup_padding_iov(&code, iov, iov_count);
        if (retval != GSS_S_COMPLETE)
            goto cleanup;
    }

    if (conf_state != NULL)
        *conf_state = (sealalg != 0xFFFF);

    if (qop_state != NULL)
        *qop_state = GSS_C_QOP_DEFAULT;

    if ((ctx->initiate && direction != 0xff) ||
        (!ctx->initiate && direction != 0)) {
        *minor_status = (OM_uint32)G_BAD_DIRECTION;
        retval = GSS_S_BAD_SIG;
    }

    code = 0;
    retval = g_order_check(&ctx->seqstate, (gssint_uint64)seqnum);

cleanup:
    krb5_free_checksum_contents(context, &md5cksum);

    *minor_status = code;

    return retval;
}


void SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) {
 if (mCodecContext == NULL) {
 if (OK != initEncoder()) {
            ALOGE("Failed to initialize encoder");
            notify(OMX_EventError,
                   OMX_ErrorUndefined,
 0, // Extra notification data
                   NULL); // Notification data pointer
 return;
 }
 }

 vpx_codec_err_t codec_return;
 List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex);
 List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex);

 while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) {
 BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin();
        OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader;

 BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin();
        OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader;

 if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) &&
                inputBufferHeader->nFilledLen == 0) {
            inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
            inputBufferInfo->mOwnedByUs = false;
            notifyEmptyBufferDone(inputBufferHeader);

            outputBufferHeader->nFilledLen = 0;
            outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS;

            outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
            outputBufferInfo->mOwnedByUs = false;
            notifyFillBufferDone(outputBufferHeader);
 return;
 }

 const uint8_t *source =
            inputBufferHeader->pBuffer + inputBufferHeader->nOffset;

 size_t frameSize = mWidth * mHeight * 3 / 2;
 if (mInputDataIsMeta) {
            source = extractGraphicBuffer(
                    mConversionBuffer, frameSize,
                    source, inputBufferHeader->nFilledLen,
                    mWidth, mHeight);
 if (source == NULL) {
                ALOGE("Unable to extract gralloc buffer in metadata mode");
                notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
 return;
 }
 } else {
 if (inputBufferHeader->nFilledLen < frameSize) {
                android_errorWriteLog(0x534e4554, "27569635");
                notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
 return;
 } else if (inputBufferHeader->nFilledLen > frameSize) {
                ALOGW("Input buffer contains too many pixels");
 }

 if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) {
 ConvertYUV420SemiPlanarToYUV420Planar(
                        source, mConversionBuffer, mWidth, mHeight);

                source = mConversionBuffer;
 }
 }
 vpx_image_t raw_frame;
        vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight,
                     kInputBufferAlignment, (uint8_t *)source);

 vpx_enc_frame_flags_t flags = 0;
 if (mTemporalPatternLength > 0) {
            flags = getEncodeFlags();
 }
 if (mKeyFrameRequested) {
            flags |= VPX_EFLAG_FORCE_KF;
            mKeyFrameRequested = false;
 }

 if (mBitrateUpdated) {
            mCodecConfiguration->rc_target_bitrate = mBitrate/1000;
 vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext,
                                                           mCodecConfiguration);
 if (res != VPX_CODEC_OK) {
                ALOGE("vp8 encoder failed to update bitrate: %s",
                      vpx_codec_err_to_string(res));
                notify(OMX_EventError,
                       OMX_ErrorUndefined,
 0, // Extra notification data
                       NULL); // Notification data pointer
 }
            mBitrateUpdated = false;
 }

 uint32_t frameDuration;
 if (inputBufferHeader->nTimeStamp > mLastTimestamp) {
            frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp);
 } else {
            frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate);
 }
        mLastTimestamp = inputBufferHeader->nTimeStamp;
        codec_return = vpx_codec_encode(
                mCodecContext,
 &raw_frame,
                inputBufferHeader->nTimeStamp, // in timebase units
                frameDuration, // frame duration in timebase units
                flags, // frame flags
                VPX_DL_REALTIME); // encoding deadline
 if (codec_return != VPX_CODEC_OK) {
            ALOGE("vpx encoder failed to encode frame");
            notify(OMX_EventError,
                   OMX_ErrorUndefined,
 0, // Extra notification data
                   NULL); // Notification data pointer
 return;
 }

 vpx_codec_iter_t encoded_packet_iterator = NULL;
 const vpx_codec_cx_pkt_t* encoded_packet;

 while ((encoded_packet = vpx_codec_get_cx_data(
                        mCodecContext, &encoded_packet_iterator))) {
 if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) {
                outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts;
                outputBufferHeader->nFlags = 0;
 if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY)
                    outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME;
                outputBufferHeader->nOffset = 0;
                outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz;
 if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) {
                    android_errorWriteLog(0x534e4554, "27569635");
                    notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
 return;
 }
                memcpy(outputBufferHeader->pBuffer,
                       encoded_packet->data.frame.buf,
                       encoded_packet->data.frame.sz);
                outputBufferInfo->mOwnedByUs = false;
                outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
 if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) {
                    outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS;
 }
                notifyFillBufferDone(outputBufferHeader);
 }
 }

        inputBufferInfo->mOwnedByUs = false;
        inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
        notifyEmptyBufferDone(inputBufferHeader);
 }
}


static void asf_build_simple_index(AVFormatContext *s, int stream_index)

{

    ff_asf_guid g;

    ASFContext *asf     = s->priv_data;

    int64_t current_pos = avio_tell(s->pb);

    int i;

    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);

    ff_get_guid(s->pb, &g);

    /* the data object can be followed by other top-level objects,

     * skip them until the simple index object is reached */

    while (ff_guidcmp(&g, &index_guid)) {

        int64_t gsize = avio_rl64(s->pb);

        if (gsize < 24 || s->pb->eof_reached) {

            avio_seek(s->pb, current_pos, SEEK_SET);

            return;

        }

        avio_skip(s->pb, gsize - 24);

        ff_get_guid(s->pb, &g);

    }

    {

        int64_t itime, last_pos = -1;

        int pct, ict;

        int64_t av_unused gsize = avio_rl64(s->pb);

        ff_get_guid(s->pb, &g);

        itime = avio_rl64(s->pb);

        pct   = avio_rl32(s->pb);

        ict   = avio_rl32(s->pb);

        av_log(s, AV_LOG_DEBUG,

               "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict);

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

            int pktnum        = avio_rl32(s->pb);

            int pktct         = avio_rl16(s->pb);

            int64_t pos       = s->data_offset + s->packet_size * (int64_t)pktnum;

            int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);

            if (pos != last_pos) {

                av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n",

                       pktnum, pktct, index_pts);

                av_add_index_entry(s->streams[stream_index], pos, index_pts,

                                   s->packet_size, 0, AVINDEX_KEYFRAME);

                last_pos = pos;

            }

        }

        asf->index_read = ict > 0;

    }

    avio_seek(s->pb, current_pos, SEEK_SET);

}


 MountError PerformFakeMount(const std::string& source_path,
                            const base::FilePath& mounted_path) {
   if (mounted_path.empty())
     return MOUNT_ERROR_INVALID_ARGUMENT;

  if (!base::CreateDirectory(mounted_path)) {
    DLOG(ERROR) << "Failed to create directory at " << mounted_path.value();
     return MOUNT_ERROR_DIRECTORY_CREATION_FAILED;
   }

   const base::FilePath dummy_file_path =
       mounted_path.Append("SUCCESSFULLY_PERFORMED_FAKE_MOUNT.txt");
  const std::string dummy_file_content = "This is a dummy file.";
  const int write_result = base::WriteFile(
      dummy_file_path, dummy_file_content.data(), dummy_file_content.size());
  if (write_result != static_cast<int>(dummy_file_content.size())) {
    DLOG(ERROR) << "Failed to put a dummy file at "
                << dummy_file_path.value();
    return MOUNT_ERROR_MOUNT_PROGRAM_FAILED;
  }

  return MOUNT_ERROR_NONE;
}


static int ___sys_recvmsg(struct socket *sock, struct msghdr __user *msg,
			 struct msghdr *msg_sys, unsigned int flags, int nosec)
{
	struct compat_msghdr __user *msg_compat =
	    (struct compat_msghdr __user *)msg;
	struct iovec iovstack[UIO_FASTIOV];
	struct iovec *iov = iovstack;
	unsigned long cmsg_ptr;
	int err, total_len, len;

	/* kernel mode address */
	struct sockaddr_storage addr;

	/* user mode address pointers */
	struct sockaddr __user *uaddr;
	int __user *uaddr_len;

	if (MSG_CMSG_COMPAT & flags) {
		if (get_compat_msghdr(msg_sys, msg_compat))
			return -EFAULT;
	} else {
		err = copy_msghdr_from_user(msg_sys, msg);
		if (err)
			return err;
	}

	if (msg_sys->msg_iovlen > UIO_FASTIOV) {
		err = -EMSGSIZE;
		if (msg_sys->msg_iovlen > UIO_MAXIOV)
			goto out;
		err = -ENOMEM;
		iov = kmalloc(msg_sys->msg_iovlen * sizeof(struct iovec),
			      GFP_KERNEL);
		if (!iov)
			goto out;
	}

	/* Save the user-mode address (verify_iovec will change the
	 * kernel msghdr to use the kernel address space)
	 */
	uaddr = (__force void __user *)msg_sys->msg_name;
	uaddr_len = COMPAT_NAMELEN(msg);
	if (MSG_CMSG_COMPAT & flags)
		err = verify_compat_iovec(msg_sys, iov, &addr, VERIFY_WRITE);
	else
		err = verify_iovec(msg_sys, iov, &addr, VERIFY_WRITE);
	if (err < 0)
		goto out_freeiov;
	total_len = err;

	cmsg_ptr = (unsigned long)msg_sys->msg_control;
	msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);

	/* We assume all kernel code knows the size of sockaddr_storage */
	msg_sys->msg_namelen = 0;

	if (sock->file->f_flags & O_NONBLOCK)
		flags |= MSG_DONTWAIT;
	err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys,
							  total_len, flags);
	if (err < 0)
		goto out_freeiov;
	len = err;

	if (uaddr != NULL) {
		err = move_addr_to_user(&addr,
					msg_sys->msg_namelen, uaddr,
					uaddr_len);
		if (err < 0)
			goto out_freeiov;
	}
	err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT),
			 COMPAT_FLAGS(msg));
	if (err)
		goto out_freeiov;
	if (MSG_CMSG_COMPAT & flags)
		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
				 &msg_compat->msg_controllen);
	else
		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
				 &msg->msg_controllen);
	if (err)
		goto out_freeiov;
	err = len;

out_freeiov:
	if (iov != iovstack)
		kfree(iov);
out:
	return err;
}


int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
                        void *ptr, size_t len, bool is_write)
{
    hwaddr phys_addr;
    vaddr l, page;
    uint8_t *buf = ptr;

    cpu_synchronize_state(cpu);
    while (len > 0) {
        int asidx;
        MemTxAttrs attrs;
        MemTxResult res;

        page = addr & TARGET_PAGE_MASK;
        phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
        asidx = cpu_asidx_from_attrs(cpu, attrs);
        /* if no physical page mapped, return an error */
        if (phys_addr == -1)
            return -1;
        l = (page + TARGET_PAGE_SIZE) - addr;
        if (l > len)
            l = len;
        phys_addr += (addr & ~TARGET_PAGE_MASK);
        if (is_write) {
            res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
                                          attrs, buf, l);
        } else {
            res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
                                     attrs, buf, l);
        }
        if (res != MEMTX_OK) {
            return -1;
        }
        len -= l;
        buf += l;
        addr += l;
    }
    return 0;
}


void Document::updateStyleAndLayoutTree()
{
    DCHECK(isMainThread());

    ScriptForbiddenScope forbidScript;
    PluginScriptForbiddenScope pluginForbidScript;

    if (!view() || !isActive())
        return;

    if (view()->shouldThrottleRendering())
        return;

    if (!needsLayoutTreeUpdate()) {
        if (lifecycle().state() < DocumentLifecycle::StyleClean) {
            lifecycle().advanceTo(DocumentLifecycle::InStyleRecalc);
            lifecycle().advanceTo(DocumentLifecycle::StyleClean);
        }
        return;
    }

    if (inStyleRecalc())
        return;

    RELEASE_ASSERT(lifecycle().stateAllowsTreeMutations());

    TRACE_EVENT_BEGIN1("blink,devtools.timeline", "UpdateLayoutTree", "beginData", InspectorRecalculateStylesEvent::data(frame()));
    TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "UpdateLayoutTree");

    unsigned startElementCount = styleEngine().styleForElementCount();

    InspectorInstrumentation::StyleRecalc instrumentation(this);

    DocumentAnimations::updateAnimationTimingIfNeeded(*this);
    evaluateMediaQueryListIfNeeded();
    updateUseShadowTreesIfNeeded();
    updateDistribution();
    updateStyleInvalidationIfNeeded();

    updateStyle();

    notifyLayoutTreeOfSubtreeChanges();

    if (hoverNode() && !hoverNode()->layoutObject() && frame())
        frame()->eventHandler().dispatchFakeMouseMoveEventSoon();

    if (m_focusedElement && !m_focusedElement->isFocusable())
        clearFocusedElementSoon();
    layoutView()->clearHitTestCache();

    DCHECK(!DocumentAnimations::needsAnimationTimingUpdate(*this));

    unsigned elementCount = styleEngine().styleForElementCount() - startElementCount;

    TRACE_EVENT_END1("blink,devtools.timeline", "UpdateLayoutTree", "elementCount", elementCount);

#if DCHECK_IS_ON()
    assertLayoutTreeUpdated(*this);
#endif
}


static void encode_block(MpegEncContext *s, int16_t *block, int n)

{

    int i, j, table_id;

    int component, dc, last_index, val, run;

    MJpegContext *m = s->mjpeg_ctx;

    /* DC coef */

    component = (n <= 3 ? 0 : (n&1) + 1);

    table_id = (n <= 3 ? 0 : 1);

    dc = block[0]; /* overflow is impossible */

    val = dc - s->last_dc[component];

    ff_mjpeg_encode_coef(m, table_id, val, 0);

    s->last_dc[component] = dc;

    /* AC coefs */

    run = 0;

    last_index = s->block_last_index[n];

    table_id |= 2;

    for(i=1;i<=last_index;i++) {

        j = s->intra_scantable.permutated[i];

        val = block[j];

        if (val == 0) {

            run++;

        } else {

            while (run >= 16) {

                ff_mjpeg_encode_code(m, table_id, 0xf0);

                run -= 16;

            }

            ff_mjpeg_encode_coef(m, table_id, val, run);

            run = 0;

        }

    }

    /* output EOB only if not already 64 values */

    if (last_index < 63 || run != 0)

        ff_mjpeg_encode_code(m, table_id, 0);

}


void RenderWidgetHostViewAura::CreateBrowserAccessibilityManagerIfNeeded() {
  if (GetBrowserAccessibilityManager())
    return;

#if defined(OS_WIN)
  aura::WindowEventDispatcher* dispatcher = window_->GetDispatcher();
  if (!dispatcher)
    return;
  HWND hwnd = dispatcher->host()->GetAcceleratedWidget();

  gfx::NativeViewAccessible accessible_parent =
      host_->GetParentNativeViewAccessible();

  BrowserAccessibilityManager* manager = new BrowserAccessibilityManagerWin(
      hwnd, accessible_parent,
      BrowserAccessibilityManagerWin::GetEmptyDocument(), this);
#else
  BrowserAccessibilityManager* manager = BrowserAccessibilityManager::Create(
      BrowserAccessibilityManager::GetEmptyDocument(), this);
#endif

  SetBrowserAccessibilityManager(manager);
}


xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
                         int normalize)
{
    xmlChar limit = 0;
    const xmlChar *in = NULL, *start, *end, *last;
    xmlChar *ret = NULL;

    GROW;
    in = (xmlChar *) CUR_PTR;
    if (*in != '"' && *in != '\'') {
        xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
        return (NULL);
    }
    ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;

    /*
     * try to handle in this routine the most common case where no
     * allocation of a new string is required and where content is
     * pure ASCII.
     */
    limit = *in++;
    end = ctxt->input->end;
    start = in;
    if (in >= end) {
        const xmlChar *oldbase = ctxt->input->base;
	GROW;
	if (oldbase != ctxt->input->base) {
	    long delta = ctxt->input->base - oldbase;
	    start = start + delta;
	    in = in + delta;
	}
	end = ctxt->input->end;
    }
    if (normalize) {
        /*
	 * Skip any leading spaces
	 */
	while ((in < end) && (*in != limit) &&
	       ((*in == 0x20) || (*in == 0x9) ||
	        (*in == 0xA) || (*in == 0xD))) {
	    in++;
	    start = in;
 	    if (in >= end) {
 		const xmlChar *oldbase = ctxt->input->base;
 		GROW;
 		if (oldbase != ctxt->input->base) {
 		    long delta = ctxt->input->base - oldbase;
 		    start = start + delta;
		    in = in + delta;
		}
		end = ctxt->input->end;
	    }
	}
	while ((in < end) && (*in != limit) && (*in >= 0x20) &&
	       (*in <= 0x7f) && (*in != '&') && (*in != '<')) {
	    if ((*in++ == 0x20) && (*in == 0x20)) break;
 	    if (in >= end) {
 		const xmlChar *oldbase = ctxt->input->base;
 		GROW;
 		if (oldbase != ctxt->input->base) {
 		    long delta = ctxt->input->base - oldbase;
 		    start = start + delta;
		    in = in + delta;
		}
		end = ctxt->input->end;
	    }
	}
	last = in;
	/*
	 * skip the trailing blanks
	 */
	while ((last[-1] == 0x20) && (last > start)) last--;
	while ((in < end) && (*in != limit) &&
	       ((*in == 0x20) || (*in == 0x9) ||
	        (*in == 0xA) || (*in == 0xD))) {
	    in++;
 	    if (in >= end) {
 		const xmlChar *oldbase = ctxt->input->base;
 		GROW;
 		if (oldbase != ctxt->input->base) {
 		    long delta = ctxt->input->base - oldbase;
 		    start = start + delta;
		    in = in + delta;
		    last = last + delta;
		}
		end = ctxt->input->end;
	    }
	}
	if (*in != limit) goto need_complex;
    } else {
	while ((in < end) && (*in != limit) && (*in >= 0x20) &&
	       (*in <= 0x7f) && (*in != '&') && (*in != '<')) {
	    in++;
 	    if (in >= end) {
 		const xmlChar *oldbase = ctxt->input->base;
 		GROW;
 		if (oldbase != ctxt->input->base) {
 		    long delta = ctxt->input->base - oldbase;
 		    start = start + delta;
		    in = in + delta;
		}
		end = ctxt->input->end;
	    }
	}
	last = in;
	if (*in != limit) goto need_complex;
    }
    in++;
    if (len != NULL) {
        *len = last - start;
        ret = (xmlChar *) start;
    } else {
        if (alloc) *alloc = 1;
        ret = xmlStrndup(start, last - start);
    }
    CUR_PTR = in;
    if (alloc) *alloc = 0;
    return ret;
need_complex:
    if (alloc) *alloc = 1;
    return xmlParseAttValueComplex(ctxt, len, normalize);
}


checkitem_common(void *context, char_u *name, dict_T *dict)
{
    typval_T	*expr = (typval_T *)context;
    typval_T	save_val;
    typval_T	rettv;
    typval_T	argv[2];
    int		retval = 0;
    int		error = FALSE;

    prepare_vimvar(VV_VAL, &save_val);
    if (name != NULL)
    {
	set_vim_var_string(VV_VAL, name, -1);
	argv[0].v_type = VAR_STRING;
	argv[0].vval.v_string = name;
    }
    else
    {
	set_vim_var_dict(VV_VAL, dict);
	argv[0].v_type = VAR_DICT;
	argv[0].vval.v_dict = dict;
    }

    if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
	goto theend;

    // We want to use -1, but also true/false should be allowed.
    if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
    {
	rettv.v_type = VAR_NUMBER;
	rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
    }
    retval = tv_get_number_chk(&rettv, &error);
    if (error)
	retval = -1;
    clear_tv(&rettv);

theend:
    if (name != NULL)
	set_vim_var_string(VV_VAL, NULL, 0);
    else
	set_vim_var_dict(VV_VAL, NULL);
    restore_vimvar(VV_VAL, &save_val);
    return retval;
}


get_schema_name(int version)
{
    if (version < 0 || version >= xml_schema_max) {
        return "unknown";
    }
    return known_schemas[version].name;
}


bool acpi_osi_is_win8(void)
{
	return acpi_gbl_osi_data >= ACPI_OSI_WIN_8;
}


static void roq_encode_video ( RoqContext * enc ) {
 RoqTempdata * tempData = enc -> tmpData ;
 int i ;
 memset ( tempData , 0 , sizeof ( * tempData ) ) ;
 create_cel_evals ( enc , tempData ) ;
 generate_new_codebooks ( enc , tempData ) ;
 if ( enc -> framesSinceKeyframe >= 1 ) {
 motion_search ( enc , 8 ) ;
 motion_search ( enc , 4 ) ;
 }
 retry_encode : for ( i = 0 ;
 i < enc -> width * enc -> height / 64 ;
 i ++ ) gather_data_for_cel ( tempData -> cel_evals + i , enc , tempData ) ;
 if ( tempData -> mainChunkSize / 8 > 65535 ) {
 av_log ( enc -> avctx , AV_LOG_ERROR , "Warning, generated a frame too big (%d > 65535), " "try using a smaller qscale value.\n" , tempData -> mainChunkSize / 8 ) ;
 enc -> lambda *= 1.5 ;
 tempData -> mainChunkSize = 0 ;
 memset ( tempData -> used_option , 0 , sizeof ( tempData -> used_option ) ) ;
 memset ( tempData -> codebooks . usedCB4 , 0 , sizeof ( tempData -> codebooks . usedCB4 ) ) ;
 memset ( tempData -> codebooks . usedCB2 , 0 , sizeof ( tempData -> codebooks . usedCB2 ) ) ;
 goto retry_encode ;
 }
 remap_codebooks ( enc , tempData ) ;
 write_codebooks ( enc , tempData ) ;
 reconstruct_and_encode_image ( enc , tempData , enc -> width , enc -> height , enc -> width * enc -> height / 64 ) ;
 enc -> avctx -> coded_frame = enc -> current_frame ;
 FFSWAP ( AVFrame * , enc -> current_frame , enc -> last_frame ) ;
 FFSWAP ( motion_vect * , enc -> last_motion4 , enc -> this_motion4 ) ;
 FFSWAP ( motion_vect * , enc -> last_motion8 , enc -> this_motion8 ) ;
 av_free ( tempData -> cel_evals ) ;
 av_free ( tempData -> closest_cb2 ) ;
 enc -> framesSinceKeyframe ++ ;
 }


void nodeRename(Proxy &node, const RegexMatchConfigs &rename_array, extra_settings &ext)
{
    std::string &remark = node.Remark, original_remark = node.Remark, returned_remark, real_rule;

    for(const RegexMatchConfig &x : rename_array)
    {
        if(!x.Script.empty() && ext.authorized)
        {
            script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx)
            {
                std::string script = x.Script;
                if(startsWith(script, "path:"))
                    script = fileGet(script.substr(5), true);
                try
                {
                    ctx.eval(script);
                    auto rename = (std::function<std::string(const Proxy&)>) ctx.eval("rename");
                    returned_remark = rename(node);
                    if(!returned_remark.empty())
                        remark = returned_remark;
                }
                catch (qjs::exception)
                {
                    script_print_stack(ctx);
                }
            }, global.scriptCleanContext);
            continue;
        }
        if(applyMatcher(x.Match, real_rule, node) && real_rule.size())
            remark = regReplace(remark, real_rule, x.Replace);
    }
    if(remark.empty())
        remark = original_remark;
    return;
}


void auth_server_connection_disconnect ( struct auth_server_connection * conn , const char * reason ) {
 if ( ! conn -> connected ) return ;
 conn -> connected = FALSE ;
 conn -> handshake_received = FALSE ;
 conn -> version_received = FALSE ;
 conn -> has_plain_mech = FALSE ;
 conn -> server_pid = 0 ;
 conn -> connect_uid = 0 ;
 conn -> cookie = NULL ;
 array_clear ( & conn -> available_auth_mechs ) ;
 timeout_remove ( & conn -> to ) ;
 io_remove ( & conn -> io ) ;
 if ( conn -> fd != - 1 ) {
 i_stream_destroy ( & conn -> input ) ;
 o_stream_destroy ( & conn -> output ) ;
 if ( close ( conn -> fd ) < 0 ) i_error ( "close(auth server connection) failed: %m" ) ;
 conn -> fd = - 1 ;
 }
 auth_server_connection_remove_requests ( conn , reason ) ;
 if ( conn -> client -> connect_notify_callback != NULL ) {
 conn -> client -> connect_notify_callback ( conn -> client , FALSE , conn -> client -> connect_notify_context ) ;
 }
 }


static bool hal_open() {
  LOG_INFO("%s", __func__);

 int number_of_ports = vendor->send_command(VENDOR_OPEN_USERIAL, &uart_fds);

 if (number_of_ports != 2 && number_of_ports != 4) {
    LOG_ERROR("%s opened the wrong number of ports: got %d, expected 2 or 4.", __func__, number_of_ports);
 goto error;
 }

  LOG_INFO("%s got uart fds: CMD=%d, EVT=%d, ACL_OUT=%d, ACL_IN=%d",
      __func__, uart_fds[CH_CMD], uart_fds[CH_EVT], uart_fds[CH_ACL_OUT], uart_fds[CH_ACL_IN]);

 if (uart_fds[CH_CMD] == INVALID_FD) {
    LOG_ERROR("%s unable to open the command uart serial port.", __func__);
 goto error;
 }

 if (uart_fds[CH_EVT] == INVALID_FD) {
    LOG_ERROR("%s unable to open the event uart serial port.", __func__);
 goto error;
 }

 if (uart_fds[CH_ACL_OUT] == INVALID_FD) {
    LOG_ERROR("%s unable to open the acl-out uart serial port.", __func__);
 goto error;
 }

 if (uart_fds[CH_ACL_IN] == INVALID_FD) {
    LOG_ERROR("%s unable to open the acl-in uart serial port.", __func__);
 goto error;
 }

  event_stream = eager_reader_new(uart_fds[CH_EVT], &allocator_malloc, HCI_HAL_SERIAL_BUFFER_SIZE, SIZE_MAX, "hci_mct");
 if (!event_stream) {
    LOG_ERROR("%s unable to create eager reader for the event uart serial port.", __func__);
 goto error;
 }

  acl_stream = eager_reader_new(uart_fds[CH_ACL_IN], &allocator_malloc, HCI_HAL_SERIAL_BUFFER_SIZE, SIZE_MAX, "hci_mct");
 if (!event_stream) {
    LOG_ERROR("%s unable to create eager reader for the acl-in uart serial port.", __func__);
 goto error;
 }

  eager_reader_register(event_stream, thread_get_reactor(thread), event_event_stream_has_bytes, NULL);
  eager_reader_register(acl_stream, thread_get_reactor(thread), event_acl_stream_has_bytes, NULL);

 return true;

error:;
  interface.close();
 return false;
}


    JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
    {
        if (IsSmallIndex())
        {
            uint32 newIndex;
            if (UInt32Math::Add(index, delta, &newIndex))
            {
                return static_cast<uint64>(index) + static_cast<uint64>(delta);
            }
            else
            {
                return newIndex; // ok if newIndex == InvalidIndex
            }
        }
        else
        {
            return bigIndex + static_cast<uint64>(delta);
        }
    }


TEST_F(HTTP2CodecTest, BadSettings) {
  auto settings = upstreamCodec_.getEgressSettings();
  settings->setSetting(SettingsId::INITIAL_WINDOW_SIZE, 0xffffffff);
  upstreamCodec_.generateSettings(output_);

  parse();
  EXPECT_EQ(callbacks_.settings, 0);
  EXPECT_EQ(callbacks_.streamErrors, 0);
  EXPECT_EQ(callbacks_.sessionErrors, 1);
}


void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
			  unsigned long end, struct page *ref_page)
{
	mutex_lock(&vma->vm_file->f_mapping->i_mmap_mutex);
	__unmap_hugepage_range(vma, start, end, ref_page);
	mutex_unlock(&vma->vm_file->f_mapping->i_mmap_mutex);
}


void AutomationProvider::SetProxyConfig(const std::string& new_proxy_config) {
  URLRequestContextGetter* context_getter = Profile::GetDefaultRequestContext();
  if (!context_getter) {
    FilePath user_data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    DCHECK(profile_manager);
    Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
    DCHECK(profile);
    context_getter = profile->GetRequestContext();
  }
  DCHECK(context_getter);

  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      new SetProxyConfigTask(context_getter, new_proxy_config));
}


int blkcg_init_queue(struct request_queue *q)
{
	struct blkcg_gq *new_blkg, *blkg;
	bool preloaded;
	int ret;

	new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);
	if (!new_blkg)
		return -ENOMEM;

	preloaded = !radix_tree_preload(GFP_KERNEL);

	/*
	 * Make sure the root blkg exists and count the existing blkgs.  As
	 * @q is bypassing at this point, blkg_lookup_create() can't be
	 * used.  Open code insertion.
	 */
	rcu_read_lock();
	spin_lock_irq(q->queue_lock);
	blkg = blkg_create(&blkcg_root, q, new_blkg);
	spin_unlock_irq(q->queue_lock);
	rcu_read_unlock();

	if (preloaded)
		radix_tree_preload_end();

	if (IS_ERR(blkg)) {
		blkg_free(new_blkg);
		return PTR_ERR(blkg);
	}

	q->root_blkg = blkg;
	q->root_rl.blkg = blkg;

	ret = blk_throtl_init(q);
	if (ret) {
		spin_lock_irq(q->queue_lock);
		blkg_destroy_all(q);
		spin_unlock_irq(q->queue_lock);
	}
	return ret;
}


int SQLiteDatabase::RunIncrementalVacuumCommand() {
  MutexLocker locker(authorizer_lock_);
  EnableAuthorizer(false);

  if (!ExecuteCommand("PRAGMA incremental_vacuum"))
    SQL_DVLOG(1) << "Unable to run incremental vacuum - " << LastErrorMsg();

  EnableAuthorizer(true);
  return LastError();
}


PackLinuxElf::addStubEntrySections(Filter const *)
{
    addLoader("ELFMAINX", nullptr);
    if (hasLoaderSection("ELFMAINXu")) {
            // brk() trouble if static
        addLoader("ELFMAINXu", nullptr);
    }
   //addLoader(getDecompressorSections(), nullptr);
    addLoader(
        ( M_IS_NRV2E(ph.method) ? "NRV_HEAD,NRV2E,NRV_TAIL"
        : M_IS_NRV2D(ph.method) ? "NRV_HEAD,NRV2D,NRV_TAIL"
        : M_IS_NRV2B(ph.method) ? "NRV_HEAD,NRV2B,NRV_TAIL"
        : M_IS_LZMA(ph.method)  ? "LZMA_ELF00,LZMA_DEC20,LZMA_DEC30"
        : nullptr), nullptr);
    if (hasLoaderSection("CFLUSH"))
        addLoader("CFLUSH");
    addLoader("ELFMAINY,IDENTSTR", nullptr);
    if (hasLoaderSection("ELFMAINZe")) { // ppc64 big-endian only
        addLoader("ELFMAINZe", nullptr);
    }
    addLoader("+40,ELFMAINZ", nullptr);
    if (hasLoaderSection("ANDMAJNZ")) { // Android trouble with args to DT_INIT
        if (opt->o_unix.android_shlib) {
            addLoader("ANDMAJNZ", nullptr);  // constant PAGE_SIZE
        }
        else {
            addLoader("ELFMAJNZ", nullptr);  // PAGE_SIZE from AT_PAGESZ
        }
        addLoader("ELFMAKNZ", nullptr);
    }
    if (hasLoaderSection("ELFMAINZu")) {
        addLoader("ELFMAINZu", nullptr);
    }
    addLoader("FOLDEXEC", nullptr);
}


void __exit sco_exit(void)
{
	bt_procfs_cleanup(&init_net, "sco");

	debugfs_remove(sco_debugfs);

	bt_sock_unregister(BTPROTO_SCO);

	proto_unregister(&sco_proto);
}


qemuProcessRefreshBlockjobs(virQEMUDriverPtr driver,
                            virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV))
        return qemuBlockJobRefreshJobs(driver, vm);
    else
        return qemuProcessRefreshLegacyBlockjobs(driver, vm);
}


bool BrowserCommandController::IsShowingMainUI(bool is_fullscreen) {
#if !defined(OS_MACOSX)
  return browser_->is_type_tabbed() && !is_fullscreen;
#else
  return browser_->is_type_tabbed();
#endif
}


ves_icall_System_Type_EqualsInternal (MonoReflectionType *type, MonoReflectionType *c)
{
	MONO_ARCH_SAVE_REGS;

	if (c && type->type && c->type)
		return mono_metadata_type_equal (type->type, c->type);
	else
		return (type == c) ? TRUE : FALSE;
}