PHP_FUNCTION(pg_connection_reset)
{
	zval *pgsql_link;
	int id = -1;
	PGconn *pgsql;

	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
								 &pgsql_link) == FAILURE) {
		RETURN_FALSE;
	}

	ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);

	PQreset(pgsql);
	if (PQstatus(pgsql) == CONNECTION_BAD) {
		RETURN_FALSE;
	}
	RETURN_TRUE;
}


teardown_normal (Test *test,
                 gconstpointer data)
{
  cockpit_assert_expected ();
  g_object_unref (test->auth);
  cockpit_conf_cleanup ();
}


    OVS_REQUIRES(ofproto_mutex)
{
    if (rule->eviction_group) {
        struct oftable *table = &rule->ofproto->tables[rule->table_id];
        struct eviction_group *evg = rule->eviction_group;

        rule->eviction_group = NULL;
        heap_remove(&evg->rules, &rule->evg_node);
        if (heap_is_empty(&evg->rules)) {
            eviction_group_destroy(table, evg);
        } else {
            eviction_group_resized(table, evg);
        }
    }
}


bool WebLocalFrameImpl::IsSelectionAnchorFirst() const {
  FrameSelection& selection = frame_->Selection();
  if (!selection.IsAvailable()) {
    return false;
  }

  return selection.GetSelectionInDOMTree().IsBaseFirst();
}


status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
 int32_t requestId, nsecs_t timeout) {
 Mutex::Autolock l(mLatestRequestMutex);
 status_t res;
 while (mLatestRequestId != requestId) {
 nsecs_t startTime = systemTime();

        res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
 if (res != OK) return res;

        timeout -= (systemTime() - startTime);
 }

 return OK;
}


StringValue* MakeInt64Value(int64 x) {
  return Value::CreateStringValue(base::Int64ToString(x));
}


bool ResourceDispatcherHostImpl::Send(IPC::Message* message) {
  delete message;
  return false;
}


static void inc_inflight(struct unix_sock *usk)
{
	atomic_long_inc(&usk->inflight);
}


static inline int do_exception(struct pt_regs *regs, int access,
			       unsigned long trans_exc_code)
{
	struct task_struct *tsk;
	struct mm_struct *mm;
	struct vm_area_struct *vma;
	unsigned long address;
	unsigned int flags;
	int fault;

	if (notify_page_fault(regs))
		return 0;

	tsk = current;
	mm = tsk->mm;

	/*
	 * Verify that the fault happened in user space, that
	 * we are not in an interrupt and that there is a
	 * user context.
	 */
	fault = VM_FAULT_BADCONTEXT;
	if (unlikely(!user_space_fault(trans_exc_code) || in_atomic() || !mm))
		goto out;

	address = trans_exc_code & __FAIL_ADDR_MASK;
	perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
	flags = FAULT_FLAG_ALLOW_RETRY;
	if (access == VM_WRITE || (trans_exc_code & store_indication) == 0x400)
		flags |= FAULT_FLAG_WRITE;
retry:
	down_read(&mm->mmap_sem);

	fault = VM_FAULT_BADMAP;
	vma = find_vma(mm, address);
	if (!vma)
		goto out_up;

	if (unlikely(vma->vm_start > address)) {
		if (!(vma->vm_flags & VM_GROWSDOWN))
			goto out_up;
		if (expand_stack(vma, address))
			goto out_up;
	}

	/*
	 * Ok, we have a good vm_area for this memory access, so
	 * we can handle it..
	 */
	fault = VM_FAULT_BADACCESS;
	if (unlikely(!(vma->vm_flags & access)))
		goto out_up;

	if (is_vm_hugetlb_page(vma))
		address &= HPAGE_MASK;
	/*
	 * If for any reason at all we couldn't handle the fault,
	 * make sure we exit gracefully rather than endlessly redo
	 * the fault.
	 */
	fault = handle_mm_fault(mm, vma, address, flags);
	if (unlikely(fault & VM_FAULT_ERROR))
		goto out_up;

	/*
	 * Major/minor page fault accounting is only done on the
	 * initial attempt. If we go through a retry, it is extremely
	 * likely that the page will be found in page cache at that point.
	 */
	if (flags & FAULT_FLAG_ALLOW_RETRY) {
		if (fault & VM_FAULT_MAJOR) {
			tsk->maj_flt++;
			perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1,
				      regs, address);
		} else {
			tsk->min_flt++;
			perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1,
				      regs, address);
		}
		if (fault & VM_FAULT_RETRY) {
			/* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk
			 * of starvation. */
			flags &= ~FAULT_FLAG_ALLOW_RETRY;
			goto retry;
		}
	}
	/*
	 * The instruction that caused the program check will
	 * be repeated. Don't signal single step via SIGTRAP.
	 */
	clear_tsk_thread_flag(tsk, TIF_PER_TRAP);
	fault = 0;
out_up:
	up_read(&mm->mmap_sem);
out:
	return fault;
}


bool AXLayoutObject::canHaveChildren() const {
  if (!m_layoutObject)
    return false;

  return AXNodeObject::canHaveChildren();
}


static int numst ( struct subre * t , int start ) {
 int i ;
 assert ( t != NULL ) ;
 i = start ;
 t -> id = ( short ) i ++ ;
 if ( t -> left != NULL ) i = numst ( t -> left , i ) ;
 if ( t -> right != NULL ) i = numst ( t -> right , i ) ;
 return i ;
 }


bool WebPluginDelegatePepper::CalculatePrintedPageDimensions(
    int page_number,
    NPPPrintExtensions* print_extensions,
    gfx::Size* page_dimensions) {
  int32 width_in_pixels = 0;
  int32 height_in_pixels = 0;
  NPError err = print_extensions->getRasterDimensions(
      instance()->npp(), page_number, &width_in_pixels, &height_in_pixels);
  if (err != NPERR_NO_ERROR)
    return false;

  DCHECK(width_in_pixels && height_in_pixels);
  page_dimensions->SetSize(width_in_pixels, height_in_pixels);
  return true;
}


void GraphicsContext::scale(const FloatSize& scale)
{
#if USE(WXGC)
    if (m_data->context) {
        wxGraphicsContext* gc = m_data->context->GetGraphicsContext();
        gc->Scale(scale.width(), scale.height());
    }
#endif
}


close_std_fd(void)
{
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
}


static void call_rlc ( tvbuff_t * tvb , packet_info * pinfo , proto_tree * tree , proto_item * ti , guint8 lchid , void * data ) {
 switch ( lchId_type_table [ lchid ] ) {
 case MAC_CONTENT_DCCH : proto_item_append_text ( ti , " (DCCH)" ) ;
 call_dissector_with_data ( rlc_dcch_handle , tvb , pinfo , tree , data ) ;
 break ;
 case MAC_CONTENT_PS_DTCH : proto_item_append_text ( ti , " (PS DTCH)" ) ;
 call_dissector_with_data ( rlc_ps_dtch_handle , tvb , pinfo , tree , data ) ;
 break ;
 case MAC_CONTENT_CS_DTCH : proto_item_append_text ( ti , " (CS DTCH)" ) ;
 break ;
 default : proto_item_append_text ( ti , " (Unknown EDCH Content)" ) ;
 expert_add_info_format ( pinfo , ti , & ei_mac_unknown_content , "Unknown EDCH Content" ) ;
 break ;
 }
 }


static int file_has_perm ( const struct cred * cred , struct file * file , u32 av ) {
 struct file_security_struct * fsec = file -> f_security ;
 struct inode * inode = file_inode ( file ) ;
 struct common_audit_data ad ;
 u32 sid = cred_sid ( cred ) ;
 int rc ;
 ad . type = LSM_AUDIT_DATA_FILE ;
 ad . u . file = file ;
 if ( sid != fsec -> sid ) {
 rc = avc_has_perm ( sid , fsec -> sid , SECCLASS_FD , FD__USE , & ad ) ;
 if ( rc ) goto out ;
 }
 rc = 0 ;
 if ( av ) rc = inode_has_perm ( cred , inode , av , & ad ) ;
 out : return rc ;
 }


static int make_ydt24_entry(int p1, int p2, int16_t *ydt)

{

    int lo, hi;

    lo = ydt[p1];

    hi = ydt[p2];

    return (lo + (hi << 8) + (hi << 16)) << 1;

}


static const uint8_t * read_huffman_tables ( FourXContext * f , const uint8_t * const buf ) {
 int frequency [ 512 ] = {
 0 }
 ;
 uint8_t flag [ 512 ] ;
 int up [ 512 ] ;
 uint8_t len_tab [ 257 ] ;
 int bits_tab [ 257 ] ;
 int start , end ;
 const uint8_t * ptr = buf ;
 int j ;
 memset ( up , - 1 , sizeof ( up ) ) ;
 start = * ptr ++ ;
 end = * ptr ++ ;
 for ( ;
 ;
 ) {
 int i ;
 for ( i = start ;
 i <= end ;
 i ++ ) frequency [ i ] = * ptr ++ ;
 start = * ptr ++ ;
 if ( start == 0 ) break ;
 end = * ptr ++ ;
 }
 frequency [ 256 ] = 1 ;
 while ( ( ptr - buf ) & 3 ) ptr ++ ;
 for ( j = 257 ;
 j < 512 ;
 j ++ ) {
 int min_freq [ 2 ] = {
 256 * 256 , 256 * 256 }
 ;
 int smallest [ 2 ] = {
 0 , 0 }
 ;
 int i ;
 for ( i = 0 ;
 i < j ;
 i ++ ) {
 if ( frequency [ i ] == 0 ) continue ;
 if ( frequency [ i ] < min_freq [ 1 ] ) {
 if ( frequency [ i ] < min_freq [ 0 ] ) {
 min_freq [ 1 ] = min_freq [ 0 ] ;
 smallest [ 1 ] = smallest [ 0 ] ;
 min_freq [ 0 ] = frequency [ i ] ;
 smallest [ 0 ] = i ;
 }
 else {
 min_freq [ 1 ] = frequency [ i ] ;
 smallest [ 1 ] = i ;
 }
 }
 }
 if ( min_freq [ 1 ] == 256 * 256 ) break ;
 frequency [ j ] = min_freq [ 0 ] + min_freq [ 1 ] ;
 flag [ smallest [ 0 ] ] = 0 ;
 flag [ smallest [ 1 ] ] = 1 ;
 up [ smallest [ 0 ] ] = up [ smallest [ 1 ] ] = j ;
 frequency [ smallest [ 0 ] ] = frequency [ smallest [ 1 ] ] = 0 ;
 }
 for ( j = 0 ;
 j < 257 ;
 j ++ ) {
 int node , len = 0 , bits = 0 ;
 for ( node = j ;
 up [ node ] != - 1 ;
 node = up [ node ] ) {
 bits += flag [ node ] << len ;
 len ++ ;
 if ( len > 31 ) av_log ( f -> avctx , AV_LOG_ERROR , "vlc length overflow\n" ) ;
 }
 bits_tab [ j ] = bits ;
 len_tab [ j ] = len ;
 }
 if ( init_vlc ( & f -> pre_vlc , ACDC_VLC_BITS , 257 , len_tab , 1 , 1 , bits_tab , 4 , 4 , 0 ) ) return NULL ;
 return ptr ;
 }


static int cpu_x86_register (CPUX86State *env, const char *cpu_model)

{

    x86_def_t def1, *def = &def1;

    if (cpu_x86_find_by_name(def, cpu_model) < 0)

        return -1;

    if (def->vendor1) {

        env->cpuid_vendor1 = def->vendor1;

        env->cpuid_vendor2 = def->vendor2;

        env->cpuid_vendor3 = def->vendor3;

    } else {

        env->cpuid_vendor1 = CPUID_VENDOR_INTEL_1;

        env->cpuid_vendor2 = CPUID_VENDOR_INTEL_2;

        env->cpuid_vendor3 = CPUID_VENDOR_INTEL_3;

    }

    env->cpuid_vendor_override = def->vendor_override;

    env->cpuid_level = def->level;

    if (def->family > 0x0f)

        env->cpuid_version = 0xf00 | ((def->family - 0x0f) << 20);

    else

        env->cpuid_version = def->family << 8;

    env->cpuid_version |= ((def->model & 0xf) << 4) | ((def->model >> 4) << 16);

    env->cpuid_version |= def->stepping;

    env->cpuid_features = def->features;

    env->pat = 0x0007040600070406ULL;

    env->cpuid_ext_features = def->ext_features;

    env->cpuid_ext2_features = def->ext2_features;

    env->cpuid_xlevel = def->xlevel;

    env->cpuid_ext3_features = def->ext3_features;

    {

        const char *model_id = def->model_id;

        int c, len, i;

        if (!model_id)

            model_id = "";

        len = strlen(model_id);

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

            if (i >= len)

                c = '\0';

            else

                c = (uint8_t)model_id[i];

            env->cpuid_model[i >> 2] |= c << (8 * (i & 3));

        }

    }

    return 0;

}


  static void MakeRequestFailOnIO(const std::string& host) {
    net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
    filter->AddHostnameInterceptor("http", host,
                                   std::unique_ptr<net::URLRequestInterceptor>(
                                       new FailedJobInterceptor()));
    filter->AddHostnameInterceptor("https", host,
                                   std::unique_ptr<net::URLRequestInterceptor>(
                                       new FailedJobInterceptor()));
  }


