static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
			  bool from_vmentry, u32 *entry_failure_code)
{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
	u32 exec_control, vmcs12_exec_ctrl;

	vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
	vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
	vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
	vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
	vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
	vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
	vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
	vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
	vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
	vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
	vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
	vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
	vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
	vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
	vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
	vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
	vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
	vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
	vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
	vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
	vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
	vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
	vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
	vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
	vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
	vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
	vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
	vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
	vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
	vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
	vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
	vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
	vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
	vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
	vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
	vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);

	if (from_vmentry &&
	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
		kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
		vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
	} else {
		kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
		vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
	}
	if (from_vmentry) {
		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
			     vmcs12->vm_entry_intr_info_field);
		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
			     vmcs12->vm_entry_exception_error_code);
		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
			     vmcs12->vm_entry_instruction_len);
		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
			     vmcs12->guest_interruptibility_info);
		vmx->loaded_vmcs->nmi_known_unmasked =
			!(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
	} else {
		vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
	}
	vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
	vmx_set_rflags(vcpu, vmcs12->guest_rflags);
	vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
		vmcs12->guest_pending_dbg_exceptions);
	vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
	vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);

	if (nested_cpu_has_xsaves(vmcs12))
		vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
	vmcs_write64(VMCS_LINK_POINTER, -1ull);

	exec_control = vmcs12->pin_based_vm_exec_control;

	/* Preemption timer setting is only taken from vmcs01.  */
	exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
	exec_control |= vmcs_config.pin_based_exec_ctrl;
	if (vmx->hv_deadline_tsc == -1)
		exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;

	/* Posted interrupts setting is only taken from vmcs12.  */
	if (nested_cpu_has_posted_intr(vmcs12)) {
		vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
		vmx->nested.pi_pending = false;
		vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
	} else {
		exec_control &= ~PIN_BASED_POSTED_INTR;
	}

	vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);

	vmx->nested.preemption_timer_expired = false;
	if (nested_cpu_has_preemption_timer(vmcs12))
		vmx_start_preemption_timer(vcpu);

	/*
	 * Whether page-faults are trapped is determined by a combination of
	 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
	 * If enable_ept, L0 doesn't care about page faults and we should
	 * set all of these to L1's desires. However, if !enable_ept, L0 does
	 * care about (at least some) page faults, and because it is not easy
	 * (if at all possible?) to merge L0 and L1's desires, we simply ask
	 * to exit on each and every L2 page fault. This is done by setting
	 * MASK=MATCH=0 and (see below) EB.PF=1.
	 * Note that below we don't need special code to set EB.PF beyond the
	 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
	 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
	 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
	 */
	vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
		enable_ept ? vmcs12->page_fault_error_code_mask : 0);
	vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
		enable_ept ? vmcs12->page_fault_error_code_match : 0);

	if (cpu_has_secondary_exec_ctrls()) {
		exec_control = vmx->secondary_exec_control;

		/* Take the following fields only from vmcs12 */
		exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
				  SECONDARY_EXEC_ENABLE_INVPCID |
				  SECONDARY_EXEC_RDTSCP |
				  SECONDARY_EXEC_XSAVES |
				  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
				  SECONDARY_EXEC_APIC_REGISTER_VIRT |
				  SECONDARY_EXEC_ENABLE_VMFUNC);
		if (nested_cpu_has(vmcs12,
				   CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
			vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
				~SECONDARY_EXEC_ENABLE_PML;
			exec_control |= vmcs12_exec_ctrl;
		}

		/* All VMFUNCs are currently emulated through L0 vmexits.  */
		if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
			vmcs_write64(VM_FUNCTION_CONTROL, 0);

		if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
			vmcs_write64(EOI_EXIT_BITMAP0,
				vmcs12->eoi_exit_bitmap0);
			vmcs_write64(EOI_EXIT_BITMAP1,
				vmcs12->eoi_exit_bitmap1);
			vmcs_write64(EOI_EXIT_BITMAP2,
				vmcs12->eoi_exit_bitmap2);
			vmcs_write64(EOI_EXIT_BITMAP3,
				vmcs12->eoi_exit_bitmap3);
			vmcs_write16(GUEST_INTR_STATUS,
				vmcs12->guest_intr_status);
		}

		/*
		 * Write an illegal value to APIC_ACCESS_ADDR. Later,
		 * nested_get_vmcs12_pages will either fix it up or
		 * remove the VM execution control.
		 */
		if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
			vmcs_write64(APIC_ACCESS_ADDR, -1ull);

		vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
	}

	/*
	 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
	 * Some constant fields are set here by vmx_set_constant_host_state().
	 * Other fields are different per CPU, and will be set later when
	 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
	 */
	vmx_set_constant_host_state(vmx);

	/*
	 * Set the MSR load/store lists to match L0's settings.
	 */
	vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
	vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
	vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
	vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr);
	vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));

	/*
	 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
	 * entry, but only if the current (host) sp changed from the value
	 * we wrote last (vmx->host_rsp). This cache is no longer relevant
	 * if we switch vmcs, and rather than hold a separate cache per vmcs,
	 * here we just force the write to happen on entry.
	 */
	vmx->host_rsp = 0;

	exec_control = vmx_exec_control(vmx); /* L0's desires */
	exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
	exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
	exec_control &= ~CPU_BASED_TPR_SHADOW;
	exec_control |= vmcs12->cpu_based_vm_exec_control;

	/*
	 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
	 * nested_get_vmcs12_pages can't fix it up, the illegal value
	 * will result in a VM entry failure.
	 */
	if (exec_control & CPU_BASED_TPR_SHADOW) {
		vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
		vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
	}

	/*
	 * Merging of IO bitmap not currently supported.
	 * Rather, exit every time.
	 */
	exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
	exec_control |= CPU_BASED_UNCOND_IO_EXITING;

	vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);

	/* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
	 * bitwise-or of what L1 wants to trap for L2, and what we want to
	 * trap. Note that CR0.TS also needs updating - we do this later.
	 */
	update_exception_bitmap(vcpu);
	vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
	vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);

	/* L2->L1 exit controls are emulated - the hardware exit is to L0 so
	 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
	 * bits are further modified by vmx_set_efer() below.
	 */
	vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);

	/* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
	 * emulated by vmx_set_efer(), below.
	 */
	vm_entry_controls_init(vmx,
		(vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
			~VM_ENTRY_IA32E_MODE) |
		(vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));

	if (from_vmentry &&
	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
		vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
		vcpu->arch.pat = vmcs12->guest_ia32_pat;
	} else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
		vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
	}

	set_cr4_guest_host_mask(vmx);

	if (from_vmentry &&
	    vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
		vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);

	if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
		vmcs_write64(TSC_OFFSET,
			vcpu->arch.tsc_offset + vmcs12->tsc_offset);
	else
		vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
	if (kvm_has_tsc_control)
		decache_tsc_multiplier(vmx);

	if (enable_vpid) {
		/*
		 * There is no direct mapping between vpid02 and vpid12, the
		 * vpid02 is per-vCPU for L0 and reused while the value of
		 * vpid12 is changed w/ one invvpid during nested vmentry.
		 * The vpid12 is allocated by L1 for L2, so it will not
		 * influence global bitmap(for vpid01 and vpid02 allocation)
		 * even if spawn a lot of nested vCPUs.
		 */
		if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
			if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
				vmx->nested.last_vpid = vmcs12->virtual_processor_id;
				__vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
			}
		} else {
			vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
			vmx_flush_tlb(vcpu);
		}

	}

	if (enable_pml) {
		/*
		 * Conceptually we want to copy the PML address and index from
		 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
		 * since we always flush the log on each vmexit, this happens
		 * to be equivalent to simply resetting the fields in vmcs02.
		 */
		ASSERT(vmx->pml_pg);
		vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
		vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
	}

	if (nested_cpu_has_ept(vmcs12)) {
		if (nested_ept_init_mmu_context(vcpu)) {
			*entry_failure_code = ENTRY_FAIL_DEFAULT;
			return 1;
		}
	} else if (nested_cpu_has2(vmcs12,
				   SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
		vmx_flush_tlb_ept_only(vcpu);
	}

	/*
	 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
	 * bits which we consider mandatory enabled.
	 * The CR0_READ_SHADOW is what L2 should have expected to read given
	 * the specifications by L1; It's not enough to take
	 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
	 * have more bits than L1 expected.
	 */
	vmx_set_cr0(vcpu, vmcs12->guest_cr0);
	vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));

	vmx_set_cr4(vcpu, vmcs12->guest_cr4);
	vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));

	if (from_vmentry &&
	    (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
		vcpu->arch.efer = vmcs12->guest_ia32_efer;
	else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
		vcpu->arch.efer |= (EFER_LMA | EFER_LME);
	else
		vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
	/* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
	vmx_set_efer(vcpu, vcpu->arch.efer);

	/* Shadow page tables on either EPT or shadow page tables. */
	if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
				entry_failure_code))
		return 1;

	if (!enable_ept)
		vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;

	/*
	 * L1 may access the L2's PDPTR, so save them to construct vmcs12
	 */
	if (enable_ept) {
		vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
		vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
		vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
		vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
	}

	kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
	kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
	return 0;
}


