static bool checkreturn check_wire_type(pb_wire_type_t wire_type, pb_field_iter_t *field)
{
    switch (PB_LTYPE(field->type))
    {
        case PB_LTYPE_BOOL:
        case PB_LTYPE_VARINT:
        case PB_LTYPE_UVARINT:
        case PB_LTYPE_SVARINT:
            return wire_type == PB_WT_VARINT;

        case PB_LTYPE_FIXED32:
            return wire_type == PB_WT_32BIT;

        case PB_LTYPE_FIXED64:
            return wire_type == PB_WT_64BIT;

        case PB_LTYPE_BYTES:
        case PB_LTYPE_STRING:
        case PB_LTYPE_SUBMESSAGE:
        case PB_LTYPE_SUBMSG_W_CB:
        case PB_LTYPE_FIXED_LENGTH_BYTES:
            return wire_type == PB_WT_STRING;

        default:
            return false;
    }
}


static gint dissect_ac_if_input_terminal ( tvbuff_t * tvb , gint offset , packet_info * pinfo _U_ , proto_tree * tree , usb_conv_info_t * usb_conv_info _U_ ) {
 gint offset_start ;
 offset_start = offset ;
 proto_tree_add_item ( tree , hf_ac_if_input_terminalid , tvb , offset , 1 , ENC_LITTLE_ENDIAN ) ;
 offset += 1 ;
 proto_tree_add_item ( tree , hf_ac_if_input_terminaltype , tvb , offset , 2 , ENC_LITTLE_ENDIAN ) ;
 offset += 2 ;
 proto_tree_add_item ( tree , hf_ac_if_input_assocterminal , tvb , offset , 1 , ENC_LITTLE_ENDIAN ) ;
 offset += 1 ;
 proto_tree_add_item ( tree , hf_ac_if_input_nrchannels , tvb , offset , 1 , ENC_LITTLE_ENDIAN ) ;
 offset += 1 ;
 proto_tree_add_item ( tree , hf_ac_if_input_channelconfig , tvb , offset , 2 , ENC_LITTLE_ENDIAN ) ;
 offset += 2 ;
 proto_tree_add_item ( tree , hf_ac_if_input_channelnames , tvb , offset , 1 , ENC_LITTLE_ENDIAN ) ;
 offset += 1 ;
 proto_tree_add_item ( tree , hf_ac_if_input_terminal , tvb , offset , 1 , ENC_LITTLE_ENDIAN ) ;
 offset += 1 ;
 return offset - offset_start ;
 }


static int dissect_rsl_ie_tfo_status ( tvbuff_t * tvb , packet_info * pinfo _U_ , proto_tree * tree , int offset , gboolean is_mandatory ) {
 proto_tree * ie_tree ;
 guint8 ie_id ;
 if ( is_mandatory == FALSE ) {
 ie_id = tvb_get_guint8 ( tvb , offset ) ;
 if ( ie_id != RSL_IE_TFO_STATUS ) return offset ;
 }
 ie_tree = proto_tree_add_subtree ( tree , tvb , offset , 0 , ett_ie_tfo_status , NULL , "TFO Status IE" ) ;
 proto_tree_add_item ( ie_tree , hf_rsl_ie_id , tvb , offset , 1 , ENC_BIG_ENDIAN ) ;
 offset ++ ;
 proto_tree_add_item ( ie_tree , hf_rsl_tfo , tvb , offset , 1 , ENC_BIG_ENDIAN ) ;
 offset ++ ;
 return offset ;
 }


static int pop_read_header(struct PopData *pop_data, struct Header *h)
{
  int rc, index;
  size_t length;
  char buf[LONG_STRING];

  FILE *f = mutt_file_mkstemp();
  if (!f)
  {
    mutt_perror("mutt_file_mkstemp failed!");
    return -3;
  }

  snprintf(buf, sizeof(buf), "LIST %d\r\n", h->refno);
  rc = pop_query(pop_data, buf, sizeof(buf));
  if (rc == 0)
  {
    sscanf(buf, "+OK %d %zu", &index, &length);

    snprintf(buf, sizeof(buf), "TOP %d 0\r\n", h->refno);
    rc = pop_fetch_data(pop_data, buf, NULL, fetch_message, f);

    if (pop_data->cmd_top == 2)
    {
      if (rc == 0)
      {
        pop_data->cmd_top = 1;

        mutt_debug(1, "set TOP capability\n");
      }

      if (rc == -2)
      {
        pop_data->cmd_top = 0;

        mutt_debug(1, "unset TOP capability\n");
        snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s",
                 _("Command TOP is not supported by server."));
      }
    }
  }

  switch (rc)
  {
    case 0:
    {
      rewind(f);
      h->env = mutt_rfc822_read_header(f, h, 0, 0);
      h->content->length = length - h->content->offset + 1;
      rewind(f);
      while (!feof(f))
      {
        h->content->length--;
        fgets(buf, sizeof(buf), f);
      }
      break;
    }
    case -2:
    {
      mutt_error("%s", pop_data->err_msg);
      break;
    }
    case -3:
    {
      mutt_error(_("Can't write header to temporary file!"));
      break;
    }
  }

  mutt_file_fclose(&f);
  return rc;
}


void d_rehash(struct dentry * entry)
{
	spin_lock(&entry->d_lock);
	_d_rehash(entry);
	spin_unlock(&entry->d_lock);
}


int main(int argc, char *argv[])
{
    int option;
    int passlen=0;
    FILE *outfp = NULL;
    char outfile[1024];
    unsigned char pass[MAX_PASSWD_BUF];
    int file_count = 0;
    unsigned char bom[2];
    int password_acquired = 0;

    while ((option = getopt(argc, argv, "vhg:p:o:")) != -1)
    {
        switch (option)
        {
            case 'h':
                usage(argv[0]);
                return 0;
            case 'v':
                version(argv[0]);
                return 0;
            case 'g':
                if (password_acquired)
                {
                    fprintf(stderr, "Error: password supplied twice\n");
                    return -1;
                }
                if (optarg != 0)
                {
                    passlen = generate_password(atoi((char*) optarg),
                                                pass);
                    if (passlen < 0)
                    {
                        return -1;
                    }
                }
                password_acquired = 1;
                break;
            case 'p':
                if (password_acquired)
                {
                    fprintf(stderr, "Error: password supplied twice\n");
                    return -1;
                }
                if (optarg != 0)
                {
                    passlen = passwd_to_utf16(  (unsigned char*) optarg,
                                                strlen((char *)optarg),
                                                MAX_PASSWD_LEN,
                                                pass);
                    if (passlen < 0)
                    {
                        return -1;
                    }
                }
                password_acquired = 1;
                break;
            default:
                fprintf(stderr, "Error: Unknown option '%c'\n", option);
                return -1;
        }
    }

    file_count = argc - optind;
    if (file_count != 1)
    {
        fprintf(stderr, "Error: A single output file must be specified.\n");
        usage(argv[0]);
        /* For security reasons, erase the password */
        memset_secure(pass, 0, MAX_PASSWD_BUF);
        return -1;
    }
    else
    {
        /* What is the filename for the key file? */
        strncpy(outfile, argv[optind++], 1024);
        outfile[1023] = '\0';
    }

    /* Prompt for password if not provided on the command line */
    if (passlen == 0)
    {
        passlen = read_password(pass, ENC);

        switch (passlen)
        {
            case 0: /* no password in input */
                fprintf(stderr, "Error: No password supplied.\n");
                return -1;
            case AESCRYPT_READPWD_FOPEN:
            case AESCRYPT_READPWD_FILENO:
            case AESCRYPT_READPWD_TCGETATTR:
            case AESCRYPT_READPWD_TCSETATTR:
            case AESCRYPT_READPWD_FGETC:
            case AESCRYPT_READPWD_TOOLONG:
            case AESCRYPT_READPWD_ICONV:
                fprintf(stderr, "Error in read_password: %s.\n",
                        read_password_error(passlen));
                return -1;
            case AESCRYPT_READPWD_NOMATCH:
                fprintf(stderr, "Error: Passwords don't match.\n");
                return -1;
        }
    }

    if(!strcmp("-", outfile))
    {
        outfp = stdout;
    }
    else if ((outfp = fopen(outfile, "w")) == NULL)
    {
        fprintf(stderr, "Error opening output file %s : ", outfile);
        perror("");
        /* For security reasons, erase the password */
        memset_secure(pass, 0, MAX_PASSWD_BUF);
        return  -1;
    }

    /* Write the BOM.  AES Crypt uses UTF-16LE */
    bom[0] = 0xFF;
    bom[1] = 0xFE;
    if (fwrite(bom, 1, 2, outfp) != 2)
    {
        fprintf(stderr, "Error: Could not write BOM to password file.\n");
        if (strcmp("-",outfile))
        {
            fclose(outfp);
        }
        cleanup(outfile);
        return  -1;
    }

    if (fwrite(pass, 1, passlen, outfp) != (size_t) passlen)
    {
        fprintf(stderr, "Error: Could not write password file.\n");
        if (strcmp("-",outfile))
        {
            fclose(outfp);
        }
        cleanup(outfile);
        return  -1;
    }

    /* Close the output file, so long as it is not stdout */
    if (strcmp("-",outfile))
    {
        fclose(outfp);
    }

    /* For security reasons, erase the password */
    memset_secure(pass, 0, MAX_PASSWD_BUF);

    return 0;
}


static void _slurm_rpc_job_pack_alloc_info ( slurm_msg_t * msg ) {
 int error_code = SLURM_SUCCESS ;
 slurm_msg_t response_msg ;
 struct job_record * job_ptr , * pack_job ;
 ListIterator iter ;
 void * working_cluster_rec = NULL ;
 List resp ;
 DEF_TIMERS ;
 job_alloc_info_msg_t * job_info_msg = ( job_alloc_info_msg_t * ) msg -> data ;
 resource_allocation_response_msg_t * job_info_resp_msg ;
 slurmctld_lock_t job_read_lock = {
 READ_LOCK , READ_LOCK , READ_LOCK , NO_LOCK , NO_LOCK }
 ;
 uid_t uid = g_slurm_auth_get_uid ( msg -> auth_cred , slurmctld_config . auth_info ) ;
 START_TIMER ;
 debug2 ( "Processing RPC: REQUEST_JOB_PACK_ALLOC_INFO from uid=%d" , uid ) ;
 lock_slurmctld ( job_read_lock ) ;
 error_code = job_alloc_info ( uid , job_info_msg -> job_id , & job_ptr ) ;
 END_TIMER2 ( "_slurm_rpc_job_pack_alloc_info" ) ;
 if ( ( error_code == SLURM_SUCCESS ) && job_ptr && ( job_ptr -> pack_job_id && ! job_ptr -> pack_job_list ) ) error_code = ESLURM_NOT_PACK_JOB_LEADER ;
 if ( error_code || ( job_ptr == NULL ) || ( job_ptr -> job_resrcs == NULL ) ) {
 unlock_slurmctld ( job_read_lock ) ;
 debug2 ( "%s: JobId=%u, uid=%u: %s" , __func__ , job_info_msg -> job_id , uid , slurm_strerror ( error_code ) ) ;
 slurm_send_rc_msg ( msg , error_code ) ;
 return ;
 }
 debug ( "%s: JobId=%u NodeList=%s %s" , __func__ , job_info_msg -> job_id , job_ptr -> nodes , TIME_STR ) ;
 if ( ! job_ptr -> pack_job_list ) {
 resp = list_create ( _pack_alloc_list_del ) ;
 job_info_resp_msg = build_job_info_resp ( job_ptr ) ;
 set_remote_working_response ( job_info_resp_msg , job_ptr , job_info_msg -> req_cluster ) ;
 list_append ( resp , job_info_resp_msg ) ;
 }
 else {
 resp = list_create ( _pack_alloc_list_del ) ;
 iter = list_iterator_create ( job_ptr -> pack_job_list ) ;
 while ( ( pack_job = ( struct job_record * ) list_next ( iter ) ) ) {
 if ( job_ptr -> pack_job_id != pack_job -> pack_job_id ) {
 error ( "%s: Bad pack_job_list for job %u" , __func__ , job_ptr -> pack_job_id ) ;
 continue ;
 }
 if ( pack_job -> job_id != job_info_msg -> job_id ) ( void ) job_alloc_info_ptr ( uid , pack_job ) ;
 job_info_resp_msg = build_job_info_resp ( pack_job ) ;
 if ( working_cluster_rec ) {
 job_info_resp_msg -> working_cluster_rec = working_cluster_rec ;
 }
 else {
 set_remote_working_response ( job_info_resp_msg , pack_job , job_info_msg -> req_cluster ) ;
 working_cluster_rec = job_info_resp_msg -> working_cluster_rec ;
 }
 list_append ( resp , job_info_resp_msg ) ;
 }
 list_iterator_destroy ( iter ) ;
 }
 unlock_slurmctld ( job_read_lock ) ;
 slurm_msg_t_init ( & response_msg ) ;
 response_msg . msg_type = RESPONSE_JOB_PACK_ALLOCATION ;
 response_msg . data = resp ;
 response_msg . flags = msg -> flags ;
 response_msg . protocol_version = msg -> protocol_version ;
 slurm_send_node_msg ( msg -> conn_fd , & response_msg ) ;
 FREE_NULL_LIST ( resp ) ;
 }


int mnt_fs_get_passno(struct libmnt_fs *fs)
{
	return fs ? fs->passno: 0;
}


void Magick::Image::strokeWidth(const double strokeWidth_)
{
  char
    value[MagickPathExtent];

  modifyImage();
  options()->strokeWidth(strokeWidth_);
  FormatLocaleString(value,MagickPathExtent,"%.20g",strokeWidth_);
  (void) SetImageArtifact(image(),"strokewidth",value);
}


static inline void pxa2xx_rtc_hz_tick ( void * opaque ) {
 PXA2xxRTCState * s = ( PXA2xxRTCState * ) opaque ;
 s -> rtsr |= ( 1 << 0 ) ;
 pxa2xx_rtc_alarm_update ( s , s -> rtsr ) ;
 pxa2xx_rtc_int_update ( s ) ;
 }