ResourceDispatcherHostImpl::CreateResourceHandler(
    ResourceRequesterInfo* requester_info,
    net::URLRequest* request,
    const network::ResourceRequest& request_data,
    int route_id,
    int child_id,
    ResourceContext* resource_context,
    uint32_t url_loader_options,
    network::mojom::URLLoaderRequest mojo_request,
    network::mojom::URLLoaderClientPtr url_loader_client) {
  DCHECK(requester_info->IsRenderer() ||
         requester_info->IsNavigationPreload() ||
         requester_info->IsCertificateFetcherForSignedExchange());
  std::unique_ptr<ResourceHandler> handler =
      std::make_unique<MojoAsyncResourceHandler>(
          request, this, std::move(mojo_request), std::move(url_loader_client),
          static_cast<ResourceType>(request_data.resource_type),
          url_loader_options);

  if (request_data.resource_type == RESOURCE_TYPE_PREFETCH) {
    auto detachable_handler = std::make_unique<DetachableResourceHandler>(
        request,
        base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs),
        std::move(handler));
    handler = std::move(detachable_handler);
  }

  return AddStandardHandlers(
      request, static_cast<ResourceType>(request_data.resource_type),
      resource_context, request_data.fetch_request_mode,
      static_cast<blink::mojom::RequestContextType>(
          request_data.fetch_request_context_type),
      url_loader_options, requester_info->appcache_service(), child_id,
      route_id, std::move(handler));
}


nfs4_stat_to_errno(int stat)
{
	int i;
	for (i = 0; nfs_errtbl[i].stat != -1; i++) {
		if (nfs_errtbl[i].stat == stat)
			return nfs_errtbl[i].errno;
	}
	if (stat <= 10000 || stat > 10100) {
		/* The server is looney tunes. */
		return -ESERVERFAULT;
	}
	/* If we cannot translate the error, the recovery routines should
	 * handle it.
	 * Note: remaining NFSv4 error codes have values > 10000, so should
	 * not conflict with native Linux error codes.
	 */
	return -stat;
}


 void HttpResponseHeaders::AddHeader(const std::string& header) {
  CheckDoesNotHaveEmbededNulls(header);
   DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 2]);
   DCHECK_EQ('\0', raw_headers_[raw_headers_.size() - 1]);
  std::string new_raw_headers(raw_headers_, 0, raw_headers_.size() - 1);
  new_raw_headers.append(header);
  new_raw_headers.push_back('\0');
  new_raw_headers.push_back('\0');

  raw_headers_.clear();
  parsed_.clear();
  Parse(new_raw_headers);
 }


bool ExtensionTtsController::IsSpeaking() const {
  return current_utterance_ != NULL;
}


static void set_guest_connected(VirtIOSerialPort *port, int guest_connected)

{

    VirtConsole *vcon = VIRTIO_CONSOLE(port);

    DeviceState *dev = DEVICE(port);

    if (vcon->chr) {

        qemu_chr_fe_set_open(vcon->chr, guest_connected);

    }

    if (dev->id) {

        qapi_event_send_vserport_change(dev->id, guest_connected,

                                        &error_abort);

    }

}


static void lexnest ( struct vars * v , const chr * beginp , const chr * endp ) {
 assert ( v -> savenow == NULL ) ;
 v -> savenow = v -> now ;
 v -> savestop = v -> stop ;
 v -> now = beginp ;
 v -> stop = endp ;
 }


MagickExport Image *SepiaToneImage(const Image *image,const double threshold,
  ExceptionInfo *exception)
{
#define SepiaToneImageTag  "SepiaTone/Image"

  CacheView
    *image_view,
    *sepia_view;

  Image
    *sepia_image;

  MagickBooleanType
    status;

  MagickOffsetType
    progress;

  ssize_t
    y;

  /*
    Initialize sepia-toned image attributes.
  */
  assert(image != (const Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  sepia_image=CloneImage(image,0,0,MagickTrue,exception);
  if (sepia_image == (Image *) NULL)
    return((Image *) NULL);
  if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse)
    {
      sepia_image=DestroyImage(sepia_image);
      return((Image *) NULL);
    }
  /*
    Tone each row of the image.
  */
  status=MagickTrue;
  progress=0;
  image_view=AcquireVirtualCacheView(image,exception);
  sepia_view=AcquireAuthenticCacheView(sepia_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(progress,status) \
    magick_threads(image,sepia_image,image->rows,1)
#endif
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register const Quantum
      *magick_restrict p;

    register ssize_t
      x;

    register Quantum
      *magick_restrict q;

    if (status == MagickFalse)
      continue;
    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
    q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1,
      exception);
    if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      double
        intensity,
        tone;

      intensity=GetPixelIntensity(image,p);
      tone=intensity > threshold ? (double) QuantumRange : intensity+
        (double) QuantumRange-threshold;
      SetPixelRed(sepia_image,ClampToQuantum(tone),q);
      tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange :
        intensity+(double) QuantumRange-7.0*threshold/6.0;
      SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
      tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0;
      SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
      tone=threshold/7.0;
      if ((double) GetPixelGreen(image,q) < tone)
        SetPixelGreen(sepia_image,ClampToQuantum(tone),q);
      if ((double) GetPixelBlue(image,q) < tone)
        SetPixelBlue(sepia_image,ClampToQuantum(tone),q);
      SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q);
      p+=GetPixelChannels(image);
      q+=GetPixelChannels(sepia_image);
    }
    if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse)
      status=MagickFalse;
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
      {
        MagickBooleanType
          proceed;

#if defined(MAGICKCORE_OPENMP_SUPPORT)
        #pragma omp critical (MagickCore_SepiaToneImage)
#endif
        proceed=SetImageProgress(image,SepiaToneImageTag,progress++,
          image->rows);
        if (proceed == MagickFalse)
          status=MagickFalse;
      }
  }
  sepia_view=DestroyCacheView(sepia_view);
  image_view=DestroyCacheView(image_view);
  (void) NormalizeImage(sepia_image,exception);
  (void) ContrastImage(sepia_image,MagickTrue,exception);
  if (status == MagickFalse)
    sepia_image=DestroyImage(sepia_image);
  return(sepia_image);
}


void aio_bh_call(QEMUBH *bh)

{

    bh->cb(bh->opaque);

}


void daemon_loop(void) {
    if(cron_init()) { /* initialize periodic events */
        s_log(LOG_CRIT, "Cron initialization failed");
        exit(1);
    }
    if(exec_connect_start()) {
        s_log(LOG_CRIT, "Failed to start exec+connect services");
        exit(1);
    }
    while(1) {
        int temporary_lack_of_resources=0;
        int num=s_poll_wait(fds, -1, -1);
        if(num>=0) {
            SERVICE_OPTIONS *opt;
            s_log(LOG_DEBUG, "Found %d ready file descriptor(s)", num);
            if(service_options.log_level>=LOG_DEBUG) /* performance optimization */
                s_poll_dump(fds, LOG_DEBUG);
            if(s_poll_canread(fds, signal_pipe[0]))
                if(signal_pipe_dispatch()) /* SIGNAL_TERMINATE or error */
                    break; /* terminate daemon_loop */
            for(opt=service_options.next; opt; opt=opt->next) {
                unsigned i;
                for(i=0; i<opt->local_addr.num; ++i) {
                    SOCKET fd=opt->local_fd[i];
                    if(fd!=INVALID_SOCKET &&
                            s_poll_canread(fds, fd) &&
                            accept_connection(opt, i))
                        temporary_lack_of_resources=1;
                }
            }
        } else {
            log_error(LOG_NOTICE, get_last_socket_error(),
                "daemon_loop: s_poll_wait");
            temporary_lack_of_resources=1;
        }
        if(temporary_lack_of_resources) {
            s_log(LOG_NOTICE,
                "Accepting new connections suspended for 1 second");
            s_poll_sleep(1, 0); /* to avoid log trashing */
        }
    }
    leak_table_utilization();
}


static BOOLEAN btm_dev_authorized (tBTM_SEC_DEV_REC *p_dev_rec)
{
 if(p_dev_rec->sec_flags & BTM_SEC_AUTHORIZED)
 {
 return(TRUE);
 }
 return(FALSE);
}


static int setcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
	if (card->type != SC_CARD_TYPE_SETCOS_44 && !SETCOS_IS_EID_APPLET(card))
		return SC_ERROR_NOT_SUPPORTED;

	switch(cmd) {
	case SC_CARDCTL_SETCOS_PUTDATA:
		return setcos_putdata(card,
				(struct sc_cardctl_setcos_data_obj*) ptr);
		break;
	case SC_CARDCTL_SETCOS_GETDATA:
		return setcos_getdata(card,
				(struct sc_cardctl_setcos_data_obj*) ptr);
		break;
	case SC_CARDCTL_SETCOS_GENERATE_STORE_KEY:
		return setcos_generate_store_key(card,
				(struct sc_cardctl_setcos_gen_store_key_info *) ptr);
	case SC_CARDCTL_SETCOS_ACTIVATE_FILE:
		return setcos_activate_file(card);
	}

	return SC_ERROR_NOT_SUPPORTED;
}


std::string parseProxy(const std::string &source)
{
    std::string proxy = source;
    if(source == "SYSTEM")
        proxy = getSystemProxy();
    else if(source == "NONE")
        proxy = "";
    return proxy;
}


static int cit_init_model0(struct gspca_dev *gspca_dev)
{
	cit_write_reg(gspca_dev, 0x0000, 0x0100); /* turn on led */
	cit_write_reg(gspca_dev, 0x0001, 0x0112); /* turn on autogain ? */
	cit_write_reg(gspca_dev, 0x0000, 0x0400);
	cit_write_reg(gspca_dev, 0x0001, 0x0400);
	cit_write_reg(gspca_dev, 0x0000, 0x0420);
	cit_write_reg(gspca_dev, 0x0001, 0x0420);
	cit_write_reg(gspca_dev, 0x000d, 0x0409);
	cit_write_reg(gspca_dev, 0x0002, 0x040a);
	cit_write_reg(gspca_dev, 0x0018, 0x0405);
	cit_write_reg(gspca_dev, 0x0008, 0x0435);
	cit_write_reg(gspca_dev, 0x0026, 0x040b);
	cit_write_reg(gspca_dev, 0x0007, 0x0437);
	cit_write_reg(gspca_dev, 0x0015, 0x042f);
	cit_write_reg(gspca_dev, 0x002b, 0x0439);
	cit_write_reg(gspca_dev, 0x0026, 0x043a);
	cit_write_reg(gspca_dev, 0x0008, 0x0438);
	cit_write_reg(gspca_dev, 0x001e, 0x042b);
	cit_write_reg(gspca_dev, 0x0041, 0x042c);

	return 0;
}


static int read_tfra(MOVContext *mov, AVIOContext *f)

{

    MOVFragmentIndex* index = NULL;

    int version, fieldlength, i, j, err;

    int64_t pos = avio_tell(f);

    uint32_t size = avio_rb32(f);

    if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {

        return -1;

    }

    av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");

    index = av_mallocz(sizeof(MOVFragmentIndex));

    if (!index) {

        return AVERROR(ENOMEM);

    }

    mov->fragment_index_count++;

    if ((err = av_reallocp(&mov->fragment_index_data,

                           mov->fragment_index_count *

                           sizeof(MOVFragmentIndex*))) < 0) {

        av_freep(&index);

        return err;

    }

    mov->fragment_index_data[mov->fragment_index_count - 1] =

        index;

    version = avio_r8(f);

    avio_rb24(f);

    index->track_id = avio_rb32(f);

    fieldlength = avio_rb32(f);

    index->item_count = avio_rb32(f);

    index->items = av_mallocz(

            index->item_count * sizeof(MOVFragmentIndexItem));

    if (!index->items) {

        return AVERROR(ENOMEM);

    }

    for (i = 0; i < index->item_count; i++) {

        int64_t time, offset;

        if (version == 1) {

            time   = avio_rb64(f);

            offset = avio_rb64(f);

        } else {

            time   = avio_rb32(f);

            offset = avio_rb32(f);

        }

        index->items[i].time = time;

        index->items[i].moof_offset = offset;

        for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)

            avio_r8(f);

        for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)

            avio_r8(f);

        for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)

            avio_r8(f);

    }

    avio_seek(f, pos + size, SEEK_SET);

    return 0;

}