static debugCBContext * debugCB_clone ( debugCBContext * ctx ) {
 debugCBContext * newCtx ;
 newCtx = malloc ( sizeof ( debugCBContext ) ) ;
 newCtx -> serial = debugCB_nextSerial ( ) ;
 newCtx -> magic = 0xC0FFEE ;
 newCtx -> subCallback = ctx -> subCallback ;
 newCtx -> subContext = ctx -> subContext ;
 # if DEBUG_TMI printf ( "debugCB_clone: %p:%d -> new context %p:%d\n" , ctx , ctx -> serial , newCtx , newCtx -> serial ) ;
 # endif return newCtx ;
 }


static int vnc_update_client(VncState *vs, int has_dirty, bool sync) { if (vs->need_update && vs->csock != -1) { VncDisplay *vd = vs->vd; VncJob *job; int y; int height; int n = 0; if (vs->output.offset && !vs->audio_cap && !vs->force_update) /* kernel send buffers are full -> drop frames to throttle */ return 0; if (!has_dirty && !vs->audio_cap && !vs->force_update) return 0; /* * Send screen updates to the vnc client using the server * surface and server dirty map. guest surface updates * happening in parallel don't disturb us, the next pass will * send them to the client. */ job = vnc_job_new(vs); height = MIN(pixman_image_get_height(vd->server), vs->client_height); y = 0; for (;;) { int x, h; unsigned long x2; unsigned long offset = find_next_bit((unsigned long *) &vs->dirty, height * VNC_DIRTY_BPL(vs), y * VNC_DIRTY_BPL(vs)); if (offset == height * VNC_DIRTY_BPL(vs)) { /* no more dirty bits */ break; } y = offset / VNC_DIRTY_BPL(vs); x = offset % VNC_DIRTY_BPL(vs); x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y], VNC_DIRTY_BPL(vs), x); bitmap_clear(vs->dirty[y], x, x2 - x); h = find_and_clear_dirty_height(vs, y, x, x2, height); n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y, (x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h); } vnc_job_push(job); vs->force_update = 0; return n; } if (vs->csock == -1) { vnc_disconnect_finish(vs); } else if (sync) { vnc_jobs_join(vs); } return 0; }


static int start_auth_vnc(VncState *vs) { make_challenge(vs); /* Send client a 'random' challenge */ vnc_write(vs, vs->challenge, sizeof(vs->challenge)); vnc_flush(vs); vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge)); return 0; }