static int shared_policy_replace(struct shared_policy *sp, unsigned long start,
				 unsigned long end, struct sp_node *new)
{
	struct sp_node *n;
	struct sp_node *n_new = NULL;
	struct mempolicy *mpol_new = NULL;
	int ret = 0;

restart:
	write_lock(&sp->lock);
	n = sp_lookup(sp, start, end);
	/* Take care of old policies in the same range. */
	while (n && n->start < end) {
		struct rb_node *next = rb_next(&n->nd);
		if (n->start >= start) {
			if (n->end <= end)
				sp_delete(sp, n);
			else
				n->start = end;
		} else {
			/* Old policy spanning whole new range. */
			if (n->end > end) {
				if (!n_new)
					goto alloc_new;

				*mpol_new = *n->policy;
				atomic_set(&mpol_new->refcnt, 1);
				sp_node_init(n_new, end, n->end, mpol_new);
				n->end = start;
				sp_insert(sp, n_new);
				n_new = NULL;
				mpol_new = NULL;
				break;
			} else
				n->end = start;
		}
		if (!next)
			break;
		n = rb_entry(next, struct sp_node, nd);
	}
	if (new)
		sp_insert(sp, new);
	write_unlock(&sp->lock);
	ret = 0;

err_out:
	if (mpol_new)
		mpol_put(mpol_new);
	if (n_new)
		kmem_cache_free(sn_cache, n_new);

	return ret;

alloc_new:
	write_unlock(&sp->lock);
	ret = -ENOMEM;
	n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
	if (!n_new)
		goto err_out;
	mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
	if (!mpol_new)
		goto err_out;
	goto restart;
}


int vp9_get_reference_mode_context ( const VP9_COMMON * cm , const MACROBLOCKD * xd ) {
 int ctx ;
 const MB_MODE_INFO * const above_mbmi = get_mbmi ( get_above_mi ( xd ) ) ;
 const MB_MODE_INFO * const left_mbmi = get_mbmi ( get_left_mi ( xd ) ) ;
 const int has_above = above_mbmi != NULL ;
 const int has_left = left_mbmi != NULL ;
 if ( has_above && has_left ) {
 if ( ! has_second_ref ( above_mbmi ) && ! has_second_ref ( left_mbmi ) ) ctx = ( above_mbmi -> ref_frame [ 0 ] == cm -> comp_fixed_ref ) ^ ( left_mbmi -> ref_frame [ 0 ] == cm -> comp_fixed_ref ) ;
 else if ( ! has_second_ref ( above_mbmi ) ) ctx = 2 + ( above_mbmi -> ref_frame [ 0 ] == cm -> comp_fixed_ref || ! is_inter_block ( above_mbmi ) ) ;
 else if ( ! has_second_ref ( left_mbmi ) ) ctx = 2 + ( left_mbmi -> ref_frame [ 0 ] == cm -> comp_fixed_ref || ! is_inter_block ( left_mbmi ) ) ;
 else ctx = 4 ;
 }
 else if ( has_above || has_left ) {
 const MB_MODE_INFO * edge_mbmi = has_above ? above_mbmi : left_mbmi ;
 if ( ! has_second_ref ( edge_mbmi ) ) ctx = edge_mbmi -> ref_frame [ 0 ] == cm -> comp_fixed_ref ;
 else ctx = 3 ;
 }
 else {
 ctx = 1 ;
 }
 assert ( ctx >= 0 && ctx < COMP_INTER_CONTEXTS ) ;
 return ctx ;
 }


static int has_spaces(const char *path)
{
  if (strchr(path, ' ') != NULL)
    return 1;
  return 0;
}


bool canIterate() { return iteration_state_ == IterationState::Continue; }


bool IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
  return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
         navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
         navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
}


static GF_Err gf_isom_get_3gpp_audio_esd(GF_SampleTableBox *stbl, u32 type, GF_GenericAudioSampleEntryBox *entry, GF_ESD **out_esd)
{
	(*out_esd) = gf_odf_desc_esd_new(2);
	(*out_esd)->decoderConfig->streamType = GF_STREAM_AUDIO;
	/*official mapping to MPEG-4*/
	switch (type) {
	case GF_ISOM_SUBTYPE_3GP_EVRC:
		(*out_esd)->decoderConfig->objectTypeIndication = GF_CODECID_EVRC;
		return GF_OK;
	case GF_ISOM_SUBTYPE_3GP_QCELP:
	{
		u32 block_size, sample_rate, sample_size, i;
		GF_SttsEntry *ent;
		GF_BitStream *bs;
		char szName[80];
		/*only map CBR*/
		sample_size = stbl->SampleSize->sampleSize;
		(*out_esd)->decoderConfig->objectTypeIndication = GF_CODECID_QCELP;
		bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
		gf_bs_write_data(bs, "QLCMfmt ", 8);
		gf_bs_write_u32_le(bs, 150);/*fmt chunk size*/
		gf_bs_write_u8(bs, 1);
		gf_bs_write_u8(bs, 0);
		/*QCELP GUID*/
		gf_bs_write_data(bs, "\x41\x6D\x7F\x5E\x15\xB1\xD0\x11\xBA\x91\x00\x80\x5F\xB4\xB9\x7E", 16);
		gf_bs_write_u16_le(bs, 1);
		memset(szName, 0, 80);
		strcpy(szName, "QCELP-13K(GPAC-emulated)");
		gf_bs_write_data(bs, szName, 80);
		ent = &stbl->TimeToSample->entries[0];
		sample_rate = entry->samplerate_hi;
		block_size = ent ? ent->sampleDelta : 160;
		gf_bs_write_u16_le(bs, 8*sample_size*sample_rate/block_size);
		gf_bs_write_u16_le(bs, sample_size);
		gf_bs_write_u16_le(bs, block_size);
		gf_bs_write_u16_le(bs, sample_rate);
		gf_bs_write_u16_le(bs, entry->bitspersample);
		gf_bs_write_u32_le(bs, sample_size ? 0 : 7);
		/**/
		for (i=0; i<7; i++) {
			static const u32 qcelp_r2s [] = {0, 1, 1, 4, 2, 8, 3, 17, 4, 35, 5, 8, 14, 1};
			if (sample_size) {
				gf_bs_write_u16(bs, 0);
			} else {
				gf_bs_write_u8(bs, qcelp_r2s[2*i+1]);
				gf_bs_write_u8(bs, qcelp_r2s[2*i]);
			}
		}
		gf_bs_write_u16(bs, 0);
		memset(szName, 0, 80);
		gf_bs_write_data(bs, szName, 20);/*reserved*/
		gf_bs_get_content(bs, & (*out_esd)->decoderConfig->decoderSpecificInfo->data, & (*out_esd)->decoderConfig->decoderSpecificInfo->dataLength);
		gf_bs_del(bs);
	}
	return GF_OK;
	case GF_ISOM_SUBTYPE_3GP_SMV:
		(*out_esd)->decoderConfig->objectTypeIndication = GF_CODECID_SMV;
		return GF_OK;
	case GF_ISOM_SUBTYPE_3GP_AMR:
		(*out_esd)->decoderConfig->objectTypeIndication = GF_CODECID_AMR;
		return GF_OK;
	case GF_ISOM_SUBTYPE_3GP_AMR_WB:
		(*out_esd)->decoderConfig->objectTypeIndication = GF_CODECID_AMR_WB;
		return GF_OK;
	default:
		GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] unsupported sample description type %s\n", gf_4cc_to_str(entry->type)));
		break;
	}
	return GF_OK;
}


static void rtl8xxxu_rx_parse_phystats(struct rtl8xxxu_priv *priv,
				       struct ieee80211_rx_status *rx_status,
				       struct rtl8723au_phy_stats *phy_stats,
				       u32 rxmcs)
{
	if (phy_stats->sgi_en)
		rx_status->enc_flags |= RX_ENC_FLAG_SHORT_GI;

	if (rxmcs < DESC_RATE_6M) {
		/*
		 * Handle PHY stats for CCK rates
		 */
		u8 cck_agc_rpt = phy_stats->cck_agc_rpt_ofdm_cfosho_a;

		switch (cck_agc_rpt & 0xc0) {
		case 0xc0:
			rx_status->signal = -46 - (cck_agc_rpt & 0x3e);
			break;
		case 0x80:
			rx_status->signal = -26 - (cck_agc_rpt & 0x3e);
			break;
		case 0x40:
			rx_status->signal = -12 - (cck_agc_rpt & 0x3e);
			break;
		case 0x00:
			rx_status->signal = 16 - (cck_agc_rpt & 0x3e);
			break;
		}
	} else {
		rx_status->signal =
			(phy_stats->cck_sig_qual_ofdm_pwdb_all >> 1) - 110;
	}
}


GF_Box *hvcc_box_new()
{
	GF_HEVCConfigurationBox *tmp = (GF_HEVCConfigurationBox *) gf_malloc(sizeof(GF_HEVCConfigurationBox));
	if (tmp == NULL) return NULL;
	memset(tmp, 0, sizeof(GF_HEVCConfigurationBox));
	tmp->type = GF_ISOM_BOX_TYPE_HVCC;
	return (GF_Box *)tmp;
}


static int do_attach(USBDevice *dev)

{

    USBBus *bus = usb_bus_from_device(dev);

    USBPort *port;

    if (dev->attached) {

        error_report("Error: tried to attach usb device %s twice\n",

                dev->product_desc);

        return -1;

    }

    if (bus->nfree == 0) {

        error_report("Error: tried to attach usb device %s to a bus with no free ports\n",

                dev->product_desc);

        return -1;

    }

    if (dev->port_path) {

        QTAILQ_FOREACH(port, &bus->free, next) {

            if (strcmp(port->path, dev->port_path) == 0) {

                break;

            }

        }

        if (port == NULL) {

            error_report("Error: usb port %s (bus %s) not found\n",

                    dev->port_path, bus->qbus.name);

            return -1;

        }

    } else {

        port = QTAILQ_FIRST(&bus->free);

    }

    if (!(port->speedmask & dev->speedmask)) {

        error_report("Warning: speed mismatch trying to attach usb device %s to bus %s\n",

                dev->product_desc, bus->qbus.name);

        return -1;

    }

    dev->attached++;

    QTAILQ_REMOVE(&bus->free, port, next);

    bus->nfree--;

    usb_attach(port, dev);

    QTAILQ_INSERT_TAIL(&bus->used, port, next);

    bus->nused++;

    return 0;

}


TIFFWriteCustomDirectory(TIFF* tif, uint64* pdiroff)
{
	return TIFFWriteDirectorySec(tif,FALSE,FALSE,pdiroff);
}


static void ccid3_hc_rx_get_info(struct sock *sk, struct tcp_info *info)
{
	info->tcpi_ca_state = ccid3_hc_rx_sk(sk)->rx_state;
	info->tcpi_options  |= TCPI_OPT_TIMESTAMPS;
	info->tcpi_rcv_rtt  = ccid3_hc_rx_sk(sk)->rx_rtt;
}


sixel_dither_set_body_only(
    sixel_dither_t /* in */ *dither,     /* dither context object */
    int            /* in */ bodyonly)    /* 0: output palette section
                                            1: do not output palette section  */
{
    dither->bodyonly = bodyonly;
}


TEST_F ( ProtocolHandlerRegistryTest , TestClearDefault ) {
 ProtocolHandler ph1 = CreateProtocolHandler ( "test" , "test1" ) ;
 ProtocolHandler ph2 = CreateProtocolHandler ( "test" , "test2" ) ;
 registry ( ) -> OnAcceptRegisterProtocolHandler ( ph1 ) ;
 registry ( ) -> OnAcceptRegisterProtocolHandler ( ph2 ) ;
 registry ( ) -> OnAcceptRegisterProtocolHandler ( ph1 ) ;
 registry ( ) -> ClearDefault ( "test" ) ;
 ASSERT_FALSE ( registry ( ) -> IsDefault ( ph1 ) ) ;
 ASSERT_FALSE ( registry ( ) -> IsDefault ( ph2 ) ) ;
 }


static void print_help()
{
  MEM_ROOT mem_root;
  init_alloc_root(&mem_root, 4096, 4096);

  pop_dynamic(&all_options);
  sys_var_add_options(&all_options, sys_var::PARSE_EARLY);
  add_plugin_options(&all_options, &mem_root);
  sort_dynamic(&all_options, (qsort_cmp) option_cmp);
  add_terminator(&all_options);

  my_print_help((my_option*) all_options.buffer);
  my_print_variables((my_option*) all_options.buffer);

  free_root(&mem_root, MYF(0));
}


  void FlipBooleanAttr(const string& attr_name, NodeDef* node) {
    const bool old_value =
        !node->attr().count(attr_name) ? false : node->attr().at(attr_name).b();
    (*node->mutable_attr())[attr_name].set_b(!old_value);
  }