static void dissect_rsvp_common ( tvbuff_t * tvb , packet_info * pinfo , proto_tree * tree , gboolean e2ei ) {
 guint8 message_type ;
 int session_off , tempfilt_off ;
 rsvp_conversation_info * rsvph ;
 conversation_t * conversation ;
 struct rsvp_request_key request_key , * new_request_key ;
 struct rsvp_request_val * request_val ;
 col_clear ( pinfo -> cinfo , COL_INFO ) ;
 message_type = tvb_get_guint8 ( tvb , 1 ) ;
 rsvph = wmem_new0 ( wmem_packet_scope ( ) , rsvp_conversation_info ) ;
 set_address ( & rsvph -> source , pinfo -> src . type , pinfo -> src . len , pinfo -> src . data ) ;
 set_address ( & rsvph -> destination , pinfo -> dst . type , pinfo -> dst . len , pinfo -> dst . data ) ;
 col_add_str ( pinfo -> cinfo , COL_INFO , val_to_str_ext ( message_type , & message_type_vals_ext , "Unknown (%u). " ) ) ;
 if ( message_type == RSVP_MSG_BUNDLE ) {
 col_set_str ( pinfo -> cinfo , COL_INFO , rsvp_bundle_dissect ? "Component Messages Dissected" : "Component Messages Not Dissected" ) ;
 }
 else {
 find_rsvp_session_tempfilt ( tvb , 0 , & session_off , & tempfilt_off ) ;
 if ( session_off ) col_append_str ( pinfo -> cinfo , COL_INFO , summary_session ( tvb , session_off ) ) ;
 if ( tempfilt_off ) col_append_str ( pinfo -> cinfo , COL_INFO , summary_template ( tvb , tempfilt_off ) ) ;
 }
 dissect_rsvp_msg_tree ( tvb , pinfo , tree , TREE ( TT_RSVP ) , rsvph , e2ei ) ;
 if ( ( message_type == RSVP_MSG_ACK ) || ( message_type == RSVP_MSG_SREFRESH ) || ( message_type == RSVP_MSG_HELLO ) ) return ;
 conversation = find_or_create_conversation ( pinfo ) ;
 memset ( & request_key , 0 , sizeof ( request_key ) ) ;
 request_key . conversation = conversation -> index ;
 request_key . session_type = rsvph -> session_type ;
 switch ( request_key . session_type ) {
 case RSVP_SESSION_TYPE_IPV4 : set_address ( & request_key . u . session_ipv4 . destination , rsvph -> destination . type , rsvph -> destination . len , rsvph -> destination . data ) ;
 request_key . u . session_ipv4 . protocol = rsvph -> protocol ;
 request_key . u . session_ipv4 . udp_dest_port = rsvph -> udp_dest_port ;
 break ;
 case RSVP_SESSION_TYPE_IPV6 : break ;
 case RSVP_SESSION_TYPE_IPV4_LSP : set_address ( & request_key . u . session_ipv4_lsp . destination , rsvph -> destination . type , rsvph -> destination . len , rsvph -> destination . data ) ;
 request_key . u . session_ipv4_lsp . udp_dest_port = rsvph -> udp_dest_port ;
 request_key . u . session_ipv4_lsp . ext_tunnel_id = rsvph -> ext_tunnel_id ;
 break ;
 case RSVP_SESSION_TYPE_AGGREGATE_IPV4 : set_address ( & request_key . u . session_agg_ipv4 . destination , rsvph -> destination . type , rsvph -> destination . len , rsvph -> destination . data ) ;
 request_key . u . session_agg_ipv4 . dscp = rsvph -> dscp ;
 break ;
 case RSVP_SESSION_TYPE_IPV4_UNI : set_address ( & request_key . u . session_ipv4_uni . destination , rsvph -> destination . type , rsvph -> destination . len , rsvph -> destination . data ) ;
 request_key . u . session_ipv4_uni . udp_dest_port = rsvph -> udp_dest_port ;
 request_key . u . session_ipv4_uni . ext_tunnel_id = rsvph -> ext_tunnel_id ;
 break ;
 case RSVP_SESSION_TYPE_IPV4_E_NNI : set_address ( & request_key . u . session_ipv4_enni . destination , rsvph -> destination . type , rsvph -> destination . len , rsvph -> destination . data ) ;
 request_key . u . session_ipv4_enni . udp_dest_port = rsvph -> udp_dest_port ;
 request_key . u . session_ipv4_enni . ext_tunnel_id = rsvph -> ext_tunnel_id ;
 break ;
 default : proto_tree_add_expert ( tree , pinfo , & ei_rsvp_session_type , tvb , 0 , 0 ) ;
 break ;
 }
 copy_address_shallow ( & request_key . source_info . source , & rsvph -> source ) ;
 request_key . source_info . udp_source_port = rsvph -> udp_source_port ;
 request_val = ( struct rsvp_request_val * ) g_hash_table_lookup ( rsvp_request_hash , & request_key ) ;
 if ( ! request_val ) {
 new_request_key = ( struct rsvp_request_key * ) wmem_memdup ( wmem_file_scope ( ) , & request_key , sizeof ( struct rsvp_request_key ) ) ;
 switch ( request_key . session_type ) {
 case RSVP_SESSION_TYPE_IPV4 : copy_address_wmem ( wmem_file_scope ( ) , & new_request_key -> u . session_ipv4 . destination , & request_key . u . session_ipv4 . destination ) ;
 break ;
 case RSVP_SESSION_TYPE_IPV4_LSP : copy_address_wmem ( wmem_file_scope ( ) , & new_request_key -> u . session_ipv4_lsp . destination , & request_key . u . session_ipv4_lsp . destination ) ;
 break ;
 case RSVP_SESSION_TYPE_AGGREGATE_IPV4 : copy_address_wmem ( wmem_file_scope ( ) , & new_request_key -> u . session_agg_ipv4 . destination , & request_key . u . session_agg_ipv4 . destination ) ;
 break ;
 case RSVP_SESSION_TYPE_IPV4_UNI : copy_address_wmem ( wmem_file_scope ( ) , & new_request_key -> u . session_ipv4_uni . destination , & request_key . u . session_ipv4_uni . destination ) ;
 break ;
 case RSVP_SESSION_TYPE_IPV4_E_NNI : copy_address_wmem ( wmem_file_scope ( ) , & new_request_key -> u . session_ipv4_enni . destination , & request_key . u . session_ipv4_enni . destination ) ;
 break ;
 default : break ;
 }
 copy_address_wmem ( wmem_file_scope ( ) , & new_request_key -> source_info . source , & rsvph -> source ) ;
 request_val = wmem_new ( wmem_file_scope ( ) , struct rsvp_request_val ) ;
 request_val -> value = conversation -> index ;
 g_hash_table_insert ( rsvp_request_hash , new_request_key , request_val ) ;
 }
 tap_queue_packet ( rsvp_tap , pinfo , rsvph ) ;
 }


static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu)
{
	return vmcs_read64(TSC_OFFSET);
}


static int make_msg_set(struct Mailbox *m, struct Buffer *buf, int flag,
                        bool changed, bool invert, int *pos)
{
  int count = 0;             /* number of messages in message set */
  unsigned int setstart = 0; /* start of current message range */
  int n;
  bool started = false;

  struct ImapAccountData *adata = imap_adata_get(m);
  if (!adata || (adata->mailbox != m))
    return -1;

  for (n = *pos; (n < m->msg_count) && (mutt_buffer_len(buf) < IMAP_MAX_CMDLEN); n++)
  {
    struct Email *e = m->emails[n];
    if (!e)
      break;
    bool match = false; /* whether current message matches flag condition */
    /* don't include pending expunged messages.
     *
     * TODO: can we unset active in cmd_parse_expunge() and
     * cmd_parse_vanished() instead of checking for index != INT_MAX. */
    if (e->active && (e->index != INT_MAX))
    {
      switch (flag)
      {
        case MUTT_DELETED:
          if (e->deleted != imap_edata_get(e)->deleted)
            match = invert ^ e->deleted;
          break;
        case MUTT_FLAG:
          if (e->flagged != imap_edata_get(e)->flagged)
            match = invert ^ e->flagged;
          break;
        case MUTT_OLD:
          if (e->old != imap_edata_get(e)->old)
            match = invert ^ e->old;
          break;
        case MUTT_READ:
          if (e->read != imap_edata_get(e)->read)
            match = invert ^ e->read;
          break;
        case MUTT_REPLIED:
          if (e->replied != imap_edata_get(e)->replied)
            match = invert ^ e->replied;
          break;
        case MUTT_TAG:
          if (e->tagged)
            match = true;
          break;
        case MUTT_TRASH:
          if (e->deleted && !e->purge)
            match = true;
          break;
      }
    }

    if (match && (!changed || e->changed))
    {
      count++;
      if (setstart == 0)
      {
        setstart = imap_edata_get(e)->uid;
        if (started)
        {
          mutt_buffer_add_printf(buf, ",%u", imap_edata_get(e)->uid);
        }
        else
        {
          mutt_buffer_add_printf(buf, "%u", imap_edata_get(e)->uid);
          started = true;
        }
      }
      /* tie up if the last message also matches */
      else if (n == (m->msg_count - 1))
        mutt_buffer_add_printf(buf, ":%u", imap_edata_get(e)->uid);
    }
    /* End current set if message doesn't match or we've reached the end
     * of the mailbox via inactive messages following the last match. */
    else if (setstart && (e->active || (n == adata->mailbox->msg_count - 1)))
    {
      if (imap_edata_get(m->emails[n - 1])->uid > setstart)
        mutt_buffer_add_printf(buf, ":%u", imap_edata_get(m->emails[n - 1])->uid);
      setstart = 0;
    }
  }

  *pos = n;

  return count;
}


dcputchar(char c)
{
	dcchkstr(1);

	*dcptr++=c;
	*dcptr='\000';
	strsize++;
}


static struct sk_buff *br_ip4_multicast_alloc_query(struct net_bridge *br,
						    __be32 group)
{
	struct sk_buff *skb;
	struct igmphdr *ih;
	struct ethhdr *eth;
	struct iphdr *iph;

	skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*iph) +
						 sizeof(*ih) + 4);
	if (!skb)
		goto out;

	skb->protocol = htons(ETH_P_IP);

	skb_reset_mac_header(skb);
	eth = eth_hdr(skb);

	memcpy(eth->h_source, br->dev->dev_addr, 6);
	eth->h_dest[0] = 1;
	eth->h_dest[1] = 0;
	eth->h_dest[2] = 0x5e;
	eth->h_dest[3] = 0;
	eth->h_dest[4] = 0;
	eth->h_dest[5] = 1;
	eth->h_proto = htons(ETH_P_IP);
	skb_put(skb, sizeof(*eth));

	skb_set_network_header(skb, skb->len);
	iph = ip_hdr(skb);

	iph->version = 4;
	iph->ihl = 6;
	iph->tos = 0xc0;
	iph->tot_len = htons(sizeof(*iph) + sizeof(*ih) + 4);
	iph->id = 0;
	iph->frag_off = htons(IP_DF);
	iph->ttl = 1;
	iph->protocol = IPPROTO_IGMP;
	iph->saddr = 0;
	iph->daddr = htonl(INADDR_ALLHOSTS_GROUP);
	((u8 *)&iph[1])[0] = IPOPT_RA;
	((u8 *)&iph[1])[1] = 4;
	((u8 *)&iph[1])[2] = 0;
	((u8 *)&iph[1])[3] = 0;
	ip_send_check(iph);
	skb_put(skb, 24);

	skb_set_transport_header(skb, skb->len);
	ih = igmp_hdr(skb);
	ih->type = IGMP_HOST_MEMBERSHIP_QUERY;
	ih->code = (group ? br->multicast_last_member_interval :
			    br->multicast_query_response_interval) /
		   (HZ / IGMP_TIMER_SCALE);
	ih->group = group;
	ih->csum = 0;
	ih->csum = ip_compute_csum((void *)ih, sizeof(struct igmphdr));
	skb_put(skb, sizeof(*ih));

	__skb_pull(skb, sizeof(*eth));

out:
	return skb;
}


std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram(
    Reference ref) {
  PersistentHistogramData* data =
      memory_allocator_->GetAsObject<PersistentHistogramData>(ref);
  const size_t length = memory_allocator_->GetAllocSize(ref);

  if (!data || data->name[0] == '\0' ||
      reinterpret_cast<char*>(data)[length - 1] != '\0' ||
      data->samples_metadata.id == 0 || data->logged_metadata.id == 0 ||
      (data->logged_metadata.id != data->samples_metadata.id &&
       data->logged_metadata.id != data->samples_metadata.id + 1) ||
       HashMetricName(data->name) != data->samples_metadata.id) {
     NOTREACHED();
     return nullptr;
   }
  return CreateHistogram(data);
}


void AudioOutputDevice::AudioThreadCallback::MapSharedMemory() {
  shared_memory_.Map(TotalSharedMemorySizeInBytes(memory_length_));

  int output_memory_size = AudioBus::CalculateMemorySize(audio_parameters_);
  int frames = audio_parameters_.frames_per_buffer();
  int input_memory_size =
      AudioBus::CalculateMemorySize(input_channels_, frames);

  int io_size = output_memory_size + input_memory_size;

  DCHECK_EQ(memory_length_, io_size);

  output_bus_ =
      AudioBus::WrapMemory(audio_parameters_, shared_memory_.memory());

  if (input_channels_ > 0) {
    char* input_data =
        static_cast<char*>(shared_memory_.memory()) + output_memory_size;
    input_bus_ =
        AudioBus::WrapMemory(input_channels_, frames, input_data);
  }
}


static int get_connection_state(const bt_bdaddr_t *bd_addr)
{
 /* sanity check */
 if (interface_ready() == FALSE)
 return 0;

 return btif_dm_get_connection_state(bd_addr);
}