Curl_cookie_add(struct Curl_easy *data,
                /*
                 * The 'data' pointer here may be NULL at times, and thus
                 * must only be used very carefully for things that can deal
                 * with data being NULL. Such as infof() and similar
                 */
                struct CookieInfo *c,
                bool httpheader, /* TRUE if HTTP header-style line */
                bool noexpire, /* if TRUE, skip remove_expired() */
                char *lineptr,   /* first character of the line */
                const char *domain, /* default domain */
                const char *path,   /* full path used when this cookie is set,
                                       used to get default path for the cookie
                                       unless set */
                bool secure)  /* TRUE if connection is over secure origin */
{
  struct Cookie *clist;
  struct Cookie *co;
  struct Cookie *lastc = NULL;
  struct Cookie *replace_co = NULL;
  struct Cookie *replace_clist = NULL;
  time_t now = time(NULL);
  bool replace_old = FALSE;
  bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
  size_t myhash;

#ifdef CURL_DISABLE_VERBOSE_STRINGS
  (void)data;
#endif

  DEBUGASSERT(MAX_SET_COOKIE_AMOUNT <= 255); /* counter is an unsigned char */
  if(data->req.setcookies >= MAX_SET_COOKIE_AMOUNT)
    return NULL;

  /* First, alloc and init a new struct for it */
  co = calloc(1, sizeof(struct Cookie));
  if(!co)
    return NULL; /* bail out if we're this low on memory */

  if(httpheader) {
    /* This line was read off a HTTP-header */
    char name[MAX_NAME];
    char what[MAX_NAME];
    const char *ptr;
    const char *semiptr;

    size_t linelength = strlen(lineptr);
    if(linelength > MAX_COOKIE_LINE) {
      /* discard overly long lines at once */
      free(co);
      return NULL;
    }

    semiptr = strchr(lineptr, ';'); /* first, find a semicolon */

    while(*lineptr && ISBLANK(*lineptr))
      lineptr++;

    ptr = lineptr;
    do {
      /* we have a <what>=<this> pair or a stand-alone word here */
      name[0] = what[0] = 0; /* init the buffers */
      if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
                     MAX_NAME_TXT "[^;\r\n]",
                     name, what)) {
        /*
         * Use strstore() below to properly deal with received cookie
         * headers that have the same string property set more than once,
         * and then we use the last one.
         */
        const char *whatptr;
        bool done = FALSE;
        bool sep;
        size_t len = strlen(what);
        size_t nlen = strlen(name);
        const char *endofn = &ptr[ nlen ];

        /*
         * Check for too long individual name or contents, or too long
         * combination of name + contents. Chrome and Firefox support 4095 or
         * 4096 bytes combo
         */
        if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) ||
           ((nlen + len) > MAX_NAME)) {
          freecookie(co);
          infof(data, "oversized cookie dropped, name/val %zu + %zu bytes",
                nlen, len);
          return NULL;
        }

        /* name ends with a '=' ? */
        sep = (*endofn == '=')?TRUE:FALSE;

        if(nlen) {
          endofn--; /* move to the last character */
          if(ISBLANK(*endofn)) {
            /* skip trailing spaces in name */
            while(*endofn && ISBLANK(*endofn) && nlen) {
              endofn--;
              nlen--;
            }
            name[nlen] = 0; /* new end of name */
          }
        }

        /* Strip off trailing whitespace from the 'what' */
        while(len && ISBLANK(what[len-1])) {
          what[len-1] = 0;
          len--;
        }

        /* Skip leading whitespace from the 'what' */
        whatptr = what;
        while(*whatptr && ISBLANK(*whatptr))
          whatptr++;

        /*
         * Check if we have a reserved prefix set before anything else, as we
         * otherwise have to test for the prefix in both the cookie name and
         * "the rest". Prefixes must start with '__' and end with a '-', so
         * only test for names where that can possibly be true.
         */
        if(nlen > 3 && name[0] == '_' && name[1] == '_') {
          if(!strncmp("__Secure-", name, 9))
            co->prefix |= COOKIE_PREFIX__SECURE;
          else if(!strncmp("__Host-", name, 7))
            co->prefix |= COOKIE_PREFIX__HOST;
        }

        if(!co->name) {
          /* The very first name/value pair is the actual cookie name */
          if(!sep) {
            /* Bad name/value pair. */
            badcookie = TRUE;
            break;
          }
          co->name = strdup(name);
          co->value = strdup(whatptr);
          done = TRUE;
          if(!co->name || !co->value) {
            badcookie = TRUE;
            break;
          }
        }
        else if(!len) {
          /*
           * this was a "<name>=" with no content, and we must allow
           * 'secure' and 'httponly' specified this weirdly
           */
          done = TRUE;
          /*
           * secure cookies are only allowed to be set when the connection is
           * using a secure protocol, or when the cookie is being set by
           * reading from file
           */
          if(strcasecompare("secure", name)) {
            if(secure || !c->running) {
              co->secure = TRUE;
            }
            else {
              badcookie = TRUE;
              break;
            }
          }
          else if(strcasecompare("httponly", name))
            co->httponly = TRUE;
          else if(sep)
            /* there was a '=' so we're not done parsing this field */
            done = FALSE;
        }
        if(done)
          ;
        else if(strcasecompare("path", name)) {
          strstore(&co->path, whatptr);
          if(!co->path) {
            badcookie = TRUE; /* out of memory bad */
            break;
          }
          free(co->spath); /* if this is set again */
          co->spath = sanitize_cookie_path(co->path);
          if(!co->spath) {
            badcookie = TRUE; /* out of memory bad */
            break;
          }
        }
        else if(strcasecompare("domain", name) && whatptr[0]) {
          bool is_ip;

          /*
           * Now, we make sure that our host is within the given domain, or
           * the given domain is not valid and thus cannot be set.
           */

          if('.' == whatptr[0])
            whatptr++; /* ignore preceding dot */

#ifndef USE_LIBPSL
          /*
           * Without PSL we don't know when the incoming cookie is set on a
           * TLD or otherwise "protected" suffix. To reduce risk, we require a
           * dot OR the exact host name being "localhost".
           */
          if(bad_domain(whatptr))
            domain = ":";
#endif

          is_ip = Curl_host_is_ipnum(domain ? domain : whatptr);

          if(!domain
             || (is_ip && !strcmp(whatptr, domain))
             || (!is_ip && tailmatch(whatptr, domain))) {
            strstore(&co->domain, whatptr);
            if(!co->domain) {
              badcookie = TRUE;
              break;
            }
            if(!is_ip)
              co->tailmatch = TRUE; /* we always do that if the domain name was
                                       given */
          }
          else {
            /*
             * We did not get a tailmatch and then the attempted set domain is
             * not a domain to which the current host belongs. Mark as bad.
             */
            badcookie = TRUE;
            infof(data, "skipped cookie with bad tailmatch domain: %s",
                  whatptr);
          }
        }
        else if(strcasecompare("version", name)) {
          strstore(&co->version, whatptr);
          if(!co->version) {
            badcookie = TRUE;
            break;
          }
        }
        else if(strcasecompare("max-age", name)) {
          /*
           * Defined in RFC2109:
           *
           * Optional.  The Max-Age attribute defines the lifetime of the
           * cookie, in seconds.  The delta-seconds value is a decimal non-
           * negative integer.  After delta-seconds seconds elapse, the
           * client should discard the cookie.  A value of zero means the
           * cookie should be discarded immediately.
           */
          strstore(&co->maxage, whatptr);
          if(!co->maxage) {
            badcookie = TRUE;
            break;
          }
        }
        else if(strcasecompare("expires", name)) {
          strstore(&co->expirestr, whatptr);
          if(!co->expirestr) {
            badcookie = TRUE;
            break;
          }
        }

        /*
         * Else, this is the second (or more) name we don't know about!
         */
      }
      else {
        /* this is an "illegal" <what>=<this> pair */
      }

      if(!semiptr || !*semiptr) {
        /* we already know there are no more cookies */
        semiptr = NULL;
        continue;
      }

      ptr = semiptr + 1;
      while(*ptr && ISBLANK(*ptr))
        ptr++;
      semiptr = strchr(ptr, ';'); /* now, find the next semicolon */

      if(!semiptr && *ptr)
        /*
         * There are no more semicolons, but there's a final name=value pair
         * coming up
         */
        semiptr = strchr(ptr, '\0');
    } while(semiptr);

    if(co->maxage) {
      CURLofft offt;
      offt = curlx_strtoofft((*co->maxage == '\"')?
                             &co->maxage[1]:&co->maxage[0], NULL, 10,
                             &co->expires);
      if(offt == CURL_OFFT_FLOW)
        /* overflow, used max value */
        co->expires = CURL_OFF_T_MAX;
      else if(!offt) {
        if(!co->expires)
          /* already expired */
          co->expires = 1;
        else if(CURL_OFF_T_MAX - now < co->expires)
          /* would overflow */
          co->expires = CURL_OFF_T_MAX;
        else
          co->expires += now;
      }
    }
    else if(co->expirestr) {
      /*
       * Note that if the date couldn't get parsed for whatever reason, the
       * cookie will be treated as a session cookie
       */
      co->expires = Curl_getdate_capped(co->expirestr);

      /*
       * Session cookies have expires set to 0 so if we get that back from the
       * date parser let's add a second to make it a non-session cookie
       */
      if(co->expires == 0)
        co->expires = 1;
      else if(co->expires < 0)
        co->expires = 0;
    }

    if(!badcookie && !co->domain) {
      if(domain) {
        /* no domain was given in the header line, set the default */
        co->domain = strdup(domain);
        if(!co->domain)
          badcookie = TRUE;
      }
    }

    if(!badcookie && !co->path && path) {
      /*
       * No path was given in the header line, set the default.  Note that the
       * passed-in path to this function MAY have a '?' and following part that
       * MUST NOT be stored as part of the path.
       */
      char *queryp = strchr(path, '?');

      /*
       * queryp is where the interesting part of the path ends, so now we
       * want to the find the last
       */
      char *endslash;
      if(!queryp)
        endslash = strrchr(path, '/');
      else
        endslash = memrchr(path, '/', (queryp - path));
      if(endslash) {
        size_t pathlen = (endslash-path + 1); /* include end slash */
        co->path = malloc(pathlen + 1); /* one extra for the zero byte */
        if(co->path) {
          memcpy(co->path, path, pathlen);
          co->path[pathlen] = 0; /* null-terminate */
          co->spath = sanitize_cookie_path(co->path);
          if(!co->spath)
            badcookie = TRUE; /* out of memory bad */
        }
        else
          badcookie = TRUE;
      }
    }

    /*
     * If we didn't get a cookie name, or a bad one, the this is an illegal
     * line so bail out.
     */
    if(badcookie || !co->name) {
      freecookie(co);
      return NULL;
    }
    data->req.setcookies++;
  }
  else {
    /*
     * This line is NOT a HTTP header style line, we do offer support for
     * reading the odd netscape cookies-file format here
     */
    char *ptr;
    char *firstptr;
    char *tok_buf = NULL;
    int fields;

    /*
     * IE introduced HTTP-only cookies to prevent XSS attacks. Cookies marked
     * with httpOnly after the domain name are not accessible from javascripts,
     * but since curl does not operate at javascript level, we include them
     * anyway. In Firefox's cookie files, these lines are preceded with
     * #HttpOnly_ and then everything is as usual, so we skip 10 characters of
     * the line..
     */
    if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
      lineptr += 10;
      co->httponly = TRUE;
    }

    if(lineptr[0]=='#') {
      /* don't even try the comments */
      free(co);
      return NULL;
    }
    /* strip off the possible end-of-line characters */
    ptr = strchr(lineptr, '\r');
    if(ptr)
      *ptr = 0; /* clear it */
    ptr = strchr(lineptr, '\n');
    if(ptr)
      *ptr = 0; /* clear it */

    firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */

    /*
     * Now loop through the fields and init the struct we already have
     * allocated
     */
    for(ptr = firstptr, fields = 0; ptr && !badcookie;
        ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
      switch(fields) {
      case 0:
        if(ptr[0]=='.') /* skip preceding dots */
          ptr++;
        co->domain = strdup(ptr);
        if(!co->domain)
          badcookie = TRUE;
        break;
      case 1:
        /*
         * flag: A TRUE/FALSE value indicating if all machines within a given
         * domain can access the variable. Set TRUE when the cookie says
         * .domain.com and to false when the domain is complete www.domain.com
         */
        co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
        break;
      case 2:
        /* The file format allows the path field to remain not filled in */
        if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
          /* only if the path doesn't look like a boolean option! */
          co->path = strdup(ptr);
          if(!co->path)
            badcookie = TRUE;
          else {
            co->spath = sanitize_cookie_path(co->path);
            if(!co->spath) {
              badcookie = TRUE; /* out of memory bad */
            }
          }
          break;
        }
        /* this doesn't look like a path, make one up! */
        co->path = strdup("/");
        if(!co->path)
          badcookie = TRUE;
        co->spath = strdup("/");
        if(!co->spath)
          badcookie = TRUE;
        fields++; /* add a field and fall down to secure */
        /* FALLTHROUGH */
      case 3:
        co->secure = FALSE;
        if(strcasecompare(ptr, "TRUE")) {
          if(secure || c->running)
            co->secure = TRUE;
          else
            badcookie = TRUE;
        }
        break;
      case 4:
        if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
          badcookie = TRUE;
        break;
      case 5:
        co->name = strdup(ptr);
        if(!co->name)
          badcookie = TRUE;
        else {
          /* For Netscape file format cookies we check prefix on the name */
          if(strncasecompare("__Secure-", co->name, 9))
            co->prefix |= COOKIE_PREFIX__SECURE;
          else if(strncasecompare("__Host-", co->name, 7))
            co->prefix |= COOKIE_PREFIX__HOST;
        }
        break;
      case 6:
        co->value = strdup(ptr);
        if(!co->value)
          badcookie = TRUE;
        break;
      }
    }
    if(6 == fields) {
      /* we got a cookie with blank contents, fix it */
      co->value = strdup("");
      if(!co->value)
        badcookie = TRUE;
      else
        fields++;
    }

    if(!badcookie && (7 != fields))
      /* we did not find the sufficient number of fields */
      badcookie = TRUE;

    if(badcookie) {
      freecookie(co);
      return NULL;
    }

  }

  if(co->prefix & COOKIE_PREFIX__SECURE) {
    /* The __Secure- prefix only requires that the cookie be set secure */
    if(!co->secure) {
      freecookie(co);
      return NULL;
    }
  }
  if(co->prefix & COOKIE_PREFIX__HOST) {
    /*
     * The __Host- prefix requires the cookie to be secure, have a "/" path
     * and not have a domain set.
     */
    if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch)
      ;
    else {
      freecookie(co);
      return NULL;
    }
  }

  if(!c->running &&    /* read from a file */
     c->newsession &&  /* clean session cookies */
     !co->expires) {   /* this is a session cookie since it doesn't expire! */
    freecookie(co);
    return NULL;
  }

  co->livecookie = c->running;
  co->creationtime = ++c->lastct;

  /*
   * Now we have parsed the incoming line, we must now check if this supersedes
   * an already existing cookie, which it may if the previous have the same
   * domain and path as this.
   */

  /* at first, remove expired cookies */
  if(!noexpire)
    remove_expired(c);

