GF_Err gf_isom_set_cts_packing(GF_ISOFile *the_file, u32 trackNumber, Bool unpack)
{
	GF_Err e;
	GF_Err stbl_repackCTS(GF_CompositionOffsetBox *ctts);
	GF_Err stbl_unpackCTS(GF_SampleTableBox *stbl);
	GF_SampleTableBox *stbl;

	GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, trackNumber);
	if (!trak) return GF_BAD_PARAM;

	stbl = trak->Media->information->sampleTable;
	if (unpack) {
		if (!stbl->CompositionOffset) {
			stbl->CompositionOffset = (GF_CompositionOffsetBox *) gf_isom_box_new_parent(&stbl->child_boxes, GF_ISOM_BOX_TYPE_CTTS);
			if (!stbl->CompositionOffset) return GF_OUT_OF_MEM;
		}
		e = stbl_unpackCTS(stbl);
	} else {
		if (!stbl->CompositionOffset) return GF_OK;
		e = stbl_repackCTS(stbl->CompositionOffset);
	}
	if (e) return e;
	return SetTrackDuration(trak);
}


static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  sqlite3DbFreeNN(db, p);
}


file_cleanup(void)
{
  size_t	i;			/* Looping var */
  char		filename[1024];		/* Temporary file */
  struct stat	fileinfo;		/* File information */
  size_t	remotebytes;		/* Size of remote data */
  const char	*tmpdir;		/* Temporary directory */
#ifdef WIN32
  char		tmppath[1024];		/* Temporary directory */
#endif /* WIN32 */
  const char	*debug;			/* HTMLDOC_DEBUG env var */

  if (http)
  {
    httpClose(http);
    http = NULL;
  }

#ifdef WIN32
  if ((tmpdir = getenv("TEMP")) == NULL)
  {
    GetTempPath(sizeof(tmppath), tmppath);
    tmpdir = tmppath;
  }
#else
  if ((tmpdir = getenv("TMPDIR")) == NULL)
    tmpdir = "/var/tmp";
#endif /* WIN32 */

 /*
  * Report on the remote data bytes that were downloaded...
  */

  debug = getenv("HTMLDOC_DEBUG");

  if (debug &&
      (strstr(debug, "all") != NULL || strstr(debug, "remotebytes") != NULL))
  {
    for (i = 0, remotebytes = 0; i < web_files; i ++)
      if (web_cache[i].url)
      {
	snprintf(filename, sizeof(filename), TEMPLATE, tmpdir, (long)getpid(), (int)(i + 1));
        if (!stat(filename, &fileinfo))
	  remotebytes += (size_t)fileinfo.st_size;
      }

    progress_error(HD_ERROR_NONE, "REMOTEBYTES: %ld", (long)remotebytes);
  }

 /*
  * Check to see if we want to leave the temporary files around for
  * debugging...
  */

  if (debug &&
      (strstr(debug, "all") != NULL || strstr(debug, "tempfiles") != NULL))
  {
   /*
    * Yes, leave the files, but show the mapping from filename to URL...
    */

    progress_error(HD_ERROR_NONE, "DEBUG: Temporary File Summary");
    progress_error(HD_ERROR_NONE, "DEBUG:");
    progress_error(HD_ERROR_NONE, "DEBUG: URL                             Filename");
    progress_error(HD_ERROR_NONE, "DEBUG: ------------------------------- ---------------------");

    for (i = 0; i < web_files; i ++)
    {
      snprintf(filename, sizeof(filename), TEMPLATE, tmpdir, (long)getpid(), (int)(i + 1));
      progress_error(HD_ERROR_NONE, "DEBUG: %-31.31s %s\n", web_cache[i].url ? web_cache[i].url : "none", filename);
    }

    progress_error(HD_ERROR_NONE, "DEBUG:");

    return;
  }

  while (web_files > 0)
  {
    snprintf(filename, sizeof(filename), TEMPLATE, tmpdir, (long)getpid(), (int)web_files);

    if (unlink(filename))
      progress_error(HD_ERROR_DELETE_ERROR,
                     "Unable to delete temporary file \"%s\": %s",
                     filename, strerror(errno));

    web_files --;

    if (web_cache[web_files].name)
      free(web_cache[web_files].name);
    if (web_cache[web_files].url)
      free(web_cache[web_files].url);
  }

  if (web_alloc)
  {
    free(web_cache);

    web_alloc = 0;
    web_cache = NULL;
  }
}


ofproto_get_ipfix_stats(struct ofproto *ofproto,
                        bool bridge_ipfix,
                        struct ovs_list *replies)
{
    int error;

    if (ofproto->ofproto_class->get_ipfix_stats) {
        error = ofproto->ofproto_class->get_ipfix_stats(ofproto,
                                                          bridge_ipfix,
                                                          replies);
    } else {
        error = EOPNOTSUPP;
    }

    return error;
}


bind_socket(struct TCP_Server_Info *server)
{
	int rc = 0;
	if (server->srcaddr.ss_family != AF_UNSPEC) {
		/* Bind to the specified local IP address */
		struct socket *socket = server->ssocket;
		rc = socket->ops->bind(socket,
				       (struct sockaddr *) &server->srcaddr,
				       sizeof(server->srcaddr));
		if (rc < 0) {
			struct sockaddr_in *saddr4;
			struct sockaddr_in6 *saddr6;
			saddr4 = (struct sockaddr_in *)&server->srcaddr;
			saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
			if (saddr6->sin6_family == AF_INET6)
				cifs_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
					 &saddr6->sin6_addr, rc);
			else
				cifs_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
					 &saddr4->sin_addr.s_addr, rc);
		}
	}
	return rc;
}


int do_execve(const char *filename,
	const char __user *const __user *__argv,
	const char __user *const __user *__envp)
{
	struct user_arg_ptr argv = { .ptr.native = __argv };
	struct user_arg_ptr envp = { .ptr.native = __envp };
	return do_execve_common(filename, argv, envp);
}


static void longAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
    TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
    TestObjectV8Internal::longAttrAttributeSetter(jsValue, info);
    TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}


static void _slurm_rpc_delete_partition ( slurm_msg_t * msg ) {
 int error_code = SLURM_SUCCESS ;
 DEF_TIMERS ;
 delete_part_msg_t * part_desc_ptr = ( delete_part_msg_t * ) msg -> data ;
 slurmctld_lock_t part_write_lock = {
 NO_LOCK , WRITE_LOCK , READ_LOCK , WRITE_LOCK , NO_LOCK }
 ;
 uid_t uid = g_slurm_auth_get_uid ( msg -> auth_cred , slurmctld_config . auth_info ) ;
 START_TIMER ;
 debug2 ( "Processing RPC: REQUEST_DELETE_PARTITION from uid=%d" , uid ) ;
 if ( ! validate_super_user ( uid ) ) {
 error_code = ESLURM_USER_ID_MISSING ;
 error ( "Security violation, DELETE_PARTITION RPC from uid=%d" , uid ) ;
 }
 if ( error_code == SLURM_SUCCESS ) {
 lock_slurmctld ( part_write_lock ) ;
 error_code = delete_partition ( part_desc_ptr ) ;
 unlock_slurmctld ( part_write_lock ) ;
 END_TIMER2 ( "_slurm_rpc_delete_partition" ) ;
 }
 if ( error_code ) {
 info ( "_slurm_rpc_delete_partition partition=%s: %s" , part_desc_ptr -> name , slurm_strerror ( error_code ) ) ;
 slurm_send_rc_msg ( msg , error_code ) ;
 }
 else {
 info ( "_slurm_rpc_delete_partition complete for %s %s" , part_desc_ptr -> name , TIME_STR ) ;
 slurm_send_rc_msg ( msg , SLURM_SUCCESS ) ;
 save_all_state ( ) ;
 queue_job_scheduler ( ) ;
 }
 }


    virtual void beginCommitOnCCThread(CCLayerTreeHostImpl* impl)
    {
        LayerChromium* root = m_layerTreeHost->rootLayer();
        if (!m_layerTreeHost->frameNumber())
            EXPECT_EQ(root->scrollPosition(), m_initialScroll);
        else if (m_layerTreeHost->frameNumber() == 1)
            EXPECT_EQ(root->scrollPosition(), m_initialScroll + m_scrollAmount + m_scrollAmount);
        else if (m_layerTreeHost->frameNumber() == 2)
            EXPECT_EQ(root->scrollPosition(), m_initialScroll + m_scrollAmount + m_scrollAmount);
    }


static void LocationByteStringAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Local<v8::Object> holder = info.Holder();

  TestObject* impl = V8TestObject::ToImpl(holder);

  V8SetReturnValueFast(info, WTF::GetPtr(impl->locationByteString()), impl);
}


VP8XChunk::VP8XChunk(Container* parent)
  : Chunk(parent, kChunk_VP8X)
{
    this->needsRewrite = true;
    this->size = 10;
    this->data.resize(this->size);
     this->data.assign(this->size, 0);
     XMP_Uns8* bitstream =
         (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data();
    XMP_Uns32 width = ((bitstream[7] << 8) | bitstream[6]) & 0x3fff;
    XMP_Uns32 height = ((bitstream[9] << 8) | bitstream[8]) & 0x3fff;
     this->width(width);
     this->height(height);
     parent->vp8x = this;
VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler)
  : Chunk(parent, handler)
{
    this->size = 10;
    this->needsRewrite = true;
    parent->vp8x = this;
}

XMP_Uns32 VP8XChunk::width()
{
    return GetLE24(&this->data[4]) + 1;
}
void VP8XChunk::width(XMP_Uns32 val)
{
    PutLE24(&this->data[4], val > 0 ? val - 1 : 0);
}
XMP_Uns32 VP8XChunk::height()
{
    return GetLE24(&this->data[7]) + 1;
}
void VP8XChunk::height(XMP_Uns32 val)
{
    PutLE24(&this->data[7], val > 0 ? val - 1 : 0);
}
bool VP8XChunk::xmp()
{
    XMP_Uns32 flags = GetLE32(&this->data[0]);
    return (bool)((flags >> XMP_FLAG_BIT) & 1);
}
void VP8XChunk::xmp(bool hasXMP)
{
    XMP_Uns32 flags = GetLE32(&this->data[0]);
    flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT);
    PutLE32(&this->data[0], flags);
}

Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler)
{
    this->needsRewrite = false;

    XMP_IO* file = handler->parent->ioRef;

    file->Seek(12, kXMP_SeekFromStart);

    XMP_Int64 size = handler->initialFileSize;

    XMP_Uns32 peek = 0;

    while (file->Offset() < size) {
        peek = XIO::PeekUns32_LE(file);
        switch (peek) {
        case kChunk_XMP_:
            this->addChunk(new XMPChunk(this, handler));
            break;
        case kChunk_VP8X:
            this->addChunk(new VP8XChunk(this, handler));
            break;
        default:
            this->addChunk(new Chunk(this, handler));
            break;
        }
    }

    if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) {
        XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat);
    }

    if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) {
        this->needsRewrite = true;
        this->addChunk(new VP8XChunk(this));
    }

    if (this->chunks[WEBP_CHUNK_XMP].size() == 0) {
        XMPChunk* xmpChunk = new XMPChunk(this);
        this->addChunk(xmpChunk);
        handler->xmpChunk = xmpChunk;
        this->vp8x->xmp(true);
    }
}

Chunk* Container::getExifChunk()
{
    if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) {
        return NULL;
    }
    return this->chunks[WEBP::WEBP_CHUNK_EXIF][0];
}

void Container::addChunk(Chunk* chunk)
{
    ChunkId idx;

    try {
        idx = chunkMap.at(chunk->tag);
    }
    catch (const std::out_of_range& e) {
        idx = WEBP_CHUNK_UNKNOWN;
    }
    this->chunks[idx].push_back(chunk);
}

void Container::write(WEBP_MetaHandler* handler)
{
    XMP_IO* file = handler->parent->ioRef;
    file->Rewind();
    XIO::WriteUns32_LE(file, this->tag);
    XIO::WriteUns32_LE(file, (XMP_Uns32) this->size);
    XIO::WriteUns32_LE(file, kChunk_WEBP);

    size_t i, j;
    std::vector<Chunk*> chunkVect;
    for (i = 0; i < WEBP_CHUNK_NIL; i++) {
        chunkVect = this->chunks[i];
        for (j = 0; j < chunkVect.size(); j++) {
            chunkVect.at(j)->write(handler);
        }
    }
    XMP_Int64 lastOffset = file->Offset();
    this->size = lastOffset - 8;
    file->Seek(this->pos + 4, kXMP_SeekFromStart);
    XIO::WriteUns32_LE(file, (XMP_Uns32) this->size);
    file->Seek(lastOffset, kXMP_SeekFromStart);
    if (lastOffset < handler->initialFileSize) {
        file->Truncate(lastOffset);
    }
}

Container::~Container()
{
    Chunk* chunk;
    size_t i;
    std::vector<Chunk*> chunkVect;
    for (i = 0; i < WEBP_CHUNK_NIL; i++) {
        chunkVect = this->chunks[i];
        while (!chunkVect.empty()) {
            chunk = chunkVect.back();
            delete chunk;
            chunkVect.pop_back();
        }
    }
}
}