std::string NgxEspRequest::GetClientIP() {
  // use remote_addr variable to get client_ip.
  ngx_esp_main_conf_t *mc = reinterpret_cast<ngx_esp_main_conf_t *>(
      ngx_http_get_module_main_conf(r_, ngx_esp_module));
  if (mc->remote_addr_variable_index != NGX_ERROR) {
    ngx_http_variable_value_t *vv =
        ngx_http_get_indexed_variable(r_, mc->remote_addr_variable_index);
    if (vv != nullptr && !vv->not_found) {
      return ngx_str_to_std(ngx_str_t({vv->len, vv->data}));
    }
  }
  return "";
}


static void r_bin_object_delete_items(RBinObject *o) {
	ut32 i = 0;
	if (!o) {
		return;
	}
	r_list_free (o->entries);
	r_list_free (o->fields);
	r_list_free (o->imports);
	r_list_free (o->libs);
	r_list_free (o->relocs);
	r_list_free (o->sections);
	r_list_free (o->strings);
	r_list_free (o->symbols);
	r_list_free (o->classes);
	r_list_free (o->lines);
	sdb_free (o->kv);
	if (o->mem) {
		o->mem->free = mem_free;
	}
	r_list_free (o->mem);
	o->mem = NULL;
	o->entries = NULL;
	o->fields = NULL;
	o->imports = NULL;
	o->libs = NULL;
	o->relocs = NULL;
	o->sections = NULL;
	o->strings = NULL;
	o->symbols = NULL;
	o->classes = NULL;
	o->lines = NULL;
	o->info = NULL;
	o->kv = NULL;
	for (i = 0; i < R_BIN_SYM_LAST; i++) {
		free (o->binsym[i]);
		o->binsym[i] = NULL;
	}
}


int blk_get_device_by_str(const char *ifname, const char *dev_hwpart_str,
			  struct blk_desc **dev_desc)
{
	char *ep;
	char *dup_str = NULL;
	const char *dev_str, *hwpart_str;
	int dev, hwpart;

	hwpart_str = strchr(dev_hwpart_str, '.');
	if (hwpart_str) {
		dup_str = strdup(dev_hwpart_str);
		dup_str[hwpart_str - dev_hwpart_str] = 0;
		dev_str = dup_str;
		hwpart_str++;
	} else {
		dev_str = dev_hwpart_str;
		hwpart = 0;
	}

	dev = simple_strtoul(dev_str, &ep, 16);
	if (*ep) {
		printf("** Bad device specification %s %s **\n",
		       ifname, dev_str);
		dev = -EINVAL;
		goto cleanup;
	}

	if (hwpart_str) {
		hwpart = simple_strtoul(hwpart_str, &ep, 16);
		if (*ep) {
			printf("** Bad HW partition specification %s %s **\n",
			    ifname, hwpart_str);
			dev = -EINVAL;
			goto cleanup;
		}
	}

	*dev_desc = get_dev_hwpart(ifname, dev, hwpart);
	if (!(*dev_desc) || ((*dev_desc)->type == DEV_TYPE_UNKNOWN)) {
		debug("** Bad device %s %s **\n", ifname, dev_hwpart_str);
		dev = -ENOENT;
		goto cleanup;
	}

#ifdef CONFIG_HAVE_BLOCK_DEVICE
	/*
	 * Updates the partition table for the specified hw partition.
	 * Always should be done, otherwise hw partition 0 will return stale
	 * data after displaying a non-zero hw partition.
	 */
	part_init(*dev_desc);
#endif

cleanup:
	free(dup_str);
	return dev;
}


std::unique_ptr<Renderer> WebMediaPlayerImpl::CreateRenderer() {
  DCHECK(main_task_runner_->BelongsToCurrentThread());

  if (always_enable_overlays_)
    EnableOverlay();

  RequestOverlayInfoCB request_overlay_info_cb;
#if defined(OS_ANDROID)
  request_overlay_info_cb = BindToCurrentLoop(
      base::Bind(&WebMediaPlayerImpl::OnOverlayInfoRequested, AsWeakPtr()));
#endif
  return renderer_factory_selector_->GetCurrentFactory()->CreateRenderer(
      media_task_runner_, worker_task_runner_, audio_source_provider_.get(),
      compositor_.get(), request_overlay_info_cb, client_->TargetColorSpace());
}


