static void proc_flush_task_mnt(struct vfsmount *mnt, pid_t pid, pid_t tgid)
{
	struct dentry *dentry, *leader, *dir;
	char buf[PROC_NUMBUF];
	struct qstr name;

	name.name = buf;
	name.len = snprintf(buf, sizeof(buf), "%d", pid);
	dentry = d_hash_and_lookup(mnt->mnt_root, &name);
	if (dentry) {
		shrink_dcache_parent(dentry);
		d_drop(dentry);
		dput(dentry);
	}

	name.name = buf;
	name.len = snprintf(buf, sizeof(buf), "%d", tgid);
	leader = d_hash_and_lookup(mnt->mnt_root, &name);
	if (!leader)
		goto out;

	name.name = "task";
	name.len = strlen(name.name);
	dir = d_hash_and_lookup(leader, &name);
	if (!dir)
		goto out_put_leader;

	name.name = buf;
	name.len = snprintf(buf, sizeof(buf), "%d", pid);
	dentry = d_hash_and_lookup(dir, &name);
	if (dentry) {
		shrink_dcache_parent(dentry);
		d_drop(dentry);
		dput(dentry);
	}

	dput(dir);
out_put_leader:
	dput(leader);
out:
	return;
}


bool HHVM_FUNCTION(key_exists,
                   const Variant& key,
                   const Variant& search) {
  return HHVM_FN(array_key_exists)(key, search);
}


 virtual status_t configureVideoTunnelMode(
            node_id node, OMX_U32 portIndex, OMX_BOOL tunneled,
            OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) {
 Parcel data, reply;
        data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
        data.writeInt32((int32_t)node);
        data.writeInt32(portIndex);
        data.writeInt32((int32_t)tunneled);
        data.writeInt32(audioHwSync);

         remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply);

         status_t err = reply.readInt32();
        if (sidebandHandle) {
             *sidebandHandle = (native_handle_t *)reply.readNativeHandle();
         }
         return err;
 }


static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
                                           const char* logname)
{
  uchar *command_buffer= NULL;
  size_t command_size= 0;
  ulong len= 0;
  uint logname_len= 0;
  uint server_id= 0;
  NET* net= NULL;
  my_off_t old_off= start_position_mot;
  char fname[FN_REFLEN + 1];
  char log_file_name[FN_REFLEN + 1];
  Exit_status retval= OK_CONTINUE;
  enum enum_server_command command= COM_END;

  DBUG_ENTER("dump_remote_log_entries");

  fname[0]= log_file_name[0]= 0;

  /*
    Even if we already read one binlog (case of >=2 binlogs on command line),
    we cannot re-use the same connection as before, because it is now dead
    (COM_BINLOG_DUMP kills the thread when it finishes).
  */
  if ((retval= safe_connect()) != OK_CONTINUE)
    DBUG_RETURN(retval);
  net= &mysql->net;

  if ((retval= check_master_version()) != OK_CONTINUE)
    DBUG_RETURN(retval);

  /*
    Fake a server ID to log continously. This will show as a
    slave on the mysql server.
  */
  server_id= ((to_last_remote_log && stop_never) ? stop_never_server_id : 0);
  size_t tlen = strlen(logname);
  if (tlen > UINT_MAX)
  {
    error("Log name too long.");
    DBUG_RETURN(ERROR_STOP);
  }
  const uint BINLOG_NAME_INFO_SIZE= logname_len= tlen;

  if (opt_remote_proto == BINLOG_DUMP_NON_GTID)
  {
    command= COM_BINLOG_DUMP;
    size_t allocation_size= ::BINLOG_POS_OLD_INFO_SIZE +
      BINLOG_NAME_INFO_SIZE + ::BINLOG_FLAGS_INFO_SIZE +
      ::BINLOG_SERVER_ID_INFO_SIZE + 1;
    if (!(command_buffer= (uchar *) my_malloc(PSI_NOT_INSTRUMENTED,
                                              allocation_size, MYF(MY_WME))))
    {
      error("Got fatal error allocating memory.");
      DBUG_RETURN(ERROR_STOP);
    }
    uchar* ptr_buffer= command_buffer;

    /*
      COM_BINLOG_DUMP accepts only 4 bytes for the position, so
      we are forced to cast to uint32.
    */
    int4store(ptr_buffer, (uint32) start_position);
    ptr_buffer+= ::BINLOG_POS_OLD_INFO_SIZE;
    int2store(ptr_buffer, binlog_flags);
    ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE;
    int4store(ptr_buffer, server_id);
    ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE;
    memcpy(ptr_buffer, logname, BINLOG_NAME_INFO_SIZE);
    ptr_buffer+= BINLOG_NAME_INFO_SIZE;

    command_size= ptr_buffer - command_buffer;
    DBUG_ASSERT(command_size == (allocation_size - 1));
  }
  else
  {
    command= COM_BINLOG_DUMP_GTID;

    global_sid_lock->rdlock();

    // allocate buffer
    size_t encoded_data_size= gtid_set_excluded->get_encoded_length();
    size_t allocation_size=
      ::BINLOG_FLAGS_INFO_SIZE + ::BINLOG_SERVER_ID_INFO_SIZE +
      ::BINLOG_NAME_SIZE_INFO_SIZE + BINLOG_NAME_INFO_SIZE +
      ::BINLOG_POS_INFO_SIZE + ::BINLOG_DATA_SIZE_INFO_SIZE +
      encoded_data_size + 1;
    if (!(command_buffer= (uchar *) my_malloc(PSI_NOT_INSTRUMENTED,
                                              allocation_size, MYF(MY_WME))))
    {
      error("Got fatal error allocating memory.");
      global_sid_lock->unlock();
      DBUG_RETURN(ERROR_STOP);
    }
    uchar* ptr_buffer= command_buffer;

    int2store(ptr_buffer, binlog_flags);
    ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE;
    int4store(ptr_buffer, server_id);
    ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE;
    int4store(ptr_buffer, BINLOG_NAME_INFO_SIZE);
    ptr_buffer+= ::BINLOG_NAME_SIZE_INFO_SIZE;
    memcpy(ptr_buffer, logname, BINLOG_NAME_INFO_SIZE);
    ptr_buffer+= BINLOG_NAME_INFO_SIZE;
    int8store(ptr_buffer, start_position);
    ptr_buffer+= ::BINLOG_POS_INFO_SIZE;
    int4store(ptr_buffer, encoded_data_size);
    ptr_buffer+= ::BINLOG_DATA_SIZE_INFO_SIZE;
    gtid_set_excluded->encode(ptr_buffer);
    ptr_buffer+= encoded_data_size;

    global_sid_lock->unlock();

    command_size= ptr_buffer - command_buffer;
    DBUG_ASSERT(command_size == (allocation_size - 1));
  }

  if (simple_command(mysql, command, command_buffer, command_size, 1))
  {
    error("Got fatal error sending the log dump command.");
    my_free(command_buffer);
    DBUG_RETURN(ERROR_STOP);
  }
  my_free(command_buffer);

  for (;;)
  {
    const char *error_msg= NULL;
    Log_event *ev= NULL;
    Log_event_type type= UNKNOWN_EVENT;

    len= cli_safe_read(mysql);
    if (len == packet_error)
    {
      error("Got error reading packet from server: %s", mysql_error(mysql));
      DBUG_RETURN(ERROR_STOP);
    }
    if (len < 8 && net->read_pos[0] == 254)
      break; // end of data
    DBUG_PRINT("info",( "len: %lu  net->read_pos[5]: %d\n",
			len, net->read_pos[5]));
    /*
      In raw mode We only need the full event details if it is a
      ROTATE_EVENT or FORMAT_DESCRIPTION_EVENT
    */

    type= (Log_event_type) net->read_pos[1 + EVENT_TYPE_OFFSET];

    /*
      Ignore HEARBEAT events. They can show up if mysqlbinlog is
      running with:

        --read-from-remote-server
        --read-from-remote-master=BINLOG-DUMP-GTIDS'
        --stop-never
        --stop-never-slave-server-id

      i.e., acting as a fake slave.
    */
    if (type == HEARTBEAT_LOG_EVENT)
      continue;

    if (!raw_mode || (type == ROTATE_EVENT) || (type == FORMAT_DESCRIPTION_EVENT))
    {
      if (!(ev= Log_event::read_log_event((const char*) net->read_pos + 1 ,
                                          len - 1, &error_msg,
                                          glob_description_event,
                                          opt_verify_binlog_checksum)))
      {
        error("Could not construct log event object: %s", error_msg);
        DBUG_RETURN(ERROR_STOP);
      }
      /*
        If reading from a remote host, ensure the temp_buf for the
        Log_event class is pointing to the incoming stream.
      */
      ev->register_temp_buf((char *) net->read_pos + 1);
    }
    if (raw_mode || (type != LOAD_EVENT))
    {
      /*
        If this is a Rotate event, maybe it's the end of the requested binlog;
        in this case we are done (stop transfer).
        This is suitable for binlogs, not relay logs (but for now we don't read
        relay logs remotely because the server is not able to do that). If one
        day we read relay logs remotely, then we will have a problem with the
        detection below: relay logs contain Rotate events which are about the
        binlogs, so which would trigger the end-detection below.
      */
      if (type == ROTATE_EVENT)
      {
        Rotate_log_event *rev= (Rotate_log_event *)ev;
        /*
          If this is a fake Rotate event, and not about our log, we can stop
          transfer. If this a real Rotate event (so it's not about our log,
          it's in our log describing the next log), we print it (because it's
          part of our log) and then we will stop when we receive the fake one
          soon.
        */
        if (raw_mode)
        {
          if (output_file != 0)
          {
            my_snprintf(log_file_name, sizeof(log_file_name), "%s%s",
                        output_file, rev->new_log_ident);
          }
          else
          {
            my_stpcpy(log_file_name, rev->new_log_ident);
          }
        }

        if (rev->when.tv_sec == 0)
        {
          if (!to_last_remote_log)
          {
            if ((rev->ident_len != logname_len) ||
                memcmp(rev->new_log_ident, logname, logname_len))
            {
              DBUG_RETURN(OK_CONTINUE);
            }
            /*
              Otherwise, this is a fake Rotate for our log, at the very
              beginning for sure. Skip it, because it was not in the original
              log. If we are running with to_last_remote_log, we print it,
              because it serves as a useful marker between binlogs then.
            */
            continue;
          }
          /*
             Reset the value of '# at pos' field shown against first event of
             next binlog file (fake rotate) picked by mysqlbinlog --to-last-log
         */
          old_off= start_position_mot;
          len= 1; // fake Rotate, so don't increment old_off
        }
      }
      else if (type == FORMAT_DESCRIPTION_EVENT)
      {
        /*
          This could be an fake Format_description_log_event that server
          (5.0+) automatically sends to a slave on connect, before sending
          a first event at the requested position.  If this is the case,
          don't increment old_off. Real Format_description_log_event always
          starts from BIN_LOG_HEADER_SIZE position.
        */
        // fake event when not in raw mode, don't increment old_off
        if ((old_off != BIN_LOG_HEADER_SIZE) && (!raw_mode))
          len= 1;
        if (raw_mode)
        {
          if (result_file && (result_file != stdout))
            my_fclose(result_file, MYF(0));
          if (!(result_file = my_fopen(log_file_name, O_WRONLY | O_BINARY,
                                       MYF(MY_WME))))
          {
            error("Could not create log file '%s'", log_file_name);
            DBUG_RETURN(ERROR_STOP);
          }
          my_fwrite(result_file, (const uchar*) BINLOG_MAGIC,
                    BIN_LOG_HEADER_SIZE, MYF(0));
          /*
            Need to handle these events correctly in raw mode too
            or this could get messy
          */
          delete glob_description_event;
          glob_description_event= (Format_description_log_event*) ev;
          print_event_info->common_header_len= glob_description_event->common_header_len;
          ev->temp_buf= 0;
          ev= 0;
        }
      }

      if (type == LOAD_EVENT)
      {
        DBUG_ASSERT(raw_mode);
        warning("Attempting to load a remote pre-4.0 binary log that contains "
                "LOAD DATA INFILE statements. The file will not be copied from "
                "the remote server. ");
      }

      if (raw_mode)
      {
        my_fwrite(result_file, net->read_pos + 1 , len - 1, MYF(0));
        if (ev)
        {
          ev->temp_buf=0;
          delete ev;
        }
      }
      else
      {
        retval= process_event(print_event_info, ev, old_off, logname);
      }

      if (retval != OK_CONTINUE)
        DBUG_RETURN(retval);
    }
    else
    {
      Load_log_event *le= (Load_log_event*)ev;
      const char *old_fname= le->fname;
      uint old_len= le->fname_len;
      File file;

      if ((file= load_processor.prepare_new_file_for_old_format(le,fname)) < 0)
        DBUG_RETURN(ERROR_STOP);

      retval= process_event(print_event_info, ev, old_off, logname);
      if (retval != OK_CONTINUE)
      {
        my_close(file,MYF(MY_WME));
        DBUG_RETURN(retval);
      }
      retval= load_processor.load_old_format_file(net,old_fname,old_len,file);
      my_close(file,MYF(MY_WME));
      if (retval != OK_CONTINUE)
        DBUG_RETURN(retval);
    }
    /*
      Let's adjust offset for remote log as for local log to produce
      similar text and to have --stop-position to work identically.
    */
    old_off+= len-1;
  }

  DBUG_RETURN(OK_CONTINUE);
}