#ifdef USE_LIBPSL
  /*
   * Check if the domain is a Public Suffix and if yes, ignore the cookie. We
   * must also check that the data handle isn't NULL since the psl code will
   * dereference it.
   */
  if(data && (domain && co->domain && !Curl_host_is_ipnum(co->domain))) {
    const psl_ctx_t *psl = Curl_psl_use(data);
    int acceptable;

    if(psl) {
      acceptable = psl_is_cookie_domain_acceptable(psl, domain, co->domain);
      Curl_psl_release(data);
    }
    else
      acceptable = !bad_domain(domain);

    if(!acceptable) {
      infof(data, "cookie '%s' dropped, domain '%s' must not "
                  "set cookies for '%s'", co->name, domain, co->domain);
      freecookie(co);
      return NULL;
    }
  }
#endif

  /* A non-secure cookie may not overlay an existing secure cookie. */
  myhash = cookiehash(co->domain);
  clist = c->cookies[myhash];
  while(clist) {
    if(strcasecompare(clist->name, co->name)) {
      /* the names are identical */
      bool matching_domains = FALSE;

      if(clist->domain && co->domain) {
        if(strcasecompare(clist->domain, co->domain))
          /* The domains are identical */
          matching_domains = TRUE;
      }
      else if(!clist->domain && !co->domain)
        matching_domains = TRUE;

      if(matching_domains && /* the domains were identical */
         clist->spath && co->spath && /* both have paths */
         clist->secure && !co->secure && !secure) {
        size_t cllen;
        const char *sep;

        /*
         * A non-secure cookie may not overlay an existing secure cookie.
         * For an existing cookie "a" with path "/login", refuse a new
         * cookie "a" with for example path "/login/en", while the path
         * "/loginhelper" is ok.
         */

        sep = strchr(clist->spath + 1, '/');

        if(sep)
          cllen = sep - clist->spath;
        else
          cllen = strlen(clist->spath);

        if(strncasecompare(clist->spath, co->spath, cllen)) {
          infof(data, "cookie '%s' for domain '%s' dropped, would "
                "overlay an existing cookie", co->name, co->domain);
          freecookie(co);
          return NULL;
        }
      }
    }

    if(!replace_co && strcasecompare(clist->name, co->name)) {
      /* the names are identical */

      if(clist->domain && co->domain) {
        if(strcasecompare(clist->domain, co->domain) &&
          (clist->tailmatch == co->tailmatch))
          /* The domains are identical */
          replace_old = TRUE;
      }
      else if(!clist->domain && !co->domain)
        replace_old = TRUE;

      if(replace_old) {
        /* the domains were identical */

        if(clist->spath && co->spath) {
          if(strcasecompare(clist->spath, co->spath))
            replace_old = TRUE;
          else
            replace_old = FALSE;
        }
        else if(!clist->spath && !co->spath)
          replace_old = TRUE;
        else
          replace_old = FALSE;

      }

      if(replace_old && !co->livecookie && clist->livecookie) {
        /*
         * Both cookies matched fine, except that the already present cookie is
         * "live", which means it was set from a header, while the new one was
         * read from a file and thus isn't "live". "live" cookies are preferred
         * so the new cookie is freed.
         */
        freecookie(co);
        return NULL;
      }
      if(replace_old) {
        replace_co = co;
        replace_clist = clist;
      }
    }
    lastc = clist;
    clist = clist->next;
  }
  if(replace_co) {
    co = replace_co;
    clist = replace_clist;
    co->next = clist->next; /* get the next-pointer first */

    /* when replacing, creationtime is kept from old */
    co->creationtime = clist->creationtime;

    /* then free all the old pointers */
    free(clist->name);
    free(clist->value);
    free(clist->domain);
    free(clist->path);
    free(clist->spath);
    free(clist->expirestr);
    free(clist->version);
    free(clist->maxage);

    *clist = *co;  /* then store all the new data */

    free(co);   /* free the newly allocated memory */
    co = clist;
  }

  if(c->running)
    /* Only show this when NOT reading the cookies from a file */
    infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
          "expire %" CURL_FORMAT_CURL_OFF_T,
          replace_old?"Replaced":"Added", co->name, co->value,
          co->domain, co->path, co->expires);

  if(!replace_old) {
    /* then make the last item point on this new one */
    if(lastc)
      lastc->next = co;
    else
      c->cookies[myhash] = co;
    c->numcookies++; /* one more cookie in the jar */
  }

  /*
   * Now that we've added a new cookie to the jar, update the expiration
   * tracker in case it is the next one to expire.
   */
  if(co->expires && (co->expires < c->next_expiration))
    c->next_expiration = co->expires;

  return co;
}


uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr) { VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev); uint16_t val; k->get_config(vdev, vdev->config); if (addr > (vdev->config_len - sizeof(val))) return (uint32_t)-1; val = lduw_p(vdev->config + addr); return val; }


static void * Type_LUT8_Read ( struct _cms_typehandler_struct * self , cmsIOHANDLER * io , cmsUInt32Number * nItems , cmsUInt32Number SizeOfTag ) {
 cmsUInt8Number InputChannels , OutputChannels , CLUTpoints ;
 cmsUInt8Number * Temp = NULL ;
 cmsPipeline * NewLUT = NULL ;
 cmsUInt32Number nTabSize , i ;
 cmsFloat64Number Matrix [ 3 * 3 ] ;
 * nItems = 0 ;
 if ( ! _cmsReadUInt8Number ( io , & InputChannels ) ) goto Error ;
 if ( ! _cmsReadUInt8Number ( io , & OutputChannels ) ) goto Error ;
 if ( ! _cmsReadUInt8Number ( io , & CLUTpoints ) ) goto Error ;
 if ( CLUTpoints == 1 ) goto Error ;
 if ( ! _cmsReadUInt8Number ( io , NULL ) ) goto Error ;
 if ( InputChannels > cmsMAXCHANNELS ) goto Error ;
 if ( OutputChannels > cmsMAXCHANNELS ) goto Error ;
 NewLUT = cmsPipelineAlloc ( self -> ContextID , InputChannels , OutputChannels ) ;
 if ( NewLUT == NULL ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 0 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 1 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 2 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 3 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 4 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 5 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 6 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 7 ] ) ) goto Error ;
 if ( ! _cmsRead15Fixed16Number ( io , & Matrix [ 8 ] ) ) goto Error ;
 if ( ( InputChannels == 3 ) && ! _cmsMAT3isIdentity ( ( cmsMAT3 * ) Matrix ) ) {
 if ( ! cmsPipelineInsertStage ( NewLUT , cmsAT_BEGIN , cmsStageAllocMatrix ( self -> ContextID , 3 , 3 , Matrix , NULL ) ) ) goto Error ;
 }
 if ( ! Read8bitTables ( self -> ContextID , io , NewLUT , InputChannels ) ) goto Error ;
 nTabSize = uipow ( OutputChannels , CLUTpoints , InputChannels ) ;
 if ( nTabSize == ( cmsUInt32Number ) - 1 ) goto Error ;
 if ( nTabSize > 0 ) {
 cmsUInt16Number * PtrW , * T ;
 PtrW = T = ( cmsUInt16Number * ) _cmsCalloc ( self -> ContextID , nTabSize , sizeof ( cmsUInt16Number ) ) ;
 if ( T == NULL ) goto Error ;
 Temp = ( cmsUInt8Number * ) _cmsMalloc ( self -> ContextID , nTabSize ) ;
 if ( Temp == NULL ) {
 _cmsFree ( self -> ContextID , T ) ;
 goto Error ;
 }
 if ( io -> Read ( io , Temp , nTabSize , 1 ) != 1 ) {
 _cmsFree ( self -> ContextID , T ) ;
 _cmsFree ( self -> ContextID , Temp ) ;
 goto Error ;
 }
 for ( i = 0 ;
 i < nTabSize ;
 i ++ ) {
 * PtrW ++ = FROM_8_TO_16 ( Temp [ i ] ) ;
 }
 _cmsFree ( self -> ContextID , Temp ) ;
 Temp = NULL ;
 if ( ! cmsPipelineInsertStage ( NewLUT , cmsAT_END , cmsStageAllocCLut16bit ( self -> ContextID , CLUTpoints , InputChannels , OutputChannels , T ) ) ) goto Error ;
 _cmsFree ( self -> ContextID , T ) ;
 }
 if ( ! Read8bitTables ( self -> ContextID , io , NewLUT , OutputChannels ) ) goto Error ;
 * nItems = 1 ;
 return NewLUT ;
 Error : if ( NewLUT != NULL ) cmsPipelineFree ( NewLUT ) ;
 return NULL ;
 cmsUNUSED_PARAMETER ( SizeOfTag ) ;
 }