Status Examples::CreateSparseFeatureRepresentation(
    const DeviceBase::CpuWorkerThreads& worker_threads, const int num_examples,
    const int num_sparse_features, const ModelWeights& weights,
    const OpInputList& sparse_example_indices_inputs,
    const OpInputList& sparse_feature_indices_inputs,
    const OpInputList& sparse_feature_values_inputs,
    std::vector<Example>* const examples) {
  mutex mu;
  Status result;  // Guarded by mu
  auto parse_partition = [&](const int64 begin, const int64 end) {
    // The static_cast here is safe since begin and end can be at most
    // num_examples which is an int.
    for (int i = static_cast<int>(begin); i < end; ++i) {
      auto example_indices =
          sparse_example_indices_inputs[i].template flat<int64>();
      auto feature_indices =
          sparse_feature_indices_inputs[i].template flat<int64>();

      // Parse features for each example. Features for a particular example
      // are at the offsets (start_id, end_id]
      int start_id = -1;
      int end_id = 0;
      for (int example_id = 0; example_id < num_examples; ++example_id) {
        start_id = end_id;
        while (end_id < example_indices.size() &&
               example_indices(end_id) == example_id) {
          ++end_id;
        }
        Example::SparseFeatures* const sparse_features =
            &(*examples)[example_id].sparse_features_[i];
        if (start_id < example_indices.size() &&
            example_indices(start_id) == example_id) {
          sparse_features->indices.reset(new UnalignedInt64Vector(
              &(feature_indices(start_id)), end_id - start_id));
          if (sparse_feature_values_inputs.size() > i) {
            auto feature_weights =
                sparse_feature_values_inputs[i].flat<float>();
            sparse_features->values.reset(new UnalignedFloatVector(
                &(feature_weights(start_id)), end_id - start_id));
          }
          // If features are non empty.
          if (end_id - start_id > 0) {
            // TODO(sibyl-Aix6ihai): Write this efficiently using vectorized
            // operations from eigen.
            for (int64 k = 0; k < sparse_features->indices->size(); ++k) {
              const int64 feature_index = (*sparse_features->indices)(k);
              if (!weights.SparseIndexValid(i, feature_index)) {
                mutex_lock l(mu);
                result = errors::InvalidArgument(
                    "Found sparse feature indices out of valid range: ",
                    (*sparse_features->indices)(k));
                return;
              }
            }
          }
        } else {
          // Add a Tensor that has size 0.
          sparse_features->indices.reset(
              new UnalignedInt64Vector(&(feature_indices(0)), 0));
          // If values exist for this feature group.
          if (sparse_feature_values_inputs.size() > i) {
            auto feature_weights =
                sparse_feature_values_inputs[i].flat<float>();
            sparse_features->values.reset(
                new UnalignedFloatVector(&(feature_weights(0)), 0));
          }
        }
      }
    }
  };
  // For each column, the cost of parsing it is O(num_examples). We use
  // num_examples here, as empirically Shard() creates the right amount of
  // threads based on the problem size.
  // TODO(sibyl-Aix6ihai): Tune this as a function of dataset size.
  const int64 kCostPerUnit = num_examples;
  Shard(worker_threads.num_threads, worker_threads.workers, num_sparse_features,
        kCostPerUnit, parse_partition);
  return result;
}


DisplayManager* GetDisplayManager() {
  return Shell::GetInstance()->display_manager();
}


bool StyleResolver::isPropertyForPass(CSSPropertyID property)
{
    COMPILE_ASSERT(CSSPropertyVariable < firstCSSProperty, CSS_variable_is_before_first_property);
    const CSSPropertyID firstAnimationProperty = CSSPropertyDisplay;
    const CSSPropertyID lastAnimationProperty = CSSPropertyTransitionTimingFunction;
    COMPILE_ASSERT(firstCSSProperty == firstAnimationProperty, CSS_first_animation_property_should_be_first_property);
    const CSSPropertyID firstHighPriorityProperty = CSSPropertyColor;
    const CSSPropertyID lastHighPriorityProperty = CSSPropertyLineHeight;
    COMPILE_ASSERT(lastAnimationProperty + 1 == firstHighPriorityProperty, CSS_color_is_first_high_priority_property);
    COMPILE_ASSERT(CSSPropertyLineHeight == firstHighPriorityProperty + 17, CSS_line_height_is_end_of_high_prioity_property_range);
    COMPILE_ASSERT(CSSPropertyZoom == lastHighPriorityProperty - 1, CSS_zoom_is_before_line_height);
    switch (pass) {
    case VariableDefinitions:
        return property == CSSPropertyVariable;
    case AnimationProperties:
        return property >= firstAnimationProperty && property <= lastAnimationProperty;
    case HighPriorityProperties:
        return property >= firstHighPriorityProperty && property <= lastHighPriorityProperty;
    case LowPriorityProperties:
        return property > lastHighPriorityProperty;
    }
    ASSERT_NOT_REACHED();
    return false;
}


void ResourceMultiBufferDataProvider::DidReceiveResponse(
    const WebURLResponse& response) {
#if DCHECK_IS_ON()
  std::string version;
  switch (response.HttpVersion()) {
    case WebURLResponse::kHTTPVersion_0_9:
      version = "0.9";
      break;
    case WebURLResponse::kHTTPVersion_1_0:
      version = "1.0";
      break;
    case WebURLResponse::kHTTPVersion_1_1:
      version = "1.1";
      break;
    case WebURLResponse::kHTTPVersion_2_0:
      version = "2.1";
      break;
    case WebURLResponse::kHTTPVersionUnknown:
      version = "unknown";
      break;
  }
  DVLOG(1) << "didReceiveResponse: HTTP/" << version << " "
           << response.HttpStatusCode();
#endif
  DCHECK(active_loader_);

  scoped_refptr<UrlData> destination_url_data(url_data_);

  if (!redirects_to_.is_empty()) {
    destination_url_data =
        url_data_->url_index()->GetByUrl(redirects_to_, cors_mode_);
    redirects_to_ = GURL();
  }

  base::Time last_modified;
  if (base::Time::FromString(
          response.HttpHeaderField("Last-Modified").Utf8().data(),
          &last_modified)) {
    destination_url_data->set_last_modified(last_modified);
  }

  destination_url_data->set_etag(
      response.HttpHeaderField("ETag").Utf8().data());

  destination_url_data->set_valid_until(base::Time::Now() +
                                        GetCacheValidUntil(response));

  uint32_t reasons = GetReasonsForUncacheability(response);
  destination_url_data->set_cacheable(reasons == 0);
  UMA_HISTOGRAM_BOOLEAN("Media.CacheUseful", reasons == 0);
  int shift = 0;
  int max_enum = base::bits::Log2Ceiling(kMaxReason);
  while (reasons) {
    DCHECK_LT(shift, max_enum);  // Sanity check.
    if (reasons & 0x1) {
      UMA_HISTOGRAM_EXACT_LINEAR("Media.UncacheableReason", shift,
                                 max_enum);  // PRESUBMIT_IGNORE_UMA_MAX
    }

    reasons >>= 1;
    ++shift;
  }

   int64_t content_length = response.ExpectedContentLength();
   bool end_of_file = false;
   bool do_fail = false;
   bytes_to_discard_ = 0;

  if (destination_url_data->url().SchemeIsHTTPOrHTTPS()) {
    bool partial_response = (response.HttpStatusCode() == kHttpPartialContent);
    bool ok_response = (response.HttpStatusCode() == kHttpOK);

    std::string accept_ranges =
        response.HttpHeaderField("Accept-Ranges").Utf8();
    if (accept_ranges.find("bytes") != std::string::npos)
      destination_url_data->set_range_supported();

    if (partial_response &&
        VerifyPartialResponse(response, destination_url_data)) {
      destination_url_data->set_range_supported();
    } else if (ok_response) {
      destination_url_data->set_length(content_length);
      bytes_to_discard_ = byte_pos();
    } else if (response.HttpStatusCode() == kHttpRangeNotSatisfiable) {
      end_of_file = true;
    } else {
      active_loader_.reset();
      do_fail = true;
    }
  } else {
    destination_url_data->set_range_supported();
    if (content_length != kPositionNotSpecified) {
      destination_url_data->set_length(content_length + byte_pos());
    }
  }

  if (!do_fail) {
    destination_url_data =
         url_data_->url_index()->TryInsert(destination_url_data);
   }

  destination_url_data->set_has_opaque_data(
      network::cors::IsCORSCrossOriginResponseType(response.GetType()));

   if (destination_url_data != url_data_) {

    scoped_refptr<UrlData> old_url_data(url_data_);
    destination_url_data->Use();

    std::unique_ptr<DataProvider> self(
        url_data_->multibuffer()->RemoveProvider(this));
    url_data_ = destination_url_data.get();
    url_data_->multibuffer()->AddProvider(std::move(self));

    old_url_data->RedirectTo(destination_url_data);
  }

  if (do_fail) {
    destination_url_data->Fail();
    return;  // "this" may be deleted now.
  }

  const GURL& original_url = response.WasFetchedViaServiceWorker()
                                 ? response.OriginalURLViaServiceWorker()
                                 : response.Url();
  if (!url_data_->ValidateDataOrigin(original_url.GetOrigin())) {
    active_loader_.reset();
    url_data_->Fail();
    return;  // "this" may be deleted now.
  }

  if (end_of_file) {
    fifo_.push_back(DataBuffer::CreateEOSBuffer());
    url_data_->multibuffer()->OnDataProviderEvent(this);
  }
}


void WebViewPlugin::startDragging(const WebDragData&,
                                  WebDragOperationsMask,
                                  const WebImage&,
                                  const WebPoint&) {
  web_view_->dragSourceSystemDragEnded();
}


xmlFreeRef(xmlLinkPtr lk) {
    xmlRefPtr ref = (xmlRefPtr)xmlLinkGetData(lk);
    if (ref == NULL) return;
    if (ref->value != NULL)
        xmlFree((xmlChar *)ref->value);
    if (ref->name != NULL)
        xmlFree((xmlChar *)ref->name);
    xmlFree(ref);
}


static int get_cox(J2kDecoderContext *s, J2kCodingStyle *c)

{

    if (s->buf_end - s->buf < 5)

        return AVERROR(EINVAL);

          c->nreslevels = bytestream_get_byte(&s->buf) + 1; // num of resolution levels - 1

     c->log2_cblk_width = bytestream_get_byte(&s->buf) + 2; // cblk width

    c->log2_cblk_height = bytestream_get_byte(&s->buf) + 2; // cblk height

    c->cblk_style = bytestream_get_byte(&s->buf);

    if (c->cblk_style != 0){ // cblk style

        av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);

    }

    c->transform = bytestream_get_byte(&s->buf); // transformation

    if (c->csty & J2K_CSTY_PREC) {

        int i;

        for (i = 0; i < c->nreslevels; i++)

            bytestream_get_byte(&s->buf);

    }

    return 0;

}


void imap_quote_string (char *dest, size_t dlen, const char *src)
{
  _imap_quote_string (dest, dlen, src, "\"\\");
}


static void loop_filter_rows_mt ( const YV12_BUFFER_CONFIG * const frame_buffer , VP9_COMMON * const cm , struct macroblockd_plane planes [ MAX_MB_PLANE ] , int start , int stop , int y_only , VP9LfSync * const lf_sync , int num_lf_workers ) {
 const int num_planes = y_only ? 1 : MAX_MB_PLANE ;
 int r , c ;
 const int sb_cols = mi_cols_aligned_to_sb ( cm -> mi_cols ) >> MI_BLOCK_SIZE_LOG2 ;
 for ( r = start ;
 r < stop ;
 r += num_lf_workers ) {
 const int mi_row = r << MI_BLOCK_SIZE_LOG2 ;
 MODE_INFO * const mi = cm -> mi + mi_row * cm -> mi_stride ;
 for ( c = 0 ;
 c < sb_cols ;
 ++ c ) {
 const int mi_col = c << MI_BLOCK_SIZE_LOG2 ;
 LOOP_FILTER_MASK lfm ;
 int plane ;
 sync_read ( lf_sync , r , c ) ;
 vp9_setup_dst_planes ( planes , frame_buffer , mi_row , mi_col ) ;
 vp9_setup_mask ( cm , mi_row , mi_col , mi + mi_col , cm -> mi_stride , & lfm ) ;
 for ( plane = 0 ;
 plane < num_planes ;
 ++ plane ) {
 vp9_filter_block_plane ( cm , & planes [ plane ] , mi_row , & lfm ) ;
 }
 sync_write ( lf_sync , r , c , sb_cols ) ;
 }
 }
 }


static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
	int start = 0;
	int i;
	u32 prev_legacy, cur_legacy;
	struct kvm_pit *pit = kvm->arch.vpit;

	mutex_lock(&pit->pit_state.lock);
	prev_legacy = pit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
	cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
	if (!prev_legacy && cur_legacy)
		start = 1;
	memcpy(&pit->pit_state.channels, &ps->channels,
	       sizeof(pit->pit_state.channels));
	pit->pit_state.flags = ps->flags;
	for (i = 0; i < 3; i++)
		kvm_pit_load_count(pit, i, pit->pit_state.channels[i].count,
				   start && i == 0);
	mutex_unlock(&pit->pit_state.lock);
	return 0;
}


ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */
{
	zend_bool old, ini;

	if (ZSTR_LEN(entry->name) == sizeof("phar.readonly")-1) {
		old = PHAR_G(readonly_orig);
	} else {
		old = PHAR_G(require_hash_orig);
	}

	if (ZSTR_LEN(new_value) == 2 && !strcasecmp("on", ZSTR_VAL(new_value))) {
		ini = (zend_bool) 1;
	}
	else if (ZSTR_LEN(new_value) == 3 && !strcasecmp("yes", ZSTR_VAL(new_value))) {
		ini = (zend_bool) 1;
	}
	else if (ZSTR_LEN(new_value) == 4 && !strcasecmp("true", ZSTR_VAL(new_value))) {
		ini = (zend_bool) 1;
	}
	else {
		ini = (zend_bool) atoi(ZSTR_VAL(new_value));
	}

	/* do not allow unsetting in runtime */
	if (stage == ZEND_INI_STAGE_STARTUP) {
		if (ZSTR_LEN(entry->name) == sizeof("phar.readonly")-1) {
			PHAR_G(readonly_orig) = ini;
		} else {
			PHAR_G(require_hash_orig) = ini;
		}
	} else if (old && !ini) {
		return FAILURE;
	}

	if (ZSTR_LEN(entry->name) == sizeof("phar.readonly")-1) {
		PHAR_G(readonly) = ini;
		if (PHAR_G(request_init) && PHAR_G(phar_fname_map.u.flags)) {
			zend_hash_apply_with_argument(&(PHAR_G(phar_fname_map)), phar_set_writeable_bit, (void *)&ini);
		}
	} else {
		PHAR_G(require_hash) = ini;
	}

	return SUCCESS;
}
/* }}}*/