static void firmware_config_callback(UNUSED_ATTR bool success) {
  LOG_INFO("%s", __func__);
  firmware_is_configured = true;
  non_repeating_timer_cancel(startup_timer);

  future_ready(startup_future, FUTURE_SUCCESS);
  startup_future = NULL;
}


  PendingPacket(scoped_ptr<VideoPacket> packet, const base::Closure& done)
      : packet_(packet.Pass()),
        done_runner_(done) {
  }


static noinline void do_low_address(struct pt_regs *regs, long int_code,
				    unsigned long trans_exc_code)
{
	/* Low-address protection hit in kernel mode means
	   NULL pointer write access in kernel mode.  */
	if (regs->psw.mask & PSW_MASK_PSTATE) {
		/* Low-address protection hit in user mode 'cannot happen'. */
		die ("Low-address protection", regs, int_code);
		do_exit(SIGKILL);
	}

	do_no_context(regs, int_code, trans_exc_code);
}


void __fastcall TSCPFileSystem::EnsureLocation()
{
  if (!FCachedDirectoryChange.IsEmpty())
  {
    FTerminal->LogEvent(FORMAT(L"Locating to cached directory \"%s\".",
      (FCachedDirectoryChange)));
    UnicodeString Directory = FCachedDirectoryChange;
    FCachedDirectoryChange = L"";
    try
    {
      ChangeDirectory(Directory);
    }
    catch(...)
    {
      // when location to cached directory fails, pretend again
      // location in cached directory
      // here used to be check (CurrentDirectory != Directory), but it is
      // false always (current directory is already set to cached directory),
      // making the condition below useless. check removed.
      if (FTerminal->Active)
      {
        FCachedDirectoryChange = Directory;
      }
      throw;
    }
  }
}


QuotaDatabase* database() const { return database_; }


static CURLcode pop3_list(struct connectdata *conn)
{
  CURLcode result = CURLE_OK;
  struct pop3_conn *pop3c = &conn->proto.pop3c;

  if(pop3c->mailbox[0] != '\0')
    result = Curl_pp_sendf(&conn->proto.pop3c.pp, "LIST %s", pop3c->mailbox);
  else
    result = Curl_pp_sendf(&conn->proto.pop3c.pp, "LIST");
  if(result)
    return result;

  if(pop3c->mailbox[0] != '\0')
    state(conn, POP3_LIST_SINGLE);
  else
    state(conn, POP3_LIST);
  return result;
}


static BOOL rdp_recv_server_set_keyboard_indicators_pdu(rdpRdp* rdp, wStream* s)
{
	UINT16 unitId;
	UINT16 ledFlags;
	rdpContext* context = rdp->instance->context;

	if (Stream_GetRemainingLength(s) < 4)
		return FALSE;

	Stream_Read_UINT16(s, unitId);   /* unitId (2 bytes) */
	Stream_Read_UINT16(s, ledFlags); /* ledFlags (2 bytes) */
	IFCALL(context->update->SetKeyboardIndicators, context, ledFlags);
	return TRUE;
}


static int ivi_create_huff_from_desc ( const IVIHuffDesc * cb , VLC * vlc , int flag ) {
 int pos , i , j , codes_per_row , prefix , not_last_row ;
 uint16_t codewords [ 256 ] ;
 uint8_t bits [ 256 ] ;
 pos = 0 ;
 for ( i = 0 ;
 i < cb -> num_rows ;
 i ++ ) {
 codes_per_row = 1 << cb -> xbits [ i ] ;
 not_last_row = ( i != cb -> num_rows - 1 ) ;
 prefix = ( ( 1 << i ) - 1 ) << ( cb -> xbits [ i ] + not_last_row ) ;
 for ( j = 0 ;
 j < codes_per_row ;
 j ++ ) {
 if ( pos >= 256 ) break ;
 bits [ pos ] = i + cb -> xbits [ i ] + not_last_row ;
 if ( bits [ pos ] > IVI_VLC_BITS ) return - 1 ;
 codewords [ pos ] = inv_bits ( ( prefix | j ) , bits [ pos ] ) ;
 if ( ! bits [ pos ] ) bits [ pos ] = 1 ;
 pos ++ ;
 }
 }
 return init_vlc ( vlc , IVI_VLC_BITS , pos , bits , 1 , 1 , codewords , 2 , 2 , ( flag ? INIT_VLC_USE_NEW_STATIC : 0 ) | INIT_VLC_LE ) ;
 }


static void coroutine_fn v9fs_create(void *opaque)
{
    int32_t fid;
    int err = 0;
    size_t offset = 7;
    V9fsFidState *fidp;
    V9fsQID qid;
    int32_t perm;
    int8_t mode;
    V9fsPath path;
    struct stat stbuf;
    V9fsString name;
    V9fsString extension;
    int iounit;
    V9fsPDU *pdu = opaque;
    V9fsState *s = pdu->s;

    v9fs_path_init(&path);
    v9fs_string_init(&name);
    v9fs_string_init(&extension);
    err = pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name,
                        &perm, &mode, &extension);
    if (err < 0) {
        goto out_nofid;
    }
    trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode);

    if (name_is_illegal(name.data)) {
        err = -ENOENT;
        goto out_nofid;
    }

    if (!strcmp(".", name.data) || !strcmp("..", name.data)) {
        err = -EEXIST;
        goto out_nofid;
    }

    fidp = get_fid(pdu, fid);
    if (fidp == NULL) {
        err = -EINVAL;
        goto out_nofid;
    }
    if (fidp->fid_type != P9_FID_NONE) {
        err = -EINVAL;
        goto out;
    }
    if (perm & P9_STAT_MODE_DIR) {
        err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777,
                            fidp->uid, -1, &stbuf);
        if (err < 0) {
            goto out;
        }
        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
        if (err < 0) {
            goto out;
        }
        v9fs_path_write_lock(s);
        v9fs_path_copy(&fidp->path, &path);
        v9fs_path_unlock(s);
        err = v9fs_co_opendir(pdu, fidp);
        if (err < 0) {
            goto out;
        }
        fidp->fid_type = P9_FID_DIR;
    } else if (perm & P9_STAT_MODE_SYMLINK) {
        err = v9fs_co_symlink(pdu, fidp, &name,
                              extension.data, -1 , &stbuf);
        if (err < 0) {
            goto out;
        }
        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
        if (err < 0) {
            goto out;
        }
        v9fs_path_write_lock(s);
        v9fs_path_copy(&fidp->path, &path);
        v9fs_path_unlock(s);
    } else if (perm & P9_STAT_MODE_LINK) {
        int32_t ofid = atoi(extension.data);
        V9fsFidState *ofidp = get_fid(pdu, ofid);
        if (ofidp == NULL) {
            err = -EINVAL;
            goto out;
        }
        err = v9fs_co_link(pdu, ofidp, fidp, &name);
        put_fid(pdu, ofidp);
        if (err < 0) {
            goto out;
        }
        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
        if (err < 0) {
            fidp->fid_type = P9_FID_NONE;
            goto out;
        }
        v9fs_path_write_lock(s);
        v9fs_path_copy(&fidp->path, &path);
        v9fs_path_unlock(s);
        err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
        if (err < 0) {
            fidp->fid_type = P9_FID_NONE;
            goto out;
        }
    } else if (perm & P9_STAT_MODE_DEVICE) {
        char ctype;
        uint32_t major, minor;
        mode_t nmode = 0;

        if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) {
            err = -errno;
            goto out;
        }

        switch (ctype) {
        case 'c':
            nmode = S_IFCHR;
            break;
        case 'b':
            nmode = S_IFBLK;
            break;
        default:
            err = -EIO;
            goto out;
        }

        nmode |= perm & 0777;
        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
                            makedev(major, minor), nmode, &stbuf);
        if (err < 0) {
            goto out;
        }
        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
        if (err < 0) {
            goto out;
        }
        v9fs_path_write_lock(s);
        v9fs_path_copy(&fidp->path, &path);
        v9fs_path_unlock(s);
    } else if (perm & P9_STAT_MODE_NAMED_PIPE) {
        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
                            0, S_IFIFO | (perm & 0777), &stbuf);
        if (err < 0) {
            goto out;
        }
        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
        if (err < 0) {
            goto out;
        }
        v9fs_path_write_lock(s);
        v9fs_path_copy(&fidp->path, &path);
        v9fs_path_unlock(s);
    } else if (perm & P9_STAT_MODE_SOCKET) {
        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,
                            0, S_IFSOCK | (perm & 0777), &stbuf);
        if (err < 0) {
            goto out;
        }
        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);
        if (err < 0) {
            goto out;
        }
        v9fs_path_write_lock(s);
        v9fs_path_copy(&fidp->path, &path);
        v9fs_path_unlock(s);
    } else {
        err = v9fs_co_open2(pdu, fidp, &name, -1,
                            omode_to_uflags(mode)|O_CREAT, perm, &stbuf);
        if (err < 0) {
            goto out;
        }
        fidp->fid_type = P9_FID_FILE;
        fidp->open_flags = omode_to_uflags(mode);
        if (fidp->open_flags & O_EXCL) {
            /*
             * We let the host file system do O_EXCL check
             * We should not reclaim such fd
             */
            fidp->flags |= FID_NON_RECLAIMABLE;
        }
    }
    iounit = get_iounit(pdu, &fidp->path);
    stat_to_qid(&stbuf, &qid);
    err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);
    if (err < 0) {
        goto out;
    }
    err += offset;
    trace_v9fs_create_return(pdu->tag, pdu->id,
                             qid.type, qid.version, qid.path, iounit);
out:
    put_fid(pdu, fidp);
out_nofid:
   pdu_complete(pdu, err);
   v9fs_string_free(&name);
   v9fs_string_free(&extension);
   v9fs_path_free(&path);
}


static void virtio_init_pci(VirtIOPCIProxy *proxy, VirtIODevice *vdev,

                            uint16_t vendor, uint16_t device,

                            uint16_t class_code, uint8_t pif)

{

    uint8_t *config;

    uint32_t size;

    proxy->vdev = vdev;

    config = proxy->pci_dev.config;

    pci_config_set_vendor_id(config, vendor);

    pci_config_set_device_id(config, device);

    config[0x08] = VIRTIO_PCI_ABI_VERSION;

    config[0x09] = pif;

    pci_config_set_class(config, class_code);

    config[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL;

    config[0x2c] = vendor & 0xFF;

    config[0x2d] = (vendor >> 8) & 0xFF;

    config[0x2e] = vdev->device_id & 0xFF;

    config[0x2f] = (vdev->device_id >> 8) & 0xFF;

    config[0x3d] = 1;

    if (vdev->nvectors && !msix_init(&proxy->pci_dev, vdev->nvectors, 1, 0,

                                     TARGET_PAGE_SIZE)) {

        pci_register_bar(&proxy->pci_dev, 1,

                         msix_bar_size(&proxy->pci_dev),

                         PCI_ADDRESS_SPACE_MEM,

                         msix_mmio_map);

    } else

        vdev->nvectors = 0;

    proxy->pci_dev.config_write = virtio_write_config;

    size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev) + vdev->config_len;

    if (size & (size-1))

        size = 1 << qemu_fls(size);

    pci_register_bar(&proxy->pci_dev, 0, size, PCI_ADDRESS_SPACE_IO,

                           virtio_map);

    qemu_register_reset(virtio_pci_reset, proxy);

    virtio_bind_device(vdev, &virtio_pci_bindings, proxy);

}