void btrfs_dev_replace_suspend_for_unmount(struct btrfs_fs_info *fs_info)
{
	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;

	mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
	down_write(&dev_replace->rwsem);

	switch (dev_replace->replace_state) {
	case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
	case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
	case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
	case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
		break;
	case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
		dev_replace->replace_state =
			BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
		dev_replace->time_stopped = ktime_get_real_seconds();
		dev_replace->item_needs_writeback = 1;
		btrfs_info(fs_info, "suspending dev_replace for unmount");
		break;
	}

	up_write(&dev_replace->rwsem);
	mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
}


int mgs_hook_pre_config ( apr_pool_t * pconf , apr_pool_t * plog , apr_pool_t * ptemp __attribute__ ( ( unused ) ) ) {
 # if MOD_GNUTLS_DEBUG apr_file_open ( & debug_log_fp , "/tmp/gnutls_debug" , APR_APPEND | APR_WRITE | APR_CREATE , APR_OS_DEFAULT , pconf ) ;
 _gnutls_log ( debug_log_fp , "%s: %d\n" , __func__ , __LINE__ ) ;
 gnutls_global_set_log_level ( 9 ) ;
 gnutls_global_set_log_function ( gnutls_debug_log_all ) ;
 _gnutls_log ( debug_log_fp , "gnutls: %s\n" , gnutls_check_version ( NULL ) ) ;
 # endif int ret ;
 if ( gnutls_check_version ( LIBGNUTLS_VERSION ) == NULL ) {
 ap_log_perror ( APLOG_MARK , APLOG_EMERG , 0 , plog , "gnutls_check_version() failed. Required: " "gnutls-%s Found: gnutls-%s" , LIBGNUTLS_VERSION , gnutls_check_version ( NULL ) ) ;
 return DONE ;
 }
 ret = gnutls_global_init ( ) ;
 if ( ret < 0 ) {
 ap_log_perror ( APLOG_MARK , APLOG_EMERG , 0 , plog , "gnutls_global_init: %s" , gnutls_strerror ( ret ) ) ;
 return DONE ;
 }
 ret = gnutls_session_ticket_key_generate ( & session_ticket_key ) ;
 if ( ret < 0 ) {
 ap_log_perror ( APLOG_MARK , APLOG_EMERG , 0 , plog , "gnutls_session_ticket_key_generate: %s" , gnutls_strerror ( ret ) ) ;
 return DONE ;
 }
 AP_OPTIONAL_HOOK ( status_hook , mgs_status_hook , NULL , NULL , APR_HOOK_MIDDLE ) ;
 apr_pool_cleanup_register ( pconf , NULL , mgs_cleanup_pre_config , apr_pool_cleanup_null ) ;
 return OK ;
 }


void AccessibilityUIElement::setSelectedTextRange(unsigned location, unsigned length)
{
}


SeekHead::~SeekHead()
{
    delete[] m_entries;
    delete[] m_void_elements;
 }


static void __exit cleanup_ipmi(void)
{
	int count;

	if (initialized) {
		atomic_notifier_chain_unregister(&panic_notifier_list,
						 &panic_block);

		/*
		 * This can't be called if any interfaces exist, so no worry
		 * about shutting down the interfaces.
		 */

		/*
		 * Tell the timer to stop, then wait for it to stop.  This
		 * avoids problems with race conditions removing the timer
		 * here.
		 */
		atomic_set(&stop_operation, 1);
		del_timer_sync(&ipmi_timer);

		initialized = false;

		/* Check for buffer leaks. */
		count = atomic_read(&smi_msg_inuse_count);
		if (count != 0)
			pr_warn("SMI message count %d at exit\n", count);
		count = atomic_read(&recv_msg_inuse_count);
		if (count != 0)
			pr_warn("recv message count %d at exit\n", count);

		cleanup_srcu_struct(&ipmi_interfaces_srcu);
	}
	if (drvregistered)
		driver_unregister(&ipmidriver.driver);
}


foreach_item_helper (GHashTable *hash,
                     NMVPNIterFunc func,
                     gpointer user_data)
{
	GList *keys, *liter;
	GSList *copied = NULL, *siter;

	g_return_if_fail (hash != NULL);

	/* Grab keys and copy them so that the callback func can modify
	 * the hash table items if it wants to.
	 */
	keys = g_hash_table_get_keys (hash);
	for (liter = keys; liter; liter = g_list_next (liter))
		copied = g_slist_prepend (copied, g_strdup (liter->data));
	copied = g_slist_reverse (copied);
	g_list_free (keys);

	for (siter = copied; siter; siter = g_slist_next (siter)) {
		gpointer value;

		value = g_hash_table_lookup (hash, siter->data);
		func (siter->data, value, user_data);
	}

	g_slist_foreach (copied, (GFunc) g_free, NULL);
	g_slist_free (copied);
}


void MediaRecorder::DispatchScheduledEvent() {
  HeapVector<Member<Event>> events;
  events.swap(scheduled_events_);

  for (const auto& event : events)
    DispatchEvent(*event);
}


valid_yank_reg(
    int	    regname,
    int	    writing)	    // if TRUE check for writable registers
{
    if (       (regname > 0 && ASCII_ISALNUM(regname))
	    || (!writing && vim_strchr((char_u *)
#ifdef FEAT_EVAL
				    "/.%:="
#else
				    "/.%:"
#endif
					, regname) != NULL)
	    || regname == '#'
	    || regname == '"'
	    || regname == '-'
	    || regname == '_'
#ifdef FEAT_CLIPBOARD
	    || regname == '*'
	    || regname == '+'
#endif
#ifdef FEAT_DND
	    || (!writing && regname == '~')
#endif
							)
	return TRUE;
    return FALSE;
}


mkvparser::IMkvReader::~IMkvReader()
#ifdef _MSC_VER
//// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif

mkvparser::IMkvReader::~IMkvReader() {}

void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) {
  major = 1;
  minor = 0;
  build = 0;
  revision = 28;
 }


static void set_name_file(pid_t pid) {
	char *fname;
	if (asprintf(&fname, "%s/%d", RUN_FIREJAIL_NAME_DIR, pid) == -1)
		errExit("asprintf");

	FILE *fp = fopen(fname, "w");
	if (!fp) {
		fprintf(stderr, "Error: cannot create %s\n", fname);
		exit(1);
	}
	fprintf(fp, "%s\n", cfg.name);

	SET_PERMS_STREAM(fp, 0, 0, 0644);
	fclose(fp);
}


int __save_altstack(stack_t __user *uss, unsigned long sp)
{
	struct task_struct *t = current;
	int err = __put_user((void __user *)t->sas_ss_sp, &uss->ss_sp) |
		__put_user(t->sas_ss_flags, &uss->ss_flags) |
		__put_user(t->sas_ss_size, &uss->ss_size);
	if (err)
		return err;
	if (t->sas_ss_flags & SS_AUTODISARM)
		sas_ss_reset(t);
	return 0;
}