int setup_allrouters_membership(struct Interface *iface)
{
	struct ipv6_mreq mreq;

	memset(&mreq, 0, sizeof(mreq));
	mreq.ipv6mr_interface = iface->if_index;

	/* ipv6-allrouters: ff02::2 */
	mreq.ipv6mr_multiaddr.s6_addr32[0] = htonl(0xFF020000);
	mreq.ipv6mr_multiaddr.s6_addr32[3] = htonl(0x2);

	if (setsockopt(sock, SOL_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
	{
		/* linux-2.6.12-bk4 returns error with HUP signal but keep listening */
		if (errno != EADDRINUSE)
		{
			flog(LOG_ERR, "can't join ipv6-allrouters on %s", iface->Name);
			return (-1);
		}
	}

	return (0);
}


void Layer::SetHaveWheelEventHandlers(bool have_wheel_event_handlers) {
  DCHECK(IsPropertyChangeAllowed());
  if (have_wheel_event_handlers_ == have_wheel_event_handlers)
    return;
  have_wheel_event_handlers_ = have_wheel_event_handlers;
  SetNeedsCommit();
}


static int add_string_metadata(int count, const char *name,

                               TiffContext *s)

{

    char *value;

    if (bytestream2_get_bytes_left(&s->gb) < count || count < 0)

        return AVERROR_INVALIDDATA;

    value = av_malloc(count + 1);

    if (!value)

        return AVERROR(ENOMEM);

    bytestream2_get_bufferu(&s->gb, value, count);

    value[count] = 0;

    av_dict_set(avpriv_frame_get_metadatap(&s->picture), name, value, AV_DICT_DONT_STRDUP_VAL);

    return 0;

}


VirtIODevice *virtio_scsi_init(DeviceState *dev, VirtIOSCSIConf *proxyconf)

{

    VirtIOSCSI *s;

    static int virtio_scsi_id;

    size_t sz;

    int i;

    sz = sizeof(VirtIOSCSI) + proxyconf->num_queues * sizeof(VirtQueue *);

    s = (VirtIOSCSI *)virtio_common_init("virtio-scsi", VIRTIO_ID_SCSI,

                                         sizeof(VirtIOSCSIConfig), sz);

    s->qdev = dev;

    s->conf = proxyconf;

    /* TODO set up vdev function pointers */

    s->vdev.get_config = virtio_scsi_get_config;

    s->vdev.set_config = virtio_scsi_set_config;

    s->vdev.get_features = virtio_scsi_get_features;

    s->vdev.reset = virtio_scsi_reset;

    s->ctrl_vq = virtio_add_queue(&s->vdev, VIRTIO_SCSI_VQ_SIZE,

                                   virtio_scsi_handle_ctrl);

    s->event_vq = virtio_add_queue(&s->vdev, VIRTIO_SCSI_VQ_SIZE,

                                   NULL);

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

        s->cmd_vqs[i] = virtio_add_queue(&s->vdev, VIRTIO_SCSI_VQ_SIZE,

                                         virtio_scsi_handle_cmd);

    }

    scsi_bus_new(&s->bus, dev, &virtio_scsi_scsi_info);

    if (!dev->hotplugged) {

        scsi_bus_legacy_handle_cmdline(&s->bus);

    }

    register_savevm(dev, "virtio-scsi", virtio_scsi_id++, 1,

                    virtio_scsi_save, virtio_scsi_load, s);

    return &s->vdev;

}


void cil_destroy_catset(struct cil_catset *catset)
{
	if (catset == NULL) {
		return;
	}

	cil_symtab_datum_destroy(&catset->datum);

	cil_destroy_cats(catset->cats);

	free(catset);
}


sctp_disposition_t sctp_sf_t1_cookie_timer_expire(struct net *net,
					   const struct sctp_endpoint *ep,
					   const struct sctp_association *asoc,
					   const sctp_subtype_t type,
					   void *arg,
					   sctp_cmd_seq_t *commands)
{
	struct sctp_chunk *repl = NULL;
	int attempts = asoc->init_err_counter + 1;

	SCTP_DEBUG_PRINTK("Timer T1 expired (COOKIE-ECHO).\n");
	SCTP_INC_STATS(net, SCTP_MIB_T1_COOKIE_EXPIREDS);

	if (attempts <= asoc->max_init_attempts) {
		repl = sctp_make_cookie_echo(asoc, NULL);
		if (!repl)
			return SCTP_DISPOSITION_NOMEM;

		sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
				SCTP_CHUNK(repl));
		/* Issue a sideeffect to do the needed accounting. */
		sctp_add_cmd_sf(commands, SCTP_CMD_COOKIEECHO_RESTART,
				SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));

		sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
	} else {
		sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
				SCTP_ERROR(ETIMEDOUT));
		sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
				SCTP_PERR(SCTP_ERROR_NO_ERROR));
		return SCTP_DISPOSITION_DELETE_TCB;
	}

	return SCTP_DISPOSITION_CONSUME;
}


    static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
{
	yy_state_type yy_current_state;
	char *yy_cp;
    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;

	yy_current_state = yyg->yy_start;

	for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
		{
		YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
		if ( yy_accept[yy_current_state] )
			{
			yyg->yy_last_accepting_state = yy_current_state;
			yyg->yy_last_accepting_cpos = yy_cp;
			}
		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
			{
			yy_current_state = (int) yy_def[yy_current_state];
			if ( yy_current_state >= 45 )
				yy_c = yy_meta[(unsigned int) yy_c];
			}
		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
		}

	return yy_current_state;


void vmxnet_tx_pkt_uninit(struct VmxnetTxPkt *pkt)
{
    if (pkt) {
        g_free(pkt->vec);
        g_free(pkt->raw);
        g_free(pkt);
    }
}


static int context_equiv(struct perf_event_context *ctx1,
			 struct perf_event_context *ctx2)
{
	return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
		&& ctx1->parent_gen == ctx2->parent_gen
		&& !ctx1->pin_count && !ctx2->pin_count;
}


static int JBIGSetupEncode(TIFF* tif)
{
	if (TIFFNumberOfStrips(tif) != 1)
	{
		TIFFErrorExt(tif->tif_clientdata, "JBIG", "Multistrip images not supported in encoder");
		return 0;
	}

	return 1;
}


static int32_t reduceToUMappings ( UCMTable * table ) {
 UCMapping * mappings ;
 int32_t * map ;
 int32_t i , j , count ;
 int8_t flag ;
 mappings = table -> mappings ;
 map = table -> reverseMap ;
 count = table -> mappingsLength ;
 for ( i = j = 0 ;
 i < count ;
 ++ i ) {
 flag = mappings [ map [ i ] ] . f ;
 if ( flag != 0 && flag != 3 ) {
 break ;
 }
 }
 for ( j = i ;
 i < count ;
 ++ i ) {
 flag = mappings [ map [ i ] ] . f ;
 if ( flag == 0 || flag == 3 ) {
 map [ j ++ ] = map [ i ] ;
 }
 }
 return j ;
 }


msg_advance(int col)
{
    if (msg_silent != 0)	// nothing to advance to
    {
	msg_col = col;		// for redirection, may fill it up later
	return;
    }
    if (col >= Columns)		// not enough room
	col = Columns - 1;
#ifdef FEAT_RIGHTLEFT
    if (cmdmsg_rl)
	while (msg_col > Columns - col)
	    msg_putchar(' ');
    else
#endif
	while (msg_col < col)
	    msg_putchar(' ');
}


void CClient::Con_RemoveFavorite(IConsole::IResult *pResult, void *pUserData)
{
	CClient *pSelf = (CClient *)pUserData;
	NETADDR Addr;
	if(net_addr_from_str(&Addr, pResult->GetString(0)) == 0)
		pSelf->m_ServerBrowser.RemoveFavorite(Addr);
}


static int xar_cleanup_temp_file(cli_ctx *ctx, int fd, char * tmpname)
{
    int rc = CL_SUCCESS;
    if (fd > -1)
        close(fd);
    if (tmpname != NULL) {
        if (!ctx->engine->keeptmp) {
            if (cli_unlink(tmpname)) {
                cli_dbgmsg("cli_scanxar: error unlinking tmpfile %s\n", tmpname);
                rc = CL_EUNLINK;
            }
        }
        free(tmpname);
    }
    return rc;
}


BlobDataHandle::BlobDataHandle(PassOwnPtr<BlobData> data, long long size)
 {
     UNUSED_PARAM(size);
     m_internalURL = BlobURL::createInternalURL();
    ThreadableBlobRegistry::registerBlobURL(m_internalURL, data);
 }


LinearHistogram::LinearHistogram(const std::string& name,
                                 Sample minimum,
                                 Sample maximum,
                                 const BucketRanges* ranges,
                                 HistogramBase::AtomicCount* counts,
                                 HistogramBase::AtomicCount* logged_counts,
                                 uint32_t counts_size,
                                 HistogramSamples::Metadata* meta,
                                 HistogramSamples::Metadata* logged_meta)
    : Histogram(name, minimum, maximum, ranges, counts, logged_counts,
                counts_size, meta, logged_meta) {}


inline bool Wasm::copyToPointerSize(const Buffer::Instance& buffer, uint64_t start, uint64_t length,
                                    uint64_t ptr_ptr, uint64_t size_ptr) {
  uint64_t size = buffer.length();
  if (size < start + length) {
    return false;
  }
  auto nslices = buffer.getRawSlices(nullptr, 0);
  auto slices = std::make_unique<Buffer::RawSlice[]>(nslices + 10 /* pad for evbuffer overrun */);
  auto actual_slices = buffer.getRawSlices(&slices[0], nslices);
  uint64_t pointer = 0;
  char* p = static_cast<char*>(allocMemory(length, &pointer));
  auto s = start;
  auto l = length;
  if (!p) {
    return false;
  }
  for (uint64_t i = 0; i < actual_slices; i++) {
    if (slices[i].len_ <= s) {
      s -= slices[i].len_;
      continue;
    }
    auto ll = l;
    if (ll > s + slices[i].len_)
      ll = s + slices[i].len_;
    memcpy(p, static_cast<char*>(slices[i].mem_) + s, ll);
    l -= ll;
    if (l <= 0) {
      break;
    }
    s = 0;
    p += ll;
  }
  if (!wasm_vm_->setWord(ptr_ptr, Word(pointer))) {
    return false;
  }
  if (!wasm_vm_->setWord(size_ptr, Word(length))) {
    return false;
  }
  return true;
}


void BaseRenderingContext2D::scale(double sx, double sy) {
  PaintCanvas* c = DrawingCanvas();
  if (!c)
    return;

  if (!std::isfinite(sx) || !std::isfinite(sy))
    return;

  AffineTransform new_transform = GetState().Transform();
  new_transform.ScaleNonUniform(sx, sy);
  if (GetState().Transform() == new_transform)
    return;

  ModifiableState().SetTransform(new_transform);
  if (!GetState().IsTransformInvertible())
    return;

  c->scale(sx, sy);
  path_.Transform(AffineTransform().ScaleNonUniform(1.0 / sx, 1.0 / sy));
}


status_t AudioSource::read(
 MediaBuffer **out, const ReadOptions * /* options */) {
 Mutex::Autolock autoLock(mLock);
 *out = NULL;

 if (mInitCheck != OK) {
 return NO_INIT;
 }

 while (mStarted && mBuffersReceived.empty()) {
        mFrameAvailableCondition.wait(mLock);
 }
 if (!mStarted) {
 return OK;
 }
 MediaBuffer *buffer = *mBuffersReceived.begin();
    mBuffersReceived.erase(mBuffersReceived.begin());
 ++mNumClientOwnedBuffers;
    buffer->setObserver(this);
    buffer->add_ref();

 int64_t timeUs;
    CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
 int64_t elapsedTimeUs = timeUs - mStartTimeUs;
 if (elapsedTimeUs < kAutoRampStartUs) {
        memset((uint8_t *) buffer->data(), 0, buffer->range_length());
 } else if (elapsedTimeUs < kAutoRampStartUs + kAutoRampDurationUs) {
 int32_t autoRampDurationFrames =
 ((int64_t)kAutoRampDurationUs * mSampleRate + 500000LL) / 1000000LL; //Need type casting

 int32_t autoRampStartFrames =
 ((int64_t)kAutoRampStartUs * mSampleRate + 500000LL) / 1000000LL; //Need type casting

 int32_t nFrames = mNumFramesReceived - autoRampStartFrames;
        rampVolume(nFrames, autoRampDurationFrames,
 (uint8_t *) buffer->data(), buffer->range_length());
 }

 if (mTrackMaxAmplitude) {
        trackMaxAmplitude(
 (int16_t *) buffer->data(), buffer->range_length() >> 1);
 }

 if (mSampleRate != mOutSampleRate) {
 if (mFirstSampleTimeUs < 0) {
            mFirstSampleTimeUs = timeUs;
 }
        timeUs = mFirstSampleTimeUs + (timeUs - mFirstSampleTimeUs)
 * (int64_t)mSampleRate / (int64_t)mOutSampleRate;
        buffer->meta_data()->setInt64(kKeyTime, timeUs);
 }

 *out = buffer;
 return OK;
}


static jpc_enc_prc_t * prc_create ( jpc_enc_prc_t * prc , jpc_enc_cp_t * cp , jpc_enc_band_t * band ) {
 uint_fast32_t prcno ;
 uint_fast32_t prcxind ;
 uint_fast32_t prcyind ;
 uint_fast32_t cbgtlx ;
 uint_fast32_t cbgtly ;
 uint_fast32_t tlprctlx ;
 uint_fast32_t tlprctly ;
 uint_fast32_t tlcbgtlx ;
 uint_fast32_t tlcbgtly ;
 uint_fast16_t rlvlno ;
 jpc_enc_rlvl_t * rlvl ;
 uint_fast32_t tlcblktlx ;
 uint_fast32_t tlcblktly ;
 uint_fast32_t brcblkbrx ;
 uint_fast32_t brcblkbry ;
 uint_fast32_t cblkno ;
 jpc_enc_cblk_t * cblk ;
 jpc_enc_tcmpt_t * tcmpt ;
 prc -> cblks = 0 ;
 prc -> incltree = 0 ;
 prc -> savincltree = 0 ;
 prc -> nlibtree = 0 ;
 prc -> savnlibtree = 0 ;
 rlvl = band -> rlvl ;
 tcmpt = rlvl -> tcmpt ;
 rlvlno = rlvl - tcmpt -> rlvls ;
 prcno = prc - band -> prcs ;
 prcxind = prcno % rlvl -> numhprcs ;
 prcyind = prcno / rlvl -> numhprcs ;
 prc -> band = band ;
 tlprctlx = JPC_FLOORTOMULTPOW2 ( rlvl -> tlx , rlvl -> prcwidthexpn ) ;
 tlprctly = JPC_FLOORTOMULTPOW2 ( rlvl -> tly , rlvl -> prcheightexpn ) ;
 if ( ! rlvlno ) {
 tlcbgtlx = tlprctlx ;
 tlcbgtly = tlprctly ;
 }
 else {
 tlcbgtlx = JPC_CEILDIVPOW2 ( tlprctlx , 1 ) ;
 tlcbgtly = JPC_CEILDIVPOW2 ( tlprctly , 1 ) ;
 }
 cbgtlx = tlcbgtlx + ( prcxind << rlvl -> cbgwidthexpn ) ;
 cbgtly = tlcbgtly + ( prcyind << rlvl -> cbgheightexpn ) ;
 prc -> tlx = JAS_MAX ( jas_seq2d_xstart ( band -> data ) , cbgtlx ) ;
 prc -> tly = JAS_MAX ( jas_seq2d_ystart ( band -> data ) , cbgtly ) ;
 prc -> brx = JAS_MIN ( jas_seq2d_xend ( band -> data ) , cbgtlx + ( 1 << rlvl -> cbgwidthexpn ) ) ;
 prc -> bry = JAS_MIN ( jas_seq2d_yend ( band -> data ) , cbgtly + ( 1 << rlvl -> cbgheightexpn ) ) ;
 if ( prc -> tlx < prc -> brx && prc -> tly < prc -> bry ) {
 tlcblktlx = JPC_FLOORTOMULTPOW2 ( prc -> tlx , rlvl -> cblkwidthexpn ) ;
 tlcblktly = JPC_FLOORTOMULTPOW2 ( prc -> tly , rlvl -> cblkheightexpn ) ;
 brcblkbrx = JPC_CEILTOMULTPOW2 ( prc -> brx , rlvl -> cblkwidthexpn ) ;
 brcblkbry = JPC_CEILTOMULTPOW2 ( prc -> bry , rlvl -> cblkheightexpn ) ;
 prc -> numhcblks = JPC_FLOORDIVPOW2 ( brcblkbrx - tlcblktlx , rlvl -> cblkwidthexpn ) ;
 prc -> numvcblks = JPC_FLOORDIVPOW2 ( brcblkbry - tlcblktly , rlvl -> cblkheightexpn ) ;
 prc -> numcblks = prc -> numhcblks * prc -> numvcblks ;
 if ( ! ( prc -> incltree = jpc_tagtree_create ( prc -> numhcblks , prc -> numvcblks ) ) ) {
 goto error ;
 }
 if ( ! ( prc -> nlibtree = jpc_tagtree_create ( prc -> numhcblks , prc -> numvcblks ) ) ) {
 goto error ;
 }
 if ( ! ( prc -> savincltree = jpc_tagtree_create ( prc -> numhcblks , prc -> numvcblks ) ) ) {
 goto error ;
 }
 if ( ! ( prc -> savnlibtree = jpc_tagtree_create ( prc -> numhcblks , prc -> numvcblks ) ) ) {
 goto error ;
 }
 if ( ! ( prc -> cblks = jas_alloc2 ( prc -> numcblks , sizeof ( jpc_enc_cblk_t ) ) ) ) {
 goto error ;
 }
 for ( cblkno = 0 , cblk = prc -> cblks ;
 cblkno < prc -> numcblks ;
 ++ cblkno , ++ cblk ) {
 cblk -> passes = 0 ;
 cblk -> stream = 0 ;
 cblk -> mqenc = 0 ;
 cblk -> data = 0 ;
 cblk -> flags = 0 ;
 cblk -> prc = prc ;
 }
 for ( cblkno = 0 , cblk = prc -> cblks ;
 cblkno < prc -> numcblks ;
 ++ cblkno , ++ cblk ) {
 if ( ! cblk_create ( cblk , cp , prc ) ) {
 goto error ;
 }
 }
 }
 else {
 prc -> tlx = prc -> brx ;
 prc -> tly = prc -> bry ;
 prc -> numcblks = 0 ;
 prc -> numhcblks = 0 ;
 prc -> numvcblks = 0 ;
 prc -> cblks = 0 ;
 prc -> incltree = 0 ;
 prc -> nlibtree = 0 ;
 prc -> savincltree = 0 ;
 prc -> savnlibtree = 0 ;
 }
 return prc ;
 error : prc_destroy ( prc ) ;
 return 0 ;
 }


list_hashtable_vars(
    hashtab_T	*ht,
    char	*prefix,
    int		empty,
    int		*first)
{
    hashitem_T	*hi;
    dictitem_T	*di;
    int		todo;
    char_u	buf[IOSIZE];

    todo = (int)ht->ht_used;
    for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
    {
	if (!HASHITEM_EMPTY(hi))
	{
	    --todo;
	    di = HI2DI(hi);

	    // apply :filter /pat/ to variable name
	    vim_strncpy((char_u *)buf, (char_u *)prefix, IOSIZE - 1);
	    vim_strcat((char_u *)buf, di->di_key, IOSIZE);
	    if (message_filtered(buf))
		continue;

	    if (empty || di->di_tv.v_type != VAR_STRING
					   || di->di_tv.vval.v_string != NULL)
		list_one_var(di, prefix, first);
	}
    }
}


  inline Eigen::DSizes<int, 2> OneByM(int m) {
    return Eigen::DSizes<int, 2>(1, m);
  }


static struct hlist_head *unix_sockets_unbound(void *addr)
{
	unsigned long hash = (unsigned long)addr;

	hash ^= hash >> 16;
	hash ^= hash >> 8;
	hash %= UNIX_HASH_SIZE;
	return &unix_socket_table[UNIX_HASH_SIZE + hash];
}


static BOOL update_gdi_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cacheBitmap)
{
	rdpBitmap* bitmap;
	rdpBitmap* prevBitmap;
	rdpCache* cache = context->cache;
	bitmap = Bitmap_Alloc(context);

	if (!bitmap)
		return FALSE;

	Bitmap_SetDimensions(bitmap, cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight);

	if (!bitmap->Decompress(context, bitmap, cacheBitmap->bitmapDataStream,
	                        cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight,
	                        cacheBitmap->bitmapBpp, cacheBitmap->bitmapLength,
	                        cacheBitmap->compressed, RDP_CODEC_ID_NONE))
	{
		Bitmap_Free(context, bitmap);
		return FALSE;
	}

	if (!bitmap->New(context, bitmap))
	{
		Bitmap_Free(context, bitmap);
		return FALSE;
	}

	prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex);
	Bitmap_Free(context, prevBitmap);
	return bitmap_cache_put(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex, bitmap);
}