enum message_cte message_decoder_parse_cte ( struct message_header_line * hdr ) {
 struct rfc822_parser_context parser ;
 enum message_cte message_cte ;
 string_t * value ;
 value = t_str_new ( 64 ) ;
 rfc822_parser_init ( & parser , hdr -> full_value , hdr -> full_value_len , NULL ) ;
 rfc822_skip_lwsp ( & parser ) ;
 ( void ) rfc822_parse_mime_token ( & parser , value ) ;
 message_cte = MESSAGE_CTE_UNKNOWN ;
 switch ( str_len ( value ) ) {
 case 4 : if ( i_memcasecmp ( str_data ( value ) , "7bit" , 4 ) == 0 || i_memcasecmp ( str_data ( value ) , "8bit" , 4 ) == 0 ) message_cte = MESSAGE_CTE_78BIT ;
 break ;
 case 6 : if ( i_memcasecmp ( str_data ( value ) , "base64" , 6 ) == 0 ) message_cte = MESSAGE_CTE_BASE64 ;
 else if ( i_memcasecmp ( str_data ( value ) , "binary" , 6 ) == 0 ) message_cte = MESSAGE_CTE_BINARY ;
 break ;
 case 16 : if ( i_memcasecmp ( str_data ( value ) , "quoted-printable" , 16 ) == 0 ) message_cte = MESSAGE_CTE_QP ;
 break ;
 }
 rfc822_parser_deinit ( & parser ) ;
 return message_cte ;
 }


multi_client_disconnect_script(struct multi_instance *mi)
{
    if ((mi->context.c2.context_auth == CAS_SUCCEEDED && mi->connection_established_flag)
        || mi->context.c2.context_auth == CAS_PARTIAL)
    {
        multi_client_disconnect_setenv(mi);

        if (plugin_defined(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT))
        {
            if (plugin_call(mi->context.plugins, OPENVPN_PLUGIN_CLIENT_DISCONNECT, NULL, NULL, mi->context.c2.es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
            {
                msg(M_WARN, "WARNING: client-disconnect plugin call failed");
            }
        }

        if (mi->context.options.client_disconnect_script)
        {
            struct argv argv = argv_new();
            setenv_str(mi->context.c2.es, "script_type", "client-disconnect");
            argv_parse_cmd(&argv, mi->context.options.client_disconnect_script);
            openvpn_run_script(&argv, mi->context.c2.es, 0, "--client-disconnect");
            argv_free(&argv);
        }
#ifdef MANAGEMENT_DEF_AUTH
        if (management)
        {
            management_notify_client_close(management, &mi->context.c2.mda_context, mi->context.c2.es);
        }
#endif

    }
}


entry_guard_set_filtered_flags(const or_options_t *options,
                               guard_selection_t *gs,
                               entry_guard_t *guard)
{
  unsigned was_filtered = guard->is_filtered_guard;
  guard->is_filtered_guard = 0;
  guard->is_usable_filtered_guard = 0;

  if (entry_guard_passes_filter(options, gs, guard)) {
    guard->is_filtered_guard = 1;

    if (guard->is_reachable != GUARD_REACHABLE_NO)
      guard->is_usable_filtered_guard = 1;

    entry_guard_consider_retry(guard);
  }
  log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
            "reachable_filtered=%d.", entry_guard_describe(guard),
            guard->is_filtered_guard, guard->is_usable_filtered_guard);

  if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
    /* This guard might now be primary or nonprimary. */
    gs->primary_guards_up_to_date = 0;
  }
}


bool ByteVector::operator==(const char *s) const
{
  if(d->size != ::strlen(s))
    return false;

  return ::memcmp(data(), s, d->size) == 0;
}


TestPaintArtifact& TestPaintArtifact::KnownToBeOpaque() {
  paint_chunks_data_.chunks.back().known_to_be_opaque = true;
  return *this;
}


get_text_gray_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval and
   converting to extended RGB */
{
  ppm_source_ptr source = (ppm_source_ptr)sinfo;
  FILE *infile = source->pub.input_file;
  register JSAMPROW ptr;
  register JSAMPLE *rescale = source->rescale;
  JDIMENSION col;
  unsigned int maxval = source->maxval;
  register int rindex = rgb_red[cinfo->in_color_space];
  register int gindex = rgb_green[cinfo->in_color_space];
  register int bindex = rgb_blue[cinfo->in_color_space];
  register int aindex = alpha_index[cinfo->in_color_space];
  register int ps = rgb_pixelsize[cinfo->in_color_space];

  ptr = source->pub.buffer[0];
  if (maxval == MAXJSAMPLE) {
    if (aindex >= 0)
      GRAY_RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),
                         ptr[aindex] = 0xFF;)
    else
      GRAY_RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),)
  } else {
    if (aindex >= 0)
      GRAY_RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],
                         ptr[aindex] = 0xFF;)
    else
      GRAY_RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],)
  }
  return 1;
}


static inline I2CBus *aux_bridge_get_i2c_bus(AUXTOI2CState *bridge)

{

    return bridge->i2c_bus;

}


void DownloadItemImplDelegate::CheckForFileRemoval(
    DownloadItemImpl* download_item) {}


MagickExport MagickBooleanType PerceptibleImage(Image *image,
  const double epsilon,ExceptionInfo *exception)
{
#define PerceptibleImageTag  "Perceptible/Image"

  CacheView
    *image_view;

  MagickBooleanType
    status;

  MagickOffsetType
    progress;

  ssize_t
    y;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickCoreSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  if (image->storage_class == PseudoClass)
    {
      register ssize_t
        i;

      register PixelInfo
        *magick_restrict q;

      q=image->colormap;
      for (i=0; i < (ssize_t) image->colors; i++)
      {
        q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red),
          epsilon);
        q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green),
          epsilon);
        q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue),
          epsilon);
        q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha),
          epsilon);
        q++;
      }
      return(SyncImage(image,exception));
    }
  /*
    Perceptible image.
  */
  status=MagickTrue;
  progress=0;
  image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static) shared(progress,status) \
    magick_number_threads(image,image,image->rows,1)
#endif
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register ssize_t
      x;

    register Quantum
      *magick_restrict q;

    if (status == MagickFalse)
      continue;
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
    if (q == (Quantum *) NULL)
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      register ssize_t
        i;

      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
      {
        PixelChannel channel = GetPixelChannelChannel(image,i);
        PixelTrait traits = GetPixelChannelTraits(image,channel);
        if (traits == UndefinedPixelTrait)
          continue;
        q[i]=PerceptibleThreshold(q[i],epsilon);
      }
      q+=GetPixelChannels(image);
    }
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
      status=MagickFalse;
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
      {
        MagickBooleanType
          proceed;

#if defined(MAGICKCORE_OPENMP_SUPPORT)
        #pragma omp atomic
#endif
        progress++;
        proceed=SetImageProgress(image,PerceptibleImageTag,progress,
          image->rows);
        if (proceed == MagickFalse)
          status=MagickFalse;
      }
  }
  image_view=DestroyCacheView(image_view);
  return(status);
}


void UrlFetcher::Core::Start(const UrlFetcher::DoneCallback& done_callback) {
  done_callback_ = done_callback;
  network_task_runner_ = request_context_getter_->GetNetworkTaskRunner();
  DCHECK(network_task_runner_);
  network_task_runner_->PostTask(FROM_HERE, base::Bind(
      &UrlFetcher::Core::DoStart, this));
}


append_locale_variants (GPtrArray *array,
                        const gchar *locale)
{
  gchar *language = NULL;
  gchar *territory = NULL;
  gchar *codeset = NULL;
  gchar *modifier = NULL;

  guint mask;
  guint i, j;

  g_return_if_fail (locale != NULL);

  mask = explode_locale (locale, &language, &territory, &codeset, &modifier);

  /* Iterate through all possible combinations, from least attractive
   * to most attractive.
   */
  for (j = 0; j <= mask; ++j)
    {
      i = mask - j;

      if ((i & ~mask) == 0)
        {
          gchar *val = g_strconcat (language,
                                    (i & COMPONENT_TERRITORY) ? territory : "",
                                    (i & COMPONENT_CODESET) ? codeset : "",
                                    (i & COMPONENT_MODIFIER) ? modifier : "",
                                    NULL);
          g_ptr_array_add (array, val);
        }
    }

  g_free (language);
  if (mask & COMPONENT_CODESET)
    g_free (codeset);
  if (mask & COMPONENT_TERRITORY)
    g_free (territory);
  if (mask & COMPONENT_MODIFIER)
    g_free (modifier);
}


ShellContentUtilityClient::ShellContentUtilityClient() {
  if (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kProcessType) == switches::kUtilityProcess)
     network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>();
 }


static int64_t expr_unary(Monitor *mon)

{

    int64_t n;

    char *p;

    int ret;

    switch(*pch) {

    case '+':

        next();

        n = expr_unary(mon);

        break;

    case '-':

        next();

        n = -expr_unary(mon);

        break;

    case '~':

        next();

        n = ~expr_unary(mon);

        break;

    case '(':

        next();

        n = expr_sum(mon);

        if (*pch != ')') {

            expr_error(mon, "')' expected");

        }

        next();

        break;

    case '\'':

        pch++;

        if (*pch == '\0')

            expr_error(mon, "character constant expected");

        n = *pch;

        pch++;

        if (*pch != '\'')

            expr_error(mon, "missing terminating \' character");

        next();

        break;

    case '$':

        {

            char buf[128], *q;

            target_long reg=0;

            pch++;

            q = buf;

            while ((*pch >= 'a' && *pch <= 'z') ||

                   (*pch >= 'A' && *pch <= 'Z') ||

                   (*pch >= '0' && *pch <= '9') ||

                   *pch == '_' || *pch == '.') {

                if ((q - buf) < sizeof(buf) - 1)

                    *q++ = *pch;

                pch++;

            }

            while (qemu_isspace(*pch))

                pch++;

            *q = 0;

            ret = get_monitor_def(&reg, buf);

            if (ret == -1)

                expr_error(mon, "unknown register");

            else if (ret == -2)

                expr_error(mon, "no cpu defined");

            n = reg;

        }

        break;

    case '\0':

        expr_error(mon, "unexpected end of expression");

        n = 0;

        break;

    default:

#if TARGET_PHYS_ADDR_BITS > 32

        n = strtoull(pch, &p, 0);

#else

        n = strtoul(pch, &p, 0);

#endif

        if (pch == p) {

            expr_error(mon, "invalid char in expression");

        }

        pch = p;

        while (qemu_isspace(*pch))

            pch++;

        break;

    }

    return n;

}


int tls1_set_server_sigalgs(SSL *s)
{
    int al;
    size_t i;

    /* Clear any shared signature algorithms */
    OPENSSL_free(s->cert->shared_sigalgs);
    s->cert->shared_sigalgs = NULL;
    s->cert->shared_sigalgslen = 0;
    /* Clear certificate digests and validity flags */
    for (i = 0; i < SSL_PKEY_NUM; i++) {
        s->s3->tmp.md[i] = NULL;
        s->s3->tmp.valid_flags[i] = 0;
    }

    /* If sigalgs received process it. */
    if (s->s3->tmp.peer_sigalgs) {
        if (!tls1_process_sigalgs(s)) {
            SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
            al = SSL_AD_INTERNAL_ERROR;
            goto err;
        }
        /* Fatal error is no shared signature algorithms */
        if (!s->cert->shared_sigalgs) {
            SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
                   SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS);
            al = SSL_AD_ILLEGAL_PARAMETER;
            goto err;
        }
    } else {
        ssl_set_default_md(s);
    }
    return 1;
 err:
    ssl3_send_alert(s, SSL3_AL_FATAL, al);
    return 0;
}


struct sock *ax25_get_socket(ax25_address *my_addr, ax25_address *dest_addr,
	int type)
{
	struct sock *sk = NULL;
	ax25_cb *s;

	spin_lock(&ax25_list_lock);
	ax25_for_each(s, &ax25_list) {
		if (s->sk && !ax25cmp(&s->source_addr, my_addr) &&
		    !ax25cmp(&s->dest_addr, dest_addr) &&
		    s->sk->sk_type == type) {
			sk = s->sk;
			sock_hold(sk);
			break;
		}
	}

	spin_unlock(&ax25_list_lock);

	return sk;
}


String Element::title() const
{
    return String();
}


static uint16_t phys_section_add(PhysPageMap *map,
                                 MemoryRegionSection *section)
{
    /* The physical section number is ORed with a page-aligned
     * pointer to produce the iotlb entries.  Thus it should
     * never overflow into the page-aligned value.
     */
    assert(map->sections_nb < TARGET_PAGE_SIZE);

    if (map->sections_nb == map->sections_nb_alloc) {
        map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
        map->sections = g_renew(MemoryRegionSection, map->sections,
                                map->sections_nb_alloc);
    }
    map->sections[map->sections_nb] = *section;
    memory_region_ref(section->mr);
    return map->sections_nb++;
}