krb5_error_code krb5_ldap_put_principal ( krb5_context context , krb5_db_entry * entry , char * * db_args ) {
 int l = 0 , kerberos_principal_object_type = 0 ;
 unsigned int ntrees = 0 , tre = 0 ;
 krb5_error_code st = 0 , tempst = 0 ;
 LDAP * ld = NULL ;
 LDAPMessage * result = NULL , * ent = NULL ;
 char * * subtreelist = NULL ;
 char * user = NULL , * subtree = NULL , * principal_dn = NULL ;
 char * * values = NULL , * strval [ 10 ] = {
 NULL }
 , errbuf [ 1024 ] ;
 char * filtuser = NULL ;
 struct berval * * bersecretkey = NULL ;
 LDAPMod * * mods = NULL ;
 krb5_boolean create_standalone_prinicipal = FALSE ;
 krb5_boolean krb_identity_exists = FALSE , establish_links = FALSE ;
 char * standalone_principal_dn = NULL ;
 krb5_tl_data * tl_data = NULL ;
 krb5_key_data * * keys = NULL ;
 kdb5_dal_handle * dal_handle = NULL ;
 krb5_ldap_context * ldap_context = NULL ;
 krb5_ldap_server_handle * ldap_server_handle = NULL ;
 osa_princ_ent_rec princ_ent = {
 0 }
 ;
 xargs_t xargs = {
 0 }
 ;
 char * polname = NULL ;
 OPERATION optype ;
 krb5_boolean found_entry = FALSE ;
 krb5_clear_error_message ( context ) ;
 SETUP_CONTEXT ( ) ;
 if ( ldap_context -> lrparams == NULL || ldap_context -> container_dn == NULL ) return EINVAL ;
 GET_HANDLE ( ) ;
 if ( ! is_principal_in_realm ( ldap_context , entry -> princ ) ) {
 st = EINVAL ;
 k5_setmsg ( context , st , _ ( "Principal does not belong to the default realm" ) ) ;
 goto cleanup ;
 }
 if ( ( ( st = krb5_unparse_name ( context , entry -> princ , & user ) ) != 0 ) || ( ( st = krb5_ldap_unparse_principal_name ( user ) ) != 0 ) ) goto cleanup ;
 filtuser = ldap_filter_correct ( user ) ;
 if ( filtuser == NULL ) {
 st = ENOMEM ;
 goto cleanup ;
 }
 if ( entry -> mask & KADM5_PRINCIPAL ) optype = ADD_PRINCIPAL ;
 else optype = MODIFY_PRINCIPAL ;
 if ( ( ( st = krb5_get_princ_type ( context , entry , & kerberos_principal_object_type ) ) != 0 ) || ( ( st = krb5_get_userdn ( context , entry , & principal_dn ) ) != 0 ) ) goto cleanup ;
 if ( ( st = process_db_args ( context , db_args , & xargs , optype ) ) != 0 ) goto cleanup ;
 if ( entry -> mask & KADM5_LOAD ) {
 unsigned int tree = 0 ;
 int numlentries = 0 ;
 char * filter = NULL ;
 if ( asprintf ( & filter , FILTER "%s))" , filtuser ) < 0 ) {
 filter = NULL ;
 st = ENOMEM ;
 goto cleanup ;
 }
 if ( ( st = krb5_get_subtree_info ( ldap_context , & subtreelist , & ntrees ) ) != 0 ) goto cleanup ;
 found_entry = FALSE ;
 for ( tree = 0 ;
 found_entry == FALSE && tree < ntrees ;
 ++ tree ) {
 if ( principal_dn == NULL ) {
 LDAP_SEARCH_1 ( subtreelist [ tree ] , ldap_context -> lrparams -> search_scope , filter , principal_attributes , IGNORE_STATUS ) ;
 }
 else {
 LDAP_SEARCH_1 ( principal_dn , LDAP_SCOPE_BASE , filter , principal_attributes , IGNORE_STATUS ) ;
 }
 if ( st == LDAP_SUCCESS ) {
 numlentries = ldap_count_entries ( ld , result ) ;
 if ( numlentries > 1 ) {
 free ( filter ) ;
 st = EINVAL ;
 k5_setmsg ( context , st , _ ( "operation can not continue, more than one " "entry with principal name \"%s\" found" ) , user ) ;
 goto cleanup ;
 }
 else if ( numlentries == 1 ) {
 found_entry = TRUE ;
 if ( principal_dn == NULL ) {
 ent = ldap_first_entry ( ld , result ) ;
 if ( ent != NULL ) {
 if ( ( principal_dn = ldap_get_dn ( ld , ent ) ) == NULL ) {
 ldap_get_option ( ld , LDAP_OPT_RESULT_CODE , & st ) ;
 st = set_ldap_error ( context , st , 0 ) ;
 free ( filter ) ;
 goto cleanup ;
 }
 }
 }
 }
 }
 else if ( st != LDAP_NO_SUCH_OBJECT ) {
 st = set_ldap_error ( context , st , 0 ) ;
 free ( filter ) ;
 goto cleanup ;
 }
 ldap_msgfree ( result ) ;
 result = NULL ;
 }
 free ( filter ) ;
 if ( found_entry == FALSE && principal_dn != NULL ) {
 create_standalone_prinicipal = TRUE ;
 standalone_principal_dn = strdup ( principal_dn ) ;
 CHECK_NULL ( standalone_principal_dn ) ;
 }
 }
 if ( principal_dn == NULL && xargs . dn == NULL ) {
 if ( entry -> princ -> length == 2 && entry -> princ -> data [ 0 ] . length == strlen ( "krbtgt" ) && strncmp ( entry -> princ -> data [ 0 ] . data , "krbtgt" , entry -> princ -> data [ 0 ] . length ) == 0 ) {
 subtree = strdup ( ldap_context -> lrparams -> realmdn ) ;
 }
 else if ( xargs . containerdn ) {
 if ( ( st = checkattributevalue ( ld , xargs . containerdn , NULL , NULL , NULL ) ) != 0 ) {
 if ( st == KRB5_KDB_NOENTRY || st == KRB5_KDB_CONSTRAINT_VIOLATION ) {
 int ost = st ;
 st = EINVAL ;
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "'%s' not found: " ) , xargs . containerdn ) ;
 prepend_err_str ( context , errbuf , st , ost ) ;
 }
 goto cleanup ;
 }
 subtree = strdup ( xargs . containerdn ) ;
 }
 else if ( ldap_context -> lrparams -> containerref && strlen ( ldap_context -> lrparams -> containerref ) != 0 ) {
 subtree = strdup ( ldap_context -> lrparams -> containerref ) ;
 }
 else {
 subtree = strdup ( ldap_context -> lrparams -> realmdn ) ;
 }
 CHECK_NULL ( subtree ) ;
 if ( asprintf ( & standalone_principal_dn , "krbprincipalname=%s,%s" , filtuser , subtree ) < 0 ) standalone_principal_dn = NULL ;
 CHECK_NULL ( standalone_principal_dn ) ;
 create_standalone_prinicipal = TRUE ;
 free ( subtree ) ;
 subtree = NULL ;
 }
 if ( xargs . dn_from_kbd == TRUE ) {
 int dnlen = 0 , subtreelen = 0 ;
 char * dn = NULL ;
 krb5_boolean outofsubtree = TRUE ;
 if ( xargs . dn != NULL ) {
 dn = xargs . dn ;
 }
 else if ( xargs . linkdn != NULL ) {
 dn = xargs . linkdn ;
 }
 else if ( standalone_principal_dn != NULL ) {
 dn = standalone_principal_dn ;
 }
 if ( subtreelist == NULL ) {
 st = krb5_get_subtree_info ( ldap_context , & subtreelist , & ntrees ) ;
 if ( st ) goto cleanup ;
 }
 for ( tre = 0 ;
 tre < ntrees ;
 ++ tre ) {
 if ( subtreelist [ tre ] == NULL || strlen ( subtreelist [ tre ] ) == 0 ) {
 outofsubtree = FALSE ;
 break ;
 }
 else {
 dnlen = strlen ( dn ) ;
 subtreelen = strlen ( subtreelist [ tre ] ) ;
 if ( ( dnlen >= subtreelen ) && ( strcasecmp ( ( dn + dnlen - subtreelen ) , subtreelist [ tre ] ) == 0 ) ) {
 outofsubtree = FALSE ;
 break ;
 }
 }
 }
 if ( outofsubtree == TRUE ) {
 st = EINVAL ;
 k5_setmsg ( context , st , _ ( "DN is out of the realm subtree" ) ) ;
 goto cleanup ;
 }
 if ( standalone_principal_dn == NULL ) {
 char * attributes [ ] = {
 "krbticketpolicyreference" , "krbprincipalname" , NULL }
 ;
 ldap_msgfree ( result ) ;
 result = NULL ;
 LDAP_SEARCH_1 ( dn , LDAP_SCOPE_BASE , 0 , attributes , IGNORE_STATUS ) ;
 if ( st == LDAP_SUCCESS ) {
 ent = ldap_first_entry ( ld , result ) ;
 if ( ent != NULL ) {
 if ( ( values = ldap_get_values ( ld , ent , "krbticketpolicyreference" ) ) != NULL ) {
 ldap_value_free ( values ) ;
 }
 if ( ( values = ldap_get_values ( ld , ent , "krbprincipalname" ) ) != NULL ) {
 krb_identity_exists = TRUE ;
 ldap_value_free ( values ) ;
 }
 }
 }
 else {
 st = set_ldap_error ( context , st , OP_SEARCH ) ;
 goto cleanup ;
 }
 }
 }
 if ( xargs . dn != NULL && krb_identity_exists == TRUE ) {
 st = EINVAL ;
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "ldap object is already kerberized" ) ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 goto cleanup ;
 }
 if ( xargs . linkdn != NULL ) {
 if ( optype == MODIFY_PRINCIPAL && kerberos_principal_object_type != KDB_STANDALONE_PRINCIPAL_OBJECT ) {
 st = EINVAL ;
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "link information can not be set/updated as the " "kerberos principal belongs to an ldap object" ) ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 goto cleanup ;
 }
 {
 char * * linkdns = NULL ;
 int j = 0 ;
 if ( ( st = krb5_get_linkdn ( context , entry , & linkdns ) ) != 0 ) {
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "Failed getting object references" ) ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 goto cleanup ;
 }
 if ( linkdns != NULL ) {
 st = EINVAL ;
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "kerberos principal is already linked to a ldap " "object" ) ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 for ( j = 0 ;
 linkdns [ j ] != NULL ;
 ++ j ) free ( linkdns [ j ] ) ;
 free ( linkdns ) ;
 goto cleanup ;
 }
 }
 establish_links = TRUE ;
 }
 if ( entry -> mask & KADM5_LAST_SUCCESS ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( entry -> last_success ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbLastSuccessfulAuth" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 if ( entry -> mask & KADM5_LAST_FAILED ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( entry -> last_failed ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbLastFailedAuth" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 if ( entry -> mask & KADM5_FAIL_AUTH_COUNT ) {
 krb5_kvno fail_auth_count ;
 fail_auth_count = entry -> fail_auth_count ;
 if ( entry -> mask & KADM5_FAIL_AUTH_COUNT_INCREMENT ) fail_auth_count ++ ;
 st = krb5_add_int_mem_ldap_mod ( & mods , "krbLoginFailedCount" , LDAP_MOD_REPLACE , fail_auth_count ) ;
 if ( st != 0 ) goto cleanup ;
 }
 else if ( entry -> mask & KADM5_FAIL_AUTH_COUNT_INCREMENT ) {
 int attr_mask = 0 ;
 krb5_boolean has_fail_count ;
 st = krb5_get_attributes_mask ( context , entry , & attr_mask ) ;
 if ( st != 0 ) goto cleanup ;
 has_fail_count = ( ( attr_mask & KDB_FAIL_AUTH_COUNT_ATTR ) != 0 ) ;
 # ifdef LDAP_MOD_INCREMENT if ( ldap_server_handle -> server_info -> modify_increment && has_fail_count ) {
 st = krb5_add_int_mem_ldap_mod ( & mods , "krbLoginFailedCount" , LDAP_MOD_INCREMENT , 1 ) ;
 if ( st != 0 ) goto cleanup ;
 }
 else {
 # endif if ( has_fail_count ) {
 st = krb5_add_int_mem_ldap_mod ( & mods , "krbLoginFailedCount" , LDAP_MOD_DELETE , entry -> fail_auth_count ) ;
 if ( st != 0 ) goto cleanup ;
 }
 st = krb5_add_int_mem_ldap_mod ( & mods , "krbLoginFailedCount" , LDAP_MOD_ADD , entry -> fail_auth_count + 1 ) ;
 if ( st != 0 ) goto cleanup ;
 # ifdef LDAP_MOD_INCREMENT }
 # endif }
 else if ( optype == ADD_PRINCIPAL ) {
 st = krb5_add_int_mem_ldap_mod ( & mods , "krbLoginFailedCount" , LDAP_MOD_ADD , 0 ) ;
 }
 if ( entry -> mask & KADM5_MAX_LIFE ) {
 if ( ( st = krb5_add_int_mem_ldap_mod ( & mods , "krbmaxticketlife" , LDAP_MOD_REPLACE , entry -> max_life ) ) != 0 ) goto cleanup ;
 }
 if ( entry -> mask & KADM5_MAX_RLIFE ) {
 if ( ( st = krb5_add_int_mem_ldap_mod ( & mods , "krbmaxrenewableage" , LDAP_MOD_REPLACE , entry -> max_renewable_life ) ) != 0 ) goto cleanup ;
 }
 if ( entry -> mask & KADM5_ATTRIBUTES ) {
 if ( ( st = krb5_add_int_mem_ldap_mod ( & mods , "krbticketflags" , LDAP_MOD_REPLACE , entry -> attributes ) ) != 0 ) goto cleanup ;
 }
 if ( entry -> mask & KADM5_PRINCIPAL ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 strval [ 0 ] = user ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbprincipalname" , LDAP_MOD_REPLACE , strval ) ) != 0 ) goto cleanup ;
 }
 if ( entry -> mask & KADM5_PRINC_EXPIRE_TIME ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( entry -> expiration ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbprincipalexpiration" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 if ( entry -> mask & KADM5_PW_EXPIRATION ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( entry -> pw_expiration ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbpasswordexpiration" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 if ( entry -> mask & KADM5_POLICY ) {
 memset ( & princ_ent , 0 , sizeof ( princ_ent ) ) ;
 for ( tl_data = entry -> tl_data ;
 tl_data ;
 tl_data = tl_data -> tl_data_next ) {
 if ( tl_data -> tl_data_type == KRB5_TL_KADM_DATA ) {
 if ( ( st = krb5_lookup_tl_kadm_data ( tl_data , & princ_ent ) ) != 0 ) {
 goto cleanup ;
 }
 break ;
 }
 }
 if ( princ_ent . aux_attributes & KADM5_POLICY ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( st = krb5_ldap_name_to_policydn ( context , princ_ent . policy , & polname ) ) != 0 ) goto cleanup ;
 strval [ 0 ] = polname ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbpwdpolicyreference" , LDAP_MOD_REPLACE , strval ) ) != 0 ) goto cleanup ;
 }
 else {
 st = EINVAL ;
 k5_setmsg ( context , st , "Password policy value null" ) ;
 goto cleanup ;
 }
 }
 else if ( entry -> mask & KADM5_LOAD && found_entry == TRUE ) {
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbpwdpolicyreference" , LDAP_MOD_REPLACE , NULL ) ) != 0 ) goto cleanup ;
 }
 if ( entry -> mask & KADM5_POLICY_CLR ) {
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbpwdpolicyreference" , LDAP_MOD_DELETE , NULL ) ) != 0 ) goto cleanup ;
 }
 if ( entry -> mask & KADM5_KEY_DATA || entry -> mask & KADM5_KVNO ) {
 krb5_kvno mkvno ;
 if ( ( st = krb5_dbe_lookup_mkvno ( context , entry , & mkvno ) ) != 0 ) goto cleanup ;
 bersecretkey = krb5_encode_krbsecretkey ( entry -> key_data , entry -> n_key_data , mkvno ) ;
 if ( ( st = krb5_add_ber_mem_ldap_mod ( & mods , "krbprincipalkey" , LDAP_MOD_REPLACE | LDAP_MOD_BVALUES , bersecretkey ) ) != 0 ) goto cleanup ;
 if ( ! ( entry -> mask & KADM5_PRINCIPAL ) ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( entry -> pw_expiration ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbpasswordexpiration" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 {
 krb5_timestamp last_pw_changed ;
 if ( ( st = krb5_dbe_lookup_last_pwd_change ( context , entry , & last_pw_changed ) ) != 0 ) goto cleanup ;
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( last_pw_changed ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbLastPwdChange" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 }
 if ( entry -> tl_data != NULL ) {
 int count = 0 ;
 struct berval * * ber_tl_data = NULL ;
 krb5_tl_data * ptr ;
 krb5_timestamp unlock_time ;
 for ( ptr = entry -> tl_data ;
 ptr != NULL ;
 ptr = ptr -> tl_data_next ) {
 if ( ptr -> tl_data_type == KRB5_TL_LAST_PWD_CHANGE # ifdef SECURID || ptr -> tl_data_type == KRB5_TL_DB_ARGS # endif || ptr -> tl_data_type == KRB5_TL_KADM_DATA || ptr -> tl_data_type == KDB_TL_USER_INFO || ptr -> tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr -> tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK ) continue ;
 count ++ ;
 }
 if ( count != 0 ) {
 int j ;
 ber_tl_data = ( struct berval * * ) calloc ( count + 1 , sizeof ( struct berval * ) ) ;
 if ( ber_tl_data == NULL ) {
 st = ENOMEM ;
 goto cleanup ;
 }
 for ( j = 0 , ptr = entry -> tl_data ;
 ptr != NULL ;
 ptr = ptr -> tl_data_next ) {
 if ( ptr -> tl_data_type == KRB5_TL_LAST_PWD_CHANGE # ifdef SECURID || ptr -> tl_data_type == KRB5_TL_DB_ARGS # endif || ptr -> tl_data_type == KRB5_TL_KADM_DATA || ptr -> tl_data_type == KDB_TL_USER_INFO || ptr -> tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL || ptr -> tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK ) continue ;
 if ( ( st = tl_data2berval ( ptr , & ber_tl_data [ j ] ) ) != 0 ) break ;
 j ++ ;
 }
 if ( st == 0 ) {
 ber_tl_data [ count ] = NULL ;
 st = krb5_add_ber_mem_ldap_mod ( & mods , "krbExtraData" , LDAP_MOD_REPLACE | LDAP_MOD_BVALUES , ber_tl_data ) ;
 }
 for ( j = 0 ;
 ber_tl_data [ j ] != NULL ;
 j ++ ) {
 free ( ber_tl_data [ j ] -> bv_val ) ;
 free ( ber_tl_data [ j ] ) ;
 }
 free ( ber_tl_data ) ;
 if ( st != 0 ) goto cleanup ;
 }
 if ( ( st = krb5_dbe_lookup_last_admin_unlock ( context , entry , & unlock_time ) ) != 0 ) goto cleanup ;
 if ( unlock_time != 0 ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 if ( ( strval [ 0 ] = getstringtime ( unlock_time ) ) == NULL ) goto cleanup ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbLastAdminUnlock" , LDAP_MOD_REPLACE , strval ) ) != 0 ) {
 free ( strval [ 0 ] ) ;
 goto cleanup ;
 }
 free ( strval [ 0 ] ) ;
 }
 }
 if ( xargs . tktpolicydn != NULL ) {
 int tmask = 0 ;
 if ( strlen ( xargs . tktpolicydn ) != 0 ) {
 st = checkattributevalue ( ld , xargs . tktpolicydn , "objectclass" , policyclass , & tmask ) ;
 CHECK_CLASS_VALIDITY ( st , tmask , _ ( "ticket policy object value: " ) ) ;
 strval [ 0 ] = xargs . tktpolicydn ;
 strval [ 1 ] = NULL ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbticketpolicyreference" , LDAP_MOD_REPLACE , strval ) ) != 0 ) goto cleanup ;
 }
 else {
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbticketpolicyreference" , LDAP_MOD_DELETE , NULL ) ) != 0 ) goto cleanup ;
 }
 }
 if ( establish_links == TRUE ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 strval [ 0 ] = xargs . linkdn ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "krbObjectReferences" , LDAP_MOD_REPLACE , strval ) ) != 0 ) goto cleanup ;
 }
 if ( mods == NULL ) goto cleanup ;
 if ( create_standalone_prinicipal == TRUE ) {
 memset ( strval , 0 , sizeof ( strval ) ) ;
 strval [ 0 ] = "krbprincipal" ;
 strval [ 1 ] = "krbprincipalaux" ;
 strval [ 2 ] = "krbTicketPolicyAux" ;
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "objectclass" , LDAP_MOD_ADD , strval ) ) != 0 ) goto cleanup ;
 st = ldap_add_ext_s ( ld , standalone_principal_dn , mods , NULL , NULL ) ;
 if ( st == LDAP_ALREADY_EXISTS && entry -> mask & KADM5_LOAD ) {
 st = ldap_delete_ext_s ( ld , standalone_principal_dn , NULL , NULL ) ;
 if ( st != LDAP_SUCCESS ) {
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "Principal delete failed (trying to replace " "entry): %s" ) , ldap_err2string ( st ) ) ;
 st = translate_ldap_error ( st , OP_ADD ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 goto cleanup ;
 }
 else {
 st = ldap_add_ext_s ( ld , standalone_principal_dn , mods , NULL , NULL ) ;
 }
 }
 if ( st != LDAP_SUCCESS ) {
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "Principal add failed: %s" ) , ldap_err2string ( st ) ) ;
 st = translate_ldap_error ( st , OP_ADD ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 goto cleanup ;
 }
 }
 else {
 {
 char * attrvalues [ ] = {
 "krbprincipalaux" , "krbTicketPolicyAux" , NULL }
 ;
 int p , q , r = 0 , amask = 0 ;
 if ( ( st = checkattributevalue ( ld , ( xargs . dn ) ? xargs . dn : principal_dn , "objectclass" , attrvalues , & amask ) ) != 0 ) goto cleanup ;
 memset ( strval , 0 , sizeof ( strval ) ) ;
 for ( p = 1 , q = 0 ;
 p <= 2 ;
 p <<= 1 , ++ q ) {
 if ( ( p & amask ) == 0 ) strval [ r ++ ] = attrvalues [ q ] ;
 }
 if ( r != 0 ) {
 if ( ( st = krb5_add_str_mem_ldap_mod ( & mods , "objectclass" , LDAP_MOD_ADD , strval ) ) != 0 ) goto cleanup ;
 }
 }
 if ( xargs . dn != NULL ) st = ldap_modify_ext_s ( ld , xargs . dn , mods , NULL , NULL ) ;
 else st = ldap_modify_ext_s ( ld , principal_dn , mods , NULL , NULL ) ;
 if ( st != LDAP_SUCCESS ) {
 snprintf ( errbuf , sizeof ( errbuf ) , _ ( "User modification failed: %s" ) , ldap_err2string ( st ) ) ;
 st = translate_ldap_error ( st , OP_MOD ) ;
 k5_setmsg ( context , st , "%s" , errbuf ) ;
 goto cleanup ;
 }
 if ( entry -> mask & KADM5_FAIL_AUTH_COUNT_INCREMENT ) entry -> fail_auth_count ++ ;
 }
 cleanup : if ( user ) free ( user ) ;
 if ( filtuser ) free ( filtuser ) ;
 free_xargs ( xargs ) ;
 if ( standalone_principal_dn ) free ( standalone_principal_dn ) ;
 if ( principal_dn ) free ( principal_dn ) ;
 if ( polname != NULL ) free ( polname ) ;
 for ( tre = 0 ;
 tre < ntrees ;
 tre ++ ) free ( subtreelist [ tre ] ) ;
 free ( subtreelist ) ;
 if ( subtree ) free ( subtree ) ;
 if ( bersecretkey ) {
 for ( l = 0 ;
 bersecretkey [ l ] ;
 ++ l ) {
 if ( bersecretkey [ l ] -> bv_val ) free ( bersecretkey [ l ] -> bv_val ) ;
 free ( bersecretkey [ l ] ) ;
 }
 free ( bersecretkey ) ;
 }
 if ( keys ) free ( keys ) ;
 ldap_mods_free ( mods , 1 ) ;
 ldap_osa_free_princ_ent ( & princ_ent ) ;
 ldap_msgfree ( result ) ;
 krb5_ldap_put_handle_to_pool ( ldap_context , ldap_server_handle ) ;
 return ( st ) ;
 }