png_do_read_interlace(png_structp png_ptr)
{
   png_row_infop row_info = &(png_ptr->row_info);
   png_bytep row = png_ptr->row_buf + 1;
   int pass = png_ptr->pass;
    png_uint_32 transformations = png_ptr->transformations;
    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
    /* Offset to next interlace block */
    PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};

    png_debug(1, "in png_do_read_interlace");
    if (row != NULL && row_info != NULL)
   {
      png_uint_32 final_width;

      final_width = row_info->width * png_pass_inc[pass];

      switch (row_info->pixel_depth)
      {
         case 1:
         {
            png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
            png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
            int sshift, dshift;
            int s_start, s_end, s_inc;
            int jstop = png_pass_inc[pass];
            png_byte v;
            png_uint_32 i;
            int j;

#ifdef PNG_READ_PACKSWAP_SUPPORTED
            if (transformations & PNG_PACKSWAP)
            {
                sshift = (int)((row_info->width + 7) & 0x07);
                dshift = (int)((final_width + 7) & 0x07);
                s_start = 7;
                s_end = 0;
                s_inc = -1;
            }
            else
#endif
            {
                sshift = 7 - (int)((row_info->width + 7) & 0x07);
                dshift = 7 - (int)((final_width + 7) & 0x07);
                s_start = 0;
                s_end = 7;
                s_inc = 1;
            }

            for (i = 0; i < row_info->width; i++)
            {
               v = (png_byte)((*sp >> sshift) & 0x01);
               for (j = 0; j < jstop; j++)
               {
                  *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
                  *dp |= (png_byte)(v << dshift);
                  if (dshift == s_end)
                  {
                     dshift = s_start;
                     dp--;
                  }
                  else
                     dshift += s_inc;
               }
               if (sshift == s_end)
               {
                  sshift = s_start;
                  sp--;
               }
               else
                  sshift += s_inc;
            }
            break;
         }
         case 2:
         {
            png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
            png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
            int sshift, dshift;
            int s_start, s_end, s_inc;
            int jstop = png_pass_inc[pass];
            png_uint_32 i;

#ifdef PNG_READ_PACKSWAP_SUPPORTED
            if (transformations & PNG_PACKSWAP)
            {
               sshift = (int)(((row_info->width + 3) & 0x03) << 1);
               dshift = (int)(((final_width + 3) & 0x03) << 1);
               s_start = 6;
               s_end = 0;
               s_inc = -2;
            }
            else
#endif
            {
               sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
               dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
               s_start = 0;
               s_end = 6;
               s_inc = 2;
            }

            for (i = 0; i < row_info->width; i++)
            {
               png_byte v;
               int j;

               v = (png_byte)((*sp >> sshift) & 0x03);
               for (j = 0; j < jstop; j++)
               {
                  *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
                  *dp |= (png_byte)(v << dshift);
                  if (dshift == s_end)
                  {
                     dshift = s_start;
                     dp--;
                  }
                  else
                     dshift += s_inc;
               }
               if (sshift == s_end)
               {
                  sshift = s_start;
                  sp--;
               }
               else
                  sshift += s_inc;
            }
            break;
         }
         case 4:
         {
            png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
            png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
            int sshift, dshift;
            int s_start, s_end, s_inc;
            png_uint_32 i;
            int jstop = png_pass_inc[pass];

#ifdef PNG_READ_PACKSWAP_SUPPORTED
            if (transformations & PNG_PACKSWAP)
            {
               sshift = (int)(((row_info->width + 1) & 0x01) << 2);
               dshift = (int)(((final_width + 1) & 0x01) << 2);
               s_start = 4;
               s_end = 0;
               s_inc = -4;
            }
            else
#endif
            {
               sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
               dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
               s_start = 0;
               s_end = 4;
               s_inc = 4;
            }

            for (i = 0; i < row_info->width; i++)
            {
               png_byte v = (png_byte)((*sp >> sshift) & 0xf);
               int j;

               for (j = 0; j < jstop; j++)
               {
                  *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
                  *dp |= (png_byte)(v << dshift);
                  if (dshift == s_end)
                  {
                     dshift = s_start;
                     dp--;
                  }
                  else
                     dshift += s_inc;
               }
               if (sshift == s_end)
               {
                  sshift = s_start;
                  sp--;
               }
               else
                  sshift += s_inc;
            }
            break;
         }
         default:
         {
            png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
            png_bytep sp = row + (png_size_t)(row_info->width - 1)
                * pixel_bytes;
            png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;

            int jstop = png_pass_inc[pass];
            png_uint_32 i;

            for (i = 0; i < row_info->width; i++)
            {
               png_byte v[8];
               int j;

               png_memcpy(v, sp, pixel_bytes);
               for (j = 0; j < jstop; j++)
               {
                  png_memcpy(dp, v, pixel_bytes);
                  dp -= pixel_bytes;
               }
               sp -= pixel_bytes;
            }
            break;
         }
      }
      row_info->width = final_width;
      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
   }
#ifndef PNG_READ_PACKSWAP_SUPPORTED
   PNG_UNUSED(transformations) /* Silence compiler warning */
#endif
}


int STDCALL mysql_set_server_option(MYSQL *mysql,
                                    enum enum_mysql_set_option option)
{
  char buffer[2];
  int2store(buffer, (uint)option);
  return(ma_simple_command(mysql, COM_SET_OPTION, buffer, sizeof(buffer), 0, 0));
}


static int read_packets ( WriterContext * w , InputFile * ifile ) {
 AVFormatContext * fmt_ctx = ifile -> fmt_ctx ;
 int i , ret = 0 ;
 int64_t cur_ts = fmt_ctx -> start_time ;
 if ( read_intervals_nb == 0 ) {
 ReadInterval interval = ( ReadInterval ) {
 . has_start = 0 , . has_end = 0 }
 ;
 ret = read_interval_packets ( w , ifile , & interval , & cur_ts ) ;
 }
 else {
 for ( i = 0 ;
 i < read_intervals_nb ;
 i ++ ) {
 ret = read_interval_packets ( w , ifile , & read_intervals [ i ] , & cur_ts ) ;
 if ( ret < 0 ) break ;
 }
 }
 return ret ;
 }


static void phar_mung_server_vars(char *fname, char *entry, int entry_len, char *basename, int request_uri_len) /* {{{ */
{
	HashTable *_SERVER;
	zval *stuff;
	char *path_info;
	int basename_len = strlen(basename);
	int code;
	zval temp;

	/* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */
	if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_UNDEF) {
		return;
	}

	_SERVER = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]);

	/* PATH_INFO and PATH_TRANSLATED should always be munged */
	if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO")-1))) {
		path_info = Z_STRVAL_P(stuff);
		code = Z_STRLEN_P(stuff);
		if (code > entry_len && !memcmp(path_info, entry, entry_len)) {
			ZVAL_STR(&temp, Z_STR_P(stuff));
			ZVAL_STRINGL(stuff, path_info + entry_len, request_uri_len);
			zend_hash_str_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO")-1, &temp);
		}
	}

	if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED")-1))) {
		zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry);

		ZVAL_STR(&temp, Z_STR_P(stuff));
		ZVAL_NEW_STR(stuff, str);

		zend_hash_str_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED")-1, &temp);
	}

	if (!PHAR_G(phar_SERVER_mung_list)) {
		return;
	}

	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_REQUEST_URI) {
		if (NULL != (stuff = zend_hash_str_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI")-1))) {
			path_info = Z_STRVAL_P(stuff);
			code = Z_STRLEN_P(stuff);
			if (code > basename_len && !memcmp(path_info, basename, basename_len)) {
				ZVAL_STR(&temp, Z_STR_P(stuff));
				ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len);
				zend_hash_str_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI")-1, &temp);
			}
		}
	}

	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_PHP_SELF) {
		if (NULL != (stuff = zend_hash_str_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF")-1))) {
			path_info = Z_STRVAL_P(stuff);
			code = Z_STRLEN_P(stuff);

			if (code > basename_len && !memcmp(path_info, basename, basename_len)) {
				ZVAL_STR(&temp, Z_STR_P(stuff));
				ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len);
				zend_hash_str_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF")-1, &temp);
			}
		}
	}

	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_NAME) {
		if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1))) {
			ZVAL_STR(&temp, Z_STR_P(stuff));
			ZVAL_STRINGL(stuff, entry, entry_len);
			zend_hash_str_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME")-1, &temp);
		}
	}

	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_FILENAME) {
		if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1))) {
			zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry);

			ZVAL_STR(&temp, Z_STR_P(stuff));
			ZVAL_NEW_STR(stuff, str);

			zend_hash_str_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME")-1, &temp);
		}
	}
}
/* }}} */


static void hwahc_init(struct hwahc *hwahc)
{
	wa_init(&hwahc->wa);
}


R_API RList *r_bin_java_get_method_exception_table_with_addr(RBinJavaObj *bin, ut64 addr) {
	RListIter *iter = NULL, *iter_tmp = NULL;
	RBinJavaField *fm_type, *res = NULL;
	if (!bin && R_BIN_JAVA_GLOBAL_BIN) {
		bin = R_BIN_JAVA_GLOBAL_BIN;
	}
	if (!bin) {
		eprintf ("Attempting to analyse function when the R_BIN_JAVA_GLOBAL_BIN has not been set.\n");
		return NULL;
	}
	r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
		ut64 offset = r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr,
		size = r_bin_java_get_method_code_size (fm_type);
		if (addr >= offset && addr <= size + offset) {
			res = fm_type;
		}
	}
	if (res) {
		RBinJavaAttrInfo *code_attr = r_bin_java_get_method_code_attribute (res);
		return code_attr->info.code_attr.exception_table;
	}
	return NULL;
}


kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma, struct buflist *buflist, MPT_ADAPTER *ioc)
{
	MptSge_t	*sg = sgl;
	struct buflist	*bl = buflist;
	u32		 nib;
	int		 dir;
	int		 n = 0;

	if (sg->FlagsLength & 0x04000000)
		dir = PCI_DMA_TODEVICE;
	else
		dir = PCI_DMA_FROMDEVICE;

	nib = (sg->FlagsLength & 0xF0000000) >> 28;
	while (! (nib & 0x4)) { /* eob */
		/* skip ignore/chain. */
		if (nib == 0 || nib == 3) {
			;
		} else if (sg->Address) {
			dma_addr_t dma_addr;
			void *kptr;
			int len;

			dma_addr = sg->Address;
			kptr = bl->kptr;
			len = bl->len;
			pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
			pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
			n++;
		}
		sg++;
		bl++;
		nib = (le32_to_cpu(sg->FlagsLength) & 0xF0000000) >> 28;
	}

	/* we're at eob! */
	if (sg->Address) {
		dma_addr_t dma_addr;
		void *kptr;
		int len;

		dma_addr = sg->Address;
		kptr = bl->kptr;
		len = bl->len;
		pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
		pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
		n++;
	}

	pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sgl, sgl_dma);
	kfree(buflist);
	dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: Free'd 1 SGL buf + %d kbufs!\n",
	    ioc->name, n));
}


static int io_buffer_validate(struct iovec *iov)
{
	unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);

	/*
	 * Don't impose further limits on the size and buffer
	 * constraints here, we'll -EINVAL later when IO is
	 * submitted if they are wrong.
	 */
	if (!iov->iov_base)
		return iov->iov_len ? -EFAULT : 0;
	if (!iov->iov_len)
		return -EFAULT;

	/* arbitrary limit, but we need something */
	if (iov->iov_len > SZ_1G)
		return -EFAULT;

	if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
		return -EOVERFLOW;

	return 0;


void OSDService::remove_pgid(spg_t pgid, PG *pg)
{
  Mutex::Locker l(pgid_lock);
  assert(pgid_tracker.count(pgid));
  assert(pgid_tracker[pgid] > 0);
  pgid_tracker[pgid]--;
  if (pgid_tracker[pgid] == 0) {
    pgid_tracker.erase(pgid);
    live_pgs.erase(pgid);
  }
}


int main(int argc, const char **argv) // ignore_convention
{
#if defined(CONF_FAMILY_WINDOWS)
	for(int i = 1; i < argc; i++) // ignore_convention
	{
		if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention
		{
			ShowWindow(GetConsoleWindow(), SW_HIDE);
			break;
		}
	}
#endif

	CServer *pServer = CreateServer();
	IKernel *pKernel = IKernel::Create();

	// create the components
	IEngine *pEngine = CreateEngine("Teeworlds");
	IEngineMap *pEngineMap = CreateEngineMap();
	IGameServer *pGameServer = CreateGameServer();
	IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON);
	IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer();
	IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention
	IConfig *pConfig = CreateConfig();

	pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole);

	{
		bool RegisterFail = false;

		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine);
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap));
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer);
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole);
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage);
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig);
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both
		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer));

		if(RegisterFail)
			return -1;
	}

	pEngine->Init();
	pConfig->Init();
	pEngineMasterServer->Init();
	pEngineMasterServer->Load();

	// register all console commands
	pServer->RegisterCommands();

	// execute autoexec file
	pConsole->ExecuteFile("autoexec.cfg");

	// parse the command line arguments
	if(argc > 1) // ignore_convention
		pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention

	// restore empty config strings to their defaults
	pConfig->RestoreStrings();

	pEngine->InitLogfile();

	// run the server
	dbg_msg("server", "starting...");
	pServer->Run();

	// free
	delete pServer;
	delete pKernel;
	delete pEngineMap;
	delete pGameServer;
	delete pConsole;
	delete pEngineMasterServer;
	delete pStorage;
	delete pConfig;
	return 0;
}