bool CameraClient::previewEnabled() {
    LOG1("previewEnabled (pid %d)", getCallingPid());

 Mutex::Autolock lock(mLock);
 if (checkPidAndHardware() != NO_ERROR) return false;
 return mHardware->previewEnabled();
}


static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
			    struct tipc_sock *tsk)
{
	int err;
	void *hdr;
	struct nlattr *attrs;
	struct net *net = sock_net(skb->sk);
	struct tipc_net *tn = net_generic(net, tipc_net_id);

	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
			  &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
	if (!hdr)
		goto msg_cancel;

	attrs = nla_nest_start(skb, TIPC_NLA_SOCK);
	if (!attrs)
		goto genlmsg_cancel;
	if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid))
		goto attr_msg_cancel;
	if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tn->own_addr))
		goto attr_msg_cancel;

	if (tsk->connected) {
		err = __tipc_nl_add_sk_con(skb, tsk);
		if (err)
			goto attr_msg_cancel;
	} else if (!list_empty(&tsk->publications)) {
		if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
			goto attr_msg_cancel;
	}
	nla_nest_end(skb, attrs);
	genlmsg_end(skb, hdr);

	return 0;

attr_msg_cancel:
	nla_nest_cancel(skb, attrs);
genlmsg_cancel:
	genlmsg_cancel(skb, hdr);
msg_cancel:
	return -EMSGSIZE;
}


void CIRCNetwork::DelServers() {
    for (CServer* pServer : m_vServers) {
        delete pServer;
    }
    m_vServers.clear();
}


static struct dentry *shmem_mount(struct file_system_type *fs_type,
	int flags, const char *dev_name, void *data)
{
	return mount_nodev(fs_type, flags, data, shmem_fill_super);
}


ScriptPromise BluetoothRemoteGATTCharacteristic::readValue(
    ScriptState* scriptState) {
  if (!getGatt()->connected()) {
    return ScriptPromise::rejectWithDOMException(
        scriptState,
        BluetoothRemoteGATTUtils::CreateDOMException(
            BluetoothRemoteGATTUtils::ExceptionType::kGATTServerNotConnected));
  }

  if (!getGatt()->device()->isValidCharacteristic(
          m_characteristic->instance_id)) {
    return ScriptPromise::rejectWithDOMException(
        scriptState,
        BluetoothRemoteGATTUtils::CreateDOMException(
            BluetoothRemoteGATTUtils::ExceptionType::kInvalidCharacteristic));
  }

  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();
  getGatt()->AddToActiveAlgorithms(resolver);

  mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service();
  service->RemoteCharacteristicReadValue(
      m_characteristic->instance_id,
      convertToBaseCallback(
          WTF::bind(&BluetoothRemoteGATTCharacteristic::ReadValueCallback,
                    wrapPersistent(this), wrapPersistent(resolver))));

  return promise;
}


GF_Err gf_isom_flush_chunk(GF_TrackBox *trak, Bool is_final)
{
	GF_Err e;
	u64 data_offset;
	u32 sample_number;
	u8 *chunk_data;
	u32 chunk_size, chunk_alloc;
	if (!trak->chunk_cache) return GF_OK;

	gf_bs_get_content_no_truncate(trak->chunk_cache, &chunk_data, &chunk_size, &chunk_alloc);

	data_offset = gf_isom_datamap_get_offset(trak->Media->information->dataHandler);

	e = gf_isom_datamap_add_data(trak->Media->information->dataHandler, chunk_data, chunk_size);
	if (e) return e;

	sample_number = 1 + trak->Media->information->sampleTable->SampleSize->sampleCount;
	sample_number -= trak->nb_samples_in_cache;

	e = stbl_AddChunkOffset(trak->Media, sample_number, trak->chunk_stsd_idx, data_offset, trak->nb_samples_in_cache);

	if (is_final) {
		gf_free(chunk_data);
		gf_bs_del(trak->chunk_cache);
		trak->chunk_cache = NULL;
	} else {
		gf_bs_reassign_buffer(trak->chunk_cache, chunk_data, chunk_alloc);
	}
	return e;
}


void Document::ViewportDefiningElementDidChange() {
  HTMLBodyElement* body = FirstBodyElement();
  if (!body)
    return;
  LayoutObject* layout_object = body->GetLayoutObject();
  if (layout_object && layout_object->IsLayoutBlock()) {
    layout_object->SetStyle(ComputedStyle::Clone(*layout_object->Style()));
    if (layout_object->HasLayer()) {
      ToLayoutBoxModelObject(layout_object)
          ->Layer()
          ->SetNeeedsCompositingReasonsUpdate();
    }
  }
}


void release_task(struct task_struct * p)
{
	struct task_struct *leader;
	int zap_leader;
repeat:
	tracehook_prepare_release_task(p);
	atomic_dec(&p->user->processes);
	proc_flush_task(p);
	write_lock_irq(&tasklist_lock);
	tracehook_finish_release_task(p);
	__exit_signal(p);

	/*
	 * If we are the last non-leader member of the thread
	 * group, and the leader is zombie, then notify the
	 * group leader's parent process. (if it wants notification.)
	 */
	zap_leader = 0;
	leader = p->group_leader;
	if (leader != p && thread_group_empty(leader) && leader->exit_state == EXIT_ZOMBIE) {
		BUG_ON(task_detached(leader));
		do_notify_parent(leader, leader->exit_signal);
		/*
		 * If we were the last child thread and the leader has
		 * exited already, and the leader's parent ignores SIGCHLD,
		 * then we are the one who should release the leader.
		 *
		 * do_notify_parent() will have marked it self-reaping in
		 * that case.
		 */
		zap_leader = task_detached(leader);

		/*
		 * This maintains the invariant that release_task()
		 * only runs on a task in EXIT_DEAD, just for sanity.
		 */
		if (zap_leader)
			leader->exit_state = EXIT_DEAD;
	}

	write_unlock_irq(&tasklist_lock);
	release_thread(p);
	call_rcu(&p->rcu, delayed_put_task_struct);

	p = leader;
	if (unlikely(zap_leader))
		goto repeat;
}


ShelfWidget::DelegateView::DelegateView(ShelfWidget* shelf_widget)
    : shelf_widget_(shelf_widget),
      focus_cycler_(nullptr),
      opaque_background_(ui::LAYER_SOLID_COLOR) {
  DCHECK(shelf_widget_);
  set_owned_by_client();  // Deleted by DeleteDelegate().

  SetLayoutManager(std::make_unique<views::FillLayout>());
  set_allow_deactivate_on_esc(true);

  UpdateOpaqueBackground();
}


void CSteamNetworkConnectionBase::SNP_PopulateQuickStats( SteamNetworkingQuickConnectionStatus &info, SteamNetworkingMicroseconds usecNow )
{
	info.m_nSendRateBytesPerSecond = SNP_ClampSendRate();
	info.m_cbPendingUnreliable = m_senderState.m_cbPendingUnreliable;
	info.m_cbPendingReliable = m_senderState.m_cbPendingReliable;
	info.m_cbSentUnackedReliable = m_senderState.m_cbSentUnackedReliable;
	if ( GetState() == k_ESteamNetworkingConnectionState_Connected )
	{

		// Accumulate tokens so that we can properly predict when the next time we'll be able to send something is
		SNP_TokenBucket_Accumulate( usecNow );

		//
		// Time until we can send the next packet
		// If anything is already queued, then that will have to go out first.  Round it down
		// to the nearest packet.
		//
		// NOTE: This ignores the precise details of SNP framing.  If there are tons of
		// small packets, it'll actually be worse.  We might be able to approximate that
		// the framing overhead better by also counting up the number of *messages* pending.
		// Probably not worth it here, but if we had that number available, we'd use it.
		int cbPendingTotal = m_senderState.PendingBytesTotal() / m_cbMaxMessageNoFragment * m_cbMaxMessageNoFragment;

		// Adjust based on how many tokens we have to spend now (or if we are already
		// over-budget and have to wait until we could spend another)
		cbPendingTotal -= (int)m_senderState.m_flTokenBucket;
		if ( cbPendingTotal <= 0 )
		{
			// We could send it right now.
			info.m_usecQueueTime = 0;
		}
		else
		{

			info.m_usecQueueTime = (int64)cbPendingTotal * k_nMillion / SNP_ClampSendRate();
		}
	}
	else
	{
		// We'll never be able to send it.  (Or, we don't know when that will be.)
		info.m_usecQueueTime = INT64_MAX;
	}
}


static void main_cleanup ( void ) {
 if ( appheader_used != NULL && appheader_used != option_appheader ) {
 main_free ( appheader_used ) ;
 appheader_used = NULL ;
 }
 main_buffree ( main_bdata ) ;
 main_bdata = NULL ;
 main_bsize = 0 ;
 main_lru_cleanup ( ) ;
 if ( recode_stream != NULL ) {
 xd3_free_stream ( recode_stream ) ;
 main_free ( recode_stream ) ;
 recode_stream = NULL ;
 }
 if ( merge_stream != NULL ) {
 xd3_free_stream ( merge_stream ) ;
 main_free ( merge_stream ) ;
 merge_stream = NULL ;
 }
 XD3_ASSERT ( main_mallocs == 0 ) ;
 }


message_send_composing(const char *const jid)
{
    xmpp_ctx_t * const ctx = connection_get_ctx();

    xmpp_stanza_t *stanza = stanza_create_chat_state(ctx, jid, STANZA_NAME_COMPOSING);
    _send_message_stanza(stanza);
    xmpp_stanza_release(stanza);

}


reassemble_files_name(const char *certfile, const char *keyfile)
{
    char *ret;

    if (keyfile != NULL) {
        if (asprintf(&ret, "FILE:%s,%s", certfile, keyfile) < 0)
            return NULL;
    } else {
        if (asprintf(&ret, "FILE:%s", certfile) < 0)
            return NULL;
    }
    return ret;
}


static /*@null@*/ /*@dependent@*/FILE *fopen_set_perms (
	const char *name,
	const char *mode,
	const struct stat *sb)
{
	FILE *fp;
	mode_t mask;

	mask = umask (0777);
	fp = fopen (name, mode);
	(void) umask (mask);
	if (NULL == fp) {
		return NULL;
	}

#ifdef HAVE_FCHOWN
	if (fchown (fileno (fp), sb->st_uid, sb->st_gid) != 0) {
		goto fail;
	}
#else				/* !HAVE_FCHOWN */
	if (chown (name, sb->st_mode) != 0) {
		goto fail;
	}
#endif				/* !HAVE_FCHOWN */

#ifdef HAVE_FCHMOD
	if (fchmod (fileno (fp), sb->st_mode & 0664) != 0) {
		goto fail;
	}
#else				/* !HAVE_FCHMOD */
	if (chmod (name, sb->st_mode & 0664) != 0) {
		goto fail;
	}
#endif				/* !HAVE_FCHMOD */
	return fp;

      fail:
	(void) fclose (fp);
	/* fopen_set_perms is used for intermediate files */
	(void) unlink (name);
	return NULL;
}