int libevt_record_values_initialize ( libevt_record_values_t * * record_values , libcerror_error_t * * error ) {
 static char * function = "libevt_record_values_initialize" ;
 if ( record_values == NULL ) {
 libcerror_error_set ( error , LIBCERROR_ERROR_DOMAIN_ARGUMENTS , LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE , "%s: invalid record values." , function ) ;
 return ( - 1 ) ;
 }
 if ( * record_values != NULL ) {
 libcerror_error_set ( error , LIBCERROR_ERROR_DOMAIN_RUNTIME , LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET , "%s: invalid record values value already set." , function ) ;
 return ( - 1 ) ;
 }
 * record_values = memory_allocate_structure ( libevt_record_values_t ) ;
 if ( * record_values == NULL ) {
 libcerror_error_set ( error , LIBCERROR_ERROR_DOMAIN_MEMORY , LIBCERROR_MEMORY_ERROR_INSUFFICIENT , "%s: unable to create record values." , function ) ;
 goto on_error ;
 }
 if ( memory_set ( * record_values , 0 , sizeof ( libevt_record_values_t ) ) == NULL ) {
 libcerror_error_set ( error , LIBCERROR_ERROR_DOMAIN_MEMORY , LIBCERROR_MEMORY_ERROR_SET_FAILED , "%s: unable to clear record values." , function ) ;
 goto on_error ;
 }
 return ( 1 ) ;
 on_error : if ( * record_values != NULL ) {
 memory_free ( * record_values ) ;
 * record_values = NULL ;
 }
 return ( - 1 ) ;
 }


static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t total_size = 0; MOVAtom a; int i; if (atom.size < 0) atom.size = INT64_MAX; while (total_size + 8 <= atom.size && !url_feof(pb)) { int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL; a.size = atom.size; a.type=0; if (atom.size >= 8) { a.size = avio_rb32(pb); a.type = avio_rl32(pb); total_size += 8; if (a.size == 1) { /* 64 bit extended size */ a.size = avio_rb64(pb) - 8; total_size += 8; } } av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n", a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size); if (a.size == 0) { a.size = atom.size - total_size + 8; if (a.size <= 8) break; } a.size -= 8; if (a.size < 0) break; a.size = FFMIN(a.size, atom.size - total_size); for (i = 0; mov_default_parse_table[i].type; i++) if (mov_default_parse_table[i].type == a.type) { parse = mov_default_parse_table[i].parse; break; } // container is user data if (!parse && (atom.type == MKTAG('u','d','t','a') || atom.type == MKTAG('i','l','s','t'))) parse = mov_read_udta_string; if (!parse) { /* skip leaf atoms data */ avio_skip(pb, a.size); } else { int64_t start_pos = avio_tell(pb); int64_t left; int err = parse(c, pb, a); if (err < 0) return err; if (c->found_moov && c->found_mdat && (!pb->seekable || start_pos + a.size == avio_size(pb))) return 0; left = a.size - avio_tell(pb) + start_pos; if (left > 0) /* skip garbage at atom end */ avio_skip(pb, left); } total_size += a.size; } if (total_size < atom.size && atom.size < 0x7ffff) avio_skip(pb, atom.size - total_size); return 0; }


static void encode_subband_c0run(SnowContext *s, SubBand *b, DWTELEM *src, DWTELEM *parent, int stride, int orientation){ const int w= b->width; const int h= b->height; int x, y; if(1){ int run=0; int runs[w*h]; int run_index=0; for(y=0; y<h; y++){ for(x=0; x<w; x++){ int v, p=0; int /*ll=0, */l=0, lt=0, t=0, rt=0; v= src[x + y*stride]; if(y){ t= src[x + (y-1)*stride]; if(x){ lt= src[x - 1 + (y-1)*stride]; } if(x + 1 < w){ rt= src[x + 1 + (y-1)*stride]; } } if(x){ l= src[x - 1 + y*stride]; /*if(x > 1){ if(orientation==1) ll= src[y + (x-2)*stride]; else ll= src[x - 2 + y*stride]; }*/ } if(parent){ int px= x>>1; int py= y>>1; if(px<b->parent->width && py<b->parent->height) p= parent[px + py*2*stride]; } if(!(/*ll|*/l|lt|t|rt|p)){ if(v){ runs[run_index++]= run; run=0; }else{ run++; } } } } runs[run_index++]= run; run_index=0; run= runs[run_index++]; put_symbol2(&s->c, b->state[1], run, 3); for(y=0; y<h; y++){ for(x=0; x<w; x++){ int v, p=0; int /*ll=0, */l=0, lt=0, t=0, rt=0; v= src[x + y*stride]; if(y){ t= src[x + (y-1)*stride]; if(x){ lt= src[x - 1 + (y-1)*stride]; } if(x + 1 < w){ rt= src[x + 1 + (y-1)*stride]; } } if(x){ l= src[x - 1 + y*stride]; /*if(x > 1){ if(orientation==1) ll= src[y + (x-2)*stride]; else ll= src[x - 2 + y*stride]; }*/ } if(parent){ int px= x>>1; int py= y>>1; if(px<b->parent->width && py<b->parent->height) p= parent[px + py*2*stride]; } if(/*ll|*/l|lt|t|rt|p){ int context= av_log2(/*ABS(ll) + */3*ABS(l) + ABS(lt) + 2*ABS(t) + ABS(rt) + ABS(p)); put_rac(&s->c, &b->state[0][context], !!v); }else{ if(!run){ run= runs[run_index++]; put_symbol2(&s->c, b->state[1], run, 3); assert(v); }else{ run--; assert(!v); } } if(v){ int context= av_log2(/*ABS(ll) + */3*ABS(l) + ABS(lt) + 2*ABS(t) + ABS(rt) + ABS(p)); put_symbol2(&s->c, b->state[context + 2], ABS(v)-1, context-4); put_rac(&s->c, &b->state[0][16 + 1 + 3 + quant3b[l&0xFF] + 3*quant3b[t&0xFF]], v<0); } } } } }


  void Compute(OpKernelContext* ctx) final {
    const Tensor& indices = ctx->input(0);
    const Tensor& values = ctx->input(1);
    const Tensor& dense_shape = ctx->input(2);
    const int rank = dense_shape.NumElements();
    OP_REQUIRES(ctx, rank == 2 || rank == 3,
                errors::InvalidArgument("SparseTensor must have rank 2 or 3; ",
                                        "but indices has rank: ", rank));
    auto dense_shape_vec = dense_shape.vec<int64_t>();
    const int64_t batch_size = (rank == 2) ? 1 : dense_shape_vec(0);
    const int64_t num_rows = dense_shape_vec((rank == 2) ? 0 : 1);
    const int64_t total_nnz = values.NumElements();

    // Allocate output Tensors.
    TensorShape batch_ptr_shape;
    OP_REQUIRES_OK(
        ctx, TensorShape::BuildTensorShape({batch_size + 1}, &batch_ptr_shape));
    Tensor batch_ptr(cpu_allocator(), DT_INT32, batch_ptr_shape);
    TensorShape csr_col_ind_shape;
    OP_REQUIRES_OK(
        ctx, TensorShape::BuildTensorShape({total_nnz}, &csr_col_ind_shape));
    Tensor csr_col_ind(cpu_allocator(), DT_INT32, csr_col_ind_shape);
    TensorShape csr_row_ind_shape;
    OP_REQUIRES_OK(ctx, TensorShape::BuildTensorShape(
                            {(num_rows + 1) * batch_size}, &csr_row_ind_shape));
    Tensor csr_row_ptr(cpu_allocator(), DT_INT32, csr_row_ind_shape);

    // Fill the row pointers with zeros.
    functor::SetZeroFunctor<CPUDevice, int32> set_zero;
    set_zero(ctx->eigen_device<CPUDevice>(), csr_row_ptr.flat<int32>());

    // Convert from COO to CSR format.
    functor::SparseTensorToCSRSparseMatrixCPUFunctor coo_to_csr;
    OP_REQUIRES_OK(
        ctx,
        coo_to_csr(batch_size, num_rows, indices.template matrix<int64_t>(),
                   batch_ptr.vec<int32>(), csr_row_ptr.vec<int32>(),
                   csr_col_ind.vec<int32>()));

    // Create the CSRSparseMatrix object from its component Tensors and prepare
    // the Variant output Tensor.
    CSRSparseMatrix output_csr_matrix;
    OP_REQUIRES_OK(
        ctx, CSRSparseMatrix::CreateCSRSparseMatrix(
                 DataTypeToEnum<T>::value, dense_shape, batch_ptr, csr_row_ptr,
                 csr_col_ind, values, &output_csr_matrix));
    Tensor* output_csr_matrix_tensor;
    AllocatorAttributes cpu_alloc;
    cpu_alloc.set_on_host(true);
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output(0, TensorShape({}), &output_csr_matrix_tensor,
                                  cpu_alloc));
    output_csr_matrix_tensor->scalar<Variant>()() =
        std::move(output_csr_matrix);
  }