static int vhost_user_set_vring_addr(struct vhost_dev *dev,

                                     struct vhost_vring_addr *addr)

{

    VhostUserMsg msg = {

        .request = VHOST_USER_SET_VRING_ADDR,

        .flags = VHOST_USER_VERSION,

        .payload.addr = *addr,

        .size = sizeof(msg.payload.addr),

    };

    vhost_user_write(dev, &msg, NULL, 0);

    return 0;

}


z2save(i_ctx_t *i_ctx_p)
{
    if (!save_page_device(igs))
        return zsave(i_ctx_p);
    return push_callout(i_ctx_p, "%savepagedevice");
}


  MockAutofillDownloadManager(AutofillDriver* driver,
                              AutofillDownloadManager::Observer* observer)
      : TestAutofillDownloadManager(driver, observer) {}


static int irda_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
	struct sock *sk = sock->sk;
	struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
	struct irda_sock *self = irda_sk(sk);
	int err;

	pr_debug("%s(%p)\n", __func__, self);

	if (addr_len != sizeof(struct sockaddr_irda))
		return -EINVAL;

	lock_sock(sk);
#ifdef CONFIG_IRDA_ULTRA
	/* Special care for Ultra sockets */
	if ((sk->sk_type == SOCK_DGRAM) &&
	    (sk->sk_protocol == IRDAPROTO_ULTRA)) {
		self->pid = addr->sir_lsap_sel;
		err = -EOPNOTSUPP;
		if (self->pid & 0x80) {
			pr_debug("%s(), extension in PID not supp!\n",
				 __func__);
			goto out;
		}
		err = irda_open_lsap(self, self->pid);
		if (err < 0)
			goto out;

		/* Pretend we are connected */
		sock->state = SS_CONNECTED;
		sk->sk_state   = TCP_ESTABLISHED;
		err = 0;

		goto out;
	}
#endif /* CONFIG_IRDA_ULTRA */

	self->ias_obj = irias_new_object(addr->sir_name, jiffies);
	err = -ENOMEM;
	if (self->ias_obj == NULL)
		goto out;

	err = irda_open_tsap(self, addr->sir_lsap_sel, addr->sir_name);
	if (err < 0) {
		irias_delete_object(self->ias_obj);
		self->ias_obj = NULL;
		goto out;
	}

	/*  Register with LM-IAS */
	irias_add_integer_attrib(self->ias_obj, "IrDA:TinyTP:LsapSel",
				 self->stsap_sel, IAS_KERNEL_ATTR);
	irias_insert_object(self->ias_obj);

	err = 0;
out:
	release_sock(sk);
	return err;
}


void DoInplaceOp(const CPUDevice& d, InplaceOpType op, const Tensor& i,
                 const Tensor& v, Tensor* y) {
  auto Ti = i.flat<int32>();
  auto Tv = v.flat_outer_dims<T>();
  auto Ty = y->flat_outer_dims<T>();
  auto nrows = Ty.dimension(0);
  for (int64_t j = 0; j < Ti.size(); ++j) {
    auto r = (Ti(j) % nrows + nrows) % nrows;  // Guard index range.
    switch (op) {
      case I_UPDATE:
        Ty.template chip<0>(r).device(d) = Tv.template chip<0>(j);
        break;
      case I_ADD:
        Ty.template chip<0>(r).device(d) += Tv.template chip<0>(j);
        break;
      case I_SUB:
        Ty.template chip<0>(r).device(d) -= Tv.template chip<0>(j);
        break;
    }
  }
}


static int _find_specialuse(const mbentry_t *mbentry, void *rock)
{
    struct _find_specialuse_data *d = (struct _find_specialuse_data *)rock;
    struct buf attrib = BUF_INITIALIZER;

    annotatemore_lookup(mbentry->name, "/specialuse", d->userid, &attrib);

    if (attrib.len) {
        strarray_t *uses = strarray_split(buf_cstring(&attrib), " ", 0);
        if (strarray_find_case(uses, d->use, 0) >= 0)
            d->mboxname = xstrdup(mbentry->name);
        strarray_free(uses);
    }

    buf_free(&attrib);

    if (d->mboxname) return CYRUSDB_DONE;
    return 0;
}


TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE(context, NumInputs(node) == 1 || NumInputs(node) == 2);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);

  // Always postpone sizing string tensors, even if we could in principle
  // calculate their shapes now. String tensors don't benefit from having their
  // shapes precalculated because the actual memory can only be allocated after
  // we know all the content.
  TfLiteTensor* output;
  TF_LITE_ENSURE_OK(context,
                    GetOutputSafe(context, node, kOutputTensor, &output));
  if (output->type != kTfLiteString) {
    if (NumInputs(node) == 1 ||
        IsConstantTensor(GetInput(context, node, kShapeTensor))) {
      TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
    } else {
      SetTensorToDynamic(output);
    }
  }
  return kTfLiteOk;
}


static int opvmon(RAsm *a, ut8 *data, const Opcode *op) {
	int l = 0;
	switch (op->operands_count) {
	case 1:
		if ( op->operands[0].type & OT_MEMORY &&
		     op->operands[0].type & OT_QWORD
		     ) {
			data[l++] = 0xf3;
			data[l++] = 0x0f;
			data[l++] = 0xc7;
			data[l++] = 0x30 | op->operands[0].regs[0];
		} else {
			return -1;
		}
		break;
	default:
		return -1;
	}
	return l;
}


static int add_recvbuf_mergeable(struct receive_queue *rq, gfp_t gfp)
{
	struct page_frag *alloc_frag = &rq->alloc_frag;
	char *buf;
	unsigned long ctx;
	int err;
	unsigned int len, hole;

	len = get_mergeable_buf_len(&rq->mrg_avg_pkt_len);
	if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
		return -ENOMEM;

	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
	ctx = mergeable_buf_to_ctx(buf, len);
	get_page(alloc_frag->page);
	alloc_frag->offset += len;
	hole = alloc_frag->size - alloc_frag->offset;
	if (hole < len) {
		/* To avoid internal fragmentation, if there is very likely not
		 * enough space for another buffer, add the remaining space to
		 * the current buffer. This extra space is not included in
		 * the truesize stored in ctx.
		 */
		len += hole;
		alloc_frag->offset += hole;
	}

	sg_init_one(rq->sg, buf, len);
	err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, (void *)ctx, gfp);
	if (err < 0)
		put_page(virt_to_head_page(buf));

	return err;
}


  void TestProcessOverflow() {
    int tab_count = 1;
    int host_count = 1;
    WebContents* tab1 = NULL;
    WebContents* tab2 = NULL;
    content::RenderProcessHost* rph1 = NULL;
    content::RenderProcessHost* rph2 = NULL;
    content::RenderProcessHost* rph3 = NULL;

    const extensions::Extension* extension =
        LoadExtension(test_data_dir_.AppendASCII("options_page"));

    GURL omnibox(chrome::kChromeUIOmniboxURL);
    ui_test_utils::NavigateToURL(browser(), omnibox);
    EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
    tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
    rph1 = tab1->GetMainFrame()->GetProcess();
    EXPECT_EQ(omnibox, tab1->GetURL());
    EXPECT_EQ(host_count, RenderProcessHostCount());

    GURL page1("data:text/html,hello world1");

    ui_test_utils::WindowedTabAddedNotificationObserver observer1(
        content::NotificationService::AllSources());
    ::ShowSingletonTab(browser(), page1);
    observer1.Wait();

    tab_count++;
    host_count++;
    EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
    tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
    rph2 = tab1->GetMainFrame()->GetProcess();
    EXPECT_EQ(tab1->GetURL(), page1);
    EXPECT_EQ(host_count, RenderProcessHostCount());
    EXPECT_NE(rph1, rph2);

    GURL page2("data:text/html,hello world2");
    ui_test_utils::WindowedTabAddedNotificationObserver observer2(
        content::NotificationService::AllSources());
    ::ShowSingletonTab(browser(), page2);
    observer2.Wait();
    tab_count++;
    if (content::AreAllSitesIsolatedForTesting())
      host_count++;
    EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
    tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
    EXPECT_EQ(tab2->GetURL(), page2);
    EXPECT_EQ(host_count, RenderProcessHostCount());
    if (content::AreAllSitesIsolatedForTesting())
      EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2);
     else
       EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2);

    // Create another WebUI tab.  Each WebUI tab should get a separate process
    // because of origin locking.
    GURL history(chrome::kChromeUIHistoryURL);
    ui_test_utils::WindowedTabAddedNotificationObserver observer3(
        content::NotificationService::AllSources());
     ::ShowSingletonTab(browser(), history);
     observer3.Wait();
     tab_count++;
    host_count++;
     EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
     tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
     EXPECT_EQ(tab2->GetURL(), GURL(history));
     EXPECT_EQ(host_count, RenderProcessHostCount());
    EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph1);

     GURL extension_url("chrome-extension://" + extension->id());
    ui_test_utils::WindowedTabAddedNotificationObserver observer4(
        content::NotificationService::AllSources());
    ::ShowSingletonTab(browser(), extension_url);

    observer4.Wait();
    tab_count++;
    host_count++;
    EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
    tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
    rph3 = tab1->GetMainFrame()->GetProcess();
    EXPECT_EQ(tab1->GetURL(), extension_url);
    EXPECT_EQ(host_count, RenderProcessHostCount());
    EXPECT_NE(rph1, rph3);
    EXPECT_NE(rph2, rph3);
  }


xmlSAXParseMemoryWithData(xmlSAXHandlerPtr sax, const char *buffer,
	          int size, int recovery, void *data) {
    xmlDocPtr ret;
    xmlParserCtxtPtr ctxt;

    xmlInitParser();

    ctxt = xmlCreateMemoryParserCtxt(buffer, size);
    if (ctxt == NULL) return(NULL);
    if (sax != NULL) {
	if (ctxt->sax != NULL)
	    xmlFree(ctxt->sax);
        ctxt->sax = sax;
    }
    xmlDetectSAX2(ctxt);
    if (data!=NULL) {
	ctxt->_private=data;
    }

    ctxt->recovery = recovery;

    xmlParseDocument(ctxt);

    if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc;
    else {
       ret = NULL;
       xmlFreeDoc(ctxt->myDoc);
       ctxt->myDoc = NULL;
    }
    if (sax != NULL)
	ctxt->sax = NULL;
    xmlFreeParserCtxt(ctxt);

    return(ret);
}


  static void InsertBroadcastLabels(int num_bcast_dims, int num_named_labels,
                                    int ellipsis_axis, Labels* labels,
                                    LabelCounts* label_counts) {
    labels->erase(labels->begin() + ellipsis_axis);
    labels->insert(labels->begin() + ellipsis_axis, num_bcast_dims, 0);
    std::iota(labels->begin() + ellipsis_axis,
              labels->begin() + ellipsis_axis + num_bcast_dims,
              num_named_labels);
    // Increment label counts. Since these are new labels, the count is set
    // to 1.
    label_counts->resize(num_named_labels + num_bcast_dims, 1);
  }


static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)

{

    cirrus_fill_t rop_func;

    if (blit_is_unsafe(s)) {

        return 0;

    }

    rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];

    rop_func(s, s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask),

             s->cirrus_blt_dstpitch,

             s->cirrus_blt_width, s->cirrus_blt_height);

    cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,

			     s->cirrus_blt_dstpitch, s->cirrus_blt_width,

			     s->cirrus_blt_height);

    cirrus_bitblt_reset(s);

    return 1;

}


static int gx_ttfReader__LoadGlyph ( ttfReader * self , int glyph_index , const byte * * p , int * size ) {
 gx_ttfReader * r = ( gx_ttfReader * ) self ;
 gs_font_type42 * pfont = r -> pfont ;
 int code ;
 if ( r -> extra_glyph_index != - 1 ) return 0 ;
 r -> glyph_data . memory = pfont -> memory ;
 code = pfont -> data . get_outline ( pfont , ( uint ) glyph_index , & r -> glyph_data ) ;
 r -> extra_glyph_index = glyph_index ;
 r -> pos = 0 ;
 if ( code < 0 ) r -> error = code ;
 else if ( code > 0 ) {
 r -> error = gs_note_error ( gs_error_unregistered ) ;
 }
 else {
 * p = r -> glyph_data . bits . data ;
 * size = r -> glyph_data . bits . size ;
 }
 return 2 ;
 }


static int setcos_putdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj)
{
	int				r;
	struct sc_apdu			apdu;

	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);

	memset(&apdu, 0, sizeof(apdu));
	apdu.cse     = SC_APDU_CASE_3_SHORT;
	apdu.cla     = 0x00;
	apdu.ins     = 0xDA;
	apdu.p1      = data_obj->P1;
	apdu.p2      = data_obj->P2;
	apdu.lc      = data_obj->DataLen;
	apdu.datalen = data_obj->DataLen;
	apdu.data    = data_obj->Data;

	r = sc_transmit_apdu(card, &apdu);
	LOG_TEST_RET(card->ctx, r, "APDU transmit failed");

	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
	LOG_TEST_RET(card->ctx, r, "PUT_DATA returned error");

	LOG_FUNC_RETURN(card->ctx, r);
}


static void nfc_llcp_recv_snl(struct nfc_llcp_local *local,
			      struct sk_buff *skb)
{
	struct nfc_llcp_sock *llcp_sock;
	u8 dsap, ssap, *tlv, type, length, tid, sap;
	u16 tlv_len, offset;
	char *service_name;
	size_t service_name_len;
	struct nfc_llcp_sdp_tlv *sdp;
	HLIST_HEAD(llc_sdres_list);
	size_t sdres_tlvs_len;
	HLIST_HEAD(nl_sdres_list);

	dsap = nfc_llcp_dsap(skb);
	ssap = nfc_llcp_ssap(skb);

	pr_debug("%d %d\n", dsap, ssap);

	if (dsap != LLCP_SAP_SDP || ssap != LLCP_SAP_SDP) {
		pr_err("Wrong SNL SAP\n");
		return;
	}

	tlv = &skb->data[LLCP_HEADER_SIZE];
	tlv_len = skb->len - LLCP_HEADER_SIZE;
	offset = 0;
	sdres_tlvs_len = 0;

	while (offset < tlv_len) {
		type = tlv[0];
		length = tlv[1];

		switch (type) {
		case LLCP_TLV_SDREQ:
			tid = tlv[2];
			service_name = (char *) &tlv[3];
			service_name_len = length - 1;

			pr_debug("Looking for %.16s\n", service_name);

			if (service_name_len == strlen("urn:nfc:sn:sdp") &&
			    !strncmp(service_name, "urn:nfc:sn:sdp",
				     service_name_len)) {
				sap = 1;
				goto add_snl;
			}

			llcp_sock = nfc_llcp_sock_from_sn(local, service_name,
							  service_name_len);
			if (!llcp_sock) {
				sap = 0;
				goto add_snl;
			}

			/*
			 * We found a socket but its ssap has not been reserved
			 * yet. We need to assign it for good and send a reply.
			 * The ssap will be freed when the socket is closed.
			 */
			if (llcp_sock->ssap == LLCP_SDP_UNBOUND) {
				atomic_t *client_count;

				sap = nfc_llcp_reserve_sdp_ssap(local);

				pr_debug("Reserving %d\n", sap);

				if (sap == LLCP_SAP_MAX) {
					sap = 0;
					goto add_snl;
				}

				client_count =
					&local->local_sdp_cnt[sap -
							      LLCP_WKS_NUM_SAP];

				atomic_inc(client_count);

				llcp_sock->ssap = sap;
				llcp_sock->reserved_ssap = sap;
			} else {
				sap = llcp_sock->ssap;
			}

			pr_debug("%p %d\n", llcp_sock, sap);

add_snl:
			sdp = nfc_llcp_build_sdres_tlv(tid, sap);
			if (sdp == NULL)
				goto exit;

			sdres_tlvs_len += sdp->tlv_len;
			hlist_add_head(&sdp->node, &llc_sdres_list);
			break;

		case LLCP_TLV_SDRES:
			mutex_lock(&local->sdreq_lock);

			pr_debug("LLCP_TLV_SDRES: searching tid %d\n", tlv[2]);

			hlist_for_each_entry(sdp, &local->pending_sdreqs, node) {
				if (sdp->tid != tlv[2])
					continue;

				sdp->sap = tlv[3];

				pr_debug("Found: uri=%s, sap=%d\n",
					 sdp->uri, sdp->sap);

				hlist_del(&sdp->node);

				hlist_add_head(&sdp->node, &nl_sdres_list);

				break;
			}

			mutex_unlock(&local->sdreq_lock);
			break;

		default:
			pr_err("Invalid SNL tlv value 0x%x\n", type);
			break;
		}

		offset += length + 2;
		tlv += length + 2;
	}

exit:
	if (!hlist_empty(&nl_sdres_list))
		nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list);

	if (!hlist_empty(&llc_sdres_list))
		nfc_llcp_send_snl_sdres(local, &llc_sdres_list, sdres_tlvs_len);
}


void br_multicast_stop(struct net_bridge *br)
{
	struct net_bridge_mdb_htable *mdb;
	struct net_bridge_mdb_entry *mp;
	struct hlist_node *p, *n;
	u32 ver;
	int i;

	del_timer_sync(&br->multicast_router_timer);
	del_timer_sync(&br->multicast_querier_timer);
	del_timer_sync(&br->multicast_query_timer);

	spin_lock_bh(&br->multicast_lock);
	mdb = mlock_dereference(br->mdb, br);
	if (!mdb)
		goto out;

	br->mdb = NULL;

	ver = mdb->ver;
	for (i = 0; i < mdb->max; i++) {
		hlist_for_each_entry_safe(mp, p, n, &mdb->mhash[i],
					  hlist[ver]) {
			del_timer(&mp->timer);
			del_timer(&mp->query_timer);
			call_rcu_bh(&mp->rcu, br_multicast_free_group);
		}
	}

	if (mdb->old) {
		spin_unlock_bh(&br->multicast_lock);
		rcu_barrier_bh();
		spin_lock_bh(&br->multicast_lock);
		WARN_ON(mdb->old);
	}

	mdb->old = mdb;
	call_rcu_bh(&mdb->rcu, br_mdb_free);

out:
	spin_unlock_bh(&br->multicast_lock);
}


void NotCalled(mojo::ScopedSharedBufferHandle shared_buffer,
               mojo::ScopedHandle socket_handle) {
  EXPECT_TRUE(false) << "The StreamCreated callback was called despite the "
                        "test expecting it not to.";
}


RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
    int id,
    bool notify_result,
    int routing_id,
    base::WeakPtr<RenderFrameImpl> render_frame_impl)
    : id_(id),
      notify_result_(notify_result),
      routing_id_(routing_id),
      render_frame_impl_(render_frame_impl) {
}


void ip_flush_pending_frames(struct sock *sk)
{
	__ip_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork);
}


bool Curl_nss_cert_status_request(void)
{
#ifdef SSL_ENABLE_OCSP_STAPLING
  return TRUE;
#else
  return FALSE;
#endif
}


bool OpenConnectionTask::checkCapabilitiesResult(const Responses::State *const resp)
{
    if (resp->tag.isEmpty())
        return false;

    if (resp->tag == capabilityCmd) {
        if (!model->accessParser(parser).capabilitiesFresh) {
            logout(tr("Server did not provide useful capabilities"));
            return true;
        }
        if (resp->kind != Responses::OK) {
            logout(tr("CAPABILITIES command has failed"));
        }
        return true;
    }

    return false;
}


handle_method_call(__attribute__((unused)) GDBusConnection *connection,
		   __attribute__((unused)) const gchar	   *sender,
					   const gchar	   *object_path,
					   const gchar	   *interface_name,
					   const gchar	   *method_name,
#ifndef _WITH_DBUS_CREATE_INSTANCE_
		   __attribute__((unused))
#endif
					   GVariant *parameters,
		   GDBusMethodInvocation *invocation,
		   __attribute__((unused)) gpointer user_data)
{
#ifdef _WITH_DBUS_CREATE_INSTANCE_
	char *iname;
	char *ifname;
	size_t len;
	unsigned family;
#endif
	dbus_queue_ent_t ent;
	char ifname_str[sizeof ((vrrp_t*)NULL)->ifp->ifname];

	if (!g_strcmp0(interface_name, DBUS_VRRP_INTERFACE)) {
		if (!g_strcmp0(method_name, "PrintData")) {
			ent.action = DBUS_PRINT_DATA;
			process_method_call(&ent);
			g_dbus_method_invocation_return_value(invocation, NULL);
		}
		else if (g_strcmp0(method_name, "PrintStats") == 0) {
			ent.action = DBUS_PRINT_STATS;
			process_method_call(&ent);
			g_dbus_method_invocation_return_value(invocation, NULL);
		}
		else if (g_strcmp0(method_name, "ReloadConfig") == 0) {
			g_dbus_method_invocation_return_value(invocation, NULL);
			kill(getppid(), SIGHUP);
		}
#ifdef _WITH_DBUS_CREATE_INSTANCE_
		else if (g_strcmp0(method_name, "CreateInstance") == 0) {
			g_variant_get(parameters, "(ssuu)", &iname, &ifname, &ent.vrid, &family);
			len = strlen(ifname);
			if (len == 0 || len >= IFNAMSIZ) {
				log_message(LOG_INFO, "Interface name '%s' too long for CreateInstance", ifname);
				g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Interface name empty or too long");
				return;
			}
			ent.action = DBUS_CREATE_INSTANCE;
			ent.ifname = ifname;
			ent.family = family == 4 ? AF_INET : family == 6 ? AF_INET6 : AF_UNSPEC;
			ent.args = g_variant_new("(s)", iname);
			process_method_call(&ent);
			g_variant_unref(ent.args);
			g_dbus_method_invocation_return_value(invocation, NULL);
		}
		else if (g_strcmp0(method_name, "DestroyInstance") == 0) {
// TODO - this should be on the instance
			ent.action = DBUS_DESTROY_INSTANCE;
			ent.args = parameters;
			process_method_call(&ent);

			if (ent.reply == DBUS_INSTANCE_NOT_FOUND) {
				g_variant_get(parameters, "(s)", &iname);
				g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s' not found", iname);
			}
			else
				g_dbus_method_invocation_return_value(invocation, NULL);
		}
#endif
		else {
			log_message(LOG_INFO, "Method %s has not been implemented yet", method_name);
			g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Method not implemented");
		}

		return;
	}

	if (!g_strcmp0(interface_name, DBUS_VRRP_INSTANCE_INTERFACE)) {
		if (!g_strcmp0(method_name, "SendGarp")) {
			get_interface_ids(object_path, ifname_str, &ent.vrid, &ent.family);
			ent.action = DBUS_SEND_GARP;
			ent.ifname = ifname_str;
			process_method_call(&ent);
			if (ent.reply ==  DBUS_INTERFACE_NOT_FOUND)
				g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s/%d/%s' not found", ifname_str, ent.vrid, family_str(ent.family));
			else
				g_dbus_method_invocation_return_value(invocation, NULL);
		} else {
			log_message(LOG_INFO, "Method %s has not been implemented yet", method_name);
			g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Method not implemented");
		}

		return;
	}

	log_message(LOG_INFO, "Interface %s has not been implemented yet", interface_name);
	g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Interface not implemented");
}


static UBool sameScript ( UScriptCode scriptOne , UScriptCode scriptTwo ) {
 return scriptOne <= USCRIPT_INHERITED || scriptTwo <= USCRIPT_INHERITED || scriptOne == scriptTwo ;
 }


static CURLcode findprotocol(struct Curl_easy *data,
                             struct connectdata *conn,
                             const char *protostr)
{
  const struct Curl_handler *p = Curl_builtin_scheme(protostr);

  if(p && /* Protocol found in table. Check if allowed */
     (data->set.allowed_protocols & p->protocol)) {

    /* it is allowed for "normal" request, now do an extra check if this is
       the result of a redirect */
    if(data->state.this_is_a_follow &&
       !(data->set.redir_protocols & p->protocol))
      /* nope, get out */
      ;
    else {
      /* Perform setup complement if some. */
      conn->handler = conn->given = p;

      /* 'port' and 'remote_port' are set in setup_connection_internals() */
      return CURLE_OK;
    }
  }

  /* The protocol was not found in the table, but we don't have to assign it
     to anything since it is already assigned to a dummy-struct in the
     create_conn() function when the connectdata struct is allocated. */
  failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
        protostr);

  return CURLE_UNSUPPORTED_PROTOCOL;
}


zcurrentcolor(i_ctx_t * i_ctx_p)
{
    os_ptr                  op = osp;
    const gs_color_space *  pcs = gs_currentcolorspace(igs);
    const gs_client_color * pcc = gs_currentcolor(igs);
    int                     i, n = cs_num_components(pcs);
    bool                    push_pattern = n < 0;

    /* check for pattern */
    if (push_pattern) {
        gs_pattern_instance_t * pinst = pcc->pattern;

        if (pinst == 0 || !pattern_instance_uses_base_space(pinst))
            n = 1;
        else
            n = -n;
    }

    /* check for sufficient space on the stack */
    push(n);
    op -= n - 1;

    /* push the numeric operands, if any */
    if (push_pattern)
        --n;
    for (i = 0; i < n; i++, op++) {
        float   rval = pcc->paint.values[i];
        int     ival = (int)rval;

        /* the following handles indexed color spaces */
        if (rval == ival && pcs->type->index == gs_color_space_index_Indexed)
            make_int(op, ival);
        else
            make_real(op, rval);
    }

    /* push the pattern dictionary or null object, if appropriate */
    if (push_pattern)
        *op = istate->pattern[0];

    return 0;
}


uint32_t GraphicsContext3DPrivate::copyToGraphicsSurface()
{
    if (!m_graphicsSurface)
        return 0;

    blitMultisampleFramebufferAndRestoreContext();
    m_graphicsSurface->copyFromTexture(m_context->m_texture, IntRect(0, 0, m_context->m_currentWidth, m_context->m_currentHeight));
    return m_graphicsSurface->frontBuffer();
}


static bool fm10k_set_qos_queues(struct fm10k_intfc *interface)
{
	struct net_device *dev = interface->netdev;
	struct fm10k_ring_feature *f;
	int rss_i, i;
	int pcs;

	/* Map queue offset and counts onto allocated tx queues */
	pcs = netdev_get_num_tc(dev);

	if (pcs <= 1)
		return false;

	/* set QoS mask and indices */
	f = &interface->ring_feature[RING_F_QOS];
	f->indices = pcs;
	f->mask = BIT(fls(pcs - 1)) - 1;

	/* determine the upper limit for our current DCB mode */
	rss_i = interface->hw.mac.max_queues / pcs;
	rss_i = BIT(fls(rss_i) - 1);

	/* set RSS mask and indices */
	f = &interface->ring_feature[RING_F_RSS];
	rss_i = min_t(u16, rss_i, f->limit);
	f->indices = rss_i;
	f->mask = BIT(fls(rss_i - 1)) - 1;

	/* configure pause class to queue mapping */
	for (i = 0; i < pcs; i++)
		netdev_set_tc_queue(dev, i, rss_i, rss_i * i);

	interface->num_rx_queues = rss_i * pcs;
	interface->num_tx_queues = rss_i * pcs;

	return true;
}


static void dumpoffset ( FILE * file , int offsize , int val ) {
 if ( offsize == 1 ) putc ( val , file ) ;
 else if ( offsize == 2 ) putshort ( file , val ) ;
 else if ( offsize == 3 ) {
 putc ( ( val >> 16 ) & 0xff , file ) ;
 putc ( ( val >> 8 ) & 0xff , file ) ;
 putc ( val & 0xff , file ) ;
 }
 else putlong ( file , val ) ;
 }


int CMS_RecipientInfo_type(CMS_RecipientInfo *ri)
{
    return ri->type;
}


static FILE *FS_FileForHandle( fileHandle_t f ) {
	if ( f < 1 || f >= MAX_FILE_HANDLES ) {
		Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
	}
	if ( fsh[f].zipFile == qtrue ) {
		Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
	}
	if ( !fsh[f].handleFiles.file.o ) {
		Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
	}

	return fsh[f].handleFiles.file.o;
}


WebContents* WebContents::From(content::WebContents* web_contents) {
  if (!web_contents)
    return nullptr;
  auto* data = static_cast<UserDataLink*>(
      web_contents->GetUserData(kElectronApiWebContentsKey));
  return data ? data->web_contents.get() : nullptr;
}


ex_copy(linenr_T line1, linenr_T line2, linenr_T n)
{
    linenr_T	count;
    char_u	*p;

    count = line2 - line1 + 1;
    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
    {
	curbuf->b_op_start.lnum = n + 1;
	curbuf->b_op_end.lnum = n + count;
	curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
    }

    /*
     * there are three situations:
     * 1. destination is above line1
     * 2. destination is between line1 and line2
     * 3. destination is below line2
     *
     * n = destination (when starting)
     * curwin->w_cursor.lnum = destination (while copying)
     * line1 = start of source (while copying)
     * line2 = end of source (while copying)
     */
    if (u_save(n, n + 1) == FAIL)
	return;

    curwin->w_cursor.lnum = n;
    while (line1 <= line2)
    {
	// need to use vim_strsave() because the line will be unlocked within
	// ml_append()
	p = vim_strsave(ml_get(line1));
	if (p != NULL)
	{
	    ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);
	    vim_free(p);
	}
	// situation 2: skip already copied lines
	if (line1 == n)
	    line1 = curwin->w_cursor.lnum;
	++line1;
	if (curwin->w_cursor.lnum < line1)
	    ++line1;
	if (curwin->w_cursor.lnum < line2)
	    ++line2;
	++curwin->w_cursor.lnum;
    }

    appended_lines_mark(n, count);
    if (VIsual_active)
	check_pos(curbuf, &VIsual);

    msgmore((long)count);
}


static int airo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
	int rc = 0;
	struct airo_info *ai = dev->ml_priv;

	if (ai->power.event)
		return 0;

	switch (cmd) {
#ifdef CISCO_EXT
	case AIROIDIFC:
#ifdef AIROOLDIDIFC
	case AIROOLDIDIFC:
#endif
	{
		int val = AIROMAGIC;
		aironet_ioctl com;
		if (copy_from_user(&com,rq->ifr_data,sizeof(com)))
			rc = -EFAULT;
		else if (copy_to_user(com.data,(char *)&val,sizeof(val)))
			rc = -EFAULT;
	}
	break;

	case AIROIOCTL:
#ifdef AIROOLDIOCTL
	case AIROOLDIOCTL:
#endif
		/* Get the command struct and hand it off for evaluation by
		 * the proper subfunction
		 */
	{
		aironet_ioctl com;
		if (copy_from_user(&com,rq->ifr_data,sizeof(com))) {
			rc = -EFAULT;
			break;
		}

		/* Separate R/W functions bracket legality here
		 */
		if ( com.command == AIRORSWVERSION ) {
			if (copy_to_user(com.data, swversion, sizeof(swversion)))
				rc = -EFAULT;
			else
				rc = 0;
		}
		else if ( com.command <= AIRORRID)
			rc = readrids(dev,&com);
		else if ( com.command >= AIROPCAP && com.command <= (AIROPLEAPUSR+2) )
			rc = writerids(dev,&com);
		else if ( com.command >= AIROFLSHRST && com.command <= AIRORESTART )
			rc = flashcard(dev,&com);
		else
			rc = -EINVAL;      /* Bad command in ioctl */
	}
	break;
#endif /* CISCO_EXT */

	// All other calls are currently unsupported
	default:
		rc = -EOPNOTSUPP;
	}
	return rc;
}