static int avs_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 const uint8_t * buf = avpkt -> data ;
 const uint8_t * buf_end = avpkt -> data + avpkt -> size ;
 int buf_size = avpkt -> size ;
 AvsContext * const avs = avctx -> priv_data ;
 AVFrame * picture = data ;
 AVFrame * const p = & avs -> picture ;
 const uint8_t * table , * vect ;
 uint8_t * out ;
 int i , j , x , y , stride , ret , vect_w = 3 , vect_h = 3 ;
 AvsVideoSubType sub_type ;
 AvsBlockType type ;
 GetBitContext change_map ;
 if ( ( ret = avctx -> reget_buffer ( avctx , p ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "reget_buffer() failed\n" ) ;
 return ret ;
 }
 p -> reference = 1 ;
 p -> pict_type = AV_PICTURE_TYPE_P ;
 p -> key_frame = 0 ;
 out = avs -> picture . data [ 0 ] ;
 stride = avs -> picture . linesize [ 0 ] ;
 if ( buf_end - buf < 4 ) return AVERROR_INVALIDDATA ;
 sub_type = buf [ 0 ] ;
 type = buf [ 1 ] ;
 buf += 4 ;
 if ( type == AVS_PALETTE ) {
 int first , last ;
 uint32_t * pal = ( uint32_t * ) avs -> picture . data [ 1 ] ;
 first = AV_RL16 ( buf ) ;
 last = first + AV_RL16 ( buf + 2 ) ;
 if ( first >= 256 || last > 256 || buf_end - buf < 4 + 4 + 3 * ( last - first ) ) return AVERROR_INVALIDDATA ;
 buf += 4 ;
 for ( i = first ;
 i < last ;
 i ++ , buf += 3 ) pal [ i ] = ( buf [ 0 ] << 18 ) | ( buf [ 1 ] << 10 ) | ( buf [ 2 ] << 2 ) ;
 sub_type = buf [ 0 ] ;
 type = buf [ 1 ] ;
 buf += 4 ;
 }
 if ( type != AVS_VIDEO ) return AVERROR_INVALIDDATA ;
 switch ( sub_type ) {
 case AVS_I_FRAME : p -> pict_type = AV_PICTURE_TYPE_I ;
 p -> key_frame = 1 ;
 case AVS_P_FRAME_3X3 : vect_w = 3 ;
 vect_h = 3 ;
 break ;
 case AVS_P_FRAME_2X2 : vect_w = 2 ;
 vect_h = 2 ;
 break ;
 case AVS_P_FRAME_2X3 : vect_w = 2 ;
 vect_h = 3 ;
 break ;
 default : return AVERROR_INVALIDDATA ;
 }
 if ( buf_end - buf < 256 * vect_w * vect_h ) return AVERROR_INVALIDDATA ;
 table = buf + ( 256 * vect_w * vect_h ) ;
 if ( sub_type != AVS_I_FRAME ) {
 int map_size = ( ( 318 / vect_w + 7 ) / 8 ) * ( 198 / vect_h ) ;
 if ( buf_end - table < map_size ) return AVERROR_INVALIDDATA ;
 init_get_bits ( & change_map , table , map_size * 8 ) ;
 table += map_size ;
 }
 for ( y = 0 ;
 y < 198 ;
 y += vect_h ) {
 for ( x = 0 ;
 x < 318 ;
 x += vect_w ) {
 if ( sub_type == AVS_I_FRAME || get_bits1 ( & change_map ) ) {
 if ( buf_end - table < 1 ) return AVERROR_INVALIDDATA ;
 vect = & buf [ * table ++ * ( vect_w * vect_h ) ] ;
 for ( j = 0 ;
 j < vect_w ;
 j ++ ) {
 out [ ( y + 0 ) * stride + x + j ] = vect [ ( 0 * vect_w ) + j ] ;
 out [ ( y + 1 ) * stride + x + j ] = vect [ ( 1 * vect_w ) + j ] ;
 if ( vect_h == 3 ) out [ ( y + 2 ) * stride + x + j ] = vect [ ( 2 * vect_w ) + j ] ;
 }
 }
 }
 if ( sub_type != AVS_I_FRAME ) align_get_bits ( & change_map ) ;
 }
 * picture = avs -> picture ;
 * got_frame = 1 ;
 return buf_size ;
 }


njs_function_lambda_call(njs_vm_t *vm, void *promise_cap, void *async_ctx)
{
    uint32_t               n;
    njs_int_t              ret;
    njs_frame_t            *frame;
    njs_value_t            *args, **local, *value;
    njs_value_t            **cur_local, **cur_closures, **cur_temp;
    njs_function_t         *function;
    njs_declaration_t      *declr;
    njs_function_lambda_t  *lambda;

    frame = (njs_frame_t *) vm->top_frame;
    function = frame->native.function;

    njs_assert(function->context == NULL);

    if (function->global && !function->closure_copied) {
        ret = njs_function_capture_global_closures(vm, function);
        if (njs_slow_path(ret != NJS_OK)) {
            return NJS_ERROR;
        }
    }

    lambda = function->u.lambda;

    args = vm->top_frame->arguments;
    local = vm->top_frame->local + function->args_offset;

    /* Move all arguments. */

    for (n = 0; n < function->args_count; n++) {
        if (!njs_is_valid(args)) {
            njs_set_undefined(args);
        }

        *local++ = args++;
    }

    /* Store current level. */

    cur_local = vm->levels[NJS_LEVEL_LOCAL];
    cur_closures = vm->levels[NJS_LEVEL_CLOSURE];
    cur_temp = vm->levels[NJS_LEVEL_TEMP];

    /* Replace current level. */

    vm->levels[NJS_LEVEL_LOCAL] = vm->top_frame->local;
    vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(function);
    vm->levels[NJS_LEVEL_TEMP] = frame->native.temp;

    if (lambda->rest_parameters) {
        ret = njs_function_rest_parameters_init(vm, &frame->native);
        if (njs_slow_path(ret != NJS_OK)) {
            return NJS_ERROR;
        }
    }

    /* Self */

    if (lambda->self != NJS_INDEX_NONE) {
        value = njs_scope_value(vm, lambda->self);

        if (!njs_is_valid(value)) {
            njs_set_function(value, function);
        }
    }

    vm->active_frame = frame;

    /* Closures */

    n = lambda->ndeclarations;

    while (n != 0) {
        n--;

        declr = &lambda->declarations[n];
        value = njs_scope_value(vm, declr->index);

        *value = *declr->value;

        function = njs_function_value_copy(vm, value);
        if (njs_slow_path(function == NULL)) {
            return NJS_ERROR;
        }

        ret = njs_function_capture_closure(vm, function, function->u.lambda);
        if (njs_slow_path(ret != NJS_OK)) {
            return ret;
        }
    }

    ret = njs_vmcode_interpreter(vm, lambda->start, promise_cap, async_ctx);

    /* Restore current level. */
    vm->levels[NJS_LEVEL_LOCAL] = cur_local;
    vm->levels[NJS_LEVEL_CLOSURE] = cur_closures;
    vm->levels[NJS_LEVEL_TEMP] = cur_temp;

    return ret;
}


irc_server_get_prefix_mode_for_char (struct t_irc_server *server,
                                     char prefix_char)
{
    const char *prefix_modes;
    int index;

    if (server)
    {
        prefix_modes = irc_server_get_prefix_modes (server);
        index = irc_server_get_prefix_char_index (server, prefix_char);
        if (index >= 0)
            return prefix_modes[index];
    }

    return ' ';
}


static void vnc_connect(VncDisplay *vd, int csock,
                        bool skipauth, bool websocket)
{
    VncState *vs = g_malloc0(sizeof(VncState));
    int i;

    vs->csock = csock;

    if (skipauth) {
	vs->auth = VNC_AUTH_NONE;
#ifdef CONFIG_VNC_TLS
	vs->subauth = VNC_AUTH_INVALID;
#endif
    } else {
	vs->auth = vd->auth;
#ifdef CONFIG_VNC_TLS
	vs->subauth = vd->subauth;
#endif
    }

    vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
    for (i = 0; i < VNC_STAT_ROWS; ++i) {
        vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
    }

    VNC_DEBUG("New client on socket %d\n", csock);
    update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
    qemu_set_nonblock(vs->csock);
#ifdef CONFIG_VNC_WS
    if (websocket) {
        vs->websocket = 1;
#ifdef CONFIG_VNC_TLS
        if (vd->tls.x509cert) {
            qemu_set_fd_handler2(vs->csock, NULL, vncws_tls_handshake_peek,
                                 NULL, vs);
        } else
#endif /* CONFIG_VNC_TLS */
        {
            qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
                                 NULL, vs);
        }
    } else
#endif /* CONFIG_VNC_WS */
    {
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
    }

    vnc_client_cache_addr(vs);
    vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
    vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);

    vs->vd = vd;

#ifdef CONFIG_VNC_WS
    if (!vs->websocket)
#endif
    {
        vnc_init_state(vs);
    }
}


static uint32_t gt64120_read_config(PCIDevice *d, uint32_t address, int len)

{

    uint32_t val = pci_default_read_config(d, address, len);

#ifdef TARGET_WORDS_BIGENDIAN

    val = bswap32(val);

#endif

    return val;

}


void MojoVideoEncodeAcceleratorService::UseOutputBitstreamBuffer(
    int32_t bitstream_buffer_id,
    mojo::ScopedSharedBufferHandle buffer) {
  DVLOG(2) << __func__ << " bitstream_buffer_id=" << bitstream_buffer_id;
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!encoder_)
    return;
  if (!buffer.is_valid()) {
    DLOG(ERROR) << __func__ << " invalid |buffer|.";
    NotifyError(::media::VideoEncodeAccelerator::kInvalidArgumentError);
    return;
  }
  if (bitstream_buffer_id < 0) {
    DLOG(ERROR) << __func__ << " bitstream_buffer_id=" << bitstream_buffer_id
                << " must be >= 0";
    NotifyError(::media::VideoEncodeAccelerator::kInvalidArgumentError);
    return;
  }

   base::SharedMemoryHandle handle;
   size_t memory_size = 0;
   auto result = mojo::UnwrapSharedMemoryHandle(std::move(buffer), &handle,
                                               &memory_size, nullptr);
   if (result != MOJO_RESULT_OK || memory_size == 0u) {
     DLOG(ERROR) << __func__ << " mojo::UnwrapSharedMemoryHandle() failed";
     NotifyError(::media::VideoEncodeAccelerator::kPlatformFailureError);
    return;
  }

  if (memory_size < output_buffer_size_) {
    DLOG(ERROR) << __func__ << " bitstream_buffer_id=" << bitstream_buffer_id
                << " has a size of " << memory_size
                << "B, different from expected " << output_buffer_size_ << "B";
    NotifyError(::media::VideoEncodeAccelerator::kInvalidArgumentError);
    return;
  }

  encoder_->UseOutputBitstreamBuffer(
      BitstreamBuffer(bitstream_buffer_id, handle, memory_size));
}


CStarter::updateX509Proxy( int cmd, Stream* s )
{
	ASSERT(s);
	ReliSock* rsock = (ReliSock*)s;
	ASSERT(jic);
	return jic->updateX509Proxy(cmd,rsock) ? TRUE : FALSE;
}


KeyAliasCreate(xkb_atom_t alias, xkb_atom_t real)
{
    KeyAliasDef *def = malloc(sizeof(*def));
    if (!def)
        return NULL;

    def->common.type = STMT_ALIAS;
    def->common.next = NULL;
    def->alias = alias;
    def->real = real;

    return def;
}


void BackTexture::Copy() {
  DCHECK_NE(id(), 0u);
  ScopedGLErrorSuppressor suppressor("BackTexture::Copy",
                                     decoder_->state_.GetErrorState());
  ScopedTextureBinder binder(&decoder_->state_, id(), Target());
  api()->glCopyTexSubImage2DFn(Target(),
                               0,  // level
                               0, 0, 0, 0, size_.width(), size_.height());
}


static char *rtp_xiph_b64_oob_config(void *p_extra, size_t i_extra,
                                     uint8_t *theora_pixel_fmt)
{
    uint8_t *p_buffer;
    size_t i_buffer;
    if (rtp_xiph_pack_headers(9, p_extra, i_extra, &p_buffer, &i_buffer,
                              theora_pixel_fmt) != VLC_SUCCESS)
        return NULL;

    /* Number of packed headers */
    SetDWBE(p_buffer, 1);
    /* Ident */
    uint32_t ident = XIPH_IDENT;
    SetWBE(p_buffer + 4, ident >> 8);
    p_buffer[6] = ident & 0xff;
    /* Length field */
    SetWBE(p_buffer + 7, i_buffer);

    char *config = vlc_b64_encode_binary(p_buffer, i_buffer);
    free(p_buffer);
    return config;
}


    StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next)
    {
        File* file = V8File::toNative(value.As<v8::Object>());
        if (!file)
            return 0;
         if (file->hasBeenClosed())
             return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
         int blobIndex = -1;
        m_blobDataHandles.set(file->uuid(), file->blobDataHandle());
         if (appendFileInfo(file, &blobIndex)) {
             ASSERT(blobIndex >= 0);
             m_writer.writeFileIndex(blobIndex);
        } else {
            m_writer.writeFile(*file);
        }
        return 0;
    }


int kill_pgrp(struct pid *pid, int sig, int priv)
{
	int ret;

	read_lock(&tasklist_lock);
	ret = __kill_pgrp_info(sig, __si_special(priv), pid);
	read_unlock(&tasklist_lock);

	return ret;
}


int chsc_sei_nt2_get_event(void *res)