static int alloc_buffer(InputStream *ist, FrameBuffer **pbuf) { AVCodecContext *s = ist->st->codec; FrameBuffer *buf = av_mallocz(sizeof(*buf)); int ret; const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1; int h_chroma_shift, v_chroma_shift; int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1 int w = s->width, h = s->height; if (!buf) return AVERROR(ENOMEM); if (!(s->flags & CODEC_FLAG_EMU_EDGE)) { w += 2*edge; h += 2*edge; } avcodec_align_dimensions(s, &w, &h); if ((ret = av_image_alloc(buf->base, buf->linesize, w, h, s->pix_fmt, 32)) < 0) { av_freep(&buf); return ret; } /* XXX this shouldn't be needed, but some tests break without this line * those decoders are buggy and need to be fixed. * the following tests fail: * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit */ memset(buf->base[0], 128, ret); avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift); for (int i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) { const int h_shift = i==0 ? 0 : h_chroma_shift; const int v_shift = i==0 ? 0 : v_chroma_shift; if (s->flags & CODEC_FLAG_EMU_EDGE) buf->data[i] = buf->base[i]; else buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*edge >> v_shift) + (pixel_size*edge >> h_shift), 32); } buf->w = s->width; buf->h = s->height; buf->pix_fmt = s->pix_fmt; buf->ist = ist; *pbuf = buf; return 0; }


static void mips_jazz_machine_init ( void ) {
 qemu_register_machine ( & mips_magnum_machine ) ;
 qemu_register_machine ( & mips_pica61_machine ) ;
 }


int http_version_print ( int32_t version , char * buf , int bufsize , int * bufindex , int * dumpoffset ) {
 # define TRY ( x ) if ( ! x ) return 0 char tmpbuf [ 16 ] ;
 http_hdr_version_to_string ( version , tmpbuf ) ;
 TRY ( mime_mem_print ( tmpbuf , 8 , buf , bufsize , bufindex , dumpoffset ) ) ;
 return 1 ;
 # undef TRY }


static bool vring_notify(VirtIODevice *vdev, VirtQueue *vq) { uint16_t old, new; bool v; /* Always notify when queue is empty (when feature acknowledge) */ if (((vdev->guest_features & (1 << VIRTIO_F_NOTIFY_ON_EMPTY)) && !vq->inuse && vring_avail_idx(vq) == vq->last_avail_idx)) { return true; } if (!(vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX))) { return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT); } v = vq->signalled_used_valid; vq->signalled_used_valid = true; old = vq->signalled_used; new = vq->signalled_used = vring_used_idx(vq); return !v || vring_need_event(vring_used_event(vq), new, old); }


void qtest_qmp_discard_response(QTestState *s, const char *fmt, ...) { va_list ap; va_start(ap, fmt); qtest_qmpv_discard_response(s, fmt, ap); va_end(ap); }


TEST_F ( BrowsingDataRemoverImplTest , CompletionInhibition ) {
 BrowsingDataRemoverCompletionInhibitor completion_inhibitor ;
 BrowsingDataRemoverImpl * remover = static_cast < BrowsingDataRemoverImpl * > ( BrowsingDataRemoverFactory : : GetForBrowserContext ( GetBrowserContext ( ) ) ) ;
 InspectableCompletionObserver completion_observer ( remover ) ;
 remover -> RemoveAndReply ( base : : Time ( ) , base : : Time : : Max ( ) , BrowsingDataRemover : : REMOVE_HISTORY , BrowsingDataHelper : : UNPROTECTED_WEB , & completion_observer ) ;
 completion_inhibitor . BlockUntilNearCompletion ( ) ;
 base : : RunLoop ( ) . RunUntilIdle ( ) ;
 EXPECT_TRUE ( remover -> is_removing ( ) ) ;
 EXPECT_FALSE ( completion_observer . called ( ) ) ;
 completion_inhibitor . ContinueToCompletion ( ) ;
 completion_observer . BlockUntilCompletion ( ) ;
 EXPECT_FALSE ( remover -> is_removing ( ) ) ;
 EXPECT_TRUE ( completion_observer . called ( ) ) ;
 }


static void http_bad_request ( void ) {
 struct timeval tv ;
 struct bufferevent * bev ;
 int fd ;
 const char * http_request ;
 short port = - 1 ;
 test_ok = 0 ;
 fprintf ( stdout , "Testing \"Bad Request\" on connection close: " ) ;
 http = http_setup ( & port , NULL ) ;
 if ( evhttp_bind_socket ( http , "127.0.0.1" , port + 1 ) == - 1 ) {
 fprintf ( stdout , "FAILED (bind)\n" ) ;
 exit ( 1 ) ;
 }
 fd = http_connect ( "127.0.0.1" , port ) ;
 bev = bufferevent_new ( fd , http_badreq_readcb , http_writecb , http_badreq_errorcb , NULL ) ;
 bufferevent_enable ( bev , EV_READ ) ;
 http_request = "" ;
 shutdown ( fd , SHUT_WR ) ;
 timerclear ( & tv ) ;
 tv . tv_usec = 10000 ;
 event_once ( - 1 , EV_TIMEOUT , http_badreq_successcb , bev , & tv ) ;
 event_dispatch ( ) ;
 bufferevent_free ( bev ) ;
 EVUTIL_CLOSESOCKET ( fd ) ;
 if ( test_ok != 0 ) {
 fprintf ( stdout , "FAILED\n" ) ;
 exit ( 1 ) ;
 }
 fd = http_connect ( "127.0.0.1" , port + 1 ) ;
 bev = bufferevent_new ( fd , http_badreq_readcb , http_writecb , http_badreq_errorcb , NULL ) ;
 bufferevent_enable ( bev , EV_READ ) ;
 http_request = "GET /badrequest HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "\r\n" ;
 bufferevent_write ( bev , http_request , strlen ( http_request ) ) ;
 timerclear ( & tv ) ;
 tv . tv_usec = 10000 ;
 event_once ( - 1 , EV_TIMEOUT , http_badreq_successcb , bev , & tv ) ;
 event_dispatch ( ) ;
 evhttp_free ( http ) ;
 if ( test_ok != 2 ) {
 fprintf ( stdout , "FAILED\n" ) ;
 exit ( 1 ) ;
 }
 fprintf ( stdout , "OK\n" ) ;
 }