RenderWidgetHostImpl::RenderWidgetHostImpl(RenderWidgetHostDelegate* delegate,
                                           RenderProcessHost* process,
                                           int32_t routing_id,
                                           bool hidden)
    : renderer_initialized_(false),
      destroyed_(false),
      delegate_(delegate),
      owner_delegate_(nullptr),
      process_(process),
      routing_id_(routing_id),
      is_loading_(false),
      is_hidden_(hidden),
      repaint_ack_pending_(false),
      resize_ack_pending_(false),
      color_profile_out_of_date_(false),
      auto_resize_enabled_(false),
      waiting_for_screen_rects_ack_(false),
      needs_repainting_on_restore_(false),
      is_unresponsive_(false),
      in_flight_event_count_(0),
      in_get_backing_store_(false),
      ignore_input_events_(false),
      text_direction_updated_(false),
      text_direction_(blink::WebTextDirectionLeftToRight),
      text_direction_canceled_(false),
      suppress_next_char_events_(false),
      pending_mouse_lock_request_(false),
      allow_privileged_mouse_lock_(false),
      has_touch_handler_(false),
      is_in_gesture_scroll_(false),
      received_paint_after_load_(false),
      next_browser_snapshot_id_(1),
      owned_by_render_frame_host_(false),
      is_focused_(false),
      scale_input_to_viewport_(IsUseZoomForDSFEnabled()),
      hung_renderer_delay_(
          base::TimeDelta::FromMilliseconds(kHungRendererDelayMs)),
      new_content_rendering_delay_(
          base::TimeDelta::FromMilliseconds(kNewContentRenderingDelayMs)),
      mouse_wheel_coalesce_timer_(new base::ElapsedTimer()),
      weak_factory_(this) {
  CHECK(delegate_);
  CHECK_NE(MSG_ROUTING_NONE, routing_id_);

  std::pair<RoutingIDWidgetMap::iterator, bool> result =
      g_routing_id_widget_map.Get().insert(std::make_pair(
          RenderWidgetHostID(process->GetID(), routing_id_), this));
  CHECK(result.second) << "Inserting a duplicate item!";
  process_->AddRoute(routing_id_, this);

  if (!hidden)
    process_->WidgetRestored();

  latency_tracker_.Initialize(routing_id_, GetProcess()->GetID());

  input_router_.reset(new InputRouterImpl(
      process_, this, this, routing_id_, GetInputRouterConfigForPlatform()));

  touch_emulator_.reset();

  if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableHangMonitor)) {
    hang_monitor_timeout_.reset(new TimeoutMonitor(
        base::Bind(&RenderWidgetHostImpl::RendererIsUnresponsive,
                   weak_factory_.GetWeakPtr())));
  }

  new_content_rendering_timeout_.reset(new TimeoutMonitor(
      base::Bind(&RenderWidgetHostImpl::ClearDisplayedGraphics,
                 weak_factory_.GetWeakPtr())));

  delegate_->RenderWidgetCreated(this);
}


static uint32_t dp8393x_readw(void *opaque, target_phys_addr_t addr)

{

    dp8393xState *s = opaque;

    int reg;

    if ((addr & ((1 << s->it_shift) - 1)) != 0) {

        return 0;

    }

    reg = addr >> s->it_shift;

    return read_register(s, reg);

}


void WebContentsImpl::Delete() {
  RenderFrameHost* focused_frame = GetFocusedFrame();
  if (!focused_frame)
    return;

  focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
  RecordAction(base::UserMetricsAction("DeleteSelection"));
}


void CL_BeginDownload( const char *localName, const char *remoteName ) {

	Com_DPrintf("***** CL_BeginDownload *****\n"
				"Localname: %s\n"
				"Remotename: %s\n"
				"****************************\n", localName, remoteName);

	Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) );
	Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName );

	// Set so UI gets access to it
	Cvar_Set( "cl_downloadName", remoteName );
	Cvar_Set( "cl_downloadSize", "0" );
	Cvar_Set( "cl_downloadCount", "0" );
	Cvar_SetValue( "cl_downloadTime", (float) cls.realtime );

	clc.downloadBlock = 0; // Starting new file
	clc.downloadCount = 0;

	CL_AddReliableCommand( va("download %s", remoteName), qfalse );
}


add_char_amb_opt_map(OptMap* map, UChar* p, UChar* end,
                     OnigEncoding enc, OnigCaseFoldType fold_flag)
{
  OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
  UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
  int i, n;

  add_char_opt_map(map, p[0], enc);

  fold_flag = DISABLE_CASE_FOLD_MULTI_CHAR(fold_flag);
  n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(enc, fold_flag, p, end, items);
  if (n < 0) return n;

  for (i = 0; i < n; i++) {
    ONIGENC_CODE_TO_MBC(enc, items[i].code[0], buf);
    add_char_opt_map(map, buf[0], enc);
  }

  return 0;
}


svc_pool_map_put(void)
{
	struct svc_pool_map *m = &svc_pool_map;

	mutex_lock(&svc_pool_map_mutex);

	if (!--m->count) {
		kfree(m->to_pool);
		m->to_pool = NULL;
		kfree(m->pool_to);
		m->pool_to = NULL;
		m->npools = 0;
	}

	mutex_unlock(&svc_pool_map_mutex);
}


PassRefPtr<Range> SimplifiedBackwardsTextIterator::range() const
{
    if (m_positionNode)
        return Range::create(m_positionNode->document(), m_positionNode, m_positionStartOffset, m_positionNode, m_positionEndOffset);

    return Range::create(m_startNode->document(), m_startNode, m_startOffset, m_startNode, m_startOffset);
}


ftp_retrieve_dirs (struct url *u, struct fileinfo *f, ccon *con)
{
  char *container = NULL;
  int container_size = 0;

  for (; f; f = f->next)
    {
      int size;
      char *odir, *newdir;

      if (opt.quota && total_downloaded_bytes > opt.quota)
        break;
      if (f->type != FT_DIRECTORY)
        continue;

      /* Allocate u->dir off stack, but reallocate only if a larger
         string is needed.  It's a pity there's no "realloca" for an
         item on the bottom of the stack.  */
      size = strlen (u->dir) + 1 + strlen (f->name) + 1;
      if (size > container_size)
        container = (char *)alloca (size);
      newdir = container;

      odir = u->dir;
      if (*odir == '\0'
          || (*odir == '/' && *(odir + 1) == '\0'))
        /* If ODIR is empty or just "/", simply append f->name to
           ODIR.  (In the former case, to preserve u->dir being
           relative; in the latter case, to avoid double slash.)  */
        sprintf (newdir, "%s%s", odir, f->name);
      else
        /* Else, use a separator. */
        sprintf (newdir, "%s/%s", odir, f->name);

      DEBUGP (("Composing new CWD relative to the initial directory.\n"));
      DEBUGP (("  odir = '%s'\n  f->name = '%s'\n  newdir = '%s'\n\n",
               odir, f->name, newdir));
      if (!accdir (newdir))
        {
          logprintf (LOG_VERBOSE, _("\
Not descending to %s as it is excluded/not-included.\n"),
                     quote (newdir));
          continue;
        }

      con->st &= ~DONE_CWD;

      odir = xstrdup (u->dir);  /* because url_set_dir will free
                                   u->dir. */
      url_set_dir (u, newdir);
      ftp_retrieve_glob (u, con, GLOB_GETALL);
      url_set_dir (u, odir);
      xfree (odir);

      /* Set the time-stamp?  */
    }

  if (opt.quota && total_downloaded_bytes > opt.quota)
    return QUOTEXC;
  else
    return RETROK;
}


UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
	char* name;
	char* path;
	char* driver;
	RDPDR_SERIAL* device;
#if defined __linux__ && !defined ANDROID
	size_t i, len;
	SERIAL_DEVICE* serial;
#endif /* __linux__ */
	UINT error = CHANNEL_RC_OK;
	device = (RDPDR_SERIAL*)pEntryPoints->device;
	name = device->Name;
	path = device->Path;
	driver = device->Driver;

	if (!name || (name[0] == '*'))
	{
		/* TODO: implement auto detection of serial ports */
		return CHANNEL_RC_OK;
	}

	if ((name && name[0]) && (path && path[0]))
	{
		wLog* log;
		log = WLog_Get("com.freerdp.channel.serial.client");
		WLog_Print(log, WLOG_DEBUG, "initializing");
#ifndef __linux__ /* to be removed */
		WLog_Print(log, WLOG_WARN, "Serial ports redirection not supported on this platform.");
		return CHANNEL_RC_INITIALIZATION_ERROR;
#else /* __linux __ */
		WLog_Print(log, WLOG_DEBUG, "Defining %s as %s", name, path);

		if (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))
		{
			DWORD status = GetLastError();
			WLog_ERR(TAG, "DefineCommDevice failed with %08" PRIx32, status);
			return ERROR_INTERNAL_ERROR;
		}

		serial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));

		if (!serial)
		{
			WLog_ERR(TAG, "calloc failed!");
			return CHANNEL_RC_NO_MEMORY;
		}

		serial->log = log;
		serial->device.type = RDPDR_DTYP_SERIAL;
		serial->device.name = name;
		serial->device.IRPRequest = serial_irp_request;
		serial->device.Free = serial_free;
		serial->rdpcontext = pEntryPoints->rdpcontext;
		len = strlen(name);
		serial->device.data = Stream_New(NULL, len + 1);

		if (!serial->device.data)
		{
			WLog_ERR(TAG, "calloc failed!");
			error = CHANNEL_RC_NO_MEMORY;
			goto error_out;
		}

		for (i = 0; i <= len; i++)
			Stream_Write_UINT8(serial->device.data, name[i] < 0 ? '_' : name[i]);

		if (driver != NULL)
		{
			if (_stricmp(driver, "Serial") == 0)
				serial->ServerSerialDriverId = SerialDriverSerialSys;
			else if (_stricmp(driver, "SerCx") == 0)
				serial->ServerSerialDriverId = SerialDriverSerCxSys;
			else if (_stricmp(driver, "SerCx2") == 0)
				serial->ServerSerialDriverId = SerialDriverSerCx2Sys;
			else
			{
				assert(FALSE);
				WLog_Print(serial->log, WLOG_DEBUG,
				           "Unknown server's serial driver: %s. SerCx2 will be used", driver);
				serial->ServerSerialDriverId = SerialDriverSerialSys;
			}
		}
		else
		{
			/* default driver */
			serial->ServerSerialDriverId = SerialDriverSerialSys;
		}

		if (device->Permissive != NULL)
		{
			if (_stricmp(device->Permissive, "permissive") == 0)
			{
				serial->permissive = TRUE;
			}
			else
			{
				WLog_Print(serial->log, WLOG_DEBUG, "Unknown flag: %s", device->Permissive);
				assert(FALSE);
			}
		}

		WLog_Print(serial->log, WLOG_DEBUG, "Server's serial driver: %s (id: %d)", driver,
		           serial->ServerSerialDriverId);
		/* TODO: implement auto detection of the server's serial driver */
		serial->MainIrpQueue = MessageQueue_New(NULL);

		if (!serial->MainIrpQueue)
		{
			WLog_ERR(TAG, "MessageQueue_New failed!");
			error = CHANNEL_RC_NO_MEMORY;
			goto error_out;
		}

		/* IrpThreads content only modified by create_irp_thread() */
		serial->IrpThreads = ListDictionary_New(FALSE);

		if (!serial->IrpThreads)
		{
			WLog_ERR(TAG, "ListDictionary_New failed!");
			error = CHANNEL_RC_NO_MEMORY;
			goto error_out;
		}

		serial->IrpThreadToBeTerminatedCount = 0;
		InitializeCriticalSection(&serial->TerminatingIrpThreadsLock);

		if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)serial)))
		{
			WLog_ERR(TAG, "EntryPoints->RegisterDevice failed with error %" PRIu32 "!", error);
			goto error_out;
		}

		if (!(serial->MainThread =
		          CreateThread(NULL, 0, serial_thread_func, (void*)serial, 0, NULL)))
		{
			WLog_ERR(TAG, "CreateThread failed!");
			error = ERROR_INTERNAL_ERROR;
			goto error_out;
		}

#endif /* __linux __ */
	}

	return error;
error_out:
#ifdef __linux__ /* to be removed */
	ListDictionary_Free(serial->IrpThreads);
	MessageQueue_Free(serial->MainIrpQueue);
	Stream_Free(serial->device.data, TRUE);
	free(serial);
#endif /* __linux __ */
	return error;
}


static inline __sum16 __tcp_checksum_complete(struct sk_buff *skb)
{
	return __skb_checksum_complete(skb);
}


static void reflectUnsignedShortAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
    TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
    v8SetReturnValueUnsigned(info, std::max(0, imp->fastGetAttribute(HTMLNames::reflectunsignedshortattributeAttr)));
}


int jbig2_parse_segment ( Jbig2Ctx * ctx , Jbig2Segment * segment , const uint8_t * segment_data ) {
 jbig2_error ( ctx , JBIG2_SEVERITY_INFO , segment -> number , "Segment %d, flags=%x, type=%d, data_length=%d" , segment -> number , segment -> flags , segment -> flags & 63 , segment -> data_length ) ;
 switch ( segment -> flags & 63 ) {
 case 0 : return jbig2_symbol_dictionary ( ctx , segment , segment_data ) ;
 case 4 : case 6 : case 7 : return jbig2_text_region ( ctx , segment , segment_data ) ;
 case 16 : return jbig2_pattern_dictionary ( ctx , segment , segment_data ) ;
 case 20 : case 22 : case 23 : return jbig2_halftone_region ( ctx , segment , segment_data ) ;
 case 36 : return jbig2_error ( ctx , JBIG2_SEVERITY_WARNING , segment -> number , "unhandled segment type 'intermediate generic region'" ) ;
 case 38 : case 39 : return jbig2_immediate_generic_region ( ctx , segment , segment_data ) ;
 case 40 : case 42 : case 43 : return jbig2_refinement_region ( ctx , segment , segment_data ) ;
 case 48 : return jbig2_page_info ( ctx , segment , segment_data ) ;
 case 49 : return jbig2_end_of_page ( ctx , segment , segment_data ) ;
 case 50 : return jbig2_end_of_stripe ( ctx , segment , segment_data ) ;
 case 51 : ctx -> state = JBIG2_FILE_EOF ;
 return jbig2_error ( ctx , JBIG2_SEVERITY_INFO , segment -> number , "end of file" ) ;
 case 52 : return jbig2_error ( ctx , JBIG2_SEVERITY_WARNING , segment -> number , "unhandled segment type 'profile'" ) ;
 case 53 : return jbig2_table ( ctx , segment , segment_data ) ;
 case 62 : return jbig2_parse_extension_segment ( ctx , segment , segment_data ) ;
 default : jbig2_error ( ctx , JBIG2_SEVERITY_WARNING , segment -> number , "unknown segment type %d" , segment -> flags & 63 ) ;
 }
 return 0 ;
 }


void RenderFrameImpl::PepperSelectionChanged(
    PepperPluginInstanceImpl* instance) {
  if (instance != focused_pepper_plugin_)
    return;
  SyncSelectionIfRequired();
}