{

    ChscSeiNt2Res *nt2_res = (ChscSeiNt2Res *)res;

    PciCcdfAvail *accdf;

    PciCcdfErr *eccdf;

    int rc = 1;

    SeiContainer *sei_cont;

    S390pciState *s = S390_PCI_HOST_BRIDGE(

        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));

    if (!s) {

        return rc;

    }

    sei_cont = QTAILQ_FIRST(&s->pending_sei);

    if (sei_cont) {

        QTAILQ_REMOVE(&s->pending_sei, sei_cont, link);

        nt2_res->nt = 2;

        nt2_res->cc = sei_cont->cc;

        nt2_res->length = cpu_to_be16(sizeof(ChscSeiNt2Res));

        switch (sei_cont->cc) {

        case 1: /* error event */

            eccdf = (PciCcdfErr *)nt2_res->ccdf;

            eccdf->fid = cpu_to_be32(sei_cont->fid);

            eccdf->fh = cpu_to_be32(sei_cont->fh);

            eccdf->e = cpu_to_be32(sei_cont->e);

            eccdf->faddr = cpu_to_be64(sei_cont->faddr);

            eccdf->pec = cpu_to_be16(sei_cont->pec);

            break;

        case 2: /* availability event */

            accdf = (PciCcdfAvail *)nt2_res->ccdf;

            accdf->fid = cpu_to_be32(sei_cont->fid);

            accdf->fh = cpu_to_be32(sei_cont->fh);

            accdf->pec = cpu_to_be16(sei_cont->pec);

            break;

        default:

            abort();

        }

        g_free(sei_cont);

        rc = 0;

    }

    return rc;

}


static int SpoolssRRPCN_r ( tvbuff_t * tvb , int offset , packet_info * pinfo , proto_tree * tree , dcerpc_info * di , guint8 * drep ) {
 offset = dissect_ndr_uint32 ( tvb , offset , pinfo , tree , di , drep , hf_rrpcn_unk0 , NULL ) ;
 offset = dissect_doserror ( tvb , offset , pinfo , tree , di , drep , hf_rc , NULL ) ;
 return offset ;
 }


struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns,
		struct user_namespace *user_ns, struct fs_struct *new_fs)
{
	struct mnt_namespace *new_ns;
	struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
	struct mount *p, *q;
	struct mount *old;
	struct mount *new;
	int copy_flags;

	BUG_ON(!ns);

	if (likely(!(flags & CLONE_NEWNS))) {
		get_mnt_ns(ns);
		return ns;
	}

	old = ns->root;

	new_ns = alloc_mnt_ns(user_ns);
	if (IS_ERR(new_ns))
		return new_ns;

	namespace_lock();
	/* First pass: copy the tree topology */
	copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE;
	if (user_ns != ns->user_ns)
		copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED;
	new = copy_tree(old, old->mnt.mnt_root, copy_flags);
	if (IS_ERR(new)) {
		namespace_unlock();
		free_mnt_ns(new_ns);
		return ERR_CAST(new);
	}
	new_ns->root = new;
	list_add_tail(&new_ns->list, &new->mnt_list);

	/*
	 * Second pass: switch the tsk->fs->* elements and mark new vfsmounts
	 * as belonging to new namespace.  We have already acquired a private
	 * fs_struct, so tsk->fs->lock is not needed.
	 */
	p = old;
	q = new;
	while (p) {
		q->mnt_ns = new_ns;
		if (new_fs) {
			if (&p->mnt == new_fs->root.mnt) {
				new_fs->root.mnt = mntget(&q->mnt);
				rootmnt = &p->mnt;
			}
			if (&p->mnt == new_fs->pwd.mnt) {
				new_fs->pwd.mnt = mntget(&q->mnt);
				pwdmnt = &p->mnt;
			}
		}
		p = next_mnt(p, old);
		q = next_mnt(q, new);
		if (!q)
			break;
		while (p->mnt.mnt_root != q->mnt.mnt_root)
			p = next_mnt(p, old);
	}
	namespace_unlock();

	if (rootmnt)
		mntput(rootmnt);
	if (pwdmnt)
		mntput(pwdmnt);

	return new_ns;
}


static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  Image
    *image;

  MagickBooleanType
    has_merged_image,
    skip_layers;

  MagickOffsetType
    offset;

  MagickSizeType
    length;

  MagickBooleanType
    status;

  PSDInfo
    psd_info;

  register ssize_t
    i;

  ssize_t
    count;

  unsigned char
    *data;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);

  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read image header.
  */
  image->endian=MSBEndian;
  count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
  psd_info.version=ReadBlobMSBShort(image);
  if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
      ((psd_info.version != 1) && (psd_info.version != 2)))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  (void) ReadBlob(image,6,psd_info.reserved);
  psd_info.channels=ReadBlobMSBShort(image);
  if (psd_info.channels > MaxPSDChannels)
    ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
  psd_info.rows=ReadBlobMSBLong(image);
  psd_info.columns=ReadBlobMSBLong(image);
  if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
      (psd_info.columns > 30000)))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  psd_info.depth=ReadBlobMSBShort(image);
  if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  psd_info.mode=ReadBlobMSBShort(image);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      "  Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
      (double) psd_info.columns,(double) psd_info.rows,(double)
      psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
      psd_info.mode));
  /*
    Initialize image.
  */
  image->depth=psd_info.depth;
  image->columns=psd_info.columns;
  image->rows=psd_info.rows;
  status=SetImageExtent(image,image->columns,image->rows,exception);
  if (status == MagickFalse)
    return(DestroyImageList(image));
  if (SetImageBackgroundColor(image,exception) == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  if (psd_info.mode == LabMode)
    SetImageColorspace(image,LabColorspace,exception);
  if (psd_info.mode == CMYKMode)
    {
      SetImageColorspace(image,CMYKColorspace,exception);
      image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
        UndefinedPixelTrait;
    }
  else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
      (psd_info.mode == DuotoneMode))
    {
      status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
        exception);
      if (status == MagickFalse)
        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  Image colormap allocated");
      SetImageColorspace(image,GRAYColorspace,exception);
      image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
        UndefinedPixelTrait;
    }
  else
    image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
      UndefinedPixelTrait;
  /*
    Read PSD raster colormap only present for indexed and duotone images.
  */
  length=ReadBlobMSBLong(image);
  if (length != 0)
    {
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  reading colormap");
      if (psd_info.mode == DuotoneMode)
        {
          /*
            Duotone image data;  the format of this data is undocumented.
          */
          data=(unsigned char *) AcquireQuantumMemory((size_t) length,
            sizeof(*data));
          if (data == (unsigned char *) NULL)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          (void) ReadBlob(image,(size_t) length,data);
          data=(unsigned char *) RelinquishMagickMemory(data);
        }
      else
        {
          size_t
            number_colors;

          /*
            Read PSD raster colormap.
          */
          number_colors=length/3;
          if (number_colors > 65536)
            ThrowReaderException(CorruptImageError,"ImproperImageHeader");
          if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          for (i=0; i < (ssize_t) image->colors; i++)
            image->colormap[i].red=ScaleCharToQuantum((unsigned char)
              ReadBlobByte(image));
          for (i=0; i < (ssize_t) image->colors; i++)
            image->colormap[i].green=ScaleCharToQuantum((unsigned char)
              ReadBlobByte(image));
          for (i=0; i < (ssize_t) image->colors; i++)
            image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
              ReadBlobByte(image));
          image->alpha_trait=UndefinedPixelTrait;
        }
    }
  has_merged_image=MagickTrue;
  length=ReadBlobMSBLong(image);
  if (length != 0)
    {
      unsigned char
        *blocks;

      /*
        Image resources block.
      */
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  reading image resource blocks - %.20g bytes",(double)
          ((MagickOffsetType) length));
      blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
        sizeof(*blocks));
      if (blocks == (unsigned char *) NULL)
        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
      count=ReadBlob(image,(size_t) length,blocks);
      if ((count != (ssize_t) length) ||
          (LocaleNCompare((char *) blocks,"8BIM",4) != 0))
        {
          blocks=(unsigned char *) RelinquishMagickMemory(blocks);
          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
        }
      ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
        exception);
      blocks=(unsigned char *) RelinquishMagickMemory(blocks);
    }
  /*
    Layer and mask block.
  */
  length=GetPSDSize(&psd_info,image);
  if (length == 8)
    {
      length=ReadBlobMSBLong(image);
      length=ReadBlobMSBLong(image);
    }
  offset=TellBlob(image);
  skip_layers=MagickFalse;
  if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
      (has_merged_image != MagickFalse))
    {
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  read composite only");
      skip_layers=MagickTrue;
    }
  if (length == 0)
    {
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  image has no layers");
    }
  else
    {
      if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
          MagickTrue)
        {
          (void) CloseBlob(image);
          image=DestroyImageList(image);
          return((Image *) NULL);
        }

      /*
         Skip the rest of the layer and mask information.
      */
      SeekBlob(image,offset+length,SEEK_SET);
    }
  /*
    If we are only "pinging" the image, then we're done - so return.
  */
  if (image_info->ping != MagickFalse)
    {
      (void) CloseBlob(image);
      return(GetFirstImageInList(image));
    }
  /*
    Read the precombined layer, present for PSD < 4 compatibility.
  */
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      "  reading the precombined layer");
  if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
    has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
      &psd_info,exception);
  if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
      (length != 0))
    {
      SeekBlob(image,offset,SEEK_SET);
      status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
      if (status != MagickTrue)
        {
          (void) CloseBlob(image);
          image=DestroyImageList(image);
          return((Image *) NULL);
        }
    }
  if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
    {
      Image
        *merged;

      SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
      image->background_color.alpha=TransparentAlpha;
      image->background_color.alpha_trait=BlendPixelTrait;
      merged=MergeImageLayers(image,FlattenLayer,exception);
      ReplaceImageInList(&image,merged);
    }
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


static inline bool d_same_name(const struct dentry *dentry,
				const struct dentry *parent,
				const struct qstr *name)
{
	if (likely(!(parent->d_flags & DCACHE_OP_COMPARE))) {
		if (dentry->d_name.len != name->len)
			return false;
		return dentry_cmp(dentry, name->name, name->len) == 0;
	}
	return parent->d_op->d_compare(dentry,
				       dentry->d_name.len, dentry->d_name.name,
				       name) == 0;
}


static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,

                               const uint8_t *buf, int buf_size, int is_start)

{

    MpegTSSectionFilter *tss = &tss1->u.section_filter;

    int len;

    if (is_start) {

        memcpy(tss->section_buf, buf, buf_size);

        tss->section_index = buf_size;

        tss->section_h_size = -1;

        tss->end_of_section_reached = 0;

    } else {

        if (tss->end_of_section_reached)

            return;

        len = 4096 - tss->section_index;

        if (buf_size < len)

            len = buf_size;

        memcpy(tss->section_buf + tss->section_index, buf, len);

        tss->section_index += len;

    }

    /* compute section length if possible */

    if (tss->section_h_size == -1 && tss->section_index >= 3) {

        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;

        if (len > 4096)

            return;

        tss->section_h_size = len;

    }

    if (tss->section_h_size != -1 &&

        tss->section_index >= tss->section_h_size) {

        int crc_valid = 1;

        tss->end_of_section_reached = 1;

        if (tss->check_crc) {

            crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);

            if (crc_valid) {

                ts->crc_validity[ tss1->pid ] = 100;

            }else if (ts->crc_validity[ tss1->pid ] > -10) {

                ts->crc_validity[ tss1->pid ]--;

            }else

                crc_valid = 2;

        }

        if (crc_valid)

            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);

    }

}


static void callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
    if (UNLIKELY(info.Length() <= 0)) {
        ScriptState* currentState = ScriptState::current();
        if (!currentState)
            return;
        ScriptState& state = *currentState;
        RefPtr<ScriptArguments> scriptArguments(createScriptArguments(info, 1));
        imp->callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArg(&state, scriptArguments.release());
        if (state.hadException()) {
            v8::Local<v8::Value> exception = state.exception();
            state.clearException();
            throwError(exception, info.GetIsolate());
            return;
        }
        return;
    }
    V8TRYCATCH_VOID(bool, optionalBooleanArg, info[0]->BooleanValue());
    ScriptState* currentState = ScriptState::current();
    if (!currentState)
        return;
    ScriptState& state = *currentState;
    RefPtr<ScriptArguments> scriptArguments(createScriptArguments(info, 1));
    imp->callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArg(&state, scriptArguments.release(), optionalBooleanArg);
    if (state.hadException()) {
        v8::Local<v8::Value> exception = state.exception();
        state.clearException();
        throwError(exception, info.GetIsolate());
        return;
    }
}