load(ImlibImage * im, ImlibProgressFunction progress,
     char progress_granularity, char immediate_load)
{
   int                 rc;
   char                p = ' ', numbers = 3, count = 0;
   int                 w = 0, h = 0, v = 255, c = 0;
   char                buf[256];
   FILE               *f = NULL;

   if (im->data)
      return 0;
   f = fopen(im->real_file, "rb");
   if (!f)
      return 0;

   /* can't use fgets(), because there might be
    * binary data after the header and there
    * needn't be a newline before the data, so
    * no chance to distinguish between end of buffer
    * and a binary 0.
    */

   /* read the header info */

   rc = 0;                      /* Error */

   c = fgetc(f);
   if (c != 'P')
      goto quit;

   p = fgetc(f);
   if (p == '1' || p == '4')
      numbers = 2;              /* bitimages don't have max value */

   if ((p < '1') || (p > '8'))
      goto quit;

   count = 0;
   while (count < numbers)
     {
        c = fgetc(f);

        if (c == EOF)
           goto quit;

        /* eat whitespace */
        while (isspace(c))
           c = fgetc(f);
        /* if comment, eat that */
        if (c == '#')
          {
             do
                c = fgetc(f);
             while (c != '\n' && c != EOF);
          }
        /* no comment -> proceed */
        else
          {
             int                 i = 0;

             /* read numbers */
             while (c != EOF && !isspace(c) && (i < 255))
               {
                  buf[i++] = c;
                  c = fgetc(f);
               }
             if (i)
               {
                  buf[i] = 0;
                  count++;
                  switch (count)
                    {
                       /* width */
                    case 1:
                       w = atoi(buf);
                       break;
                       /* height */
                    case 2:
                       h = atoi(buf);
                       break;
                       /* max value, only for color and greyscale */
                    case 3:
                       v = atoi(buf);
                       break;
                    }
               }
          }
     }
   if ((v < 0) || (v > 255))
      goto quit;

   im->w = w;
   im->h = h;
   if (!IMAGE_DIMENSIONS_OK(w, h))
      goto quit;

   if (!im->format)
     {
        if (p == '8')
           SET_FLAG(im->flags, F_HAS_ALPHA);
        else
           UNSET_FLAG(im->flags, F_HAS_ALPHA);
        im->format = strdup("pnm");
     }

   rc = 1;                      /* Ok */

   if (((!im->data) && (im->loader)) || (immediate_load) || (progress))
     {
        DATA8              *data = NULL;        /* for the binary versions */
        DATA8              *ptr = NULL;
        int                *idata = NULL;       /* for the ASCII versions */
        int                *iptr;
        char                buf2[256];
        DATA32             *ptr2;
        int                 i, j, x, y, pl = 0;
        char                pper = 0;

        /* must set the im->data member before callign progress function */
        ptr2 = im->data = malloc(w * h * sizeof(DATA32));
        if (!im->data)
           goto quit_error;

        /* start reading the data */
        switch (p)
          {
          case '1':            /* ASCII monochrome */
             buf[0] = 0;
             i = 0;
             for (y = 0; y < h; y++)
               {
                  x = 0;
                  while (x < w)
                    {
                       if (!buf[i])     /* fill buffer */
                         {
                            if (!fgets(buf, 255, f))
                               goto quit_error;
                            i = 0;
                         }
                       while (buf[i] && isspace(buf[i]))
                          i++;
                       if (buf[i])
                         {
                            if (buf[i] == '1')
                               *ptr2 = 0xff000000;
                            else if (buf[i] == '0')
                               *ptr2 = 0xffffffff;
                            else
                               goto quit_error;
                            ptr2++;
                            i++;
                         }
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '2':            /* ASCII greyscale */
             idata = malloc(sizeof(int) * w);
             if (!idata)
                goto quit_error;

             buf[0] = 0;
             i = 0;
             j = 0;
             for (y = 0; y < h; y++)
               {
                  iptr = idata;
                  x = 0;
                  while (x < w)
                    {
                       int                 k;

                       /* check 4 chars ahead to see if we need to
                        * fill the buffer */
                       for (k = 0; k < 4; k++)
                         {
                            if (!buf[i + k])    /* fill buffer */
                              {
                                 if (fseek(f, -k, SEEK_CUR) == -1 ||
                                     !fgets(buf, 255, f))
                                    goto quit_error;
                                 i = 0;
                                 break;
                              }
                         }
                       while (buf[i] && isspace(buf[i]))
                          i++;
                       while (buf[i] && !isspace(buf[i]))
                          buf2[j++] = buf[i++];
                       if (j)
                         {
                            buf2[j] = 0;
                            *(iptr++) = atoi(buf2);
                            j = 0;
                            x++;
                          }
                     }
                   iptr = idata;
                  if (v == 0 || v == 255)
                     {
                        for (x = 0; x < w; x++)
                          {
                            *ptr2 =
                               0xff000000 | (iptr[0] << 16) | (iptr[0] << 8)
                               | iptr[0];
                            ptr2++;
                            iptr++;
                         }
                    }
                  else
                    {
                       for (x = 0; x < w; x++)
                         {
                            *ptr2 =
                               0xff000000 |
                               (((iptr[0] * 255) / v) << 16) |
                               (((iptr[0] * 255) / v) << 8) |
                               ((iptr[0] * 255) / v);
                            ptr2++;
                            iptr++;
                         }
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '3':            /* ASCII RGB */
             idata = malloc(3 * sizeof(int) * w);
             if (!idata)
                goto quit_error;

             buf[0] = 0;
             i = 0;
             j = 0;
             for (y = 0; y < h; y++)
               {
                  int                 w3 = 3 * w;

                  iptr = idata;
                  x = 0;
                  while (x < w3)
                    {
                       int                 k;

                       /* check 4 chars ahead to see if we need to
                        * fill the buffer */
                       for (k = 0; k < 4; k++)
                         {
                            if (!buf[i + k])    /* fill buffer */
                              {
                                 if (fseek(f, -k, SEEK_CUR) == -1 ||
                                     !fgets(buf, 255, f))
                                    goto quit_error;
                                 i = 0;
                                 break;
                              }
                         }
                       while (buf[i] && isspace(buf[i]))
                          i++;
                       while (buf[i] && !isspace(buf[i]))
                          buf2[j++] = buf[i++];
                       if (j)
                         {
                            buf2[j] = 0;
                            *(iptr++) = atoi(buf2);
                            j = 0;
                            x++;
                          }
                     }
                   iptr = idata;
                  if (v == 0 || v == 255)
                     {
                        for (x = 0; x < w; x++)
                          {
                            *ptr2 =
                               0xff000000 | (iptr[0] << 16) | (iptr[1] << 8)
                               | iptr[2];
                            ptr2++;
                            iptr += 3;
                         }
                    }
                  else
                    {
                       for (x = 0; x < w; x++)
                         {
                            *ptr2 =
                               0xff000000 |
                               (((iptr[0] * 255) / v) << 16) |
                               (((iptr[1] * 255) / v) << 8) |
                               ((iptr[2] * 255) / v);
                            ptr2++;
                            iptr += 3;
                         }
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '4':            /* binary 1bit monochrome */
             data = malloc((w + 7) / 8 * sizeof(DATA8));
             if (!data)
                goto quit_error;

             ptr2 = im->data;
             for (y = 0; y < h; y++)
               {
                  if (!fread(data, (w + 7) / 8, 1, f))
                     goto quit_error;

                  ptr = data;
                  for (x = 0; x < w; x += 8)
                    {
                       j = (w - x >= 8) ? 8 : w - x;
                       for (i = 0; i < j; i++)
                         {
                            if (ptr[0] & (0x80 >> i))
                               *ptr2 = 0xff000000;
                            else
                               *ptr2 = 0xffffffff;
                            ptr2++;
                         }
                       ptr++;
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '5':            /* binary 8bit grayscale GGGGGGGG */
             data = malloc(1 * sizeof(DATA8) * w);
             if (!data)
                goto quit_error;

             ptr2 = im->data;
             for (y = 0; y < h; y++)
               {
                  if (!fread(data, w * 1, 1, f))
                      break;

                   ptr = data;
                  if (v == 0 || v == 255)
                     {
                        for (x = 0; x < w; x++)
                          {
                            *ptr2 =
                               0xff000000 | (ptr[0] << 16) | (ptr[0] << 8) |
                               ptr[0];
                            ptr2++;
                            ptr++;
                         }
                    }
                  else
                    {
                       for (x = 0; x < w; x++)
                         {
                            *ptr2 =
                               0xff000000 |
                               (((ptr[0] * 255) / v) << 16) |
                               (((ptr[0] * 255) / v) << 8) |
                               ((ptr[0] * 255) / v);
                            ptr2++;
                            ptr++;
                         }
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '6':            /* 24bit binary RGBRGBRGB */
             data = malloc(3 * sizeof(DATA8) * w);
             if (!data)
                goto quit_error;

             ptr2 = im->data;
             for (y = 0; y < h; y++)
               {
                  if (!fread(data, w * 3, 1, f))
                      break;

                   ptr = data;
                  if (v == 0 || v == 255)
                     {
                        for (x = 0; x < w; x++)
                          {
                            *ptr2 =
                               0xff000000 | (ptr[0] << 16) | (ptr[1] << 8) |
                               ptr[2];
                            ptr2++;
                            ptr += 3;
                         }
                    }
                  else
                    {
                       for (x = 0; x < w; x++)
                         {
                            *ptr2 =
                               0xff000000 |
                               (((ptr[0] * 255) / v) << 16) |
                               (((ptr[1] * 255) / v) << 8) |
                               ((ptr[2] * 255) / v);
                            ptr2++;
                            ptr += 3;
                         }
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '7':            /* XV's 8bit 332 format */
             data = malloc(1 * sizeof(DATA8) * w);
             if (!data)
                goto quit_error;

             ptr2 = im->data;
             for (y = 0; y < h; y++)
               {
                  if (!fread(data, w * 1, 1, f))
                     break;

                  ptr = data;
                  for (x = 0; x < w; x++)
                    {
                       int                 r, g, b;

                       r = (*ptr >> 5) & 0x7;
                       g = (*ptr >> 2) & 0x7;
                       b = (*ptr) & 0x3;
                       *ptr2 =
                          0xff000000 |
                          (((r << 21) | (r << 18) | (r << 15)) & 0xff0000) |
                          (((g << 13) | (g << 10) | (g << 7)) & 0xff00) |
                          ((b << 6) | (b << 4) | (b << 2) | (b << 0));
                       ptr2++;
                       ptr++;
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          case '8':            /* 24bit binary RGBARGBARGBA */
             data = malloc(4 * sizeof(DATA8) * w);
             if (!data)
                goto quit_error;

             ptr2 = im->data;
             for (y = 0; y < h; y++)
               {
                  if (!fread(data, w * 4, 1, f))
                      break;

                   ptr = data;
                  if (v == 0 || v == 255)
                     {
                        for (x = 0; x < w; x++)
                          {
                            *ptr2 =
                               (ptr[3] << 24) | (ptr[0] << 16) |
                               (ptr[1] << 8) | ptr[2];
                            ptr2++;
                            ptr += 4;
                         }
                    }
                  else
                    {
                       for (x = 0; x < w; x++)
                         {
                            *ptr2 =
                               (((ptr[3] * 255) / v) << 24) |
                               (((ptr[0] * 255) / v) << 16) |
                               (((ptr[1] * 255) / v) << 8) |
                               ((ptr[2] * 255) / v);
                            ptr2++;
                            ptr += 4;
                         }
                    }
                  if (progress &&
                      do_progress(im, progress, progress_granularity,
                                  &pper, &pl, y))
                     goto quit_progress;
               }
             break;
          default:
           quit_error:
             rc = 0;
             break;
           quit_progress:
             rc = 2;
             break;
          }
        if (idata)
           free(idata);
        if (data)
           free(data);
     }
 quit:
   fclose(f);
   return rc;
}


struct ib_mr *bnxt_re_alloc_mr(struct ib_pd *ib_pd, enum ib_mr_type type,
			       u32 max_num_sg, struct ib_udata *udata)
{
	struct bnxt_re_pd *pd = container_of(ib_pd, struct bnxt_re_pd, ib_pd);
	struct bnxt_re_dev *rdev = pd->rdev;
	struct bnxt_re_mr *mr = NULL;
	int rc;

	if (type != IB_MR_TYPE_MEM_REG) {
		dev_dbg(rdev_to_dev(rdev), "MR type 0x%x not supported", type);
		return ERR_PTR(-EINVAL);
	}
	if (max_num_sg > MAX_PBL_LVL_1_PGS)
		return ERR_PTR(-EINVAL);

	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
	if (!mr)
		return ERR_PTR(-ENOMEM);

	mr->rdev = rdev;
	mr->qplib_mr.pd = &pd->qplib_pd;
	mr->qplib_mr.flags = BNXT_QPLIB_FR_PMR;
	mr->qplib_mr.type = CMDQ_ALLOCATE_MRW_MRW_FLAGS_PMR;

	rc = bnxt_qplib_alloc_mrw(&rdev->qplib_res, &mr->qplib_mr);
	if (rc)
		goto bail;

	mr->ib_mr.lkey = mr->qplib_mr.lkey;
	mr->ib_mr.rkey = mr->ib_mr.lkey;

	mr->pages = kcalloc(max_num_sg, sizeof(u64), GFP_KERNEL);
	if (!mr->pages) {
		rc = -ENOMEM;
		goto fail;
	}
	rc = bnxt_qplib_alloc_fast_reg_page_list(&rdev->qplib_res,
						 &mr->qplib_frpl, max_num_sg);
	if (rc) {
		dev_err(rdev_to_dev(rdev),
			"Failed to allocate HW FR page list");
		goto fail_mr;
	}

	atomic_inc(&rdev->mr_count);
	return &mr->ib_mr;

fail_mr:
	kfree(mr->pages);
fail:
	bnxt_qplib_free_mrw(&rdev->qplib_res, &mr->qplib_mr);
bail:
	kfree(mr);
	return ERR_PTR(rc);
}


static inline void gen_intermediate_code_internal(OpenRISCCPU *cpu,

                                                  TranslationBlock *tb,

                                                  int search_pc)

{

    struct DisasContext ctx, *dc = &ctx;

    uint16_t *gen_opc_end;

    uint32_t pc_start;

    int j, k;

    uint32_t next_page_start;

    int num_insns;

    int max_insns;

    qemu_log_try_set_file(stderr);

    pc_start = tb->pc;

    dc->tb = tb;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    dc->ppc = pc_start;

    dc->pc = pc_start;

    dc->flags = cpu->env.cpucfgr;

    dc->mem_idx = cpu_mmu_index(&cpu->env);

    dc->synced_flags = dc->tb_flags = tb->flags;

    dc->delayed_branch = !!(dc->tb_flags & D_FLAG);

    dc->singlestep_enabled = cpu->env.singlestep_enabled;

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("-----------------------------------------\n");

        log_cpu_state(&cpu->env, 0);

    }

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    k = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    gen_icount_start();

    do {

        check_breakpoint(cpu, dc);

        if (search_pc) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (k < j) {

                k++;

                while (k < j) {

                    tcg_ctx.gen_opc_instr_start[k++] = 0;

                }

            }

            tcg_ctx.gen_opc_pc[k] = dc->pc;

            tcg_ctx.gen_opc_instr_start[k] = 1;

            tcg_ctx.gen_opc_icount[k] = num_insns;

        }

        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) {

            tcg_gen_debug_insn_start(dc->pc);

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        dc->ppc = dc->pc - 4;

        dc->npc = dc->pc + 4;

        tcg_gen_movi_tl(cpu_ppc, dc->ppc);

        tcg_gen_movi_tl(cpu_npc, dc->npc);

        disas_openrisc_insn(dc, cpu);

        dc->pc = dc->npc;

        num_insns++;

        /* delay slot */

        if (dc->delayed_branch) {

            dc->delayed_branch--;

            if (!dc->delayed_branch) {

                dc->tb_flags &= ~D_FLAG;

                gen_sync_flags(dc);

                tcg_gen_mov_tl(cpu_pc, jmp_pc);

                tcg_gen_mov_tl(cpu_npc, jmp_pc);

                tcg_gen_movi_tl(jmp_pc, 0);

                tcg_gen_exit_tb(0);

                dc->is_jmp = DISAS_JUMP;

                break;

            }

        }

    } while (!dc->is_jmp

             && tcg_ctx.gen_opc_ptr < gen_opc_end

             && !cpu->env.singlestep_enabled

             && !singlestep

             && (dc->pc < next_page_start)

             && num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        gen_io_end();

    }

    if (dc->is_jmp == DISAS_NEXT) {

        dc->is_jmp = DISAS_UPDATE;

        tcg_gen_movi_tl(cpu_pc, dc->pc);

    }

    if (unlikely(cpu->env.singlestep_enabled)) {

        if (dc->is_jmp == DISAS_NEXT) {

            tcg_gen_movi_tl(cpu_pc, dc->pc);

        }

        gen_exception(dc, EXCP_DEBUG);

    } else {

        switch (dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 0, dc->pc);

            break;

        default:

        case DISAS_JUMP:

            break;

        case DISAS_UPDATE:

            /* indicate that the hash table must be used

               to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        }

    }

    gen_icount_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        k++;

        while (k <= j) {

            tcg_ctx.gen_opc_instr_start[k++] = 0;

        }

    } else {

        tb->size = dc->pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("\n");

        log_target_disas(&cpu->env, pc_start, dc->pc - pc_start, 0);

        qemu_log("\nisize=%d osize=%td\n",

            dc->pc - pc_start, tcg_ctx.gen_opc_ptr -

            tcg_ctx.gen_opc_buf);

    }

#endif

}


static inline bool page_is_guard(struct page *page) { return false; }


void NetworkHandler::ContinueInterceptedRequest(
    const std::string& interception_id,
    Maybe<std::string> error_reason,
    Maybe<std::string> base64_raw_response,
    Maybe<std::string> url,
    Maybe<std::string> method,
    Maybe<std::string> post_data,
    Maybe<protocol::Network::Headers> headers,
     Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
     std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
   DevToolsInterceptorController* interceptor =
      DevToolsInterceptorController::FromBrowserContext(
          process_->GetBrowserContext());
   if (!interceptor) {
     callback->sendFailure(Response::InternalError());
     return;
  }

  base::Optional<std::string> raw_response;
  if (base64_raw_response.isJust()) {
    std::string decoded;
    if (!base::Base64Decode(base64_raw_response.fromJust(), &decoded)) {
      callback->sendFailure(Response::InvalidParams("Invalid rawResponse."));
      return;
    }
    raw_response = decoded;
  }

  base::Optional<net::Error> error;
  bool mark_as_canceled = false;
  if (error_reason.isJust()) {
    bool ok;
    error = NetErrorFromString(error_reason.fromJust(), &ok);
    if (!ok) {
      callback->sendFailure(Response::InvalidParams("Invalid errorReason."));
      return;
    }

    mark_as_canceled = true;
  }

  interceptor->ContinueInterceptedRequest(
      interception_id,
      std::make_unique<DevToolsURLRequestInterceptor::Modifications>(
          std::move(error), std::move(raw_response), std::move(url),
          std::move(method), std::move(post_data), std::move(headers),
          std::move(auth_challenge_response), mark_as_canceled),
      std::move(callback));
}


JSObject* JSTestInterface::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
    return JSTestInterfacePrototype::create(exec->globalData(), globalObject, JSTestInterfacePrototype::createStructure(globalObject->globalData(), globalObject, globalObject->objectPrototype()));
}


static void DeleteSession( SESSION *session )
{
    SESSION_LIST_ENTRY *predSession;
    void *newNextEntry;

    if( session == &local_sessions_list->session )
        local_sessions_list = 0;
    else
    {
        // Find predecessor.
        for( predSession = local_sessions_list;
                predSession != 0 && &( ( ( SESSION_LIST_ENTRY *)predSession->nextEntry )->session ) != session;
                predSession = predSession->nextEntry )
            ;

        if( predSession != 0 )
        {
            local_session_entries_used--;

            newNextEntry = &( (SESSION_LIST_ENTRY *)predSession->nextEntry)->nextEntry;

            free( predSession->nextEntry );

            predSession->nextEntry = newNextEntry;
        }
    }
}


bool AreAllTabsMuted(const TabStripModel& tab_strip,
                     const std::vector<int>& indices) {
  for (std::vector<int>::const_iterator i = indices.begin(); i != indices.end();
       ++i) {
    if (!tab_strip.GetWebContentsAt(*i)->IsAudioMuted())
      return false;
  }
  return true;
}


GF_Err senc_box_write(GF_Box *s, GF_BitStream *bs)
{
	GF_Err e;
	u32 i;
	u32 sample_count, nb_crypt_samples;
	GF_SampleEncryptionBox *ptr = (GF_SampleEncryptionBox *) s;

	sample_count = gf_list_count(ptr->samp_aux_info);
	//temp patch until we cleanup the spec...
	nb_crypt_samples = 0;
	for (i = 0; i < sample_count; i++) {
		GF_CENCSampleAuxInfo *sai = (GF_CENCSampleAuxInfo *)gf_list_get(ptr->samp_aux_info, i);
		if (!sai->isNotProtected) nb_crypt_samples++;
	}
	if (!nb_crypt_samples) {
		ptr->size = 0;
		return GF_OK;
	}

	e = gf_isom_box_write_header(s, bs);
	if (e) return e;
	//WARNING - PSEC (UUID) IS TYPECASTED TO SENC (FULL BOX) SO WE CANNOT USE USUAL FULL BOX FUNCTIONS
	gf_bs_write_u8(bs, ptr->version);
	gf_bs_write_u24(bs, ptr->flags);

	gf_bs_write_u32(bs, nb_crypt_samples);

	e = store_senc_info(ptr, bs);
	if (e) return e;

	for (i = 0; i < sample_count; i++) {
		GF_CENCSampleAuxInfo *sai = (GF_CENCSampleAuxInfo *)gf_list_get(ptr->samp_aux_info, i);
		if (sai->isNotProtected || !sai->cenc_data_size)
			continue;
		gf_bs_write_data(bs, sai->cenc_data, sai->cenc_data_size);
	}
	return GF_OK;
}


nameserver_read(struct nameserver *ns) {
	struct sockaddr_storage ss;
	ev_socklen_t addrlen = sizeof(ss);
	u8 packet[1500];
	char addrbuf[128];
	ASSERT_LOCKED(ns->base);

	for (;;) {
		const int r = recvfrom(ns->socket, (void*)packet,
		    sizeof(packet), 0,
		    (struct sockaddr*)&ss, &addrlen);
		if (r < 0) {
			int err = evutil_socket_geterror(ns->socket);
			if (EVUTIL_ERR_RW_RETRIABLE(err))
				return;
			nameserver_failed(ns,
			    evutil_socket_error_to_string(err));
			return;
		}
		if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
			(struct sockaddr*)&ns->address, 0)) {
			log(EVDNS_LOG_WARN, "Address mismatch on received "
			    "DNS packet.  Apparent source was %s",
			    evutil_format_sockaddr_port_(
				    (struct sockaddr *)&ss,
				    addrbuf, sizeof(addrbuf)));
			return;
		}

		ns->timedout = 0;
		reply_parse(ns->base, packet, r);
	}
}


TestSynchronousCompositor::~TestSynchronousCompositor() {
  SetClient(NULL);
}


  bool OnRequest(content::URLLoaderInterceptor::RequestParams* params) {
    if (callback_ && callback_.Run(params))
      return true;
    if (params->url_request.url.host() == "clients2.google.com" &&
        params->url_request.url.path() == "/service/update2/crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good2_update_manifest.xml",
          params->client.get());
      return true;
    }

    if (params->url_request.url.path() == "/good_update_manifest.xml") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good2_update_manifest.xml",
          params->client.get());
      return true;
    }
    if (params->url_request.url.path() == "/extensions/good_v1.crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good_v1.crx", params->client.get());
      return true;
    }
    if (params->url_request.url.path() == "/extensions/good2.crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good2.crx", params->client.get());
      return true;
    }

    return false;
  }


void Performance::clearMarks(const String& mark_name) {
  if (!user_timing_)
    user_timing_ = UserTiming::Create(*this);
  user_timing_->ClearMarks(mark_name);
}


static void nonrd_pick_sb_modes ( VP9_COMP * cpi , const TileInfo * const tile , int mi_row , int mi_col , int * rate , int64_t * dist , BLOCK_SIZE bsize , PICK_MODE_CONTEXT * ctx ) {
 VP9_COMMON * const cm = & cpi -> common ;
 MACROBLOCK * const x = & cpi -> mb ;
 MACROBLOCKD * const xd = & x -> e_mbd ;
 MB_MODE_INFO * mbmi ;
 set_offsets ( cpi , tile , mi_row , mi_col , bsize ) ;
 mbmi = & xd -> mi [ 0 ] . src_mi -> mbmi ;
 mbmi -> sb_type = bsize ;
 if ( cpi -> oxcf . aq_mode == CYCLIC_REFRESH_AQ && cm -> seg . enabled ) if ( mbmi -> segment_id && x -> in_static_area ) x -> rdmult = vp9_cyclic_refresh_get_rdmult ( cpi -> cyclic_refresh ) ;
 if ( vp9_segfeature_active ( & cm -> seg , mbmi -> segment_id , SEG_LVL_SKIP ) ) set_mode_info_seg_skip ( x , cm -> tx_mode , rate , dist , bsize ) ;
 else vp9_pick_inter_mode ( cpi , x , tile , mi_row , mi_col , rate , dist , bsize , ctx ) ;
 duplicate_mode_info_in_sb ( cm , xd , mi_row , mi_col , bsize ) ;
 }


static int MP4_ReadBox_String( stream_t *p_stream, MP4_Box_t *p_box )
{
    MP4_READBOX_ENTER( MP4_Box_data_string_t );

    p_box->data.p_string->psz_text = malloc( p_box->i_size + 1 - 8 ); /* +\0, -name, -size */
    if( p_box->data.p_string->psz_text == NULL )
        MP4_READBOX_EXIT( 0 );

    memcpy( p_box->data.p_string->psz_text, p_peek, p_box->i_size - 8 );
    p_box->data.p_string->psz_text[p_box->i_size - 8] = '\0';

#ifdef MP4_VERBOSE
        msg_Dbg( p_stream, "read box: \"%4.4s\" text=`%s'", (char *) & p_box->i_type,
                 p_box->data.p_string->psz_text );
#endif
    MP4_READBOX_EXIT( 1 );
}


std::wstring GetUninstallRegistryPath() {
  std::wstring result(
      L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
  if (*kCompanyPathName)
    result.append(kCompanyPathName).append(1, L' ');
  result.append(kProductPathName, kProductPathNameLength);
  return result.append(InstallDetails::Get().mode().install_suffix);
}


TfLiteStatus Subgraph::ModifyGraphWithDelegate(TfLiteDelegate* delegate) {
  TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(),
                                       "ModifyGraphWithDelegate");

  if (delegate == nullptr) {
    ReportError("Null delegate.");
    return kTfLiteDelegateError;
  }

  // Restore delegation state if applicable.
  TF_LITE_ENSURE_STATUS(RedoAllDelegates());

  if (state_ == kStateInvokableAndImmutable) {
    ReportError(
        "ModifyGraphWithDelegate is disallowed when graph is immutable.");
    return kTfLiteApplicationError;
  }

  if (!(delegate->flags & kTfLiteDelegateFlagsAllowDynamicTensors)) {
    int last_execution_plan_index_prepared;
    TF_LITE_ENSURE_OK(
        &context_, PrepareOpsStartingAt(0, execution_plan_,
                                        &last_execution_plan_index_prepared));
    if (has_dynamic_tensors_) {
      // Make sure that we are in a defined ready state before returning.
      // Plan and allocate tensors before returning.
      TF_LITE_ENSURE_OK(&context_, EnsureMemoryAllocations());
      ReportError(
          "Attempting to use a delegate that only supports static-sized "
          "tensors with a graph that has dynamic-sized tensors.");
      return kTfLiteApplicationError;
    }
  }

  const bool was_invokable_before_delegate = state_ == kStateInvokable;
  if (delegates_applied_.empty()) {
    // This is the first delegate being applied, so remember original execution
    // plan.
    // TODO(b/119623453): Restore execution plan to this state if delegate
    // application fails.
    pre_delegation_execution_plan_ = execution_plan_;
  }

  // TODO(aselle): Consider if it is worth storing pointers to delegates.
  // Setup additional context interface.
  SwitchToDelegateContext();

  auto reset_delegation_if_not_ok = [this](TfLiteStatus status) {
    if (status != kTfLiteOk) {
      TF_LITE_ENSURE_STATUS(RemoveAllDelegates());
      ReportError(
          "Restored original execution plan after delegate application "
          "failure.");
      return kTfLiteDelegateError;
    }
    return kTfLiteOk;
  };

  TfLiteStatus status = delegate->Prepare(&context_, delegate);

  // Remove additional context info.
  SwitchToKernelContext();

  TF_LITE_ENSURE_STATUS(reset_delegation_if_not_ok(status));

  if (!(delegate->flags & kTfLiteDelegateFlagsAllowDynamicTensors)) {
    // Reset the state to force tensor/op reallocation.
    state_ = kStateUninvokable;
    TF_LITE_ENSURE_STATUS(
        reset_delegation_if_not_ok(EnsureMemoryAllocations()));
    // After using a delegate which doesn't support dynamic tensors, make the
    // entire graph immutable.
    state_ = kStateInvokableAndImmutable;
  } else if (was_invokable_before_delegate) {
    // If the graph was invokable prior to delegate application, flush
    // allocation now to leave it in a consistent state.
    TF_LITE_ENSURE_STATUS(
        reset_delegation_if_not_ok(EnsureMemoryAllocations()));
  }
  delegates_applied_.push_back(delegate);

  return status;
}


ipf_list_clean(struct hmap *frag_lists,
               struct ipf_list *ipf_list)
    /* OVS_REQUIRES(ipf_lock) */
{
    ovs_list_remove(&ipf_list->list_node);
    hmap_remove(frag_lists, &ipf_list->node);
    free(ipf_list->frag_list);
    free(ipf_list);
}


ChannelMergerNode* BaseAudioContext::createChannelMerger(
    uint32_t number_of_inputs,
    ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  return ChannelMergerNode::Create(*this, number_of_inputs, exception_state);
}


static void unclone_ctx(struct perf_event_context *ctx)
{
	if (ctx->parent_ctx) {
		put_ctx(ctx->parent_ctx);
		ctx->parent_ctx = NULL;
	}
}


static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  FILE
    *file;

  Image
    *image,
    *next_image,
    *pwp_image;

  ImageInfo
    *read_info;

  int
    c,
    unique_file;

  MagickBooleanType
    status;

  register Image
    *p;

  register ssize_t
    i;

  size_t
    filesize,
    length;

  ssize_t
    count;

  unsigned char
    magick[MaxTextExtent];

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  pwp_image=AcquireImage(image_info);
  image=pwp_image;
  status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    return((Image *) NULL);
  count=ReadBlob(pwp_image,5,magick);
  if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  read_info=CloneImageInfo(image_info);
  (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
    (void *) NULL);
  SetImageInfoBlob(read_info,(void *) NULL,0);
  unique_file=AcquireUniqueFileResource(read_info->filename);
  for ( ; ; )
  {
    for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
    {
      for (i=0; i < 17; i++)
        magick[i]=magick[i+1];
      magick[17]=(unsigned char) c;
      if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
        break;
    }
    if (c == EOF)
      break;
    if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
      {
        (void) RelinquishUniqueFileResource(read_info->filename);
        ThrowReaderException(CorruptImageError,"ImproperImageHeader");
      }
    /*
      Dump SFW image to a temporary file.
    */
    file=(FILE *) NULL;
    if (unique_file != -1)
      file=fdopen(unique_file,"wb");
    if ((unique_file == -1) || (file == (FILE *) NULL))
      {
        (void) RelinquishUniqueFileResource(read_info->filename);
        ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
          image->filename);
        image=DestroyImageList(image);
        return((Image *) NULL);
      }
    length=fwrite("SFW94A",1,6,file);
    (void) length;
    filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
    for (i=0; i < (ssize_t) filesize; i++)
    {
      c=ReadBlobByte(pwp_image);
      (void) fputc(c,file);
    }
    (void) fclose(file);
    next_image=ReadImage(read_info,exception);
    if (next_image == (Image *) NULL)
      break;
    (void) FormatLocaleString(next_image->filename,MaxTextExtent,
      "slide_%02ld.sfw",(long) next_image->scene);
    if (image == (Image *) NULL)
      image=next_image;
    else
      {
        /*
          Link image into image list.
        */
        for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
        next_image->previous=p;
        next_image->scene=p->scene+1;
        p->next=next_image;
      }
    if (image_info->number_scenes != 0)
      if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
      GetBlobSize(pwp_image));
    if (status == MagickFalse)
      break;
  }
  if (unique_file != -1)
     (void) close(unique_file);
   (void) RelinquishUniqueFileResource(read_info->filename);
   read_info=DestroyImageInfo(read_info);
  (void) CloseBlob(pwp_image);
  pwp_image=DestroyImage(pwp_image);
   if (EOFBlob(image) != MagickFalse)
     {
       char
        *message;

      message=GetExceptionMessage(errno);
      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
        "UnexpectedEndOfFile","`%s': %s",image->filename,message);
      message=DestroyString(message);
    }
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


void DevToolsWindow::SearchInPath(int request_id,
                                  const std::string& file_system_path,
                                  const std::string& query) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  CHECK(web_contents_->GetURL().SchemeIs(chrome::kChromeDevToolsScheme));
  if (!file_helper_->IsFileSystemAdded(file_system_path)) {
    SearchCompleted(request_id, file_system_path, std::vector<std::string>());
    return;
  }
  file_system_indexer_->SearchInPath(file_system_path,
                                     query,
                                     Bind(&DevToolsWindow::SearchCompleted,
                                          weak_factory_.GetWeakPtr(),
                                          request_id,
                                          file_system_path));
}


static int nl80211_pre_doit(const struct genl_ops *ops, struct sk_buff *skb,
			    struct genl_info *info)
{
	struct cfg80211_registered_device *rdev;
	struct wireless_dev *wdev;
	struct net_device *dev;
	bool rtnl = ops->internal_flags & NL80211_FLAG_NEED_RTNL;

	if (rtnl)
		rtnl_lock();

	if (ops->internal_flags & NL80211_FLAG_NEED_WIPHY) {
		rdev = cfg80211_get_dev_from_info(genl_info_net(info), info);
		if (IS_ERR(rdev)) {
			if (rtnl)
				rtnl_unlock();
			return PTR_ERR(rdev);
		}
		info->user_ptr[0] = rdev;
	} else if (ops->internal_flags & NL80211_FLAG_NEED_NETDEV ||
		   ops->internal_flags & NL80211_FLAG_NEED_WDEV) {
		ASSERT_RTNL();

		wdev = __cfg80211_wdev_from_attrs(genl_info_net(info),
						  info->attrs);
		if (IS_ERR(wdev)) {
			if (rtnl)
				rtnl_unlock();
			return PTR_ERR(wdev);
		}

		dev = wdev->netdev;
		rdev = wiphy_to_rdev(wdev->wiphy);

		if (ops->internal_flags & NL80211_FLAG_NEED_NETDEV) {
			if (!dev) {
				if (rtnl)
					rtnl_unlock();
				return -EINVAL;
			}

			info->user_ptr[1] = dev;
		} else {
			info->user_ptr[1] = wdev;
		}

		if (ops->internal_flags & NL80211_FLAG_CHECK_NETDEV_UP &&
		    !wdev_running(wdev)) {
			if (rtnl)
				rtnl_unlock();
			return -ENETDOWN;
		}

		if (dev)
			dev_hold(dev);

		info->user_ptr[0] = rdev;
	}

	return 0;
}


rfbClientSendString(rfbClientPtr cl, const char *reason)
{
    char *buf;
    int len = strlen(reason);

    rfbLog("rfbClientSendString(\"%s\")\n", reason);

    buf = (char *)malloc(4 + len);
    if (buf) {
        ((uint32_t *)buf)[0] = Swap32IfLE(len);
        memcpy(buf + 4, reason, len);

        if (rfbWriteExact(cl, buf, 4 + len) < 0)
            rfbLogPerror("rfbClientSendString: write");
        free(buf);
    }

    rfbCloseClient(cl);
}


terminate_cib(const char *caller, gboolean fast)
{
    if (remote_fd > 0) {
        close(remote_fd);
        remote_fd = 0;
    }
    if (remote_tls_fd > 0) {
        close(remote_tls_fd);
        remote_tls_fd = 0;
    }

    if(!fast) {
        crm_info("%s: Disconnecting from cluster infrastructure", caller);
        crm_cluster_disconnect(&crm_cluster);
    }

    uninitializeCib();

    crm_info("%s: Exiting%s...", caller, fast?" fast":mainloop?" from mainloop":"");

    if(fast == FALSE && mainloop != NULL && g_main_is_running(mainloop)) {
        g_main_quit(mainloop);

    } else {
        qb_ipcs_destroy(ipcs_ro);
        qb_ipcs_destroy(ipcs_rw);
        qb_ipcs_destroy(ipcs_shm);

        if (fast) {
            crm_exit(EX_USAGE);
        } else {
            crm_exit(EX_OK);
        }
    }
}


PJ_DEF(pj_status_t) pjmedia_codec_speex_deinit(void)
{
    pjmedia_codec_mgr *codec_mgr;
    pj_status_t status;

    if (spx_factory.pool == NULL) {
	/* Already deinitialized */
	return PJ_SUCCESS;
    }

    pj_mutex_lock(spx_factory.mutex);

    /* We don't want to deinit if there's outstanding codec. */
    /* This is silly, as we'll always have codec in the list if
       we ever allocate a codec! A better behavior maybe is to
       deallocate all codecs in the list.
    if (!pj_list_empty(&spx_factory.codec_list)) {
	pj_mutex_unlock(spx_factory.mutex);
	return PJ_EBUSY;
    }
    */

    /* Get the codec manager. */
    codec_mgr = pjmedia_endpt_get_codec_mgr(spx_factory.endpt);
    if (!codec_mgr) {
	pj_pool_release(spx_factory.pool);
	spx_factory.pool = NULL;
	return PJ_EINVALIDOP;
    }

    /* Unregister Speex codec factory. */
    status = pjmedia_codec_mgr_unregister_factory(codec_mgr,
						  &spx_factory.base);

    /* Destroy mutex. */
    pj_mutex_unlock(spx_factory.mutex);
    pj_mutex_destroy(spx_factory.mutex);
    spx_factory.mutex = NULL;

    /* Destroy pool. */
    pj_pool_release(spx_factory.pool);
    spx_factory.pool = NULL;

    return status;
}


int get_sw_value(buf_T *buf)
{
  long result = buf->b_p_sw ? buf->b_p_sw : buf->b_p_ts;
  assert(result >= 0 && result <= INT_MAX);
  return (int)result;
}


void InitManagerMojoOnIO(mojom::DiscardableSharedMemoryManagerPtr* manager_mojo,
                         mojom::DiscardableSharedMemoryManagerPtrInfo info) {
  manager_mojo->Bind(std::move(info));
}


static bool access_pmu_evtyper(struct kvm_vcpu *vcpu, struct sys_reg_params *p,
			       const struct sys_reg_desc *r)
{
	u64 idx, reg;

	if (!kvm_arm_pmu_v3_ready(vcpu))
		return trap_raz_wi(vcpu, p, r);

	if (pmu_access_el0_disabled(vcpu))
		return false;

	if (r->CRn == 9 && r->CRm == 13 && r->Op2 == 1) {
		/* PMXEVTYPER_EL0 */
		idx = vcpu_sys_reg(vcpu, PMSELR_EL0) & ARMV8_PMU_COUNTER_MASK;
		reg = PMEVTYPER0_EL0 + idx;
	} else if (r->CRn == 14 && (r->CRm & 12) == 12) {
		idx = ((r->CRm & 3) << 3) | (r->Op2 & 7);
		if (idx == ARMV8_PMU_CYCLE_IDX)
			reg = PMCCFILTR_EL0;
		else
			/* PMEVTYPERn_EL0 */
			reg = PMEVTYPER0_EL0 + idx;
	} else {
		BUG();
	}

	if (!pmu_counter_idx_valid(vcpu, idx))
		return false;

	if (p->is_write) {
		kvm_pmu_set_counter_event_type(vcpu, p->regval, idx);
		vcpu_sys_reg(vcpu, reg) = p->regval & ARMV8_PMU_EVTYPE_MASK;
	} else {
		p->regval = vcpu_sys_reg(vcpu, reg) & ARMV8_PMU_EVTYPE_MASK;
	}

	return true;
}


bool GLES2DecoderImpl::CheckCurrentProgram(const char* function_name) {
  if (!current_program_) {
    SetGLError(GL_INVALID_OPERATION, function_name, "no program in use");
    return false;
  }
  if (!current_program_->InUse()) {
    SetGLError(GL_INVALID_OPERATION, function_name, "program not linked");
    return false;
  }
  return true;
}


static int get_snd_codec_id(audio_format_t format)
{
 int id = 0;

 switch (format & AUDIO_FORMAT_MAIN_MASK) {
 default:
        ALOGE("%s: Unsupported audio format", __func__);
 }

 return id;
}


const fz_color_params * fz_default_color_params ( fz_context * ctx ) {
 return default_color_params ;
 }


NameValueParserStartElt(void * d, const char * name, int l)
{
	struct NameValueParserData * data = (struct NameValueParserData *)d;
	data->topelt = 1;
    if(l>63)
        l = 63;
    memcpy(data->curelt, name, l);
    data->curelt[l] = '\0';
	data->cdata = NULL;
	data->cdatalen = 0;
}


static struct sock *__udp6_lib_lookup_skb(struct sk_buff *skb,
					  __be16 sport, __be16 dport,
					  struct udp_table *udptable)
{
	struct sock *sk;
	struct ipv6hdr *iph = ipv6_hdr(skb);

	if (unlikely(sk = skb_steal_sock(skb)))
		return sk;
	return __udp6_lib_lookup(dev_net(skb_dst(skb)->dev), &iph->saddr, sport,
				 &iph->daddr, dport, inet6_iif(skb),
				 udptable);
}


static int WM_LoadConfig(const char *config_file) {
    return load_config(config_file, NULL);
}


get_lval(
    char_u	*name,
    typval_T	*rettv,
    lval_T	*lp,
    int		unlet,
    int		skip,
    int		flags,	    // GLV_ values
    int		fne_flags)  // flags for find_name_end()
{
    char_u	*p;
    char_u	*expr_start, *expr_end;
    int		cc;
    dictitem_T	*v;
    typval_T	var1;
    typval_T	var2;
    int		empty1 = FALSE;
    char_u	*key = NULL;
    int		len;
    hashtab_T	*ht = NULL;
    int		quiet = flags & GLV_QUIET;
    int		writing;

    // Clear everything in "lp".
    CLEAR_POINTER(lp);

    if (skip || (flags & GLV_COMPILING))
    {
	// When skipping or compiling just find the end of the name.
	lp->ll_name = name;
	lp->ll_name_end = find_name_end(name, NULL, NULL,
						      FNE_INCL_BR | fne_flags);
	return lp->ll_name_end;
    }

    // Find the end of the name.
    p = find_name_end(name, &expr_start, &expr_end, fne_flags);
    lp->ll_name_end = p;
    if (expr_start != NULL)
    {
	// Don't expand the name when we already know there is an error.
	if (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)
						    && *p != '[' && *p != '.')
	{
	    semsg(_(e_trailing_arg), p);
	    return NULL;
	}

	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
	if (lp->ll_exp_name == NULL)
	{
	    // Report an invalid expression in braces, unless the
	    // expression evaluation has been cancelled due to an
	    // aborting error, an interrupt, or an exception.
	    if (!aborting() && !quiet)
	    {
		emsg_severe = TRUE;
		semsg(_(e_invarg2), name);
		return NULL;
	    }
	}
	lp->ll_name = lp->ll_exp_name;
    }
    else
    {
	lp->ll_name = name;

	if (in_vim9script())
	{
	    // "a: type" is declaring variable "a" with a type, not "a:".
	    if (p == name + 2 && p[-1] == ':')
	    {
		--p;
		lp->ll_name_end = p;
	    }
	    if (*p == ':')
	    {
		scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
		char_u	     *tp = skipwhite(p + 1);

		if (tp == p + 1 && !quiet)
		{
		    semsg(_(e_white_space_required_after_str_str), ":", p);
		    return NULL;
		}

		// parse the type after the name
		lp->ll_type = parse_type(&tp, &si->sn_type_list, !quiet);
		if (lp->ll_type == NULL && !quiet)
		    return NULL;
		lp->ll_name_end = tp;
	    }
	}
    }

    // Without [idx] or .key we are done.
    if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
	return p;

    if (in_vim9script() && lval_root != NULL)
    {
	// using local variable
	lp->ll_tv = lval_root;
	v = NULL;
    }
    else
    {
	cc = *p;
	*p = NUL;
	// When we would write to the variable pass &ht and prevent autoload.
	writing = !(flags & GLV_READ_ONLY);
	v = find_var(lp->ll_name, writing ? &ht : NULL,
					 (flags & GLV_NO_AUTOLOAD) || writing);
	if (v == NULL && !quiet)
	    semsg(_(e_undefined_variable_str), lp->ll_name);
	*p = cc;
	if (v == NULL)
	    return NULL;
	lp->ll_tv = &v->di_tv;
    }

    if (in_vim9script() && (flags & GLV_NO_DECL) == 0)
    {
	if (!quiet)
	    semsg(_(e_variable_already_declared), lp->ll_name);
	return NULL;
    }

    /*
     * Loop until no more [idx] or .key is following.
     */
    var1.v_type = VAR_UNKNOWN;
    var2.v_type = VAR_UNKNOWN;
    while (*p == '[' || (*p == '.' && p[1] != '=' && p[1] != '.'))
    {
	if (*p == '.' && lp->ll_tv->v_type != VAR_DICT)
	{
	    if (!quiet)
		semsg(_(e_dot_can_only_be_used_on_dictionary_str), name);
	    return NULL;
	}
	if (lp->ll_tv->v_type != VAR_LIST
		&& lp->ll_tv->v_type != VAR_DICT
		&& lp->ll_tv->v_type != VAR_BLOB)
	{
	    if (!quiet)
		emsg(_("E689: Can only index a List, Dictionary or Blob"));
	    return NULL;
	}

	// a NULL list/blob works like an empty list/blob, allocate one now.
	if (lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list == NULL)
	    rettv_list_alloc(lp->ll_tv);
	else if (lp->ll_tv->v_type == VAR_BLOB
					     && lp->ll_tv->vval.v_blob == NULL)
	    rettv_blob_alloc(lp->ll_tv);

	if (lp->ll_range)
	{
	    if (!quiet)
		emsg(_("E708: [:] must come last"));
	    return NULL;
	}

	if (in_vim9script() && lp->ll_valtype == NULL
		&& v != NULL
		&& lp->ll_tv == &v->di_tv
		&& ht != NULL && ht == get_script_local_ht())
	{
	    svar_T  *sv = find_typval_in_script(lp->ll_tv);

	    // Vim9 script local variable: get the type
	    if (sv != NULL)
		lp->ll_valtype = sv->sv_type;
	}

	len = -1;
	if (*p == '.')
	{
	    key = p + 1;
	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
		;
	    if (len == 0)
	    {
		if (!quiet)
		    emsg(_(e_emptykey));
		return NULL;
	    }
	    p = key + len;
	}
	else
	{
	    // Get the index [expr] or the first index [expr: ].
	    p = skipwhite(p + 1);
	    if (*p == ':')
		empty1 = TRUE;
	    else
	    {
		empty1 = FALSE;
		if (eval1(&p, &var1, &EVALARG_EVALUATE) == FAIL)  // recursive!
		    return NULL;
		if (tv_get_string_chk(&var1) == NULL)
		{
		    // not a number or string
		    clear_tv(&var1);
		    return NULL;
		}
		p = skipwhite(p);
	    }

	    // Optionally get the second index [ :expr].
	    if (*p == ':')
	    {
		if (lp->ll_tv->v_type == VAR_DICT)
		{
		    if (!quiet)
			emsg(_(e_cannot_slice_dictionary));
		    clear_tv(&var1);
		    return NULL;
		}
		if (rettv != NULL
			&& !(rettv->v_type == VAR_LIST
						 && rettv->vval.v_list != NULL)
			&& !(rettv->v_type == VAR_BLOB
						&& rettv->vval.v_blob != NULL))
		{
		    if (!quiet)
			emsg(_("E709: [:] requires a List or Blob value"));
		    clear_tv(&var1);
		    return NULL;
		}
		p = skipwhite(p + 1);
		if (*p == ']')
		    lp->ll_empty2 = TRUE;
		else
		{
		    lp->ll_empty2 = FALSE;
		    // recursive!
		    if (eval1(&p, &var2, &EVALARG_EVALUATE) == FAIL)
		    {
			clear_tv(&var1);
			return NULL;
		    }
		    if (tv_get_string_chk(&var2) == NULL)
		    {
			// not a number or string
			clear_tv(&var1);
			clear_tv(&var2);
			return NULL;
		    }
		}
		lp->ll_range = TRUE;
	    }
	    else
		lp->ll_range = FALSE;

	    if (*p != ']')
	    {
		if (!quiet)
		    emsg(_(e_missing_closing_square_brace));
		clear_tv(&var1);
		clear_tv(&var2);
		return NULL;
	    }

	    // Skip to past ']'.
	    ++p;
	}

	if (lp->ll_tv->v_type == VAR_DICT)
	{
	    if (len == -1)
	    {
		// "[key]": get key from "var1"
		key = tv_get_string_chk(&var1);	// is number or string
		if (key == NULL)
		{
		    clear_tv(&var1);
		    return NULL;
		}
	    }
	    lp->ll_list = NULL;

	    // a NULL dict is equivalent with an empty dict
	    if (lp->ll_tv->vval.v_dict == NULL)
	    {
		lp->ll_tv->vval.v_dict = dict_alloc();
		if (lp->ll_tv->vval.v_dict == NULL)
		{
		    clear_tv(&var1);
		    return NULL;
		}
		++lp->ll_tv->vval.v_dict->dv_refcount;
	    }
	    lp->ll_dict = lp->ll_tv->vval.v_dict;

	    lp->ll_di = dict_find(lp->ll_dict, key, len);

	    // When assigning to a scope dictionary check that a function and
	    // variable name is valid (only variable name unless it is l: or
	    // g: dictionary). Disallow overwriting a builtin function.
	    if (rettv != NULL && lp->ll_dict->dv_scope != 0)
	    {
		int prevval;
		int wrong;

		if (len != -1)
		{
		    prevval = key[len];
		    key[len] = NUL;
		}
		else
		    prevval = 0; // avoid compiler warning
		wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
			       && rettv->v_type == VAR_FUNC
			       && var_wrong_func_name(key, lp->ll_di == NULL))
			|| !valid_varname(key, -1, TRUE);
		if (len != -1)
		    key[len] = prevval;
		if (wrong)
		{
		    clear_tv(&var1);
		    return NULL;
		}
	    }

	    if (lp->ll_valtype != NULL)
		// use the type of the member
		lp->ll_valtype = lp->ll_valtype->tt_member;

	    if (lp->ll_di == NULL)
	    {
		// Can't add "v:" or "a:" variable.
		if (lp->ll_dict == get_vimvar_dict()
			 || &lp->ll_dict->dv_hashtab == get_funccal_args_ht())
		{
		    semsg(_(e_illvar), name);
		    clear_tv(&var1);
		    return NULL;
		}

		// Key does not exist in dict: may need to add it.
		if (*p == '[' || *p == '.' || unlet)
		{
		    if (!quiet)
			semsg(_(e_dictkey), key);
		    clear_tv(&var1);
		    return NULL;
		}
		if (len == -1)
		    lp->ll_newkey = vim_strsave(key);
		else
		    lp->ll_newkey = vim_strnsave(key, len);
		clear_tv(&var1);
		if (lp->ll_newkey == NULL)
		    p = NULL;
		break;
	    }
	    // existing variable, need to check if it can be changed
	    else if ((flags & GLV_READ_ONLY) == 0
			&& (var_check_ro(lp->ll_di->di_flags, name, FALSE)
			  || var_check_lock(lp->ll_di->di_flags, name, FALSE)))
	    {
		clear_tv(&var1);
		return NULL;
	    }

	    clear_tv(&var1);
	    lp->ll_tv = &lp->ll_di->di_tv;
	}
	else if (lp->ll_tv->v_type == VAR_BLOB)
	{
	    long bloblen = blob_len(lp->ll_tv->vval.v_blob);

	    /*
	     * Get the number and item for the only or first index of the List.
	     */
	    if (empty1)
		lp->ll_n1 = 0;
	    else
		// is number or string
		lp->ll_n1 = (long)tv_get_number(&var1);
	    clear_tv(&var1);

	    if (check_blob_index(bloblen, lp->ll_n1, quiet) == FAIL)
	    {
		clear_tv(&var2);
		return NULL;
	    }
	    if (lp->ll_range && !lp->ll_empty2)
	    {
		lp->ll_n2 = (long)tv_get_number(&var2);
		clear_tv(&var2);
		if (check_blob_range(bloblen, lp->ll_n1, lp->ll_n2, quiet)
								       == FAIL)
		    return NULL;
	    }
	    lp->ll_blob = lp->ll_tv->vval.v_blob;
	    lp->ll_tv = NULL;
	    break;
	}
	else
	{
	    /*
	     * Get the number and item for the only or first index of the List.
	     */
	    if (empty1)
		lp->ll_n1 = 0;
	    else
		// is number or string
		lp->ll_n1 = (long)tv_get_number(&var1);
	    clear_tv(&var1);

	    lp->ll_dict = NULL;
	    lp->ll_list = lp->ll_tv->vval.v_list;
	    lp->ll_li = check_range_index_one(lp->ll_list, &lp->ll_n1, quiet);
	    if (lp->ll_li == NULL)
	    {
		clear_tv(&var2);
		return NULL;
	    }

	    if (lp->ll_valtype != NULL)
		// use the type of the member
		lp->ll_valtype = lp->ll_valtype->tt_member;

	    /*
	     * May need to find the item or absolute index for the second
	     * index of a range.
	     * When no index given: "lp->ll_empty2" is TRUE.
	     * Otherwise "lp->ll_n2" is set to the second index.
	     */
	    if (lp->ll_range && !lp->ll_empty2)
	    {
		lp->ll_n2 = (long)tv_get_number(&var2);
						    // is number or string
		clear_tv(&var2);
		if (check_range_index_two(lp->ll_list,
					    &lp->ll_n1, lp->ll_li,
					    &lp->ll_n2, quiet) == FAIL)
		    return NULL;
	    }

	    lp->ll_tv = &lp->ll_li->li_tv;
	}
    }

    clear_tv(&var1);
    lp->ll_name_end = p;
    return p;
}


dataiterator_clonepos(Dataiterator *di, Dataiterator *from)
{
  di->state = from->state;
  di->flags &= ~SEARCH_THISSOLVID;
  di->flags |= (from->flags & SEARCH_THISSOLVID);
  di->repo = from->repo;
  di->data = from->data;
  di->dp = from->dp;
  di->ddp = from->ddp;
  di->idp = from->idp;
  di->keyp = from->keyp;
  di->key = from->key;
  di->kv = from->kv;
  di->repodataid = from->repodataid;
  di->solvid = from->solvid;
  di->repoid = from->repoid;
  di->rootlevel = from->rootlevel;
  memcpy(di->parents, from->parents, sizeof(from->parents));
  di->nparents = from->nparents;
  if (di->nparents)
    {
      int i;
      for (i = 1; i < di->nparents; i++)
	di->parents[i].kv.parent = &di->parents[i - 1].kv;
      di->kv.parent = &di->parents[di->nparents - 1].kv;
    }
  di->dupstr = 0;
  di->dupstrn = 0;
  if (from->dupstr && from->dupstr == from->kv.str)
    {
      di->dupstrn = from->dupstrn;
      di->dupstr = solv_memdup(from->dupstr, from->dupstrn);
    }
}


static void dns_stats_tree_init ( stats_tree * st ) {
 st_node_packets = stats_tree_create_node ( st , st_str_packets , 0 , TRUE ) ;
 st_node_packet_qr = stats_tree_create_pivot ( st , st_str_packet_qr , st_node_packets ) ;
 st_node_packet_qtypes = stats_tree_create_pivot ( st , st_str_packet_qtypes , st_node_packets ) ;
 st_node_packet_qclasses = stats_tree_create_pivot ( st , st_str_packet_qclasses , st_node_packets ) ;
 st_node_packet_rcodes = stats_tree_create_pivot ( st , st_str_packet_rcodes , st_node_packets ) ;
 st_node_packet_opcodes = stats_tree_create_pivot ( st , st_str_packet_opcodes , st_node_packets ) ;
 st_node_packets_avg_size = stats_tree_create_node ( st , st_str_packets_avg_size , 0 , FALSE ) ;
 st_node_query_stats = stats_tree_create_node ( st , st_str_query_stats , 0 , TRUE ) ;
 st_node_query_qname_len = stats_tree_create_node ( st , st_str_query_qname_len , st_node_query_stats , FALSE ) ;
 st_node_query_domains = stats_tree_create_node ( st , st_str_query_domains , st_node_query_stats , TRUE ) ;
 st_node_query_domains_l1 = stats_tree_create_node ( st , st_str_query_domains_l1 , st_node_query_domains , FALSE ) ;
 st_node_query_domains_l2 = stats_tree_create_node ( st , st_str_query_domains_l2 , st_node_query_domains , FALSE ) ;
 st_node_query_domains_l3 = stats_tree_create_node ( st , st_str_query_domains_l3 , st_node_query_domains , FALSE ) ;
 st_node_query_domains_lmore = stats_tree_create_node ( st , st_str_query_domains_lmore , st_node_query_domains , FALSE ) ;
 st_node_response_stats = stats_tree_create_node ( st , st_str_response_stats , 0 , TRUE ) ;
 st_node_response_nquestions = stats_tree_create_node ( st , st_str_response_nquestions , st_node_response_stats , FALSE ) ;
 st_node_response_nanswers = stats_tree_create_node ( st , st_str_response_nanswers , st_node_response_stats , FALSE ) ;
 st_node_response_nauthorities = stats_tree_create_node ( st , st_str_response_nauthorities , st_node_response_stats , FALSE ) ;
 st_node_response_nadditionals = stats_tree_create_node ( st , st_str_response_nadditionals , st_node_response_stats , FALSE ) ;
 }


int xmlrpc_unregister_method ( const char * method ) {
 return_val_if_fail ( method != NULL , XMLRPC_ERR_PARAMS ) ;
 mowgli_patricia_delete ( XMLRPCCMD , method ) ;
 return XMLRPC_ERR_OK ;
 }


  gfx::NativeViewAccessible GetNativeViewAccessible() {
    return View::GetNativeViewAccessible();
  }


void HTMLLinkElement::removedFromDocument()
{
    HTMLElement::removedFromDocument();

    document()->removeStyleSheetCandidateNode(this);

     if (document()->renderer())
         document()->updateStyleSelector();
    m_shouldProcessAfterAttach = false;
 }


bool ShouldShowManualFallbackForPreLollipop(syncer::SyncService* sync_service) {
#if defined(OS_ANDROID)
  return ((base::android::BuildInfo::GetInstance()->sdk_int() >=
           base::android::SDK_VERSION_LOLLIPOP) ||
          (password_manager_util::GetPasswordSyncState(sync_service) ==
           SYNCING_NORMAL_ENCRYPTION));
#else
  return true;
#endif
}


uint8_t *buffer_end(Buffer *buffer)
{
    return buffer->buffer + buffer->offset;
}


GF_Err ipro_box_read(GF_Box *s, GF_BitStream *bs)
{
	ISOM_DECREASE_SIZE(s, 2)
	gf_bs_read_u16(bs);
	return gf_isom_box_array_read(s, bs);
}


static int url_to_curl_url(const char *url, const char **out)
{
	/*
	 * We don't need to check for case-aliases, "http.exe", and so
	 * on because in the default configuration, is_transport_allowed
	 * prevents URLs with those schemes from being cloned
	 * automatically.
	 */
	if (skip_prefix(url, "http::", out) ||
	    skip_prefix(url, "https::", out) ||
	    skip_prefix(url, "ftp::", out) ||
	    skip_prefix(url, "ftps::", out))
		return 1;
	if (starts_with(url, "http://") ||
	    starts_with(url, "https://") ||
	    starts_with(url, "ftp://") ||
	    starts_with(url, "ftps://")) {
		*out = url;
		return 1;
	}
	return 0;
}


free_locals(cctx_T *cctx)
{
    unwind_locals(cctx, 0);
    ga_clear(&cctx->ctx_locals);
}


size_t zmalloc_get_memory_size(void) {
#if defined(__unix__) || defined(__unix) || defined(unix) || \
    (defined(__APPLE__) && defined(__MACH__))
#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
    int mib[2];
    mib[0] = CTL_HW;
#if defined(HW_MEMSIZE)
    mib[1] = HW_MEMSIZE;            /* OSX. --------------------- */
#elif defined(HW_PHYSMEM64)
    mib[1] = HW_PHYSMEM64;          /* NetBSD, OpenBSD. --------- */
#endif
    int64_t size = 0;               /* 64-bit */
    size_t len = sizeof(size);
    if (sysctl( mib, 2, &size, &len, NULL, 0) == 0)
        return (size_t)size;
    return 0L;          /* Failed? */

#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
    /* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */
    return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE);

#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))
    /* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */
    int mib[2];
    mib[0] = CTL_HW;
#if defined(HW_REALMEM)
    mib[1] = HW_REALMEM;        /* FreeBSD. ----------------- */
#elif defined(HW_PHYSMEM)
    mib[1] = HW_PHYSMEM;        /* Others. ------------------ */
#endif
    unsigned int size = 0;      /* 32-bit */
    size_t len = sizeof(size);
    if (sysctl(mib, 2, &size, &len, NULL, 0) == 0)
        return (size_t)size;
    return 0L;          /* Failed? */
#else
    return 0L;          /* Unknown method to get the data. */
#endif
#else
    return 0L;          /* Unknown OS. */
#endif
}


lys_deviation_free(struct lys_module *module, struct lys_deviation *dev,
                   void (*private_destructor)(const struct lys_node *node, void *priv))
{
    int i, j, k;
    struct ly_ctx *ctx;
    struct lys_node *next, *elem;

    ctx = module->ctx;

    lydict_remove(ctx, dev->target_name);
    lydict_remove(ctx, dev->dsc);
    lydict_remove(ctx, dev->ref);
    lys_extension_instances_free(ctx, dev->ext, dev->ext_size, private_destructor);

    if (!dev->deviate) {
        return;
    }

    /* it could not be applied because it failed to be applied */
    if (dev->orig_node) {
        /* the module was freed, but we only need the context from orig_node, use ours */
        if (dev->deviate[0].mod == LY_DEVIATE_NO) {
            /* it's actually a node subtree, we need to update modules on all the nodes :-/ */
            LY_TREE_DFS_BEGIN(dev->orig_node, next, elem) {
                elem->module = module;

                LY_TREE_DFS_END(dev->orig_node, next, elem);
            }
            lys_node_free(dev->orig_node, NULL, 0);
        } else {
            /* it's just a shallow copy, freeing one node */
            dev->orig_node->module = module;
            lys_node_free(dev->orig_node, NULL, 1);
        }
    }

    for (i = 0; i < dev->deviate_size; i++) {
        lys_extension_instances_free(ctx, dev->deviate[i].ext, dev->deviate[i].ext_size, private_destructor);

        for (j = 0; j < dev->deviate[i].dflt_size; j++) {
            lydict_remove(ctx, dev->deviate[i].dflt[j]);
        }
        free(dev->deviate[i].dflt);

        lydict_remove(ctx, dev->deviate[i].units);

        if (dev->deviate[i].mod == LY_DEVIATE_DEL) {
            for (j = 0; j < dev->deviate[i].must_size; j++) {
                lys_restr_free(ctx, &dev->deviate[i].must[j], private_destructor);
            }
            free(dev->deviate[i].must);

            for (j = 0; j < dev->deviate[i].unique_size; j++) {
                for (k = 0; k < dev->deviate[i].unique[j].expr_size; k++) {
                    lydict_remove(ctx, dev->deviate[i].unique[j].expr[k]);
                }
                free(dev->deviate[i].unique[j].expr);
            }
            free(dev->deviate[i].unique);
        }
    }
    free(dev->deviate);
}


R_API ut64 r_bin_java_get_method_end(RBinJavaObj *bin, RBinJavaField *fm_type) {
	return r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr +
	+r_bin_java_get_method_code_size (fm_type);
}


const char * SSL_alert_desc_string ( int value ) {
 const char * str ;
 switch ( value & 0xff ) {
 case SSL3_AD_CLOSE_NOTIFY : str = "CN" ;
 break ;
 case SSL3_AD_UNEXPECTED_MESSAGE : str = "UM" ;
 break ;
 case SSL3_AD_BAD_RECORD_MAC : str = "BM" ;
 break ;
 case SSL3_AD_DECOMPRESSION_FAILURE : str = "DF" ;
 break ;
 case SSL3_AD_HANDSHAKE_FAILURE : str = "HF" ;
 break ;
 case SSL3_AD_NO_CERTIFICATE : str = "NC" ;
 break ;
 case SSL3_AD_BAD_CERTIFICATE : str = "BC" ;
 break ;
 case SSL3_AD_UNSUPPORTED_CERTIFICATE : str = "UC" ;
 break ;
 case SSL3_AD_CERTIFICATE_REVOKED : str = "CR" ;
 break ;
 case SSL3_AD_CERTIFICATE_EXPIRED : str = "CE" ;
 break ;
 case SSL3_AD_CERTIFICATE_UNKNOWN : str = "CU" ;
 break ;
 case SSL3_AD_ILLEGAL_PARAMETER : str = "IP" ;
 break ;
 case TLS1_AD_DECRYPTION_FAILED : str = "DC" ;
 break ;
 case TLS1_AD_RECORD_OVERFLOW : str = "RO" ;
 break ;
 case TLS1_AD_UNKNOWN_CA : str = "CA" ;
 break ;
 case TLS1_AD_ACCESS_DENIED : str = "AD" ;
 break ;
 case TLS1_AD_DECODE_ERROR : str = "DE" ;
 break ;
 case TLS1_AD_DECRYPT_ERROR : str = "CY" ;
 break ;
 case TLS1_AD_EXPORT_RESTRICTION : str = "ER" ;
 break ;
 case TLS1_AD_PROTOCOL_VERSION : str = "PV" ;
 break ;
 case TLS1_AD_INSUFFICIENT_SECURITY : str = "IS" ;
 break ;
 case TLS1_AD_INTERNAL_ERROR : str = "IE" ;
 break ;
 case TLS1_AD_USER_CANCELLED : str = "US" ;
 break ;
 case TLS1_AD_NO_RENEGOTIATION : str = "NR" ;
 break ;
 case TLS1_AD_UNSUPPORTED_EXTENSION : str = "UE" ;
 break ;
 case TLS1_AD_CERTIFICATE_UNOBTAINABLE : str = "CO" ;
 break ;
 case TLS1_AD_UNRECOGNIZED_NAME : str = "UN" ;
 break ;
 case TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE : str = "BR" ;
 break ;
 case TLS1_AD_BAD_CERTIFICATE_HASH_VALUE : str = "BH" ;
 break ;
 case TLS1_AD_UNKNOWN_PSK_IDENTITY : str = "UP" ;
 break ;
 default : str = "UK" ;
 break ;
 }
 return ( str ) ;
 }


static void hidg_free_inst(struct usb_function_instance *f)
{
	struct f_hid_opts *opts;

	opts = container_of(f, struct f_hid_opts, func_inst);

	mutex_lock(&hidg_ida_lock);

	hidg_put_minor(opts->minor);
	if (ida_is_empty(&hidg_ida))
		ghid_cleanup();

	mutex_unlock(&hidg_ida_lock);

	if (opts->report_desc_alloc)
		kfree(opts->report_desc);

	kfree(opts);
}


static struct page *new_vma_page(struct page *page, unsigned long private, int **x)
{
	struct vm_area_struct *vma = (struct vm_area_struct *)private;
	unsigned long uninitialized_var(address);

	while (vma) {
		address = page_address_in_vma(page, vma);
		if (address != -EFAULT)
			break;
		vma = vma->vm_next;
	}

	/*
	 * if !vma, alloc_page_vma() will use task or system default policy
	 */
	return alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
}


static void cmv_motcomp ( unsigned char * dst , int dst_stride , const unsigned char * src , int src_stride , int x , int y , int xoffset , int yoffset , int width , int height ) {
 int i , j ;
 for ( j = y ;
 j < y + 4 ;
 j ++ ) for ( i = x ;
 i < x + 4 ;
 i ++ ) {
 if ( i + xoffset >= 0 && i + xoffset < width && j + yoffset >= 0 && j + yoffset < height ) {
 dst [ j * dst_stride + i ] = src [ ( j + yoffset ) * src_stride + i + xoffset ] ;
 }
 else {
 dst [ j * dst_stride + i ] = 0 ;
 }
 }
 }


SPL_METHOD ( DirectoryIterator , next ) {
 spl_filesystem_object * intern = ( spl_filesystem_object * ) zend_object_store_get_object ( getThis ( ) TSRMLS_CC ) ;
 int skip_dots = SPL_HAS_FLAG ( intern -> flags , SPL_FILE_DIR_SKIPDOTS ) ;
 if ( zend_parse_parameters_none ( ) == FAILURE ) {
 return ;
 }
 intern -> u . dir . index ++ ;
 do {
 spl_filesystem_dir_read ( intern TSRMLS_CC ) ;
 }
 while ( skip_dots && spl_filesystem_is_dot ( intern -> u . dir . entry . d_name ) ) ;
 if ( intern -> file_name ) {
 efree ( intern -> file_name ) ;
 intern -> file_name = NULL ;
 }
 }


bool IsEqualForTesting(const SendTabToSelfEntry& a,
                       const SendTabToSelfEntry& b) {
  return a.GetGUID() == b.GetGUID() && a.GetURL() == b.GetURL() &&
         a.GetTitle() == b.GetTitle() &&
         a.GetDeviceName() == b.GetDeviceName() &&
         a.GetTargetDeviceSyncCacheGuid() == b.GetTargetDeviceSyncCacheGuid() &&
         a.GetSharedTime() == b.GetSharedTime() &&
         a.GetOriginalNavigationTime() == b.GetOriginalNavigationTime();
}


void WebPage::releaseBackForwardEntry(BackForwardId id) const
{
    HistoryItem* item = historyItemFromBackForwardId(id);
    ASSERT(item);
    item->deref();
}


static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt, int *serial)

{

    int got_picture;

    if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)

        return -1;

    if (pkt->data == flush_pkt.data) {

        avcodec_flush_buffers(is->video_st->codec);

        SDL_LockMutex(is->pictq_mutex);

        // Make sure there are no long delay timers (ideally we should just flush the queue but that's harder)

        while (is->pictq_size && !is->videoq.abort_request) {

            SDL_CondWait(is->pictq_cond, is->pictq_mutex);

        }

        is->video_current_pos = -1;

        is->frame_last_pts = AV_NOPTS_VALUE;

        is->frame_last_duration = 0;

        is->frame_timer = (double)av_gettime() / 1000000.0;

        is->frame_last_dropped_pts = AV_NOPTS_VALUE;

        SDL_UnlockMutex(is->pictq_mutex);

        return 0;

    }

    if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)

        return 0;

    if (got_picture) {

        int ret = 1;

        if (decoder_reorder_pts == -1) {

            *pts = av_frame_get_best_effort_timestamp(frame);

        } else if (decoder_reorder_pts) {

            *pts = frame->pkt_pts;

        } else {

            *pts = frame->pkt_dts;

        }

        if (*pts == AV_NOPTS_VALUE) {

            *pts = 0;

        }

        if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {

            SDL_LockMutex(is->pictq_mutex);

            if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {

                double clockdiff = get_video_clock(is) - get_master_clock(is);

                double dpts = av_q2d(is->video_st->time_base) * *pts;

                double ptsdiff = dpts - is->frame_last_pts;

                if (!isnan(clockdiff) && fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&

                     ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&

                     clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {

                    is->frame_last_dropped_pos = pkt->pos;

                    is->frame_last_dropped_pts = dpts;

                    is->frame_drops_early++;

                    ret = 0;

                }

            }

            SDL_UnlockMutex(is->pictq_mutex);

        }

        return ret;

    }

    return 0;

}


void ImageLoader::DecodeRequest::Trace(blink::Visitor* visitor) {
  visitor->Trace(resolver_);
  visitor->Trace(loader_);
}


static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,
  Image *image, ExceptionInfo *exception)
{
  MagickBooleanType
    logging,
    status;

  MngInfo
    *mng_info;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()");
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
  if (status == MagickFalse)
    return(status);
  if ((image->columns > 65535UL) || (image->rows > 65535UL))
    ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");

  /*
    Allocate a MngInfo structure.
  */
  mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
  if (mng_info == (MngInfo *) NULL)
    ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
  /*
    Initialize members of the MngInfo structure.
  */
  (void) memset(mng_info,0,sizeof(MngInfo));
  mng_info->image=image;

  (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n");

  status=WriteOneJNGImage(mng_info,image_info,image,exception);
  mng_info=MngInfoFreeStruct(mng_info);
  (void) CloseBlob(image);

  (void) CatchImageException(image);
  if (logging != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteJNGImage()");
  return(status);
}


const WTF::AtomicString& Bluetooth::InterfaceName() const {
  return event_type_names::kAdvertisementreceived;
}


static inline void decode4x4 ( GetBitContext * gb , uint8_t * dst , int linesize ) {
 int i , j , v [ 2 ] ;
 switch ( get_bits ( gb , 2 ) ) {
 case 1 : v [ 0 ] = get_bits ( gb , 8 ) ;
 for ( j = 0 ;
 j < 4 ;
 j ++ ) memset ( dst + j * linesize , v [ 0 ] , 4 ) ;
 break ;
 case 2 : v [ 0 ] = get_bits ( gb , 8 ) ;
 v [ 1 ] = get_bits ( gb , 8 ) ;
 for ( j = 2 ;
 j >= 0 ;
 j -= 2 ) {
 for ( i = 0 ;
 i < 4 ;
 i ++ ) dst [ j * linesize + i ] = v [ get_bits1 ( gb ) ] ;
 for ( i = 0 ;
 i < 4 ;
 i ++ ) dst [ ( j + 1 ) * linesize + i ] = v [ get_bits1 ( gb ) ] ;
 }
 break ;
 case 3 : for ( j = 0 ;
 j < 4 ;
 j += 2 ) for ( i = 0 ;
 i < 4 ;
 i += 2 ) decode2x2 ( gb , dst + j * linesize + i , linesize ) ;
 }
 }


QEvent::Type GetPrepareToCloseBypassEventType() {
  static int g_event_type = QEvent::registerEventType();
  return QEvent::Type(g_event_type);
}


static int vtd_page_walk_level(dma_addr_t addr, uint64_t start,

                               uint64_t end, vtd_page_walk_hook hook_fn,

                               void *private, uint32_t level,

                               bool read, bool write, bool notify_unmap)

{

    bool read_cur, write_cur, entry_valid;

    uint32_t offset;

    uint64_t slpte;

    uint64_t subpage_size, subpage_mask;

    IOMMUTLBEntry entry;

    uint64_t iova = start;

    uint64_t iova_next;

    int ret = 0;

    trace_vtd_page_walk_level(addr, level, start, end);

    subpage_size = 1ULL << vtd_slpt_level_shift(level);

    subpage_mask = vtd_slpt_level_page_mask(level);

    while (iova < end) {

        iova_next = (iova & subpage_mask) + subpage_size;

        offset = vtd_iova_level_offset(iova, level);

        slpte = vtd_get_slpte(addr, offset);

        if (slpte == (uint64_t)-1) {

            trace_vtd_page_walk_skip_read(iova, iova_next);

            goto next;

        }

        if (vtd_slpte_nonzero_rsvd(slpte, level)) {

            trace_vtd_page_walk_skip_reserve(iova, iova_next);

            goto next;

        }

        /* Permissions are stacked with parents' */

        read_cur = read && (slpte & VTD_SL_R);

        write_cur = write && (slpte & VTD_SL_W);

        /*

         * As long as we have either read/write permission, this is a

         * valid entry. The rule works for both page entries and page

         * table entries.

         */

        entry_valid = read_cur | write_cur;

        if (vtd_is_last_slpte(slpte, level)) {

            entry.target_as = &address_space_memory;

            entry.iova = iova & subpage_mask;

            /* NOTE: this is only meaningful if entry_valid == true */

            entry.translated_addr = vtd_get_slpte_addr(slpte);

            entry.addr_mask = ~subpage_mask;

            entry.perm = IOMMU_ACCESS_FLAG(read_cur, write_cur);

            if (!entry_valid && !notify_unmap) {

                trace_vtd_page_walk_skip_perm(iova, iova_next);

                goto next;

            }

            trace_vtd_page_walk_one(level, entry.iova, entry.translated_addr,

                                    entry.addr_mask, entry.perm);

            if (hook_fn) {

                ret = hook_fn(&entry, private);

                if (ret < 0) {

                    return ret;

                }

            }

        } else {

            if (!entry_valid) {

                trace_vtd_page_walk_skip_perm(iova, iova_next);

                goto next;

            }

            ret = vtd_page_walk_level(vtd_get_slpte_addr(slpte), iova,

                                      MIN(iova_next, end), hook_fn, private,

                                      level - 1, read_cur, write_cur,

                                      notify_unmap);

            if (ret < 0) {

                return ret;

            }

        }

next:

        iova = iova_next;

    }

    return 0;

}


onig_builtin_cmp(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
  int r;
  int slot;
  long lv;
  long rv;
  OnigType  type;
  OnigValue val;
  regex_t* reg;
  enum OP_CMP op;

  reg = args->regex;

  r = onig_get_arg_by_callout_args(args, 0, &type, &val);
  if (r != ONIG_NORMAL) return r;

  if (type == ONIG_TYPE_TAG) {
    r = onig_get_callout_data_by_callout_args(args, val.tag, 0, &type, &val);
    if (r < ONIG_NORMAL) return r;
    else if (r > ONIG_NORMAL)
      lv = 0L;
    else
      lv = val.l;
  }
  else { /* ONIG_TYPE_LONG */
    lv = val.l;
  }

  r = onig_get_arg_by_callout_args(args, 2, &type, &val);
  if (r != ONIG_NORMAL) return r;

  if (type == ONIG_TYPE_TAG) {
    r = onig_get_callout_data_by_callout_args(args, val.tag, 0, &type, &val);
    if (r < ONIG_NORMAL) return r;
    else if (r > ONIG_NORMAL)
      rv = 0L;
    else
      rv = val.l;
  }
  else { /* ONIG_TYPE_LONG */
    rv = val.l;
  }

  slot = 0;
  r = onig_get_callout_data_by_callout_args_self(args, slot, &type, &val);
  if (r < ONIG_NORMAL)
    return r;
  else if (r > ONIG_NORMAL) {
    /* type == void: initial state */
    OnigCodePoint c1, c2;
    UChar* p;

    r = onig_get_arg_by_callout_args(args, 1, &type, &val);
    if (r != ONIG_NORMAL) return r;

    p = val.s.start;
    c1 = ONIGENC_MBC_TO_CODE(reg->enc, p, val.s.end);
    p += ONIGENC_MBC_ENC_LEN(reg->enc, p);
    if (p < val.s.end) {
      c2 = ONIGENC_MBC_TO_CODE(reg->enc, p, val.s.end);
      p += ONIGENC_MBC_ENC_LEN(reg->enc, p);
      if (p != val.s.end)  return ONIGERR_INVALID_CALLOUT_ARG;
    }
    else
      c2 = 0;

    switch (c1) {
    case '=':
      if (c2 != '=') return ONIGERR_INVALID_CALLOUT_ARG;
      op = OP_EQ;
      break;
    case '!':
      if (c2 != '=') return ONIGERR_INVALID_CALLOUT_ARG;
      op = OP_NE;
      break;
    case '<':
      if (c2 == '=') op = OP_LE;
      else if (c2 == 0) op = OP_LT;
      else  return ONIGERR_INVALID_CALLOUT_ARG;
      break;
    case '>':
      if (c2 == '=') op = OP_GE;
      else if (c2 == 0) op = OP_GT;
      else  return ONIGERR_INVALID_CALLOUT_ARG;
      break;
    default:
      return ONIGERR_INVALID_CALLOUT_ARG;
      break;
    }
    val.l = (long )op;
    r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
    if (r != ONIG_NORMAL) return r;
  }
  else {
    op = (enum OP_CMP )val.l;
  }

  switch (op) {
  case OP_EQ: r = (lv == rv); break;
  case OP_NE: r = (lv != rv); break;
  case OP_LT: r = (lv <  rv); break;
  case OP_GT: r = (lv >  rv); break;
  case OP_LE: r = (lv <= rv); break;
  case OP_GE: r = (lv >= rv); break;
  }

  return r == 0 ? ONIG_CALLOUT_FAIL : ONIG_CALLOUT_SUCCESS;
}


bool Document::hasSVGRootNode() const
{
    return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
}


OMXNodeInstance::OMXNodeInstance(
        OMX *owner, const sp<IOMXObserver> &observer, const char *name)
 : mOwner(owner),
      mNodeID(0),
      mHandle(NULL),
      mObserver(observer),
      mDying(false),
      mBufferIDCount(0)
{
    mName = ADebug::GetDebugName(name);
    DEBUG = ADebug::GetDebugLevelFromProperty(name, "debug.stagefright.omx-debug");
    ALOGV("debug level for %s is %d", name, DEBUG);
    DEBUG_BUMP = DEBUG;
    mNumPortBuffers[0] = 0;
    mNumPortBuffers[1] = 0;
    mDebugLevelBumpPendingBuffers[0] = 0;
    mDebugLevelBumpPendingBuffers[1] = 0;
    mMetadataType[0] = kMetadataBufferTypeInvalid;
    mMetadataType[1] = kMetadataBufferTypeInvalid;
    mIsSecure = AString(name).endsWith(".secure");
}


static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
{
	struct vm_area_struct *prev;
	struct rb_node **rb_link, *rb_parent;

	if (find_vma_links(mm, vma->vm_start, vma->vm_end,
			   &prev, &rb_link, &rb_parent))
		BUG();
	__vma_link(mm, vma, prev, rb_link, rb_parent);
	mm->map_count++;
}