static av_cold int nvenc_encode_init(AVCodecContext *avctx) { NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 }; NV_ENC_PRESET_CONFIG preset_config = { 0 }; CUcontext cu_context_curr; CUresult cu_res; GUID encoder_preset = NV_ENC_PRESET_HQ_GUID; GUID codec; NVENCSTATUS nv_status = NV_ENC_SUCCESS; int surfaceCount = 0; int i, num_mbs; int isLL = 0; int res = 0; int dw, dh; NvencContext *ctx = avctx->priv_data; NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs; NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs; if (!nvenc_dyload_nvenc(avctx)) return AVERROR_EXTERNAL; avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { res = AVERROR(ENOMEM); goto error; } ctx->last_dts = AV_NOPTS_VALUE; ctx->encode_config.version = NV_ENC_CONFIG_VER; ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER; preset_config.version = NV_ENC_PRESET_CONFIG_VER; preset_config.presetCfg.version = NV_ENC_CONFIG_VER; encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER; encode_session_params.apiVersion = NVENCAPI_VERSION; if (ctx->gpu >= dl_fn->nvenc_device_count) { av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count); res = AVERROR(EINVAL); goto error; } ctx->cu_context = NULL; cu_res = dl_fn->cu_ctx_create(&ctx->cu_context, 0, dl_fn->nvenc_devices[ctx->gpu]); if (cu_res != CUDA_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res); res = AVERROR_EXTERNAL; goto error; } cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr); if (cu_res != CUDA_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res); res = AVERROR_EXTERNAL; goto error; } encode_session_params.device = ctx->cu_context; encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA; nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder); if (nv_status != NV_ENC_SUCCESS) { ctx->nvencoder = NULL; av_log(avctx, AV_LOG_FATAL, "OpenEncodeSessionEx failed: 0x%x - invalid license key?\n", (int)nv_status); res = AVERROR_EXTERNAL; goto error; } if (ctx->preset) { if (!strcmp(ctx->preset, "hp")) { encoder_preset = NV_ENC_PRESET_HP_GUID; } else if (!strcmp(ctx->preset, "hq")) { encoder_preset = NV_ENC_PRESET_HQ_GUID; } else if (!strcmp(ctx->preset, "bd")) { encoder_preset = NV_ENC_PRESET_BD_GUID; } else if (!strcmp(ctx->preset, "ll")) { encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID; isLL = 1; } else if (!strcmp(ctx->preset, "llhp")) { encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID; isLL = 1; } else if (!strcmp(ctx->preset, "llhq")) { encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID; isLL = 1; } else if (!strcmp(ctx->preset, "default")) { encoder_preset = NV_ENC_PRESET_DEFAULT_GUID; } else { av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: hp, hq, bd, ll, llhp, llhq, default\n", ctx->preset); res = AVERROR(EINVAL); goto error; } } switch (avctx->codec->id) { case AV_CODEC_ID_H264: codec = NV_ENC_CODEC_H264_GUID; break; case AV_CODEC_ID_H265: codec = NV_ENC_CODEC_HEVC_GUID; break; default: av_log(avctx, AV_LOG_ERROR, "nvenc: Unknown codec name\n"); res = AVERROR(EINVAL); goto error; } nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config); if (nv_status != NV_ENC_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "GetEncodePresetConfig failed: 0x%x\n", (int)nv_status); res = AVERROR_EXTERNAL; goto error; } ctx->init_encode_params.encodeGUID = codec; ctx->init_encode_params.encodeHeight = avctx->height; ctx->init_encode_params.encodeWidth = avctx->width; if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den && (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) { av_reduce(&dw, &dh, avctx->width * avctx->sample_aspect_ratio.num, avctx->height * avctx->sample_aspect_ratio.den, 1024 * 1024); ctx->init_encode_params.darHeight = dh; ctx->init_encode_params.darWidth = dw; } else { ctx->init_encode_params.darHeight = avctx->height; ctx->init_encode_params.darWidth = avctx->width; } // De-compensate for hardware, dubiously, trying to compensate for // playback at 704 pixel width. if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) { av_reduce(&dw, &dh, ctx->init_encode_params.darWidth * 44, ctx->init_encode_params.darHeight * 45, 1024 * 1024); ctx->init_encode_params.darHeight = dh; ctx->init_encode_params.darWidth = dw; } ctx->init_encode_params.frameRateNum = avctx->time_base.den; ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame; num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4); ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48; ctx->init_encode_params.enableEncodeAsync = 0; ctx->init_encode_params.enablePTD = 1; ctx->init_encode_params.presetGUID = encoder_preset; ctx->init_encode_params.encodeConfig = &ctx->encode_config; memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config)); ctx->encode_config.version = NV_ENC_CONFIG_VER; if (avctx->refs >= 0) { /* 0 means "let the hardware decide" */ switch (avctx->codec->id) { case AV_CODEC_ID_H264: ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs; break; case AV_CODEC_ID_H265: ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs; break; /* Earlier switch/case will return if unknown codec is passed. */ } } if (avctx->gop_size > 0) { if (avctx->max_b_frames >= 0) { /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */ ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1; } ctx->encode_config.gopLength = avctx->gop_size; switch (avctx->codec->id) { case AV_CODEC_ID_H264: ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size; break; case AV_CODEC_ID_H265: ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size; break; /* Earlier switch/case will return if unknown codec is passed. */ } } else if (avctx->gop_size == 0) { ctx->encode_config.frameIntervalP = 0; ctx->encode_config.gopLength = 1; switch (avctx->codec->id) { case AV_CODEC_ID_H264: ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1; break; case AV_CODEC_ID_H265: ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1; break; /* Earlier switch/case will return if unknown codec is passed. */ } } /* when there're b frames, set dts offset */ if (ctx->encode_config.frameIntervalP >= 2) ctx->last_dts = -2; if (avctx->bit_rate > 0) ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate; if (avctx->rc_max_rate > 0) ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate; if (ctx->cbr) { if (!ctx->twopass) { ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR; } else if (ctx->twopass == 1 || isLL) { ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY; if (avctx->codec->id == AV_CODEC_ID_H264) { ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE; ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE; } if (!isLL) av_log(avctx, AV_LOG_WARNING, "Twopass mode is only known to work with low latency (ll, llhq, llhp) presets.\n"); } else { ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR; } } else if (avctx->global_quality > 0) { ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP; ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality; ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality; ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality; avctx->qmin = -1; avctx->qmax = -1; } else if (avctx->qmin >= 0 && avctx->qmax >= 0) { ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR; ctx->encode_config.rcParams.enableMinQP = 1; ctx->encode_config.rcParams.enableMaxQP = 1; ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin; ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin; ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin; ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax; ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax; ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax; } if (avctx->rc_buffer_size > 0) ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size; if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) { ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD; } else { ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME; } switch (avctx->codec->id) { case AV_CODEC_ID_H264: ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1; ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1; ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace; ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries; ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc; ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG; ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0; ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1; if (!ctx->profile) { switch (avctx->profile) { case FF_PROFILE_H264_BASELINE: ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID; break; case FF_PROFILE_H264_MAIN: ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID; break; case FF_PROFILE_H264_HIGH: case FF_PROFILE_UNKNOWN: ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID; break; default: av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n"); ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID; break; } } else { if (!strcmp(ctx->profile, "high")) { ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID; avctx->profile = FF_PROFILE_H264_HIGH; } else if (!strcmp(ctx->profile, "main")) { ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID; avctx->profile = FF_PROFILE_H264_MAIN; } else if (!strcmp(ctx->profile, "baseline")) { ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID; avctx->profile = FF_PROFILE_H264_BASELINE; } else { av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile); res = AVERROR(EINVAL); goto error; } } if (ctx->level) { res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level); if (res) { av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 1b, 1.1, 1.2, 1.3, 2, 2.1, 2.2, 3, 3.1, 3.2, 4, 4.1, 4.2, 5, 5.1\n", ctx->level); goto error; } } else { ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT; } break; case AV_CODEC_ID_H265: ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0; ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1; /* No other profile is supported in the current SDK version 5 */ ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID; avctx->profile = FF_PROFILE_HEVC_MAIN; if (ctx->level) { res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level); if (res) { av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2\n", ctx->level); goto error; } } else { ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT; } if (ctx->tier) { if (!strcmp(ctx->tier, "main")) { ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN; } else if (!strcmp(ctx->tier, "high")) { ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH; } else { av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier); res = AVERROR(EINVAL); goto error; } } break; /* Earlier switch/case will return if unknown codec is passed. */ } nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params); if (nv_status != NV_ENC_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "InitializeEncoder failed: 0x%x\n", (int)nv_status); res = AVERROR_EXTERNAL; goto error; } ctx->input_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->input_surfaces)); if (!ctx->input_surfaces) { res = AVERROR(ENOMEM); goto error; } ctx->output_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->output_surfaces)); if (!ctx->output_surfaces) { res = AVERROR(ENOMEM); goto error; } for (surfaceCount = 0; surfaceCount < ctx->max_surface_count; ++surfaceCount) { NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 }; NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 }; allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER; allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER; allocSurf.width = (avctx->width + 31) & ~31; allocSurf.height = (avctx->height + 31) & ~31; allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED; switch (avctx->pix_fmt) { case AV_PIX_FMT_YUV420P: allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL; break; case AV_PIX_FMT_NV12: allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL; break; case AV_PIX_FMT_YUV444P: allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL; break; default: av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n"); res = AVERROR(EINVAL); goto error; } nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf); if (nv_status != NV_ENC_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "CreateInputBuffer failed\n"); res = AVERROR_EXTERNAL; goto error; } ctx->input_surfaces[surfaceCount].lockCount = 0; ctx->input_surfaces[surfaceCount].input_surface = allocSurf.inputBuffer; ctx->input_surfaces[surfaceCount].format = allocSurf.bufferFmt; ctx->input_surfaces[surfaceCount].width = allocSurf.width; ctx->input_surfaces[surfaceCount].height = allocSurf.height; /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */ allocOut.size = 1024 * 1024; allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED; nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut); if (nv_status != NV_ENC_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "CreateBitstreamBuffer failed\n"); ctx->output_surfaces[surfaceCount++].output_surface = NULL; res = AVERROR_EXTERNAL; goto error; } ctx->output_surfaces[surfaceCount].output_surface = allocOut.bitstreamBuffer; ctx->output_surfaces[surfaceCount].size = allocOut.size; ctx->output_surfaces[surfaceCount].busy = 0; } if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) { uint32_t outSize = 0; char tmpHeader[256]; NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 }; payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER; payload.spsppsBuffer = tmpHeader; payload.inBufferSize = sizeof(tmpHeader); payload.outSPSPPSPayloadSize = &outSize; nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload); if (nv_status != NV_ENC_SUCCESS) { av_log(avctx, AV_LOG_FATAL, "GetSequenceParams failed\n"); goto error; } avctx->extradata_size = outSize; avctx->extradata = av_mallocz(outSize + FF_INPUT_BUFFER_PADDING_SIZE); if (!avctx->extradata) { res = AVERROR(ENOMEM); goto error; } memcpy(avctx->extradata, tmpHeader, outSize); } if (ctx->encode_config.frameIntervalP > 1) avctx->has_b_frames = 2; if (ctx->encode_config.rcParams.averageBitRate > 0) avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate; return 0; error: for (i = 0; i < surfaceCount; ++i) { p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface); if (ctx->output_surfaces[i].output_surface) p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface); } if (ctx->nvencoder) p_nvenc->nvEncDestroyEncoder(ctx->nvencoder); if (ctx->cu_context) dl_fn->cu_ctx_destroy(ctx->cu_context); av_frame_free(&avctx->coded_frame); nvenc_unload_nvenc(avctx); ctx->nvencoder = NULL; ctx->cu_context = NULL; return res; }


m48t59_t *m48t59_init_isa(uint32_t io_base, uint16_t size, int type) { M48t59ISAState *d; ISADevice *dev; m48t59_t *s; dev = isa_create("m48t59_isa"); qdev_prop_set_uint32(&dev->qdev, "type", type); qdev_prop_set_uint32(&dev->qdev, "size", size); qdev_prop_set_uint32(&dev->qdev, "io_base", io_base); qdev_init(&dev->qdev); d = DO_UPCAST(M48t59ISAState, busdev, dev); s = &d->state; if (io_base != 0) { register_ioport_read(io_base, 0x04, 1, NVRAM_readb, s); register_ioport_write(io_base, 0x04, 1, NVRAM_writeb, s); } return s; }


static void sdhci_do_data_transfer(void *opaque) { SDHCIState *s = (SDHCIState *)opaque; SDHCI_GET_CLASS(s)->data_transfer(s); }


struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
				const u8 *addr, gfp_t gfp)
{
	struct ieee80211_local *local = sdata->local;
	struct sta_info *sta;
	struct timespec uptime;
	struct ieee80211_tx_latency_bin_ranges *tx_latency;
	int i;

	sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp);
	if (!sta)
		return NULL;

	rcu_read_lock();
	tx_latency = rcu_dereference(local->tx_latency);
	/* init stations Tx latency statistics && TID bins */
	if (tx_latency) {
		sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS *
				      sizeof(struct ieee80211_tx_latency_stat),
				      GFP_ATOMIC);
		if (!sta->tx_lat) {
			rcu_read_unlock();
			goto free;
		}

		if (tx_latency->n_ranges) {
			for (i = 0; i < IEEE80211_NUM_TIDS; i++) {
				/* size of bins is size of the ranges +1 */
				sta->tx_lat[i].bin_count =
					tx_latency->n_ranges + 1;
				sta->tx_lat[i].bins =
					kcalloc(sta->tx_lat[i].bin_count,
						sizeof(u32), GFP_ATOMIC);
				if (!sta->tx_lat[i].bins) {
					rcu_read_unlock();
					goto free;
				}
			}
		}
	}
	rcu_read_unlock();

	spin_lock_init(&sta->lock);
	INIT_WORK(&sta->drv_unblock_wk, sta_unblock);
	INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work);
	mutex_init(&sta->ampdu_mlme.mtx);