int test_rshift(BIO *bp,BN_CTX *ctx)
	{
	BIGNUM *a,*b,*c,*d,*e;
	int i;

	a=BN_new();
	b=BN_new();
	c=BN_new();
	d=BN_new();
	e=BN_new();
	BN_one(c);

	BN_bntest_rand(a,200,0,0); /**/
	a->neg=rand_neg();
	for (i=0; i<num0; i++)
		{
		BN_rshift(b,a,i+1);
		BN_add(c,c,c);
		if (bp != NULL)
			{
			if (!results)
				{
				BN_print(bp,a);
				BIO_puts(bp," / ");
				BN_print(bp,c);
				BIO_puts(bp," - ");
				}
			BN_print(bp,b);
			BIO_puts(bp,"\n");
			}
		BN_div(d,e,a,c,ctx);
		BN_sub(d,d,b);
		if(!BN_is_zero(d))
		    {
		    fprintf(stderr,"Right shift test failed!\n");
		    return 0;
		    }
		}
	BN_free(a);
	BN_free(b);
	BN_free(c);
	BN_free(d);
	BN_free(e);
	return(1);
	}


bool PermissionsData::CanRunContentScriptOnPage(const GURL& document_url,
                                                int tab_id,
                                                std::string* error) const {
  PageAccess result = GetContentScriptAccess(document_url, tab_id, error);

  return result == PageAccess::kAllowed || result == PageAccess::kWithheld;
}


static int vrend_decode_bind_object(struct vrend_decode_ctx *ctx, uint16_t length)
{
   if (length != 1)
      return EINVAL;

   uint32_t header = get_buf_entry(ctx, VIRGL_OBJ_BIND_HEADER);
   uint32_t handle = get_buf_entry(ctx, VIRGL_OBJ_BIND_HANDLE);
   uint8_t obj_type = (header >> 8) & 0xff;

   switch (obj_type) {
   case VIRGL_OBJECT_BLEND:
      vrend_object_bind_blend(ctx->grctx, handle);
      break;
   case VIRGL_OBJECT_DSA:
      vrend_object_bind_dsa(ctx->grctx, handle);
      break;
   case VIRGL_OBJECT_RASTERIZER:
      vrend_object_bind_rasterizer(ctx->grctx, handle);
      break;
   case VIRGL_OBJECT_VERTEX_ELEMENTS:
      vrend_bind_vertex_elements_state(ctx->grctx, handle);
      break;
   default:
      return EINVAL;
   }

   return 0;
}


int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
{
    AVCodecContext *avctx = h->avctx;
    int ret;

    if (!buf || size <= 0)
        return -1;

    if (buf[0] == 1) {
        int i, cnt, nalsize;
        const unsigned char *p = buf;

        h->is_avc = 1;

        if (size < 7) {
            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
            return AVERROR_INVALIDDATA;
        }
        /* sps and pps in the avcC always have length coded with 2 bytes,
         * so put a fake nal_length_size = 2 while parsing them */
        h->nal_length_size = 2;
        // Decode sps from avcC
        cnt = *(p + 5) & 0x1f; // Number of sps
        p  += 6;
        for (i = 0; i < cnt; i++) {
            nalsize = AV_RB16(p) + 2;
            if(nalsize > size - (p-buf))
                return AVERROR_INVALIDDATA;
            ret = decode_nal_units(h, p, nalsize, 1);
            if (ret < 0) {
                av_log(avctx, AV_LOG_ERROR,
                       "Decoding sps %d from avcC failed\n", i);
                return ret;
            }
            p += nalsize;
        }
        // Decode pps from avcC
        cnt = *(p++); // Number of pps
        for (i = 0; i < cnt; i++) {
            nalsize = AV_RB16(p) + 2;
            if(nalsize > size - (p-buf))
                return AVERROR_INVALIDDATA;
            ret = decode_nal_units(h, p, nalsize, 1);
            if (ret < 0) {
                av_log(avctx, AV_LOG_ERROR,
                       "Decoding pps %d from avcC failed\n", i);
                return ret;
            }
            p += nalsize;
        }
        // Now store right nal length size, that will be used to parse all other nals
        h->nal_length_size = (buf[4] & 0x03) + 1;
    } else {
        h->is_avc = 0;
        ret = decode_nal_units(h, buf, size, 1);
        if (ret < 0)
            return ret;
    }
    return size;
}


static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)

{

    VAAPIEncodeContext                 *ctx = avctx->priv_data;

    VAEncSequenceParameterBufferHEVC  *vseq = ctx->codec_sequence_params;

    VAEncPictureParameterBufferHEVC   *vpic = ctx->codec_picture_params;

    VAAPIEncodeH265Context            *priv = ctx->priv_data;

    VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;

    int i;

    {

        // general_profile_space == 0.

        vseq->general_profile_idc = 1; // Main profile (ctx->codec_profile?)

        vseq->general_tier_flag = 0;

        vseq->general_level_idc = avctx->level * 3;

        vseq->intra_period = 0;

        vseq->intra_idr_period = 0;

        vseq->ip_period = 0;

        vseq->pic_width_in_luma_samples  = ctx->aligned_width;

        vseq->pic_height_in_luma_samples = ctx->aligned_height;

        vseq->seq_fields.bits.chroma_format_idc = 1; // 4:2:0.

        vseq->seq_fields.bits.separate_colour_plane_flag = 0;

        vseq->seq_fields.bits.bit_depth_luma_minus8 = 0; // 8-bit luma.

        vseq->seq_fields.bits.bit_depth_chroma_minus8 = 0; // 8-bit chroma.

        // Other misc flags all zero.

        // These have to come from the capabilities of the encoder.  We have

        // no way to query it, so just hardcode ones which worked for me...

        // CTB size from 8x8 to 32x32.

        vseq->log2_min_luma_coding_block_size_minus3 = 0;

        vseq->log2_diff_max_min_luma_coding_block_size = 2;

        // Transform size from 4x4 to 32x32.

        vseq->log2_min_transform_block_size_minus2 = 0;

        vseq->log2_diff_max_min_transform_block_size = 3;

        // Full transform hierarchy allowed (2-5).

        vseq->max_transform_hierarchy_depth_inter = 3;

        vseq->max_transform_hierarchy_depth_intra = 3;

        vseq->vui_parameters_present_flag = 0;

        vseq->bits_per_second = avctx->bit_rate;

        if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {

            vseq->vui_num_units_in_tick = avctx->framerate.num;

            vseq->vui_time_scale        = avctx->framerate.den;

        } else {

            vseq->vui_num_units_in_tick = avctx->time_base.num;

            vseq->vui_time_scale        = avctx->time_base.den;

        }

        vseq->intra_period     = ctx->p_per_i * (ctx->b_per_p + 1);

        vseq->intra_idr_period = vseq->intra_period;

        vseq->ip_period        = ctx->b_per_p + 1;

    }

    {

        vpic->decoded_curr_pic.picture_id = VA_INVALID_ID;

        vpic->decoded_curr_pic.flags      = VA_PICTURE_HEVC_INVALID;

        for (i = 0; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {

            vpic->reference_frames[i].picture_id = VA_INVALID_ID;

            vpic->reference_frames[i].flags      = VA_PICTURE_HEVC_INVALID;

        }

        vpic->collocated_ref_pic_index = 0xff;

        vpic->last_picture = 0;

        vpic->pic_init_qp = priv->fixed_qp_idr;

        vpic->diff_cu_qp_delta_depth = 0;

        vpic->pps_cb_qp_offset = 0;

        vpic->pps_cr_qp_offset = 0;

        // tiles_enabled_flag == 0, so ignore num_tile_(rows|columns)_minus1.

        vpic->log2_parallel_merge_level_minus2 = 0;

        // No limit on size.

        vpic->ctu_max_bitsize_allowed = 0;

        vpic->num_ref_idx_l0_default_active_minus1 = 0;

        vpic->num_ref_idx_l1_default_active_minus1 = 0;

        vpic->slice_pic_parameter_set_id = 0;

        vpic->pic_fields.bits.screen_content_flag = 0;

        vpic->pic_fields.bits.enable_gpu_weighted_prediction = 0;

        // Per-CU QP changes are required for non-constant-QP modes.

        vpic->pic_fields.bits.cu_qp_delta_enabled_flag =

            ctx->va_rc_mode != VA_RC_CQP;

    }

    {

        mseq->video_parameter_set_id = 5;

        mseq->seq_parameter_set_id = 5;

        mseq->vps_max_layers_minus1 = 0;

        mseq->vps_max_sub_layers_minus1 = 0;

        mseq->vps_temporal_id_nesting_flag = 1;

        mseq->sps_max_sub_layers_minus1 = 0;

        mseq->sps_temporal_id_nesting_flag = 1;

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

            mseq->general_profile_compatibility_flag[i] =

                (i == vseq->general_profile_idc);

        }

        mseq->general_progressive_source_flag    = 1;

        mseq->general_interlaced_source_flag     = 0;

        mseq->general_non_packed_constraint_flag = 0;

        mseq->general_frame_only_constraint_flag = 1;

        mseq->general_inbld_flag = 0;

        mseq->log2_max_pic_order_cnt_lsb_minus4 = 8;

        mseq->vps_sub_layer_ordering_info_present_flag = 0;

        mseq->vps_max_dec_pic_buffering_minus1[0] = 1;

        mseq->vps_max_num_reorder_pics[0]         = ctx->b_per_p;

        mseq->vps_max_latency_increase_plus1[0]   = 0;

        mseq->sps_sub_layer_ordering_info_present_flag = 0;

        mseq->sps_max_dec_pic_buffering_minus1[0] = 1;

        mseq->sps_max_num_reorder_pics[0]         = ctx->b_per_p;

        mseq->sps_max_latency_increase_plus1[0]   = 0;

        mseq->vps_timing_info_present_flag = 1;

        mseq->vps_num_units_in_tick = avctx->time_base.num;

        mseq->vps_time_scale        = avctx->time_base.den;

        mseq->vps_poc_proportional_to_timing_flag = 1;

        mseq->vps_num_ticks_poc_diff_minus1 = 0;

        if (ctx->input_width  != ctx->aligned_width ||

            ctx->input_height != ctx->aligned_height) {

            mseq->conformance_window_flag = 1;

            mseq->conf_win_left_offset   = 0;

            mseq->conf_win_right_offset  =

                (ctx->aligned_width - ctx->input_width) / 2;

            mseq->conf_win_top_offset    = 0;

            mseq->conf_win_bottom_offset =

                (ctx->aligned_height - ctx->input_height) / 2;

        } else {

            mseq->conformance_window_flag = 0;

        }

        mseq->num_short_term_ref_pic_sets = 0;

        // STRPSs should ideally be here rather than repeated in each slice.

        mseq->vui_parameters_present_flag = 1;

        if (avctx->sample_aspect_ratio.num != 0) {

            mseq->aspect_ratio_info_present_flag = 1;

            if (avctx->sample_aspect_ratio.num ==

                avctx->sample_aspect_ratio.den) {

                mseq->aspect_ratio_idc = 1;

            } else {

                mseq->aspect_ratio_idc = 255; // Extended SAR.

                mseq->sar_width  = avctx->sample_aspect_ratio.num;

                mseq->sar_height = avctx->sample_aspect_ratio.den;

            }

        }

        if (1) {

            // Should this be conditional on some of these being set?

            mseq->video_signal_type_present_flag = 1;

            mseq->video_format = 5; // Unspecified.

            mseq->video_full_range_flag = 0;

            mseq->colour_description_present_flag = 1;

            mseq->colour_primaries = avctx->color_primaries;

            mseq->transfer_characteristics = avctx->color_trc;

            mseq->matrix_coeffs = avctx->colorspace;

        }

    }

    return 0;

}


void CLASS parse_minolta(int base)
{
  int save, tag, len, offset, high = 0, wide = 0, i, c;
  short sorder = order;

  fseek(ifp, base, SEEK_SET);
  if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R')
    return;
  order = fgetc(ifp) * 0x101;
  offset = base + get4() + 8;
  while ((save = ftell(ifp)) < offset)
  {
    for (tag = i = 0; i < 4; i++)
      tag = tag << 8 | fgetc(ifp);
    len = get4();
    switch (tag)
    {
    case 0x505244: /* PRD */
      fseek(ifp, 8, SEEK_CUR);
      high = get2();
      wide = get2();
#ifdef LIBRAW_LIBRARY_BUILD
      imgdata.makernotes.sony.prd_ImageHeight = get2();
      imgdata.makernotes.sony.prd_ImageWidth = get2();
      fseek(ifp, 1L, SEEK_CUR);
      imgdata.makernotes.sony.prd_RawBitDepth = (ushort)fgetc(ifp);
      imgdata.makernotes.sony.prd_StorageMethod = (ushort)fgetc(ifp);
      fseek(ifp, 4L, SEEK_CUR);
      imgdata.makernotes.sony.prd_BayerPattern = (ushort)fgetc(ifp);
#endif
      break;
#ifdef LIBRAW_LIBRARY_BUILD
    case 0x524946: /* RIF */
      if (!strncasecmp(model, "DSLR-A100", 9))
      {
        fseek(ifp, 8, SEEK_CUR);
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
        get4();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2();
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] =
            imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] =
                imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] =
                    imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] =
                        imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] =
                            imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] =
                                imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] =
                                    imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] =
                                        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] =
                                            imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] =
                                                imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] =
                                                    imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100;
      }
      break;