expand_filename(
    exarg_T	*eap,
    char_u	**cmdlinep,
    char	**errormsgp)
{
    int		has_wildcards;	// need to expand wildcards
    char_u	*repl;
    int		srclen;
    char_u	*p;
    int		n;
    int		escaped;

#ifdef FEAT_QUICKFIX
    // Skip a regexp pattern for ":vimgrep[add] pat file..."
    p = skip_grep_pat(eap);
#else
    p = eap->arg;
#endif

    /*
     * Decide to expand wildcards *before* replacing '%', '#', etc.  If
     * the file name contains a wildcard it should not cause expanding.
     * (it will be expanded anyway if there is a wildcard before replacing).
     */
    has_wildcards = mch_has_wildcard(p);
    while (*p != NUL)
    {
#ifdef FEAT_EVAL
	// Skip over `=expr`, wildcards in it are not expanded.
	if (p[0] == '`' && p[1] == '=')
	{
	    p += 2;
	    (void)skip_expr(&p, NULL);
	    if (*p == '`')
		++p;
	    continue;
	}
#endif
	/*
	 * Quick check if this cannot be the start of a special string.
	 * Also removes backslash before '%', '#' and '<'.
	 */
	if (vim_strchr((char_u *)"%#<", *p) == NULL)
	{
	    ++p;
	    continue;
	}

	/*
	 * Try to find a match at this position.
	 */
	repl = eval_vars(p, eap->arg, &srclen, &(eap->do_ecmd_lnum),
						    errormsgp, &escaped, TRUE);
	if (*errormsgp != NULL)		// error detected
	    return FAIL;
	if (repl == NULL)		// no match found
	{
	    p += srclen;
	    continue;
	}

	// Wildcards won't be expanded below, the replacement is taken
	// literally.  But do expand "~/file", "~user/file" and "$HOME/file".
	if (vim_strchr(repl, '$') != NULL || vim_strchr(repl, '~') != NULL)
	{
	    char_u *l = repl;

	    repl = expand_env_save(repl);
	    vim_free(l);
	}

	// Need to escape white space et al. with a backslash.
	// Don't do this for:
	// - replacement that already has been escaped: "##"
	// - shell commands (may have to use quotes instead).
	// - non-unix systems when there is a single argument (spaces don't
	//   separate arguments then).
	if (!eap->usefilter
		&& !escaped
		&& eap->cmdidx != CMD_bang
		&& eap->cmdidx != CMD_grep
		&& eap->cmdidx != CMD_grepadd
		&& eap->cmdidx != CMD_hardcopy
		&& eap->cmdidx != CMD_lgrep
		&& eap->cmdidx != CMD_lgrepadd
		&& eap->cmdidx != CMD_lmake
		&& eap->cmdidx != CMD_make
		&& eap->cmdidx != CMD_terminal
#ifndef UNIX
		&& !(eap->argt & EX_NOSPC)
#endif
		)
	{
	    char_u	*l;
#ifdef BACKSLASH_IN_FILENAME
	    // Don't escape a backslash here, because rem_backslash() doesn't
	    // remove it later.
	    static char_u *nobslash = (char_u *)" \t\"|";
# define ESCAPE_CHARS nobslash
#else
# define ESCAPE_CHARS escape_chars
#endif

	    for (l = repl; *l; ++l)
		if (vim_strchr(ESCAPE_CHARS, *l) != NULL)
		{
		    l = vim_strsave_escaped(repl, ESCAPE_CHARS);
		    if (l != NULL)
		    {
			vim_free(repl);
			repl = l;
		    }
		    break;
		}
	}

	// For a shell command a '!' must be escaped.
	if ((eap->usefilter || eap->cmdidx == CMD_bang
						|| eap->cmdidx == CMD_terminal)
			    && vim_strpbrk(repl, (char_u *)"!") != NULL)
	{
	    char_u	*l;

	    l = vim_strsave_escaped(repl, (char_u *)"!");
	    if (l != NULL)
	    {
		vim_free(repl);
		repl = l;
	    }
	}

	p = repl_cmdline(eap, p, srclen, repl, cmdlinep);
	vim_free(repl);
	if (p == NULL)
	    return FAIL;
    }

    /*
     * One file argument: Expand wildcards.
     * Don't do this with ":r !command" or ":w !command".
     */
    if ((eap->argt & EX_NOSPC) && !eap->usefilter)
    {
	/*
	 * May do this twice:
	 * 1. Replace environment variables.
	 * 2. Replace any other wildcards, remove backslashes.
	 */
	for (n = 1; n <= 2; ++n)
	{
	    if (n == 2)
	    {
		/*
		 * Halve the number of backslashes (this is Vi compatible).
		 * For Unix and OS/2, when wildcards are expanded, this is
		 * done by ExpandOne() below.
		 */
#if defined(UNIX)
		if (!has_wildcards)
#endif
		    backslash_halve(eap->arg);
	    }

	    if (has_wildcards)
	    {
		if (n == 1)
		{
		    /*
		     * First loop: May expand environment variables.  This
		     * can be done much faster with expand_env() than with
		     * something else (e.g., calling a shell).
		     * After expanding environment variables, check again
		     * if there are still wildcards present.
		     */
		    if (vim_strchr(eap->arg, '$') != NULL
			    || vim_strchr(eap->arg, '~') != NULL)
		    {
			expand_env_esc(eap->arg, NameBuff, MAXPATHL,
							    TRUE, TRUE, NULL);
			has_wildcards = mch_has_wildcard(NameBuff);
			p = NameBuff;
		    }
		    else
			p = NULL;
		}
		else // n == 2
		{
		    expand_T	xpc;
		    int		options = WILD_LIST_NOTFOUND
					       | WILD_NOERROR | WILD_ADD_SLASH;

		    ExpandInit(&xpc);
		    xpc.xp_context = EXPAND_FILES;
		    if (p_wic)
			options += WILD_ICASE;
		    p = ExpandOne(&xpc, eap->arg, NULL,
						   options, WILD_EXPAND_FREE);
		    if (p == NULL)
			return FAIL;
		}
		if (p != NULL)
		{
		    (void)repl_cmdline(eap, eap->arg, (int)STRLEN(eap->arg),
								 p, cmdlinep);
		    if (n == 2)	// p came from ExpandOne()
			vim_free(p);
		}
	    }
	}
    }
    return OK;
}


IN_PROC_BROWSER_TEST_F ( WebRtcApprtcBrowserTest , MANUAL_WorksOnApprtc ) {
 DetectErrorsInJavaScript ( ) ;
 ASSERT_TRUE ( LaunchApprtcInstanceOnLocalhost ( "9999" ) ) ;
 ASSERT_TRUE ( LaunchColliderOnLocalHost ( "http://localhost:9999" , "8089" ) ) ;
 while ( ! LocalApprtcInstanceIsUp ( ) ) DVLOG ( 1 ) << "Waiting for AppRTC to come up..." ;
 GURL room_url = GURL ( "http://localhost:9999/r/some_room" "?wshpp=localhost:8089&wstls=false" ) ;
 chrome : : AddTabAt ( browser ( ) , GURL ( ) , - 1 , true ) ;
 content : : WebContents * left_tab = browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) ;
 PermissionRequestManager : : FromWebContents ( left_tab ) -> set_auto_response_for_test ( PermissionRequestManager : : ACCEPT_ALL ) ;
 InfoBarResponder left_infobar_responder ( InfoBarService : : FromWebContents ( left_tab ) , InfoBarResponder : : ACCEPT ) ;
 ui_test_utils : : NavigateToURL ( browser ( ) , room_url ) ;
 chrome : : AddTabAt ( browser ( ) , GURL ( ) , - 1 , true ) ;
 content : : WebContents * right_tab = browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) ;
 PermissionRequestManager : : FromWebContents ( right_tab ) -> set_auto_response_for_test ( PermissionRequestManager : : ACCEPT_ALL ) ;
 InfoBarResponder right_infobar_responder ( InfoBarService : : FromWebContents ( right_tab ) , InfoBarResponder : : ACCEPT ) ;
 ui_test_utils : : NavigateToURL ( browser ( ) , room_url ) ;
 ASSERT_TRUE ( WaitForCallToComeUp ( left_tab ) ) ;
 ASSERT_TRUE ( WaitForCallToComeUp ( right_tab ) ) ;
 ASSERT_TRUE ( DetectRemoteVideoPlaying ( left_tab ) ) ;
 ASSERT_TRUE ( DetectRemoteVideoPlaying ( right_tab ) ) ;
 chrome : : CloseWebContents ( browser ( ) , left_tab , false ) ;
 chrome : : CloseWebContents ( browser ( ) , right_tab , false ) ;
 }


md_is_entity_str(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end)
{
    int is_contents;
    OFF off = beg;

    MD_ASSERT(text[off] == _T('&'));
    off++;

    if(off+2 < max_end  &&  text[off] == _T('#')  &&  (text[off+1] == _T('x') || text[off+1] == _T('X')))
        is_contents = md_is_hex_entity_contents(ctx, text, off+2, max_end, &off);
    else if(off+1 < max_end  &&  text[off] == _T('#'))
        is_contents = md_is_dec_entity_contents(ctx, text, off+1, max_end, &off);
    else
        is_contents = md_is_named_entity_contents(ctx, text, off, max_end, &off);

    if(is_contents  &&  off < max_end  &&  text[off] == _T(';')) {
        *p_end = off+1;
        return TRUE;
    } else {
        return FALSE;
    }
}


png_write_png(png_structp png_ptr, png_infop info_ptr,
              int transforms, voidp params)
{
   if (png_ptr == NULL || info_ptr == NULL)
      return;

   /* Write the file header information. */
   png_write_info(png_ptr, info_ptr);

   /* ------ these transformations don't touch the info structure ------- */

#ifdef PNG_WRITE_INVERT_SUPPORTED
   /* Invert monochrome pixels */
   if (transforms & PNG_TRANSFORM_INVERT_MONO)
      png_set_invert_mono(png_ptr);
#endif

#ifdef PNG_WRITE_SHIFT_SUPPORTED
   /* Shift the pixels up to a legal bit depth and fill in
    * as appropriate to correctly scale the image.
    */
   if ((transforms & PNG_TRANSFORM_SHIFT)
               && (info_ptr->valid & PNG_INFO_sBIT))
      png_set_shift(png_ptr, &info_ptr->sig_bit);
#endif

#ifdef PNG_WRITE_PACK_SUPPORTED
   /* Pack pixels into bytes */
   if (transforms & PNG_TRANSFORM_PACKING)
       png_set_packing(png_ptr);
#endif

#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
   /* Swap location of alpha bytes from ARGB to RGBA */
   if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
      png_set_swap_alpha(png_ptr);
#endif

#ifdef PNG_WRITE_FILLER_SUPPORTED
   /* Pack XRGB/RGBX/ARGB/RGBA into * RGB (4 channels -> 3 channels) */
   if (transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER)
      png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
   else if (transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE)
      png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
#endif

#ifdef PNG_WRITE_BGR_SUPPORTED
   /* Flip BGR pixels to RGB */
   if (transforms & PNG_TRANSFORM_BGR)
      png_set_bgr(png_ptr);
#endif

#ifdef PNG_WRITE_SWAP_SUPPORTED
   /* Swap bytes of 16-bit files to most significant byte first */
   if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
      png_set_swap(png_ptr);
#endif

#ifdef PNG_WRITE_PACKSWAP_SUPPORTED
   /* Swap bits of 1, 2, 4 bit packed pixel formats */
   if (transforms & PNG_TRANSFORM_PACKSWAP)
      png_set_packswap(png_ptr);
#endif

#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
   /* Invert the alpha channel from opacity to transparency */
   if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
      png_set_invert_alpha(png_ptr);
#endif

   /* ----------------------- end of transformations ------------------- */

   /* Write the bits */
   if (info_ptr->valid & PNG_INFO_IDAT)
       png_write_image(png_ptr, info_ptr->row_pointers);

   /* It is REQUIRED to call this to finish writing the rest of the file */
   png_write_end(png_ptr, info_ptr);

   PNG_UNUSED(transforms) /* Quiet compiler warnings */
   PNG_UNUSED(params)
}


void WebContentsImpl::OnDidDisplayInsecureContent() {
  RecordAction(UserMetricsAction("SSL.DisplayedInsecureContent"));
  displayed_insecure_content_ = true;
  SSLManager::NotifySSLInternalStateChanged(
      GetController().GetBrowserContext());
}


void PersistentHistogramAllocator::ClearLastCreatedReferenceForTesting() {
   subtle::NoBarrier_Store(&last_created_, 0);
 }


  sync_pb::EntitySpecifics DefaultPreferencesSpecifics() {
    sync_pb::EntitySpecifics result;
    AddDefaultFieldValue(syncable::PREFERENCES, &result);
    return result;
  }


ex_tabnext(exarg_T *eap)
{
    int tab_number;

    switch (eap->cmdidx)
    {
	case CMD_tabfirst:
	case CMD_tabrewind:
	    goto_tabpage(1);
	    break;
	case CMD_tablast:
	    goto_tabpage(9999);
	    break;
	case CMD_tabprevious:
	case CMD_tabNext:
	    if (eap->arg && *eap->arg != NUL)
	    {
		char_u *p = eap->arg;
		char_u *p_save = p;

		tab_number = getdigits(&p);
		if (p == p_save || *p_save == '-' || *p != NUL
			    || tab_number == 0)
		{
		    /* No numbers as argument. */
		    eap->errmsg = e_invarg;
		    return;
		}
	    }
	    else
	    {
		if (eap->addr_count == 0)
		    tab_number = 1;
		else
		{
		    tab_number = eap->line2;
		    if (tab_number < 1)
		    {
			eap->errmsg = e_invrange;
			return;
		    }
		}
	    }
	    goto_tabpage(-tab_number);
	    break;
	default: /* CMD_tabnext */
	    tab_number = get_tabpage_arg(eap);
	    if (eap->errmsg == NULL)
		goto_tabpage(tab_number);
	    break;
    }
}