#ifdef CONFIG_MAC80211_MESH
	if (ieee80211_vif_is_mesh(&sdata->vif) &&
	    !sdata->u.mesh.user_mpm)
		init_timer(&sta->plink_timer);
	sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE;
#endif

	memcpy(sta->sta.addr, addr, ETH_ALEN);
	sta->local = local;
	sta->sdata = sdata;
	sta->last_rx = jiffies;

	sta->sta_state = IEEE80211_STA_NONE;

	do_posix_clock_monotonic_gettime(&uptime);
	sta->last_connected = uptime.tv_sec;
	ewma_init(&sta->avg_signal, 1024, 8);
	for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++)
		ewma_init(&sta->chain_signal_avg[i], 1024, 8);

	if (sta_prepare_rate_control(local, sta, gfp))
		goto free;

	for (i = 0; i < IEEE80211_NUM_TIDS; i++) {
		/*
		 * timer_to_tid must be initialized with identity mapping
		 * to enable session_timer's data differentiation. See
		 * sta_rx_agg_session_timer_expired for usage.
		 */
		sta->timer_to_tid[i] = i;
	}
	for (i = 0; i < IEEE80211_NUM_ACS; i++) {
		skb_queue_head_init(&sta->ps_tx_buf[i]);
		skb_queue_head_init(&sta->tx_filtered[i]);
	}

	for (i = 0; i < IEEE80211_NUM_TIDS; i++)
		sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX);

	sta->sta.smps_mode = IEEE80211_SMPS_OFF;
	if (sdata->vif.type == NL80211_IFTYPE_AP ||
	    sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
		struct ieee80211_supported_band *sband =
			local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)];
		u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >>
				IEEE80211_HT_CAP_SM_PS_SHIFT;
		/*
		 * Assume that hostapd advertises our caps in the beacon and
		 * this is the known_smps_mode for a station that just assciated
		 */
		switch (smps) {
		case WLAN_HT_SMPS_CONTROL_DISABLED:
			sta->known_smps_mode = IEEE80211_SMPS_OFF;
			break;
		case WLAN_HT_SMPS_CONTROL_STATIC:
			sta->known_smps_mode = IEEE80211_SMPS_STATIC;
			break;
		case WLAN_HT_SMPS_CONTROL_DYNAMIC:
			sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC;
			break;
		default:
			WARN_ON(1);
		}
	}

	sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr);
	return sta;

free:
	if (sta->tx_lat) {
		for (i = 0; i < IEEE80211_NUM_TIDS; i++)
			kfree(sta->tx_lat[i].bins);
		kfree(sta->tx_lat);
	}
	kfree(sta);
	return NULL;
}


static int blkdebug_co_flush(BlockDriverState *bs) { BDRVBlkdebugState *s = bs->opaque; BlkdebugRule *rule = NULL; QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) { if (rule->options.inject.offset == -1) { break; } } if (rule && rule->options.inject.error) { return inject_error(bs, rule); } return bdrv_co_flush(bs->file->bs); }


static void proto_tree_set_float ( field_info * fi , float value ) {
 fvalue_set_floating ( & fi -> value , value ) ;
 }


static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config) { VirtIOBlock *s = VIRTIO_BLK(vdev); struct virtio_blk_config blkcfg; memcpy(&blkcfg, config, sizeof(blkcfg)); aio_context_acquire(bdrv_get_aio_context(s->bs)); bdrv_set_enable_write_cache(s->bs, blkcfg.wce != 0); aio_context_release(bdrv_get_aio_context(s->bs)); }