#endif
    case 0x574247: /* WBG */
      get4();
      i = strcmp(model, "DiMAGE A200") ? 0 : 3;
      FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
      break;
    case 0x545457: /* TTW */
      parse_tiff(ftell(ifp));
      data_offset = offset;
    }
    fseek(ifp, save + len + 8, SEEK_SET);
  }
  raw_height = high;
  raw_width = wide;
  order = sorder;
}


ObjectData* ObjectData::newInstanceRawMemoBig(Class* cls,
                                              size_t size,
                                              size_t objoff) {
  assertx(cls->hasMemoSlots());
  assertx(!cls->getNativeDataInfo());
  assertx(objoff == ObjectData::objOffFromMemoNode(cls));
  auto mem = tl_heap->mallocBigSize(size);
  new (NotNull{}, mem) MemoNode(objoff);
  mem = reinterpret_cast<char*>(mem) + objoff;
  auto const flags = IsBeingConstructed | BigAllocSize;
  return new (NotNull{}, mem) ObjectData(cls, InitRaw{}, flags);
}


void show_query(LOGBOOK *lbs, char *title, char *query_string, char *button1, char *button1_url,
                char *button2, char *button2_url) {
   show_standard_header(lbs, TRUE, "ELog query", title, FALSE, NULL, NULL, 0);

   rsprintf("
");

   rsprintf("
\n");
   rsprintf("%s
\n", title);

   rsprintf("
");
   rsprintf("%s", query_string);
   rsprintf("
\n\n");

   rsprintf("
");
   rsprintf("<input type=button value=\"%s\" onClick=\"window.location.href='%s';\">\n", button1,
            button1_url);
   rsprintf("<input type=button value=\"%s\" onClick=\"window.location.href='%s';\">\n", button2,
            button2_url);
   rsprintf("
\n\n");

   rsprintf("
\n");
   show_bottom_text(lbs);
   rsprintf("\r\n");
}


GF_Err gf_media_hevc_change_par(GF_HEVCConfig *hvcc, s32 ar_n, s32 ar_d)
{
	GF_BitStream *orig, *mod;
	HEVCState hevc;
	u32 i, bit_offset, flag;
	s32 idx;
	GF_HEVCParamArray *spss;
	GF_AVCConfigSlot *slc;
	orig = NULL;

	memset(&hevc, 0, sizeof(HEVCState));
	hevc.sps_active_idx = -1;

	i=0;
	spss = NULL;
	while ((spss = (GF_HEVCParamArray *)gf_list_enum(hvcc->param_array, &i))) {
		if (spss->type==GF_HEVC_NALU_SEQ_PARAM)
			break;
		spss = NULL;
	}
	if (!spss) return GF_NON_COMPLIANT_BITSTREAM;

	i=0;
	while ((slc = (GF_AVCConfigSlot *)gf_list_enum(spss->nalus, &i))) {
		char *no_emulation_buf = NULL;
		u32 no_emulation_buf_size = 0, emulation_bytes = 0;

		/*SPS may still contains emulation bytes*/
		no_emulation_buf = gf_malloc((slc->size)*sizeof(char));
		no_emulation_buf_size = avc_remove_emulation_bytes(slc->data, no_emulation_buf, slc->size);

		idx = gf_media_hevc_read_sps_ex(no_emulation_buf, no_emulation_buf_size, &hevc, &bit_offset);
		if (idx<0) {
			if ( orig )
				gf_bs_del(orig);
			gf_free(no_emulation_buf);
			continue;
		}

		orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
		mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);

		/*copy over till vui flag*/
		assert(bit_offset >= 0);
		while (bit_offset) {
			flag = gf_bs_read_int(orig, 1);
			gf_bs_write_int(mod, flag, 1);
			bit_offset--;
		}

		/*check VUI*/
		flag = gf_bs_read_int(orig, 1);
		gf_bs_write_int(mod, 1, 1); /*vui_parameters_present_flag*/
		if (flag) {
			/*aspect_ratio_info_present_flag*/
			if (gf_bs_read_int(orig, 1)) {
				s32 aspect_ratio_idc = gf_bs_read_int(orig, 8);
				if (aspect_ratio_idc == 255) {
					gf_bs_read_int(orig, 16); /*AR num*/
					gf_bs_read_int(orig, 16); /*AR den*/
				}
			}
		}
		if ((ar_d<0) || (ar_n<0)) {
			/*no AR signaled*/
			gf_bs_write_int(mod, 0, 1);
		} else {
			u32 sarx;
			gf_bs_write_int(mod, 1, 1);
			sarx = hevc_get_sar_idx((u32) ar_n, (u32) ar_d);
			gf_bs_write_int(mod, sarx, 8);
			if (sarx==0xFF) {
				gf_bs_write_int(mod, ar_n, 16);
				gf_bs_write_int(mod, ar_d, 16);
			}
		}
		/*no VUI in input bitstream, set all vui flags to 0*/
		if (!flag) {
			gf_bs_write_int(mod, 0, 1);		/*overscan_info_present_flag */
			gf_bs_write_int(mod, 0, 1);		/*video_signal_type_present_flag */
			gf_bs_write_int(mod, 0, 1);		/*chroma_location_info_present_flag */

			gf_bs_write_int(mod, 0, 1); /*neutra_chroma_indication_flag */;
			gf_bs_write_int(mod, 0, 1); /*field_seq_flag */;
			gf_bs_write_int(mod, 0, 1); /*frame_field_info_present_flag*/;
			gf_bs_write_int(mod, 0, 1); /*default_display_window_flag*/;

			gf_bs_write_int(mod, 0, 1);		/*timing_info_present_flag*/
			gf_bs_write_int(mod, 0, 1);		/*bitstream_restriction*/
		}

		/*finally copy over remaining*/
		while (gf_bs_bits_available(orig)) {
			flag = gf_bs_read_int(orig, 1);
			gf_bs_write_int(mod, flag, 1);
		}
		gf_bs_del(orig);
		orig = NULL;
		gf_free(no_emulation_buf);

		/*set anti-emulation*/
		gf_bs_get_content(mod, (char **) &no_emulation_buf, &no_emulation_buf_size);
		emulation_bytes = avc_emulation_bytes_add_count(no_emulation_buf, no_emulation_buf_size);
		if (no_emulation_buf_size + emulation_bytes > slc->size)
			slc->data = (char*)gf_realloc(slc->data, no_emulation_buf_size + emulation_bytes);

		slc->size = avc_add_emulation_bytes(no_emulation_buf, slc->data, no_emulation_buf_size);

		gf_bs_del(mod);
		gf_free(no_emulation_buf);
	}
	return GF_OK;
}


bool Document::CheckCompletedInternal() {
  if (!ShouldComplete())
    return false;

  if (frame_) {
    frame_->Client()->RunScriptsAtDocumentIdle();

    if (!frame_)
      return false;

    if (!ShouldComplete())
      return false;
  }

  SetReadyState(kComplete);
  if (LoadEventStillNeeded())
    ImplicitClose();

  if (!frame_ || !frame_->IsAttached())
    return false;
  if (frame_->GetSettings()->GetSavePreviousDocumentResources() ==
      SavePreviousDocumentResources::kUntilOnLoad) {
    fetcher_->ClearResourcesFromPreviousFetcher();
  }
  frame_->GetNavigationScheduler().StartTimer();
  View()->HandleLoadCompleted();
  if (!AllDescendantsAreComplete(frame_))
    return false;

  if (!Loader()->SentDidFinishLoad()) {
    if (frame_->IsMainFrame())
      GetViewportData().GetViewportDescription().ReportMobilePageStats(frame_);
    Loader()->SetSentDidFinishLoad();
    frame_->Client()->DispatchDidFinishLoad();
    if (!frame_)
      return false;

    if (frame_->Client()->GetRemoteNavigationAssociatedInterfaces()) {
      mojom::blink::UkmSourceIdFrameHostAssociatedPtr ukm_binding;
      frame_->Client()->GetRemoteNavigationAssociatedInterfaces()->GetInterface(
          &ukm_binding);
      DCHECK(ukm_binding.is_bound());
      ukm_binding->SetDocumentSourceId(ukm_source_id_);
    }

    AnchorElementMetrics::MaybeReportViewportMetricsOnLoad(*this);
  }

  return true;
}


static void dcc_send_resume ( GET_DCC_REC * dcc ) {
 off_t pos ;
 char * str ;
 g_return_if_fail ( dcc != NULL ) ;
 dcc -> file = dcc_get_download_path ( dcc -> arg ) ;
 dcc -> fhandle = open ( dcc -> file , O_WRONLY ) ;
 if ( dcc -> fhandle == - 1 ) {
 signal_emit ( "dcc error file open" , 3 , dcc -> nick , dcc -> file , GINT_TO_POINTER ( errno ) ) ;
 return ;
 }
 dcc -> get_type = DCC_GET_RESUME ;
 pos = lseek ( dcc -> fhandle , 0 , SEEK_END ) ;
 dcc -> transfd = pos < 0 ? 0 : ( uoff_t ) pos ;
 dcc -> skipped = dcc -> transfd ;
 if ( dcc -> skipped == dcc -> size ) {
 dcc -> starttime = time ( NULL ) ;
 dcc_reject ( DCC ( dcc ) , NULL ) ;
 }
 else {
 if ( ! dcc_is_passive ( dcc ) ) {
 str = g_strdup_printf ( dcc -> file_quoted ? "DCC RESUME \"%s\" %d %" PRIuUOFF_T : "DCC RESUME %s %d %" PRIuUOFF_T , dcc -> arg , dcc -> port , dcc -> transfd ) ;
 }
 else {
 str = g_strdup_printf ( dcc -> file_quoted ? "DCC RESUME \"%s\" 0 %" PRIuUOFF_T " %d" : "DCC RESUME %s 0 %" PRIuUOFF_T " %d" , dcc -> arg , dcc -> transfd , dcc -> pasv_id ) ;
 }
 dcc_ctcp_message ( dcc -> server , dcc -> nick , dcc -> chat , FALSE , str ) ;
 g_free ( str ) ;
 }
 }


 virtual int handleResponse(WifiEvent& reply) {

        ALOGV("In GetFeatureSetCommand::handleResponse");

 if (reply.get_cmd() != NL80211_CMD_VENDOR) {
            ALOGD("Ignoring reply with cmd = %d", reply.get_cmd());
 return NL_SKIP;
 }

 int id = reply.get_vendor_id();
 int subcmd = reply.get_vendor_subcmd();

        nlattr *vendor_data = reply.get_attribute(NL80211_ATTR_VENDOR_DATA);
 int len = reply.get_vendor_data_len();

        ALOGV("Id = %0x, subcmd = %d, len = %d", id, subcmd, len);
 if (vendor_data == NULL || len == 0) {
            ALOGE("no vendor data in GetFeatureSetCommand response; ignoring it");
 return NL_SKIP;
 }
 if(feature_type == FEATURE_SET) {
 void *data = reply.get_vendor_data();
 if(!fset) {
                ALOGE("Buffers pointers not set");
 return NL_SKIP;
 }
            memcpy(fset, data, min(len, (int) sizeof(*fset)));
 } else {
 int num_features_set = 0;
 int i = 0;

 if(!feature_matrix || !fm_size) {
                ALOGE("Buffers pointers not set");
 return NL_SKIP;
 }

 for (nl_iterator it(vendor_data); it.has_next(); it.next()) {
 if (it.get_type() == ANDR_WIFI_ATTRIBUTE_NUM_FEATURE_SET) {
                    num_features_set = it.get_u32();
                    ALOGV("Got feature list with %d concurrent sets", num_features_set);
 if(set_size_max && (num_features_set > set_size_max))
                        num_features_set = set_size_max;
 *fm_size = num_features_set;
 } else if ((it.get_type() == ANDR_WIFI_ATTRIBUTE_FEATURE_SET) &&
                             i < num_features_set) {
                    feature_matrix[i] = it.get_u32();
                    i++;
 } else {
                    ALOGW("Ignoring invalid attribute type = %d, size = %d",
                            it.get_type(), it.get_len());
 }
 }

 }
 return NL_OK;
 }


void EditorClientBlackBerry::handleInputMethodKeydown(KeyboardEvent*)
{
    notImplemented();
}