void HTMLInputElement::DisabledAttributeChanged() {
  TextControlElement::DisabledAttributeChanged();
  input_type_view_->DisabledAttributeChanged();
}


void WallpaperManager::SetDefaultWallpaperPath(
    const base::FilePath& default_small_wallpaper_file,
    std::unique_ptr<gfx::ImageSkia> small_wallpaper_image,
    const base::FilePath& default_large_wallpaper_file,
    std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) {
  default_small_wallpaper_file_ = default_small_wallpaper_file;
  default_large_wallpaper_file_ = default_large_wallpaper_file;

  ash::WallpaperController* controller =
      ash::Shell::Get()->wallpaper_controller();

  const bool need_update_screen =
      default_wallpaper_image_.get() &&
      controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(),
                                           false /* compare_layouts */,
                                           wallpaper::WALLPAPER_LAYOUT_CENTER);

  default_wallpaper_image_.reset();
  if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) {
    if (small_wallpaper_image) {
      default_wallpaper_image_.reset(
          new user_manager::UserImage(*small_wallpaper_image));
      default_wallpaper_image_->set_file_path(default_small_wallpaper_file);
    }
  } else {
    if (large_wallpaper_image) {
      default_wallpaper_image_.reset(
          new user_manager::UserImage(*large_wallpaper_image));
      default_wallpaper_image_->set_file_path(default_large_wallpaper_file);
     }
   }

  if (need_update_screen)
    DoSetDefaultWallpaper(EmptyAccountId(), MovableOnDestroyCallbackHolder());
 }


static void qemu_kvm_eat_signals ( CPUState * cpu ) {
 }


void killchild(gpointer key, gpointer value, gpointer user_data) {
	pid_t *pid=value;

	kill(*pid, SIGTERM);
}


Jsi_HashSearchNext(Jsi_HashSearch *searchPtr)
{
    Jsi_HashEntry *hPtr;
    Jsi_Hash *tablePtr = searchPtr->tablePtr;
    int locked = 0;

    while (searchPtr->nextEntryPtr == NULL) {
        if (searchPtr->nextIndex >= (size_t)tablePtr->numBuckets) {
            if (tablePtr->opts.lockHashProc && locked)
                (*tablePtr->opts.lockHashProc)(tablePtr, 0);
            return NULL;
        }
        if (tablePtr->opts.lockHashProc && locked == 0 && (*tablePtr->opts.lockHashProc)(tablePtr, locked++) != JSI_OK)
            return NULL;
        searchPtr->nextEntryPtr =
            tablePtr->buckets[searchPtr->nextIndex];
        searchPtr->nextIndex++;
    }
    if (tablePtr->opts.lockHashProc && locked)
        (*tablePtr->opts.lockHashProc)(tablePtr, 0);
    hPtr = searchPtr->nextEntryPtr;
    searchPtr->nextEntryPtr = hPtr->nextPtr;
    return hPtr;
}


horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
	uint16 *ToLinear16)
{
    register unsigned int  cr, cg, cb, ca, mask;

    if (n >= stride) {
	mask = CODE_MASK;
	if (stride == 3) {
	    op[0] = ToLinear16[cr = (wp[0] & mask)];
	    op[1] = ToLinear16[cg = (wp[1] & mask)];
	    op[2] = ToLinear16[cb = (wp[2] & mask)];
	    n -= 3;
	    while (n > 0) {
		wp += 3;
		op += 3;
		n -= 3;
		op[0] = ToLinear16[(cr += wp[0]) & mask];
		op[1] = ToLinear16[(cg += wp[1]) & mask];
		op[2] = ToLinear16[(cb += wp[2]) & mask];
	    }
	} else if (stride == 4) {
	    op[0] = ToLinear16[cr = (wp[0] & mask)];
	    op[1] = ToLinear16[cg = (wp[1] & mask)];
	    op[2] = ToLinear16[cb = (wp[2] & mask)];
	    op[3] = ToLinear16[ca = (wp[3] & mask)];
	    n -= 4;
	    while (n > 0) {
		wp += 4;
		op += 4;
		n -= 4;
		op[0] = ToLinear16[(cr += wp[0]) & mask];
		op[1] = ToLinear16[(cg += wp[1]) & mask];
		op[2] = ToLinear16[(cb += wp[2]) & mask];
		op[3] = ToLinear16[(ca += wp[3]) & mask];
	    }
	} else {
	    REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++)
	    n -= stride;
	    while (n > 0) {
		REPEAT(stride,
		    wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++)
		n -= stride;
	    }
	}
    }
}


static void conn_reset_postponed_data(struct connectdata *conn, int num)
{
  struct postponed_data * const psnd = &(conn->postponed[num]);
  if(psnd->buffer) {
    DEBUGASSERT(psnd->allocated_size > 0);
    DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
    DEBUGASSERT(psnd->recv_size ?
                (psnd->recv_processed < psnd->recv_size) :
                (psnd->recv_processed == 0));
    DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
    free(psnd->buffer);
    psnd->buffer = NULL;
    psnd->allocated_size = 0;
    psnd->recv_size = 0;
    psnd->recv_processed = 0;
#ifdef DEBUGBUILD
    psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
#endif /* DEBUGBUILD */
  }
  else {
    DEBUGASSERT(psnd->allocated_size == 0);
    DEBUGASSERT(psnd->recv_size == 0);
    DEBUGASSERT(psnd->recv_processed == 0);
    DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
  }
}


static void fts_parser_script_more ( struct fts_parser * _parser , struct message_block * block ) {
 struct script_fts_parser * parser = ( struct script_fts_parser * ) _parser ;
 ssize_t ret ;
 if ( block -> size > 0 ) {
 if ( ! parser -> failed && write_full ( parser -> fd , block -> data , block -> size ) < 0 ) {
 i_error ( "write(%s) failed: %m" , parser -> path ) ;
 parser -> failed = TRUE ;
 }
 block -> size = 0 ;
 }
 else {
 if ( ! parser -> shutdown ) {
 if ( shutdown ( parser -> fd , SHUT_WR ) < 0 ) i_error ( "shutdown(%s) failed: %m" , parser -> path ) ;
 parser -> shutdown = TRUE ;
 }
 ret = read ( parser -> fd , parser -> outbuf , sizeof ( parser -> outbuf ) ) ;
 if ( ret < 0 ) i_error ( "read(%s) failed: %m" , parser -> path ) ;
 else {
 block -> data = parser -> outbuf ;
 block -> size = ret ;
 }
 }
 }


SWFShape_addBitmapFillStyle(SWFShape shape, SWFBitmap bitmap, byte flags)
{
	SWFFillStyle fill;

	if ( bitmap )
	{
		SWFCharacter_addDependency((SWFCharacter)shape,
		                           (SWFCharacter)bitmap);
	}

	fill = newSWFBitmapFillStyle(bitmap, flags);
	if(addFillStyle(shape, fill) < 0)
	{
		destroySWFFillStyle(fill);
		return NULL;
	}
	return fill;
}


const char* Track::GetCodecNameAsUTF8() const
{
    return m_info.codecNameAsUTF8;
}


void FrameView::updateWidgetPositions()
{
    WillBeHeapVector<RefPtrWillBeMember<RenderWidget> > widgets;
    copyToVector(m_widgets, widgets);

    for (size_t i = 0; i < widgets.size() && renderView(); ++i)
        widgets[i]->updateWidgetPosition();

    for (size_t i = 0; i < widgets.size() && renderView(); ++i)
        widgets[i]->widgetPositionsUpdated();
}


static void gen_exception_return(DisasContext *s, TCGv_i32 pc)

{

    TCGv_i32 tmp;

    store_reg(s, 15, pc);

    tmp = load_cpu_field(spsr);

    gen_set_cpsr(tmp, CPSR_ERET_MASK);

    tcg_temp_free_i32(tmp);

    s->is_jmp = DISAS_JUMP;

}


static MemTxResult access_with_adjusted_size(struct uc_struct *uc, hwaddr addr,
                                      uint64_t *value,
                                      unsigned size,
                                      unsigned access_size_min,
                                      unsigned access_size_max,
                                      MemTxResult (*access_fn)
                                                  (struct uc_struct *uc,
                                                   MemoryRegion *mr,
                                                   hwaddr addr,
                                                   uint64_t *value,
                                                   unsigned size,
                                                   signed shift,
                                                   uint64_t mask,
                                                   MemTxAttrs attrs),
                                      MemoryRegion *mr,
                                      MemTxAttrs attrs)
{
    uint64_t access_mask;
    unsigned access_size;
    unsigned i;
    MemTxResult r = MEMTX_OK;

    if (!access_size_min) {
        access_size_min = 1;
    }
    if (!access_size_max) {
        access_size_max = 4;
    }

    /* FIXME: support unaligned access? */
    access_size = MAX(MIN(size, access_size_max), access_size_min);
    access_mask = MAKE_64BIT_MASK(0, access_size * 8);
    if (memory_region_big_endian(mr)) {
        for (i = 0; i < size; i += access_size) {
            r |= access_fn(uc, mr, addr + i, value, access_size,
                        (size - access_size - i) * 8, access_mask, attrs);
        }
    } else {
        for (i = 0; i < size; i += access_size) {
            r |= access_fn(uc, mr, addr + i, value, access_size, i * 8,
                        access_mask, attrs);
        }
    }
    return r;
}


ref_param_begin_write_collection(gs_param_list * plist, gs_param_name pkey,
                                 gs_param_dict * pvalue,
                                 gs_param_collection_type_t coll_type)
{
    iparam_list *const iplist = (iparam_list *) plist;
    gs_ref_memory_t *imem = iplist->ref_memory;
    dict_param_list *dlist = (dict_param_list *)
        gs_alloc_bytes(plist->memory, size_of(dict_param_list),
                       "ref_param_begin_write_collection");
    int code;

    if (dlist == 0)
        return_error(gs_error_VMerror);
    if (coll_type != gs_param_collection_array) {
        ref dref;

        code = dict_alloc(imem, pvalue->size, &dref);
        if (code >= 0) {
            code = dict_param_list_write(dlist, &dref, NULL, imem);
            dlist->int_keys = coll_type == gs_param_collection_dict_int_keys;
        }
    } else {
        ref aref;

        code = gs_alloc_ref_array(imem, &aref, a_all, pvalue->size,
                                  "ref_param_begin_write_collection");
        if (code >= 0)
            code = array_new_indexed_plist_write(dlist, &aref, NULL, imem);
    }
    if (code < 0)
        gs_free_object(plist->memory, dlist, "ref_param_begin_write_collection");
    else
        pvalue->list = (gs_param_list *) dlist;
    return code;
}


static struct page *get_next_nat_page(struct f2fs_sb_info *sbi, nid_t nid)
{
	struct page *src_page;
	struct page *dst_page;
	pgoff_t src_off;
	pgoff_t dst_off;
	void *src_addr;
	void *dst_addr;
	struct f2fs_nm_info *nm_i = NM_I(sbi);

	src_off = current_nat_addr(sbi, nid);
	dst_off = next_nat_addr(sbi, src_off);

	/* get current nat block page with lock */
	src_page = get_meta_page(sbi, src_off);
	dst_page = grab_meta_page(sbi, dst_off);
	f2fs_bug_on(sbi, PageDirty(src_page));

	src_addr = page_address(src_page);
	dst_addr = page_address(dst_page);
	memcpy(dst_addr, src_addr, PAGE_SIZE);
	set_page_dirty(dst_page);
	f2fs_put_page(src_page, 1);

	set_to_next_nat(nm_i, nid);

	return dst_page;
}


mm_answer_rsa_challenge(int sock, Buffer *m)
{
	Key *key = NULL;
	u_char *blob;
	u_int blen;

	debug3("%s entering", __func__);

	if (!authctxt->valid)
		fatal("%s: authctxt not valid", __func__);
	blob = buffer_get_string(m, &blen);
	if (!monitor_allowed_key(blob, blen))
		fatal("%s: bad key, not previously allowed", __func__);
	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
		fatal("%s: key type mismatch", __func__);
	if ((key = key_from_blob(blob, blen)) == NULL)
		fatal("%s: received bad key", __func__);
	if (key->type != KEY_RSA)
		fatal("%s: received bad key type %d", __func__, key->type);
	key->type = KEY_RSA1;
	if (ssh1_challenge)
		BN_clear_free(ssh1_challenge);
	ssh1_challenge = auth_rsa_generate_challenge(key);

	buffer_clear(m);
	buffer_put_bignum2(m, ssh1_challenge);

	debug3("%s sending reply", __func__);
	mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);

	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);

	free(blob);
	key_free(key);
	return (0);
}