id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_2858_0 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright IBM Corp. 2007
*
* Authors: Hollis Blanchard <hollisb@us.ibm.com>
* Christian Ehrhardt <ehrhardt@linux.vnet.ibm.com>
*/
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/kvm_host.h>
#include <linux/vmalloc.h>
#include <linux/hrtimer.h>
#include <linux/sched/signal.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/module.h>
#include <linux/irqbypass.h>
#include <linux/kvm_irqfd.h>
#include <asm/cputable.h>
#include <linux/uaccess.h>
#include <asm/kvm_ppc.h>
#include <asm/tlbflush.h>
#include <asm/cputhreads.h>
#include <asm/irqflags.h>
#include <asm/iommu.h>
#include <asm/switch_to.h>
#include <asm/xive.h>
#include "timing.h"
#include "irq.h"
#include "../mm/mmu_decl.h"
#define CREATE_TRACE_POINTS
#include "trace.h"
struct kvmppc_ops *kvmppc_hv_ops;
EXPORT_SYMBOL_GPL(kvmppc_hv_ops);
struct kvmppc_ops *kvmppc_pr_ops;
EXPORT_SYMBOL_GPL(kvmppc_pr_ops);
int kvm_arch_vcpu_runnable(struct kvm_vcpu *v)
{
return !!(v->arch.pending_exceptions) || kvm_request_pending(v);
}
bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu)
{
return false;
}
int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
{
return 1;
}
/*
* Common checks before entering the guest world. Call with interrupts
* disabled.
*
* returns:
*
* == 1 if we're ready to go into guest state
* <= 0 if we need to go back to the host with return value
*/
int kvmppc_prepare_to_enter(struct kvm_vcpu *vcpu)
{
int r;
WARN_ON(irqs_disabled());
hard_irq_disable();
while (true) {
if (need_resched()) {
local_irq_enable();
cond_resched();
hard_irq_disable();
continue;
}
if (signal_pending(current)) {
kvmppc_account_exit(vcpu, SIGNAL_EXITS);
vcpu->run->exit_reason = KVM_EXIT_INTR;
r = -EINTR;
break;
}
vcpu->mode = IN_GUEST_MODE;
/*
* Reading vcpu->requests must happen after setting vcpu->mode,
* so we don't miss a request because the requester sees
* OUTSIDE_GUEST_MODE and assumes we'll be checking requests
* before next entering the guest (and thus doesn't IPI).
* This also orders the write to mode from any reads
* to the page tables done while the VCPU is running.
* Please see the comment in kvm_flush_remote_tlbs.
*/
smp_mb();
if (kvm_request_pending(vcpu)) {
/* Make sure we process requests preemptable */
local_irq_enable();
trace_kvm_check_requests(vcpu);
r = kvmppc_core_check_requests(vcpu);
hard_irq_disable();
if (r > 0)
continue;
break;
}
if (kvmppc_core_prepare_to_enter(vcpu)) {
/* interrupts got enabled in between, so we
are back at square 1 */
continue;
}
guest_enter_irqoff();
return 1;
}
/* return to host */
local_irq_enable();
return r;
}
EXPORT_SYMBOL_GPL(kvmppc_prepare_to_enter);
#if defined(CONFIG_PPC_BOOK3S_64) && defined(CONFIG_KVM_BOOK3S_PR_POSSIBLE)
static void kvmppc_swab_shared(struct kvm_vcpu *vcpu)
{
struct kvm_vcpu_arch_shared *shared = vcpu->arch.shared;
int i;
shared->sprg0 = swab64(shared->sprg0);
shared->sprg1 = swab64(shared->sprg1);
shared->sprg2 = swab64(shared->sprg2);
shared->sprg3 = swab64(shared->sprg3);
shared->srr0 = swab64(shared->srr0);
shared->srr1 = swab64(shared->srr1);
shared->dar = swab64(shared->dar);
shared->msr = swab64(shared->msr);
shared->dsisr = swab32(shared->dsisr);
shared->int_pending = swab32(shared->int_pending);
for (i = 0; i < ARRAY_SIZE(shared->sr); i++)
shared->sr[i] = swab32(shared->sr[i]);
}
#endif
int kvmppc_kvm_pv(struct kvm_vcpu *vcpu)
{
int nr = kvmppc_get_gpr(vcpu, 11);
int r;
unsigned long __maybe_unused param1 = kvmppc_get_gpr(vcpu, 3);
unsigned long __maybe_unused param2 = kvmppc_get_gpr(vcpu, 4);
unsigned long __maybe_unused param3 = kvmppc_get_gpr(vcpu, 5);
unsigned long __maybe_unused param4 = kvmppc_get_gpr(vcpu, 6);
unsigned long r2 = 0;
if (!(kvmppc_get_msr(vcpu) & MSR_SF)) {
/* 32 bit mode */
param1 &= 0xffffffff;
param2 &= 0xffffffff;
param3 &= 0xffffffff;
param4 &= 0xffffffff;
}
switch (nr) {
case KVM_HCALL_TOKEN(KVM_HC_PPC_MAP_MAGIC_PAGE):
{
#if defined(CONFIG_PPC_BOOK3S_64) && defined(CONFIG_KVM_BOOK3S_PR_POSSIBLE)
/* Book3S can be little endian, find it out here */
int shared_big_endian = true;
if (vcpu->arch.intr_msr & MSR_LE)
shared_big_endian = false;
if (shared_big_endian != vcpu->arch.shared_big_endian)
kvmppc_swab_shared(vcpu);
vcpu->arch.shared_big_endian = shared_big_endian;
#endif
if (!(param2 & MAGIC_PAGE_FLAG_NOT_MAPPED_NX)) {
/*
* Older versions of the Linux magic page code had
* a bug where they would map their trampoline code
* NX. If that's the case, remove !PR NX capability.
*/
vcpu->arch.disable_kernel_nx = true;
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
}
vcpu->arch.magic_page_pa = param1 & ~0xfffULL;
vcpu->arch.magic_page_ea = param2 & ~0xfffULL;
#ifdef CONFIG_PPC_64K_PAGES
/*
* Make sure our 4k magic page is in the same window of a 64k
* page within the guest and within the host's page.
*/
if ((vcpu->arch.magic_page_pa & 0xf000) !=
((ulong)vcpu->arch.shared & 0xf000)) {
void *old_shared = vcpu->arch.shared;
ulong shared = (ulong)vcpu->arch.shared;
void *new_shared;
shared &= PAGE_MASK;
shared |= vcpu->arch.magic_page_pa & 0xf000;
new_shared = (void*)shared;
memcpy(new_shared, old_shared, 0x1000);
vcpu->arch.shared = new_shared;
}
#endif
r2 = KVM_MAGIC_FEAT_SR | KVM_MAGIC_FEAT_MAS0_TO_SPRG7;
r = EV_SUCCESS;
break;
}
case KVM_HCALL_TOKEN(KVM_HC_FEATURES):
r = EV_SUCCESS;
#if defined(CONFIG_PPC_BOOK3S) || defined(CONFIG_KVM_E500V2)
r2 |= (1 << KVM_FEATURE_MAGIC_PAGE);
#endif
/* Second return value is in r4 */
break;
case EV_HCALL_TOKEN(EV_IDLE):
r = EV_SUCCESS;
kvm_vcpu_block(vcpu);
kvm_clear_request(KVM_REQ_UNHALT, vcpu);
break;
default:
r = EV_UNIMPLEMENTED;
break;
}
kvmppc_set_gpr(vcpu, 4, r2);
return r;
}
EXPORT_SYMBOL_GPL(kvmppc_kvm_pv);
int kvmppc_sanity_check(struct kvm_vcpu *vcpu)
{
int r = false;
/* We have to know what CPU to virtualize */
if (!vcpu->arch.pvr)
goto out;
/* PAPR only works with book3s_64 */
if ((vcpu->arch.cpu_type != KVM_CPU_3S_64) && vcpu->arch.papr_enabled)
goto out;
/* HV KVM can only do PAPR mode for now */
if (!vcpu->arch.papr_enabled && is_kvmppc_hv_enabled(vcpu->kvm))
goto out;
#ifdef CONFIG_KVM_BOOKE_HV
if (!cpu_has_feature(CPU_FTR_EMB_HV))
goto out;
#endif
r = true;
out:
vcpu->arch.sane = r;
return r ? 0 : -EINVAL;
}
EXPORT_SYMBOL_GPL(kvmppc_sanity_check);
int kvmppc_emulate_mmio(struct kvm_run *run, struct kvm_vcpu *vcpu)
{
enum emulation_result er;
int r;
er = kvmppc_emulate_loadstore(vcpu);
switch (er) {
case EMULATE_DONE:
/* Future optimization: only reload non-volatiles if they were
* actually modified. */
r = RESUME_GUEST_NV;
break;
case EMULATE_AGAIN:
r = RESUME_GUEST;
break;
case EMULATE_DO_MMIO:
run->exit_reason = KVM_EXIT_MMIO;
/* We must reload nonvolatiles because "update" load/store
* instructions modify register state. */
/* Future optimization: only reload non-volatiles if they were
* actually modified. */
r = RESUME_HOST_NV;
break;
case EMULATE_FAIL:
{
u32 last_inst;
kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst);
/* XXX Deliver Program interrupt to guest. */
pr_emerg("%s: emulation failed (%08x)\n", __func__, last_inst);
r = RESUME_HOST;
break;
}
default:
WARN_ON(1);
r = RESUME_GUEST;
}
return r;
}
EXPORT_SYMBOL_GPL(kvmppc_emulate_mmio);
int kvmppc_st(struct kvm_vcpu *vcpu, ulong *eaddr, int size, void *ptr,
bool data)
{
ulong mp_pa = vcpu->arch.magic_page_pa & KVM_PAM & PAGE_MASK;
struct kvmppc_pte pte;
int r;
vcpu->stat.st++;
r = kvmppc_xlate(vcpu, *eaddr, data ? XLATE_DATA : XLATE_INST,
XLATE_WRITE, &pte);
if (r < 0)
return r;
*eaddr = pte.raddr;
if (!pte.may_write)
return -EPERM;
/* Magic page override */
if (kvmppc_supports_magic_page(vcpu) && mp_pa &&
((pte.raddr & KVM_PAM & PAGE_MASK) == mp_pa) &&
!(kvmppc_get_msr(vcpu) & MSR_PR)) {
void *magic = vcpu->arch.shared;
magic += pte.eaddr & 0xfff;
memcpy(magic, ptr, size);
return EMULATE_DONE;
}
if (kvm_write_guest(vcpu->kvm, pte.raddr, ptr, size))
return EMULATE_DO_MMIO;
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvmppc_st);
int kvmppc_ld(struct kvm_vcpu *vcpu, ulong *eaddr, int size, void *ptr,
bool data)
{
ulong mp_pa = vcpu->arch.magic_page_pa & KVM_PAM & PAGE_MASK;
struct kvmppc_pte pte;
int rc;
vcpu->stat.ld++;
rc = kvmppc_xlate(vcpu, *eaddr, data ? XLATE_DATA : XLATE_INST,
XLATE_READ, &pte);
if (rc)
return rc;
*eaddr = pte.raddr;
if (!pte.may_read)
return -EPERM;
if (!data && !pte.may_execute)
return -ENOEXEC;
/* Magic page override */
if (kvmppc_supports_magic_page(vcpu) && mp_pa &&
((pte.raddr & KVM_PAM & PAGE_MASK) == mp_pa) &&
!(kvmppc_get_msr(vcpu) & MSR_PR)) {
void *magic = vcpu->arch.shared;
magic += pte.eaddr & 0xfff;
memcpy(ptr, magic, size);
return EMULATE_DONE;
}
if (kvm_read_guest(vcpu->kvm, pte.raddr, ptr, size))
return EMULATE_DO_MMIO;
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvmppc_ld);
int kvm_arch_hardware_enable(void)
{
return 0;
}
int kvm_arch_hardware_setup(void)
{
return 0;
}
void kvm_arch_check_processor_compat(void *rtn)
{
*(int *)rtn = kvmppc_core_check_processor_compat();
}
int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
{
struct kvmppc_ops *kvm_ops = NULL;
/*
* if we have both HV and PR enabled, default is HV
*/
if (type == 0) {
if (kvmppc_hv_ops)
kvm_ops = kvmppc_hv_ops;
else
kvm_ops = kvmppc_pr_ops;
if (!kvm_ops)
goto err_out;
} else if (type == KVM_VM_PPC_HV) {
if (!kvmppc_hv_ops)
goto err_out;
kvm_ops = kvmppc_hv_ops;
} else if (type == KVM_VM_PPC_PR) {
if (!kvmppc_pr_ops)
goto err_out;
kvm_ops = kvmppc_pr_ops;
} else
goto err_out;
if (kvm_ops->owner && !try_module_get(kvm_ops->owner))
return -ENOENT;
kvm->arch.kvm_ops = kvm_ops;
return kvmppc_core_init_vm(kvm);
err_out:
return -EINVAL;
}
bool kvm_arch_has_vcpu_debugfs(void)
{
return false;
}
int kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
{
return 0;
}
void kvm_arch_destroy_vm(struct kvm *kvm)
{
unsigned int i;
struct kvm_vcpu *vcpu;
#ifdef CONFIG_KVM_XICS
/*
* We call kick_all_cpus_sync() to ensure that all
* CPUs have executed any pending IPIs before we
* continue and free VCPUs structures below.
*/
if (is_kvmppc_hv_enabled(kvm))
kick_all_cpus_sync();
#endif
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_arch_vcpu_free(vcpu);
mutex_lock(&kvm->lock);
for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
kvm->vcpus[i] = NULL;
atomic_set(&kvm->online_vcpus, 0);
kvmppc_core_destroy_vm(kvm);
mutex_unlock(&kvm->lock);
/* drop the module reference */
module_put(kvm->arch.kvm_ops->owner);
}
int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
{
int r;
/* Assume we're using HV mode when the HV module is loaded */
int hv_enabled = kvmppc_hv_ops ? 1 : 0;
if (kvm) {
/*
* Hooray - we know which VM type we're running on. Depend on
* that rather than the guess above.
*/
hv_enabled = is_kvmppc_hv_enabled(kvm);
}
switch (ext) {
#ifdef CONFIG_BOOKE
case KVM_CAP_PPC_BOOKE_SREGS:
case KVM_CAP_PPC_BOOKE_WATCHDOG:
case KVM_CAP_PPC_EPR:
#else
case KVM_CAP_PPC_SEGSTATE:
case KVM_CAP_PPC_HIOR:
case KVM_CAP_PPC_PAPR:
#endif
case KVM_CAP_PPC_UNSET_IRQ:
case KVM_CAP_PPC_IRQ_LEVEL:
case KVM_CAP_ENABLE_CAP:
case KVM_CAP_ENABLE_CAP_VM:
case KVM_CAP_ONE_REG:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_DEVICE_CTRL:
case KVM_CAP_IMMEDIATE_EXIT:
r = 1;
break;
case KVM_CAP_PPC_PAIRED_SINGLES:
case KVM_CAP_PPC_OSI:
case KVM_CAP_PPC_GET_PVINFO:
#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)
case KVM_CAP_SW_TLB:
#endif
/* We support this only for PR */
r = !hv_enabled;
break;
#ifdef CONFIG_KVM_MPIC
case KVM_CAP_IRQ_MPIC:
r = 1;
break;
#endif
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_SPAPR_TCE:
case KVM_CAP_SPAPR_TCE_64:
/* fallthrough */
case KVM_CAP_SPAPR_TCE_VFIO:
case KVM_CAP_PPC_RTAS:
case KVM_CAP_PPC_FIXUP_HCALL:
case KVM_CAP_PPC_ENABLE_HCALL:
#ifdef CONFIG_KVM_XICS
case KVM_CAP_IRQ_XICS:
#endif
r = 1;
break;
case KVM_CAP_PPC_ALLOC_HTAB:
r = hv_enabled;
break;
#endif /* CONFIG_PPC_BOOK3S_64 */
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_SMT:
r = 0;
if (kvm) {
if (kvm->arch.emul_smt_mode > 1)
r = kvm->arch.emul_smt_mode;
else
r = kvm->arch.smt_mode;
} else if (hv_enabled) {
if (cpu_has_feature(CPU_FTR_ARCH_300))
r = 1;
else
r = threads_per_subcore;
}
break;
case KVM_CAP_PPC_SMT_POSSIBLE:
r = 1;
if (hv_enabled) {
if (!cpu_has_feature(CPU_FTR_ARCH_300))
r = ((threads_per_subcore << 1) - 1);
else
/* P9 can emulate dbells, so allow any mode */
r = 8 | 4 | 2 | 1;
}
break;
case KVM_CAP_PPC_RMA:
r = 0;
break;
case KVM_CAP_PPC_HWRNG:
r = kvmppc_hwrng_present();
break;
case KVM_CAP_PPC_MMU_RADIX:
r = !!(hv_enabled && radix_enabled());
break;
case KVM_CAP_PPC_MMU_HASH_V3:
r = !!(hv_enabled && !radix_enabled() &&
cpu_has_feature(CPU_FTR_ARCH_300));
break;
#endif
case KVM_CAP_SYNC_MMU:
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
r = hv_enabled;
#elif defined(KVM_ARCH_WANT_MMU_NOTIFIER)
r = 1;
#else
r = 0;
#endif
break;
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_HTAB_FD:
r = hv_enabled;
break;
#endif
case KVM_CAP_NR_VCPUS:
/*
* Recommending a number of CPUs is somewhat arbitrary; we
* return the number of present CPUs for -HV (since a host
* will have secondary threads "offline"), and for other KVM
* implementations just count online CPUs.
*/
if (hv_enabled)
r = num_present_cpus();
else
r = num_online_cpus();
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_PPC_GET_SMMU_INFO:
r = 1;
break;
case KVM_CAP_SPAPR_MULTITCE:
r = 1;
break;
case KVM_CAP_SPAPR_RESIZE_HPT:
/* Disable this on POWER9 until code handles new HPTE format */
r = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300);
break;
#endif
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_FWNMI:
r = hv_enabled;
break;
#endif
case KVM_CAP_PPC_HTM:
r = cpu_has_feature(CPU_FTR_TM_COMP) &&
is_kvmppc_hv_enabled(kvm);
break;
default:
r = 0;
break;
}
return r;
}
long kvm_arch_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
return -EINVAL;
}
void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
kvmppc_core_free_memslot(kvm, free, dont);
}
int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
unsigned long npages)
{
return kvmppc_core_create_memslot(kvm, slot, npages);
}
int kvm_arch_prepare_memory_region(struct kvm *kvm,
struct kvm_memory_slot *memslot,
const struct kvm_userspace_memory_region *mem,
enum kvm_mr_change change)
{
return kvmppc_core_prepare_memory_region(kvm, memslot, mem);
}
void kvm_arch_commit_memory_region(struct kvm *kvm,
const struct kvm_userspace_memory_region *mem,
const struct kvm_memory_slot *old,
const struct kvm_memory_slot *new,
enum kvm_mr_change change)
{
kvmppc_core_commit_memory_region(kvm, mem, old, new);
}
void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvmppc_core_flush_memslot(kvm, slot);
}
struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm, unsigned int id)
{
struct kvm_vcpu *vcpu;
vcpu = kvmppc_core_vcpu_create(kvm, id);
if (!IS_ERR(vcpu)) {
vcpu->arch.wqp = &vcpu->wq;
kvmppc_create_vcpu_debugfs(vcpu, id);
}
return vcpu;
}
void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
{
}
void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
{
/* Make sure we're not using the vcpu anymore */
hrtimer_cancel(&vcpu->arch.dec_timer);
kvmppc_remove_vcpu_debugfs(vcpu);
switch (vcpu->arch.irq_type) {
case KVMPPC_IRQ_MPIC:
kvmppc_mpic_disconnect_vcpu(vcpu->arch.mpic, vcpu);
break;
case KVMPPC_IRQ_XICS:
if (xive_enabled())
kvmppc_xive_cleanup_vcpu(vcpu);
else
kvmppc_xics_free_icp(vcpu);
break;
}
kvmppc_core_vcpu_free(vcpu);
}
void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
{
kvm_arch_vcpu_free(vcpu);
}
int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu)
{
return kvmppc_core_pending_dec(vcpu);
}
static enum hrtimer_restart kvmppc_decrementer_wakeup(struct hrtimer *timer)
{
struct kvm_vcpu *vcpu;
vcpu = container_of(timer, struct kvm_vcpu, arch.dec_timer);
kvmppc_decrementer_func(vcpu);
return HRTIMER_NORESTART;
}
int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
{
int ret;
hrtimer_init(&vcpu->arch.dec_timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
vcpu->arch.dec_timer.function = kvmppc_decrementer_wakeup;
vcpu->arch.dec_expires = ~(u64)0;
#ifdef CONFIG_KVM_EXIT_TIMING
mutex_init(&vcpu->arch.exit_timing_lock);
#endif
ret = kvmppc_subarch_vcpu_init(vcpu);
return ret;
}
void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
{
kvmppc_mmu_destroy(vcpu);
kvmppc_subarch_vcpu_uninit(vcpu);
}
void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
#ifdef CONFIG_BOOKE
/*
* vrsave (formerly usprg0) isn't used by Linux, but may
* be used by the guest.
*
* On non-booke this is associated with Altivec and
* is handled by code in book3s.c.
*/
mtspr(SPRN_VRSAVE, vcpu->arch.vrsave);
#endif
kvmppc_core_vcpu_load(vcpu, cpu);
}
void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
{
kvmppc_core_vcpu_put(vcpu);
#ifdef CONFIG_BOOKE
vcpu->arch.vrsave = mfspr(SPRN_VRSAVE);
#endif
}
/*
* irq_bypass_add_producer and irq_bypass_del_producer are only
* useful if the architecture supports PCI passthrough.
* irq_bypass_stop and irq_bypass_start are not needed and so
* kvm_ops are not defined for them.
*/
bool kvm_arch_has_irq_bypass(void)
{
return ((kvmppc_hv_ops && kvmppc_hv_ops->irq_bypass_add_producer) ||
(kvmppc_pr_ops && kvmppc_pr_ops->irq_bypass_add_producer));
}
int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *cons,
struct irq_bypass_producer *prod)
{
struct kvm_kernel_irqfd *irqfd =
container_of(cons, struct kvm_kernel_irqfd, consumer);
struct kvm *kvm = irqfd->kvm;
if (kvm->arch.kvm_ops->irq_bypass_add_producer)
return kvm->arch.kvm_ops->irq_bypass_add_producer(cons, prod);
return 0;
}
void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons,
struct irq_bypass_producer *prod)
{
struct kvm_kernel_irqfd *irqfd =
container_of(cons, struct kvm_kernel_irqfd, consumer);
struct kvm *kvm = irqfd->kvm;
if (kvm->arch.kvm_ops->irq_bypass_del_producer)
kvm->arch.kvm_ops->irq_bypass_del_producer(cons, prod);
}
#ifdef CONFIG_VSX
static inline int kvmppc_get_vsr_dword_offset(int index)
{
int offset;
if ((index != 0) && (index != 1))
return -1;
#ifdef __BIG_ENDIAN
offset = index;
#else
offset = 1 - index;
#endif
return offset;
}
static inline int kvmppc_get_vsr_word_offset(int index)
{
int offset;
if ((index > 3) || (index < 0))
return -1;
#ifdef __BIG_ENDIAN
offset = index;
#else
offset = 3 - index;
#endif
return offset;
}
static inline void kvmppc_set_vsr_dword(struct kvm_vcpu *vcpu,
u64 gpr)
{
union kvmppc_one_reg val;
int offset = kvmppc_get_vsr_dword_offset(vcpu->arch.mmio_vsx_offset);
int index = vcpu->arch.io_gpr & KVM_MMIO_REG_MASK;
if (offset == -1)
return;
if (vcpu->arch.mmio_vsx_tx_sx_enabled) {
val.vval = VCPU_VSX_VR(vcpu, index);
val.vsxval[offset] = gpr;
VCPU_VSX_VR(vcpu, index) = val.vval;
} else {
VCPU_VSX_FPR(vcpu, index, offset) = gpr;
}
}
static inline void kvmppc_set_vsr_dword_dump(struct kvm_vcpu *vcpu,
u64 gpr)
{
union kvmppc_one_reg val;
int index = vcpu->arch.io_gpr & KVM_MMIO_REG_MASK;
if (vcpu->arch.mmio_vsx_tx_sx_enabled) {
val.vval = VCPU_VSX_VR(vcpu, index);
val.vsxval[0] = gpr;
val.vsxval[1] = gpr;
VCPU_VSX_VR(vcpu, index) = val.vval;
} else {
VCPU_VSX_FPR(vcpu, index, 0) = gpr;
VCPU_VSX_FPR(vcpu, index, 1) = gpr;
}
}
static inline void kvmppc_set_vsr_word(struct kvm_vcpu *vcpu,
u32 gpr32)
{
union kvmppc_one_reg val;
int offset = kvmppc_get_vsr_word_offset(vcpu->arch.mmio_vsx_offset);
int index = vcpu->arch.io_gpr & KVM_MMIO_REG_MASK;
int dword_offset, word_offset;
if (offset == -1)
return;
if (vcpu->arch.mmio_vsx_tx_sx_enabled) {
val.vval = VCPU_VSX_VR(vcpu, index);
val.vsx32val[offset] = gpr32;
VCPU_VSX_VR(vcpu, index) = val.vval;
} else {
dword_offset = offset / 2;
word_offset = offset % 2;
val.vsxval[0] = VCPU_VSX_FPR(vcpu, index, dword_offset);
val.vsx32val[word_offset] = gpr32;
VCPU_VSX_FPR(vcpu, index, dword_offset) = val.vsxval[0];
}
}
#endif /* CONFIG_VSX */
#ifdef CONFIG_PPC_FPU
static inline u64 sp_to_dp(u32 fprs)
{
u64 fprd;
preempt_disable();
enable_kernel_fp();
asm ("lfs%U1%X1 0,%1; stfd%U0%X0 0,%0" : "=m" (fprd) : "m" (fprs)
: "fr0");
preempt_enable();
return fprd;
}
static inline u32 dp_to_sp(u64 fprd)
{
u32 fprs;
preempt_disable();
enable_kernel_fp();
asm ("lfd%U1%X1 0,%1; stfs%U0%X0 0,%0" : "=m" (fprs) : "m" (fprd)
: "fr0");
preempt_enable();
return fprs;
}
#else
#define sp_to_dp(x) (x)
#define dp_to_sp(x) (x)
#endif /* CONFIG_PPC_FPU */
static void kvmppc_complete_mmio_load(struct kvm_vcpu *vcpu,
struct kvm_run *run)
{
u64 uninitialized_var(gpr);
if (run->mmio.len > sizeof(gpr)) {
printk(KERN_ERR "bad MMIO length: %d\n", run->mmio.len);
return;
}
if (!vcpu->arch.mmio_host_swabbed) {
switch (run->mmio.len) {
case 8: gpr = *(u64 *)run->mmio.data; break;
case 4: gpr = *(u32 *)run->mmio.data; break;
case 2: gpr = *(u16 *)run->mmio.data; break;
case 1: gpr = *(u8 *)run->mmio.data; break;
}
} else {
switch (run->mmio.len) {
case 8: gpr = swab64(*(u64 *)run->mmio.data); break;
case 4: gpr = swab32(*(u32 *)run->mmio.data); break;
case 2: gpr = swab16(*(u16 *)run->mmio.data); break;
case 1: gpr = *(u8 *)run->mmio.data; break;
}
}
/* conversion between single and double precision */
if ((vcpu->arch.mmio_sp64_extend) && (run->mmio.len == 4))
gpr = sp_to_dp(gpr);
if (vcpu->arch.mmio_sign_extend) {
switch (run->mmio.len) {
#ifdef CONFIG_PPC64
case 4:
gpr = (s64)(s32)gpr;
break;
#endif
case 2:
gpr = (s64)(s16)gpr;
break;
case 1:
gpr = (s64)(s8)gpr;
break;
}
}
switch (vcpu->arch.io_gpr & KVM_MMIO_REG_EXT_MASK) {
case KVM_MMIO_REG_GPR:
kvmppc_set_gpr(vcpu, vcpu->arch.io_gpr, gpr);
break;
case KVM_MMIO_REG_FPR:
VCPU_FPR(vcpu, vcpu->arch.io_gpr & KVM_MMIO_REG_MASK) = gpr;
break;
#ifdef CONFIG_PPC_BOOK3S
case KVM_MMIO_REG_QPR:
vcpu->arch.qpr[vcpu->arch.io_gpr & KVM_MMIO_REG_MASK] = gpr;
break;
case KVM_MMIO_REG_FQPR:
VCPU_FPR(vcpu, vcpu->arch.io_gpr & KVM_MMIO_REG_MASK) = gpr;
vcpu->arch.qpr[vcpu->arch.io_gpr & KVM_MMIO_REG_MASK] = gpr;
break;
#endif
#ifdef CONFIG_VSX
case KVM_MMIO_REG_VSX:
if (vcpu->arch.mmio_vsx_copy_type == KVMPPC_VSX_COPY_DWORD)
kvmppc_set_vsr_dword(vcpu, gpr);
else if (vcpu->arch.mmio_vsx_copy_type == KVMPPC_VSX_COPY_WORD)
kvmppc_set_vsr_word(vcpu, gpr);
else if (vcpu->arch.mmio_vsx_copy_type ==
KVMPPC_VSX_COPY_DWORD_LOAD_DUMP)
kvmppc_set_vsr_dword_dump(vcpu, gpr);
break;
#endif
default:
BUG();
}
}
static int __kvmppc_handle_load(struct kvm_run *run, struct kvm_vcpu *vcpu,
unsigned int rt, unsigned int bytes,
int is_default_endian, int sign_extend)
{
int idx, ret;
bool host_swabbed;
/* Pity C doesn't have a logical XOR operator */
if (kvmppc_need_byteswap(vcpu)) {
host_swabbed = is_default_endian;
} else {
host_swabbed = !is_default_endian;
}
if (bytes > sizeof(run->mmio.data)) {
printk(KERN_ERR "%s: bad MMIO length: %d\n", __func__,
run->mmio.len);
}
run->mmio.phys_addr = vcpu->arch.paddr_accessed;
run->mmio.len = bytes;
run->mmio.is_write = 0;
vcpu->arch.io_gpr = rt;
vcpu->arch.mmio_host_swabbed = host_swabbed;
vcpu->mmio_needed = 1;
vcpu->mmio_is_write = 0;
vcpu->arch.mmio_sign_extend = sign_extend;
idx = srcu_read_lock(&vcpu->kvm->srcu);
ret = kvm_io_bus_read(vcpu, KVM_MMIO_BUS, run->mmio.phys_addr,
bytes, &run->mmio.data);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
if (!ret) {
kvmppc_complete_mmio_load(vcpu, run);
vcpu->mmio_needed = 0;
return EMULATE_DONE;
}
return EMULATE_DO_MMIO;
}
int kvmppc_handle_load(struct kvm_run *run, struct kvm_vcpu *vcpu,
unsigned int rt, unsigned int bytes,
int is_default_endian)
{
return __kvmppc_handle_load(run, vcpu, rt, bytes, is_default_endian, 0);
}
EXPORT_SYMBOL_GPL(kvmppc_handle_load);
/* Same as above, but sign extends */
int kvmppc_handle_loads(struct kvm_run *run, struct kvm_vcpu *vcpu,
unsigned int rt, unsigned int bytes,
int is_default_endian)
{
return __kvmppc_handle_load(run, vcpu, rt, bytes, is_default_endian, 1);
}
#ifdef CONFIG_VSX
int kvmppc_handle_vsx_load(struct kvm_run *run, struct kvm_vcpu *vcpu,
unsigned int rt, unsigned int bytes,
int is_default_endian, int mmio_sign_extend)
{
enum emulation_result emulated = EMULATE_DONE;
/* Currently, mmio_vsx_copy_nums only allowed to be less than 4 */
if ( (vcpu->arch.mmio_vsx_copy_nums > 4) ||
(vcpu->arch.mmio_vsx_copy_nums < 0) ) {
return EMULATE_FAIL;
}
while (vcpu->arch.mmio_vsx_copy_nums) {
emulated = __kvmppc_handle_load(run, vcpu, rt, bytes,
is_default_endian, mmio_sign_extend);
if (emulated != EMULATE_DONE)
break;
vcpu->arch.paddr_accessed += run->mmio.len;
vcpu->arch.mmio_vsx_copy_nums--;
vcpu->arch.mmio_vsx_offset++;
}
return emulated;
}
#endif /* CONFIG_VSX */
int kvmppc_handle_store(struct kvm_run *run, struct kvm_vcpu *vcpu,
u64 val, unsigned int bytes, int is_default_endian)
{
void *data = run->mmio.data;
int idx, ret;
bool host_swabbed;
/* Pity C doesn't have a logical XOR operator */
if (kvmppc_need_byteswap(vcpu)) {
host_swabbed = is_default_endian;
} else {
host_swabbed = !is_default_endian;
}
if (bytes > sizeof(run->mmio.data)) {
printk(KERN_ERR "%s: bad MMIO length: %d\n", __func__,
run->mmio.len);
}
run->mmio.phys_addr = vcpu->arch.paddr_accessed;
run->mmio.len = bytes;
run->mmio.is_write = 1;
vcpu->mmio_needed = 1;
vcpu->mmio_is_write = 1;
if ((vcpu->arch.mmio_sp64_extend) && (bytes == 4))
val = dp_to_sp(val);
/* Store the value at the lowest bytes in 'data'. */
if (!host_swabbed) {
switch (bytes) {
case 8: *(u64 *)data = val; break;
case 4: *(u32 *)data = val; break;
case 2: *(u16 *)data = val; break;
case 1: *(u8 *)data = val; break;
}
} else {
switch (bytes) {
case 8: *(u64 *)data = swab64(val); break;
case 4: *(u32 *)data = swab32(val); break;
case 2: *(u16 *)data = swab16(val); break;
case 1: *(u8 *)data = val; break;
}
}
idx = srcu_read_lock(&vcpu->kvm->srcu);
ret = kvm_io_bus_write(vcpu, KVM_MMIO_BUS, run->mmio.phys_addr,
bytes, &run->mmio.data);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
if (!ret) {
vcpu->mmio_needed = 0;
return EMULATE_DONE;
}
return EMULATE_DO_MMIO;
}
EXPORT_SYMBOL_GPL(kvmppc_handle_store);
#ifdef CONFIG_VSX
static inline int kvmppc_get_vsr_data(struct kvm_vcpu *vcpu, int rs, u64 *val)
{
u32 dword_offset, word_offset;
union kvmppc_one_reg reg;
int vsx_offset = 0;
int copy_type = vcpu->arch.mmio_vsx_copy_type;
int result = 0;
switch (copy_type) {
case KVMPPC_VSX_COPY_DWORD:
vsx_offset =
kvmppc_get_vsr_dword_offset(vcpu->arch.mmio_vsx_offset);
if (vsx_offset == -1) {
result = -1;
break;
}
if (!vcpu->arch.mmio_vsx_tx_sx_enabled) {
*val = VCPU_VSX_FPR(vcpu, rs, vsx_offset);
} else {
reg.vval = VCPU_VSX_VR(vcpu, rs);
*val = reg.vsxval[vsx_offset];
}
break;
case KVMPPC_VSX_COPY_WORD:
vsx_offset =
kvmppc_get_vsr_word_offset(vcpu->arch.mmio_vsx_offset);
if (vsx_offset == -1) {
result = -1;
break;
}
if (!vcpu->arch.mmio_vsx_tx_sx_enabled) {
dword_offset = vsx_offset / 2;
word_offset = vsx_offset % 2;
reg.vsxval[0] = VCPU_VSX_FPR(vcpu, rs, dword_offset);
*val = reg.vsx32val[word_offset];
} else {
reg.vval = VCPU_VSX_VR(vcpu, rs);
*val = reg.vsx32val[vsx_offset];
}
break;
default:
result = -1;
break;
}
return result;
}
int kvmppc_handle_vsx_store(struct kvm_run *run, struct kvm_vcpu *vcpu,
int rs, unsigned int bytes, int is_default_endian)
{
u64 val;
enum emulation_result emulated = EMULATE_DONE;
vcpu->arch.io_gpr = rs;
/* Currently, mmio_vsx_copy_nums only allowed to be less than 4 */
if ( (vcpu->arch.mmio_vsx_copy_nums > 4) ||
(vcpu->arch.mmio_vsx_copy_nums < 0) ) {
return EMULATE_FAIL;
}
while (vcpu->arch.mmio_vsx_copy_nums) {
if (kvmppc_get_vsr_data(vcpu, rs, &val) == -1)
return EMULATE_FAIL;
emulated = kvmppc_handle_store(run, vcpu,
val, bytes, is_default_endian);
if (emulated != EMULATE_DONE)
break;
vcpu->arch.paddr_accessed += run->mmio.len;
vcpu->arch.mmio_vsx_copy_nums--;
vcpu->arch.mmio_vsx_offset++;
}
return emulated;
}
static int kvmppc_emulate_mmio_vsx_loadstore(struct kvm_vcpu *vcpu,
struct kvm_run *run)
{
enum emulation_result emulated = EMULATE_FAIL;
int r;
vcpu->arch.paddr_accessed += run->mmio.len;
if (!vcpu->mmio_is_write) {
emulated = kvmppc_handle_vsx_load(run, vcpu, vcpu->arch.io_gpr,
run->mmio.len, 1, vcpu->arch.mmio_sign_extend);
} else {
emulated = kvmppc_handle_vsx_store(run, vcpu,
vcpu->arch.io_gpr, run->mmio.len, 1);
}
switch (emulated) {
case EMULATE_DO_MMIO:
run->exit_reason = KVM_EXIT_MMIO;
r = RESUME_HOST;
break;
case EMULATE_FAIL:
pr_info("KVM: MMIO emulation failed (VSX repeat)\n");
run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
r = RESUME_HOST;
break;
default:
r = RESUME_GUEST;
break;
}
return r;
}
#endif /* CONFIG_VSX */
int kvm_vcpu_ioctl_get_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg)
{
int r = 0;
union kvmppc_one_reg val;
int size;
size = one_reg_size(reg->id);
if (size > sizeof(val))
return -EINVAL;
r = kvmppc_get_one_reg(vcpu, reg->id, &val);
if (r == -EINVAL) {
r = 0;
switch (reg->id) {
#ifdef CONFIG_ALTIVEC
case KVM_REG_PPC_VR0 ... KVM_REG_PPC_VR31:
if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
r = -ENXIO;
break;
}
val.vval = vcpu->arch.vr.vr[reg->id - KVM_REG_PPC_VR0];
break;
case KVM_REG_PPC_VSCR:
if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
r = -ENXIO;
break;
}
val = get_reg_val(reg->id, vcpu->arch.vr.vscr.u[3]);
break;
case KVM_REG_PPC_VRSAVE:
val = get_reg_val(reg->id, vcpu->arch.vrsave);
break;
#endif /* CONFIG_ALTIVEC */
default:
r = -EINVAL;
break;
}
}
if (r)
return r;
if (copy_to_user((char __user *)(unsigned long)reg->addr, &val, size))
r = -EFAULT;
return r;
}
int kvm_vcpu_ioctl_set_one_reg(struct kvm_vcpu *vcpu, struct kvm_one_reg *reg)
{
int r;
union kvmppc_one_reg val;
int size;
size = one_reg_size(reg->id);
if (size > sizeof(val))
return -EINVAL;
if (copy_from_user(&val, (char __user *)(unsigned long)reg->addr, size))
return -EFAULT;
r = kvmppc_set_one_reg(vcpu, reg->id, &val);
if (r == -EINVAL) {
r = 0;
switch (reg->id) {
#ifdef CONFIG_ALTIVEC
case KVM_REG_PPC_VR0 ... KVM_REG_PPC_VR31:
if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
r = -ENXIO;
break;
}
vcpu->arch.vr.vr[reg->id - KVM_REG_PPC_VR0] = val.vval;
break;
case KVM_REG_PPC_VSCR:
if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
r = -ENXIO;
break;
}
vcpu->arch.vr.vscr.u[3] = set_reg_val(reg->id, val);
break;
case KVM_REG_PPC_VRSAVE:
if (!cpu_has_feature(CPU_FTR_ALTIVEC)) {
r = -ENXIO;
break;
}
vcpu->arch.vrsave = set_reg_val(reg->id, val);
break;
#endif /* CONFIG_ALTIVEC */
default:
r = -EINVAL;
break;
}
}
return r;
}
int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
{
int r;
sigset_t sigsaved;
if (vcpu->mmio_needed) {
vcpu->mmio_needed = 0;
if (!vcpu->mmio_is_write)
kvmppc_complete_mmio_load(vcpu, run);
#ifdef CONFIG_VSX
if (vcpu->arch.mmio_vsx_copy_nums > 0) {
vcpu->arch.mmio_vsx_copy_nums--;
vcpu->arch.mmio_vsx_offset++;
}
if (vcpu->arch.mmio_vsx_copy_nums > 0) {
r = kvmppc_emulate_mmio_vsx_loadstore(vcpu, run);
if (r == RESUME_HOST) {
vcpu->mmio_needed = 1;
return r;
}
}
#endif
} else if (vcpu->arch.osi_needed) {
u64 *gprs = run->osi.gprs;
int i;
for (i = 0; i < 32; i++)
kvmppc_set_gpr(vcpu, i, gprs[i]);
vcpu->arch.osi_needed = 0;
} else if (vcpu->arch.hcall_needed) {
int i;
kvmppc_set_gpr(vcpu, 3, run->papr_hcall.ret);
for (i = 0; i < 9; ++i)
kvmppc_set_gpr(vcpu, 4 + i, run->papr_hcall.args[i]);
vcpu->arch.hcall_needed = 0;
#ifdef CONFIG_BOOKE
} else if (vcpu->arch.epr_needed) {
kvmppc_set_epr(vcpu, run->epr.epr);
vcpu->arch.epr_needed = 0;
#endif
}
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
if (run->immediate_exit)
r = -EINTR;
else
r = kvmppc_vcpu_run(run, vcpu);
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return r;
}
int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu, struct kvm_interrupt *irq)
{
if (irq->irq == KVM_INTERRUPT_UNSET) {
kvmppc_core_dequeue_external(vcpu);
return 0;
}
kvmppc_core_queue_external(vcpu, irq);
kvm_vcpu_kick(vcpu);
return 0;
}
static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu,
struct kvm_enable_cap *cap)
{
int r;
if (cap->flags)
return -EINVAL;
switch (cap->cap) {
case KVM_CAP_PPC_OSI:
r = 0;
vcpu->arch.osi_enabled = true;
break;
case KVM_CAP_PPC_PAPR:
r = 0;
vcpu->arch.papr_enabled = true;
break;
case KVM_CAP_PPC_EPR:
r = 0;
if (cap->args[0])
vcpu->arch.epr_flags |= KVMPPC_EPR_USER;
else
vcpu->arch.epr_flags &= ~KVMPPC_EPR_USER;
break;
#ifdef CONFIG_BOOKE
case KVM_CAP_PPC_BOOKE_WATCHDOG:
r = 0;
vcpu->arch.watchdog_enabled = true;
break;
#endif
#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)
case KVM_CAP_SW_TLB: {
struct kvm_config_tlb cfg;
void __user *user_ptr = (void __user *)(uintptr_t)cap->args[0];
r = -EFAULT;
if (copy_from_user(&cfg, user_ptr, sizeof(cfg)))
break;
r = kvm_vcpu_ioctl_config_tlb(vcpu, &cfg);
break;
}
#endif
#ifdef CONFIG_KVM_MPIC
case KVM_CAP_IRQ_MPIC: {
struct fd f;
struct kvm_device *dev;
r = -EBADF;
f = fdget(cap->args[0]);
if (!f.file)
break;
r = -EPERM;
dev = kvm_device_from_filp(f.file);
if (dev)
r = kvmppc_mpic_connect_vcpu(dev, vcpu, cap->args[1]);
fdput(f);
break;
}
#endif
#ifdef CONFIG_KVM_XICS
case KVM_CAP_IRQ_XICS: {
struct fd f;
struct kvm_device *dev;
r = -EBADF;
f = fdget(cap->args[0]);
if (!f.file)
break;
r = -EPERM;
dev = kvm_device_from_filp(f.file);
if (dev) {
if (xive_enabled())
r = kvmppc_xive_connect_vcpu(dev, vcpu, cap->args[1]);
else
r = kvmppc_xics_connect_vcpu(dev, vcpu, cap->args[1]);
}
fdput(f);
break;
}
#endif /* CONFIG_KVM_XICS */
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_FWNMI:
r = -EINVAL;
if (!is_kvmppc_hv_enabled(vcpu->kvm))
break;
r = 0;
vcpu->kvm->arch.fwnmi_enabled = true;
break;
#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */
default:
r = -EINVAL;
break;
}
if (!r)
r = kvmppc_sanity_check(vcpu);
return r;
}
bool kvm_arch_intc_initialized(struct kvm *kvm)
{
#ifdef CONFIG_KVM_MPIC
if (kvm->arch.mpic)
return true;
#endif
#ifdef CONFIG_KVM_XICS
if (kvm->arch.xics || kvm->arch.xive)
return true;
#endif
return false;
}
int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
return -EINVAL;
}
int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
return -EINVAL;
}
long kvm_arch_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
long r;
switch (ioctl) {
case KVM_INTERRUPT: {
struct kvm_interrupt irq;
r = -EFAULT;
if (copy_from_user(&irq, argp, sizeof(irq)))
goto out;
r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
goto out;
}
case KVM_ENABLE_CAP:
{
struct kvm_enable_cap cap;
r = -EFAULT;
if (copy_from_user(&cap, argp, sizeof(cap)))
goto out;
r = kvm_vcpu_ioctl_enable_cap(vcpu, &cap);
break;
}
case KVM_SET_ONE_REG:
case KVM_GET_ONE_REG:
{
struct kvm_one_reg reg;
r = -EFAULT;
if (copy_from_user(®, argp, sizeof(reg)))
goto out;
if (ioctl == KVM_SET_ONE_REG)
r = kvm_vcpu_ioctl_set_one_reg(vcpu, ®);
else
r = kvm_vcpu_ioctl_get_one_reg(vcpu, ®);
break;
}
#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)
case KVM_DIRTY_TLB: {
struct kvm_dirty_tlb dirty;
r = -EFAULT;
if (copy_from_user(&dirty, argp, sizeof(dirty)))
goto out;
r = kvm_vcpu_ioctl_dirty_tlb(vcpu, &dirty);
break;
}
#endif
default:
r = -EINVAL;
}
out:
return r;
}
int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
{
return VM_FAULT_SIGBUS;
}
static int kvm_vm_ioctl_get_pvinfo(struct kvm_ppc_pvinfo *pvinfo)
{
u32 inst_nop = 0x60000000;
#ifdef CONFIG_KVM_BOOKE_HV
u32 inst_sc1 = 0x44000022;
pvinfo->hcall[0] = cpu_to_be32(inst_sc1);
pvinfo->hcall[1] = cpu_to_be32(inst_nop);
pvinfo->hcall[2] = cpu_to_be32(inst_nop);
pvinfo->hcall[3] = cpu_to_be32(inst_nop);
#else
u32 inst_lis = 0x3c000000;
u32 inst_ori = 0x60000000;
u32 inst_sc = 0x44000002;
u32 inst_imm_mask = 0xffff;
/*
* The hypercall to get into KVM from within guest context is as
* follows:
*
* lis r0, r0, KVM_SC_MAGIC_R0@h
* ori r0, KVM_SC_MAGIC_R0@l
* sc
* nop
*/
pvinfo->hcall[0] = cpu_to_be32(inst_lis | ((KVM_SC_MAGIC_R0 >> 16) & inst_imm_mask));
pvinfo->hcall[1] = cpu_to_be32(inst_ori | (KVM_SC_MAGIC_R0 & inst_imm_mask));
pvinfo->hcall[2] = cpu_to_be32(inst_sc);
pvinfo->hcall[3] = cpu_to_be32(inst_nop);
#endif
pvinfo->flags = KVM_PPC_PVINFO_FLAGS_EV_IDLE;
return 0;
}
int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
bool line_status)
{
if (!irqchip_in_kernel(kvm))
return -ENXIO;
irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event->irq, irq_event->level,
line_status);
return 0;
}
static int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
struct kvm_enable_cap *cap)
{
int r;
if (cap->flags)
return -EINVAL;
switch (cap->cap) {
#ifdef CONFIG_KVM_BOOK3S_64_HANDLER
case KVM_CAP_PPC_ENABLE_HCALL: {
unsigned long hcall = cap->args[0];
r = -EINVAL;
if (hcall > MAX_HCALL_OPCODE || (hcall & 3) ||
cap->args[1] > 1)
break;
if (!kvmppc_book3s_hcall_implemented(kvm, hcall))
break;
if (cap->args[1])
set_bit(hcall / 4, kvm->arch.enabled_hcalls);
else
clear_bit(hcall / 4, kvm->arch.enabled_hcalls);
r = 0;
break;
}
case KVM_CAP_PPC_SMT: {
unsigned long mode = cap->args[0];
unsigned long flags = cap->args[1];
r = -EINVAL;
if (kvm->arch.kvm_ops->set_smt_mode)
r = kvm->arch.kvm_ops->set_smt_mode(kvm, mode, flags);
break;
}
#endif
default:
r = -EINVAL;
break;
}
return r;
}
long kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm __maybe_unused = filp->private_data;
void __user *argp = (void __user *)arg;
long r;
switch (ioctl) {
case KVM_PPC_GET_PVINFO: {
struct kvm_ppc_pvinfo pvinfo;
memset(&pvinfo, 0, sizeof(pvinfo));
r = kvm_vm_ioctl_get_pvinfo(&pvinfo);
if (copy_to_user(argp, &pvinfo, sizeof(pvinfo))) {
r = -EFAULT;
goto out;
}
break;
}
case KVM_ENABLE_CAP:
{
struct kvm_enable_cap cap;
r = -EFAULT;
if (copy_from_user(&cap, argp, sizeof(cap)))
goto out;
r = kvm_vm_ioctl_enable_cap(kvm, &cap);
break;
}
#ifdef CONFIG_SPAPR_TCE_IOMMU
case KVM_CREATE_SPAPR_TCE_64: {
struct kvm_create_spapr_tce_64 create_tce_64;
r = -EFAULT;
if (copy_from_user(&create_tce_64, argp, sizeof(create_tce_64)))
goto out;
if (create_tce_64.flags) {
r = -EINVAL;
goto out;
}
r = kvm_vm_ioctl_create_spapr_tce(kvm, &create_tce_64);
goto out;
}
case KVM_CREATE_SPAPR_TCE: {
struct kvm_create_spapr_tce create_tce;
struct kvm_create_spapr_tce_64 create_tce_64;
r = -EFAULT;
if (copy_from_user(&create_tce, argp, sizeof(create_tce)))
goto out;
create_tce_64.liobn = create_tce.liobn;
create_tce_64.page_shift = IOMMU_PAGE_SHIFT_4K;
create_tce_64.offset = 0;
create_tce_64.size = create_tce.window_size >>
IOMMU_PAGE_SHIFT_4K;
create_tce_64.flags = 0;
r = kvm_vm_ioctl_create_spapr_tce(kvm, &create_tce_64);
goto out;
}
#endif
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_PPC_GET_SMMU_INFO: {
struct kvm_ppc_smmu_info info;
struct kvm *kvm = filp->private_data;
memset(&info, 0, sizeof(info));
r = kvm->arch.kvm_ops->get_smmu_info(kvm, &info);
if (r >= 0 && copy_to_user(argp, &info, sizeof(info)))
r = -EFAULT;
break;
}
case KVM_PPC_RTAS_DEFINE_TOKEN: {
struct kvm *kvm = filp->private_data;
r = kvm_vm_ioctl_rtas_define_token(kvm, argp);
break;
}
case KVM_PPC_CONFIGURE_V3_MMU: {
struct kvm *kvm = filp->private_data;
struct kvm_ppc_mmuv3_cfg cfg;
r = -EINVAL;
if (!kvm->arch.kvm_ops->configure_mmu)
goto out;
r = -EFAULT;
if (copy_from_user(&cfg, argp, sizeof(cfg)))
goto out;
r = kvm->arch.kvm_ops->configure_mmu(kvm, &cfg);
break;
}
case KVM_PPC_GET_RMMU_INFO: {
struct kvm *kvm = filp->private_data;
struct kvm_ppc_rmmu_info info;
r = -EINVAL;
if (!kvm->arch.kvm_ops->get_rmmu_info)
goto out;
r = kvm->arch.kvm_ops->get_rmmu_info(kvm, &info);
if (r >= 0 && copy_to_user(argp, &info, sizeof(info)))
r = -EFAULT;
break;
}
default: {
struct kvm *kvm = filp->private_data;
r = kvm->arch.kvm_ops->arch_vm_ioctl(filp, ioctl, arg);
}
#else /* CONFIG_PPC_BOOK3S_64 */
default:
r = -ENOTTY;
#endif
}
out:
return r;
}
static unsigned long lpid_inuse[BITS_TO_LONGS(KVMPPC_NR_LPIDS)];
static unsigned long nr_lpids;
long kvmppc_alloc_lpid(void)
{
long lpid;
do {
lpid = find_first_zero_bit(lpid_inuse, KVMPPC_NR_LPIDS);
if (lpid >= nr_lpids) {
pr_err("%s: No LPIDs free\n", __func__);
return -ENOMEM;
}
} while (test_and_set_bit(lpid, lpid_inuse));
return lpid;
}
EXPORT_SYMBOL_GPL(kvmppc_alloc_lpid);
void kvmppc_claim_lpid(long lpid)
{
set_bit(lpid, lpid_inuse);
}
EXPORT_SYMBOL_GPL(kvmppc_claim_lpid);
void kvmppc_free_lpid(long lpid)
{
clear_bit(lpid, lpid_inuse);
}
EXPORT_SYMBOL_GPL(kvmppc_free_lpid);
void kvmppc_init_lpid(unsigned long nr_lpids_param)
{
nr_lpids = min_t(unsigned long, KVMPPC_NR_LPIDS, nr_lpids_param);
memset(lpid_inuse, 0, sizeof(lpid_inuse));
}
EXPORT_SYMBOL_GPL(kvmppc_init_lpid);
int kvm_arch_init(void *opaque)
{
return 0;
}
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_ppc_instr);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_2858_0 |
crossvul-cpp_data_good_3256_0 | /*
* This contains encryption functions for per-file encryption.
*
* Copyright (C) 2015, Google, Inc.
* Copyright (C) 2015, Motorola Mobility
*
* Written by Michael Halcrow, 2014.
*
* Filename encryption additions
* Uday Savagaonkar, 2014
* Encryption policy handling additions
* Ildar Muslukhov, 2014
* Add fscrypt_pullback_bio_page()
* Jaegeuk Kim, 2015.
*
* This has not yet undergone a rigorous security audit.
*
* The usage of AES-XTS should conform to recommendations in NIST
* Special Publication 800-38E and IEEE P1619/D16.
*/
#include <linux/pagemap.h>
#include <linux/mempool.h>
#include <linux/module.h>
#include <linux/scatterlist.h>
#include <linux/ratelimit.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include "fscrypt_private.h"
static unsigned int num_prealloc_crypto_pages = 32;
static unsigned int num_prealloc_crypto_ctxs = 128;
module_param(num_prealloc_crypto_pages, uint, 0444);
MODULE_PARM_DESC(num_prealloc_crypto_pages,
"Number of crypto pages to preallocate");
module_param(num_prealloc_crypto_ctxs, uint, 0444);
MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
"Number of crypto contexts to preallocate");
static mempool_t *fscrypt_bounce_page_pool = NULL;
static LIST_HEAD(fscrypt_free_ctxs);
static DEFINE_SPINLOCK(fscrypt_ctx_lock);
struct workqueue_struct *fscrypt_read_workqueue;
static DEFINE_MUTEX(fscrypt_init_mutex);
static struct kmem_cache *fscrypt_ctx_cachep;
struct kmem_cache *fscrypt_info_cachep;
/**
* fscrypt_release_ctx() - Releases an encryption context
* @ctx: The encryption context to release.
*
* If the encryption context was allocated from the pre-allocated pool, returns
* it to that pool. Else, frees it.
*
* If there's a bounce page in the context, this frees that.
*/
void fscrypt_release_ctx(struct fscrypt_ctx *ctx)
{
unsigned long flags;
if (ctx->flags & FS_CTX_HAS_BOUNCE_BUFFER_FL && ctx->w.bounce_page) {
mempool_free(ctx->w.bounce_page, fscrypt_bounce_page_pool);
ctx->w.bounce_page = NULL;
}
ctx->w.control_page = NULL;
if (ctx->flags & FS_CTX_REQUIRES_FREE_ENCRYPT_FL) {
kmem_cache_free(fscrypt_ctx_cachep, ctx);
} else {
spin_lock_irqsave(&fscrypt_ctx_lock, flags);
list_add(&ctx->free_list, &fscrypt_free_ctxs);
spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
}
}
EXPORT_SYMBOL(fscrypt_release_ctx);
/**
* fscrypt_get_ctx() - Gets an encryption context
* @inode: The inode for which we are doing the crypto
* @gfp_flags: The gfp flag for memory allocation
*
* Allocates and initializes an encryption context.
*
* Return: An allocated and initialized encryption context on success; error
* value or NULL otherwise.
*/
struct fscrypt_ctx *fscrypt_get_ctx(const struct inode *inode, gfp_t gfp_flags)
{
struct fscrypt_ctx *ctx = NULL;
struct fscrypt_info *ci = inode->i_crypt_info;
unsigned long flags;
if (ci == NULL)
return ERR_PTR(-ENOKEY);
/*
* We first try getting the ctx from a free list because in
* the common case the ctx will have an allocated and
* initialized crypto tfm, so it's probably a worthwhile
* optimization. For the bounce page, we first try getting it
* from the kernel allocator because that's just about as fast
* as getting it from a list and because a cache of free pages
* should generally be a "last resort" option for a filesystem
* to be able to do its job.
*/
spin_lock_irqsave(&fscrypt_ctx_lock, flags);
ctx = list_first_entry_or_null(&fscrypt_free_ctxs,
struct fscrypt_ctx, free_list);
if (ctx)
list_del(&ctx->free_list);
spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
if (!ctx) {
ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, gfp_flags);
if (!ctx)
return ERR_PTR(-ENOMEM);
ctx->flags |= FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
} else {
ctx->flags &= ~FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
}
ctx->flags &= ~FS_CTX_HAS_BOUNCE_BUFFER_FL;
return ctx;
}
EXPORT_SYMBOL(fscrypt_get_ctx);
/**
* page_crypt_complete() - completion callback for page crypto
* @req: The asynchronous cipher request context
* @res: The result of the cipher operation
*/
static void page_crypt_complete(struct crypto_async_request *req, int res)
{
struct fscrypt_completion_result *ecr = req->data;
if (res == -EINPROGRESS)
return;
ecr->res = res;
complete(&ecr->completion);
}
int fscrypt_do_page_crypto(const struct inode *inode, fscrypt_direction_t rw,
u64 lblk_num, struct page *src_page,
struct page *dest_page, unsigned int len,
unsigned int offs, gfp_t gfp_flags)
{
struct {
__le64 index;
u8 padding[FS_XTS_TWEAK_SIZE - sizeof(__le64)];
} xts_tweak;
struct skcipher_request *req = NULL;
DECLARE_FS_COMPLETION_RESULT(ecr);
struct scatterlist dst, src;
struct fscrypt_info *ci = inode->i_crypt_info;
struct crypto_skcipher *tfm = ci->ci_ctfm;
int res = 0;
BUG_ON(len == 0);
req = skcipher_request_alloc(tfm, gfp_flags);
if (!req) {
printk_ratelimited(KERN_ERR
"%s: crypto_request_alloc() failed\n",
__func__);
return -ENOMEM;
}
skcipher_request_set_callback(
req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
page_crypt_complete, &ecr);
BUILD_BUG_ON(sizeof(xts_tweak) != FS_XTS_TWEAK_SIZE);
xts_tweak.index = cpu_to_le64(lblk_num);
memset(xts_tweak.padding, 0, sizeof(xts_tweak.padding));
sg_init_table(&dst, 1);
sg_set_page(&dst, dest_page, len, offs);
sg_init_table(&src, 1);
sg_set_page(&src, src_page, len, offs);
skcipher_request_set_crypt(req, &src, &dst, len, &xts_tweak);
if (rw == FS_DECRYPT)
res = crypto_skcipher_decrypt(req);
else
res = crypto_skcipher_encrypt(req);
if (res == -EINPROGRESS || res == -EBUSY) {
BUG_ON(req->base.data != &ecr);
wait_for_completion(&ecr.completion);
res = ecr.res;
}
skcipher_request_free(req);
if (res) {
printk_ratelimited(KERN_ERR
"%s: crypto_skcipher_encrypt() returned %d\n",
__func__, res);
return res;
}
return 0;
}
struct page *fscrypt_alloc_bounce_page(struct fscrypt_ctx *ctx,
gfp_t gfp_flags)
{
ctx->w.bounce_page = mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);
if (ctx->w.bounce_page == NULL)
return ERR_PTR(-ENOMEM);
ctx->flags |= FS_CTX_HAS_BOUNCE_BUFFER_FL;
return ctx->w.bounce_page;
}
/**
* fscypt_encrypt_page() - Encrypts a page
* @inode: The inode for which the encryption should take place
* @page: The page to encrypt. Must be locked for bounce-page
* encryption.
* @len: Length of data to encrypt in @page and encrypted
* data in returned page.
* @offs: Offset of data within @page and returned
* page holding encrypted data.
* @lblk_num: Logical block number. This must be unique for multiple
* calls with same inode, except when overwriting
* previously written data.
* @gfp_flags: The gfp flag for memory allocation
*
* Encrypts @page using the ctx encryption context. Performs encryption
* either in-place or into a newly allocated bounce page.
* Called on the page write path.
*
* Bounce page allocation is the default.
* In this case, the contents of @page are encrypted and stored in an
* allocated bounce page. @page has to be locked and the caller must call
* fscrypt_restore_control_page() on the returned ciphertext page to
* release the bounce buffer and the encryption context.
*
* In-place encryption is used by setting the FS_CFLG_OWN_PAGES flag in
* fscrypt_operations. Here, the input-page is returned with its content
* encrypted.
*
* Return: A page with the encrypted content on success. Else, an
* error value or NULL.
*/
struct page *fscrypt_encrypt_page(const struct inode *inode,
struct page *page,
unsigned int len,
unsigned int offs,
u64 lblk_num, gfp_t gfp_flags)
{
struct fscrypt_ctx *ctx;
struct page *ciphertext_page = page;
int err;
BUG_ON(len % FS_CRYPTO_BLOCK_SIZE != 0);
if (inode->i_sb->s_cop->flags & FS_CFLG_OWN_PAGES) {
/* with inplace-encryption we just encrypt the page */
err = fscrypt_do_page_crypto(inode, FS_ENCRYPT, lblk_num, page,
ciphertext_page, len, offs,
gfp_flags);
if (err)
return ERR_PTR(err);
return ciphertext_page;
}
BUG_ON(!PageLocked(page));
ctx = fscrypt_get_ctx(inode, gfp_flags);
if (IS_ERR(ctx))
return (struct page *)ctx;
/* The encryption operation will require a bounce page. */
ciphertext_page = fscrypt_alloc_bounce_page(ctx, gfp_flags);
if (IS_ERR(ciphertext_page))
goto errout;
ctx->w.control_page = page;
err = fscrypt_do_page_crypto(inode, FS_ENCRYPT, lblk_num,
page, ciphertext_page, len, offs,
gfp_flags);
if (err) {
ciphertext_page = ERR_PTR(err);
goto errout;
}
SetPagePrivate(ciphertext_page);
set_page_private(ciphertext_page, (unsigned long)ctx);
lock_page(ciphertext_page);
return ciphertext_page;
errout:
fscrypt_release_ctx(ctx);
return ciphertext_page;
}
EXPORT_SYMBOL(fscrypt_encrypt_page);
/**
* fscrypt_decrypt_page() - Decrypts a page in-place
* @inode: The corresponding inode for the page to decrypt.
* @page: The page to decrypt. Must be locked in case
* it is a writeback page (FS_CFLG_OWN_PAGES unset).
* @len: Number of bytes in @page to be decrypted.
* @offs: Start of data in @page.
* @lblk_num: Logical block number.
*
* Decrypts page in-place using the ctx encryption context.
*
* Called from the read completion callback.
*
* Return: Zero on success, non-zero otherwise.
*/
int fscrypt_decrypt_page(const struct inode *inode, struct page *page,
unsigned int len, unsigned int offs, u64 lblk_num)
{
if (!(inode->i_sb->s_cop->flags & FS_CFLG_OWN_PAGES))
BUG_ON(!PageLocked(page));
return fscrypt_do_page_crypto(inode, FS_DECRYPT, lblk_num, page, page,
len, offs, GFP_NOFS);
}
EXPORT_SYMBOL(fscrypt_decrypt_page);
/*
* Validate dentries for encrypted directories to make sure we aren't
* potentially caching stale data after a key has been added or
* removed.
*/
static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
{
struct dentry *dir;
int dir_has_key, cached_with_key;
if (flags & LOOKUP_RCU)
return -ECHILD;
dir = dget_parent(dentry);
if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) {
dput(dir);
return 0;
}
/* this should eventually be an flag in d_flags */
spin_lock(&dentry->d_lock);
cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY;
spin_unlock(&dentry->d_lock);
dir_has_key = (d_inode(dir)->i_crypt_info != NULL);
dput(dir);
/*
* If the dentry was cached without the key, and it is a
* negative dentry, it might be a valid name. We can't check
* if the key has since been made available due to locking
* reasons, so we fail the validation so ext4_lookup() can do
* this check.
*
* We also fail the validation if the dentry was created with
* the key present, but we no longer have the key, or vice versa.
*/
if ((!cached_with_key && d_is_negative(dentry)) ||
(!cached_with_key && dir_has_key) ||
(cached_with_key && !dir_has_key))
return 0;
return 1;
}
const struct dentry_operations fscrypt_d_ops = {
.d_revalidate = fscrypt_d_revalidate,
};
EXPORT_SYMBOL(fscrypt_d_ops);
void fscrypt_restore_control_page(struct page *page)
{
struct fscrypt_ctx *ctx;
ctx = (struct fscrypt_ctx *)page_private(page);
set_page_private(page, (unsigned long)NULL);
ClearPagePrivate(page);
unlock_page(page);
fscrypt_release_ctx(ctx);
}
EXPORT_SYMBOL(fscrypt_restore_control_page);
static void fscrypt_destroy(void)
{
struct fscrypt_ctx *pos, *n;
list_for_each_entry_safe(pos, n, &fscrypt_free_ctxs, free_list)
kmem_cache_free(fscrypt_ctx_cachep, pos);
INIT_LIST_HEAD(&fscrypt_free_ctxs);
mempool_destroy(fscrypt_bounce_page_pool);
fscrypt_bounce_page_pool = NULL;
}
/**
* fscrypt_initialize() - allocate major buffers for fs encryption.
* @cop_flags: fscrypt operations flags
*
* We only call this when we start accessing encrypted files, since it
* results in memory getting allocated that wouldn't otherwise be used.
*
* Return: Zero on success, non-zero otherwise.
*/
int fscrypt_initialize(unsigned int cop_flags)
{
int i, res = -ENOMEM;
/*
* No need to allocate a bounce page pool if there already is one or
* this FS won't use it.
*/
if (cop_flags & FS_CFLG_OWN_PAGES || fscrypt_bounce_page_pool)
return 0;
mutex_lock(&fscrypt_init_mutex);
if (fscrypt_bounce_page_pool)
goto already_initialized;
for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
struct fscrypt_ctx *ctx;
ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, GFP_NOFS);
if (!ctx)
goto fail;
list_add(&ctx->free_list, &fscrypt_free_ctxs);
}
fscrypt_bounce_page_pool =
mempool_create_page_pool(num_prealloc_crypto_pages, 0);
if (!fscrypt_bounce_page_pool)
goto fail;
already_initialized:
mutex_unlock(&fscrypt_init_mutex);
return 0;
fail:
fscrypt_destroy();
mutex_unlock(&fscrypt_init_mutex);
return res;
}
/**
* fscrypt_init() - Set up for fs encryption.
*/
static int __init fscrypt_init(void)
{
fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",
WQ_HIGHPRI, 0);
if (!fscrypt_read_workqueue)
goto fail;
fscrypt_ctx_cachep = KMEM_CACHE(fscrypt_ctx, SLAB_RECLAIM_ACCOUNT);
if (!fscrypt_ctx_cachep)
goto fail_free_queue;
fscrypt_info_cachep = KMEM_CACHE(fscrypt_info, SLAB_RECLAIM_ACCOUNT);
if (!fscrypt_info_cachep)
goto fail_free_ctx;
return 0;
fail_free_ctx:
kmem_cache_destroy(fscrypt_ctx_cachep);
fail_free_queue:
destroy_workqueue(fscrypt_read_workqueue);
fail:
return -ENOMEM;
}
module_init(fscrypt_init)
/**
* fscrypt_exit() - Shutdown the fs encryption system
*/
static void __exit fscrypt_exit(void)
{
fscrypt_destroy();
if (fscrypt_read_workqueue)
destroy_workqueue(fscrypt_read_workqueue);
kmem_cache_destroy(fscrypt_ctx_cachep);
kmem_cache_destroy(fscrypt_info_cachep);
}
module_exit(fscrypt_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3256_0 |
crossvul-cpp_data_bad_528_1 | #include "vterm_internal.h"
#include <stdio.h>
#include <string.h>
#include "rect.h"
#include "utf8.h"
#define UNICODE_SPACE 0x20
#define UNICODE_LINEFEED 0x0a
/* State of the pen at some moment in time, also used in a cell */
typedef struct
{
/* After the bitfield */
VTermColor fg, bg;
unsigned int bold : 1;
unsigned int underline : 2;
unsigned int italic : 1;
unsigned int blink : 1;
unsigned int reverse : 1;
unsigned int strike : 1;
unsigned int font : 4; /* 0 to 9 */
/* Extra state storage that isn't strictly pen-related */
unsigned int protected_cell : 1;
unsigned int dwl : 1; /* on a DECDWL or DECDHL line */
unsigned int dhl : 2; /* on a DECDHL line (1=top 2=bottom) */
} ScreenPen;
/* Internal representation of a screen cell */
typedef struct
{
uint32_t chars[VTERM_MAX_CHARS_PER_CELL];
ScreenPen pen;
} ScreenCell;
static int vterm_screen_set_cell(VTermScreen *screen, VTermPos pos, const VTermScreenCell *cell);
struct VTermScreen
{
VTerm *vt;
VTermState *state;
const VTermScreenCallbacks *callbacks;
void *cbdata;
VTermDamageSize damage_merge;
/* start_row == -1 => no damage */
VTermRect damaged;
VTermRect pending_scrollrect;
int pending_scroll_downward, pending_scroll_rightward;
int rows;
int cols;
int global_reverse;
/* Primary and Altscreen. buffers[1] is lazily allocated as needed */
ScreenCell *buffers[2];
/* buffer will == buffers[0] or buffers[1], depending on altscreen */
ScreenCell *buffer;
/* buffer for a single screen row used in scrollback storage callbacks */
VTermScreenCell *sb_buffer;
ScreenPen pen;
};
static ScreenCell *getcell(const VTermScreen *screen, int row, int col)
{
if(row < 0 || row >= screen->rows)
return NULL;
if(col < 0 || col >= screen->cols)
return NULL;
return screen->buffer + (screen->cols * row) + col;
}
static ScreenCell *realloc_buffer(VTermScreen *screen, ScreenCell *buffer, int new_rows, int new_cols)
{
ScreenCell *new_buffer = vterm_allocator_malloc(screen->vt, sizeof(ScreenCell) * new_rows * new_cols);
int row, col;
for(row = 0; row < new_rows; row++) {
for(col = 0; col < new_cols; col++) {
ScreenCell *new_cell = new_buffer + row*new_cols + col;
if(buffer && row < screen->rows && col < screen->cols)
*new_cell = buffer[row * screen->cols + col];
else {
new_cell->chars[0] = 0;
new_cell->pen = screen->pen;
}
}
}
if(buffer)
vterm_allocator_free(screen->vt, buffer);
return new_buffer;
}
static void damagerect(VTermScreen *screen, VTermRect rect)
{
VTermRect emit;
switch(screen->damage_merge) {
case VTERM_DAMAGE_CELL:
/* Always emit damage event */
emit = rect;
break;
case VTERM_DAMAGE_ROW:
/* Emit damage longer than one row. Try to merge with existing damage in
* the same row */
if(rect.end_row > rect.start_row + 1) {
// Bigger than 1 line - flush existing, emit this
vterm_screen_flush_damage(screen);
emit = rect;
}
else if(screen->damaged.start_row == -1) {
// None stored yet
screen->damaged = rect;
return;
}
else if(rect.start_row == screen->damaged.start_row) {
// Merge with the stored line
if(screen->damaged.start_col > rect.start_col)
screen->damaged.start_col = rect.start_col;
if(screen->damaged.end_col < rect.end_col)
screen->damaged.end_col = rect.end_col;
return;
}
else {
// Emit the currently stored line, store a new one
emit = screen->damaged;
screen->damaged = rect;
}
break;
case VTERM_DAMAGE_SCREEN:
case VTERM_DAMAGE_SCROLL:
/* Never emit damage event */
if(screen->damaged.start_row == -1)
screen->damaged = rect;
else {
rect_expand(&screen->damaged, &rect);
}
return;
default:
DEBUG_LOG1("TODO: Maybe merge damage for level %d\n", screen->damage_merge);
return;
}
if(screen->callbacks && screen->callbacks->damage)
(*screen->callbacks->damage)(emit, screen->cbdata);
}
static void damagescreen(VTermScreen *screen)
{
VTermRect rect = {0,0,0,0};
rect.end_row = screen->rows;
rect.end_col = screen->cols;
damagerect(screen, rect);
}
static int putglyph(VTermGlyphInfo *info, VTermPos pos, void *user)
{
int i;
int col;
VTermRect rect;
VTermScreen *screen = user;
ScreenCell *cell = getcell(screen, pos.row, pos.col);
if(!cell)
return 0;
for(i = 0; i < VTERM_MAX_CHARS_PER_CELL && info->chars[i]; i++) {
cell->chars[i] = info->chars[i];
cell->pen = screen->pen;
}
if(i < VTERM_MAX_CHARS_PER_CELL)
cell->chars[i] = 0;
for(col = 1; col < info->width; col++)
getcell(screen, pos.row, pos.col + col)->chars[0] = (uint32_t)-1;
rect.start_row = pos.row;
rect.end_row = pos.row+1;
rect.start_col = pos.col;
rect.end_col = pos.col+info->width;
cell->pen.protected_cell = info->protected_cell;
cell->pen.dwl = info->dwl;
cell->pen.dhl = info->dhl;
damagerect(screen, rect);
return 1;
}
static int moverect_internal(VTermRect dest, VTermRect src, void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->sb_pushline &&
dest.start_row == 0 && dest.start_col == 0 && // starts top-left corner
dest.end_col == screen->cols && // full width
screen->buffer == screen->buffers[0]) { // not altscreen
VTermPos pos;
for(pos.row = 0; pos.row < src.start_row; pos.row++) {
for(pos.col = 0; pos.col < screen->cols; pos.col++)
(void)vterm_screen_get_cell(screen, pos, screen->sb_buffer + pos.col);
(screen->callbacks->sb_pushline)(screen->cols, screen->sb_buffer, screen->cbdata);
}
}
{
int cols = src.end_col - src.start_col;
int downward = src.start_row - dest.start_row;
int init_row, test_row, inc_row;
int row;
if(downward < 0) {
init_row = dest.end_row - 1;
test_row = dest.start_row - 1;
inc_row = -1;
}
else {
init_row = dest.start_row;
test_row = dest.end_row;
inc_row = +1;
}
for(row = init_row; row != test_row; row += inc_row)
memmove(getcell(screen, row, dest.start_col),
getcell(screen, row + downward, src.start_col),
cols * sizeof(ScreenCell));
}
return 1;
}
static int moverect_user(VTermRect dest, VTermRect src, void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->moverect) {
if(screen->damage_merge != VTERM_DAMAGE_SCROLL)
// Avoid an infinite loop
vterm_screen_flush_damage(screen);
if((*screen->callbacks->moverect)(dest, src, screen->cbdata))
return 1;
}
damagerect(screen, dest);
return 1;
}
static int erase_internal(VTermRect rect, int selective, void *user)
{
VTermScreen *screen = user;
int row, col;
for(row = rect.start_row; row < screen->state->rows && row < rect.end_row; row++) {
const VTermLineInfo *info = vterm_state_get_lineinfo(screen->state, row);
for(col = rect.start_col; col < rect.end_col; col++) {
ScreenCell *cell = getcell(screen, row, col);
if(selective && cell->pen.protected_cell)
continue;
cell->chars[0] = 0;
cell->pen = screen->pen;
cell->pen.dwl = info->doublewidth;
cell->pen.dhl = info->doubleheight;
}
}
return 1;
}
static int erase_user(VTermRect rect, int selective UNUSED, void *user)
{
VTermScreen *screen = user;
damagerect(screen, rect);
return 1;
}
static int erase(VTermRect rect, int selective, void *user)
{
erase_internal(rect, selective, user);
return erase_user(rect, 0, user);
}
static int scrollrect(VTermRect rect, int downward, int rightward, void *user)
{
VTermScreen *screen = user;
if(screen->damage_merge != VTERM_DAMAGE_SCROLL) {
vterm_scroll_rect(rect, downward, rightward,
moverect_internal, erase_internal, screen);
vterm_screen_flush_damage(screen);
vterm_scroll_rect(rect, downward, rightward,
moverect_user, erase_user, screen);
return 1;
}
if(screen->damaged.start_row != -1 &&
!rect_intersects(&rect, &screen->damaged)) {
vterm_screen_flush_damage(screen);
}
if(screen->pending_scrollrect.start_row == -1) {
screen->pending_scrollrect = rect;
screen->pending_scroll_downward = downward;
screen->pending_scroll_rightward = rightward;
}
else if(rect_equal(&screen->pending_scrollrect, &rect) &&
((screen->pending_scroll_downward == 0 && downward == 0) ||
(screen->pending_scroll_rightward == 0 && rightward == 0))) {
screen->pending_scroll_downward += downward;
screen->pending_scroll_rightward += rightward;
}
else {
vterm_screen_flush_damage(screen);
screen->pending_scrollrect = rect;
screen->pending_scroll_downward = downward;
screen->pending_scroll_rightward = rightward;
}
vterm_scroll_rect(rect, downward, rightward,
moverect_internal, erase_internal, screen);
if(screen->damaged.start_row == -1)
return 1;
if(rect_contains(&rect, &screen->damaged)) {
/* Scroll region entirely contains the damage; just move it */
vterm_rect_move(&screen->damaged, -downward, -rightward);
rect_clip(&screen->damaged, &rect);
}
/* There are a number of possible cases here, but lets restrict this to only
* the common case where we might actually gain some performance by
* optimising it. Namely, a vertical scroll that neatly cuts the damage
* region in half.
*/
else if(rect.start_col <= screen->damaged.start_col &&
rect.end_col >= screen->damaged.end_col &&
rightward == 0) {
if(screen->damaged.start_row >= rect.start_row &&
screen->damaged.start_row < rect.end_row) {
screen->damaged.start_row -= downward;
if(screen->damaged.start_row < rect.start_row)
screen->damaged.start_row = rect.start_row;
if(screen->damaged.start_row > rect.end_row)
screen->damaged.start_row = rect.end_row;
}
if(screen->damaged.end_row >= rect.start_row &&
screen->damaged.end_row < rect.end_row) {
screen->damaged.end_row -= downward;
if(screen->damaged.end_row < rect.start_row)
screen->damaged.end_row = rect.start_row;
if(screen->damaged.end_row > rect.end_row)
screen->damaged.end_row = rect.end_row;
}
}
else {
DEBUG_LOG2("TODO: Just flush and redo damaged=" STRFrect " rect=" STRFrect "\n",
ARGSrect(screen->damaged), ARGSrect(rect));
}
return 1;
}
static int movecursor(VTermPos pos, VTermPos oldpos, int visible, void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->movecursor)
return (*screen->callbacks->movecursor)(pos, oldpos, visible, screen->cbdata);
return 0;
}
static int setpenattr(VTermAttr attr, VTermValue *val, void *user)
{
VTermScreen *screen = user;
switch(attr) {
case VTERM_ATTR_BOLD:
screen->pen.bold = val->boolean;
return 1;
case VTERM_ATTR_UNDERLINE:
screen->pen.underline = val->number;
return 1;
case VTERM_ATTR_ITALIC:
screen->pen.italic = val->boolean;
return 1;
case VTERM_ATTR_BLINK:
screen->pen.blink = val->boolean;
return 1;
case VTERM_ATTR_REVERSE:
screen->pen.reverse = val->boolean;
return 1;
case VTERM_ATTR_STRIKE:
screen->pen.strike = val->boolean;
return 1;
case VTERM_ATTR_FONT:
screen->pen.font = val->number;
return 1;
case VTERM_ATTR_FOREGROUND:
screen->pen.fg = val->color;
return 1;
case VTERM_ATTR_BACKGROUND:
screen->pen.bg = val->color;
return 1;
case VTERM_N_ATTRS:
return 0;
}
return 0;
}
static int settermprop(VTermProp prop, VTermValue *val, void *user)
{
VTermScreen *screen = user;
switch(prop) {
case VTERM_PROP_ALTSCREEN:
if(val->boolean && !screen->buffers[1])
return 0;
screen->buffer = val->boolean ? screen->buffers[1] : screen->buffers[0];
/* only send a damage event on disable; because during enable there's an
* erase that sends a damage anyway
*/
if(!val->boolean)
damagescreen(screen);
break;
case VTERM_PROP_REVERSE:
screen->global_reverse = val->boolean;
damagescreen(screen);
break;
default:
; /* ignore */
}
if(screen->callbacks && screen->callbacks->settermprop)
return (*screen->callbacks->settermprop)(prop, val, screen->cbdata);
return 1;
}
static int bell(void *user)
{
VTermScreen *screen = user;
if(screen->callbacks && screen->callbacks->bell)
return (*screen->callbacks->bell)(screen->cbdata);
return 0;
}
static int resize(int new_rows, int new_cols, VTermPos *delta, void *user)
{
VTermScreen *screen = user;
int is_altscreen = (screen->buffers[1] && screen->buffer == screen->buffers[1]);
int old_rows = screen->rows;
int old_cols = screen->cols;
int first_blank_row;
if(!is_altscreen && new_rows < old_rows) {
// Fewer rows - determine if we're going to scroll at all, and if so, push
// those lines to scrollback
VTermPos pos = { 0, 0 };
VTermPos cursor = screen->state->pos;
// Find the first blank row after the cursor.
for(pos.row = old_rows - 1; pos.row >= new_rows; pos.row--)
if(!vterm_screen_is_eol(screen, pos) || cursor.row == pos.row)
break;
first_blank_row = pos.row + 1;
if(first_blank_row > new_rows) {
VTermRect rect = {0,0,0,0};
rect.end_row = old_rows;
rect.end_col = old_cols;
scrollrect(rect, first_blank_row - new_rows, 0, user);
vterm_screen_flush_damage(screen);
delta->row -= first_blank_row - new_rows;
}
}
screen->buffers[0] = realloc_buffer(screen, screen->buffers[0], new_rows, new_cols);
if(screen->buffers[1])
screen->buffers[1] = realloc_buffer(screen, screen->buffers[1], new_rows, new_cols);
screen->buffer = is_altscreen ? screen->buffers[1] : screen->buffers[0];
screen->rows = new_rows;
screen->cols = new_cols;
if(screen->sb_buffer)
vterm_allocator_free(screen->vt, screen->sb_buffer);
screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * new_cols);
if(new_cols > old_cols) {
VTermRect rect;
rect.start_row = 0;
rect.end_row = old_rows;
rect.start_col = old_cols;
rect.end_col = new_cols;
damagerect(screen, rect);
}
if(new_rows > old_rows) {
if(!is_altscreen && screen->callbacks && screen->callbacks->sb_popline) {
int rows = new_rows - old_rows;
while(rows) {
VTermRect rect = {0,0,0,0};
VTermPos pos = { 0, 0 };
if(!(screen->callbacks->sb_popline(screen->cols, screen->sb_buffer, screen->cbdata)))
break;
rect.end_row = screen->rows;
rect.end_col = screen->cols;
scrollrect(rect, -1, 0, user);
for(pos.col = 0; pos.col < screen->cols; pos.col += screen->sb_buffer[pos.col].width)
vterm_screen_set_cell(screen, pos, screen->sb_buffer + pos.col);
rect.end_row = 1;
damagerect(screen, rect);
vterm_screen_flush_damage(screen);
rows--;
delta->row++;
}
}
{
VTermRect rect;
rect.start_row = old_rows;
rect.end_row = new_rows;
rect.start_col = 0;
rect.end_col = new_cols;
damagerect(screen, rect);
}
}
if(screen->callbacks && screen->callbacks->resize)
return (*screen->callbacks->resize)(new_rows, new_cols, screen->cbdata);
return 1;
}
static int setlineinfo(int row, const VTermLineInfo *newinfo, const VTermLineInfo *oldinfo, void *user)
{
VTermScreen *screen = user;
int col;
VTermRect rect;
if(newinfo->doublewidth != oldinfo->doublewidth ||
newinfo->doubleheight != oldinfo->doubleheight) {
for(col = 0; col < screen->cols; col++) {
ScreenCell *cell = getcell(screen, row, col);
cell->pen.dwl = newinfo->doublewidth;
cell->pen.dhl = newinfo->doubleheight;
}
rect.start_row = row;
rect.end_row = row + 1;
rect.start_col = 0;
rect.end_col = newinfo->doublewidth ? screen->cols / 2 : screen->cols;
damagerect(screen, rect);
if(newinfo->doublewidth) {
rect.start_col = screen->cols / 2;
rect.end_col = screen->cols;
erase_internal(rect, 0, user);
}
}
return 1;
}
static VTermStateCallbacks state_cbs = {
&putglyph, /* putglyph */
&movecursor, /* movecursor */
&scrollrect, /* scrollrect */
NULL, /* moverect */
&erase, /* erase */
NULL, /* initpen */
&setpenattr, /* setpenattr */
&settermprop, /* settermprop */
&bell, /* bell */
&resize, /* resize */
&setlineinfo /* setlineinfo */
};
static VTermScreen *screen_new(VTerm *vt)
{
VTermState *state = vterm_obtain_state(vt);
VTermScreen *screen;
int rows, cols;
if(!state)
return NULL;
screen = vterm_allocator_malloc(vt, sizeof(VTermScreen));
vterm_get_size(vt, &rows, &cols);
screen->vt = vt;
screen->state = state;
screen->damage_merge = VTERM_DAMAGE_CELL;
screen->damaged.start_row = -1;
screen->pending_scrollrect.start_row = -1;
screen->rows = rows;
screen->cols = cols;
screen->callbacks = NULL;
screen->cbdata = NULL;
screen->buffers[0] = realloc_buffer(screen, NULL, rows, cols);
screen->buffer = screen->buffers[0];
screen->sb_buffer = vterm_allocator_malloc(screen->vt, sizeof(VTermScreenCell) * cols);
vterm_state_set_callbacks(screen->state, &state_cbs, screen);
return screen;
}
INTERNAL void vterm_screen_free(VTermScreen *screen)
{
vterm_allocator_free(screen->vt, screen->buffers[0]);
if(screen->buffers[1])
vterm_allocator_free(screen->vt, screen->buffers[1]);
vterm_allocator_free(screen->vt, screen->sb_buffer);
vterm_allocator_free(screen->vt, screen);
}
void vterm_screen_reset(VTermScreen *screen, int hard)
{
screen->damaged.start_row = -1;
screen->pending_scrollrect.start_row = -1;
vterm_state_reset(screen->state, hard);
vterm_screen_flush_damage(screen);
}
static size_t _get_chars(const VTermScreen *screen, const int utf8, void *buffer, size_t len, const VTermRect rect)
{
size_t outpos = 0;
int padding = 0;
int row, col;
#define PUT(c) \
if(utf8) { \
size_t thislen = utf8_seqlen(c); \
if(buffer && outpos + thislen <= len) \
outpos += fill_utf8((c), (char *)buffer + outpos); \
else \
outpos += thislen; \
} \
else { \
if(buffer && outpos + 1 <= len) \
((uint32_t*)buffer)[outpos++] = (c); \
else \
outpos++; \
}
for(row = rect.start_row; row < rect.end_row; row++) {
for(col = rect.start_col; col < rect.end_col; col++) {
ScreenCell *cell = getcell(screen, row, col);
int i;
if(cell->chars[0] == 0)
// Erased cell, might need a space
padding++;
else if(cell->chars[0] == (uint32_t)-1)
// Gap behind a double-width char, do nothing
;
else {
while(padding) {
PUT(UNICODE_SPACE);
padding--;
}
for(i = 0; i < VTERM_MAX_CHARS_PER_CELL && cell->chars[i]; i++) {
PUT(cell->chars[i]);
}
}
}
if(row < rect.end_row - 1) {
PUT(UNICODE_LINEFEED);
padding = 0;
}
}
return outpos;
}
size_t vterm_screen_get_chars(const VTermScreen *screen, uint32_t *chars, size_t len, const VTermRect rect)
{
return _get_chars(screen, 0, chars, len, rect);
}
size_t vterm_screen_get_text(const VTermScreen *screen, char *str, size_t len, const VTermRect rect)
{
return _get_chars(screen, 1, str, len, rect);
}
/* Copy internal to external representation of a screen cell */
int vterm_screen_get_cell(const VTermScreen *screen, VTermPos pos, VTermScreenCell *cell)
{
ScreenCell *intcell = getcell(screen, pos.row, pos.col);
int i;
if(!intcell)
return 0;
for(i = 0; ; i++) {
cell->chars[i] = intcell->chars[i];
if(!intcell->chars[i])
break;
}
cell->attrs.bold = intcell->pen.bold;
cell->attrs.underline = intcell->pen.underline;
cell->attrs.italic = intcell->pen.italic;
cell->attrs.blink = intcell->pen.blink;
cell->attrs.reverse = intcell->pen.reverse ^ screen->global_reverse;
cell->attrs.strike = intcell->pen.strike;
cell->attrs.font = intcell->pen.font;
cell->attrs.dwl = intcell->pen.dwl;
cell->attrs.dhl = intcell->pen.dhl;
cell->fg = intcell->pen.fg;
cell->bg = intcell->pen.bg;
if(pos.col < (screen->cols - 1) &&
getcell(screen, pos.row, pos.col + 1)->chars[0] == (uint32_t)-1)
cell->width = 2;
else
cell->width = 1;
return 1;
}
/* Copy external to internal representation of a screen cell */
/* static because it's only used internally for sb_popline during resize */
static int vterm_screen_set_cell(VTermScreen *screen, VTermPos pos, const VTermScreenCell *cell)
{
ScreenCell *intcell = getcell(screen, pos.row, pos.col);
int i;
if(!intcell)
return 0;
for(i = 0; ; i++) {
intcell->chars[i] = cell->chars[i];
if(!cell->chars[i])
break;
}
intcell->pen.bold = cell->attrs.bold;
intcell->pen.underline = cell->attrs.underline;
intcell->pen.italic = cell->attrs.italic;
intcell->pen.blink = cell->attrs.blink;
intcell->pen.reverse = cell->attrs.reverse ^ screen->global_reverse;
intcell->pen.strike = cell->attrs.strike;
intcell->pen.font = cell->attrs.font;
intcell->pen.fg = cell->fg;
intcell->pen.bg = cell->bg;
if(cell->width == 2)
getcell(screen, pos.row, pos.col + 1)->chars[0] = (uint32_t)-1;
return 1;
}
int vterm_screen_is_eol(const VTermScreen *screen, VTermPos pos)
{
/* This cell is EOL if this and every cell to the right is black */
for(; pos.col < screen->cols; pos.col++) {
ScreenCell *cell = getcell(screen, pos.row, pos.col);
if(cell->chars[0] != 0)
return 0;
}
return 1;
}
VTermScreen *vterm_obtain_screen(VTerm *vt)
{
if(!vt->screen)
vt->screen = screen_new(vt);
return vt->screen;
}
void vterm_screen_enable_altscreen(VTermScreen *screen, int altscreen)
{
if(!screen->buffers[1] && altscreen) {
int rows, cols;
vterm_get_size(screen->vt, &rows, &cols);
screen->buffers[1] = realloc_buffer(screen, NULL, rows, cols);
}
}
void vterm_screen_set_callbacks(VTermScreen *screen, const VTermScreenCallbacks *callbacks, void *user)
{
screen->callbacks = callbacks;
screen->cbdata = user;
}
void *vterm_screen_get_cbdata(VTermScreen *screen)
{
return screen->cbdata;
}
void vterm_screen_set_unrecognised_fallbacks(VTermScreen *screen, const VTermParserCallbacks *fallbacks, void *user)
{
vterm_state_set_unrecognised_fallbacks(screen->state, fallbacks, user);
}
void *vterm_screen_get_unrecognised_fbdata(VTermScreen *screen)
{
return vterm_state_get_unrecognised_fbdata(screen->state);
}
void vterm_screen_flush_damage(VTermScreen *screen)
{
if(screen->pending_scrollrect.start_row != -1) {
vterm_scroll_rect(screen->pending_scrollrect, screen->pending_scroll_downward, screen->pending_scroll_rightward,
moverect_user, erase_user, screen);
screen->pending_scrollrect.start_row = -1;
}
if(screen->damaged.start_row != -1) {
if(screen->callbacks && screen->callbacks->damage)
(*screen->callbacks->damage)(screen->damaged, screen->cbdata);
screen->damaged.start_row = -1;
}
}
void vterm_screen_set_damage_merge(VTermScreen *screen, VTermDamageSize size)
{
vterm_screen_flush_damage(screen);
screen->damage_merge = size;
}
static int attrs_differ(VTermAttrMask attrs, ScreenCell *a, ScreenCell *b)
{
if((attrs & VTERM_ATTR_BOLD_MASK) && (a->pen.bold != b->pen.bold))
return 1;
if((attrs & VTERM_ATTR_UNDERLINE_MASK) && (a->pen.underline != b->pen.underline))
return 1;
if((attrs & VTERM_ATTR_ITALIC_MASK) && (a->pen.italic != b->pen.italic))
return 1;
if((attrs & VTERM_ATTR_BLINK_MASK) && (a->pen.blink != b->pen.blink))
return 1;
if((attrs & VTERM_ATTR_REVERSE_MASK) && (a->pen.reverse != b->pen.reverse))
return 1;
if((attrs & VTERM_ATTR_STRIKE_MASK) && (a->pen.strike != b->pen.strike))
return 1;
if((attrs & VTERM_ATTR_FONT_MASK) && (a->pen.font != b->pen.font))
return 1;
if((attrs & VTERM_ATTR_FOREGROUND_MASK) && !vterm_color_equal(a->pen.fg, b->pen.fg))
return 1;
if((attrs & VTERM_ATTR_BACKGROUND_MASK) && !vterm_color_equal(a->pen.bg, b->pen.bg))
return 1;
return 0;
}
int vterm_screen_get_attrs_extent(const VTermScreen *screen, VTermRect *extent, VTermPos pos, VTermAttrMask attrs)
{
int col;
ScreenCell *target = getcell(screen, pos.row, pos.col);
// TODO: bounds check
extent->start_row = pos.row;
extent->end_row = pos.row + 1;
if(extent->start_col < 0)
extent->start_col = 0;
if(extent->end_col < 0)
extent->end_col = screen->cols;
for(col = pos.col - 1; col >= extent->start_col; col--)
if(attrs_differ(attrs, target, getcell(screen, pos.row, col)))
break;
extent->start_col = col + 1;
for(col = pos.col + 1; col < extent->end_col; col++)
if(attrs_differ(attrs, target, getcell(screen, pos.row, col)))
break;
extent->end_col = col - 1;
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_528_1 |
crossvul-cpp_data_good_178_0 | /*
** class.c - Class class
**
** See Copyright Notice in mruby.h
*/
#include <stdarg.h>
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/numeric.h>
#include <mruby/proc.h>
#include <mruby/string.h>
#include <mruby/variable.h>
#include <mruby/error.h>
#include <mruby/data.h>
#include <mruby/istruct.h>
KHASH_DEFINE(mt, mrb_sym, mrb_method_t, TRUE, kh_int_hash_func, kh_int_hash_equal)
void
mrb_gc_mark_mt(mrb_state *mrb, struct RClass *c)
{
khiter_t k;
khash_t(mt) *h = c->mt;
if (!h) return;
for (k = kh_begin(h); k != kh_end(h); k++) {
if (kh_exist(h, k)) {
mrb_method_t m = kh_value(h, k);
if (MRB_METHOD_PROC_P(m)) {
struct RProc *p = MRB_METHOD_PROC(m);
mrb_gc_mark(mrb, (struct RBasic*)p);
}
}
}
}
size_t
mrb_gc_mark_mt_size(mrb_state *mrb, struct RClass *c)
{
khash_t(mt) *h = c->mt;
if (!h) return 0;
return kh_size(h);
}
void
mrb_gc_free_mt(mrb_state *mrb, struct RClass *c)
{
kh_destroy(mt, mrb, c->mt);
}
void
mrb_class_name_class(mrb_state *mrb, struct RClass *outer, struct RClass *c, mrb_sym id)
{
mrb_value name;
mrb_sym nsym = mrb_intern_lit(mrb, "__classname__");
if (mrb_obj_iv_defined(mrb, (struct RObject*)c, nsym)) return;
if (outer == NULL || outer == mrb->object_class) {
name = mrb_symbol_value(id);
}
else {
name = mrb_class_path(mrb, outer);
if (mrb_nil_p(name)) { /* unnamed outer class */
if (outer != mrb->object_class) {
mrb_obj_iv_set(mrb, (struct RObject*)c, mrb_intern_lit(mrb, "__outer__"),
mrb_obj_value(outer));
}
return;
}
mrb_str_cat_cstr(mrb, name, "::");
mrb_str_cat_cstr(mrb, name, mrb_sym2name(mrb, id));
}
mrb_obj_iv_set(mrb, (struct RObject*)c, nsym, name);
}
static void
setup_class(mrb_state *mrb, struct RClass *outer, struct RClass *c, mrb_sym id)
{
mrb_class_name_class(mrb, outer, c, id);
mrb_obj_iv_set(mrb, (struct RObject*)outer, id, mrb_obj_value(c));
}
#define make_metaclass(mrb, c) prepare_singleton_class((mrb), (struct RBasic*)(c))
static void
prepare_singleton_class(mrb_state *mrb, struct RBasic *o)
{
struct RClass *sc, *c;
if (o->c->tt == MRB_TT_SCLASS) return;
sc = (struct RClass*)mrb_obj_alloc(mrb, MRB_TT_SCLASS, mrb->class_class);
sc->flags |= MRB_FLAG_IS_INHERITED;
sc->mt = kh_init(mt, mrb);
sc->iv = 0;
if (o->tt == MRB_TT_CLASS) {
c = (struct RClass*)o;
if (!c->super) {
sc->super = mrb->class_class;
}
else {
sc->super = c->super->c;
}
}
else if (o->tt == MRB_TT_SCLASS) {
c = (struct RClass*)o;
while (c->super->tt == MRB_TT_ICLASS)
c = c->super;
make_metaclass(mrb, c->super);
sc->super = c->super->c;
}
else {
sc->super = o->c;
prepare_singleton_class(mrb, (struct RBasic*)sc);
}
o->c = sc;
mrb_field_write_barrier(mrb, (struct RBasic*)o, (struct RBasic*)sc);
mrb_field_write_barrier(mrb, (struct RBasic*)sc, (struct RBasic*)o);
mrb_obj_iv_set(mrb, (struct RObject*)sc, mrb_intern_lit(mrb, "__attached__"), mrb_obj_value(o));
}
static struct RClass*
class_from_sym(mrb_state *mrb, struct RClass *klass, mrb_sym id)
{
mrb_value c = mrb_const_get(mrb, mrb_obj_value(klass), id);
mrb_check_type(mrb, c, MRB_TT_CLASS);
return mrb_class_ptr(c);
}
static struct RClass*
module_from_sym(mrb_state *mrb, struct RClass *klass, mrb_sym id)
{
mrb_value c = mrb_const_get(mrb, mrb_obj_value(klass), id);
mrb_check_type(mrb, c, MRB_TT_MODULE);
return mrb_class_ptr(c);
}
static mrb_bool
class_ptr_p(mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_CLASS:
case MRB_TT_SCLASS:
case MRB_TT_MODULE:
return TRUE;
default:
return FALSE;
}
}
static void
check_if_class_or_module(mrb_state *mrb, mrb_value obj)
{
if (!class_ptr_p(obj)) {
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a class/module", mrb_inspect(mrb, obj));
}
}
static struct RClass*
define_module(mrb_state *mrb, mrb_sym name, struct RClass *outer)
{
struct RClass *m;
if (mrb_const_defined_at(mrb, mrb_obj_value(outer), name)) {
return module_from_sym(mrb, outer, name);
}
m = mrb_module_new(mrb);
setup_class(mrb, outer, m, name);
return m;
}
MRB_API struct RClass*
mrb_define_module_id(mrb_state *mrb, mrb_sym name)
{
return define_module(mrb, name, mrb->object_class);
}
MRB_API struct RClass*
mrb_define_module(mrb_state *mrb, const char *name)
{
return define_module(mrb, mrb_intern_cstr(mrb, name), mrb->object_class);
}
MRB_API struct RClass*
mrb_vm_define_module(mrb_state *mrb, mrb_value outer, mrb_sym id)
{
check_if_class_or_module(mrb, outer);
if (mrb_const_defined_at(mrb, outer, id)) {
mrb_value old = mrb_const_get(mrb, outer, id);
if (mrb_type(old) != MRB_TT_MODULE) {
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a module", mrb_inspect(mrb, old));
}
return mrb_class_ptr(old);
}
return define_module(mrb, id, mrb_class_ptr(outer));
}
MRB_API struct RClass*
mrb_define_module_under(mrb_state *mrb, struct RClass *outer, const char *name)
{
mrb_sym id = mrb_intern_cstr(mrb, name);
struct RClass * c = define_module(mrb, id, outer);
setup_class(mrb, outer, c, id);
return c;
}
static struct RClass*
find_origin(struct RClass *c)
{
MRB_CLASS_ORIGIN(c);
return c;
}
static struct RClass*
define_class(mrb_state *mrb, mrb_sym name, struct RClass *super, struct RClass *outer)
{
struct RClass * c;
if (mrb_const_defined_at(mrb, mrb_obj_value(outer), name)) {
c = class_from_sym(mrb, outer, name);
MRB_CLASS_ORIGIN(c);
if (super && mrb_class_real(c->super) != super) {
mrb_raisef(mrb, E_TYPE_ERROR, "superclass mismatch for Class %S (%S not %S)",
mrb_sym2str(mrb, name),
mrb_obj_value(c->super), mrb_obj_value(super));
}
return c;
}
c = mrb_class_new(mrb, super);
setup_class(mrb, outer, c, name);
return c;
}
MRB_API struct RClass*
mrb_define_class_id(mrb_state *mrb, mrb_sym name, struct RClass *super)
{
if (!super) {
mrb_warn(mrb, "no super class for '%S', Object assumed", mrb_sym2str(mrb, name));
}
return define_class(mrb, name, super, mrb->object_class);
}
MRB_API struct RClass*
mrb_define_class(mrb_state *mrb, const char *name, struct RClass *super)
{
return mrb_define_class_id(mrb, mrb_intern_cstr(mrb, name), super);
}
static mrb_value mrb_bob_init(mrb_state *mrb, mrb_value);
#ifdef MRB_METHOD_CACHE
static void mc_clear_all(mrb_state *mrb);
static void mc_clear_by_class(mrb_state *mrb, struct RClass*);
static void mc_clear_by_id(mrb_state *mrb, struct RClass*, mrb_sym);
#else
#define mc_clear_all(mrb)
#define mc_clear_by_class(mrb,c)
#define mc_clear_by_id(mrb,c,s)
#endif
static void
mrb_class_inherited(mrb_state *mrb, struct RClass *super, struct RClass *klass)
{
mrb_value s;
mrb_sym mid;
if (!super)
super = mrb->object_class;
super->flags |= MRB_FLAG_IS_INHERITED;
s = mrb_obj_value(super);
mc_clear_by_class(mrb, klass);
mid = mrb_intern_lit(mrb, "inherited");
if (!mrb_func_basic_p(mrb, s, mid, mrb_bob_init)) {
mrb_value c = mrb_obj_value(klass);
mrb_funcall_argv(mrb, s, mid, 1, &c);
}
}
MRB_API struct RClass*
mrb_vm_define_class(mrb_state *mrb, mrb_value outer, mrb_value super, mrb_sym id)
{
struct RClass *s;
struct RClass *c;
if (!mrb_nil_p(super)) {
if (mrb_type(super) != MRB_TT_CLASS) {
mrb_raisef(mrb, E_TYPE_ERROR, "superclass must be a Class (%S given)",
mrb_inspect(mrb, super));
}
s = mrb_class_ptr(super);
}
else {
s = 0;
}
check_if_class_or_module(mrb, outer);
if (mrb_const_defined_at(mrb, outer, id)) {
mrb_value old = mrb_const_get(mrb, outer, id);
if (mrb_type(old) != MRB_TT_CLASS) {
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a class", mrb_inspect(mrb, old));
}
c = mrb_class_ptr(old);
if (s) {
/* check super class */
if (mrb_class_real(c->super) != s) {
mrb_raisef(mrb, E_TYPE_ERROR, "superclass mismatch for class %S", old);
}
}
return c;
}
c = define_class(mrb, id, s, mrb_class_ptr(outer));
mrb_class_inherited(mrb, mrb_class_real(c->super), c);
return c;
}
MRB_API mrb_bool
mrb_class_defined(mrb_state *mrb, const char *name)
{
mrb_value sym = mrb_check_intern_cstr(mrb, name);
if (mrb_nil_p(sym)) {
return FALSE;
}
return mrb_const_defined(mrb, mrb_obj_value(mrb->object_class), mrb_symbol(sym));
}
MRB_API mrb_bool
mrb_class_defined_under(mrb_state *mrb, struct RClass *outer, const char *name)
{
mrb_value sym = mrb_check_intern_cstr(mrb, name);
if (mrb_nil_p(sym)) {
return FALSE;
}
return mrb_const_defined_at(mrb, mrb_obj_value(outer), mrb_symbol(sym));
}
MRB_API struct RClass*
mrb_class_get_under(mrb_state *mrb, struct RClass *outer, const char *name)
{
return class_from_sym(mrb, outer, mrb_intern_cstr(mrb, name));
}
MRB_API struct RClass*
mrb_class_get(mrb_state *mrb, const char *name)
{
return mrb_class_get_under(mrb, mrb->object_class, name);
}
MRB_API struct RClass*
mrb_exc_get(mrb_state *mrb, const char *name)
{
struct RClass *exc, *e;
mrb_value c = mrb_const_get(mrb, mrb_obj_value(mrb->object_class),
mrb_intern_cstr(mrb, name));
if (mrb_type(c) != MRB_TT_CLASS) {
mrb_raise(mrb, mrb->eException_class, "exception corrupted");
}
exc = e = mrb_class_ptr(c);
while (e) {
if (e == mrb->eException_class)
return exc;
e = e->super;
}
return mrb->eException_class;
}
MRB_API struct RClass*
mrb_module_get_under(mrb_state *mrb, struct RClass *outer, const char *name)
{
return module_from_sym(mrb, outer, mrb_intern_cstr(mrb, name));
}
MRB_API struct RClass*
mrb_module_get(mrb_state *mrb, const char *name)
{
return mrb_module_get_under(mrb, mrb->object_class, name);
}
/*!
* Defines a class under the namespace of \a outer.
* \param outer a class which contains the new class.
* \param id name of the new class
* \param super a class from which the new class will derive.
* NULL means \c Object class.
* \return the created class
* \throw TypeError if the constant name \a name is already taken but
* the constant is not a \c Class.
* \throw NameError if the class is already defined but the class can not
* be reopened because its superclass is not \a super.
* \post top-level constant named \a name refers the returned class.
*
* \note if a class named \a name is already defined and its superclass is
* \a super, the function just returns the defined class.
*/
MRB_API struct RClass*
mrb_define_class_under(mrb_state *mrb, struct RClass *outer, const char *name, struct RClass *super)
{
mrb_sym id = mrb_intern_cstr(mrb, name);
struct RClass * c;
#if 0
if (!super) {
mrb_warn(mrb, "no super class for '%S::%S', Object assumed",
mrb_obj_value(outer), mrb_sym2str(mrb, id));
}
#endif
c = define_class(mrb, id, super, outer);
setup_class(mrb, outer, c, id);
return c;
}
MRB_API void
mrb_define_method_raw(mrb_state *mrb, struct RClass *c, mrb_sym mid, mrb_method_t m)
{
khash_t(mt) *h;
khiter_t k;
MRB_CLASS_ORIGIN(c);
h = c->mt;
if (MRB_FROZEN_P(c)) {
if (c->tt == MRB_TT_MODULE)
mrb_raise(mrb, E_FROZEN_ERROR, "can't modify frozen module");
else
mrb_raise(mrb, E_FROZEN_ERROR, "can't modify frozen class");
}
if (!h) h = c->mt = kh_init(mt, mrb);
k = kh_put(mt, mrb, h, mid);
kh_value(h, k) = m;
if (MRB_METHOD_PROC_P(m) && !MRB_METHOD_UNDEF_P(m)) {
struct RProc *p = MRB_METHOD_PROC(m);
p->flags |= MRB_PROC_SCOPE;
p->c = NULL;
mrb_field_write_barrier(mrb, (struct RBasic*)c, (struct RBasic*)p);
if (!MRB_PROC_ENV_P(p)) {
MRB_PROC_SET_TARGET_CLASS(p, c);
}
}
mc_clear_by_id(mrb, c, mid);
}
MRB_API void
mrb_define_method_id(mrb_state *mrb, struct RClass *c, mrb_sym mid, mrb_func_t func, mrb_aspec aspec)
{
mrb_method_t m;
int ai = mrb_gc_arena_save(mrb);
MRB_METHOD_FROM_FUNC(m, func);
mrb_define_method_raw(mrb, c, mid, m);
mrb_gc_arena_restore(mrb, ai);
}
MRB_API void
mrb_define_method(mrb_state *mrb, struct RClass *c, const char *name, mrb_func_t func, mrb_aspec aspec)
{
mrb_define_method_id(mrb, c, mrb_intern_cstr(mrb, name), func, aspec);
}
/* a function to raise NotImplementedError with current method name */
MRB_API void
mrb_notimplement(mrb_state *mrb)
{
const char *str;
mrb_int len;
mrb_callinfo *ci = mrb->c->ci;
if (ci->mid) {
str = mrb_sym2name_len(mrb, ci->mid, &len);
mrb_raisef(mrb, E_NOTIMP_ERROR,
"%S() function is unimplemented on this machine",
mrb_str_new_static(mrb, str, (size_t)len));
}
}
/* a function to be replacement of unimplemented method */
MRB_API mrb_value
mrb_notimplement_m(mrb_state *mrb, mrb_value self)
{
mrb_notimplement(mrb);
/* not reached */
return mrb_nil_value();
}
static mrb_value
check_type(mrb_state *mrb, mrb_value val, enum mrb_vtype t, const char *c, const char *m)
{
mrb_value tmp;
tmp = mrb_check_convert_type(mrb, val, t, c, m);
if (mrb_nil_p(tmp)) {
mrb_raisef(mrb, E_TYPE_ERROR, "expected %S", mrb_str_new_cstr(mrb, c));
}
return tmp;
}
static mrb_value
to_str(mrb_state *mrb, mrb_value val)
{
return check_type(mrb, val, MRB_TT_STRING, "String", "to_str");
}
static mrb_value
to_ary(mrb_state *mrb, mrb_value val)
{
return check_type(mrb, val, MRB_TT_ARRAY, "Array", "to_ary");
}
static mrb_value
to_hash(mrb_state *mrb, mrb_value val)
{
return check_type(mrb, val, MRB_TT_HASH, "Hash", "to_hash");
}
static mrb_sym
to_sym(mrb_state *mrb, mrb_value ss)
{
if (mrb_type(ss) == MRB_TT_SYMBOL) {
return mrb_symbol(ss);
}
else if (mrb_string_p(ss)) {
return mrb_intern_str(mrb, to_str(mrb, ss));
}
else {
mrb_value obj = mrb_funcall(mrb, ss, "inspect", 0);
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a symbol", obj);
/* not reached */
return 0;
}
}
MRB_API mrb_int
mrb_get_argc(mrb_state *mrb)
{
mrb_int argc = mrb->c->ci->argc;
if (argc < 0) {
struct RArray *a = mrb_ary_ptr(mrb->c->stack[1]);
argc = ARY_LEN(a);
}
return argc;
}
MRB_API mrb_value*
mrb_get_argv(mrb_state *mrb)
{
mrb_int argc = mrb->c->ci->argc;
mrb_value *array_argv;
if (argc < 0) {
struct RArray *a = mrb_ary_ptr(mrb->c->stack[1]);
array_argv = ARY_PTR(a);
}
else {
array_argv = NULL;
}
return array_argv;
}
/*
retrieve arguments from mrb_state.
mrb_get_args(mrb, format, ...)
returns number of arguments parsed.
format specifiers:
string mruby type C type note
----------------------------------------------------------------------------------------------
o: Object [mrb_value]
C: class/module [mrb_value]
S: String [mrb_value] when ! follows, the value may be nil
A: Array [mrb_value] when ! follows, the value may be nil
H: Hash [mrb_value] when ! follows, the value may be nil
s: String [char*,mrb_int] Receive two arguments; s! gives (NULL,0) for nil
z: String [char*] NUL terminated string; z! gives NULL for nil
a: Array [mrb_value*,mrb_int] Receive two arguments; a! gives (NULL,0) for nil
f: Float [mrb_float]
i: Integer [mrb_int]
b: Boolean [mrb_bool]
n: Symbol [mrb_sym]
d: Data [void*,mrb_data_type const] 2nd argument will be used to check data type so it won't be modified
I: Inline struct [void*]
&: Block [mrb_value] &! raises exception if no block given
*: rest argument [mrb_value*,mrb_int] The rest of the arguments as an array; *! avoid copy of the stack
|: optional Following arguments are optional
?: optional given [mrb_bool] true if preceding argument (optional) is given
*/
MRB_API mrb_int
mrb_get_args(mrb_state *mrb, const char *format, ...)
{
const char *fmt = format;
char c;
mrb_int i = 0;
va_list ap;
mrb_int argc = mrb_get_argc(mrb);
mrb_int arg_i = 0;
mrb_value *array_argv = mrb_get_argv(mrb);
mrb_bool opt = FALSE;
mrb_bool opt_skip = TRUE;
mrb_bool given = TRUE;
va_start(ap, format);
#define ARGV \
(array_argv ? array_argv : (mrb->c->stack + 1))
while ((c = *fmt++)) {
switch (c) {
case '|':
opt = TRUE;
break;
case '*':
opt_skip = FALSE;
goto check_exit;
case '!':
break;
case '&': case '?':
if (opt) opt_skip = FALSE;
break;
default:
break;
}
}
check_exit:
opt = FALSE;
i = 0;
while ((c = *format++)) {
switch (c) {
case '|': case '*': case '&': case '?':
break;
default:
if (argc <= i) {
if (opt) {
given = FALSE;
}
else {
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
}
}
break;
}
switch (c) {
case 'o':
{
mrb_value *p;
p = va_arg(ap, mrb_value*);
if (i < argc) {
*p = ARGV[arg_i++];
i++;
}
}
break;
case 'C':
{
mrb_value *p;
p = va_arg(ap, mrb_value*);
if (i < argc) {
mrb_value ss;
ss = ARGV[arg_i++];
if (!class_ptr_p(ss)) {
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not class/module", ss);
}
*p = ss;
i++;
}
}
break;
case 'S':
{
mrb_value *p;
p = va_arg(ap, mrb_value*);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*p = ARGV[arg_i++];
i++;
break;
}
}
if (i < argc) {
*p = to_str(mrb, ARGV[arg_i++]);
i++;
}
}
break;
case 'A':
{
mrb_value *p;
p = va_arg(ap, mrb_value*);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*p = ARGV[arg_i++];
i++;
break;
}
}
if (i < argc) {
*p = to_ary(mrb, ARGV[arg_i++]);
i++;
}
}
break;
case 'H':
{
mrb_value *p;
p = va_arg(ap, mrb_value*);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*p = ARGV[arg_i++];
i++;
break;
}
}
if (i < argc) {
*p = to_hash(mrb, ARGV[arg_i++]);
i++;
}
}
break;
case 's':
{
mrb_value ss;
char **ps = 0;
mrb_int *pl = 0;
ps = va_arg(ap, char**);
pl = va_arg(ap, mrb_int*);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*ps = NULL;
*pl = 0;
i++; arg_i++;
break;
}
}
if (i < argc) {
ss = to_str(mrb, ARGV[arg_i++]);
*ps = RSTRING_PTR(ss);
*pl = RSTRING_LEN(ss);
i++;
}
}
break;
case 'z':
{
mrb_value ss;
const char **ps;
ps = va_arg(ap, const char**);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*ps = NULL;
i++; arg_i++;
break;
}
}
if (i < argc) {
ss = to_str(mrb, ARGV[arg_i++]);
*ps = mrb_string_value_cstr(mrb, &ss);
i++;
}
}
break;
case 'a':
{
mrb_value aa;
struct RArray *a;
mrb_value **pb;
mrb_int *pl;
pb = va_arg(ap, mrb_value**);
pl = va_arg(ap, mrb_int*);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*pb = 0;
*pl = 0;
i++; arg_i++;
break;
}
}
if (i < argc) {
aa = to_ary(mrb, ARGV[arg_i++]);
a = mrb_ary_ptr(aa);
*pb = ARY_PTR(a);
*pl = ARY_LEN(a);
i++;
}
}
break;
case 'I':
{
void* *p;
mrb_value ss;
p = va_arg(ap, void**);
if (i < argc) {
ss = ARGV[arg_i];
if (mrb_type(ss) != MRB_TT_ISTRUCT)
{
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not inline struct", ss);
}
*p = mrb_istruct_ptr(ss);
arg_i++;
i++;
}
}
break;
#ifndef MRB_WITHOUT_FLOAT
case 'f':
{
mrb_float *p;
p = va_arg(ap, mrb_float*);
if (i < argc) {
*p = mrb_to_flo(mrb, ARGV[arg_i]);
arg_i++;
i++;
}
}
break;
#endif
case 'i':
{
mrb_int *p;
p = va_arg(ap, mrb_int*);
if (i < argc) {
switch (mrb_type(ARGV[arg_i])) {
case MRB_TT_FIXNUM:
*p = mrb_fixnum(ARGV[arg_i]);
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
{
mrb_float f = mrb_float(ARGV[arg_i]);
if (!FIXABLE_FLOAT(f)) {
mrb_raise(mrb, E_RANGE_ERROR, "float too big for int");
}
*p = (mrb_int)f;
}
break;
#endif
case MRB_TT_STRING:
mrb_raise(mrb, E_TYPE_ERROR, "no implicit conversion of String into Integer");
break;
default:
*p = mrb_fixnum(mrb_Integer(mrb, ARGV[arg_i]));
break;
}
arg_i++;
i++;
}
}
break;
case 'b':
{
mrb_bool *boolp = va_arg(ap, mrb_bool*);
if (i < argc) {
mrb_value b = ARGV[arg_i++];
*boolp = mrb_test(b);
i++;
}
}
break;
case 'n':
{
mrb_sym *symp;
symp = va_arg(ap, mrb_sym*);
if (i < argc) {
mrb_value ss;
ss = ARGV[arg_i++];
*symp = to_sym(mrb, ss);
i++;
}
}
break;
case 'd':
{
void** datap;
struct mrb_data_type const* type;
datap = va_arg(ap, void**);
type = va_arg(ap, struct mrb_data_type const*);
if (*format == '!') {
format++;
if (i < argc && mrb_nil_p(ARGV[arg_i])) {
*datap = 0;
i++; arg_i++;
break;
}
}
if (i < argc) {
*datap = mrb_data_get_ptr(mrb, ARGV[arg_i++], type);
++i;
}
}
break;
case '&':
{
mrb_value *p, *bp;
p = va_arg(ap, mrb_value*);
if (mrb->c->ci->argc < 0) {
bp = mrb->c->stack + 2;
}
else {
bp = mrb->c->stack + mrb->c->ci->argc + 1;
}
if (*format == '!') {
format ++;
if (mrb_nil_p(*bp)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
}
*p = *bp;
}
break;
case '|':
if (opt_skip && i == argc) return argc;
opt = TRUE;
break;
case '?':
{
mrb_bool *p;
p = va_arg(ap, mrb_bool*);
*p = given;
}
break;
case '*':
{
mrb_value **var;
mrb_int *pl;
mrb_bool nocopy = array_argv ? TRUE : FALSE;
if (*format == '!') {
format++;
nocopy = TRUE;
}
var = va_arg(ap, mrb_value**);
pl = va_arg(ap, mrb_int*);
if (argc > i) {
*pl = argc-i;
if (*pl > 0) {
if (nocopy) {
*var = ARGV+arg_i;
}
else {
mrb_value args = mrb_ary_new_from_values(mrb, *pl, ARGV+arg_i);
RARRAY(args)->c = NULL;
*var = RARRAY_PTR(args);
}
}
i = argc;
arg_i += *pl;
}
else {
*pl = 0;
*var = NULL;
}
}
break;
default:
mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid argument specifier %S", mrb_str_new(mrb, &c, 1));
break;
}
}
#undef ARGV
if (!c && argc > i) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments");
}
va_end(ap);
return i;
}
static struct RClass*
boot_defclass(mrb_state *mrb, struct RClass *super)
{
struct RClass *c;
c = (struct RClass*)mrb_obj_alloc(mrb, MRB_TT_CLASS, mrb->class_class);
if (super) {
c->super = super;
mrb_field_write_barrier(mrb, (struct RBasic*)c, (struct RBasic*)super);
}
else {
c->super = mrb->object_class;
}
c->mt = kh_init(mt, mrb);
return c;
}
static void
boot_initmod(mrb_state *mrb, struct RClass *mod)
{
if (!mod->mt) {
mod->mt = kh_init(mt, mrb);
}
}
static struct RClass*
include_class_new(mrb_state *mrb, struct RClass *m, struct RClass *super)
{
struct RClass *ic = (struct RClass*)mrb_obj_alloc(mrb, MRB_TT_ICLASS, mrb->class_class);
if (m->tt == MRB_TT_ICLASS) {
m = m->c;
}
MRB_CLASS_ORIGIN(m);
ic->iv = m->iv;
ic->mt = m->mt;
ic->super = super;
if (m->tt == MRB_TT_ICLASS) {
ic->c = m->c;
}
else {
ic->c = m;
}
return ic;
}
static int
include_module_at(mrb_state *mrb, struct RClass *c, struct RClass *ins_pos, struct RClass *m, int search_super)
{
struct RClass *p, *ic;
void *klass_mt = find_origin(c)->mt;
while (m) {
int superclass_seen = 0;
if (m->flags & MRB_FLAG_IS_PREPENDED)
goto skip;
if (klass_mt && klass_mt == m->mt)
return -1;
p = c->super;
while (p) {
if (p->tt == MRB_TT_ICLASS) {
if (p->mt == m->mt) {
if (!superclass_seen) {
ins_pos = p; /* move insert point */
}
goto skip;
}
} else if (p->tt == MRB_TT_CLASS) {
if (!search_super) break;
superclass_seen = 1;
}
p = p->super;
}
ic = include_class_new(mrb, m, ins_pos->super);
m->flags |= MRB_FLAG_IS_INHERITED;
ins_pos->super = ic;
mrb_field_write_barrier(mrb, (struct RBasic*)ins_pos, (struct RBasic*)ic);
mc_clear_by_class(mrb, ins_pos);
ins_pos = ic;
skip:
m = m->super;
}
mc_clear_all(mrb);
return 0;
}
MRB_API void
mrb_include_module(mrb_state *mrb, struct RClass *c, struct RClass *m)
{
int changed = include_module_at(mrb, c, find_origin(c), m, 1);
if (changed < 0) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "cyclic include detected");
}
}
MRB_API void
mrb_prepend_module(mrb_state *mrb, struct RClass *c, struct RClass *m)
{
struct RClass *origin;
int changed = 0;
if (!(c->flags & MRB_FLAG_IS_PREPENDED)) {
origin = (struct RClass*)mrb_obj_alloc(mrb, MRB_TT_ICLASS, c);
origin->flags |= MRB_FLAG_IS_ORIGIN | MRB_FLAG_IS_INHERITED;
origin->super = c->super;
c->super = origin;
origin->mt = c->mt;
c->mt = kh_init(mt, mrb);
mrb_field_write_barrier(mrb, (struct RBasic*)c, (struct RBasic*)origin);
c->flags |= MRB_FLAG_IS_PREPENDED;
}
changed = include_module_at(mrb, c, c, m, 0);
if (changed < 0) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "cyclic prepend detected");
}
}
static mrb_value
mrb_mod_prepend_features(mrb_state *mrb, mrb_value mod)
{
mrb_value klass;
mrb_check_type(mrb, mod, MRB_TT_MODULE);
mrb_get_args(mrb, "C", &klass);
mrb_prepend_module(mrb, mrb_class_ptr(klass), mrb_class_ptr(mod));
return mod;
}
static mrb_value
mrb_mod_append_features(mrb_state *mrb, mrb_value mod)
{
mrb_value klass;
mrb_check_type(mrb, mod, MRB_TT_MODULE);
mrb_get_args(mrb, "C", &klass);
mrb_include_module(mrb, mrb_class_ptr(klass), mrb_class_ptr(mod));
return mod;
}
/* 15.2.2.4.28 */
/*
* call-seq:
* mod.include?(module) -> true or false
*
* Returns <code>true</code> if <i>module</i> is included in
* <i>mod</i> or one of <i>mod</i>'s ancestors.
*
* module A
* end
* class B
* include A
* end
* class C < B
* end
* B.include?(A) #=> true
* C.include?(A) #=> true
* A.include?(A) #=> false
*/
static mrb_value
mrb_mod_include_p(mrb_state *mrb, mrb_value mod)
{
mrb_value mod2;
struct RClass *c = mrb_class_ptr(mod);
mrb_get_args(mrb, "C", &mod2);
mrb_check_type(mrb, mod2, MRB_TT_MODULE);
while (c) {
if (c->tt == MRB_TT_ICLASS) {
if (c->c == mrb_class_ptr(mod2)) return mrb_true_value();
}
c = c->super;
}
return mrb_false_value();
}
static mrb_value
mrb_mod_ancestors(mrb_state *mrb, mrb_value self)
{
mrb_value result;
struct RClass *c = mrb_class_ptr(self);
result = mrb_ary_new(mrb);
while (c) {
if (c->tt == MRB_TT_ICLASS) {
mrb_ary_push(mrb, result, mrb_obj_value(c->c));
}
else if (!(c->flags & MRB_FLAG_IS_PREPENDED)) {
mrb_ary_push(mrb, result, mrb_obj_value(c));
}
c = c->super;
}
return result;
}
static mrb_value
mrb_mod_extend_object(mrb_state *mrb, mrb_value mod)
{
mrb_value obj;
mrb_check_type(mrb, mod, MRB_TT_MODULE);
mrb_get_args(mrb, "o", &obj);
mrb_include_module(mrb, mrb_class_ptr(mrb_singleton_class(mrb, obj)), mrb_class_ptr(mod));
return mod;
}
static mrb_value
mrb_mod_included_modules(mrb_state *mrb, mrb_value self)
{
mrb_value result;
struct RClass *c = mrb_class_ptr(self);
struct RClass *origin = c;
MRB_CLASS_ORIGIN(origin);
result = mrb_ary_new(mrb);
while (c) {
if (c != origin && c->tt == MRB_TT_ICLASS) {
if (c->c->tt == MRB_TT_MODULE) {
mrb_ary_push(mrb, result, mrb_obj_value(c->c));
}
}
c = c->super;
}
return result;
}
static mrb_value
mrb_mod_initialize(mrb_state *mrb, mrb_value mod)
{
mrb_value b;
struct RClass *m = mrb_class_ptr(mod);
boot_initmod(mrb, m); /* bootstrap a newly initialized module */
mrb_get_args(mrb, "|&", &b);
if (!mrb_nil_p(b)) {
mrb_yield_with_class(mrb, b, 1, &mod, mod, m);
}
return mod;
}
mrb_value mrb_class_instance_method_list(mrb_state*, mrb_bool, struct RClass*, int);
/* 15.2.2.4.33 */
/*
* call-seq:
* mod.instance_methods(include_super=true) -> array
*
* Returns an array containing the names of the public and protected instance
* methods in the receiver. For a module, these are the public and protected methods;
* for a class, they are the instance (not singleton) methods. With no
* argument, or with an argument that is <code>false</code>, the
* instance methods in <i>mod</i> are returned, otherwise the methods
* in <i>mod</i> and <i>mod</i>'s superclasses are returned.
*
* module A
* def method1() end
* end
* class B
* def method2() end
* end
* class C < B
* def method3() end
* end
*
* A.instance_methods #=> [:method1]
* B.instance_methods(false) #=> [:method2]
* C.instance_methods(false) #=> [:method3]
* C.instance_methods(true).length #=> 43
*/
static mrb_value
mrb_mod_instance_methods(mrb_state *mrb, mrb_value mod)
{
struct RClass *c = mrb_class_ptr(mod);
mrb_bool recur = TRUE;
mrb_get_args(mrb, "|b", &recur);
return mrb_class_instance_method_list(mrb, recur, c, 0);
}
/* implementation of module_eval/class_eval */
mrb_value mrb_mod_module_eval(mrb_state*, mrb_value);
static mrb_value
mrb_mod_dummy_visibility(mrb_state *mrb, mrb_value mod)
{
return mod;
}
MRB_API mrb_value
mrb_singleton_class(mrb_state *mrb, mrb_value v)
{
struct RBasic *obj;
switch (mrb_type(v)) {
case MRB_TT_FALSE:
if (mrb_nil_p(v))
return mrb_obj_value(mrb->nil_class);
return mrb_obj_value(mrb->false_class);
case MRB_TT_TRUE:
return mrb_obj_value(mrb->true_class);
case MRB_TT_CPTR:
return mrb_obj_value(mrb->object_class);
case MRB_TT_SYMBOL:
case MRB_TT_FIXNUM:
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#endif
mrb_raise(mrb, E_TYPE_ERROR, "can't define singleton");
return mrb_nil_value(); /* not reached */
default:
break;
}
obj = mrb_basic_ptr(v);
prepare_singleton_class(mrb, obj);
return mrb_obj_value(obj->c);
}
MRB_API void
mrb_define_singleton_method(mrb_state *mrb, struct RObject *o, const char *name, mrb_func_t func, mrb_aspec aspec)
{
prepare_singleton_class(mrb, (struct RBasic*)o);
mrb_define_method_id(mrb, o->c, mrb_intern_cstr(mrb, name), func, aspec);
}
MRB_API void
mrb_define_class_method(mrb_state *mrb, struct RClass *c, const char *name, mrb_func_t func, mrb_aspec aspec)
{
mrb_define_singleton_method(mrb, (struct RObject*)c, name, func, aspec);
}
MRB_API void
mrb_define_module_function(mrb_state *mrb, struct RClass *c, const char *name, mrb_func_t func, mrb_aspec aspec)
{
mrb_define_class_method(mrb, c, name, func, aspec);
mrb_define_method(mrb, c, name, func, aspec);
}
#ifdef MRB_METHOD_CACHE
static void
mc_clear_all(mrb_state *mrb)
{
struct mrb_cache_entry *mc = mrb->cache;
int i;
for (i=0; i<MRB_METHOD_CACHE_SIZE; i++) {
mc[i].c = 0;
}
}
static void
mc_clear_by_class(mrb_state *mrb, struct RClass *c)
{
struct mrb_cache_entry *mc = mrb->cache;
int i;
if (c->flags & MRB_FLAG_IS_INHERITED) {
mc_clear_all(mrb);
c->flags &= ~MRB_FLAG_IS_INHERITED;
return;
}
for (i=0; i<MRB_METHOD_CACHE_SIZE; i++) {
if (mc[i].c == c) mc[i].c = 0;
}
}
static void
mc_clear_by_id(mrb_state *mrb, struct RClass *c, mrb_sym mid)
{
struct mrb_cache_entry *mc = mrb->cache;
int i;
if (c->flags & MRB_FLAG_IS_INHERITED) {
mc_clear_all(mrb);
c->flags &= ~MRB_FLAG_IS_INHERITED;
return;
}
for (i=0; i<MRB_METHOD_CACHE_SIZE; i++) {
if (mc[i].c == c || mc[i].mid == mid)
mc[i].c = 0;
}
}
#endif
MRB_API mrb_method_t
mrb_method_search_vm(mrb_state *mrb, struct RClass **cp, mrb_sym mid)
{
khiter_t k;
mrb_method_t m;
struct RClass *c = *cp;
#ifdef MRB_METHOD_CACHE
struct RClass *oc = c;
int h = kh_int_hash_func(mrb, ((intptr_t)oc) ^ mid) & (MRB_METHOD_CACHE_SIZE-1);
struct mrb_cache_entry *mc = &mrb->cache[h];
if (mc->c == c && mc->mid == mid) {
*cp = mc->c0;
return mc->m;
}
#endif
while (c) {
khash_t(mt) *h = c->mt;
if (h) {
k = kh_get(mt, mrb, h, mid);
if (k != kh_end(h)) {
m = kh_value(h, k);
if (MRB_METHOD_UNDEF_P(m)) break;
*cp = c;
#ifdef MRB_METHOD_CACHE
mc->c = oc;
mc->c0 = c;
mc->mid = mid;
mc->m = m;
#endif
return m;
}
}
c = c->super;
}
MRB_METHOD_FROM_PROC(m, NULL);
return m; /* no method */
}
MRB_API mrb_method_t
mrb_method_search(mrb_state *mrb, struct RClass* c, mrb_sym mid)
{
mrb_method_t m;
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value inspect = mrb_funcall(mrb, mrb_obj_value(c), "inspect", 0);
if (mrb_string_p(inspect) && RSTRING_LEN(inspect) > 64) {
inspect = mrb_any_to_s(mrb, mrb_obj_value(c));
}
mrb_name_error(mrb, mid, "undefined method '%S' for class %S",
mrb_sym2str(mrb, mid), inspect);
}
return m;
}
static mrb_value
attr_reader(mrb_state *mrb, mrb_value obj)
{
mrb_value name = mrb_proc_cfunc_env_get(mrb, 0);
return mrb_iv_get(mrb, obj, to_sym(mrb, name));
}
static mrb_value
mrb_mod_attr_reader(mrb_state *mrb, mrb_value mod)
{
struct RClass *c = mrb_class_ptr(mod);
mrb_value *argv;
mrb_int argc, i;
int ai;
mrb_get_args(mrb, "*", &argv, &argc);
ai = mrb_gc_arena_save(mrb);
for (i=0; i<argc; i++) {
mrb_value name, str;
mrb_sym method, sym;
struct RProc *p;
mrb_method_t m;
method = to_sym(mrb, argv[i]);
name = mrb_sym2str(mrb, method);
str = mrb_str_new_capa(mrb, RSTRING_LEN(name)+1);
mrb_str_cat_lit(mrb, str, "@");
mrb_str_cat_str(mrb, str, name);
sym = mrb_intern_str(mrb, str);
mrb_iv_check(mrb, sym);
name = mrb_symbol_value(sym);
p = mrb_proc_new_cfunc_with_env(mrb, attr_reader, 1, &name);
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, c, method, m);
mrb_gc_arena_restore(mrb, ai);
}
return mrb_nil_value();
}
static mrb_value
attr_writer(mrb_state *mrb, mrb_value obj)
{
mrb_value name = mrb_proc_cfunc_env_get(mrb, 0);
mrb_value val;
mrb_get_args(mrb, "o", &val);
mrb_iv_set(mrb, obj, to_sym(mrb, name), val);
return val;
}
static mrb_value
mrb_mod_attr_writer(mrb_state *mrb, mrb_value mod)
{
struct RClass *c = mrb_class_ptr(mod);
mrb_value *argv;
mrb_int argc, i;
int ai;
mrb_get_args(mrb, "*", &argv, &argc);
ai = mrb_gc_arena_save(mrb);
for (i=0; i<argc; i++) {
mrb_value name, str, attr;
mrb_sym method, sym;
struct RProc *p;
mrb_method_t m;
method = to_sym(mrb, argv[i]);
/* prepare iv name (@name) */
name = mrb_sym2str(mrb, method);
str = mrb_str_new_capa(mrb, RSTRING_LEN(name)+1);
mrb_str_cat_lit(mrb, str, "@");
mrb_str_cat_str(mrb, str, name);
sym = mrb_intern_str(mrb, str);
mrb_iv_check(mrb, sym);
attr = mrb_symbol_value(sym);
/* prepare method name (name=) */
str = mrb_str_new_capa(mrb, RSTRING_LEN(str));
mrb_str_cat_str(mrb, str, name);
mrb_str_cat_lit(mrb, str, "=");
method = mrb_intern_str(mrb, str);
p = mrb_proc_new_cfunc_with_env(mrb, attr_writer, 1, &attr);
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, c, method, m);
mrb_gc_arena_restore(mrb, ai);
}
return mrb_nil_value();
}
static mrb_value
mrb_instance_alloc(mrb_state *mrb, mrb_value cv)
{
struct RClass *c = mrb_class_ptr(cv);
struct RObject *o;
enum mrb_vtype ttype = MRB_INSTANCE_TT(c);
if (c->tt == MRB_TT_SCLASS)
mrb_raise(mrb, E_TYPE_ERROR, "can't create instance of singleton class");
if (ttype == 0) ttype = MRB_TT_OBJECT;
if (ttype <= MRB_TT_CPTR) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't create instance of %S", cv);
}
o = (struct RObject*)mrb_obj_alloc(mrb, ttype, c);
return mrb_obj_value(o);
}
/*
* call-seq:
* class.new(args, ...) -> obj
*
* Creates a new object of <i>class</i>'s class, then
* invokes that object's <code>initialize</code> method,
* passing it <i>args</i>. This is the method that ends
* up getting called whenever an object is constructed using
* `.new`.
*
*/
MRB_API mrb_value
mrb_instance_new(mrb_state *mrb, mrb_value cv)
{
mrb_value obj, blk;
mrb_value *argv;
mrb_int argc;
mrb_sym init;
mrb_method_t m;
mrb_get_args(mrb, "*&", &argv, &argc, &blk);
obj = mrb_instance_alloc(mrb, cv);
init = mrb_intern_lit(mrb, "initialize");
m = mrb_method_search(mrb, mrb_class(mrb, obj), init);
if (MRB_METHOD_CFUNC_P(m)) {
mrb_func_t f = MRB_METHOD_CFUNC(m);
if (f != mrb_bob_init) {
f(mrb, obj);
}
}
else {
mrb_funcall_with_block(mrb, obj, init, argc, argv, blk);
}
return obj;
}
MRB_API mrb_value
mrb_obj_new(mrb_state *mrb, struct RClass *c, mrb_int argc, const mrb_value *argv)
{
mrb_value obj;
mrb_sym mid;
obj = mrb_instance_alloc(mrb, mrb_obj_value(c));
mid = mrb_intern_lit(mrb, "initialize");
if (!mrb_func_basic_p(mrb, obj, mid, mrb_bob_init)) {
mrb_funcall_argv(mrb, obj, mid, argc, argv);
}
return obj;
}
static mrb_value
mrb_class_initialize(mrb_state *mrb, mrb_value c)
{
mrb_value a, b;
mrb_get_args(mrb, "|C&", &a, &b);
if (!mrb_nil_p(b)) {
mrb_yield_with_class(mrb, b, 1, &c, c, mrb_class_ptr(c));
}
return c;
}
static mrb_value
mrb_class_new_class(mrb_state *mrb, mrb_value cv)
{
mrb_int n;
mrb_value super, blk;
mrb_value new_class;
mrb_sym mid;
n = mrb_get_args(mrb, "|C&", &super, &blk);
if (n == 0) {
super = mrb_obj_value(mrb->object_class);
}
new_class = mrb_obj_value(mrb_class_new(mrb, mrb_class_ptr(super)));
mid = mrb_intern_lit(mrb, "initialize");
if (!mrb_func_basic_p(mrb, new_class, mid, mrb_bob_init)) {
mrb_funcall_with_block(mrb, new_class, mid, n, &super, blk);
}
mrb_class_inherited(mrb, mrb_class_ptr(super), mrb_class_ptr(new_class));
return new_class;
}
static mrb_value
mrb_class_superclass(mrb_state *mrb, mrb_value klass)
{
struct RClass *c;
c = mrb_class_ptr(klass);
c = find_origin(c)->super;
while (c && c->tt == MRB_TT_ICLASS) {
c = find_origin(c)->super;
}
if (!c) return mrb_nil_value();
return mrb_obj_value(c);
}
static mrb_value
mrb_bob_init(mrb_state *mrb, mrb_value cv)
{
return mrb_nil_value();
}
static mrb_value
mrb_bob_not(mrb_state *mrb, mrb_value cv)
{
return mrb_bool_value(!mrb_test(cv));
}
/* 15.3.1.3.1 */
/* 15.3.1.3.10 */
/* 15.3.1.3.11 */
/*
* call-seq:
* obj == other -> true or false
* obj.equal?(other) -> true or false
* obj.eql?(other) -> true or false
*
* Equality---At the <code>Object</code> level, <code>==</code> returns
* <code>true</code> only if <i>obj</i> and <i>other</i> are the
* same object. Typically, this method is overridden in descendant
* classes to provide class-specific meaning.
*
* Unlike <code>==</code>, the <code>equal?</code> method should never be
* overridden by subclasses: it is used to determine object identity
* (that is, <code>a.equal?(b)</code> iff <code>a</code> is the same
* object as <code>b</code>).
*
* The <code>eql?</code> method returns <code>true</code> if
* <i>obj</i> and <i>anObject</i> have the same value. Used by
* <code>Hash</code> to test members for equality. For objects of
* class <code>Object</code>, <code>eql?</code> is synonymous with
* <code>==</code>. Subclasses normally continue this tradition, but
* there are exceptions. <code>Numeric</code> types, for example,
* perform type conversion across <code>==</code>, but not across
* <code>eql?</code>, so:
*
* 1 == 1.0 #=> true
* 1.eql? 1.0 #=> false
*/
mrb_value
mrb_obj_equal_m(mrb_state *mrb, mrb_value self)
{
mrb_value arg;
mrb_get_args(mrb, "o", &arg);
return mrb_bool_value(mrb_obj_equal(mrb, self, arg));
}
static mrb_value
mrb_obj_not_equal_m(mrb_state *mrb, mrb_value self)
{
mrb_value arg;
mrb_get_args(mrb, "o", &arg);
return mrb_bool_value(!mrb_equal(mrb, self, arg));
}
MRB_API mrb_bool
mrb_obj_respond_to(mrb_state *mrb, struct RClass* c, mrb_sym mid)
{
mrb_method_t m;
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
return FALSE;
}
return TRUE;
}
MRB_API mrb_bool
mrb_respond_to(mrb_state *mrb, mrb_value obj, mrb_sym mid)
{
return mrb_obj_respond_to(mrb, mrb_class(mrb, obj), mid);
}
MRB_API mrb_value
mrb_class_path(mrb_state *mrb, struct RClass *c)
{
mrb_value path;
mrb_sym nsym = mrb_intern_lit(mrb, "__classname__");
path = mrb_obj_iv_get(mrb, (struct RObject*)c, nsym);
if (mrb_nil_p(path)) {
/* no name (yet) */
return mrb_class_find_path(mrb, c);
}
else if (mrb_symbol_p(path)) {
/* toplevel class/module */
const char *str;
mrb_int len;
str = mrb_sym2name_len(mrb, mrb_symbol(path), &len);
return mrb_str_new(mrb, str, len);
}
return mrb_str_dup(mrb, path);
}
MRB_API struct RClass*
mrb_class_real(struct RClass* cl)
{
if (cl == 0) return NULL;
while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {
cl = cl->super;
if (cl == 0) return NULL;
}
return cl;
}
MRB_API const char*
mrb_class_name(mrb_state *mrb, struct RClass* c)
{
mrb_value path = mrb_class_path(mrb, c);
if (mrb_nil_p(path)) {
path = mrb_str_new_lit(mrb, "#<Class:");
mrb_str_concat(mrb, path, mrb_ptr_to_str(mrb, c));
mrb_str_cat_lit(mrb, path, ">");
}
return RSTRING_PTR(path);
}
MRB_API const char*
mrb_obj_classname(mrb_state *mrb, mrb_value obj)
{
return mrb_class_name(mrb, mrb_obj_class(mrb, obj));
}
/*!
* Ensures a class can be derived from super.
*
* \param super a reference to an object.
* \exception TypeError if \a super is not a Class or \a super is a singleton class.
*/
static void
mrb_check_inheritable(mrb_state *mrb, struct RClass *super)
{
if (super->tt != MRB_TT_CLASS) {
mrb_raisef(mrb, E_TYPE_ERROR, "superclass must be a Class (%S given)", mrb_obj_value(super));
}
if (super->tt == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't make subclass of singleton class");
}
if (super == mrb->class_class) {
mrb_raise(mrb, E_TYPE_ERROR, "can't make subclass of Class");
}
}
/*!
* Creates a new class.
* \param super a class from which the new class derives.
* \exception TypeError \a super is not inheritable.
* \exception TypeError \a super is the Class class.
*/
MRB_API struct RClass*
mrb_class_new(mrb_state *mrb, struct RClass *super)
{
struct RClass *c;
if (super) {
mrb_check_inheritable(mrb, super);
}
c = boot_defclass(mrb, super);
if (super) {
MRB_SET_INSTANCE_TT(c, MRB_INSTANCE_TT(super));
}
make_metaclass(mrb, c);
return c;
}
/*!
* Creates a new module.
*/
MRB_API struct RClass*
mrb_module_new(mrb_state *mrb)
{
struct RClass *m = (struct RClass*)mrb_obj_alloc(mrb, MRB_TT_MODULE, mrb->module_class);
boot_initmod(mrb, m);
return m;
}
/*
* call-seq:
* obj.class => class
*
* Returns the class of <i>obj</i>, now preferred over
* <code>Object#type</code>, as an object's type in Ruby is only
* loosely tied to that object's class. This method must always be
* called with an explicit receiver, as <code>class</code> is also a
* reserved word in Ruby.
*
* 1.class #=> Fixnum
* self.class #=> Object
*/
MRB_API struct RClass*
mrb_obj_class(mrb_state *mrb, mrb_value obj)
{
return mrb_class_real(mrb_class(mrb, obj));
}
MRB_API void
mrb_alias_method(mrb_state *mrb, struct RClass *c, mrb_sym a, mrb_sym b)
{
mrb_method_t m = mrb_method_search(mrb, c, b);
mrb_define_method_raw(mrb, c, a, m);
}
/*!
* Defines an alias of a method.
* \param klass the class which the original method belongs to
* \param name1 a new name for the method
* \param name2 the original name of the method
*/
MRB_API void
mrb_define_alias(mrb_state *mrb, struct RClass *klass, const char *name1, const char *name2)
{
mrb_alias_method(mrb, klass, mrb_intern_cstr(mrb, name1), mrb_intern_cstr(mrb, name2));
}
/*
* call-seq:
* mod.to_s -> string
*
* Return a string representing this module or class. For basic
* classes and modules, this is the name. For singletons, we
* show information on the thing we're attached to as well.
*/
static mrb_value
mrb_mod_to_s(mrb_state *mrb, mrb_value klass)
{
mrb_value str;
if (mrb_type(klass) == MRB_TT_SCLASS) {
mrb_value v = mrb_iv_get(mrb, klass, mrb_intern_lit(mrb, "__attached__"));
str = mrb_str_new_lit(mrb, "#<Class:");
if (class_ptr_p(v)) {
mrb_str_cat_str(mrb, str, mrb_inspect(mrb, v));
}
else {
mrb_str_cat_str(mrb, str, mrb_any_to_s(mrb, v));
}
return mrb_str_cat_lit(mrb, str, ">");
}
else {
struct RClass *c;
mrb_value path;
str = mrb_str_new_capa(mrb, 32);
c = mrb_class_ptr(klass);
path = mrb_class_path(mrb, c);
if (mrb_nil_p(path)) {
switch (mrb_type(klass)) {
case MRB_TT_CLASS:
mrb_str_cat_lit(mrb, str, "#<Class:");
break;
case MRB_TT_MODULE:
mrb_str_cat_lit(mrb, str, "#<Module:");
break;
default:
/* Shouldn't be happened? */
mrb_str_cat_lit(mrb, str, "#<??????:");
break;
}
mrb_str_concat(mrb, str, mrb_ptr_to_str(mrb, c));
return mrb_str_cat_lit(mrb, str, ">");
}
else {
return path;
}
}
}
static mrb_value
mrb_mod_alias(mrb_state *mrb, mrb_value mod)
{
struct RClass *c = mrb_class_ptr(mod);
mrb_sym new_name, old_name;
mrb_get_args(mrb, "nn", &new_name, &old_name);
mrb_alias_method(mrb, c, new_name, old_name);
return mrb_nil_value();
}
static void
undef_method(mrb_state *mrb, struct RClass *c, mrb_sym a)
{
if (!mrb_obj_respond_to(mrb, c, a)) {
mrb_name_error(mrb, a, "undefined method '%S' for class '%S'", mrb_sym2str(mrb, a), mrb_obj_value(c));
}
else {
mrb_method_t m;
MRB_METHOD_FROM_PROC(m, NULL);
mrb_define_method_raw(mrb, c, a, m);
}
}
MRB_API void
mrb_undef_method(mrb_state *mrb, struct RClass *c, const char *name)
{
undef_method(mrb, c, mrb_intern_cstr(mrb, name));
}
MRB_API void
mrb_undef_class_method(mrb_state *mrb, struct RClass *c, const char *name)
{
mrb_undef_method(mrb, mrb_class_ptr(mrb_singleton_class(mrb, mrb_obj_value(c))), name);
}
static mrb_value
mrb_mod_undef(mrb_state *mrb, mrb_value mod)
{
struct RClass *c = mrb_class_ptr(mod);
mrb_int argc;
mrb_value *argv;
mrb_get_args(mrb, "*", &argv, &argc);
while (argc--) {
undef_method(mrb, c, to_sym(mrb, *argv));
argv++;
}
return mrb_nil_value();
}
static mrb_value
mod_define_method(mrb_state *mrb, mrb_value self)
{
struct RClass *c = mrb_class_ptr(self);
struct RProc *p;
mrb_method_t m;
mrb_sym mid;
mrb_value proc = mrb_undef_value();
mrb_value blk;
mrb_get_args(mrb, "n|o&", &mid, &proc, &blk);
switch (mrb_type(proc)) {
case MRB_TT_PROC:
blk = proc;
break;
case MRB_TT_UNDEF:
/* ignored */
break;
default:
mrb_raisef(mrb, E_TYPE_ERROR, "wrong argument type %S (expected Proc)", mrb_obj_value(mrb_obj_class(mrb, proc)));
break;
}
if (mrb_nil_p(blk)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
p = (struct RProc*)mrb_obj_alloc(mrb, MRB_TT_PROC, mrb->proc_class);
mrb_proc_copy(p, mrb_proc_ptr(blk));
p->flags |= MRB_PROC_STRICT;
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, c, mid, m);
return mrb_symbol_value(mid);
}
static mrb_value
top_define_method(mrb_state *mrb, mrb_value self)
{
return mod_define_method(mrb, mrb_obj_value(mrb->object_class));
}
static void
check_cv_name_str(mrb_state *mrb, mrb_value str)
{
const char *s = RSTRING_PTR(str);
mrb_int len = RSTRING_LEN(str);
if (len < 3 || !(s[0] == '@' && s[1] == '@')) {
mrb_name_error(mrb, mrb_intern_str(mrb, str), "'%S' is not allowed as a class variable name", str);
}
}
static void
check_cv_name_sym(mrb_state *mrb, mrb_sym id)
{
check_cv_name_str(mrb, mrb_sym2str(mrb, id));
}
/* 15.2.2.4.16 */
/*
* call-seq:
* obj.class_variable_defined?(symbol) -> true or false
*
* Returns <code>true</code> if the given class variable is defined
* in <i>obj</i>.
*
* class Fred
* @@foo = 99
* end
* Fred.class_variable_defined?(:@@foo) #=> true
* Fred.class_variable_defined?(:@@bar) #=> false
*/
static mrb_value
mrb_mod_cvar_defined(mrb_state *mrb, mrb_value mod)
{
mrb_sym id;
mrb_get_args(mrb, "n", &id);
check_cv_name_sym(mrb, id);
return mrb_bool_value(mrb_cv_defined(mrb, mod, id));
}
/* 15.2.2.4.17 */
/*
* call-seq:
* mod.class_variable_get(symbol) -> obj
*
* Returns the value of the given class variable (or throws a
* <code>NameError</code> exception). The <code>@@</code> part of the
* variable name should be included for regular class variables
*
* class Fred
* @@foo = 99
* end
* Fred.class_variable_get(:@@foo) #=> 99
*/
static mrb_value
mrb_mod_cvar_get(mrb_state *mrb, mrb_value mod)
{
mrb_sym id;
mrb_get_args(mrb, "n", &id);
check_cv_name_sym(mrb, id);
return mrb_cv_get(mrb, mod, id);
}
/* 15.2.2.4.18 */
/*
* call-seq:
* obj.class_variable_set(symbol, obj) -> obj
*
* Sets the class variable names by <i>symbol</i> to
* <i>object</i>.
*
* class Fred
* @@foo = 99
* def foo
* @@foo
* end
* end
* Fred.class_variable_set(:@@foo, 101) #=> 101
* Fred.new.foo #=> 101
*/
static mrb_value
mrb_mod_cvar_set(mrb_state *mrb, mrb_value mod)
{
mrb_value value;
mrb_sym id;
mrb_get_args(mrb, "no", &id, &value);
check_cv_name_sym(mrb, id);
mrb_cv_set(mrb, mod, id, value);
return value;
}
/* 15.2.2.4.39 */
/*
* call-seq:
* remove_class_variable(sym) -> obj
*
* Removes the definition of the <i>sym</i>, returning that
* constant's value.
*
* class Dummy
* @@var = 99
* puts @@var
* p class_variables
* remove_class_variable(:@@var)
* p class_variables
* end
*
* <em>produces:</em>
*
* 99
* [:@@var]
* []
*/
static mrb_value
mrb_mod_remove_cvar(mrb_state *mrb, mrb_value mod)
{
mrb_value val;
mrb_sym id;
mrb_get_args(mrb, "n", &id);
check_cv_name_sym(mrb, id);
val = mrb_iv_remove(mrb, mod, id);
if (!mrb_undef_p(val)) return val;
if (mrb_cv_defined(mrb, mod, id)) {
mrb_name_error(mrb, id, "cannot remove %S for %S",
mrb_sym2str(mrb, id), mod);
}
mrb_name_error(mrb, id, "class variable %S not defined for %S",
mrb_sym2str(mrb, id), mod);
/* not reached */
return mrb_nil_value();
}
/* 15.2.2.4.34 */
/*
* call-seq:
* mod.method_defined?(symbol) -> true or false
*
* Returns +true+ if the named method is defined by
* _mod_ (or its included modules and, if _mod_ is a class,
* its ancestors). Public and protected methods are matched.
*
* module A
* def method1() end
* end
* class B
* def method2() end
* end
* class C < B
* include A
* def method3() end
* end
*
* A.method_defined? :method1 #=> true
* C.method_defined? "method1" #=> true
* C.method_defined? "method2" #=> true
* C.method_defined? "method3" #=> true
* C.method_defined? "method4" #=> false
*/
static mrb_value
mrb_mod_method_defined(mrb_state *mrb, mrb_value mod)
{
mrb_sym id;
mrb_get_args(mrb, "n", &id);
return mrb_bool_value(mrb_obj_respond_to(mrb, mrb_class_ptr(mod), id));
}
static void
remove_method(mrb_state *mrb, mrb_value mod, mrb_sym mid)
{
struct RClass *c = mrb_class_ptr(mod);
khash_t(mt) *h = find_origin(c)->mt;
khiter_t k;
if (h) {
k = kh_get(mt, mrb, h, mid);
if (k != kh_end(h)) {
kh_del(mt, mrb, h, k);
mrb_funcall(mrb, mod, "method_removed", 1, mrb_symbol_value(mid));
return;
}
}
mrb_name_error(mrb, mid, "method '%S' not defined in %S",
mrb_sym2str(mrb, mid), mod);
}
/* 15.2.2.4.41 */
/*
* call-seq:
* remove_method(symbol) -> self
*
* Removes the method identified by _symbol_ from the current
* class. For an example, see <code>Module.undef_method</code>.
*/
static mrb_value
mrb_mod_remove_method(mrb_state *mrb, mrb_value mod)
{
mrb_int argc;
mrb_value *argv;
mrb_get_args(mrb, "*", &argv, &argc);
while (argc--) {
remove_method(mrb, mod, to_sym(mrb, *argv));
argv++;
}
return mod;
}
static void
check_const_name_str(mrb_state *mrb, mrb_value str)
{
if (RSTRING_LEN(str) < 1 || !ISUPPER(*RSTRING_PTR(str))) {
mrb_name_error(mrb, mrb_intern_str(mrb, str), "wrong constant name %S", str);
}
}
static void
check_const_name_sym(mrb_state *mrb, mrb_sym id)
{
check_const_name_str(mrb, mrb_sym2str(mrb, id));
}
static mrb_value
const_defined(mrb_state *mrb, mrb_value mod, mrb_sym id, mrb_bool inherit)
{
if (inherit) {
return mrb_bool_value(mrb_const_defined(mrb, mod, id));
}
return mrb_bool_value(mrb_const_defined_at(mrb, mod, id));
}
static mrb_value
mrb_mod_const_defined(mrb_state *mrb, mrb_value mod)
{
mrb_sym id;
mrb_bool inherit = TRUE;
mrb_get_args(mrb, "n|b", &id, &inherit);
check_const_name_sym(mrb, id);
return const_defined(mrb, mod, id, inherit);
}
static mrb_value
mrb_const_get_sym(mrb_state *mrb, mrb_value mod, mrb_sym id)
{
check_const_name_sym(mrb, id);
return mrb_const_get(mrb, mod, id);
}
static mrb_value
mrb_mod_const_get(mrb_state *mrb, mrb_value mod)
{
mrb_value path;
mrb_sym id;
char *ptr;
mrb_int off, end, len;
mrb_get_args(mrb, "o", &path);
if (mrb_symbol_p(path)) {
/* const get with symbol */
id = mrb_symbol(path);
return mrb_const_get_sym(mrb, mod, id);
}
/* const get with class path string */
path = mrb_string_type(mrb, path);
ptr = RSTRING_PTR(path);
len = RSTRING_LEN(path);
off = 0;
while (off < len) {
end = mrb_str_index_lit(mrb, path, "::", off);
end = (end == -1) ? len : end;
id = mrb_intern(mrb, ptr+off, end-off);
mod = mrb_const_get_sym(mrb, mod, id);
off = (end == len) ? end : end+2;
}
return mod;
}
static mrb_value
mrb_mod_const_set(mrb_state *mrb, mrb_value mod)
{
mrb_sym id;
mrb_value value;
mrb_get_args(mrb, "no", &id, &value);
check_const_name_sym(mrb, id);
mrb_const_set(mrb, mod, id, value);
return value;
}
static mrb_value
mrb_mod_remove_const(mrb_state *mrb, mrb_value mod)
{
mrb_sym id;
mrb_value val;
mrb_get_args(mrb, "n", &id);
check_const_name_sym(mrb, id);
val = mrb_iv_remove(mrb, mod, id);
if (mrb_undef_p(val)) {
mrb_name_error(mrb, id, "constant %S not defined", mrb_sym2str(mrb, id));
}
return val;
}
static mrb_value
mrb_mod_const_missing(mrb_state *mrb, mrb_value mod)
{
mrb_sym sym;
mrb_get_args(mrb, "n", &sym);
if (mrb_class_real(mrb_class_ptr(mod)) != mrb->object_class) {
mrb_name_error(mrb, sym, "uninitialized constant %S::%S",
mod,
mrb_sym2str(mrb, sym));
}
else {
mrb_name_error(mrb, sym, "uninitialized constant %S",
mrb_sym2str(mrb, sym));
}
/* not reached */
return mrb_nil_value();
}
static mrb_value
mrb_mod_s_constants(mrb_state *mrb, mrb_value mod)
{
mrb_raise(mrb, E_NOTIMP_ERROR, "Module.constants not implemented");
return mrb_nil_value(); /* not reached */
}
static mrb_value
mrb_mod_eqq(mrb_state *mrb, mrb_value mod)
{
mrb_value obj;
mrb_bool eqq;
mrb_get_args(mrb, "o", &obj);
eqq = mrb_obj_is_kind_of(mrb, obj, mrb_class_ptr(mod));
return mrb_bool_value(eqq);
}
MRB_API mrb_value
mrb_mod_module_function(mrb_state *mrb, mrb_value mod)
{
mrb_value *argv;
mrb_int argc, i;
mrb_sym mid;
mrb_method_t m;
struct RClass *rclass;
int ai;
mrb_check_type(mrb, mod, MRB_TT_MODULE);
mrb_get_args(mrb, "*", &argv, &argc);
if (argc == 0) {
/* set MODFUNC SCOPE if implemented */
return mod;
}
/* set PRIVATE method visibility if implemented */
/* mrb_mod_dummy_visibility(mrb, mod); */
for (i=0; i<argc; i++) {
mrb_check_type(mrb, argv[i], MRB_TT_SYMBOL);
mid = mrb_symbol(argv[i]);
rclass = mrb_class_ptr(mod);
m = mrb_method_search(mrb, rclass, mid);
prepare_singleton_class(mrb, (struct RBasic*)rclass);
ai = mrb_gc_arena_save(mrb);
mrb_define_method_raw(mrb, rclass->c, mid, m);
mrb_gc_arena_restore(mrb, ai);
}
return mod;
}
/* implementation of __id__ */
mrb_value mrb_obj_id_m(mrb_state *mrb, mrb_value self);
/* implementation of instance_eval */
mrb_value mrb_obj_instance_eval(mrb_state*, mrb_value);
/* implementation of Module.nesting */
mrb_value mrb_mod_s_nesting(mrb_state*, mrb_value);
static mrb_value
inspect_main(mrb_state *mrb, mrb_value mod)
{
return mrb_str_new_lit(mrb, "main");
}
void
mrb_init_class(mrb_state *mrb)
{
struct RClass *bob; /* BasicObject */
struct RClass *obj; /* Object */
struct RClass *mod; /* Module */
struct RClass *cls; /* Class */
/* boot class hierarchy */
bob = boot_defclass(mrb, 0);
obj = boot_defclass(mrb, bob); mrb->object_class = obj;
mod = boot_defclass(mrb, obj); mrb->module_class = mod;/* obj -> mod */
cls = boot_defclass(mrb, mod); mrb->class_class = cls; /* obj -> cls */
/* fix-up loose ends */
bob->c = obj->c = mod->c = cls->c = cls;
make_metaclass(mrb, bob);
make_metaclass(mrb, obj);
make_metaclass(mrb, mod);
make_metaclass(mrb, cls);
/* name basic classes */
mrb_define_const(mrb, bob, "BasicObject", mrb_obj_value(bob));
mrb_define_const(mrb, obj, "BasicObject", mrb_obj_value(bob));
mrb_define_const(mrb, obj, "Object", mrb_obj_value(obj));
mrb_define_const(mrb, obj, "Module", mrb_obj_value(mod));
mrb_define_const(mrb, obj, "Class", mrb_obj_value(cls));
/* name each classes */
mrb_class_name_class(mrb, NULL, bob, mrb_intern_lit(mrb, "BasicObject"));
mrb_class_name_class(mrb, NULL, obj, mrb_intern_lit(mrb, "Object")); /* 15.2.1 */
mrb_class_name_class(mrb, NULL, mod, mrb_intern_lit(mrb, "Module")); /* 15.2.2 */
mrb_class_name_class(mrb, NULL, cls, mrb_intern_lit(mrb, "Class")); /* 15.2.3 */
mrb->proc_class = mrb_define_class(mrb, "Proc", mrb->object_class); /* 15.2.17 */
MRB_SET_INSTANCE_TT(mrb->proc_class, MRB_TT_PROC);
MRB_SET_INSTANCE_TT(cls, MRB_TT_CLASS);
mrb_define_method(mrb, bob, "initialize", mrb_bob_init, MRB_ARGS_NONE());
mrb_define_method(mrb, bob, "!", mrb_bob_not, MRB_ARGS_NONE());
mrb_define_method(mrb, bob, "==", mrb_obj_equal_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.1 */
mrb_define_method(mrb, bob, "!=", mrb_obj_not_equal_m, MRB_ARGS_REQ(1));
mrb_define_method(mrb, bob, "__id__", mrb_obj_id_m, MRB_ARGS_NONE()); /* 15.3.1.3.3 */
mrb_define_method(mrb, bob, "__send__", mrb_f_send, MRB_ARGS_ANY()); /* 15.3.1.3.4 */
mrb_define_method(mrb, bob, "instance_eval", mrb_obj_instance_eval, MRB_ARGS_ANY()); /* 15.3.1.3.18 */
mrb_define_class_method(mrb, cls, "new", mrb_class_new_class, MRB_ARGS_OPT(1));
mrb_define_method(mrb, cls, "superclass", mrb_class_superclass, MRB_ARGS_NONE()); /* 15.2.3.3.4 */
mrb_define_method(mrb, cls, "new", mrb_instance_new, MRB_ARGS_ANY()); /* 15.2.3.3.3 */
mrb_define_method(mrb, cls, "initialize", mrb_class_initialize, MRB_ARGS_OPT(1)); /* 15.2.3.3.1 */
mrb_define_method(mrb, cls, "inherited", mrb_bob_init, MRB_ARGS_REQ(1));
MRB_SET_INSTANCE_TT(mod, MRB_TT_MODULE);
mrb_define_method(mrb, mod, "class_variable_defined?", mrb_mod_cvar_defined, MRB_ARGS_REQ(1)); /* 15.2.2.4.16 */
mrb_define_method(mrb, mod, "class_variable_get", mrb_mod_cvar_get, MRB_ARGS_REQ(1)); /* 15.2.2.4.17 */
mrb_define_method(mrb, mod, "class_variable_set", mrb_mod_cvar_set, MRB_ARGS_REQ(2)); /* 15.2.2.4.18 */
mrb_define_method(mrb, mod, "extend_object", mrb_mod_extend_object, MRB_ARGS_REQ(1)); /* 15.2.2.4.25 */
mrb_define_method(mrb, mod, "extended", mrb_bob_init, MRB_ARGS_REQ(1)); /* 15.2.2.4.26 */
mrb_define_method(mrb, mod, "prepended", mrb_bob_init, MRB_ARGS_REQ(1));
mrb_define_method(mrb, mod, "prepend_features", mrb_mod_prepend_features, MRB_ARGS_REQ(1));
mrb_define_method(mrb, mod, "include?", mrb_mod_include_p, MRB_ARGS_REQ(1)); /* 15.2.2.4.28 */
mrb_define_method(mrb, mod, "append_features", mrb_mod_append_features, MRB_ARGS_REQ(1)); /* 15.2.2.4.10 */
mrb_define_method(mrb, mod, "class_eval", mrb_mod_module_eval, MRB_ARGS_ANY()); /* 15.2.2.4.15 */
mrb_define_method(mrb, mod, "included", mrb_bob_init, MRB_ARGS_REQ(1)); /* 15.2.2.4.29 */
mrb_define_method(mrb, mod, "included_modules", mrb_mod_included_modules, MRB_ARGS_NONE()); /* 15.2.2.4.30 */
mrb_define_method(mrb, mod, "initialize", mrb_mod_initialize, MRB_ARGS_NONE()); /* 15.2.2.4.31 */
mrb_define_method(mrb, mod, "instance_methods", mrb_mod_instance_methods, MRB_ARGS_ANY()); /* 15.2.2.4.33 */
mrb_define_method(mrb, mod, "method_defined?", mrb_mod_method_defined, MRB_ARGS_REQ(1)); /* 15.2.2.4.34 */
mrb_define_method(mrb, mod, "module_eval", mrb_mod_module_eval, MRB_ARGS_ANY()); /* 15.2.2.4.35 */
mrb_define_method(mrb, mod, "module_function", mrb_mod_module_function, MRB_ARGS_ANY());
mrb_define_method(mrb, mod, "private", mrb_mod_dummy_visibility, MRB_ARGS_ANY()); /* 15.2.2.4.36 */
mrb_define_method(mrb, mod, "protected", mrb_mod_dummy_visibility, MRB_ARGS_ANY()); /* 15.2.2.4.37 */
mrb_define_method(mrb, mod, "public", mrb_mod_dummy_visibility, MRB_ARGS_ANY()); /* 15.2.2.4.38 */
mrb_define_method(mrb, mod, "remove_class_variable", mrb_mod_remove_cvar, MRB_ARGS_REQ(1)); /* 15.2.2.4.39 */
mrb_define_method(mrb, mod, "remove_method", mrb_mod_remove_method, MRB_ARGS_ANY()); /* 15.2.2.4.41 */
mrb_define_method(mrb, mod, "method_removed", mrb_bob_init, MRB_ARGS_REQ(1));
mrb_define_method(mrb, mod, "attr_reader", mrb_mod_attr_reader, MRB_ARGS_ANY()); /* 15.2.2.4.13 */
mrb_define_method(mrb, mod, "attr_writer", mrb_mod_attr_writer, MRB_ARGS_ANY()); /* 15.2.2.4.14 */
mrb_define_method(mrb, mod, "to_s", mrb_mod_to_s, MRB_ARGS_NONE());
mrb_define_method(mrb, mod, "inspect", mrb_mod_to_s, MRB_ARGS_NONE());
mrb_define_method(mrb, mod, "alias_method", mrb_mod_alias, MRB_ARGS_ANY()); /* 15.2.2.4.8 */
mrb_define_method(mrb, mod, "ancestors", mrb_mod_ancestors, MRB_ARGS_NONE()); /* 15.2.2.4.9 */
mrb_define_method(mrb, mod, "undef_method", mrb_mod_undef, MRB_ARGS_ANY()); /* 15.2.2.4.41 */
mrb_define_method(mrb, mod, "const_defined?", mrb_mod_const_defined, MRB_ARGS_ARG(1,1)); /* 15.2.2.4.20 */
mrb_define_method(mrb, mod, "const_get", mrb_mod_const_get, MRB_ARGS_REQ(1)); /* 15.2.2.4.21 */
mrb_define_method(mrb, mod, "const_set", mrb_mod_const_set, MRB_ARGS_REQ(2)); /* 15.2.2.4.23 */
mrb_define_method(mrb, mod, "constants", mrb_mod_constants, MRB_ARGS_OPT(1)); /* 15.2.2.4.24 */
mrb_define_method(mrb, mod, "remove_const", mrb_mod_remove_const, MRB_ARGS_REQ(1)); /* 15.2.2.4.40 */
mrb_define_method(mrb, mod, "const_missing", mrb_mod_const_missing, MRB_ARGS_REQ(1));
mrb_define_method(mrb, mod, "define_method", mod_define_method, MRB_ARGS_ARG(1,1));
mrb_define_method(mrb, mod, "class_variables", mrb_mod_class_variables, MRB_ARGS_NONE()); /* 15.2.2.4.19 */
mrb_define_method(mrb, mod, "===", mrb_mod_eqq, MRB_ARGS_REQ(1));
mrb_define_class_method(mrb, mod, "constants", mrb_mod_s_constants, MRB_ARGS_ANY()); /* 15.2.2.3.1 */
mrb_define_class_method(mrb, mod, "nesting", mrb_mod_s_nesting, MRB_ARGS_REQ(0)); /* 15.2.2.3.2 */
mrb_undef_method(mrb, cls, "append_features");
mrb_undef_method(mrb, cls, "extend_object");
mrb->top_self = (struct RObject*)mrb_obj_alloc(mrb, MRB_TT_OBJECT, mrb->object_class);
mrb_define_singleton_method(mrb, mrb->top_self, "inspect", inspect_main, MRB_ARGS_NONE());
mrb_define_singleton_method(mrb, mrb->top_self, "to_s", inspect_main, MRB_ARGS_NONE());
mrb_define_singleton_method(mrb, mrb->top_self, "define_method", top_define_method, MRB_ARGS_ARG(1,1));
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_178_0 |
crossvul-cpp_data_good_3370_0 | /*
* Symmetric key cipher operations.
*
* Generic encrypt/decrypt wrapper for ciphers, handles operations across
* multiple page boundaries by using temporary blocks. In user context,
* the kernel is given a chance to schedule us once per page.
*
* Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/internal/aead.h>
#include <crypto/internal/skcipher.h>
#include <crypto/scatterwalk.h>
#include <linux/bug.h>
#include <linux/cryptouser.h>
#include <linux/compiler.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <linux/seq_file.h>
#include <net/netlink.h>
#include "internal.h"
enum {
SKCIPHER_WALK_PHYS = 1 << 0,
SKCIPHER_WALK_SLOW = 1 << 1,
SKCIPHER_WALK_COPY = 1 << 2,
SKCIPHER_WALK_DIFF = 1 << 3,
SKCIPHER_WALK_SLEEP = 1 << 4,
};
struct skcipher_walk_buffer {
struct list_head entry;
struct scatter_walk dst;
unsigned int len;
u8 *data;
u8 buffer[];
};
static int skcipher_walk_next(struct skcipher_walk *walk);
static inline void skcipher_unmap(struct scatter_walk *walk, void *vaddr)
{
if (PageHighMem(scatterwalk_page(walk)))
kunmap_atomic(vaddr);
}
static inline void *skcipher_map(struct scatter_walk *walk)
{
struct page *page = scatterwalk_page(walk);
return (PageHighMem(page) ? kmap_atomic(page) : page_address(page)) +
offset_in_page(walk->offset);
}
static inline void skcipher_map_src(struct skcipher_walk *walk)
{
walk->src.virt.addr = skcipher_map(&walk->in);
}
static inline void skcipher_map_dst(struct skcipher_walk *walk)
{
walk->dst.virt.addr = skcipher_map(&walk->out);
}
static inline void skcipher_unmap_src(struct skcipher_walk *walk)
{
skcipher_unmap(&walk->in, walk->src.virt.addr);
}
static inline void skcipher_unmap_dst(struct skcipher_walk *walk)
{
skcipher_unmap(&walk->out, walk->dst.virt.addr);
}
static inline gfp_t skcipher_walk_gfp(struct skcipher_walk *walk)
{
return walk->flags & SKCIPHER_WALK_SLEEP ? GFP_KERNEL : GFP_ATOMIC;
}
/* Get a spot of the specified length that does not straddle a page.
* The caller needs to ensure that there is enough space for this operation.
*/
static inline u8 *skcipher_get_spot(u8 *start, unsigned int len)
{
u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK);
return max(start, end_page);
}
static int skcipher_done_slow(struct skcipher_walk *walk, unsigned int bsize)
{
u8 *addr;
addr = (u8 *)ALIGN((unsigned long)walk->buffer, walk->alignmask + 1);
addr = skcipher_get_spot(addr, bsize);
scatterwalk_copychunks(addr, &walk->out, bsize,
(walk->flags & SKCIPHER_WALK_PHYS) ? 2 : 1);
return 0;
}
int skcipher_walk_done(struct skcipher_walk *walk, int err)
{
unsigned int n = walk->nbytes - err;
unsigned int nbytes;
nbytes = walk->total - n;
if (unlikely(err < 0)) {
nbytes = 0;
n = 0;
} else if (likely(!(walk->flags & (SKCIPHER_WALK_PHYS |
SKCIPHER_WALK_SLOW |
SKCIPHER_WALK_COPY |
SKCIPHER_WALK_DIFF)))) {
unmap_src:
skcipher_unmap_src(walk);
} else if (walk->flags & SKCIPHER_WALK_DIFF) {
skcipher_unmap_dst(walk);
goto unmap_src;
} else if (walk->flags & SKCIPHER_WALK_COPY) {
skcipher_map_dst(walk);
memcpy(walk->dst.virt.addr, walk->page, n);
skcipher_unmap_dst(walk);
} else if (unlikely(walk->flags & SKCIPHER_WALK_SLOW)) {
if (WARN_ON(err)) {
err = -EINVAL;
nbytes = 0;
} else
n = skcipher_done_slow(walk, n);
}
if (err > 0)
err = 0;
walk->total = nbytes;
walk->nbytes = nbytes;
scatterwalk_advance(&walk->in, n);
scatterwalk_advance(&walk->out, n);
scatterwalk_done(&walk->in, 0, nbytes);
scatterwalk_done(&walk->out, 1, nbytes);
if (nbytes) {
crypto_yield(walk->flags & SKCIPHER_WALK_SLEEP ?
CRYPTO_TFM_REQ_MAY_SLEEP : 0);
return skcipher_walk_next(walk);
}
/* Short-circuit for the common/fast path. */
if (!((unsigned long)walk->buffer | (unsigned long)walk->page))
goto out;
if (walk->flags & SKCIPHER_WALK_PHYS)
goto out;
if (walk->iv != walk->oiv)
memcpy(walk->oiv, walk->iv, walk->ivsize);
if (walk->buffer != walk->page)
kfree(walk->buffer);
if (walk->page)
free_page((unsigned long)walk->page);
out:
return err;
}
EXPORT_SYMBOL_GPL(skcipher_walk_done);
void skcipher_walk_complete(struct skcipher_walk *walk, int err)
{
struct skcipher_walk_buffer *p, *tmp;
list_for_each_entry_safe(p, tmp, &walk->buffers, entry) {
u8 *data;
if (err)
goto done;
data = p->data;
if (!data) {
data = PTR_ALIGN(&p->buffer[0], walk->alignmask + 1);
data = skcipher_get_spot(data, walk->stride);
}
scatterwalk_copychunks(data, &p->dst, p->len, 1);
if (offset_in_page(p->data) + p->len + walk->stride >
PAGE_SIZE)
free_page((unsigned long)p->data);
done:
list_del(&p->entry);
kfree(p);
}
if (!err && walk->iv != walk->oiv)
memcpy(walk->oiv, walk->iv, walk->ivsize);
if (walk->buffer != walk->page)
kfree(walk->buffer);
if (walk->page)
free_page((unsigned long)walk->page);
}
EXPORT_SYMBOL_GPL(skcipher_walk_complete);
static void skcipher_queue_write(struct skcipher_walk *walk,
struct skcipher_walk_buffer *p)
{
p->dst = walk->out;
list_add_tail(&p->entry, &walk->buffers);
}
static int skcipher_next_slow(struct skcipher_walk *walk, unsigned int bsize)
{
bool phys = walk->flags & SKCIPHER_WALK_PHYS;
unsigned alignmask = walk->alignmask;
struct skcipher_walk_buffer *p;
unsigned a;
unsigned n;
u8 *buffer;
void *v;
if (!phys) {
if (!walk->buffer)
walk->buffer = walk->page;
buffer = walk->buffer;
if (buffer)
goto ok;
}
/* Start with the minimum alignment of kmalloc. */
a = crypto_tfm_ctx_alignment() - 1;
n = bsize;
if (phys) {
/* Calculate the minimum alignment of p->buffer. */
a &= (sizeof(*p) ^ (sizeof(*p) - 1)) >> 1;
n += sizeof(*p);
}
/* Minimum size to align p->buffer by alignmask. */
n += alignmask & ~a;
/* Minimum size to ensure p->buffer does not straddle a page. */
n += (bsize - 1) & ~(alignmask | a);
v = kzalloc(n, skcipher_walk_gfp(walk));
if (!v)
return skcipher_walk_done(walk, -ENOMEM);
if (phys) {
p = v;
p->len = bsize;
skcipher_queue_write(walk, p);
buffer = p->buffer;
} else {
walk->buffer = v;
buffer = v;
}
ok:
walk->dst.virt.addr = PTR_ALIGN(buffer, alignmask + 1);
walk->dst.virt.addr = skcipher_get_spot(walk->dst.virt.addr, bsize);
walk->src.virt.addr = walk->dst.virt.addr;
scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0);
walk->nbytes = bsize;
walk->flags |= SKCIPHER_WALK_SLOW;
return 0;
}
static int skcipher_next_copy(struct skcipher_walk *walk)
{
struct skcipher_walk_buffer *p;
u8 *tmp = walk->page;
skcipher_map_src(walk);
memcpy(tmp, walk->src.virt.addr, walk->nbytes);
skcipher_unmap_src(walk);
walk->src.virt.addr = tmp;
walk->dst.virt.addr = tmp;
if (!(walk->flags & SKCIPHER_WALK_PHYS))
return 0;
p = kmalloc(sizeof(*p), skcipher_walk_gfp(walk));
if (!p)
return -ENOMEM;
p->data = walk->page;
p->len = walk->nbytes;
skcipher_queue_write(walk, p);
if (offset_in_page(walk->page) + walk->nbytes + walk->stride >
PAGE_SIZE)
walk->page = NULL;
else
walk->page += walk->nbytes;
return 0;
}
static int skcipher_next_fast(struct skcipher_walk *walk)
{
unsigned long diff;
walk->src.phys.page = scatterwalk_page(&walk->in);
walk->src.phys.offset = offset_in_page(walk->in.offset);
walk->dst.phys.page = scatterwalk_page(&walk->out);
walk->dst.phys.offset = offset_in_page(walk->out.offset);
if (walk->flags & SKCIPHER_WALK_PHYS)
return 0;
diff = walk->src.phys.offset - walk->dst.phys.offset;
diff |= walk->src.virt.page - walk->dst.virt.page;
skcipher_map_src(walk);
walk->dst.virt.addr = walk->src.virt.addr;
if (diff) {
walk->flags |= SKCIPHER_WALK_DIFF;
skcipher_map_dst(walk);
}
return 0;
}
static int skcipher_walk_next(struct skcipher_walk *walk)
{
unsigned int bsize;
unsigned int n;
int err;
walk->flags &= ~(SKCIPHER_WALK_SLOW | SKCIPHER_WALK_COPY |
SKCIPHER_WALK_DIFF);
n = walk->total;
bsize = min(walk->stride, max(n, walk->blocksize));
n = scatterwalk_clamp(&walk->in, n);
n = scatterwalk_clamp(&walk->out, n);
if (unlikely(n < bsize)) {
if (unlikely(walk->total < walk->blocksize))
return skcipher_walk_done(walk, -EINVAL);
slow_path:
err = skcipher_next_slow(walk, bsize);
goto set_phys_lowmem;
}
if (unlikely((walk->in.offset | walk->out.offset) & walk->alignmask)) {
if (!walk->page) {
gfp_t gfp = skcipher_walk_gfp(walk);
walk->page = (void *)__get_free_page(gfp);
if (!walk->page)
goto slow_path;
}
walk->nbytes = min_t(unsigned, n,
PAGE_SIZE - offset_in_page(walk->page));
walk->flags |= SKCIPHER_WALK_COPY;
err = skcipher_next_copy(walk);
goto set_phys_lowmem;
}
walk->nbytes = n;
return skcipher_next_fast(walk);
set_phys_lowmem:
if (!err && (walk->flags & SKCIPHER_WALK_PHYS)) {
walk->src.phys.page = virt_to_page(walk->src.virt.addr);
walk->dst.phys.page = virt_to_page(walk->dst.virt.addr);
walk->src.phys.offset &= PAGE_SIZE - 1;
walk->dst.phys.offset &= PAGE_SIZE - 1;
}
return err;
}
EXPORT_SYMBOL_GPL(skcipher_walk_next);
static int skcipher_copy_iv(struct skcipher_walk *walk)
{
unsigned a = crypto_tfm_ctx_alignment() - 1;
unsigned alignmask = walk->alignmask;
unsigned ivsize = walk->ivsize;
unsigned bs = walk->stride;
unsigned aligned_bs;
unsigned size;
u8 *iv;
aligned_bs = ALIGN(bs, alignmask);
/* Minimum size to align buffer by alignmask. */
size = alignmask & ~a;
if (walk->flags & SKCIPHER_WALK_PHYS)
size += ivsize;
else {
size += aligned_bs + ivsize;
/* Minimum size to ensure buffer does not straddle a page. */
size += (bs - 1) & ~(alignmask | a);
}
walk->buffer = kmalloc(size, skcipher_walk_gfp(walk));
if (!walk->buffer)
return -ENOMEM;
iv = PTR_ALIGN(walk->buffer, alignmask + 1);
iv = skcipher_get_spot(iv, bs) + aligned_bs;
walk->iv = memcpy(iv, walk->iv, walk->ivsize);
return 0;
}
static int skcipher_walk_first(struct skcipher_walk *walk)
{
walk->nbytes = 0;
if (WARN_ON_ONCE(in_irq()))
return -EDEADLK;
if (unlikely(!walk->total))
return 0;
walk->buffer = NULL;
if (unlikely(((unsigned long)walk->iv & walk->alignmask))) {
int err = skcipher_copy_iv(walk);
if (err)
return err;
}
walk->page = NULL;
walk->nbytes = walk->total;
return skcipher_walk_next(walk);
}
static int skcipher_walk_skcipher(struct skcipher_walk *walk,
struct skcipher_request *req)
{
struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
scatterwalk_start(&walk->in, req->src);
scatterwalk_start(&walk->out, req->dst);
walk->total = req->cryptlen;
walk->iv = req->iv;
walk->oiv = req->iv;
walk->flags &= ~SKCIPHER_WALK_SLEEP;
walk->flags |= req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP ?
SKCIPHER_WALK_SLEEP : 0;
walk->blocksize = crypto_skcipher_blocksize(tfm);
walk->stride = crypto_skcipher_walksize(tfm);
walk->ivsize = crypto_skcipher_ivsize(tfm);
walk->alignmask = crypto_skcipher_alignmask(tfm);
return skcipher_walk_first(walk);
}
int skcipher_walk_virt(struct skcipher_walk *walk,
struct skcipher_request *req, bool atomic)
{
int err;
walk->flags &= ~SKCIPHER_WALK_PHYS;
err = skcipher_walk_skcipher(walk, req);
walk->flags &= atomic ? ~SKCIPHER_WALK_SLEEP : ~0;
return err;
}
EXPORT_SYMBOL_GPL(skcipher_walk_virt);
void skcipher_walk_atomise(struct skcipher_walk *walk)
{
walk->flags &= ~SKCIPHER_WALK_SLEEP;
}
EXPORT_SYMBOL_GPL(skcipher_walk_atomise);
int skcipher_walk_async(struct skcipher_walk *walk,
struct skcipher_request *req)
{
walk->flags |= SKCIPHER_WALK_PHYS;
INIT_LIST_HEAD(&walk->buffers);
return skcipher_walk_skcipher(walk, req);
}
EXPORT_SYMBOL_GPL(skcipher_walk_async);
static int skcipher_walk_aead_common(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
int err;
walk->flags &= ~SKCIPHER_WALK_PHYS;
scatterwalk_start(&walk->in, req->src);
scatterwalk_start(&walk->out, req->dst);
scatterwalk_copychunks(NULL, &walk->in, req->assoclen, 2);
scatterwalk_copychunks(NULL, &walk->out, req->assoclen, 2);
walk->iv = req->iv;
walk->oiv = req->iv;
if (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP)
walk->flags |= SKCIPHER_WALK_SLEEP;
else
walk->flags &= ~SKCIPHER_WALK_SLEEP;
walk->blocksize = crypto_aead_blocksize(tfm);
walk->stride = crypto_aead_chunksize(tfm);
walk->ivsize = crypto_aead_ivsize(tfm);
walk->alignmask = crypto_aead_alignmask(tfm);
err = skcipher_walk_first(walk);
if (atomic)
walk->flags &= ~SKCIPHER_WALK_SLEEP;
return err;
}
int skcipher_walk_aead(struct skcipher_walk *walk, struct aead_request *req,
bool atomic)
{
walk->total = req->cryptlen;
return skcipher_walk_aead_common(walk, req, atomic);
}
EXPORT_SYMBOL_GPL(skcipher_walk_aead);
int skcipher_walk_aead_encrypt(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
walk->total = req->cryptlen;
return skcipher_walk_aead_common(walk, req, atomic);
}
EXPORT_SYMBOL_GPL(skcipher_walk_aead_encrypt);
int skcipher_walk_aead_decrypt(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
walk->total = req->cryptlen - crypto_aead_authsize(tfm);
return skcipher_walk_aead_common(walk, req, atomic);
}
EXPORT_SYMBOL_GPL(skcipher_walk_aead_decrypt);
static unsigned int crypto_skcipher_extsize(struct crypto_alg *alg)
{
if (alg->cra_type == &crypto_blkcipher_type)
return sizeof(struct crypto_blkcipher *);
if (alg->cra_type == &crypto_ablkcipher_type ||
alg->cra_type == &crypto_givcipher_type)
return sizeof(struct crypto_ablkcipher *);
return crypto_alg_extsize(alg);
}
static int skcipher_setkey_blkcipher(struct crypto_skcipher *tfm,
const u8 *key, unsigned int keylen)
{
struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm);
struct crypto_blkcipher *blkcipher = *ctx;
int err;
crypto_blkcipher_clear_flags(blkcipher, ~0);
crypto_blkcipher_set_flags(blkcipher, crypto_skcipher_get_flags(tfm) &
CRYPTO_TFM_REQ_MASK);
err = crypto_blkcipher_setkey(blkcipher, key, keylen);
crypto_skcipher_set_flags(tfm, crypto_blkcipher_get_flags(blkcipher) &
CRYPTO_TFM_RES_MASK);
return err;
}
static int skcipher_crypt_blkcipher(struct skcipher_request *req,
int (*crypt)(struct blkcipher_desc *,
struct scatterlist *,
struct scatterlist *,
unsigned int))
{
struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm);
struct blkcipher_desc desc = {
.tfm = *ctx,
.info = req->iv,
.flags = req->base.flags,
};
return crypt(&desc, req->dst, req->src, req->cryptlen);
}
static int skcipher_encrypt_blkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
return skcipher_crypt_blkcipher(req, alg->encrypt);
}
static int skcipher_decrypt_blkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
return skcipher_crypt_blkcipher(req, alg->decrypt);
}
static void crypto_exit_skcipher_ops_blkcipher(struct crypto_tfm *tfm)
{
struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm);
crypto_free_blkcipher(*ctx);
}
static int crypto_init_skcipher_ops_blkcipher(struct crypto_tfm *tfm)
{
struct crypto_alg *calg = tfm->__crt_alg;
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm);
struct crypto_blkcipher *blkcipher;
struct crypto_tfm *btfm;
if (!crypto_mod_get(calg))
return -EAGAIN;
btfm = __crypto_alloc_tfm(calg, CRYPTO_ALG_TYPE_BLKCIPHER,
CRYPTO_ALG_TYPE_MASK);
if (IS_ERR(btfm)) {
crypto_mod_put(calg);
return PTR_ERR(btfm);
}
blkcipher = __crypto_blkcipher_cast(btfm);
*ctx = blkcipher;
tfm->exit = crypto_exit_skcipher_ops_blkcipher;
skcipher->setkey = skcipher_setkey_blkcipher;
skcipher->encrypt = skcipher_encrypt_blkcipher;
skcipher->decrypt = skcipher_decrypt_blkcipher;
skcipher->ivsize = crypto_blkcipher_ivsize(blkcipher);
skcipher->keysize = calg->cra_blkcipher.max_keysize;
return 0;
}
static int skcipher_setkey_ablkcipher(struct crypto_skcipher *tfm,
const u8 *key, unsigned int keylen)
{
struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm);
struct crypto_ablkcipher *ablkcipher = *ctx;
int err;
crypto_ablkcipher_clear_flags(ablkcipher, ~0);
crypto_ablkcipher_set_flags(ablkcipher,
crypto_skcipher_get_flags(tfm) &
CRYPTO_TFM_REQ_MASK);
err = crypto_ablkcipher_setkey(ablkcipher, key, keylen);
crypto_skcipher_set_flags(tfm,
crypto_ablkcipher_get_flags(ablkcipher) &
CRYPTO_TFM_RES_MASK);
return err;
}
static int skcipher_crypt_ablkcipher(struct skcipher_request *req,
int (*crypt)(struct ablkcipher_request *))
{
struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm);
struct ablkcipher_request *subreq = skcipher_request_ctx(req);
ablkcipher_request_set_tfm(subreq, *ctx);
ablkcipher_request_set_callback(subreq, skcipher_request_flags(req),
req->base.complete, req->base.data);
ablkcipher_request_set_crypt(subreq, req->src, req->dst, req->cryptlen,
req->iv);
return crypt(subreq);
}
static int skcipher_encrypt_ablkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher;
return skcipher_crypt_ablkcipher(req, alg->encrypt);
}
static int skcipher_decrypt_ablkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher;
return skcipher_crypt_ablkcipher(req, alg->decrypt);
}
static void crypto_exit_skcipher_ops_ablkcipher(struct crypto_tfm *tfm)
{
struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm);
crypto_free_ablkcipher(*ctx);
}
static int crypto_init_skcipher_ops_ablkcipher(struct crypto_tfm *tfm)
{
struct crypto_alg *calg = tfm->__crt_alg;
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm);
struct crypto_ablkcipher *ablkcipher;
struct crypto_tfm *abtfm;
if (!crypto_mod_get(calg))
return -EAGAIN;
abtfm = __crypto_alloc_tfm(calg, 0, 0);
if (IS_ERR(abtfm)) {
crypto_mod_put(calg);
return PTR_ERR(abtfm);
}
ablkcipher = __crypto_ablkcipher_cast(abtfm);
*ctx = ablkcipher;
tfm->exit = crypto_exit_skcipher_ops_ablkcipher;
skcipher->setkey = skcipher_setkey_ablkcipher;
skcipher->encrypt = skcipher_encrypt_ablkcipher;
skcipher->decrypt = skcipher_decrypt_ablkcipher;
skcipher->ivsize = crypto_ablkcipher_ivsize(ablkcipher);
skcipher->reqsize = crypto_ablkcipher_reqsize(ablkcipher) +
sizeof(struct ablkcipher_request);
skcipher->keysize = calg->cra_ablkcipher.max_keysize;
return 0;
}
static int skcipher_setkey_unaligned(struct crypto_skcipher *tfm,
const u8 *key, unsigned int keylen)
{
unsigned long alignmask = crypto_skcipher_alignmask(tfm);
struct skcipher_alg *cipher = crypto_skcipher_alg(tfm);
u8 *buffer, *alignbuffer;
unsigned long absize;
int ret;
absize = keylen + alignmask;
buffer = kmalloc(absize, GFP_ATOMIC);
if (!buffer)
return -ENOMEM;
alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1);
memcpy(alignbuffer, key, keylen);
ret = cipher->setkey(tfm, alignbuffer, keylen);
kzfree(buffer);
return ret;
}
static int skcipher_setkey(struct crypto_skcipher *tfm, const u8 *key,
unsigned int keylen)
{
struct skcipher_alg *cipher = crypto_skcipher_alg(tfm);
unsigned long alignmask = crypto_skcipher_alignmask(tfm);
if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) {
crypto_skcipher_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
if ((unsigned long)key & alignmask)
return skcipher_setkey_unaligned(tfm, key, keylen);
return cipher->setkey(tfm, key, keylen);
}
static void crypto_skcipher_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
alg->exit(skcipher);
}
static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = skcipher_setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
}
static void crypto_skcipher_free_instance(struct crypto_instance *inst)
{
struct skcipher_instance *skcipher =
container_of(inst, struct skcipher_instance, s.base);
skcipher->free(skcipher);
}
static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg)
__maybe_unused;
static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg)
{
struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg,
base);
seq_printf(m, "type : skcipher\n");
seq_printf(m, "async : %s\n",
alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no");
seq_printf(m, "blocksize : %u\n", alg->cra_blocksize);
seq_printf(m, "min keysize : %u\n", skcipher->min_keysize);
seq_printf(m, "max keysize : %u\n", skcipher->max_keysize);
seq_printf(m, "ivsize : %u\n", skcipher->ivsize);
seq_printf(m, "chunksize : %u\n", skcipher->chunksize);
seq_printf(m, "walksize : %u\n", skcipher->walksize);
}
#ifdef CONFIG_NET
static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg,
base);
strncpy(rblkcipher.type, "skcipher", sizeof(rblkcipher.type));
strncpy(rblkcipher.geniv, "<none>", sizeof(rblkcipher.geniv));
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = skcipher->min_keysize;
rblkcipher.max_keysize = skcipher->max_keysize;
rblkcipher.ivsize = skcipher->ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
#else
static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
return -ENOSYS;
}
#endif
static const struct crypto_type crypto_skcipher_type2 = {
.extsize = crypto_skcipher_extsize,
.init_tfm = crypto_skcipher_init_tfm,
.free = crypto_skcipher_free_instance,
#ifdef CONFIG_PROC_FS
.show = crypto_skcipher_show,
#endif
.report = crypto_skcipher_report,
.maskclear = ~CRYPTO_ALG_TYPE_MASK,
.maskset = CRYPTO_ALG_TYPE_BLKCIPHER_MASK,
.type = CRYPTO_ALG_TYPE_SKCIPHER,
.tfmsize = offsetof(struct crypto_skcipher, base),
};
int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn,
const char *name, u32 type, u32 mask)
{
spawn->base.frontend = &crypto_skcipher_type2;
return crypto_grab_spawn(&spawn->base, name, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_grab_skcipher);
struct crypto_skcipher *crypto_alloc_skcipher(const char *alg_name,
u32 type, u32 mask)
{
return crypto_alloc_tfm(alg_name, &crypto_skcipher_type2, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_alloc_skcipher);
int crypto_has_skcipher2(const char *alg_name, u32 type, u32 mask)
{
return crypto_type_has_alg(alg_name, &crypto_skcipher_type2,
type, mask);
}
EXPORT_SYMBOL_GPL(crypto_has_skcipher2);
static int skcipher_prepare_alg(struct skcipher_alg *alg)
{
struct crypto_alg *base = &alg->base;
if (alg->ivsize > PAGE_SIZE / 8 || alg->chunksize > PAGE_SIZE / 8 ||
alg->walksize > PAGE_SIZE / 8)
return -EINVAL;
if (!alg->chunksize)
alg->chunksize = base->cra_blocksize;
if (!alg->walksize)
alg->walksize = alg->chunksize;
base->cra_type = &crypto_skcipher_type2;
base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK;
base->cra_flags |= CRYPTO_ALG_TYPE_SKCIPHER;
return 0;
}
int crypto_register_skcipher(struct skcipher_alg *alg)
{
struct crypto_alg *base = &alg->base;
int err;
err = skcipher_prepare_alg(alg);
if (err)
return err;
return crypto_register_alg(base);
}
EXPORT_SYMBOL_GPL(crypto_register_skcipher);
void crypto_unregister_skcipher(struct skcipher_alg *alg)
{
crypto_unregister_alg(&alg->base);
}
EXPORT_SYMBOL_GPL(crypto_unregister_skcipher);
int crypto_register_skciphers(struct skcipher_alg *algs, int count)
{
int i, ret;
for (i = 0; i < count; i++) {
ret = crypto_register_skcipher(&algs[i]);
if (ret)
goto err;
}
return 0;
err:
for (--i; i >= 0; --i)
crypto_unregister_skcipher(&algs[i]);
return ret;
}
EXPORT_SYMBOL_GPL(crypto_register_skciphers);
void crypto_unregister_skciphers(struct skcipher_alg *algs, int count)
{
int i;
for (i = count - 1; i >= 0; --i)
crypto_unregister_skcipher(&algs[i]);
}
EXPORT_SYMBOL_GPL(crypto_unregister_skciphers);
int skcipher_register_instance(struct crypto_template *tmpl,
struct skcipher_instance *inst)
{
int err;
err = skcipher_prepare_alg(&inst->alg);
if (err)
return err;
return crypto_register_instance(tmpl, skcipher_crypto_instance(inst));
}
EXPORT_SYMBOL_GPL(skcipher_register_instance);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Symmetric key cipher type");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3370_0 |
crossvul-cpp_data_bad_864_0 | /* $Id: pcpserver.c,v 1.47 2018/03/13 10:21:19 nanard Exp $ */
/* MiniUPnP project
* Website : http://miniupnp.free.fr/
* Author : Peter Tatrai
Copyright (c) 2013 by Cisco Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* Current assumptions:
- IPv4 is always NATted (internal -> external)
- IPv6 is always firewalled (this may need some work, NAT6* do exist)
- we make the judgement based on (in order, picking first one available):
- third party address
- internal client address
TODO : handle NAT46, NAT64, NPT66. In addition, beyond FW/NAT
choice, should also add for proxy (=as much as possible transparent
pass-through to one or more servers).
TODO: IPv6 permission handling (for the time being, we just assume
anyone on IPv6 is a good guy, but fixing that would include
upnppermissions rewrite to be AF neutral).
*/
#include "config.h"
#ifdef ENABLE_PCP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <signal.h>
#include <stdio.h>
#include <ctype.h>
#include <syslog.h>
#include "pcpserver.h"
#include "natpmp.h"
#include "macros.h"
#include "upnpglobalvars.h"
#include "pcplearndscp.h"
#include "upnpredirect.h"
#include "commonrdr.h"
#include "getifaddr.h"
#include "asyncsendto.h"
#include "upnputils.h"
#include "portinuse.h"
#include "pcp_msg_struct.h"
#ifdef ENABLE_UPNPPINHOLE
#include "upnppinhole.h"
#endif /* ENABLE_UPNPPINHOLE */
#ifdef PCP_PEER
/* TODO make this platform independent */
#ifdef USE_NETFILTER
#include "netfilter/iptcrdr.h"
#else
#error "PCP Peer is only supported with NETFILTER"
#endif /* USE_NETFILTER */
#endif /* PCP_PEER */
/* server specific information */
struct pcp_server_info {
uint8_t server_version;
};
/* default server settings, highest version supported is the default */
static const struct pcp_server_info this_server_info = {2};
/* structure holding information from PCP msg*/
/* all variables are in host byte order except IP addresses */
typedef struct pcp_info {
uint8_t version;
uint8_t opcode;
uint8_t result_code;
uint32_t lifetime; /* lifetime of the mapping */
uint32_t epochtime;
/* both MAP and PEER opcode specific information */
uint32_t nonce[3]; /* random value generated by client */
uint8_t protocol;
uint16_t int_port;
const struct in6_addr *int_ip; /* in network order */
uint16_t ext_port;
const struct in6_addr *ext_ip; /* Suggested external IP in network order*/
/* PEER specific information */
#ifdef PCP_PEER
uint16_t peer_port;
const struct in6_addr *peer_ip; /* Destination IP in network order */
#endif /* PCP_PEER */
#ifdef PCP_SADSCP
/* SADSCP specific information */
uint8_t delay_tolerance;
uint8_t loss_tolerance;
uint8_t jitter_tolerance;
uint8_t app_name_len;
const char* app_name;
uint8_t sadscp_dscp;
uint8_t matched_name;
int8_t is_sadscp_op;
#endif
#ifdef PCP_FLOWP
uint8_t dscp_up;
uint8_t dscp_down;
int flowp_present;
#endif
uint8_t is_map_op;
uint8_t is_peer_op;
const struct in6_addr *thirdp_ip;
const struct in6_addr *mapped_ip;
char mapped_str[INET6_ADDRSTRLEN];
int pfailure_present;
struct in6_addr sender_ip;
int is_fw; /* is this firewall operation? if not, nat. */
char desc[64];
} pcp_info_t;
/* getPCPOpCodeStr()
* return a string representation of the PCP OpCode
* can be used for debug output */
static const char * getPCPOpCodeStr(uint8_t opcode)
{
switch(opcode) {
case PCP_OPCODE_ANNOUNCE:
return "ANNOUNCE";
case PCP_OPCODE_MAP:
return "MAP";
case PCP_OPCODE_PEER:
return "PEER";
#ifdef PCP_SADSCP
case PCP_OPCODE_SADSCP:
return "SADSCP";
#endif /* PCP_SADSCP */
default:
return "UNKNOWN";
}
}
/* useful to copy ext_ip only if needed, as request and response
* buffers are same */
static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src) {
memcpy(dest, src, sizeof(struct in6_addr));
}
}
#ifdef PCP_SADSCP
int get_dscp_value(pcp_info_t *pcp_msg_info) {
unsigned int ind;
for (ind = 0; ind < num_dscp_values; ind++) {
if ((dscp_values_list[ind].app_name) &&
(!strcmp(dscp_values_list[ind].app_name,
pcp_msg_info->app_name)) &&
(pcp_msg_info->delay_tolerance == dscp_values_list[ind].delay) &&
(pcp_msg_info->loss_tolerance == dscp_values_list[ind].loss) &&
(pcp_msg_info->jitter_tolerance == dscp_values_list[ind].jitter)
)
{
pcp_msg_info->sadscp_dscp = dscp_values_list[ind].dscp_value;
pcp_msg_info->matched_name = 1;
return 0;
} else
if ((pcp_msg_info->app_name_len==0) &&
(dscp_values_list[ind].app_name_len==0) &&
(pcp_msg_info->delay_tolerance == dscp_values_list[ind].delay) &&
(pcp_msg_info->loss_tolerance == dscp_values_list[ind].loss) &&
(pcp_msg_info->jitter_tolerance == dscp_values_list[ind].jitter)
)
{
pcp_msg_info->sadscp_dscp = dscp_values_list[ind].dscp_value;
pcp_msg_info->matched_name = 0;
return 0;
} else
if ((dscp_values_list[ind].app_name_len==0) &&
(pcp_msg_info->delay_tolerance == dscp_values_list[ind].delay) &&
(pcp_msg_info->loss_tolerance == dscp_values_list[ind].loss) &&
(pcp_msg_info->jitter_tolerance == dscp_values_list[ind].jitter)
)
{
pcp_msg_info->sadscp_dscp = dscp_values_list[ind].dscp_value;
pcp_msg_info->matched_name = 0;
return 0;
}
}
//if nothing matched return Default value i.e. 0
pcp_msg_info->sadscp_dscp = 0;
pcp_msg_info->matched_name = 0;
return 0;
}
#endif
/*
* Function extracting information from common_req (common request header)
* into pcp_msg_info.
* @return : when no problem occurred 0 is returned, 1 otherwise and appropriate
* result code is assigned to pcp_msg_info->result_code to indicate
* what kind of error occurred
*/
static int parseCommonRequestHeader(const uint8_t *common_req, pcp_info_t *pcp_msg_info)
{
pcp_msg_info->version = common_req[0] ;
pcp_msg_info->opcode = common_req[1] & 0x7f;
pcp_msg_info->lifetime = READNU32(common_req + 4);
pcp_msg_info->int_ip = (struct in6_addr *)(common_req + 8);
pcp_msg_info->mapped_ip = (struct in6_addr *)(common_req + 8);
if ( (pcp_msg_info->version > this_server_info.server_version) ) {
pcp_msg_info->result_code = PCP_ERR_UNSUPP_VERSION;
return 1;
}
if (pcp_msg_info->lifetime > max_lifetime ) {
pcp_msg_info->lifetime = max_lifetime;
}
if ( (pcp_msg_info->lifetime < min_lifetime) && (pcp_msg_info->lifetime != 0) ) {
pcp_msg_info->lifetime = min_lifetime;
}
return 0;
}
#ifdef DEBUG
static void printMAPOpcodeVersion1(const uint8_t *buf)
{
char map_addr[INET6_ADDRSTRLEN];
syslog(LOG_DEBUG, "PCP MAP: v1 Opcode specific information. \n");
syslog(LOG_DEBUG, "MAP protocol: \t\t %d\n", (int)buf[0] );
syslog(LOG_DEBUG, "MAP int port: \t\t %d\n", (int)READNU16(buf+4));
syslog(LOG_DEBUG, "MAP ext port: \t\t %d\n", (int)READNU16(buf+6));
syslog(LOG_DEBUG, "MAP Ext IP: \t\t %s\n", inet_ntop(AF_INET6,
buf+8, map_addr, INET6_ADDRSTRLEN));
}
static void printMAPOpcodeVersion2(const uint8_t *buf)
{
char map_addr[INET6_ADDRSTRLEN];
syslog(LOG_DEBUG, "PCP MAP: v2 Opcode specific information.");
syslog(LOG_DEBUG, "MAP nonce: \t%08x%08x%08x",
READNU32(buf), READNU32(buf+4), READNU32(buf+8));
syslog(LOG_DEBUG, "MAP protocol:\t%d", (int)buf[12]);
syslog(LOG_DEBUG, "MAP int port:\t%d", (int)READNU16(buf+16));
syslog(LOG_DEBUG, "MAP ext port:\t%d", (int)READNU16(buf+18));
syslog(LOG_DEBUG, "MAP Ext IP: \t%s", inet_ntop(AF_INET6,
buf+20, map_addr, INET6_ADDRSTRLEN));
}
#endif /* DEBUG */
static void parsePCPMAP_version1(const uint8_t *map_v1,
pcp_info_t *pcp_msg_info)
{
pcp_msg_info->is_map_op = 1;
pcp_msg_info->protocol = map_v1[0];
pcp_msg_info->int_port = READNU16(map_v1 + 4);
pcp_msg_info->ext_port = READNU16(map_v1 + 6);
pcp_msg_info->ext_ip = (struct in6_addr *)(map_v1 + 8);
}
static void parsePCPMAP_version2(const uint8_t *map_v2,
pcp_info_t *pcp_msg_info)
{
pcp_msg_info->is_map_op = 1;
memcpy(pcp_msg_info->nonce, map_v2, 12);
pcp_msg_info->protocol = map_v2[12];
pcp_msg_info->int_port = READNU16(map_v2 + 16);
pcp_msg_info->ext_port = READNU16(map_v2 + 18);
pcp_msg_info->ext_ip = (struct in6_addr *)(map_v2 + 20);
}
#ifdef PCP_PEER
#ifdef DEBUG
static void printPEEROpcodeVersion1(const uint8_t *buf)
{
char ext_addr[INET6_ADDRSTRLEN];
char peer_addr[INET6_ADDRSTRLEN];
syslog(LOG_DEBUG, "PCP PEER: v1 Opcode specific information. \n");
syslog(LOG_DEBUG, "Protocol: \t\t %d\n", (int)buf[0]);
syslog(LOG_DEBUG, "Internal port: \t\t %d\n", READNU16(buf + 4));
syslog(LOG_DEBUG, "External IP: \t\t %s\n", inet_ntop(AF_INET6, buf + 8,
ext_addr,INET6_ADDRSTRLEN));
syslog(LOG_DEBUG, "External port port: \t\t %d\n", READNU16(buf + 6));
syslog(LOG_DEBUG, "PEER IP: \t\t %s\n", inet_ntop(AF_INET6, buf + 28,
peer_addr,INET6_ADDRSTRLEN));
syslog(LOG_DEBUG, "PEER port port: \t\t %d\n", READNU16(buf + 24));
}
static void printPEEROpcodeVersion2(const uint8_t *buf)
{
char ext_addr[INET6_ADDRSTRLEN];
char peer_addr[INET6_ADDRSTRLEN];
syslog(LOG_DEBUG, "PCP PEER: v2 Opcode specific information.");
syslog(LOG_DEBUG, "nonce: \t%08x%08x%08x",
READNU32(buf), READNU32(buf+4), READNU32(buf+8));
syslog(LOG_DEBUG, "Protocol: \t%d", buf[12]);
syslog(LOG_DEBUG, "Internal port:\t%d", READNU16(buf + 16));
syslog(LOG_DEBUG, "External IP: \t%s", inet_ntop(AF_INET6, buf + 20,
ext_addr, INET6_ADDRSTRLEN));
syslog(LOG_DEBUG, "External port:\t%d", READNU16(buf + 18));
syslog(LOG_DEBUG, "PEER IP: \t%s", inet_ntop(AF_INET6, buf + 40,
peer_addr, INET6_ADDRSTRLEN));
syslog(LOG_DEBUG, "PEER port: \t%d", READNU16(buf + 36));
}
#endif /* DEBUG */
/*
* Function extracting information from peer_buf to pcp_msg_info
* @return : when no problem occurred 0 is returned, 1 otherwise
*/
static void parsePCPPEER_version1(const uint8_t *buf,
pcp_info_t *pcp_msg_info)
{
pcp_msg_info->is_peer_op = 1;
pcp_msg_info->protocol = buf[0];
pcp_msg_info->int_port = READNU16(buf + 4);
pcp_msg_info->ext_port = READNU16(buf + 6);
pcp_msg_info->peer_port = READNU16(buf + 24);
pcp_msg_info->ext_ip = (struct in6_addr *)(buf + 8);
pcp_msg_info->peer_ip = (struct in6_addr *)(buf + 28);
}
/*
* Function extracting information from peer_buf to pcp_msg_info
* @return : when no problem occurred 0 is returned, 1 otherwise
*/
static void parsePCPPEER_version2(const uint8_t *buf, pcp_info_t *pcp_msg_info)
{
pcp_msg_info->is_peer_op = 1;
memcpy(pcp_msg_info->nonce, buf, 12);
pcp_msg_info->protocol = buf[12];
pcp_msg_info->int_port = READNU16(buf + 16);
pcp_msg_info->ext_port = READNU16(buf + 18);
pcp_msg_info->peer_port = READNU16(buf + 36);
pcp_msg_info->ext_ip = (struct in6_addr *)(buf + 20);
pcp_msg_info->peer_ip = (struct in6_addr *)(buf + 40);
}
#endif /* PCP_PEER */
#ifdef PCP_SADSCP
#ifdef DEBUG
static void printSADSCPOpcode(const uint8_t *buf)
{
unsigned char sadscp_tol;
sadscp_tol = buf[12]; /* tolerance_fields */
syslog(LOG_DEBUG, "PCP SADSCP: Opcode specific information.\n");
syslog(LOG_DEBUG, "Delay tolerance %d \n", (sadscp_tol>>6)&3);
syslog(LOG_DEBUG, "Loss tolerance %d \n", (sadscp_tol>>4)&3);
syslog(LOG_DEBUG, "Jitter tolerance %d \n", (sadscp_tol>>2)&3);
syslog(LOG_DEBUG, "RRR %d \n", sadscp_tol&3);
syslog(LOG_DEBUG, "AppName Length %d \n", buf[13]);
syslog(LOG_DEBUG, "Application name %.*s \n", buf[13], buf + 14);
}
#endif //DEBUG
static int parseSADSCP(const uint8_t *buf, pcp_info_t *pcp_msg_info)
{
pcp_msg_info->delay_tolerance = (buf[12]>>6)&3;
pcp_msg_info->loss_tolerance = (buf[12]>>4)&3;
pcp_msg_info->jitter_tolerance = (buf[12]>>2)&3;
if (pcp_msg_info->delay_tolerance == 3 ||
pcp_msg_info->loss_tolerance == 3 ||
pcp_msg_info->jitter_tolerance == 3 ) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return 1;
}
pcp_msg_info->app_name = (const char *)(buf + 14);
pcp_msg_info->app_name_len = buf[13];
return 0;
}
#endif /* PCP_SADSCP */
static int parsePCPOption(uint8_t* pcp_buf, int remain, pcp_info_t *pcp_msg_info)
{
#ifdef DEBUG
char third_addr[INET6_ADDRSTRLEN];
#endif /* DEBUG */
unsigned short option_length;
/* Do centralized option sanity checks here. */
if (remain < (int)PCP_OPTION_HDR_SIZE) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
option_length = READNU16(pcp_buf + 2) + 4; /* len */
if (remain < option_length) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
switch (pcp_buf[0]) { /* code */
case PCP_OPTION_3RD_PARTY:
if (option_length != PCP_3RD_PARTY_OPTION_SIZE) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
#ifdef DEBUG
syslog(LOG_DEBUG, "PCP OPTION: \t Third party\n");
syslog(LOG_DEBUG, "Third PARTY IP: \t %s\n", inet_ntop(AF_INET6,
pcp_buf + 4, third_addr, INET6_ADDRSTRLEN));
#endif
if (pcp_msg_info->thirdp_ip ) {
syslog(LOG_ERR, "PCP: THIRD PARTY OPTION was already present. \n");
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
} else {
pcp_msg_info->thirdp_ip = (struct in6_addr *)(pcp_buf + 4);
pcp_msg_info->mapped_ip = (struct in6_addr *)(pcp_buf + 4);
}
break;
case PCP_OPTION_PREF_FAIL:
if (option_length != PCP_PREFER_FAIL_OPTION_SIZE) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
#ifdef DEBUG
syslog(LOG_DEBUG, "PCP OPTION: \t Prefer failure \n");
#endif
if (pcp_msg_info->opcode != PCP_OPCODE_MAP) {
syslog(LOG_DEBUG, "PCP: Unsupported OPTION for given OPCODE.\n");
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
}
if (pcp_msg_info->pfailure_present != 0 ) {
syslog(LOG_DEBUG, "PCP: PREFER FAILURE OPTION was already present.\n");
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
} else {
pcp_msg_info->pfailure_present = 1;
}
break;
case PCP_OPTION_FILTER:
/* TODO fully implement filter */
if (option_length != PCP_FILTER_OPTION_SIZE) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
#ifdef DEBUG
syslog(LOG_DEBUG, "PCP OPTION: \t Filter\n");
#endif
if (pcp_msg_info->opcode != PCP_OPCODE_MAP) {
syslog(LOG_ERR, "PCP: Unsupported OPTION for given OPCODE.\n");
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return 0;
}
break;
#ifdef PCP_FLOWP
case PCP_OPTION_FLOW_PRIORITY:
#ifdef DEBUG
syslog(LOG_DEBUG, "PCP OPTION: \t Flow priority\n");
#endif
if (option_length != PCP_FLOW_PRIORITY_OPTION_SIZE) {
syslog(LOG_ERR, "PCP: Error processing DSCP. sizeof %d and remaining %d. flow len %d \n",
PCP_FLOW_PRIORITY_OPTION_SIZE, remain, READNU16(pcp_buf + 2));
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
#ifdef DEBUG
syslog(LOG_DEBUG, "DSCP UP: \t %d\n", pcp_buf[4]);
syslog(LOG_DEBUG, "DSCP DOWN: \t %d\n", pcp_buf[5]);
#endif
pcp_msg_info->dscp_up = pcp_buf[4];
pcp_msg_info->dscp_down = pcp_buf[5];
pcp_msg_info->flowp_present = 1;
break;
#endif
default:
if (pcp_buf[0] < 128) {
syslog(LOG_ERR, "PCP: Unrecognized mandatory PCP OPTION: %d \n", (int)pcp_buf[0]);
/* Mandatory to understand */
pcp_msg_info->result_code = PCP_ERR_UNSUPP_OPTION;
remain = 0;
break;
}
/* TODO - log optional not understood options? */
break;
}
return option_length;
}
static void parsePCPOptions(void* pcp_buf, int remain, pcp_info_t *pcp_msg_info)
{
int option_length;
while (remain > 0) {
option_length = parsePCPOption(pcp_buf, remain, pcp_msg_info);
if (!option_length)
break;
remain -= option_length;
pcp_buf += option_length;
}
if (remain > 0) {
syslog(LOG_WARNING, "%s: remain=%d", "parsePCPOptions", remain);
}
}
/* CheckExternalAddress()
* Check that suggested external address in request match a real external
* IP address.
* Suggested address can also be 0 IPv4 or IPv6 address.
* (see http://tools.ietf.org/html/rfc6887#section-10 )
* return values :
* 0 : check is OK
* -1 : check failed */
static int CheckExternalAddress(pcp_info_t* pcp_msg_info)
{
/* can contain a IPv4-mapped IPv6 address */
static struct in6_addr external_addr;
int af;
af = IN6_IS_ADDR_V4MAPPED(pcp_msg_info->mapped_ip)
? AF_INET : AF_INET6;
pcp_msg_info->is_fw = af == AF_INET6;
if (pcp_msg_info->is_fw) {
external_addr = *pcp_msg_info->mapped_ip;
} else {
/* TODO : be able to handle case with multiple
* external addresses */
if(use_ext_ip_addr) {
if (inet_pton(AF_INET, use_ext_ip_addr,
((uint32_t*)external_addr.s6_addr)+3) == 1) {
((uint32_t*)external_addr.s6_addr)[0] = 0;
((uint32_t*)external_addr.s6_addr)[1] = 0;
((uint32_t*)external_addr.s6_addr)[2] = htonl(0xFFFF);
} else if (inet_pton(AF_INET6, use_ext_ip_addr, external_addr.s6_addr)
!= 1) {
pcp_msg_info->result_code = PCP_ERR_NETWORK_FAILURE;
return -1;
}
} else {
if(!ext_if_name || ext_if_name[0]=='\0') {
pcp_msg_info->result_code = PCP_ERR_NETWORK_FAILURE;
return -1;
}
if(getifaddr_in6(ext_if_name, af, &external_addr) < 0) {
pcp_msg_info->result_code = PCP_ERR_NETWORK_FAILURE;
return -1;
}
}
}
if (pcp_msg_info->ext_ip == NULL ||
IN6_IS_ADDR_UNSPECIFIED(pcp_msg_info->ext_ip) ||
(IN6_IS_ADDR_V4MAPPED(pcp_msg_info->ext_ip)
&& ((uint32_t *)pcp_msg_info->ext_ip->s6_addr)[3] == INADDR_ANY)) {
/* no suggested external address : use real external address */
pcp_msg_info->ext_ip = &external_addr;
return 0;
}
if (!IN6_ARE_ADDR_EQUAL(pcp_msg_info->ext_ip, &external_addr)) {
syslog(LOG_ERR,
"PCP: External IP in request didn't match interface IP \n");
#ifdef DEBUG
{
char s[INET6_ADDRSTRLEN];
syslog(LOG_DEBUG, "Interface IP %s \n",
inet_ntop(AF_INET6, &external_addr.s6_addr, s, sizeof(s)));
syslog(LOG_DEBUG, "IP in the PCP request %s \n",
inet_ntop(AF_INET6, pcp_msg_info->ext_ip, s, sizeof(s)));
}
#endif
if (pcp_msg_info->pfailure_present) {
pcp_msg_info->result_code = PCP_ERR_CANNOT_PROVIDE_EXTERNAL;
return -1;
} else {
pcp_msg_info->ext_ip = &external_addr;
}
}
return 0;
}
static const char* inet_n46top(const struct in6_addr* in,
char* buf, size_t buf_len)
{
if (IN6_IS_ADDR_V4MAPPED(in)) {
return inet_ntop(AF_INET, ((uint32_t*)(in->s6_addr))+3, buf, buf_len);
} else {
return inet_ntop(AF_INET6, in, buf, buf_len);
}
}
#ifdef PCP_PEER
static void FillSA(struct sockaddr *sa, const struct in6_addr *in6,
uint16_t port)
{
if (IN6_IS_ADDR_V4MAPPED(in6)) {
struct sockaddr_in *sa4 = (struct sockaddr_in *)sa;
sa4->sin_family = AF_INET;
sa4->sin_addr.s_addr = ((uint32_t*)(in6)->s6_addr)[3];
sa4->sin_port = htons(port);
} else {
struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
sa6->sin6_family = AF_INET6;
sa6->sin6_addr = *in6;
sa6->sin6_port = htons(port);
}
}
static const char* inet_satop(struct sockaddr* sa, char* buf, size_t buf_len)
{
if (sa->sa_family == AF_INET) {
return inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), buf, buf_len);
} else {
return inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), buf, buf_len);
}
}
static int CreatePCPPeer_NAT(pcp_info_t *pcp_msg_info)
{
struct sockaddr_storage intip;
struct sockaddr_storage peerip;
struct sockaddr_storage extip;
struct sockaddr_storage ret_extip;
uint8_t proto = pcp_msg_info->protocol;
uint16_t eport = pcp_msg_info->ext_port; /* public port */
char peerip_s[INET6_ADDRSTRLEN], extip_s[INET6_ADDRSTRLEN];
time_t timestamp = upnp_time() + pcp_msg_info->lifetime;
int r;
FillSA((struct sockaddr*)&intip, pcp_msg_info->mapped_ip,
pcp_msg_info->int_port);
FillSA((struct sockaddr*)&peerip, pcp_msg_info->peer_ip,
pcp_msg_info->peer_port);
FillSA((struct sockaddr*)&extip, pcp_msg_info->ext_ip,
eport);
inet_satop((struct sockaddr*)&peerip, peerip_s, sizeof(peerip_s));
inet_satop((struct sockaddr*)&extip, extip_s, sizeof(extip_s));
/* check if connection with given peer exists, if it was */
/* already established use this external port */
if (get_nat_ext_addr( (struct sockaddr*)&intip, (struct sockaddr*)&peerip,
proto, (struct sockaddr*)&ret_extip) == 1) {
if (ret_extip.ss_family == AF_INET) {
struct sockaddr_in* ret_ext4 = (struct sockaddr_in*)&ret_extip;
uint16_t ret_eport = ntohs(ret_ext4->sin_port);
eport = ret_eport;
} else if (ret_extip.ss_family == AF_INET6) {
struct sockaddr_in6* ret_ext6 = (struct sockaddr_in6*)&ret_extip;
uint16_t ret_eport = ntohs(ret_ext6->sin6_port);
eport = ret_eport;
} else {
return PCP_ERR_CANNOT_PROVIDE_EXTERNAL;
}
}
/* Create Peer Mapping */
if (eport == 0) {
eport = pcp_msg_info->int_port;
}
#ifdef PCP_FLOWP
if (pcp_msg_info->flowp_present && pcp_msg_info->dscp_up) {
if (add_peer_dscp_rule2(ext_if_name, peerip_s,
pcp_msg_info->peer_port, pcp_msg_info->dscp_up,
pcp_msg_info->mapped_str, pcp_msg_info->int_port,
proto, pcp_msg_info->desc, timestamp) < 0 ) {
syslog(LOG_ERR, "PCP: failed to add flowp upstream mapping %s:%hu->%s:%hu '%s'",
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
peerip_s,
pcp_msg_info->peer_port,
pcp_msg_info->desc);
return PCP_ERR_NO_RESOURCES;
}
}
if (pcp_msg_info->flowp_present && pcp_msg_info->dscp_down) {
if (add_peer_dscp_rule2(ext_if_name, pcp_msg_info->mapped_str,
pcp_msg_info->int_port, pcp_msg_info->dscp_down,
peerip_s, pcp_msg_info->peer_port, proto, pcp_msg_info->desc, timestamp)
< 0 ) {
syslog(LOG_ERR, "PCP: failed to add flowp downstream mapping %s:%hu->%s:%hu '%s'",
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
peerip_s,
pcp_msg_info->peer_port,
pcp_msg_info->desc);
pcp_msg_info->result_code = PCP_ERR_NO_RESOURCES;
return PCP_ERR_NO_RESOURCES;
}
}
#endif
r = add_peer_redirect_rule2(ext_if_name,
peerip_s,
pcp_msg_info->peer_port,
extip_s,
eport,
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->protocol,
pcp_msg_info->desc,
timestamp);
if (r < 0)
return PCP_ERR_NO_RESOURCES;
pcp_msg_info->ext_port = eport;
return PCP_SUCCESS;
}
static void CreatePCPPeer(pcp_info_t *pcp_msg_info)
{
char peerip_s[INET6_ADDRSTRLEN];
int r = -1;
if (!inet_n46top(pcp_msg_info->peer_ip, peerip_s, sizeof(peerip_s))) {
syslog(LOG_ERR, "inet_n46top(peer_ip): %m");
return;
}
if (pcp_msg_info->is_fw) {
#if 0
/* Someday, something like this is available.. and we're ready! */
#ifdef ENABLE_UPNPPINHOLE
pcp_msg_info->ext_port = pcp_msg_info->int_port;
r = upnp_add_outbound_pinhole(peerip_s,
pcp_msg_info->peer_port,
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->protocol,
pcp_msg_info->desc,
pcp_msg_info->lifetime, NULL);
#endif /* ENABLE_UPNPPINHOLE */
#else
r = PCP_ERR_UNSUPP_OPCODE;
#endif /* 0 */
} else {
r = CreatePCPPeer_NAT(pcp_msg_info);
}
/* TODO: add upnp function for PI */
pcp_msg_info->result_code = r;
syslog(r == PCP_SUCCESS ? LOG_INFO : LOG_ERR,
"PCP PEER: %s peer mapping %s %s:%hu(%hu)->%s:%hu '%s'",
r == PCP_SUCCESS ? "added" : "failed to add",
(pcp_msg_info->protocol==IPPROTO_TCP)?"TCP":"UDP",
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->ext_port,
peerip_s,
pcp_msg_info->peer_port,
pcp_msg_info->desc);
}
static void DeletePCPPeer(pcp_info_t *pcp_msg_info)
{
uint16_t iport = pcp_msg_info->int_port; /* private port */
uint16_t rport = pcp_msg_info->peer_port; /* private port */
uint8_t proto = pcp_msg_info->protocol;
char rhost[INET6_ADDRSTRLEN];
int r = -1;
/* remove requested mappings for this client */
int index = 0;
unsigned short eport2, iport2, rport2;
char iaddr2[INET6_ADDRSTRLEN], rhost2[INET6_ADDRSTRLEN];
int proto2;
char desc[64];
unsigned int timestamp;
#if 0
int uid;
#endif /* 0 */
if (pcp_msg_info->is_fw) {
pcp_msg_info->result_code = PCP_ERR_UNSUPP_OPCODE;
return;
}
inet_n46top((struct in6_addr*)pcp_msg_info->peer_ip, rhost, sizeof(rhost));
for (index = 0 ;
(!pcp_msg_info->is_fw &&
get_peer_rule_by_index(index, 0,
&eport2, iaddr2, sizeof(iaddr2),
&iport2, &proto2,
desc, sizeof(desc),
rhost2, sizeof(rhost2), &rport2,
×tamp, 0, 0) >= 0)
#if 0
/* Some day if outbound pinholes are supported.. */
||
(pcp_msg_info->is_fw &&
(uid=upnp_get_pinhole_uid_by_index(index))>=0 &&
upnp_get_pinhole_info((unsigned short)uid,
rhost2, sizeof(rhost2), &rport2,
iaddr2, sizeof(iaddr2), &iport2,
&proto2, desc, sizeof(desc),
×tamp, NULL) >= 0)
#endif /* 0 */
;
index++)
if((0 == strcmp(iaddr2, pcp_msg_info->mapped_str))
&& (0 == strcmp(rhost2, rhost))
&& (proto2==proto)
&& 0 == strcmp(desc, pcp_msg_info->desc)
&& (iport2==iport) && (rport2==rport)) {
if (!pcp_msg_info->is_fw)
r = _upnp_delete_redir(eport2, proto2);
#if 0
else
r = upnp_delete_outboundpinhole(uid);
#endif /* 0 */
if(r<0) {
syslog(LOG_ERR, "PCP PEER: failed to remove peer mapping");
} else {
syslog(LOG_INFO, "PCP PEER: %s port %hu peer mapping removed",
proto2==IPPROTO_TCP?"TCP":"UDP", eport2);
}
return;
}
if (r==-1) {
syslog(LOG_ERR, "PCP PEER: Failed to find PCP mapping internal port %hu, protocol %s",
iport, (pcp_msg_info->protocol == IPPROTO_TCP)?"TCP":"UDP");
pcp_msg_info->result_code = PCP_ERR_NO_RESOURCES;
}
}
#endif /* PCP_PEER */
static int CreatePCPMap_NAT(pcp_info_t *pcp_msg_info)
{
int r = 0;
char iaddr_old[INET6_ADDRSTRLEN];
uint16_t iport_old, eport_first = 0;
int any_eport_allowed = 0;
unsigned int timestamp = upnp_time() + pcp_msg_info->lifetime;
if (pcp_msg_info->ext_port == 0) {
pcp_msg_info->ext_port = pcp_msg_info->int_port;
}
/* TODO: Support non-TCP/UDP */
if (pcp_msg_info->ext_port == 0) {
return PCP_ERR_MALFORMED_REQUEST;
}
do {
if (eport_first == 0) { /* first time in loop */
eport_first = pcp_msg_info->ext_port;
} else if (pcp_msg_info->ext_port == eport_first) { /* no eport available */
/* all eports rejected by permissions? */
if (any_eport_allowed == 0)
return PCP_ERR_NOT_AUTHORIZED;
/* at least one eport allowed (but none available) */
return PCP_ERR_NO_RESOURCES;
}
if ((IN6_IS_ADDR_V4MAPPED(pcp_msg_info->mapped_ip) &&
(!check_upnp_rule_against_permissions(upnppermlist,
num_upnpperm, pcp_msg_info->ext_port,
((struct in_addr*)pcp_msg_info->mapped_ip->s6_addr)[3],
pcp_msg_info->int_port)))) {
if (pcp_msg_info->pfailure_present) {
return PCP_ERR_CANNOT_PROVIDE_EXTERNAL;
}
pcp_msg_info->ext_port++;
if (pcp_msg_info->ext_port == 0) { /* skip port zero */
pcp_msg_info->ext_port++;
}
continue;
}
any_eport_allowed = 1;
#ifdef CHECK_PORTINUSE
if (port_in_use(ext_if_name, pcp_msg_info->ext_port, pcp_msg_info->protocol,
pcp_msg_info->mapped_str, pcp_msg_info->int_port) > 0) {
syslog(LOG_INFO, "port %hu protocol %s already in use",
pcp_msg_info->ext_port,
(pcp_msg_info->protocol==IPPROTO_TCP)?"tcp":"udp");
pcp_msg_info->ext_port++;
if (pcp_msg_info->ext_port == 0) { /* skip port zero */
pcp_msg_info->ext_port++;
}
continue;
}
#endif
r = get_redirect_rule(ext_if_name,
pcp_msg_info->ext_port,
pcp_msg_info->protocol,
iaddr_old, sizeof(iaddr_old),
&iport_old, 0, 0, 0, 0,
NULL/*×tamp*/, 0, 0);
if(r==0) {
if((strcmp(pcp_msg_info->mapped_str, iaddr_old)!=0)
|| (pcp_msg_info->int_port != iport_old)) {
/* redirection already existing */
if (pcp_msg_info->pfailure_present) {
return PCP_ERR_CANNOT_PROVIDE_EXTERNAL;
}
} else {
syslog(LOG_INFO, "port %hu %s already redirected to %s:%hu, replacing",
pcp_msg_info->ext_port, (pcp_msg_info->protocol==IPPROTO_TCP)?"tcp":"udp",
iaddr_old, iport_old);
/* remove and then add again */
if (_upnp_delete_redir(pcp_msg_info->ext_port,
pcp_msg_info->protocol)==0) {
break;
} else if (pcp_msg_info->pfailure_present) {
return PCP_ERR_CANNOT_PROVIDE_EXTERNAL;
}
}
pcp_msg_info->ext_port++;
if (pcp_msg_info->ext_port == 0) { /* skip port zero */
pcp_msg_info->ext_port++;
}
}
} while (r==0);
r = upnp_redirect_internal(NULL,
pcp_msg_info->ext_port,
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->protocol,
pcp_msg_info->desc,
timestamp);
if (r < 0)
return PCP_ERR_NO_RESOURCES;
return PCP_SUCCESS;
}
static int CreatePCPMap_FW(pcp_info_t *pcp_msg_info)
{
#ifdef ENABLE_UPNPPINHOLE
int uid;
int r;
/* first check if pinhole already exists */
uid = upnp_find_inboundpinhole(NULL, 0,
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->protocol,
NULL, 0, /* desc */
NULL /* lifetime */);
if(uid >= 0) {
/* pinhole already exists, updating */
syslog(LOG_INFO, "updating pinhole to %s:%hu %s",
pcp_msg_info->mapped_str, pcp_msg_info->int_port,
(pcp_msg_info->protocol == IPPROTO_TCP)?"TCP":"UDP");
r = upnp_update_inboundpinhole((unsigned short)uid, pcp_msg_info->lifetime);
return r >= 0 ? PCP_SUCCESS : PCP_ERR_NO_RESOURCES;
} else {
r = upnp_add_inboundpinhole(NULL, 0,
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->protocol,
pcp_msg_info->desc,
pcp_msg_info->lifetime,
&uid);
if (r < 0)
return PCP_ERR_NO_RESOURCES;
pcp_msg_info->ext_port = pcp_msg_info->int_port;
return PCP_SUCCESS;
}
#else
UNUSED(pcp_msg_info);
return PCP_ERR_NO_RESOURCES;
#endif /* ENABLE_UPNPPINHOLE */
}
/* internal external PCP remote peer actual remote peer
* -------- ------- --------------- ------------------
* IPv4 firewall IPv4 IPv4 IPv4 IPv4
* IPv6 firewall IPv6 IPv6 IPv6 IPv6
* NAT44 IPv4 IPv4 IPv4 IPv4
* NAT46 IPv4 IPv6 IPv4 IPv6
* NAT64 IPv6 IPv4 IPv6 IPv4
* NPTv6 IPv6 IPv6 IPv6 IPv6
*
* Address Families with MAP and PEER
*
* The 'internal' address is implicitly the same as the source IP
* address of the PCP request, except when the THIRD_PARTY option is
* used.
*
* The 'external' address is the Suggested External Address field of the
* MAP or PEER request, and its address family is usually the same as
* the 'internal' address family, except when technologies like NAT64
* are used.
*
* The 'remote peer' address is the remote peer IP address of the PEER
* request or the FILTER option of the MAP request, and is always the
* same address family as the 'internal' address, even when NAT64 is
* used. In NAT64, the IPv6 PCP client is not necessarily aware of the
* NAT64 or aware of the actual IPv4 address of the remote peer, so it
* expresses the IPv6 address from its perspective. */
/* TODO: Support more than basic NAT44 / IPv6 firewall cases. */
static void CreatePCPMap(pcp_info_t *pcp_msg_info)
{
int r;
if (pcp_msg_info->is_fw)
r = CreatePCPMap_FW(pcp_msg_info);
else
r = CreatePCPMap_NAT(pcp_msg_info);
pcp_msg_info->result_code = r;
syslog(r == PCP_SUCCESS ? LOG_INFO : LOG_ERR,
"PCP MAP: %s mapping %s %hu->%s:%hu '%s'",
r == PCP_SUCCESS ? "added" : "failed to add",
(pcp_msg_info->protocol==IPPROTO_TCP)?"TCP":"UDP",
pcp_msg_info->ext_port,
pcp_msg_info->mapped_str,
pcp_msg_info->int_port,
pcp_msg_info->desc);
}
static void DeletePCPMap(pcp_info_t *pcp_msg_info)
{
uint16_t iport = pcp_msg_info->int_port; /* private port */
uint8_t proto = pcp_msg_info->protocol;
int r=-1;
/* remove the mapping */
/* remove all the mappings for this client */
int index;
unsigned short eport2, iport2;
char iaddr2[INET6_ADDRSTRLEN];
int proto2;
char desc[64];
unsigned int timestamp;
#ifdef ENABLE_UPNPPINHOLE
int uid = -1;
#endif /* ENABLE_UPNPPINHOLE */
/* iterate through all rules and delete the requested ones */
for (index = 0 ;
(!pcp_msg_info->is_fw &&
get_redirect_rule_by_index(index, 0,
&eport2, iaddr2, sizeof(iaddr2),
&iport2, &proto2,
desc, sizeof(desc),
0, 0, ×tamp, 0, 0) >= 0)
#ifdef ENABLE_UPNPPINHOLE
||
(pcp_msg_info->is_fw &&
(uid=upnp_get_pinhole_uid_by_index(index))>=0 &&
upnp_get_pinhole_info((unsigned short)uid,
NULL, 0, NULL,
iaddr2, sizeof(iaddr2), &iport2,
&proto2, desc, sizeof(desc),
×tamp, NULL) >= 0)
#endif /* ENABLE_UPNPPINHOLE */
;
index++)
if(0 == strcmp(iaddr2, pcp_msg_info->mapped_str)
&& (proto2==proto)
&& ((iport2==iport) || (iport==0))) {
if(0 != strcmp(desc, pcp_msg_info->desc)) {
/* nonce does not match */
pcp_msg_info->result_code = PCP_ERR_NOT_AUTHORIZED;
syslog(LOG_ERR, "Unauthorized to remove PCP mapping internal port %hu, protocol %s",
iport, (pcp_msg_info->protocol == IPPROTO_TCP)?"TCP":"UDP");
return;
} else if (!pcp_msg_info->is_fw) {
r = _upnp_delete_redir(eport2, proto2);
} else {
#ifdef ENABLE_UPNPPINHOLE
r = upnp_delete_inboundpinhole(uid);
#endif /* ENABLE_UPNPPINHOLE */
}
break;
}
if (r >= 0) {
syslog(LOG_INFO, "PCP: %s port %hu mapping removed",
proto2==IPPROTO_TCP?"TCP":"UDP", eport2);
} else {
syslog(LOG_ERR, "Failed to remove PCP mapping internal port %hu, protocol %s",
iport, (pcp_msg_info->protocol == IPPROTO_TCP)?"TCP":"UDP");
pcp_msg_info->result_code = PCP_ERR_NO_RESOURCES;
}
}
static int ValidatePCPMsg(pcp_info_t *pcp_msg_info)
{
if (pcp_msg_info->result_code) {
return 0;
}
/* RFC 6887, section 8.2: MUST return address mismatch if NAT
* in middle. */
if (memcmp(pcp_msg_info->int_ip,
&pcp_msg_info->sender_ip,
sizeof(pcp_msg_info->sender_ip)) != 0) {
pcp_msg_info->result_code = PCP_ERR_ADDRESS_MISMATCH;
return 0;
}
if (pcp_msg_info->thirdp_ip) {
if (!GETFLAG(PCP_ALLOWTHIRDPARTYMASK)) {
pcp_msg_info->result_code = PCP_ERR_UNSUPP_OPTION;
return 0;
}
/* RFC687, section 13.1 - if sender ip == THIRD_PARTY,
* it's an error. */
if (memcmp(pcp_msg_info->thirdp_ip,
&pcp_msg_info->sender_ip,
sizeof(pcp_msg_info->sender_ip)) == 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return 0;
}
}
/* Produce mapped_str for future use. */
if (!inet_n46top(pcp_msg_info->mapped_ip, pcp_msg_info->mapped_str,
sizeof(pcp_msg_info->mapped_str))) {
syslog(LOG_ERR, "inet_ntop(pcpserver): %m");
return 0;
}
/* protocol zero means 'all protocols' : internal port MUST be zero */
if (pcp_msg_info->protocol == 0 && pcp_msg_info->int_port != 0) {
syslog(LOG_ERR, "PCP %s: Protocol was ZERO, but internal port "
"has non-ZERO value.", getPCPOpCodeStr(pcp_msg_info->opcode));
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return 0;
}
if (pcp_msg_info->pfailure_present) {
if ( (IN6_IS_ADDR_UNSPECIFIED(pcp_msg_info->ext_ip) ||
((IN6_IS_ADDR_V4MAPPED(pcp_msg_info->ext_ip)) &&
(((uint32_t*)pcp_msg_info->ext_ip->s6_addr)[3] == 0))) &&
(pcp_msg_info->ext_port == 0)
)
{
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return 0;
}
}
if (CheckExternalAddress(pcp_msg_info)) {
return 0;
}
/* Fill in the desc that describes uniquely what flow we're
* dealing with (same code used in both create + delete of
* MAP/PEER) */
switch (pcp_msg_info->opcode) {
case PCP_OPCODE_MAP:
case PCP_OPCODE_PEER:
snprintf(pcp_msg_info->desc, sizeof(pcp_msg_info->desc),
"PCP %s %08x%08x%08x",
getPCPOpCodeStr(pcp_msg_info->opcode),
pcp_msg_info->nonce[0],
pcp_msg_info->nonce[1], pcp_msg_info->nonce[2]);
break;
}
return 1;
}
/*
* return value indicates whether the request is valid or not.
* Based on the return value simple response can be formed.
*/
static int processPCPRequest(void * req, int req_size, pcp_info_t *pcp_msg_info)
{
int remainingSize;
/* start with PCP_SUCCESS as result code,
* if everything is OK value will be unchanged */
pcp_msg_info->result_code = PCP_SUCCESS;
remainingSize = req_size;
/* discard request that exceeds maximal length,
or that is shorter than PCP_MIN_LEN (=24)
or that is not the multiple of 4 */
if (req_size < 3)
return 0; /* ignore msg */
if (req_size < PCP_MIN_LEN) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return 1; /* send response */
}
if ( (req_size > PCP_MAX_LEN) || ( (req_size & 3) != 0)) {
syslog(LOG_ERR, "PCP: Size of PCP packet(%d) is larger than %d bytes or "
"the size is not multiple of 4.\n", req_size, PCP_MAX_LEN);
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return 1; /* send response */
}
/* first parse request header */
if (parseCommonRequestHeader(req, pcp_msg_info) ) {
return 1;
}
remainingSize -= PCP_COMMON_REQUEST_SIZE;
req += PCP_COMMON_REQUEST_SIZE;
if (pcp_msg_info->version == 1) {
/* legacy PCP version 1 support */
switch (pcp_msg_info->opcode) {
case PCP_OPCODE_MAP:
remainingSize -= PCP_MAP_V1_SIZE;
if (remainingSize < 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return pcp_msg_info->result_code;
}
#ifdef DEBUG
printMAPOpcodeVersion1(req);
#endif /* DEBUG */
parsePCPMAP_version1(req, pcp_msg_info);
req += PCP_MAP_V1_SIZE;
parsePCPOptions(req, remainingSize, pcp_msg_info);
if (ValidatePCPMsg(pcp_msg_info)) {
if (pcp_msg_info->lifetime == 0) {
DeletePCPMap(pcp_msg_info);
} else {
CreatePCPMap(pcp_msg_info);
}
} else {
syslog(LOG_ERR, "PCP: Invalid PCP v1 MAP message.");
return pcp_msg_info->result_code;
}
break;
#ifdef PCP_PEER
case PCP_OPCODE_PEER:
remainingSize -= PCP_PEER_V1_SIZE;
if (remainingSize < 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return pcp_msg_info->result_code;
}
#ifdef DEBUG
printPEEROpcodeVersion1(req);
#endif /* DEBUG */
parsePCPPEER_version1(req, pcp_msg_info);
req += PCP_PEER_V1_SIZE;
parsePCPOptions(req, remainingSize, pcp_msg_info);
if (ValidatePCPMsg(pcp_msg_info)) {
if (pcp_msg_info->lifetime == 0) {
DeletePCPPeer(pcp_msg_info);
} else {
CreatePCPPeer(pcp_msg_info);
}
} else {
syslog(LOG_ERR, "PCP: Invalid PCP v1 PEER message.");
return pcp_msg_info->result_code;
}
break;
#endif /* PCP_PEER */
default:
pcp_msg_info->result_code = PCP_ERR_UNSUPP_OPCODE;
break;
}
} else if (pcp_msg_info->version == 2) {
/* RFC 6887 PCP support
* http://tools.ietf.org/html/rfc6887 */
switch (pcp_msg_info->opcode) {
case PCP_OPCODE_ANNOUNCE:
/* should check PCP Client's IP Address in request */
/* see http://tools.ietf.org/html/rfc6887#section-14.1 */
break;
case PCP_OPCODE_MAP:
remainingSize -= PCP_MAP_V2_SIZE;
if (remainingSize < 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return pcp_msg_info->result_code;
}
#ifdef DEBUG
printMAPOpcodeVersion2(req);
#endif /* DEBUG */
parsePCPMAP_version2(req, pcp_msg_info);
req += PCP_MAP_V2_SIZE;
parsePCPOptions(req, remainingSize, pcp_msg_info);
if (ValidatePCPMsg(pcp_msg_info)) {
if (pcp_msg_info->lifetime == 0) {
DeletePCPMap(pcp_msg_info);
} else {
CreatePCPMap(pcp_msg_info);
}
} else {
syslog(LOG_ERR, "PCP: Invalid PCP v2 MAP message.");
return pcp_msg_info->result_code;
}
break;
#ifdef PCP_PEER
case PCP_OPCODE_PEER:
remainingSize -= PCP_PEER_V2_SIZE;
if (remainingSize < 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return pcp_msg_info->result_code;
}
#ifdef DEBUG
printPEEROpcodeVersion2(req);
#endif /* DEBUG */
parsePCPPEER_version2(req, pcp_msg_info);
req += PCP_PEER_V2_SIZE;
if (pcp_msg_info->result_code != 0) {
return pcp_msg_info->result_code;
}
parsePCPOptions(req, remainingSize, pcp_msg_info);
if (ValidatePCPMsg(pcp_msg_info)) {
if (pcp_msg_info->lifetime == 0) {
DeletePCPPeer(pcp_msg_info);
} else {
CreatePCPPeer(pcp_msg_info);
}
} else {
syslog(LOG_ERR, "PCP: Invalid PCP v2 PEER message.");
}
break;
#endif /* PCP_PEER */
#ifdef PCP_SADSCP
case PCP_OPCODE_SADSCP:
remainingSize -= PCP_SADSCP_REQ_SIZE;
if (remainingSize < 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_REQUEST;
return pcp_msg_info->result_code;
}
remainingSize -= ((uint8_t *)req)[13]; /* app_name_length */
if (remainingSize < 0) {
pcp_msg_info->result_code = PCP_ERR_MALFORMED_OPTION;
return pcp_msg_info->result_code;
}
#ifdef DEBUG
printSADSCPOpcode(req);
#endif
parseSADSCP(req, pcp_msg_info);
req += PCP_SADSCP_REQ_SIZE;
if (pcp_msg_info->result_code != 0) {
return pcp_msg_info->result_code;
}
req += pcp_msg_info->app_name_len;
get_dscp_value(pcp_msg_info);
break;
#endif
default:
pcp_msg_info->result_code = PCP_ERR_UNSUPP_OPCODE;
break;
}
} else {
pcp_msg_info->result_code = PCP_ERR_UNSUPP_VERSION;
return pcp_msg_info->result_code;
}
return 1;
}
static void createPCPResponse(unsigned char *response, const pcp_info_t *pcp_msg_info)
{
response[2] = 0; /* reserved */
memset(response + 12, 0, 12); /* reserved */
if (pcp_msg_info->result_code == PCP_ERR_UNSUPP_VERSION ) {
/* highest supported version */
response[0] = this_server_info.server_version;
} else {
response[0] = pcp_msg_info->version;
}
response[1] = pcp_msg_info->opcode | 0x80; /* r_opcode */
response[3] = pcp_msg_info->result_code;
if(epoch_origin == 0) {
epoch_origin = startup_time;
}
WRITENU32(response + 8, upnp_time() - epoch_origin); /* epochtime */
switch (pcp_msg_info->result_code) {
/*long lifetime errors*/
case PCP_ERR_UNSUPP_VERSION:
case PCP_ERR_NOT_AUTHORIZED:
case PCP_ERR_MALFORMED_REQUEST:
case PCP_ERR_UNSUPP_OPCODE:
case PCP_ERR_UNSUPP_OPTION:
case PCP_ERR_MALFORMED_OPTION:
case PCP_ERR_UNSUPP_PROTOCOL:
case PCP_ERR_ADDRESS_MISMATCH:
case PCP_ERR_CANNOT_PROVIDE_EXTERNAL:
case PCP_ERR_EXCESSIVE_REMOTE_PEERS:
WRITENU32(response + 4, 0); /* lifetime */
break;
case PCP_ERR_NETWORK_FAILURE:
case PCP_ERR_NO_RESOURCES:
case PCP_ERR_USER_EX_QUOTA:
WRITENU32(response + 4, 30); /* lifetime */
break;
case PCP_SUCCESS:
default:
WRITENU32(response + 4, pcp_msg_info->lifetime); /* lifetime */
break;
}
if (response[1] == 0x81) { /* MAP response */
if (response[0] == 1) { /* version */
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 4, pcp_msg_info->int_port);
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 6, pcp_msg_info->ext_port);
copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 8,
pcp_msg_info->ext_ip);
}
else if (response[0] == 2) {
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 16, pcp_msg_info->int_port);
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 18, pcp_msg_info->ext_port);
copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 20,
pcp_msg_info->ext_ip);
}
}
#ifdef PCP_PEER
else if (response[1] == 0x82) { /* PEER response */
if (response[0] == 1) {
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 4, pcp_msg_info->int_port);
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 6, pcp_msg_info->ext_port);
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 24, pcp_msg_info->peer_port);
copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 8,
pcp_msg_info->ext_ip);
}
else if (response[0] == 2) {
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 16, pcp_msg_info->int_port);
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 18, pcp_msg_info->ext_port);
WRITENU16(response + PCP_COMMON_RESPONSE_SIZE + 36, pcp_msg_info->peer_port);
copyIPv6IfDifferent(response + PCP_COMMON_RESPONSE_SIZE + 20,
pcp_msg_info->ext_ip);
}
}
#endif /* PCP_PEER */
#ifdef PCP_SADSCP
else if (response[1] == 0x83) { /*SADSCP response*/
response[PCP_COMMON_RESPONSE_SIZE + 12]
= ((pcp_msg_info->matched_name<<7) & ~(1<<6)) |
(pcp_msg_info->sadscp_dscp & PCP_SADSCP_MASK);
memset(response + PCP_COMMON_RESPONSE_SIZE + 13, 0, 3);
}
#endif /* PCP_SADSCP */
}
int ProcessIncomingPCPPacket(int s, unsigned char *buff, int len,
const struct sockaddr *senderaddr,
const struct sockaddr_in6 *receiveraddr)
{
pcp_info_t pcp_msg_info;
struct lan_addr_s * lan_addr;
char addr_str[64];
memset(&pcp_msg_info, 0, sizeof(pcp_info_t));
if(senderaddr->sa_family == AF_INET) {
const struct sockaddr_in * senderaddr_v4 =
(const struct sockaddr_in *)senderaddr;
pcp_msg_info.sender_ip.s6_addr[11] = 0xff;
pcp_msg_info.sender_ip.s6_addr[10] = 0xff;
memcpy(pcp_msg_info.sender_ip.s6_addr+12,
&senderaddr_v4->sin_addr, 4);
} else if(senderaddr->sa_family == AF_INET6) {
const struct sockaddr_in6 * senderaddr_v6 =
(const struct sockaddr_in6 *)senderaddr;
pcp_msg_info.sender_ip = senderaddr_v6->sin6_addr;
} else {
syslog(LOG_WARNING, "unknown PCP packet sender address family %d",
senderaddr->sa_family);
return 0;
}
if(sockaddr_to_string(senderaddr, addr_str, sizeof(addr_str)))
syslog(LOG_DEBUG, "PCP request received from %s %dbytes",
addr_str, len);
if(buff[1] & 128) {
/* discarding PCP responses silently */
return 0;
}
/* If we're in allow third party-mode, we probably don't care
* about locality either. Let's hope firewall is ok. */
if (!GETFLAG(PCP_ALLOWTHIRDPARTYMASK)) {
lan_addr = get_lan_for_peer(senderaddr);
if(lan_addr == NULL) {
syslog(LOG_WARNING, "PCP packet sender %s not from a LAN, ignoring",
addr_str);
return 0;
}
}
if (processPCPRequest(buff, len, &pcp_msg_info) ) {
createPCPResponse(buff, &pcp_msg_info);
if(len < PCP_MIN_LEN)
len = PCP_MIN_LEN;
else
len = (len + 3) & ~3; /* round up resp. length to multiple of 4 */
len = sendto_or_schedule2(s, buff, len, 0, senderaddr,
(senderaddr->sa_family == AF_INET) ?
sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6),
receiveraddr);
if( len < 0 ) {
syslog(LOG_ERR, "sendto(pcpserver): %m");
}
}
return 0;
}
#ifdef ENABLE_IPV6
int OpenAndConfPCPv6Socket(void)
{
int s;
int i = 1;
struct sockaddr_in6 addr;
s = socket(PF_INET6, SOCK_DGRAM, 0/*IPPROTO_UDP*/);
if(s < 0) {
syslog(LOG_ERR, "%s: socket(): %m", "OpenAndConfPCPv6Socket");
return -1;
}
if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)) < 0) {
syslog(LOG_WARNING, "%s: setsockopt(SO_REUSEADDR): %m",
"OpenAndConfPCPv6Socket");
}
#ifdef IPV6_V6ONLY
/* force IPV6 only for IPV6 socket.
* see http://www.ietf.org/rfc/rfc3493.txt section 5.3 */
if(setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &i, sizeof(i)) < 0) {
syslog(LOG_WARNING, "%s: setsockopt(IPV6_V6ONLY): %m",
"OpenAndConfPCPv6Socket");
}
#endif
#ifdef IPV6_RECVPKTINFO
/* see RFC3542 */
if(setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO, &i, sizeof(i)) < 0) {
syslog(LOG_WARNING, "%s: setsockopt(IPV6_RECVPKTINFO): %m",
"OpenAndConfPCPv6Socket");
}
#endif
if(!set_non_blocking(s)) {
syslog(LOG_WARNING, "%s: set_non_blocking(): %m",
"OpenAndConfPCPv6Socket");
}
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(NATPMP_PORT);
addr.sin6_addr = ipv6_bind_addr;
if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
syslog(LOG_ERR, "%s: bind(): %m", "OpenAndConfPCPv6Socket");
close(s);
return -1;
}
return s;
}
#endif /*ENABLE_IPV6*/
#ifdef ENABLE_IPV6
void PCPSendUnsolicitedAnnounce(int * sockets, int n_sockets, int socket6)
#else /* IPv4 only */
void PCPSendUnsolicitedAnnounce(int * sockets, int n_sockets)
#endif
{
int i;
unsigned char buff[PCP_MIN_LEN];
pcp_info_t info;
ssize_t len;
struct sockaddr_in addr;
#ifdef ENABLE_IPV6
struct sockaddr_in6 addr6;
#endif /* ENABLE_IPV6 */
/* this is an Unsolicited ANNOUNCE response */
info.version = this_server_info.server_version;
info.opcode = PCP_OPCODE_ANNOUNCE;
info.result_code = PCP_SUCCESS;
info.lifetime = 0;
createPCPResponse(buff, &info);
/* Multicast PCP restart announcements are sent to
* 224.0.0.1:5350 and/or [ff02::1]:5350 */
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("224.0.0.1");
addr.sin_port = htons(5350);
for(i = 0; i < n_sockets; i++) {
len = sendto_or_schedule(sockets[i], buff, PCP_MIN_LEN, 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
if( len < 0 ) {
syslog(LOG_ERR, "PCPSendUnsolicitedAnnounce() sendto(): %m");
}
}
#ifdef ENABLE_IPV6
memset(&addr6, 0, sizeof(struct sockaddr_in6));
addr6.sin6_family = AF_INET6;
inet_pton(AF_INET6, "FF02::1", &(addr6.sin6_addr));
addr6.sin6_port = htons(5350);
len = sendto_or_schedule(socket6, buff, PCP_MIN_LEN, 0, (struct sockaddr *)&addr6, sizeof(struct sockaddr_in6));
if( len < 0 ) {
syslog(LOG_ERR, "PCPSendUnsolicitedAnnounce() IPv6 sendto(): %m");
}
#endif /* ENABLE_IPV6 */
}
#ifdef ENABLE_IPV6
void PCPPublicAddressChanged(int * sockets, int n_sockets, int socket6)
#else /* IPv4 only */
void PCPPublicAddressChanged(int * sockets, int n_sockets)
#endif
{
/* according to RFC 6887 8.5 :
* if the external IP address(es) of the NAT (controlled by
* the PCP server) changes, the Epoch time MUST be reset. */
epoch_origin = upnp_time();
#ifdef ENABLE_IPV6
PCPSendUnsolicitedAnnounce(sockets, n_sockets, socket6);
#else /* IPv4 Only */
PCPSendUnsolicitedAnnounce(sockets, n_sockets);
#endif
}
#endif /*ENABLE_PCP*/
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_864_0 |
crossvul-cpp_data_good_176_0 | /*
** kernel.c - Kernel module
**
** See Copyright Notice in mruby.h
*/
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/hash.h>
#include <mruby/class.h>
#include <mruby/proc.h>
#include <mruby/string.h>
#include <mruby/variable.h>
#include <mruby/error.h>
#include <mruby/istruct.h>
typedef enum {
NOEX_PUBLIC = 0x00,
NOEX_NOSUPER = 0x01,
NOEX_PRIVATE = 0x02,
NOEX_PROTECTED = 0x04,
NOEX_MASK = 0x06,
NOEX_BASIC = 0x08,
NOEX_UNDEF = NOEX_NOSUPER,
NOEX_MODFUNC = 0x12,
NOEX_SUPER = 0x20,
NOEX_VCALL = 0x40,
NOEX_RESPONDS = 0x80
} mrb_method_flag_t;
MRB_API mrb_bool
mrb_func_basic_p(mrb_state *mrb, mrb_value obj, mrb_sym mid, mrb_func_t func)
{
mrb_method_t m = mrb_method_search(mrb, mrb_class(mrb, obj), mid);
struct RProc *p;
if (MRB_METHOD_UNDEF_P(m)) return FALSE;
if (MRB_METHOD_FUNC_P(m))
return MRB_METHOD_FUNC(m) == func;
p = MRB_METHOD_PROC(m);
if (MRB_PROC_CFUNC_P(p) && (MRB_PROC_CFUNC(p) == func))
return TRUE;
return FALSE;
}
static mrb_bool
mrb_obj_basic_to_s_p(mrb_state *mrb, mrb_value obj)
{
return mrb_func_basic_p(mrb, obj, mrb_intern_lit(mrb, "to_s"), mrb_any_to_s);
}
/* 15.3.1.3.17 */
/*
* call-seq:
* obj.inspect -> string
*
* Returns a string containing a human-readable representation of
* <i>obj</i>. If not overridden and no instance variables, uses the
* <code>to_s</code> method to generate the string.
* <i>obj</i>. If not overridden, uses the <code>to_s</code> method to
* generate the string.
*
* [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
* Time.new.inspect #=> "2008-03-08 19:43:39 +0900"
*/
MRB_API mrb_value
mrb_obj_inspect(mrb_state *mrb, mrb_value obj)
{
if ((mrb_type(obj) == MRB_TT_OBJECT) && mrb_obj_basic_to_s_p(mrb, obj)) {
return mrb_obj_iv_inspect(mrb, mrb_obj_ptr(obj));
}
return mrb_any_to_s(mrb, obj);
}
/* 15.3.1.3.2 */
/*
* call-seq:
* obj === other -> true or false
*
* Case Equality---For class <code>Object</code>, effectively the same
* as calling <code>#==</code>, but typically overridden by descendants
* to provide meaningful semantics in <code>case</code> statements.
*/
static mrb_value
mrb_equal_m(mrb_state *mrb, mrb_value self)
{
mrb_value arg;
mrb_get_args(mrb, "o", &arg);
return mrb_bool_value(mrb_equal(mrb, self, arg));
}
/* 15.3.1.3.3 */
/* 15.3.1.3.33 */
/*
* Document-method: __id__
* Document-method: object_id
*
* call-seq:
* obj.__id__ -> fixnum
* obj.object_id -> fixnum
*
* Returns an integer identifier for <i>obj</i>. The same number will
* be returned on all calls to <code>id</code> for a given object, and
* no two active objects will share an id.
* <code>Object#object_id</code> is a different concept from the
* <code>:name</code> notation, which returns the symbol id of
* <code>name</code>. Replaces the deprecated <code>Object#id</code>.
*/
mrb_value
mrb_obj_id_m(mrb_state *mrb, mrb_value self)
{
return mrb_fixnum_value(mrb_obj_id(self));
}
/* 15.3.1.2.2 */
/* 15.3.1.2.5 */
/* 15.3.1.3.6 */
/* 15.3.1.3.25 */
/*
* call-seq:
* block_given? -> true or false
* iterator? -> true or false
*
* Returns <code>true</code> if <code>yield</code> would execute a
* block in the current context. The <code>iterator?</code> form
* is mildly deprecated.
*
* def try
* if block_given?
* yield
* else
* "no block"
* end
* end
* try #=> "no block"
* try { "hello" } #=> "hello"
* try do "hello" end #=> "hello"
*/
static mrb_value
mrb_f_block_given_p_m(mrb_state *mrb, mrb_value self)
{
mrb_callinfo *ci = &mrb->c->ci[-1];
mrb_callinfo *cibase = mrb->c->cibase;
mrb_value *bp;
struct RProc *p;
if (ci <= cibase) {
/* toplevel does not have block */
return mrb_false_value();
}
p = ci->proc;
/* search method/class/module proc */
while (p) {
if (MRB_PROC_SCOPE_P(p)) break;
p = p->upper;
}
if (p == NULL) return mrb_false_value();
/* search ci corresponding to proc */
while (cibase < ci) {
if (ci->proc == p) break;
ci--;
}
if (ci == cibase) {
return mrb_false_value();
}
else if (ci->env) {
struct REnv *e = ci->env;
int bidx;
/* top-level does not have block slot (always false) */
if (e->stack == mrb->c->stbase)
return mrb_false_value();
/* use saved block arg position */
bidx = MRB_ENV_BIDX(e);
/* bidx may be useless (e.g. define_method) */
if (bidx >= MRB_ENV_STACK_LEN(e))
return mrb_false_value();
bp = &e->stack[bidx];
}
else {
bp = ci[1].stackent+1;
if (ci->argc >= 0) {
bp += ci->argc;
}
else {
bp++;
}
}
if (mrb_nil_p(*bp))
return mrb_false_value();
return mrb_true_value();
}
/* 15.3.1.3.7 */
/*
* call-seq:
* obj.class -> class
*
* Returns the class of <i>obj</i>. This method must always be
* called with an explicit receiver, as <code>class</code> is also a
* reserved word in Ruby.
*
* 1.class #=> Fixnum
* self.class #=> Object
*/
static mrb_value
mrb_obj_class_m(mrb_state *mrb, mrb_value self)
{
return mrb_obj_value(mrb_obj_class(mrb, self));
}
static struct RClass*
mrb_singleton_class_clone(mrb_state *mrb, mrb_value obj)
{
struct RClass *klass = mrb_basic_ptr(obj)->c;
if (klass->tt != MRB_TT_SCLASS)
return klass;
else {
/* copy singleton(unnamed) class */
struct RClass *clone = (struct RClass*)mrb_obj_alloc(mrb, klass->tt, mrb->class_class);
switch (mrb_type(obj)) {
case MRB_TT_CLASS:
case MRB_TT_SCLASS:
break;
default:
clone->c = mrb_singleton_class_clone(mrb, mrb_obj_value(klass));
break;
}
clone->super = klass->super;
if (klass->iv) {
mrb_iv_copy(mrb, mrb_obj_value(clone), mrb_obj_value(klass));
mrb_obj_iv_set(mrb, (struct RObject*)clone, mrb_intern_lit(mrb, "__attached__"), obj);
}
if (klass->mt) {
clone->mt = kh_copy(mt, mrb, klass->mt);
}
else {
clone->mt = kh_init(mt, mrb);
}
clone->tt = MRB_TT_SCLASS;
return clone;
}
}
static void
copy_class(mrb_state *mrb, mrb_value dst, mrb_value src)
{
struct RClass *dc = mrb_class_ptr(dst);
struct RClass *sc = mrb_class_ptr(src);
/* if the origin is not the same as the class, then the origin and
the current class need to be copied */
if (sc->flags & MRB_FLAG_IS_PREPENDED) {
struct RClass *c0 = sc->super;
struct RClass *c1 = dc;
/* copy prepended iclasses */
while (!(c0->flags & MRB_FLAG_IS_ORIGIN)) {
c1->super = mrb_class_ptr(mrb_obj_dup(mrb, mrb_obj_value(c0)));
c1 = c1->super;
c0 = c0->super;
}
c1->super = mrb_class_ptr(mrb_obj_dup(mrb, mrb_obj_value(c0)));
c1->super->flags |= MRB_FLAG_IS_ORIGIN;
}
if (sc->mt) {
dc->mt = kh_copy(mt, mrb, sc->mt);
}
else {
dc->mt = kh_init(mt, mrb);
}
dc->super = sc->super;
MRB_SET_INSTANCE_TT(dc, MRB_INSTANCE_TT(sc));
}
static void
init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_ICLASS:
copy_class(mrb, dest, obj);
return;
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
/* 15.3.1.3.8 */
/*
* call-seq:
* obj.clone -> an_object
*
* Produces a shallow copy of <i>obj</i>---the instance variables of
* <i>obj</i> are copied, but not the objects they reference. Copies
* the frozen state of <i>obj</i>. See also the discussion
* under <code>Object#dup</code>.
*
* class Klass
* attr_accessor :str
* end
* s1 = Klass.new #=> #<Klass:0x401b3a38>
* s1.str = "Hello" #=> "Hello"
* s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello">
* s2.str[1,4] = "i" #=> "i"
* s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
* s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"
*
* This method may have class-specific behavior. If so, that
* behavior will be documented under the #+initialize_copy+ method of
* the class.
*
* Some Class(True False Nil Symbol Fixnum Float) Object cannot clone.
*/
MRB_API mrb_value
mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;
return clone;
}
/* 15.3.1.3.9 */
/*
* call-seq:
* obj.dup -> an_object
*
* Produces a shallow copy of <i>obj</i>---the instance variables of
* <i>obj</i> are copied, but not the objects they reference.
* <code>dup</code> copies the frozen state of <i>obj</i>. See also
* the discussion under <code>Object#clone</code>. In general,
* <code>clone</code> and <code>dup</code> may have different semantics
* in descendant classes. While <code>clone</code> is used to duplicate
* an object, including its internal state, <code>dup</code> typically
* uses the class of the descendant object to create the new instance.
*
* This method may have class-specific behavior. If so, that
* behavior will be documented under the #+initialize_copy+ method of
* the class.
*/
MRB_API mrb_value
mrb_obj_dup(mrb_state *mrb, mrb_value obj)
{
struct RBasic *p;
mrb_value dup;
if (mrb_immediate_p(obj)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't dup %S", obj);
}
if (mrb_type(obj) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't dup singleton class");
}
p = mrb_obj_alloc(mrb, mrb_type(obj), mrb_obj_class(mrb, obj));
dup = mrb_obj_value(p);
init_copy(mrb, dup, obj);
return dup;
}
static mrb_value
mrb_obj_extend(mrb_state *mrb, mrb_int argc, mrb_value *argv, mrb_value obj)
{
mrb_int i;
if (argc == 0) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (at least 1)");
}
for (i = 0; i < argc; i++) {
mrb_check_type(mrb, argv[i], MRB_TT_MODULE);
}
while (argc--) {
mrb_funcall(mrb, argv[argc], "extend_object", 1, obj);
mrb_funcall(mrb, argv[argc], "extended", 1, obj);
}
return obj;
}
/* 15.3.1.3.13 */
/*
* call-seq:
* obj.extend(module, ...) -> obj
*
* Adds to _obj_ the instance methods from each module given as a
* parameter.
*
* module Mod
* def hello
* "Hello from Mod.\n"
* end
* end
*
* class Klass
* def hello
* "Hello from Klass.\n"
* end
* end
*
* k = Klass.new
* k.hello #=> "Hello from Klass.\n"
* k.extend(Mod) #=> #<Klass:0x401b3bc8>
* k.hello #=> "Hello from Mod.\n"
*/
static mrb_value
mrb_obj_extend_m(mrb_state *mrb, mrb_value self)
{
mrb_value *argv;
mrb_int argc;
mrb_get_args(mrb, "*", &argv, &argc);
return mrb_obj_extend(mrb, argc, argv, self);
}
static mrb_value
mrb_obj_freeze(mrb_state *mrb, mrb_value self)
{
struct RBasic *b;
switch (mrb_type(self)) {
case MRB_TT_FALSE:
case MRB_TT_TRUE:
case MRB_TT_FIXNUM:
case MRB_TT_SYMBOL:
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#endif
return self;
default:
break;
}
b = mrb_basic_ptr(self);
if (!MRB_FROZEN_P(b)) {
MRB_SET_FROZEN_FLAG(b);
}
return self;
}
static mrb_value
mrb_obj_frozen(mrb_state *mrb, mrb_value self)
{
struct RBasic *b;
switch (mrb_type(self)) {
case MRB_TT_FALSE:
case MRB_TT_TRUE:
case MRB_TT_FIXNUM:
case MRB_TT_SYMBOL:
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#endif
return mrb_true_value();
default:
break;
}
b = mrb_basic_ptr(self);
if (!MRB_FROZEN_P(b)) {
return mrb_false_value();
}
return mrb_true_value();
}
/* 15.3.1.3.15 */
/*
* call-seq:
* obj.hash -> fixnum
*
* Generates a <code>Fixnum</code> hash value for this object. This
* function must have the property that <code>a.eql?(b)</code> implies
* <code>a.hash == b.hash</code>. The hash value is used by class
* <code>Hash</code>. Any hash value that exceeds the capacity of a
* <code>Fixnum</code> will be truncated before being used.
*/
MRB_API mrb_value
mrb_obj_hash(mrb_state *mrb, mrb_value self)
{
return mrb_fixnum_value(mrb_obj_id(self));
}
/* 15.3.1.3.16 */
static mrb_value
mrb_obj_init_copy(mrb_state *mrb, mrb_value self)
{
mrb_value orig;
mrb_get_args(mrb, "o", &orig);
if (mrb_obj_equal(mrb, self, orig)) return self;
if ((mrb_type(self) != mrb_type(orig)) || (mrb_obj_class(mrb, self) != mrb_obj_class(mrb, orig))) {
mrb_raise(mrb, E_TYPE_ERROR, "initialize_copy should take same class object");
}
return self;
}
MRB_API mrb_bool
mrb_obj_is_instance_of(mrb_state *mrb, mrb_value obj, struct RClass* c)
{
if (mrb_obj_class(mrb, obj) == c) return TRUE;
return FALSE;
}
/* 15.3.1.3.19 */
/*
* call-seq:
* obj.instance_of?(class) -> true or false
*
* Returns <code>true</code> if <i>obj</i> is an instance of the given
* class. See also <code>Object#kind_of?</code>.
*/
static mrb_value
obj_is_instance_of(mrb_state *mrb, mrb_value self)
{
mrb_value arg;
mrb_get_args(mrb, "C", &arg);
return mrb_bool_value(mrb_obj_is_instance_of(mrb, self, mrb_class_ptr(arg)));
}
/* 15.3.1.3.20 */
/*
* call-seq:
* obj.instance_variable_defined?(symbol) -> true or false
*
* Returns <code>true</code> if the given instance variable is
* defined in <i>obj</i>.
*
* class Fred
* def initialize(p1, p2)
* @a, @b = p1, p2
* end
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_defined?(:@a) #=> true
* fred.instance_variable_defined?("@b") #=> true
* fred.instance_variable_defined?("@c") #=> false
*/
static mrb_value
mrb_obj_ivar_defined(mrb_state *mrb, mrb_value self)
{
mrb_sym sym;
mrb_get_args(mrb, "n", &sym);
mrb_iv_check(mrb, sym);
return mrb_bool_value(mrb_iv_defined(mrb, self, sym));
}
/* 15.3.1.3.21 */
/*
* call-seq:
* obj.instance_variable_get(symbol) -> obj
*
* Returns the value of the given instance variable, or nil if the
* instance variable is not set. The <code>@</code> part of the
* variable name should be included for regular instance
* variables. Throws a <code>NameError</code> exception if the
* supplied symbol is not valid as an instance variable name.
*
* class Fred
* def initialize(p1, p2)
* @a, @b = p1, p2
* end
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_get(:@a) #=> "cat"
* fred.instance_variable_get("@b") #=> 99
*/
static mrb_value
mrb_obj_ivar_get(mrb_state *mrb, mrb_value self)
{
mrb_sym iv_name;
mrb_get_args(mrb, "n", &iv_name);
mrb_iv_check(mrb, iv_name);
return mrb_iv_get(mrb, self, iv_name);
}
/* 15.3.1.3.22 */
/*
* call-seq:
* obj.instance_variable_set(symbol, obj) -> obj
*
* Sets the instance variable names by <i>symbol</i> to
* <i>object</i>, thereby frustrating the efforts of the class's
* author to attempt to provide proper encapsulation. The variable
* did not have to exist prior to this call.
*
* class Fred
* def initialize(p1, p2)
* @a, @b = p1, p2
* end
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_set(:@a, 'dog') #=> "dog"
* fred.instance_variable_set(:@c, 'cat') #=> "cat"
* fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
*/
static mrb_value
mrb_obj_ivar_set(mrb_state *mrb, mrb_value self)
{
mrb_sym iv_name;
mrb_value val;
mrb_get_args(mrb, "no", &iv_name, &val);
mrb_iv_check(mrb, iv_name);
mrb_iv_set(mrb, self, iv_name, val);
return val;
}
/* 15.3.1.3.24 */
/* 15.3.1.3.26 */
/*
* call-seq:
* obj.is_a?(class) -> true or false
* obj.kind_of?(class) -> true or false
*
* Returns <code>true</code> if <i>class</i> is the class of
* <i>obj</i>, or if <i>class</i> is one of the superclasses of
* <i>obj</i> or modules included in <i>obj</i>.
*
* module M; end
* class A
* include M
* end
* class B < A; end
* class C < B; end
* b = B.new
* b.instance_of? A #=> false
* b.instance_of? B #=> true
* b.instance_of? C #=> false
* b.instance_of? M #=> false
* b.kind_of? A #=> true
* b.kind_of? B #=> true
* b.kind_of? C #=> false
* b.kind_of? M #=> true
*/
static mrb_value
mrb_obj_is_kind_of_m(mrb_state *mrb, mrb_value self)
{
mrb_value arg;
mrb_get_args(mrb, "C", &arg);
return mrb_bool_value(mrb_obj_is_kind_of(mrb, self, mrb_class_ptr(arg)));
}
KHASH_DECLARE(st, mrb_sym, char, FALSE)
KHASH_DEFINE(st, mrb_sym, char, FALSE, kh_int_hash_func, kh_int_hash_equal)
static void
method_entry_loop(mrb_state *mrb, struct RClass* klass, khash_t(st)* set)
{
khint_t i;
khash_t(mt) *h = klass->mt;
if (!h || kh_size(h) == 0) return;
for (i=0;i<kh_end(h);i++) {
if (kh_exist(h, i)) {
mrb_method_t m = kh_value(h, i);
if (MRB_METHOD_UNDEF_P(m)) continue;
kh_put(st, mrb, set, kh_key(h, i));
}
}
}
mrb_value
mrb_class_instance_method_list(mrb_state *mrb, mrb_bool recur, struct RClass* klass, int obj)
{
khint_t i;
mrb_value ary;
mrb_bool prepended = FALSE;
struct RClass* oldklass;
khash_t(st)* set = kh_init(st, mrb);
if (!recur && (klass->flags & MRB_FLAG_IS_PREPENDED)) {
MRB_CLASS_ORIGIN(klass);
prepended = TRUE;
}
oldklass = 0;
while (klass && (klass != oldklass)) {
method_entry_loop(mrb, klass, set);
if ((klass->tt == MRB_TT_ICLASS && !prepended) ||
(klass->tt == MRB_TT_SCLASS)) {
}
else {
if (!recur) break;
}
oldklass = klass;
klass = klass->super;
}
ary = mrb_ary_new_capa(mrb, kh_size(set));
for (i=0;i<kh_end(set);i++) {
if (kh_exist(set, i)) {
mrb_ary_push(mrb, ary, mrb_symbol_value(kh_key(set, i)));
}
}
kh_destroy(st, mrb, set);
return ary;
}
static mrb_value
mrb_obj_singleton_methods(mrb_state *mrb, mrb_bool recur, mrb_value obj)
{
khint_t i;
mrb_value ary;
struct RClass* klass;
khash_t(st)* set = kh_init(st, mrb);
klass = mrb_class(mrb, obj);
if (klass && (klass->tt == MRB_TT_SCLASS)) {
method_entry_loop(mrb, klass, set);
klass = klass->super;
}
if (recur) {
while (klass && ((klass->tt == MRB_TT_SCLASS) || (klass->tt == MRB_TT_ICLASS))) {
method_entry_loop(mrb, klass, set);
klass = klass->super;
}
}
ary = mrb_ary_new(mrb);
for (i=0;i<kh_end(set);i++) {
if (kh_exist(set, i)) {
mrb_ary_push(mrb, ary, mrb_symbol_value(kh_key(set, i)));
}
}
kh_destroy(st, mrb, set);
return ary;
}
static mrb_value
mrb_obj_methods(mrb_state *mrb, mrb_bool recur, mrb_value obj, mrb_method_flag_t flag)
{
return mrb_class_instance_method_list(mrb, recur, mrb_class(mrb, obj), 0);
}
/* 15.3.1.3.31 */
/*
* call-seq:
* obj.methods -> array
*
* Returns a list of the names of methods publicly accessible in
* <i>obj</i>. This will include all the methods accessible in
* <i>obj</i>'s ancestors.
*
* class Klass
* def kMethod()
* end
* end
* k = Klass.new
* k.methods[0..9] #=> [:kMethod, :respond_to?, :nil?, :is_a?,
* # :class, :instance_variable_set,
* # :methods, :extend, :__send__, :instance_eval]
* k.methods.length #=> 42
*/
static mrb_value
mrb_obj_methods_m(mrb_state *mrb, mrb_value self)
{
mrb_bool recur = TRUE;
mrb_get_args(mrb, "|b", &recur);
return mrb_obj_methods(mrb, recur, self, (mrb_method_flag_t)0); /* everything but private */
}
/* 15.3.1.3.32 */
/*
* call_seq:
* nil.nil? -> true
* <anything_else>.nil? -> false
*
* Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
*/
static mrb_value
mrb_false(mrb_state *mrb, mrb_value self)
{
return mrb_false_value();
}
/* 15.3.1.3.36 */
/*
* call-seq:
* obj.private_methods(all=true) -> array
*
* Returns the list of private methods accessible to <i>obj</i>. If
* the <i>all</i> parameter is set to <code>false</code>, only those methods
* in the receiver will be listed.
*/
static mrb_value
mrb_obj_private_methods(mrb_state *mrb, mrb_value self)
{
mrb_bool recur = TRUE;
mrb_get_args(mrb, "|b", &recur);
return mrb_obj_methods(mrb, recur, self, NOEX_PRIVATE); /* private attribute not define */
}
/* 15.3.1.3.37 */
/*
* call-seq:
* obj.protected_methods(all=true) -> array
*
* Returns the list of protected methods accessible to <i>obj</i>. If
* the <i>all</i> parameter is set to <code>false</code>, only those methods
* in the receiver will be listed.
*/
static mrb_value
mrb_obj_protected_methods(mrb_state *mrb, mrb_value self)
{
mrb_bool recur = TRUE;
mrb_get_args(mrb, "|b", &recur);
return mrb_obj_methods(mrb, recur, self, NOEX_PROTECTED); /* protected attribute not define */
}
/* 15.3.1.3.38 */
/*
* call-seq:
* obj.public_methods(all=true) -> array
*
* Returns the list of public methods accessible to <i>obj</i>. If
* the <i>all</i> parameter is set to <code>false</code>, only those methods
* in the receiver will be listed.
*/
static mrb_value
mrb_obj_public_methods(mrb_state *mrb, mrb_value self)
{
mrb_bool recur = TRUE;
mrb_get_args(mrb, "|b", &recur);
return mrb_obj_methods(mrb, recur, self, NOEX_PUBLIC); /* public attribute not define */
}
/* 15.3.1.2.12 */
/* 15.3.1.3.40 */
/*
* call-seq:
* raise
* raise(string)
* raise(exception [, string])
*
* With no arguments, raises a <code>RuntimeError</code>
* With a single +String+ argument, raises a
* +RuntimeError+ with the string as a message. Otherwise,
* the first parameter should be the name of an +Exception+
* class (or an object that returns an +Exception+ object when sent
* an +exception+ message). The optional second parameter sets the
* message associated with the exception, and the third parameter is an
* array of callback information. Exceptions are caught by the
* +rescue+ clause of <code>begin...end</code> blocks.
*
* raise "Failed to create socket"
* raise ArgumentError, "No parameters", caller
*/
MRB_API mrb_value
mrb_f_raise(mrb_state *mrb, mrb_value self)
{
mrb_value a[2], exc;
mrb_int argc;
argc = mrb_get_args(mrb, "|oo", &a[0], &a[1]);
switch (argc) {
case 0:
mrb_raise(mrb, E_RUNTIME_ERROR, "");
break;
case 1:
if (mrb_string_p(a[0])) {
a[1] = a[0];
argc = 2;
a[0] = mrb_obj_value(E_RUNTIME_ERROR);
}
/* fall through */
default:
exc = mrb_make_exception(mrb, argc, a);
mrb_exc_raise(mrb, exc);
break;
}
return mrb_nil_value(); /* not reached */
}
static mrb_value
mrb_krn_class_defined(mrb_state *mrb, mrb_value self)
{
mrb_value str;
mrb_get_args(mrb, "S", &str);
return mrb_bool_value(mrb_class_defined(mrb, RSTRING_PTR(str)));
}
/* 15.3.1.3.41 */
/*
* call-seq:
* obj.remove_instance_variable(symbol) -> obj
*
* Removes the named instance variable from <i>obj</i>, returning that
* variable's value.
*
* class Dummy
* attr_reader :var
* def initialize
* @var = 99
* end
* def remove
* remove_instance_variable(:@var)
* end
* end
* d = Dummy.new
* d.var #=> 99
* d.remove #=> 99
* d.var #=> nil
*/
static mrb_value
mrb_obj_remove_instance_variable(mrb_state *mrb, mrb_value self)
{
mrb_sym sym;
mrb_value val;
mrb_get_args(mrb, "n", &sym);
mrb_iv_check(mrb, sym);
val = mrb_iv_remove(mrb, self, sym);
if (mrb_undef_p(val)) {
mrb_name_error(mrb, sym, "instance variable %S not defined", mrb_sym2str(mrb, sym));
}
return val;
}
void
mrb_method_missing(mrb_state *mrb, mrb_sym name, mrb_value self, mrb_value args)
{
mrb_no_method_error(mrb, name, args, "undefined method '%S'", mrb_sym2str(mrb, name));
}
/* 15.3.1.3.30 */
/*
* call-seq:
* obj.method_missing(symbol [, *args] ) -> result
*
* Invoked by Ruby when <i>obj</i> is sent a message it cannot handle.
* <i>symbol</i> is the symbol for the method called, and <i>args</i>
* are any arguments that were passed to it. By default, the interpreter
* raises an error when this method is called. However, it is possible
* to override the method to provide more dynamic behavior.
* If it is decided that a particular method should not be handled, then
* <i>super</i> should be called, so that ancestors can pick up the
* missing method.
* The example below creates
* a class <code>Roman</code>, which responds to methods with names
* consisting of roman numerals, returning the corresponding integer
* values.
*
* class Roman
* def romanToInt(str)
* # ...
* end
* def method_missing(methId)
* str = methId.id2name
* romanToInt(str)
* end
* end
*
* r = Roman.new
* r.iv #=> 4
* r.xxiii #=> 23
* r.mm #=> 2000
*/
#ifdef MRB_DEFAULT_METHOD_MISSING
static mrb_value
mrb_obj_missing(mrb_state *mrb, mrb_value mod)
{
mrb_sym name;
mrb_value *a;
mrb_int alen;
mrb_get_args(mrb, "n*!", &name, &a, &alen);
mrb_method_missing(mrb, name, mod, mrb_ary_new_from_values(mrb, alen, a));
/* not reached */
return mrb_nil_value();
}
#endif
static inline mrb_bool
basic_obj_respond_to(mrb_state *mrb, mrb_value obj, mrb_sym id, int pub)
{
return mrb_respond_to(mrb, obj, id);
}
/* 15.3.1.3.43 */
/*
* call-seq:
* obj.respond_to?(symbol, include_private=false) -> true or false
*
* Returns +true+ if _obj_ responds to the given
* method. Private methods are included in the search only if the
* optional second parameter evaluates to +true+.
*
* If the method is not implemented,
* as Process.fork on Windows, File.lchmod on GNU/Linux, etc.,
* false is returned.
*
* If the method is not defined, <code>respond_to_missing?</code>
* method is called and the result is returned.
*/
static mrb_value
obj_respond_to(mrb_state *mrb, mrb_value self)
{
mrb_value mid;
mrb_sym id, rtm_id;
mrb_bool priv = FALSE, respond_to_p = TRUE;
mrb_get_args(mrb, "o|b", &mid, &priv);
if (mrb_symbol_p(mid)) {
id = mrb_symbol(mid);
}
else {
mrb_value tmp;
if (mrb_string_p(mid)) {
tmp = mrb_check_intern_str(mrb, mid);
}
else {
tmp = mrb_check_string_type(mrb, mid);
if (mrb_nil_p(tmp)) {
tmp = mrb_inspect(mrb, mid);
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a symbol", tmp);
}
tmp = mrb_check_intern_str(mrb, tmp);
}
if (mrb_nil_p(tmp)) {
respond_to_p = FALSE;
}
else {
id = mrb_symbol(tmp);
}
}
if (respond_to_p) {
respond_to_p = basic_obj_respond_to(mrb, self, id, !priv);
}
if (!respond_to_p) {
rtm_id = mrb_intern_lit(mrb, "respond_to_missing?");
if (basic_obj_respond_to(mrb, self, rtm_id, !priv)) {
mrb_value args[2], v;
args[0] = mid;
args[1] = mrb_bool_value(priv);
v = mrb_funcall_argv(mrb, self, rtm_id, 2, args);
return mrb_bool_value(mrb_bool(v));
}
}
return mrb_bool_value(respond_to_p);
}
/* 15.3.1.3.45 */
/*
* call-seq:
* obj.singleton_methods(all=true) -> array
*
* Returns an array of the names of singleton methods for <i>obj</i>.
* If the optional <i>all</i> parameter is true, the list will include
* methods in modules included in <i>obj</i>.
* Only public and protected singleton methods are returned.
*
* module Other
* def three() end
* end
*
* class Single
* def Single.four() end
* end
*
* a = Single.new
*
* def a.one()
* end
*
* class << a
* include Other
* def two()
* end
* end
*
* Single.singleton_methods #=> [:four]
* a.singleton_methods(false) #=> [:two, :one]
* a.singleton_methods #=> [:two, :one, :three]
*/
static mrb_value
mrb_obj_singleton_methods_m(mrb_state *mrb, mrb_value self)
{
mrb_bool recur = TRUE;
mrb_get_args(mrb, "|b", &recur);
return mrb_obj_singleton_methods(mrb, recur, self);
}
static mrb_value
mod_define_singleton_method(mrb_state *mrb, mrb_value self)
{
struct RProc *p;
mrb_method_t m;
mrb_sym mid;
mrb_value blk = mrb_nil_value();
mrb_get_args(mrb, "n&", &mid, &blk);
if (mrb_nil_p(blk)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
p = (struct RProc*)mrb_obj_alloc(mrb, MRB_TT_PROC, mrb->proc_class);
mrb_proc_copy(p, mrb_proc_ptr(blk));
p->flags |= MRB_PROC_STRICT;
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, mrb_class_ptr(mrb_singleton_class(mrb, self)), mid, m);
return mrb_symbol_value(mid);
}
static mrb_value
mrb_obj_ceqq(mrb_state *mrb, mrb_value self)
{
mrb_value v;
mrb_int i, len;
mrb_sym eqq = mrb_intern_lit(mrb, "===");
mrb_value ary = mrb_ary_splat(mrb, self);
mrb_get_args(mrb, "o", &v);
len = RARRAY_LEN(ary);
for (i=0; i<len; i++) {
mrb_value c = mrb_funcall_argv(mrb, mrb_ary_entry(ary, i), eqq, 1, &v);
if (mrb_test(c)) return mrb_true_value();
}
return mrb_false_value();
}
/* 15.3.1.2.7 */
/*
* call-seq:
* local_variables -> array
*
* Returns the names of local variables in the current scope.
*
* [mruby limitation]
* If variable symbol information was stripped out from
* compiled binary files using `mruby-strip -l`, this
* method always returns an empty array.
*/
static mrb_value
mrb_local_variables(mrb_state *mrb, mrb_value self)
{
struct RProc *proc;
mrb_irep *irep;
mrb_value vars;
size_t i;
proc = mrb->c->ci[-1].proc;
if (MRB_PROC_CFUNC_P(proc)) {
return mrb_ary_new(mrb);
}
vars = mrb_hash_new(mrb);
while (proc) {
if (MRB_PROC_CFUNC_P(proc)) break;
irep = proc->body.irep;
if (!irep->lv) break;
for (i = 0; i + 1 < irep->nlocals; ++i) {
if (irep->lv[i].name) {
mrb_hash_set(mrb, vars, mrb_symbol_value(irep->lv[i].name), mrb_true_value());
}
}
if (!MRB_PROC_ENV_P(proc)) break;
proc = proc->upper;
//if (MRB_PROC_SCOPE_P(proc)) break;
if (!proc->c) break;
}
return mrb_hash_keys(mrb, vars);
}
mrb_value mrb_obj_equal_m(mrb_state *mrb, mrb_value);
void
mrb_init_kernel(mrb_state *mrb)
{
struct RClass *krn;
mrb->kernel_module = krn = mrb_define_module(mrb, "Kernel"); /* 15.3.1 */
mrb_define_class_method(mrb, krn, "block_given?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.2.2 */
mrb_define_class_method(mrb, krn, "global_variables", mrb_f_global_variables, MRB_ARGS_NONE()); /* 15.3.1.2.4 */
mrb_define_class_method(mrb, krn, "iterator?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.2.5 */
mrb_define_class_method(mrb, krn, "local_variables", mrb_local_variables, MRB_ARGS_NONE()); /* 15.3.1.2.7 */
; /* 15.3.1.2.11 */
mrb_define_class_method(mrb, krn, "raise", mrb_f_raise, MRB_ARGS_OPT(2)); /* 15.3.1.2.12 */
mrb_define_method(mrb, krn, "singleton_class", mrb_singleton_class, MRB_ARGS_NONE());
mrb_define_method(mrb, krn, "===", mrb_equal_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.2 */
mrb_define_method(mrb, krn, "block_given?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.3.6 */
mrb_define_method(mrb, krn, "class", mrb_obj_class_m, MRB_ARGS_NONE()); /* 15.3.1.3.7 */
mrb_define_method(mrb, krn, "clone", mrb_obj_clone, MRB_ARGS_NONE()); /* 15.3.1.3.8 */
mrb_define_method(mrb, krn, "dup", mrb_obj_dup, MRB_ARGS_NONE()); /* 15.3.1.3.9 */
mrb_define_method(mrb, krn, "eql?", mrb_obj_equal_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.10 */
mrb_define_method(mrb, krn, "equal?", mrb_obj_equal_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.11 */
mrb_define_method(mrb, krn, "extend", mrb_obj_extend_m, MRB_ARGS_ANY()); /* 15.3.1.3.13 */
mrb_define_method(mrb, krn, "freeze", mrb_obj_freeze, MRB_ARGS_NONE());
mrb_define_method(mrb, krn, "frozen?", mrb_obj_frozen, MRB_ARGS_NONE());
mrb_define_method(mrb, krn, "global_variables", mrb_f_global_variables, MRB_ARGS_NONE()); /* 15.3.1.3.14 */
mrb_define_method(mrb, krn, "hash", mrb_obj_hash, MRB_ARGS_NONE()); /* 15.3.1.3.15 */
mrb_define_method(mrb, krn, "initialize_copy", mrb_obj_init_copy, MRB_ARGS_REQ(1)); /* 15.3.1.3.16 */
mrb_define_method(mrb, krn, "inspect", mrb_obj_inspect, MRB_ARGS_NONE()); /* 15.3.1.3.17 */
mrb_define_method(mrb, krn, "instance_of?", obj_is_instance_of, MRB_ARGS_REQ(1)); /* 15.3.1.3.19 */
mrb_define_method(mrb, krn, "instance_variable_defined?", mrb_obj_ivar_defined, MRB_ARGS_REQ(1)); /* 15.3.1.3.20 */
mrb_define_method(mrb, krn, "instance_variable_get", mrb_obj_ivar_get, MRB_ARGS_REQ(1)); /* 15.3.1.3.21 */
mrb_define_method(mrb, krn, "instance_variable_set", mrb_obj_ivar_set, MRB_ARGS_REQ(2)); /* 15.3.1.3.22 */
mrb_define_method(mrb, krn, "instance_variables", mrb_obj_instance_variables, MRB_ARGS_NONE()); /* 15.3.1.3.23 */
mrb_define_method(mrb, krn, "is_a?", mrb_obj_is_kind_of_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.24 */
mrb_define_method(mrb, krn, "iterator?", mrb_f_block_given_p_m, MRB_ARGS_NONE()); /* 15.3.1.3.25 */
mrb_define_method(mrb, krn, "kind_of?", mrb_obj_is_kind_of_m, MRB_ARGS_REQ(1)); /* 15.3.1.3.26 */
mrb_define_method(mrb, krn, "local_variables", mrb_local_variables, MRB_ARGS_NONE()); /* 15.3.1.3.28 */
#ifdef MRB_DEFAULT_METHOD_MISSING
mrb_define_method(mrb, krn, "method_missing", mrb_obj_missing, MRB_ARGS_ANY()); /* 15.3.1.3.30 */
#endif
mrb_define_method(mrb, krn, "methods", mrb_obj_methods_m, MRB_ARGS_OPT(1)); /* 15.3.1.3.31 */
mrb_define_method(mrb, krn, "nil?", mrb_false, MRB_ARGS_NONE()); /* 15.3.1.3.32 */
mrb_define_method(mrb, krn, "object_id", mrb_obj_id_m, MRB_ARGS_NONE()); /* 15.3.1.3.33 */
mrb_define_method(mrb, krn, "private_methods", mrb_obj_private_methods, MRB_ARGS_OPT(1)); /* 15.3.1.3.36 */
mrb_define_method(mrb, krn, "protected_methods", mrb_obj_protected_methods, MRB_ARGS_OPT(1)); /* 15.3.1.3.37 */
mrb_define_method(mrb, krn, "public_methods", mrb_obj_public_methods, MRB_ARGS_OPT(1)); /* 15.3.1.3.38 */
mrb_define_method(mrb, krn, "raise", mrb_f_raise, MRB_ARGS_ANY()); /* 15.3.1.3.40 */
mrb_define_method(mrb, krn, "remove_instance_variable", mrb_obj_remove_instance_variable,MRB_ARGS_REQ(1)); /* 15.3.1.3.41 */
mrb_define_method(mrb, krn, "respond_to?", obj_respond_to, MRB_ARGS_ANY()); /* 15.3.1.3.43 */
mrb_define_method(mrb, krn, "send", mrb_f_send, MRB_ARGS_ANY()); /* 15.3.1.3.44 */
mrb_define_method(mrb, krn, "singleton_methods", mrb_obj_singleton_methods_m, MRB_ARGS_OPT(1)); /* 15.3.1.3.45 */
mrb_define_method(mrb, krn, "define_singleton_method", mod_define_singleton_method, MRB_ARGS_ANY());
mrb_define_method(mrb, krn, "to_s", mrb_any_to_s, MRB_ARGS_NONE()); /* 15.3.1.3.46 */
mrb_define_method(mrb, krn, "__case_eqq", mrb_obj_ceqq, MRB_ARGS_REQ(1)); /* internal */
mrb_define_method(mrb, krn, "class_defined?", mrb_krn_class_defined, MRB_ARGS_REQ(1));
mrb_include_module(mrb, mrb->object_class, mrb->kernel_module);
mrb_alias_method(mrb, mrb->module_class, mrb_intern_lit(mrb, "dup"), mrb_intern_lit(mrb, "clone"));
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_176_0 |
crossvul-cpp_data_good_3960_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* USB IBM C-It Video Camera driver
*
* Supports Xirlink C-It Video Camera, IBM PC Camera,
* IBM NetCamera and Veo Stingray.
*
* Copyright (C) 2010 Hans de Goede <hdegoede@redhat.com>
*
* This driver is based on earlier work of:
*
* (C) Copyright 1999 Johannes Erdfelt
* (C) Copyright 1999 Randy Dunlap
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "xirlink-cit"
#include <linux/input.h>
#include "gspca.h"
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_DESCRIPTION("Xirlink C-IT");
MODULE_LICENSE("GPL");
/* FIXME we should autodetect this */
static int ibm_netcam_pro;
module_param(ibm_netcam_pro, int, 0);
MODULE_PARM_DESC(ibm_netcam_pro,
"Use IBM Netcamera Pro init sequences for Model 3 cams");
/* FIXME this should be handled through the V4L2 input selection API */
static int rca_input;
module_param(rca_input, int, 0644);
MODULE_PARM_DESC(rca_input,
"Use rca input instead of ccd sensor on Model 3 cams");
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct v4l2_ctrl *lighting;
u8 model;
#define CIT_MODEL0 0 /* bcd version 0.01 cams ie the xvp-500 */
#define CIT_MODEL1 1 /* The model 1 - 4 nomenclature comes from the old */
#define CIT_MODEL2 2 /* ibmcam driver */
#define CIT_MODEL3 3
#define CIT_MODEL4 4
#define CIT_IBM_NETCAM_PRO 5
u8 input_index;
u8 button_state;
u8 stop_on_control_change;
u8 sof_read;
u8 sof_len;
};
static void sd_stop0(struct gspca_dev *gspca_dev);
static const struct v4l2_pix_format cif_yuv_mode[] = {
{176, 144, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{352, 288, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format vga_yuv_mode[] = {
{160, 120, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{320, 240, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{640, 480, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format model0_mode[] = {
{160, 120, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{176, 144, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{320, 240, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format model2_mode[] = {
{160, 120, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{176, 144, V4L2_PIX_FMT_CIT_YYVYUY, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 2 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{320, 240, V4L2_PIX_FMT_SGRBG8, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
{352, 288, V4L2_PIX_FMT_SGRBG8, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 + 4,
.colorspace = V4L2_COLORSPACE_SRGB},
};
/*
* 01.01.08 - Added for RCA video in support -LO
* This struct is used to init the Model3 cam to use the RCA video in port
* instead of the CCD sensor.
*/
static const u16 rca_initdata[][3] = {
{0, 0x0000, 0x010c},
{0, 0x0006, 0x012c},
{0, 0x0078, 0x012d},
{0, 0x0046, 0x012f},
{0, 0xd141, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfea8, 0x0124},
{1, 0x0000, 0x0116},
{0, 0x0064, 0x0116},
{1, 0x0000, 0x0115},
{0, 0x0003, 0x0115},
{0, 0x0008, 0x0123},
{0, 0x0000, 0x0117},
{0, 0x0000, 0x0112},
{0, 0x0080, 0x0100},
{0, 0x0000, 0x0100},
{1, 0x0000, 0x0116},
{0, 0x0060, 0x0116},
{0, 0x0002, 0x0112},
{0, 0x0000, 0x0123},
{0, 0x0001, 0x0117},
{0, 0x0040, 0x0108},
{0, 0x0019, 0x012c},
{0, 0x0040, 0x0116},
{0, 0x000a, 0x0115},
{0, 0x000b, 0x0115},
{0, 0x0078, 0x012d},
{0, 0x0046, 0x012f},
{0, 0xd141, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfea8, 0x0124},
{0, 0x0064, 0x0116},
{0, 0x0000, 0x0115},
{0, 0x0001, 0x0115},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00aa, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f2, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x000f, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f8, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00fc, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f9, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x003c, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xffff, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0027, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0019, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0021, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0006, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0045, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002a, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x000e, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002b, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00f4, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002c, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0004, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002d, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0014, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002e, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0003, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x002f, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0003, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0014, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0053, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0x0000, 0x0101},
{0, 0x00a0, 0x0103},
{0, 0x0078, 0x0105},
{0, 0x0000, 0x010a},
{0, 0x0024, 0x010b},
{0, 0x0028, 0x0119},
{0, 0x0088, 0x011b},
{0, 0x0002, 0x011d},
{0, 0x0003, 0x011e},
{0, 0x0000, 0x0129},
{0, 0x00fc, 0x012b},
{0, 0x0008, 0x0102},
{0, 0x0000, 0x0104},
{0, 0x0008, 0x011a},
{0, 0x0028, 0x011c},
{0, 0x0021, 0x012a},
{0, 0x0000, 0x0118},
{0, 0x0000, 0x0132},
{0, 0x0000, 0x0109},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0031, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x00dc, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0032, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0020, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0001, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0040, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0037, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0030, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0xfff9, 0x0124},
{0, 0x0086, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0038, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0008, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0x0000, 0x0127},
{0, 0xfff8, 0x0124},
{0, 0xfffd, 0x0124},
{0, 0xfffa, 0x0124},
{0, 0x0003, 0x0111},
};
/* TESTME the old ibmcam driver repeats certain commands to Model1 cameras, we
do the same for now (testing needed to see if this is really necessary) */
static const int cit_model1_ntries = 5;
static const int cit_model1_ntries2 = 2;
static int cit_write_reg(struct gspca_dev *gspca_dev, u16 value, u16 index)
{
struct usb_device *udev = gspca_dev->dev;
int err;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x00,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
value, index, NULL, 0, 1000);
if (err < 0)
pr_err("Failed to write a register (index 0x%04X, value 0x%02X, error %d)\n",
index, value, err);
return 0;
}
static int cit_read_reg(struct gspca_dev *gspca_dev, u16 index, int verbose)
{
struct usb_device *udev = gspca_dev->dev;
__u8 *buf = gspca_dev->usb_buf;
int res;
res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x01,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_ENDPOINT,
0x00, index, buf, 8, 1000);
if (res < 0) {
pr_err("Failed to read a register (index 0x%04X, error %d)\n",
index, res);
return res;
}
if (verbose)
gspca_dbg(gspca_dev, D_PROBE, "Register %04x value: %02x\n",
index, buf[0]);
return 0;
}
/*
* cit_send_FF_04_02()
*
* This procedure sends magic 3-command prefix to the camera.
* The purpose of this prefix is not known.
*
* History:
* 1/2/00 Created.
*/
static void cit_send_FF_04_02(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x00FF, 0x0127);
cit_write_reg(gspca_dev, 0x0004, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
}
static void cit_send_00_04_06(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x0004, 0x0124);
cit_write_reg(gspca_dev, 0x0006, 0x0124);
}
static void cit_send_x_00(struct gspca_dev *gspca_dev, unsigned short x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
}
static void cit_send_x_00_05(struct gspca_dev *gspca_dev, unsigned short x)
{
cit_send_x_00(gspca_dev, x);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
}
static void cit_send_x_00_05_02(struct gspca_dev *gspca_dev, unsigned short x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
}
static void cit_send_x_01_00_05(struct gspca_dev *gspca_dev, u16 x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0001, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
}
static void cit_send_x_00_05_02_01(struct gspca_dev *gspca_dev, u16 x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0124);
}
static void cit_send_x_00_05_02_08_01(struct gspca_dev *gspca_dev, u16 x)
{
cit_write_reg(gspca_dev, x, 0x0127);
cit_write_reg(gspca_dev, 0x0000, 0x0124);
cit_write_reg(gspca_dev, 0x0005, 0x0124);
cit_write_reg(gspca_dev, 0x0002, 0x0124);
cit_write_reg(gspca_dev, 0x0008, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0124);
}
static void cit_Packet_Format1(struct gspca_dev *gspca_dev, u16 fkey, u16 val)
{
cit_send_x_01_00_05(gspca_dev, 0x0088);
cit_send_x_00_05(gspca_dev, fkey);
cit_send_x_00_05_02_08_01(gspca_dev, val);
cit_send_x_00_05(gspca_dev, 0x0088);
cit_send_x_00_05_02_01(gspca_dev, fkey);
cit_send_x_00_05(gspca_dev, 0x0089);
cit_send_x_00(gspca_dev, fkey);
cit_send_00_04_06(gspca_dev);
cit_read_reg(gspca_dev, 0x0126, 0);
cit_send_FF_04_02(gspca_dev);
}
static void cit_PacketFormat2(struct gspca_dev *gspca_dev, u16 fkey, u16 val)
{
cit_send_x_01_00_05(gspca_dev, 0x0088);
cit_send_x_00_05(gspca_dev, fkey);
cit_send_x_00_05_02(gspca_dev, val);
}
static void cit_model2_Packet2(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x00ff, 0x012d);
cit_write_reg(gspca_dev, 0xfea3, 0x0124);
}
static void cit_model2_Packet1(struct gspca_dev *gspca_dev, u16 v1, u16 v2)
{
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x00ff, 0x012e);
cit_write_reg(gspca_dev, v1, 0x012f);
cit_write_reg(gspca_dev, 0x00ff, 0x0130);
cit_write_reg(gspca_dev, 0xc719, 0x0124);
cit_write_reg(gspca_dev, v2, 0x0127);
cit_model2_Packet2(gspca_dev);
}
/*
* cit_model3_Packet1()
*
* 00_0078_012d
* 00_0097_012f
* 00_d141_0124
* 00_0096_0127
* 00_fea8_0124
*/
static void cit_model3_Packet1(struct gspca_dev *gspca_dev, u16 v1, u16 v2)
{
cit_write_reg(gspca_dev, 0x0078, 0x012d);
cit_write_reg(gspca_dev, v1, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, v2, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
}
static void cit_model4_Packet1(struct gspca_dev *gspca_dev, u16 v1, u16 v2)
{
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, v1, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, v2, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
}
static void cit_model4_BrightnessPacket(struct gspca_dev *gspca_dev, u16 val)
{
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0026, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, val, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0038, 0x012d);
cit_write_reg(gspca_dev, 0x0004, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam;
sd->model = id->driver_info;
if (sd->model == CIT_MODEL3 && ibm_netcam_pro)
sd->model = CIT_IBM_NETCAM_PRO;
cam = &gspca_dev->cam;
switch (sd->model) {
case CIT_MODEL0:
cam->cam_mode = model0_mode;
cam->nmodes = ARRAY_SIZE(model0_mode);
sd->sof_len = 4;
break;
case CIT_MODEL1:
cam->cam_mode = cif_yuv_mode;
cam->nmodes = ARRAY_SIZE(cif_yuv_mode);
sd->sof_len = 4;
break;
case CIT_MODEL2:
cam->cam_mode = model2_mode + 1; /* no 160x120 */
cam->nmodes = 3;
break;
case CIT_MODEL3:
cam->cam_mode = vga_yuv_mode;
cam->nmodes = ARRAY_SIZE(vga_yuv_mode);
sd->stop_on_control_change = 1;
sd->sof_len = 4;
break;
case CIT_MODEL4:
cam->cam_mode = model2_mode;
cam->nmodes = ARRAY_SIZE(model2_mode);
break;
case CIT_IBM_NETCAM_PRO:
cam->cam_mode = vga_yuv_mode;
cam->nmodes = 2; /* no 640 x 480 */
cam->input_flags = V4L2_IN_ST_VFLIP;
sd->stop_on_control_change = 1;
sd->sof_len = 4;
break;
}
return 0;
}
static int cit_init_model0(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* turn on led */
cit_write_reg(gspca_dev, 0x0001, 0x0112); /* turn on autogain ? */
cit_write_reg(gspca_dev, 0x0000, 0x0400);
cit_write_reg(gspca_dev, 0x0001, 0x0400);
cit_write_reg(gspca_dev, 0x0000, 0x0420);
cit_write_reg(gspca_dev, 0x0001, 0x0420);
cit_write_reg(gspca_dev, 0x000d, 0x0409);
cit_write_reg(gspca_dev, 0x0002, 0x040a);
cit_write_reg(gspca_dev, 0x0018, 0x0405);
cit_write_reg(gspca_dev, 0x0008, 0x0435);
cit_write_reg(gspca_dev, 0x0026, 0x040b);
cit_write_reg(gspca_dev, 0x0007, 0x0437);
cit_write_reg(gspca_dev, 0x0015, 0x042f);
cit_write_reg(gspca_dev, 0x002b, 0x0439);
cit_write_reg(gspca_dev, 0x0026, 0x043a);
cit_write_reg(gspca_dev, 0x0008, 0x0438);
cit_write_reg(gspca_dev, 0x001e, 0x042b);
cit_write_reg(gspca_dev, 0x0041, 0x042c);
return 0;
}
static int cit_init_ibm_netcam_pro(struct gspca_dev *gspca_dev)
{
cit_read_reg(gspca_dev, 0x128, 1);
cit_write_reg(gspca_dev, 0x0003, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0112);
cit_write_reg(gspca_dev, 0x0000, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0123);
cit_write_reg(gspca_dev, 0x0001, 0x0117);
cit_write_reg(gspca_dev, 0x0040, 0x0108);
cit_write_reg(gspca_dev, 0x0019, 0x012c);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0115);
cit_write_reg(gspca_dev, 0x000b, 0x0115);
cit_write_reg(gspca_dev, 0x0078, 0x012d);
cit_write_reg(gspca_dev, 0x0001, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0079, 0x012d);
cit_write_reg(gspca_dev, 0x00ff, 0x0130);
cit_write_reg(gspca_dev, 0xcd41, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_read_reg(gspca_dev, 0x0126, 1);
cit_model3_Packet1(gspca_dev, 0x0000, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0000, 0x0001);
cit_model3_Packet1(gspca_dev, 0x000b, 0x0000);
cit_model3_Packet1(gspca_dev, 0x000c, 0x0008);
cit_model3_Packet1(gspca_dev, 0x000d, 0x003a);
cit_model3_Packet1(gspca_dev, 0x000e, 0x0060);
cit_model3_Packet1(gspca_dev, 0x000f, 0x0060);
cit_model3_Packet1(gspca_dev, 0x0010, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0011, 0x0004);
cit_model3_Packet1(gspca_dev, 0x0012, 0x0028);
cit_model3_Packet1(gspca_dev, 0x0013, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0014, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0015, 0x00fb);
cit_model3_Packet1(gspca_dev, 0x0016, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0017, 0x0037);
cit_model3_Packet1(gspca_dev, 0x0018, 0x0036);
cit_model3_Packet1(gspca_dev, 0x001e, 0x0000);
cit_model3_Packet1(gspca_dev, 0x001f, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0020, 0x00c1);
cit_model3_Packet1(gspca_dev, 0x0021, 0x0034);
cit_model3_Packet1(gspca_dev, 0x0022, 0x0034);
cit_model3_Packet1(gspca_dev, 0x0025, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0028, 0x0022);
cit_model3_Packet1(gspca_dev, 0x0029, 0x000a);
cit_model3_Packet1(gspca_dev, 0x002b, 0x0000);
cit_model3_Packet1(gspca_dev, 0x002c, 0x0000);
cit_model3_Packet1(gspca_dev, 0x002d, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x002e, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x002f, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x0030, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x0031, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x0032, 0x0007);
cit_model3_Packet1(gspca_dev, 0x0033, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0037, 0x0040);
cit_model3_Packet1(gspca_dev, 0x0039, 0x0000);
cit_model3_Packet1(gspca_dev, 0x003a, 0x0000);
cit_model3_Packet1(gspca_dev, 0x003b, 0x0001);
cit_model3_Packet1(gspca_dev, 0x003c, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0040, 0x000c);
cit_model3_Packet1(gspca_dev, 0x0041, 0x00fb);
cit_model3_Packet1(gspca_dev, 0x0042, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0043, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0045, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0046, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0047, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0048, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0049, 0x0000);
cit_model3_Packet1(gspca_dev, 0x004a, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x004b, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x004c, 0x00ff);
cit_model3_Packet1(gspca_dev, 0x004f, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0050, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0051, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0055, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0056, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0057, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0058, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0059, 0x0000);
cit_model3_Packet1(gspca_dev, 0x005c, 0x0016);
cit_model3_Packet1(gspca_dev, 0x005d, 0x0022);
cit_model3_Packet1(gspca_dev, 0x005e, 0x003c);
cit_model3_Packet1(gspca_dev, 0x005f, 0x0050);
cit_model3_Packet1(gspca_dev, 0x0060, 0x0044);
cit_model3_Packet1(gspca_dev, 0x0061, 0x0005);
cit_model3_Packet1(gspca_dev, 0x006a, 0x007e);
cit_model3_Packet1(gspca_dev, 0x006f, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0072, 0x001b);
cit_model3_Packet1(gspca_dev, 0x0073, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0074, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0075, 0x001b);
cit_model3_Packet1(gspca_dev, 0x0076, 0x002a);
cit_model3_Packet1(gspca_dev, 0x0077, 0x003c);
cit_model3_Packet1(gspca_dev, 0x0078, 0x0050);
cit_model3_Packet1(gspca_dev, 0x007b, 0x0000);
cit_model3_Packet1(gspca_dev, 0x007c, 0x0011);
cit_model3_Packet1(gspca_dev, 0x007d, 0x0024);
cit_model3_Packet1(gspca_dev, 0x007e, 0x0043);
cit_model3_Packet1(gspca_dev, 0x007f, 0x005a);
cit_model3_Packet1(gspca_dev, 0x0084, 0x0020);
cit_model3_Packet1(gspca_dev, 0x0085, 0x0033);
cit_model3_Packet1(gspca_dev, 0x0086, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0087, 0x0030);
cit_model3_Packet1(gspca_dev, 0x0088, 0x0070);
cit_model3_Packet1(gspca_dev, 0x008b, 0x0008);
cit_model3_Packet1(gspca_dev, 0x008f, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0090, 0x0006);
cit_model3_Packet1(gspca_dev, 0x0091, 0x0028);
cit_model3_Packet1(gspca_dev, 0x0092, 0x005a);
cit_model3_Packet1(gspca_dev, 0x0093, 0x0082);
cit_model3_Packet1(gspca_dev, 0x0096, 0x0014);
cit_model3_Packet1(gspca_dev, 0x0097, 0x0020);
cit_model3_Packet1(gspca_dev, 0x0098, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00b0, 0x0046);
cit_model3_Packet1(gspca_dev, 0x00b1, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00b2, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00b3, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00b4, 0x0007);
cit_model3_Packet1(gspca_dev, 0x00b6, 0x0002);
cit_model3_Packet1(gspca_dev, 0x00b7, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00bb, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00bc, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00bd, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00bf, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c0, 0x00c8);
cit_model3_Packet1(gspca_dev, 0x00c1, 0x0014);
cit_model3_Packet1(gspca_dev, 0x00c2, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00c3, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c4, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00cb, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00cc, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00cd, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00ce, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00cf, 0x0020);
cit_model3_Packet1(gspca_dev, 0x00d0, 0x0040);
cit_model3_Packet1(gspca_dev, 0x00d1, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00d1, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00d2, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00d3, 0x00bf);
cit_model3_Packet1(gspca_dev, 0x00ea, 0x0008);
cit_model3_Packet1(gspca_dev, 0x00eb, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00ec, 0x00e8);
cit_model3_Packet1(gspca_dev, 0x00ed, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00ef, 0x0022);
cit_model3_Packet1(gspca_dev, 0x00f0, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00f2, 0x0028);
cit_model3_Packet1(gspca_dev, 0x00f4, 0x0002);
cit_model3_Packet1(gspca_dev, 0x00f5, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fa, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fb, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00fc, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fd, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00fe, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00ff, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00be, 0x0003);
cit_model3_Packet1(gspca_dev, 0x00c8, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c9, 0x0020);
cit_model3_Packet1(gspca_dev, 0x00ca, 0x0040);
cit_model3_Packet1(gspca_dev, 0x0053, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0082, 0x000e);
cit_model3_Packet1(gspca_dev, 0x0083, 0x0020);
cit_model3_Packet1(gspca_dev, 0x0034, 0x003c);
cit_model3_Packet1(gspca_dev, 0x006e, 0x0055);
cit_model3_Packet1(gspca_dev, 0x0062, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0063, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0066, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0067, 0x0006);
cit_model3_Packet1(gspca_dev, 0x006b, 0x0010);
cit_model3_Packet1(gspca_dev, 0x005a, 0x0001);
cit_model3_Packet1(gspca_dev, 0x005b, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0023, 0x0006);
cit_model3_Packet1(gspca_dev, 0x0026, 0x0004);
cit_model3_Packet1(gspca_dev, 0x0036, 0x0069);
cit_model3_Packet1(gspca_dev, 0x0038, 0x0064);
cit_model3_Packet1(gspca_dev, 0x003d, 0x0003);
cit_model3_Packet1(gspca_dev, 0x003e, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00b8, 0x0014);
cit_model3_Packet1(gspca_dev, 0x00b9, 0x0014);
cit_model3_Packet1(gspca_dev, 0x00e6, 0x0004);
cit_model3_Packet1(gspca_dev, 0x00e8, 0x0001);
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
cit_init_model0(gspca_dev);
sd_stop0(gspca_dev);
break;
case CIT_MODEL1:
case CIT_MODEL2:
case CIT_MODEL3:
case CIT_MODEL4:
break; /* All is done in sd_start */
case CIT_IBM_NETCAM_PRO:
cit_init_ibm_netcam_pro(gspca_dev);
sd_stop0(gspca_dev);
break;
}
return 0;
}
static int cit_set_brightness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
int i;
switch (sd->model) {
case CIT_MODEL0:
case CIT_IBM_NETCAM_PRO:
/* No (known) brightness control for these */
break;
case CIT_MODEL1:
/* Model 1: Brightness range 0 - 63 */
cit_Packet_Format1(gspca_dev, 0x0031, val);
cit_Packet_Format1(gspca_dev, 0x0032, val);
cit_Packet_Format1(gspca_dev, 0x0033, val);
break;
case CIT_MODEL2:
/* Model 2: Brightness range 0x60 - 0xee */
/* Scale 0 - 63 to 0x60 - 0xee */
i = 0x60 + val * 2254 / 1000;
cit_model2_Packet1(gspca_dev, 0x001a, i);
break;
case CIT_MODEL3:
/* Model 3: Brightness range 'i' in [0x0C..0x3F] */
i = val;
if (i < 0x0c)
i = 0x0c;
cit_model3_Packet1(gspca_dev, 0x0036, i);
break;
case CIT_MODEL4:
/* Model 4: Brightness range 'i' in [0x04..0xb4] */
/* Scale 0 - 63 to 0x04 - 0xb4 */
i = 0x04 + val * 2794 / 1000;
cit_model4_BrightnessPacket(gspca_dev, i);
break;
}
return 0;
}
static int cit_set_contrast(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0: {
int i;
/* gain 0-15, 0-20 -> 0-15 */
i = val * 1000 / 1333;
cit_write_reg(gspca_dev, i, 0x0422);
/* gain 0-31, may not be lower then 0x0422, 0-20 -> 0-31 */
i = val * 2000 / 1333;
cit_write_reg(gspca_dev, i, 0x0423);
/* gain 0-127, may not be lower then 0x0423, 0-20 -> 0-63 */
i = val * 4000 / 1333;
cit_write_reg(gspca_dev, i, 0x0424);
/* gain 0-127, may not be lower then 0x0424, , 0-20 -> 0-127 */
i = val * 8000 / 1333;
cit_write_reg(gspca_dev, i, 0x0425);
break;
}
case CIT_MODEL2:
case CIT_MODEL4:
/* These models do not have this control. */
break;
case CIT_MODEL1:
{
/* Scale 0 - 20 to 15 - 0 */
int i, new_contrast = (20 - val) * 1000 / 1333;
for (i = 0; i < cit_model1_ntries; i++) {
cit_Packet_Format1(gspca_dev, 0x0014, new_contrast);
cit_send_FF_04_02(gspca_dev);
}
break;
}
case CIT_MODEL3:
{ /* Preset hardware values */
static const struct {
unsigned short cv1;
unsigned short cv2;
unsigned short cv3;
} cv[7] = {
{ 0x05, 0x05, 0x0f }, /* Minimum */
{ 0x04, 0x04, 0x16 },
{ 0x02, 0x03, 0x16 },
{ 0x02, 0x08, 0x16 },
{ 0x01, 0x0c, 0x16 },
{ 0x01, 0x0e, 0x16 },
{ 0x01, 0x10, 0x16 } /* Maximum */
};
int i = val / 3;
cit_model3_Packet1(gspca_dev, 0x0067, cv[i].cv1);
cit_model3_Packet1(gspca_dev, 0x005b, cv[i].cv2);
cit_model3_Packet1(gspca_dev, 0x005c, cv[i].cv3);
break;
}
case CIT_IBM_NETCAM_PRO:
cit_model3_Packet1(gspca_dev, 0x005b, val + 1);
break;
}
return 0;
}
static int cit_set_hue(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL1:
case CIT_IBM_NETCAM_PRO:
/* No hue control for these models */
break;
case CIT_MODEL2:
cit_model2_Packet1(gspca_dev, 0x0024, val);
/* cit_model2_Packet1(gspca_dev, 0x0020, sat); */
break;
case CIT_MODEL3: {
/* Model 3: Brightness range 'i' in [0x05..0x37] */
/* TESTME according to the ibmcam driver this does not work */
if (0) {
/* Scale 0 - 127 to 0x05 - 0x37 */
int i = 0x05 + val * 1000 / 2540;
cit_model3_Packet1(gspca_dev, 0x007e, i);
}
break;
}
case CIT_MODEL4:
/* HDG: taken from ibmcam, setting the color gains does not
* really belong here.
*
* I am not sure r/g/b_gain variables exactly control gain
* of those channels. Most likely they subtly change some
* very internal image processing settings in the camera.
* In any case, here is what they do, and feel free to tweak:
*
* r_gain: seriously affects red gain
* g_gain: seriously affects green gain
* b_gain: seriously affects blue gain
* hue: changes average color from violet (0) to red (0xFF)
*/
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 160, 0x0127); /* Green gain */
cit_write_reg(gspca_dev, 160, 0x012e); /* Red gain */
cit_write_reg(gspca_dev, 160, 0x0130); /* Blue gain */
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, val, 0x012d); /* Hue */
cit_write_reg(gspca_dev, 0xf545, 0x0124);
break;
}
return 0;
}
static int cit_set_sharpness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL2:
case CIT_MODEL4:
case CIT_IBM_NETCAM_PRO:
/* These models do not have this control */
break;
case CIT_MODEL1: {
int i;
static const unsigned short sa[] = {
0x11, 0x13, 0x16, 0x18, 0x1a, 0x8, 0x0a };
for (i = 0; i < cit_model1_ntries; i++)
cit_PacketFormat2(gspca_dev, 0x0013, sa[val]);
break;
}
case CIT_MODEL3:
{ /*
* "Use a table of magic numbers.
* This setting doesn't really change much.
* But that's how Windows does it."
*/
static const struct {
unsigned short sv1;
unsigned short sv2;
unsigned short sv3;
unsigned short sv4;
} sv[7] = {
{ 0x00, 0x00, 0x05, 0x14 }, /* Smoothest */
{ 0x01, 0x04, 0x05, 0x14 },
{ 0x02, 0x04, 0x05, 0x14 },
{ 0x03, 0x04, 0x05, 0x14 },
{ 0x03, 0x05, 0x05, 0x14 },
{ 0x03, 0x06, 0x05, 0x14 },
{ 0x03, 0x07, 0x05, 0x14 } /* Sharpest */
};
cit_model3_Packet1(gspca_dev, 0x0060, sv[val].sv1);
cit_model3_Packet1(gspca_dev, 0x0061, sv[val].sv2);
cit_model3_Packet1(gspca_dev, 0x0062, sv[val].sv3);
cit_model3_Packet1(gspca_dev, 0x0063, sv[val].sv4);
break;
}
}
return 0;
}
/*
* cit_set_lighting()
*
* Camera model 1:
* We have 3 levels of lighting conditions: 0=Bright, 1=Medium, 2=Low.
*
* Camera model 2:
* We have 16 levels of lighting, 0 for bright light and up to 15 for
* low light. But values above 5 or so are useless because camera is
* not really capable to produce anything worth viewing at such light.
* This setting may be altered only in certain camera state.
*
* Low lighting forces slower FPS.
*
* History:
* 1/5/00 Created.
* 2/20/00 Added support for Model 2 cameras.
*/
static void cit_set_lighting(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL2:
case CIT_MODEL3:
case CIT_MODEL4:
case CIT_IBM_NETCAM_PRO:
break;
case CIT_MODEL1: {
int i;
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x0027, val);
break;
}
}
}
static void cit_set_hflip(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
if (val)
cit_write_reg(gspca_dev, 0x0020, 0x0115);
else
cit_write_reg(gspca_dev, 0x0040, 0x0115);
break;
case CIT_MODEL1:
case CIT_MODEL2:
case CIT_MODEL3:
case CIT_MODEL4:
case CIT_IBM_NETCAM_PRO:
break;
}
}
static int cit_restart_stream(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL1:
cit_write_reg(gspca_dev, 0x0001, 0x0114);
/* Fall through */
case CIT_MODEL2:
case CIT_MODEL4:
cit_write_reg(gspca_dev, 0x00c0, 0x010c); /* Go! */
usb_clear_halt(gspca_dev->dev, gspca_dev->urb[0]->pipe);
break;
case CIT_MODEL3:
case CIT_IBM_NETCAM_PRO:
cit_write_reg(gspca_dev, 0x0001, 0x0114);
cit_write_reg(gspca_dev, 0x00c0, 0x010c); /* Go! */
usb_clear_halt(gspca_dev->dev, gspca_dev->urb[0]->pipe);
/* Clear button events from while we were not streaming */
cit_write_reg(gspca_dev, 0x0001, 0x0113);
break;
}
sd->sof_read = 0;
return 0;
}
static int cit_get_packet_size(struct gspca_dev *gspca_dev)
{
struct usb_host_interface *alt;
struct usb_interface *intf;
intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
alt = usb_altnum_to_altsetting(intf, gspca_dev->alt);
if (!alt) {
pr_err("Couldn't get altsetting\n");
return -EIO;
}
if (alt->desc.bNumEndpoints < 1)
return -ENODEV;
return le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
}
/* Calculate the clockdiv giving us max fps given the available bandwidth */
static int cit_get_clock_div(struct gspca_dev *gspca_dev)
{
int clock_div = 7; /* 0=30 1=25 2=20 3=15 4=12 5=7.5 6=6 7=3fps ?? */
int fps[8] = { 30, 25, 20, 15, 12, 8, 6, 3 };
int packet_size;
packet_size = cit_get_packet_size(gspca_dev);
if (packet_size < 0)
return packet_size;
while (clock_div > 3 &&
1000 * packet_size >
gspca_dev->pixfmt.width * gspca_dev->pixfmt.height *
fps[clock_div - 1] * 3 / 2)
clock_div--;
gspca_dbg(gspca_dev, D_PROBE,
"PacketSize: %d, res: %dx%d -> using clockdiv: %d (%d fps)\n",
packet_size,
gspca_dev->pixfmt.width, gspca_dev->pixfmt.height,
clock_div, fps[clock_div]);
return clock_div;
}
static int cit_start_model0(struct gspca_dev *gspca_dev)
{
const unsigned short compression = 0; /* 0=none, 7=best frame rate */
int clock_div;
clock_div = cit_get_clock_div(gspca_dev);
if (clock_div < 0)
return clock_div;
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* turn on led */
cit_write_reg(gspca_dev, 0x0003, 0x0438);
cit_write_reg(gspca_dev, 0x001e, 0x042b);
cit_write_reg(gspca_dev, 0x0041, 0x042c);
cit_write_reg(gspca_dev, 0x0008, 0x0436);
cit_write_reg(gspca_dev, 0x0024, 0x0403);
cit_write_reg(gspca_dev, 0x002c, 0x0404);
cit_write_reg(gspca_dev, 0x0002, 0x0426);
cit_write_reg(gspca_dev, 0x0014, 0x0427);
switch (gspca_dev->pixfmt.width) {
case 160: /* 160x120 */
cit_write_reg(gspca_dev, 0x0004, 0x010b);
cit_write_reg(gspca_dev, 0x0001, 0x010a);
cit_write_reg(gspca_dev, 0x0010, 0x0102);
cit_write_reg(gspca_dev, 0x00a0, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0078, 0x0105);
break;
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x0006, 0x010b);
cit_write_reg(gspca_dev, 0x0000, 0x010a);
cit_write_reg(gspca_dev, 0x0005, 0x0102);
cit_write_reg(gspca_dev, 0x00b0, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0090, 0x0105);
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0008, 0x010b);
cit_write_reg(gspca_dev, 0x0004, 0x010a);
cit_write_reg(gspca_dev, 0x0005, 0x0102);
cit_write_reg(gspca_dev, 0x00a0, 0x0103);
cit_write_reg(gspca_dev, 0x0010, 0x0104);
cit_write_reg(gspca_dev, 0x0078, 0x0105);
break;
}
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, clock_div, 0x0111);
return 0;
}
static int cit_start_model1(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i, clock_div;
clock_div = cit_get_clock_div(gspca_dev);
if (clock_div < 0)
return clock_div;
cit_read_reg(gspca_dev, 0x0128, 1);
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x01, 0x0100); /* LED On */
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x81, 0x0100); /* LED Off */
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x01, 0x0100); /* LED On */
cit_write_reg(gspca_dev, 0x01, 0x0108);
cit_write_reg(gspca_dev, 0x03, 0x0112);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x06, 0x0115);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x44, 0x0116);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x40, 0x0116);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x0e, 0x0115);
cit_write_reg(gspca_dev, 0x19, 0x012c);
cit_Packet_Format1(gspca_dev, 0x00, 0x1e);
cit_Packet_Format1(gspca_dev, 0x39, 0x0d);
cit_Packet_Format1(gspca_dev, 0x39, 0x09);
cit_Packet_Format1(gspca_dev, 0x3b, 0x00);
cit_Packet_Format1(gspca_dev, 0x28, 0x22);
cit_Packet_Format1(gspca_dev, 0x27, 0x00);
cit_Packet_Format1(gspca_dev, 0x2b, 0x1f);
cit_Packet_Format1(gspca_dev, 0x39, 0x08);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x2c, 0x00);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x30, 0x14);
cit_PacketFormat2(gspca_dev, 0x39, 0x02);
cit_PacketFormat2(gspca_dev, 0x01, 0xe1);
cit_PacketFormat2(gspca_dev, 0x02, 0xcd);
cit_PacketFormat2(gspca_dev, 0x03, 0xcd);
cit_PacketFormat2(gspca_dev, 0x04, 0xfa);
cit_PacketFormat2(gspca_dev, 0x3f, 0xff);
cit_PacketFormat2(gspca_dev, 0x39, 0x00);
cit_PacketFormat2(gspca_dev, 0x39, 0x02);
cit_PacketFormat2(gspca_dev, 0x0a, 0x37);
cit_PacketFormat2(gspca_dev, 0x0b, 0xb8);
cit_PacketFormat2(gspca_dev, 0x0c, 0xf3);
cit_PacketFormat2(gspca_dev, 0x0d, 0xe3);
cit_PacketFormat2(gspca_dev, 0x0e, 0x0d);
cit_PacketFormat2(gspca_dev, 0x0f, 0xf2);
cit_PacketFormat2(gspca_dev, 0x10, 0xd5);
cit_PacketFormat2(gspca_dev, 0x11, 0xba);
cit_PacketFormat2(gspca_dev, 0x12, 0x53);
cit_PacketFormat2(gspca_dev, 0x3f, 0xff);
cit_PacketFormat2(gspca_dev, 0x39, 0x00);
cit_PacketFormat2(gspca_dev, 0x39, 0x02);
cit_PacketFormat2(gspca_dev, 0x16, 0x00);
cit_PacketFormat2(gspca_dev, 0x17, 0x28);
cit_PacketFormat2(gspca_dev, 0x18, 0x7d);
cit_PacketFormat2(gspca_dev, 0x19, 0xbe);
cit_PacketFormat2(gspca_dev, 0x3f, 0xff);
cit_PacketFormat2(gspca_dev, 0x39, 0x00);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x00, 0x18);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x13, 0x18);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x14, 0x06);
/* TESTME These are handled through controls
KEEP until someone can test leaving this out is ok */
if (0) {
/* This is default brightness */
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x31, 0x37);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x32, 0x46);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x33, 0x55);
}
cit_Packet_Format1(gspca_dev, 0x2e, 0x04);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x2d, 0x04);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x29, 0x80);
cit_Packet_Format1(gspca_dev, 0x2c, 0x01);
cit_Packet_Format1(gspca_dev, 0x30, 0x17);
cit_Packet_Format1(gspca_dev, 0x39, 0x08);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x34, 0x00);
cit_write_reg(gspca_dev, 0x00, 0x0101);
cit_write_reg(gspca_dev, 0x00, 0x010a);
switch (gspca_dev->pixfmt.width) {
case 128: /* 128x96 */
cit_write_reg(gspca_dev, 0x80, 0x0103);
cit_write_reg(gspca_dev, 0x60, 0x0105);
cit_write_reg(gspca_dev, 0x0c, 0x010b);
cit_write_reg(gspca_dev, 0x04, 0x011b); /* Same everywhere */
cit_write_reg(gspca_dev, 0x0b, 0x011d);
cit_write_reg(gspca_dev, 0x00, 0x011e); /* Same everywhere */
cit_write_reg(gspca_dev, 0x00, 0x0129);
break;
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0xb0, 0x0103);
cit_write_reg(gspca_dev, 0x8f, 0x0105);
cit_write_reg(gspca_dev, 0x06, 0x010b);
cit_write_reg(gspca_dev, 0x04, 0x011b); /* Same everywhere */
cit_write_reg(gspca_dev, 0x0d, 0x011d);
cit_write_reg(gspca_dev, 0x00, 0x011e); /* Same everywhere */
cit_write_reg(gspca_dev, 0x03, 0x0129);
break;
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0xb0, 0x0103);
cit_write_reg(gspca_dev, 0x90, 0x0105);
cit_write_reg(gspca_dev, 0x02, 0x010b);
cit_write_reg(gspca_dev, 0x04, 0x011b); /* Same everywhere */
cit_write_reg(gspca_dev, 0x05, 0x011d);
cit_write_reg(gspca_dev, 0x00, 0x011e); /* Same everywhere */
cit_write_reg(gspca_dev, 0x00, 0x0129);
break;
}
cit_write_reg(gspca_dev, 0xff, 0x012b);
/* TESTME These are handled through controls
KEEP until someone can test leaving this out is ok */
if (0) {
/* This is another brightness - don't know why */
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x31, 0xc3);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x32, 0xd2);
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x33, 0xe1);
/* Default contrast */
for (i = 0; i < cit_model1_ntries; i++)
cit_Packet_Format1(gspca_dev, 0x14, 0x0a);
/* Default sharpness */
for (i = 0; i < cit_model1_ntries2; i++)
cit_PacketFormat2(gspca_dev, 0x13, 0x1a);
/* Default lighting conditions */
cit_Packet_Format1(gspca_dev, 0x0027,
v4l2_ctrl_g_ctrl(sd->lighting));
}
/* Assorted init */
switch (gspca_dev->pixfmt.width) {
case 128: /* 128x96 */
cit_Packet_Format1(gspca_dev, 0x2b, 0x1e);
cit_write_reg(gspca_dev, 0xc9, 0x0119); /* Same everywhere */
cit_write_reg(gspca_dev, 0x80, 0x0109); /* Same everywhere */
cit_write_reg(gspca_dev, 0x36, 0x0102);
cit_write_reg(gspca_dev, 0x1a, 0x0104);
cit_write_reg(gspca_dev, 0x04, 0x011a); /* Same everywhere */
cit_write_reg(gspca_dev, 0x2b, 0x011c);
cit_write_reg(gspca_dev, 0x23, 0x012a); /* Same everywhere */
break;
case 176: /* 176x144 */
cit_Packet_Format1(gspca_dev, 0x2b, 0x1e);
cit_write_reg(gspca_dev, 0xc9, 0x0119); /* Same everywhere */
cit_write_reg(gspca_dev, 0x80, 0x0109); /* Same everywhere */
cit_write_reg(gspca_dev, 0x04, 0x0102);
cit_write_reg(gspca_dev, 0x02, 0x0104);
cit_write_reg(gspca_dev, 0x04, 0x011a); /* Same everywhere */
cit_write_reg(gspca_dev, 0x2b, 0x011c);
cit_write_reg(gspca_dev, 0x23, 0x012a); /* Same everywhere */
break;
case 352: /* 352x288 */
cit_Packet_Format1(gspca_dev, 0x2b, 0x1f);
cit_write_reg(gspca_dev, 0xc9, 0x0119); /* Same everywhere */
cit_write_reg(gspca_dev, 0x80, 0x0109); /* Same everywhere */
cit_write_reg(gspca_dev, 0x08, 0x0102);
cit_write_reg(gspca_dev, 0x01, 0x0104);
cit_write_reg(gspca_dev, 0x04, 0x011a); /* Same everywhere */
cit_write_reg(gspca_dev, 0x2f, 0x011c);
cit_write_reg(gspca_dev, 0x23, 0x012a); /* Same everywhere */
break;
}
cit_write_reg(gspca_dev, 0x01, 0x0100); /* LED On */
cit_write_reg(gspca_dev, clock_div, 0x0111);
return 0;
}
static int cit_start_model2(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int clock_div = 0;
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* LED on */
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0112);
cit_write_reg(gspca_dev, 0x00bc, 0x012c);
cit_write_reg(gspca_dev, 0x0008, 0x012b);
cit_write_reg(gspca_dev, 0x0000, 0x0108);
cit_write_reg(gspca_dev, 0x0001, 0x0133);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x002c, 0x0103); /* All except 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x0024, 0x0105); /* 176x144, 352x288 */
cit_write_reg(gspca_dev, 0x00b9, 0x010a); /* Unique to this mode */
cit_write_reg(gspca_dev, 0x0038, 0x0119); /* Unique to this mode */
/* TESTME HDG: this does not seem right
(it is 2 for all other resolutions) */
sd->sof_len = 10;
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0028, 0x0103); /* Unique to this mode */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x001e, 0x0105); /* 320x240, 352x240 */
cit_write_reg(gspca_dev, 0x0039, 0x010a); /* All except 176x144 */
cit_write_reg(gspca_dev, 0x0070, 0x0119); /* All except 176x144 */
sd->sof_len = 2;
break;
#if 0
case VIDEOSIZE_352x240:
cit_write_reg(gspca_dev, 0x002c, 0x0103); /* All except 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x001e, 0x0105); /* 320x240, 352x240 */
cit_write_reg(gspca_dev, 0x0039, 0x010a); /* All except 176x144 */
cit_write_reg(gspca_dev, 0x0070, 0x0119); /* All except 176x144 */
sd->sof_len = 2;
break;
#endif
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0x002c, 0x0103); /* All except 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0104); /* Same */
cit_write_reg(gspca_dev, 0x0024, 0x0105); /* 176x144, 352x288 */
cit_write_reg(gspca_dev, 0x0039, 0x010a); /* All except 176x144 */
cit_write_reg(gspca_dev, 0x0070, 0x0119); /* All except 176x144 */
sd->sof_len = 2;
break;
}
cit_write_reg(gspca_dev, 0x0000, 0x0100); /* LED on */
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x0050, 0x0111);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
break;
case 320: /* 320x240 */
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0x0040, 0x0111);
cit_write_reg(gspca_dev, 0x00c0, 0x0111);
break;
}
cit_write_reg(gspca_dev, 0x009b, 0x010f);
cit_write_reg(gspca_dev, 0x00bb, 0x010f);
/*
* Hardware settings, may affect CMOS sensor; not user controls!
* -------------------------------------------------------------
* 0x0004: no effect
* 0x0006: hardware effect
* 0x0008: no effect
* 0x000a: stops video stream, probably important h/w setting
* 0x000c: changes color in hardware manner (not user setting)
* 0x0012: changes number of colors (does not affect speed)
* 0x002a: no effect
* 0x002c: hardware setting (related to scan lines)
* 0x002e: stops video stream, probably important h/w setting
*/
cit_model2_Packet1(gspca_dev, 0x000a, 0x005c);
cit_model2_Packet1(gspca_dev, 0x0004, 0x0000);
cit_model2_Packet1(gspca_dev, 0x0006, 0x00fb);
cit_model2_Packet1(gspca_dev, 0x0008, 0x0000);
cit_model2_Packet1(gspca_dev, 0x000c, 0x0009);
cit_model2_Packet1(gspca_dev, 0x0012, 0x000a);
cit_model2_Packet1(gspca_dev, 0x002a, 0x0000);
cit_model2_Packet1(gspca_dev, 0x002c, 0x0000);
cit_model2_Packet1(gspca_dev, 0x002e, 0x0008);
/*
* Function 0x0030 pops up all over the place. Apparently
* it is a hardware control register, with every bit assigned to
* do something.
*/
cit_model2_Packet1(gspca_dev, 0x0030, 0x0000);
/*
* Magic control of CMOS sensor. Only lower values like
* 0-3 work, and picture shifts left or right. Don't change.
*/
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0002);
cit_model2_Packet1(gspca_dev, 0x0016, 0x0002); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x004a); /* Another hardware setting */
clock_div = 6;
break;
case 320: /* 320x240 */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0009);
cit_model2_Packet1(gspca_dev, 0x0016, 0x0005); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x0044); /* Another hardware setting */
clock_div = 8;
break;
#if 0
case VIDEOSIZE_352x240:
/* This mode doesn't work as Windows programs it; changed to work */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0009); /* Windows sets this to 8 */
cit_model2_Packet1(gspca_dev, 0x0016, 0x0003); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x0044); /* Windows sets this to 0x0045 */
clock_div = 10;
break;
#endif
case 352: /* 352x288 */
cit_model2_Packet1(gspca_dev, 0x0014, 0x0003);
cit_model2_Packet1(gspca_dev, 0x0016, 0x0002); /* Horizontal shift */
cit_model2_Packet1(gspca_dev, 0x0018, 0x004a); /* Another hardware setting */
clock_div = 16;
break;
}
/* TESTME These are handled through controls
KEEP until someone can test leaving this out is ok */
if (0)
cit_model2_Packet1(gspca_dev, 0x001a, 0x005a);
/*
* We have our own frame rate setting varying from 0 (slowest) to 6
* (fastest). The camera model 2 allows frame rate in range [0..0x1F]
# where 0 is also the slowest setting. However for all practical
# reasons high settings make no sense because USB is not fast enough
# to support high FPS. Be aware that the picture datastream will be
# severely disrupted if you ask for frame rate faster than allowed
# for the video size - see below:
*
* Allowable ranges (obtained experimentally on OHCI, K6-3, 450 MHz):
* -----------------------------------------------------------------
* 176x144: [6..31]
* 320x240: [8..31]
* 352x240: [10..31]
* 352x288: [16..31] I have to raise lower threshold for stability...
*
* As usual, slower FPS provides better sensitivity.
*/
cit_model2_Packet1(gspca_dev, 0x001c, clock_div);
/*
* This setting does not visibly affect pictures; left it here
* because it was present in Windows USB data stream. This function
* does not allow arbitrary values and apparently is a bit mask, to
* be activated only at appropriate time. Don't change it randomly!
*/
switch (gspca_dev->pixfmt.width) {
case 176: /* 176x144 */
cit_model2_Packet1(gspca_dev, 0x0026, 0x00c2);
break;
case 320: /* 320x240 */
cit_model2_Packet1(gspca_dev, 0x0026, 0x0044);
break;
#if 0
case VIDEOSIZE_352x240:
cit_model2_Packet1(gspca_dev, 0x0026, 0x0046);
break;
#endif
case 352: /* 352x288 */
cit_model2_Packet1(gspca_dev, 0x0026, 0x0048);
break;
}
cit_model2_Packet1(gspca_dev, 0x0028, v4l2_ctrl_g_ctrl(sd->lighting));
/* model2 cannot change the backlight compensation while streaming */
v4l2_ctrl_grab(sd->lighting, true);
/* color balance rg2 */
cit_model2_Packet1(gspca_dev, 0x001e, 0x002f);
/* saturation */
cit_model2_Packet1(gspca_dev, 0x0020, 0x0034);
/* color balance yb */
cit_model2_Packet1(gspca_dev, 0x0022, 0x00a0);
/* Hardware control command */
cit_model2_Packet1(gspca_dev, 0x0030, 0x0004);
return 0;
}
static int cit_start_model3(struct gspca_dev *gspca_dev)
{
const unsigned short compression = 0; /* 0=none, 7=best frame rate */
int i, clock_div = 0;
/* HDG not in ibmcam driver, added to see if it helps with
auto-detecting between model3 and ibm netcamera pro */
cit_read_reg(gspca_dev, 0x128, 1);
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0112);
cit_write_reg(gspca_dev, 0x0000, 0x0123);
cit_write_reg(gspca_dev, 0x0001, 0x0117);
cit_write_reg(gspca_dev, 0x0040, 0x0108);
cit_write_reg(gspca_dev, 0x0019, 0x012c);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
cit_write_reg(gspca_dev, 0x0002, 0x0115);
cit_write_reg(gspca_dev, 0x0003, 0x0115);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x000b, 0x0115);
/* TESTME HDG not in ibmcam driver, added to see if it helps with
auto-detecting between model3 and ibm netcamera pro */
if (0) {
cit_write_reg(gspca_dev, 0x0078, 0x012d);
cit_write_reg(gspca_dev, 0x0001, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0079, 0x012d);
cit_write_reg(gspca_dev, 0x00ff, 0x0130);
cit_write_reg(gspca_dev, 0xcd41, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_read_reg(gspca_dev, 0x0126, 1);
}
cit_model3_Packet1(gspca_dev, 0x000a, 0x0040);
cit_model3_Packet1(gspca_dev, 0x000b, 0x00f6);
cit_model3_Packet1(gspca_dev, 0x000c, 0x0002);
cit_model3_Packet1(gspca_dev, 0x000d, 0x0020);
cit_model3_Packet1(gspca_dev, 0x000e, 0x0033);
cit_model3_Packet1(gspca_dev, 0x000f, 0x0007);
cit_model3_Packet1(gspca_dev, 0x0010, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0011, 0x0070);
cit_model3_Packet1(gspca_dev, 0x0012, 0x0030);
cit_model3_Packet1(gspca_dev, 0x0013, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0014, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0015, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0016, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0017, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0018, 0x0000);
cit_model3_Packet1(gspca_dev, 0x001e, 0x00c3);
cit_model3_Packet1(gspca_dev, 0x0020, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0028, 0x0010);
cit_model3_Packet1(gspca_dev, 0x0029, 0x0054);
cit_model3_Packet1(gspca_dev, 0x002a, 0x0013);
cit_model3_Packet1(gspca_dev, 0x002b, 0x0007);
cit_model3_Packet1(gspca_dev, 0x002d, 0x0028);
cit_model3_Packet1(gspca_dev, 0x002e, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0031, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0032, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0033, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0034, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0035, 0x0038);
cit_model3_Packet1(gspca_dev, 0x003a, 0x0001);
cit_model3_Packet1(gspca_dev, 0x003c, 0x001e);
cit_model3_Packet1(gspca_dev, 0x003f, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0041, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0046, 0x003f);
cit_model3_Packet1(gspca_dev, 0x0047, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0050, 0x0005);
cit_model3_Packet1(gspca_dev, 0x0052, 0x001a);
cit_model3_Packet1(gspca_dev, 0x0053, 0x0003);
cit_model3_Packet1(gspca_dev, 0x005a, 0x006b);
cit_model3_Packet1(gspca_dev, 0x005d, 0x001e);
cit_model3_Packet1(gspca_dev, 0x005e, 0x0030);
cit_model3_Packet1(gspca_dev, 0x005f, 0x0041);
cit_model3_Packet1(gspca_dev, 0x0064, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0065, 0x0015);
cit_model3_Packet1(gspca_dev, 0x0068, 0x000f);
cit_model3_Packet1(gspca_dev, 0x0079, 0x0000);
cit_model3_Packet1(gspca_dev, 0x007a, 0x0000);
cit_model3_Packet1(gspca_dev, 0x007c, 0x003f);
cit_model3_Packet1(gspca_dev, 0x0082, 0x000f);
cit_model3_Packet1(gspca_dev, 0x0085, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0099, 0x0000);
cit_model3_Packet1(gspca_dev, 0x009b, 0x0023);
cit_model3_Packet1(gspca_dev, 0x009c, 0x0022);
cit_model3_Packet1(gspca_dev, 0x009d, 0x0096);
cit_model3_Packet1(gspca_dev, 0x009e, 0x0096);
cit_model3_Packet1(gspca_dev, 0x009f, 0x000a);
switch (gspca_dev->pixfmt.width) {
case 160:
cit_write_reg(gspca_dev, 0x0000, 0x0101); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x00a0, 0x0103); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0078, 0x0105); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0024, 0x010b); /* Differs everywhere */
cit_write_reg(gspca_dev, 0x00a9, 0x0119);
cit_write_reg(gspca_dev, 0x0016, 0x011b);
cit_write_reg(gspca_dev, 0x0002, 0x011d); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0003, 0x011e); /* Same on 160x120, 640x480 */
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
cit_write_reg(gspca_dev, 0x0018, 0x0102);
cit_write_reg(gspca_dev, 0x0004, 0x0104);
cit_write_reg(gspca_dev, 0x0004, 0x011a);
cit_write_reg(gspca_dev, 0x0028, 0x011c);
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
cit_write_reg(gspca_dev, 0x0000, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
cit_model3_Packet1(gspca_dev, 0x0021, 0x0001); /* Same */
cit_write_reg(gspca_dev, compression, 0x0109);
clock_div = 3;
break;
case 320:
cit_write_reg(gspca_dev, 0x0000, 0x0101); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x00a0, 0x0103); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0078, 0x0105); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0028, 0x010b); /* Differs everywhere */
cit_write_reg(gspca_dev, 0x0002, 0x011d); /* Same */
cit_write_reg(gspca_dev, 0x0000, 0x011e);
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
/* 4 commands from 160x120 skipped */
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
cit_model3_Packet1(gspca_dev, 0x0021, 0x0001); /* Same */
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, 0x00d9, 0x0119);
cit_write_reg(gspca_dev, 0x0006, 0x011b);
cit_write_reg(gspca_dev, 0x0021, 0x0102); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0010, 0x0104);
cit_write_reg(gspca_dev, 0x0004, 0x011a);
cit_write_reg(gspca_dev, 0x003f, 0x011c);
cit_write_reg(gspca_dev, 0x001c, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
clock_div = 5;
break;
case 640:
cit_write_reg(gspca_dev, 0x00f0, 0x0105);
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0038, 0x010b); /* Differs everywhere */
cit_write_reg(gspca_dev, 0x00d9, 0x0119); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0006, 0x011b); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0004, 0x011d); /* NC */
cit_write_reg(gspca_dev, 0x0003, 0x011e); /* Same on 160x120, 640x480 */
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
cit_write_reg(gspca_dev, 0x0021, 0x0102); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0016, 0x0104); /* NC */
cit_write_reg(gspca_dev, 0x0004, 0x011a); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x003f, 0x011c); /* Same on 320x240, 640x480 */
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
cit_write_reg(gspca_dev, 0x001c, 0x0118); /* Same on 320x240, 640x480 */
cit_model3_Packet1(gspca_dev, 0x0021, 0x0001); /* Same */
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, 0x0040, 0x0101);
cit_write_reg(gspca_dev, 0x0040, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0132); /* Same on 320x240, 640x480 */
clock_div = 7;
break;
}
cit_model3_Packet1(gspca_dev, 0x007e, 0x000e); /* Hue */
cit_model3_Packet1(gspca_dev, 0x0036, 0x0011); /* Brightness */
cit_model3_Packet1(gspca_dev, 0x0060, 0x0002); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0061, 0x0004); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0062, 0x0005); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0063, 0x0014); /* Sharpness */
cit_model3_Packet1(gspca_dev, 0x0096, 0x00a0); /* Red sharpness */
cit_model3_Packet1(gspca_dev, 0x0097, 0x0096); /* Blue sharpness */
cit_model3_Packet1(gspca_dev, 0x0067, 0x0001); /* Contrast */
cit_model3_Packet1(gspca_dev, 0x005b, 0x000c); /* Contrast */
cit_model3_Packet1(gspca_dev, 0x005c, 0x0016); /* Contrast */
cit_model3_Packet1(gspca_dev, 0x0098, 0x000b);
cit_model3_Packet1(gspca_dev, 0x002c, 0x0003); /* Was 1, broke 640x480 */
cit_model3_Packet1(gspca_dev, 0x002f, 0x002a);
cit_model3_Packet1(gspca_dev, 0x0030, 0x0029);
cit_model3_Packet1(gspca_dev, 0x0037, 0x0002);
cit_model3_Packet1(gspca_dev, 0x0038, 0x0059);
cit_model3_Packet1(gspca_dev, 0x003d, 0x002e);
cit_model3_Packet1(gspca_dev, 0x003e, 0x0028);
cit_model3_Packet1(gspca_dev, 0x0078, 0x0005);
cit_model3_Packet1(gspca_dev, 0x007b, 0x0011);
cit_model3_Packet1(gspca_dev, 0x007d, 0x004b);
cit_model3_Packet1(gspca_dev, 0x007f, 0x0022);
cit_model3_Packet1(gspca_dev, 0x0080, 0x000c);
cit_model3_Packet1(gspca_dev, 0x0081, 0x000b);
cit_model3_Packet1(gspca_dev, 0x0083, 0x00fd);
cit_model3_Packet1(gspca_dev, 0x0086, 0x000b);
cit_model3_Packet1(gspca_dev, 0x0087, 0x000b);
cit_model3_Packet1(gspca_dev, 0x007e, 0x000e);
cit_model3_Packet1(gspca_dev, 0x0096, 0x00a0); /* Red sharpness */
cit_model3_Packet1(gspca_dev, 0x0097, 0x0096); /* Blue sharpness */
cit_model3_Packet1(gspca_dev, 0x0098, 0x000b);
/* FIXME we should probably use cit_get_clock_div() here (in
combination with isoc negotiation using the programmable isoc size)
like with the IBM netcam pro). */
cit_write_reg(gspca_dev, clock_div, 0x0111); /* Clock Divider */
switch (gspca_dev->pixfmt.width) {
case 160:
cit_model3_Packet1(gspca_dev, 0x001f, 0x0000); /* Same */
cit_model3_Packet1(gspca_dev, 0x0039, 0x001f); /* Same */
cit_model3_Packet1(gspca_dev, 0x003b, 0x003c); /* Same */
cit_model3_Packet1(gspca_dev, 0x0040, 0x000a);
cit_model3_Packet1(gspca_dev, 0x0051, 0x000a);
break;
case 320:
cit_model3_Packet1(gspca_dev, 0x001f, 0x0000); /* Same */
cit_model3_Packet1(gspca_dev, 0x0039, 0x001f); /* Same */
cit_model3_Packet1(gspca_dev, 0x003b, 0x003c); /* Same */
cit_model3_Packet1(gspca_dev, 0x0040, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0051, 0x000b);
break;
case 640:
cit_model3_Packet1(gspca_dev, 0x001f, 0x0002); /* !Same */
cit_model3_Packet1(gspca_dev, 0x0039, 0x003e); /* !Same */
cit_model3_Packet1(gspca_dev, 0x0040, 0x0008);
cit_model3_Packet1(gspca_dev, 0x0051, 0x000a);
break;
}
/* if (sd->input_index) { */
if (rca_input) {
for (i = 0; i < ARRAY_SIZE(rca_initdata); i++) {
if (rca_initdata[i][0])
cit_read_reg(gspca_dev, rca_initdata[i][2], 0);
else
cit_write_reg(gspca_dev, rca_initdata[i][1],
rca_initdata[i][2]);
}
}
return 0;
}
static int cit_start_model4(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_write_reg(gspca_dev, 0x00c0, 0x0111);
cit_write_reg(gspca_dev, 0x00bc, 0x012c);
cit_write_reg(gspca_dev, 0x0080, 0x012b);
cit_write_reg(gspca_dev, 0x0000, 0x0108);
cit_write_reg(gspca_dev, 0x0001, 0x0133);
cit_write_reg(gspca_dev, 0x009b, 0x010f);
cit_write_reg(gspca_dev, 0x00bb, 0x010f);
cit_model4_Packet1(gspca_dev, 0x0038, 0x0000);
cit_model4_Packet1(gspca_dev, 0x000a, 0x005c);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0004, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00fb, 0x012e);
cit_write_reg(gspca_dev, 0x0000, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x000c, 0x0127);
cit_write_reg(gspca_dev, 0x0009, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0012, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0008, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x002a, 0x012d);
cit_write_reg(gspca_dev, 0x0000, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_model4_Packet1(gspca_dev, 0x0034, 0x0000);
switch (gspca_dev->pixfmt.width) {
case 128: /* 128x96 */
cit_write_reg(gspca_dev, 0x0070, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x0039, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x0028, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x001e, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x000a, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005a, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0043, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00eb, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x0031, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x012d);
cit_write_reg(gspca_dev, 0x0078, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
case 160: /* 160x120 */
cit_write_reg(gspca_dev, 0x0038, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x00b9, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x0028, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x001e, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x000b, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005a, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0043, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00c7, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0025, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0048, 0x0127);
cit_write_reg(gspca_dev, 0x0035, 0x012e);
cit_write_reg(gspca_dev, 0x00d0, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0048, 0x012d);
cit_write_reg(gspca_dev, 0x0090, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
case 176: /* 176x144 */
cit_write_reg(gspca_dev, 0x0038, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x00b9, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x002c, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0024, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0007, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0001, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005e, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0049, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00c7, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0028, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x002a, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x012d);
cit_write_reg(gspca_dev, 0x006d, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0001, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
/* TESTME HDG: this does not seem right
(it is 2 for all other resolutions) */
sd->sof_len = 10;
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0070, 0x0119);
cit_write_reg(gspca_dev, 0x00d0, 0x0111);
cit_write_reg(gspca_dev, 0x0039, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x0028, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x001e, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x000a, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005a, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0043, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00eb, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x0031, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0017, 0x012d);
cit_write_reg(gspca_dev, 0x0078, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
case 352: /* 352x288 */
cit_write_reg(gspca_dev, 0x0070, 0x0119);
cit_write_reg(gspca_dev, 0x00c0, 0x0111);
cit_write_reg(gspca_dev, 0x0039, 0x010a);
cit_write_reg(gspca_dev, 0x0001, 0x0102);
cit_write_reg(gspca_dev, 0x002c, 0x0103);
cit_write_reg(gspca_dev, 0x0000, 0x0104);
cit_write_reg(gspca_dev, 0x0024, 0x0105);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0016, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0006, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0014, 0x012d);
cit_write_reg(gspca_dev, 0x0002, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012e);
cit_write_reg(gspca_dev, 0x001a, 0x0130);
cit_write_reg(gspca_dev, 0x8a0a, 0x0124);
cit_write_reg(gspca_dev, 0x005e, 0x012d);
cit_write_reg(gspca_dev, 0x9545, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x0127);
cit_write_reg(gspca_dev, 0x0018, 0x012e);
cit_write_reg(gspca_dev, 0x0049, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012f);
cit_write_reg(gspca_dev, 0xd055, 0x0124);
cit_write_reg(gspca_dev, 0x001c, 0x0127);
cit_write_reg(gspca_dev, 0x00cf, 0x012e);
cit_write_reg(gspca_dev, 0xaa28, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x0032, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0x00aa, 0x0130);
cit_write_reg(gspca_dev, 0x82a8, 0x0124);
cit_write_reg(gspca_dev, 0x0036, 0x012d);
cit_write_reg(gspca_dev, 0x0008, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0xfffa, 0x0124);
cit_write_reg(gspca_dev, 0x00aa, 0x012d);
cit_write_reg(gspca_dev, 0x001e, 0x012f);
cit_write_reg(gspca_dev, 0xd141, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x0127);
cit_write_reg(gspca_dev, 0x0013, 0x012e);
cit_write_reg(gspca_dev, 0x0025, 0x0130);
cit_write_reg(gspca_dev, 0x8a28, 0x0124);
cit_write_reg(gspca_dev, 0x0010, 0x012d);
cit_write_reg(gspca_dev, 0x0048, 0x012f);
cit_write_reg(gspca_dev, 0xd145, 0x0124);
cit_write_reg(gspca_dev, 0x0000, 0x0127);
cit_write_reg(gspca_dev, 0xfea8, 0x0124);
sd->sof_len = 2;
break;
}
cit_model4_Packet1(gspca_dev, 0x0038, 0x0004);
return 0;
}
static int cit_start_ibm_netcam_pro(struct gspca_dev *gspca_dev)
{
const unsigned short compression = 0; /* 0=none, 7=best frame rate */
int i, clock_div;
clock_div = cit_get_clock_div(gspca_dev);
if (clock_div < 0)
return clock_div;
cit_write_reg(gspca_dev, 0x0003, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0100);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
/* cit_write_reg(gspca_dev, 0x0002, 0x0112); see sd_stop0 */
cit_write_reg(gspca_dev, 0x0000, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0123);
cit_write_reg(gspca_dev, 0x0001, 0x0117);
cit_write_reg(gspca_dev, 0x0040, 0x0108);
cit_write_reg(gspca_dev, 0x0019, 0x012c);
cit_write_reg(gspca_dev, 0x0060, 0x0116);
/* cit_write_reg(gspca_dev, 0x000b, 0x0115); see sd_stop0 */
cit_model3_Packet1(gspca_dev, 0x0049, 0x0000);
cit_write_reg(gspca_dev, 0x0000, 0x0101); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x003a, 0x0102); /* Hstart */
cit_write_reg(gspca_dev, 0x00a0, 0x0103); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0078, 0x0105); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x010a); /* Same */
cit_write_reg(gspca_dev, 0x0002, 0x011d); /* Same on 160x120, 320x240 */
cit_write_reg(gspca_dev, 0x0000, 0x0129); /* Same */
cit_write_reg(gspca_dev, 0x00fc, 0x012b); /* Same */
cit_write_reg(gspca_dev, 0x0022, 0x012a); /* Same */
switch (gspca_dev->pixfmt.width) {
case 160: /* 160x120 */
cit_write_reg(gspca_dev, 0x0024, 0x010b);
cit_write_reg(gspca_dev, 0x0089, 0x0119);
cit_write_reg(gspca_dev, 0x000a, 0x011b);
cit_write_reg(gspca_dev, 0x0003, 0x011e);
cit_write_reg(gspca_dev, 0x0007, 0x0104);
cit_write_reg(gspca_dev, 0x0009, 0x011a);
cit_write_reg(gspca_dev, 0x008b, 0x011c);
cit_write_reg(gspca_dev, 0x0008, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
break;
case 320: /* 320x240 */
cit_write_reg(gspca_dev, 0x0028, 0x010b);
cit_write_reg(gspca_dev, 0x00d9, 0x0119);
cit_write_reg(gspca_dev, 0x0006, 0x011b);
cit_write_reg(gspca_dev, 0x0000, 0x011e);
cit_write_reg(gspca_dev, 0x000e, 0x0104);
cit_write_reg(gspca_dev, 0x0004, 0x011a);
cit_write_reg(gspca_dev, 0x003f, 0x011c);
cit_write_reg(gspca_dev, 0x000c, 0x0118);
cit_write_reg(gspca_dev, 0x0000, 0x0132);
break;
}
cit_model3_Packet1(gspca_dev, 0x0019, 0x0031);
cit_model3_Packet1(gspca_dev, 0x001a, 0x0003);
cit_model3_Packet1(gspca_dev, 0x001b, 0x0038);
cit_model3_Packet1(gspca_dev, 0x001c, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0024, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0027, 0x0001);
cit_model3_Packet1(gspca_dev, 0x002a, 0x0004);
cit_model3_Packet1(gspca_dev, 0x0035, 0x000b);
cit_model3_Packet1(gspca_dev, 0x003f, 0x0001);
cit_model3_Packet1(gspca_dev, 0x0044, 0x0000);
cit_model3_Packet1(gspca_dev, 0x0054, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00c4, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00e7, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00e9, 0x0001);
cit_model3_Packet1(gspca_dev, 0x00ee, 0x0000);
cit_model3_Packet1(gspca_dev, 0x00f3, 0x00c0);
cit_write_reg(gspca_dev, compression, 0x0109);
cit_write_reg(gspca_dev, clock_div, 0x0111);
/* if (sd->input_index) { */
if (rca_input) {
for (i = 0; i < ARRAY_SIZE(rca_initdata); i++) {
if (rca_initdata[i][0])
cit_read_reg(gspca_dev, rca_initdata[i][2], 0);
else
cit_write_reg(gspca_dev, rca_initdata[i][1],
rca_initdata[i][2]);
}
}
return 0;
}
/* -- start the camera -- */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int packet_size;
packet_size = cit_get_packet_size(gspca_dev);
if (packet_size < 0)
return packet_size;
switch (sd->model) {
case CIT_MODEL0:
cit_start_model0(gspca_dev);
break;
case CIT_MODEL1:
cit_start_model1(gspca_dev);
break;
case CIT_MODEL2:
cit_start_model2(gspca_dev);
break;
case CIT_MODEL3:
cit_start_model3(gspca_dev);
break;
case CIT_MODEL4:
cit_start_model4(gspca_dev);
break;
case CIT_IBM_NETCAM_PRO:
cit_start_ibm_netcam_pro(gspca_dev);
break;
}
/* Program max isoc packet size */
cit_write_reg(gspca_dev, packet_size >> 8, 0x0106);
cit_write_reg(gspca_dev, packet_size & 0xff, 0x0107);
cit_restart_stream(gspca_dev);
return 0;
}
static int sd_isoc_init(struct gspca_dev *gspca_dev)
{
struct usb_interface_cache *intfc;
struct usb_host_interface *alt;
int max_packet_size;
switch (gspca_dev->pixfmt.width) {
case 160:
max_packet_size = 450;
break;
case 176:
max_packet_size = 600;
break;
default:
max_packet_size = 1022;
break;
}
intfc = gspca_dev->dev->actconfig->intf_cache[0];
if (intfc->num_altsetting < 2)
return -ENODEV;
alt = &intfc->altsetting[1];
if (alt->desc.bNumEndpoints < 1)
return -ENODEV;
/* Start isoc bandwidth "negotiation" at max isoc bandwidth */
alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(max_packet_size);
return 0;
}
static int sd_isoc_nego(struct gspca_dev *gspca_dev)
{
int ret, packet_size, min_packet_size;
struct usb_host_interface *alt;
switch (gspca_dev->pixfmt.width) {
case 160:
min_packet_size = 200;
break;
case 176:
min_packet_size = 266;
break;
default:
min_packet_size = 400;
break;
}
/*
* Existence of altsetting and endpoint was verified in sd_isoc_init()
*/
alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
if (packet_size <= min_packet_size)
return -EIO;
packet_size -= 100;
if (packet_size < min_packet_size)
packet_size = min_packet_size;
alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(packet_size);
ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 1);
if (ret < 0)
pr_err("set alt 1 err %d\n", ret);
return ret;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
cit_write_reg(gspca_dev, 0x0000, 0x010c);
}
static void sd_stop0(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (!gspca_dev->present)
return;
switch (sd->model) {
case CIT_MODEL0:
/* HDG windows does this, but it causes the cams autogain to
restart from a gain of 0, which does not look good when
changing resolutions. */
/* cit_write_reg(gspca_dev, 0x0000, 0x0112); */
cit_write_reg(gspca_dev, 0x00c0, 0x0100); /* LED Off */
break;
case CIT_MODEL1:
cit_send_FF_04_02(gspca_dev);
cit_read_reg(gspca_dev, 0x0100, 0);
cit_write_reg(gspca_dev, 0x81, 0x0100); /* LED Off */
break;
case CIT_MODEL2:
v4l2_ctrl_grab(sd->lighting, false);
/* Fall through! */
case CIT_MODEL4:
cit_model2_Packet1(gspca_dev, 0x0030, 0x0004);
cit_write_reg(gspca_dev, 0x0080, 0x0100); /* LED Off */
cit_write_reg(gspca_dev, 0x0020, 0x0111);
cit_write_reg(gspca_dev, 0x00a0, 0x0111);
cit_model2_Packet1(gspca_dev, 0x0030, 0x0002);
cit_write_reg(gspca_dev, 0x0020, 0x0111);
cit_write_reg(gspca_dev, 0x0000, 0x0112);
break;
case CIT_MODEL3:
cit_write_reg(gspca_dev, 0x0006, 0x012c);
cit_model3_Packet1(gspca_dev, 0x0046, 0x0000);
cit_read_reg(gspca_dev, 0x0116, 0);
cit_write_reg(gspca_dev, 0x0064, 0x0116);
cit_read_reg(gspca_dev, 0x0115, 0);
cit_write_reg(gspca_dev, 0x0003, 0x0115);
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0000, 0x0112);
cit_write_reg(gspca_dev, 0x0080, 0x0100);
break;
case CIT_IBM_NETCAM_PRO:
cit_model3_Packet1(gspca_dev, 0x0049, 0x00ff);
cit_write_reg(gspca_dev, 0x0006, 0x012c);
cit_write_reg(gspca_dev, 0x0000, 0x0116);
/* HDG windows does this, but I cannot get the camera
to restart with this without redoing the entire init
sequence which makes switching modes really slow */
/* cit_write_reg(gspca_dev, 0x0006, 0x0115); */
cit_write_reg(gspca_dev, 0x0008, 0x0123);
cit_write_reg(gspca_dev, 0x0000, 0x0117);
cit_write_reg(gspca_dev, 0x0003, 0x0133);
cit_write_reg(gspca_dev, 0x0000, 0x0111);
/* HDG windows does this, but I get a green picture when
restarting the stream after this */
/* cit_write_reg(gspca_dev, 0x0000, 0x0112); */
cit_write_reg(gspca_dev, 0x00c0, 0x0100);
break;
}
#if IS_ENABLED(CONFIG_INPUT)
/* If the last button state is pressed, release it now! */
if (sd->button_state) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
sd->button_state = 0;
}
#endif
}
static u8 *cit_find_sof(struct gspca_dev *gspca_dev, u8 *data, int len)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 byte3 = 0, byte4 = 0;
int i;
switch (sd->model) {
case CIT_MODEL0:
case CIT_MODEL1:
case CIT_MODEL3:
case CIT_IBM_NETCAM_PRO:
switch (gspca_dev->pixfmt.width) {
case 160: /* 160x120 */
byte3 = 0x02;
byte4 = 0x0a;
break;
case 176: /* 176x144 */
byte3 = 0x02;
byte4 = 0x0e;
break;
case 320: /* 320x240 */
byte3 = 0x02;
byte4 = 0x08;
break;
case 352: /* 352x288 */
byte3 = 0x02;
byte4 = 0x00;
break;
case 640:
byte3 = 0x03;
byte4 = 0x08;
break;
}
/* These have a different byte3 */
if (sd->model <= CIT_MODEL1)
byte3 = 0x00;
for (i = 0; i < len; i++) {
/* For this model the SOF always starts at offset 0
so no need to search the entire frame */
if (sd->model == CIT_MODEL0 && sd->sof_read != i)
break;
switch (sd->sof_read) {
case 0:
if (data[i] == 0x00)
sd->sof_read++;
break;
case 1:
if (data[i] == 0xff)
sd->sof_read++;
else if (data[i] == 0x00)
sd->sof_read = 1;
else
sd->sof_read = 0;
break;
case 2:
if (data[i] == byte3)
sd->sof_read++;
else if (data[i] == 0x00)
sd->sof_read = 1;
else
sd->sof_read = 0;
break;
case 3:
if (data[i] == byte4) {
sd->sof_read = 0;
return data + i + (sd->sof_len - 3);
}
if (byte3 == 0x00 && data[i] == 0xff)
sd->sof_read = 2;
else if (data[i] == 0x00)
sd->sof_read = 1;
else
sd->sof_read = 0;
break;
}
}
break;
case CIT_MODEL2:
case CIT_MODEL4:
/* TESTME we need to find a longer sof signature to avoid
false positives */
for (i = 0; i < len; i++) {
switch (sd->sof_read) {
case 0:
if (data[i] == 0x00)
sd->sof_read++;
break;
case 1:
sd->sof_read = 0;
if (data[i] == 0xff) {
if (i >= 4)
gspca_dbg(gspca_dev, D_FRAM,
"header found at offset: %d: %02x %02x 00 %3ph\n\n",
i - 1,
data[i - 4],
data[i - 3],
&data[i]);
else
gspca_dbg(gspca_dev, D_FRAM,
"header found at offset: %d: 00 %3ph\n\n",
i - 1,
&data[i]);
return data + i + (sd->sof_len - 1);
}
break;
}
}
break;
}
return NULL;
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, int len)
{
struct sd *sd = (struct sd *) gspca_dev;
unsigned char *sof;
sof = cit_find_sof(gspca_dev, data, len);
if (sof) {
int n;
/* finish decoding current frame */
n = sof - data;
if (n > sd->sof_len)
n -= sd->sof_len;
else
n = 0;
gspca_frame_add(gspca_dev, LAST_PACKET,
data, n);
gspca_frame_add(gspca_dev, FIRST_PACKET, NULL, 0);
len -= sof - data;
data = sof;
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
#if IS_ENABLED(CONFIG_INPUT)
static void cit_check_button(struct gspca_dev *gspca_dev)
{
int new_button_state;
struct sd *sd = (struct sd *)gspca_dev;
switch (sd->model) {
case CIT_MODEL3:
case CIT_IBM_NETCAM_PRO:
break;
default: /* TEST ME unknown if this works on other models too */
return;
}
/* Read the button state */
cit_read_reg(gspca_dev, 0x0113, 0);
new_button_state = !gspca_dev->usb_buf[0];
/* Tell the cam we've seen the button press, notice that this
is a nop (iow the cam keeps reporting pressed) until the
button is actually released. */
if (new_button_state)
cit_write_reg(gspca_dev, 0x01, 0x0113);
if (sd->button_state != new_button_state) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA,
new_button_state);
input_sync(gspca_dev->input_dev);
sd->button_state = new_button_state;
}
}
#endif
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (!gspca_dev->streaming)
return 0;
if (sd->stop_on_control_change)
sd_stopN(gspca_dev);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
cit_set_brightness(gspca_dev, ctrl->val);
break;
case V4L2_CID_CONTRAST:
cit_set_contrast(gspca_dev, ctrl->val);
break;
case V4L2_CID_HUE:
cit_set_hue(gspca_dev, ctrl->val);
break;
case V4L2_CID_HFLIP:
cit_set_hflip(gspca_dev, ctrl->val);
break;
case V4L2_CID_SHARPNESS:
cit_set_sharpness(gspca_dev, ctrl->val);
break;
case V4L2_CID_BACKLIGHT_COMPENSATION:
cit_set_lighting(gspca_dev, ctrl->val);
break;
}
if (sd->stop_on_control_change)
cit_restart_stream(gspca_dev);
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.s_ctrl = sd_s_ctrl,
};
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *)gspca_dev;
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
bool has_brightness;
bool has_contrast;
bool has_hue;
bool has_sharpness;
bool has_lighting;
bool has_hflip;
has_brightness = has_contrast = has_hue =
has_sharpness = has_hflip = has_lighting = false;
switch (sd->model) {
case CIT_MODEL0:
has_contrast = has_hflip = true;
break;
case CIT_MODEL1:
has_brightness = has_contrast =
has_sharpness = has_lighting = true;
break;
case CIT_MODEL2:
has_brightness = has_hue = has_lighting = true;
break;
case CIT_MODEL3:
has_brightness = has_contrast = has_sharpness = true;
break;
case CIT_MODEL4:
has_brightness = has_hue = true;
break;
case CIT_IBM_NETCAM_PRO:
has_brightness = has_hue =
has_sharpness = has_hflip = has_lighting = true;
break;
}
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 5);
if (has_brightness)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 63, 1, 32);
if (has_contrast)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_CONTRAST, 0, 20, 1, 10);
if (has_hue)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_HUE, 0, 127, 1, 63);
if (has_sharpness)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_SHARPNESS, 0, 6, 1, 3);
if (has_lighting)
sd->lighting = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BACKLIGHT_COMPENSATION, 0, 2, 1, 1);
if (has_hflip)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
if (hdl->error) {
pr_err("Could not initialize controls\n");
return hdl->error;
}
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
#if IS_ENABLED(CONFIG_INPUT)
.dq_callback = cit_check_button,
.other_input = 1,
#endif
};
static const struct sd_desc sd_desc_isoc_nego = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.isoc_init = sd_isoc_init,
.isoc_nego = sd_isoc_nego,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
#if IS_ENABLED(CONFIG_INPUT)
.dq_callback = cit_check_button,
.other_input = 1,
#endif
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{ USB_DEVICE_VER(0x0545, 0x8080, 0x0001, 0x0001), .driver_info = CIT_MODEL0 },
{ USB_DEVICE_VER(0x0545, 0x8080, 0x0002, 0x0002), .driver_info = CIT_MODEL1 },
{ USB_DEVICE_VER(0x0545, 0x8080, 0x030a, 0x030a), .driver_info = CIT_MODEL2 },
{ USB_DEVICE_VER(0x0545, 0x8080, 0x0301, 0x0301), .driver_info = CIT_MODEL3 },
{ USB_DEVICE_VER(0x0545, 0x8002, 0x030a, 0x030a), .driver_info = CIT_MODEL4 },
{ USB_DEVICE_VER(0x0545, 0x800c, 0x030a, 0x030a), .driver_info = CIT_MODEL2 },
{ USB_DEVICE_VER(0x0545, 0x800d, 0x030a, 0x030a), .driver_info = CIT_MODEL4 },
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
const struct sd_desc *desc = &sd_desc;
switch (id->driver_info) {
case CIT_MODEL0:
case CIT_MODEL1:
if (intf->cur_altsetting->desc.bInterfaceNumber != 2)
return -ENODEV;
break;
case CIT_MODEL2:
case CIT_MODEL4:
if (intf->cur_altsetting->desc.bInterfaceNumber != 0)
return -ENODEV;
break;
case CIT_MODEL3:
if (intf->cur_altsetting->desc.bInterfaceNumber != 0)
return -ENODEV;
/* FIXME this likely applies to all model3 cams and probably
to other models too. */
if (ibm_netcam_pro)
desc = &sd_desc_isoc_nego;
break;
}
return gspca_dev_probe2(intf, id, desc, sizeof(struct sd), THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3960_0 |
crossvul-cpp_data_good_5358_0 | /*
* RAW MPEG-4 video demuxer
* Copyright (c) 2006 Thijs Vermeir <thijs.vermeir@barco.com>
*
* This file is part of Libav.
*
* Libav is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Libav is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Libav; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "avformat.h"
#include "rawdec.h"
#define VISUAL_OBJECT_START_CODE 0x000001b5
#define VOP_START_CODE 0x000001b6
static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if (temp_buffer & 0xfffffe00)
continue;
if (temp_buffer < 2)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer >= 0x100 && temp_buffer < 0x120)
VO++;
else if (temp_buffer >= 0x120 && temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
}
FF_DEF_RAWVIDEO_DEMUXER(m4v, "raw MPEG-4 video", mpeg4video_probe, "m4v",
AV_CODEC_ID_MPEG4)
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5358_0 |
crossvul-cpp_data_bad_576_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved
*
* $Header$
*/
#include "k5-int.h"
#include <sys/time.h>
#include <kadm5/admin.h>
#include <kdb.h>
#include "server_internal.h"
#ifdef USE_PASSWORD_SERVER
#include <sys/wait.h>
#include <signal.h>
#endif
#include <krb5/kadm5_hook_plugin.h>
#ifdef USE_VALGRIND
#include <valgrind/memcheck.h>
#else
#define VALGRIND_CHECK_DEFINED(LVALUE) ((void)0)
#endif
extern krb5_principal master_princ;
extern krb5_principal hist_princ;
extern krb5_keyblock master_keyblock;
extern krb5_db_entry master_db;
static int decrypt_key_data(krb5_context context,
int n_key_data, krb5_key_data *key_data,
krb5_keyblock **keyblocks, int *n_keys);
/*
* XXX Functions that ought to be in libkrb5.a, but aren't.
*/
kadm5_ret_t krb5_copy_key_data_contents(context, from, to)
krb5_context context;
krb5_key_data *from, *to;
{
int i, idx;
*to = *from;
idx = (from->key_data_ver == 1 ? 1 : 2);
for (i = 0; i < idx; i++) {
if ( from->key_data_length[i] ) {
to->key_data_contents[i] = malloc(from->key_data_length[i]);
if (to->key_data_contents[i] == NULL) {
for (i = 0; i < idx; i++)
zapfree(to->key_data_contents[i], to->key_data_length[i]);
return ENOMEM;
}
memcpy(to->key_data_contents[i], from->key_data_contents[i],
from->key_data_length[i]);
}
}
return 0;
}
static krb5_tl_data *dup_tl_data(krb5_tl_data *tl)
{
krb5_tl_data *n;
n = (krb5_tl_data *) malloc(sizeof(krb5_tl_data));
if (n == NULL)
return NULL;
n->tl_data_contents = malloc(tl->tl_data_length);
if (n->tl_data_contents == NULL) {
free(n);
return NULL;
}
memcpy(n->tl_data_contents, tl->tl_data_contents, tl->tl_data_length);
n->tl_data_type = tl->tl_data_type;
n->tl_data_length = tl->tl_data_length;
n->tl_data_next = NULL;
return n;
}
/* This is in lib/kdb/kdb_cpw.c, but is static */
static void cleanup_key_data(context, count, data)
krb5_context context;
int count;
krb5_key_data * data;
{
int i;
for (i = 0; i < count; i++)
krb5_free_key_data_contents(context, &data[i]);
free(data);
}
/* Check whether a ks_tuple is present in an array of ks_tuples. */
static krb5_boolean
ks_tuple_present(int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_key_salt_tuple *looking_for)
{
int i;
for (i = 0; i < n_ks_tuple; i++) {
if (ks_tuple[i].ks_enctype == looking_for->ks_enctype &&
ks_tuple[i].ks_salttype == looking_for->ks_salttype)
return TRUE;
}
return FALSE;
}
/* Fetch a policy if it exists; set *have_pol_out appropriately. Return
* success whether or not the policy exists. */
static kadm5_ret_t
get_policy(kadm5_server_handle_t handle, const char *name,
kadm5_policy_ent_t policy_out, krb5_boolean *have_pol_out)
{
kadm5_ret_t ret;
*have_pol_out = FALSE;
if (name == NULL)
return 0;
ret = kadm5_get_policy(handle->lhandle, (char *)name, policy_out);
if (ret == 0)
*have_pol_out = TRUE;
return (ret == KADM5_UNK_POLICY) ? 0 : ret;
}
/*
* Apply the -allowedkeysalts policy (see kadmin(1)'s addpol/modpol
* commands). We use the allowed key/salt tuple list as a default if
* no ks tuples as provided by the caller. We reject lists that include
* key/salts outside the policy. We re-order the requested ks tuples
* (which may be a subset of the policy) to reflect the policy order.
*/
static kadm5_ret_t
apply_keysalt_policy(kadm5_server_handle_t handle, const char *policy,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
int *new_n_kstp, krb5_key_salt_tuple **new_kstp)
{
kadm5_ret_t ret;
kadm5_policy_ent_rec polent;
krb5_boolean have_polent;
int ak_n_ks_tuple = 0;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *ak_ks_tuple = NULL;
krb5_key_salt_tuple *new_ks_tuple = NULL;
krb5_key_salt_tuple *subset;
int i, m;
if (new_n_kstp != NULL) {
*new_n_kstp = 0;
*new_kstp = NULL;
}
memset(&polent, 0, sizeof(polent));
ret = get_policy(handle, policy, &polent, &have_polent);
if (ret)
goto cleanup;
if (polent.allowed_keysalts == NULL) {
/* Requested keysalts allowed or default to supported_enctypes. */
if (n_ks_tuple == 0) {
/* Default to supported_enctypes. */
n_ks_tuple = handle->params.num_keysalts;
ks_tuple = handle->params.keysalts;
}
/* Dup the requested or defaulted keysalt tuples. */
new_ks_tuple = malloc(n_ks_tuple * sizeof(*new_ks_tuple));
if (new_ks_tuple == NULL) {
ret = ENOMEM;
goto cleanup;
}
memcpy(new_ks_tuple, ks_tuple, n_ks_tuple * sizeof(*new_ks_tuple));
new_n_ks_tuple = n_ks_tuple;
ret = 0;
goto cleanup;
}
ret = krb5_string_to_keysalts(polent.allowed_keysalts,
",", /* Tuple separators */
NULL, /* Key/salt separators */
0, /* No duplicates */
&ak_ks_tuple,
&ak_n_ks_tuple);
/*
* Malformed policy? Shouldn't happen, but it's remotely possible
* someday, so we don't assert, just bail.
*/
if (ret)
goto cleanup;
/* Check that the requested ks_tuples are within policy, if we have one. */
for (i = 0; i < n_ks_tuple; i++) {
if (!ks_tuple_present(ak_n_ks_tuple, ak_ks_tuple, &ks_tuple[i])) {
ret = KADM5_BAD_KEYSALTS;
goto cleanup;
}
}
/* Have policy but no ks_tuple input? Output the policy. */
if (n_ks_tuple == 0) {
new_n_ks_tuple = ak_n_ks_tuple;
new_ks_tuple = ak_ks_tuple;
ak_ks_tuple = NULL;
goto cleanup;
}
/*
* Now filter the policy ks tuples by the requested ones so as to
* preserve in the requested sub-set the relative ordering from the
* policy. We could optimize this (if (n_ks_tuple == ak_n_ks_tuple)
* then skip this), but we don't bother.
*/
subset = calloc(n_ks_tuple, sizeof(*subset));
if (subset == NULL) {
ret = ENOMEM;
goto cleanup;
}
for (m = 0, i = 0; i < ak_n_ks_tuple && m < n_ks_tuple; i++) {
if (ks_tuple_present(n_ks_tuple, ks_tuple, &ak_ks_tuple[i]))
subset[m++] = ak_ks_tuple[i];
}
new_ks_tuple = subset;
new_n_ks_tuple = m;
ret = 0;
cleanup:
if (have_polent)
kadm5_free_policy_ent(handle->lhandle, &polent);
free(ak_ks_tuple);
if (new_n_kstp != NULL) {
*new_n_kstp = new_n_ks_tuple;
*new_kstp = new_ks_tuple;
} else {
free(new_ks_tuple);
}
return ret;
}
/*
* Set *passptr to NULL if the request looks like the first part of a krb5 1.6
* addprinc -randkey operation. The krb5 1.6 dummy password for these requests
* was invalid UTF-8, which runs afoul of the arcfour string-to-key.
*/
static void
check_1_6_dummy(kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr)
{
int i;
char *password = *passptr;
/* Old-style randkey operations disallowed tickets to start. */
if (password == NULL || !(mask & KADM5_ATTRIBUTES) ||
!(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX))
return;
/* The 1.6 dummy password was the octets 1..255. */
for (i = 0; (unsigned char) password[i] == i + 1; i++);
if (password[i] != '\0' || i != 255)
return;
/* This will make the caller use a random password instead. */
*passptr = NULL;
}
/* Return the number of keys with the newest kvno. Assumes that all key data
* with the newest kvno are at the front of the key data array. */
static int
count_new_keys(int n_key_data, krb5_key_data *key_data)
{
int n;
for (n = 1; n < n_key_data; n++) {
if (key_data[n - 1].key_data_kvno != key_data[n].key_data_kvno)
return n;
}
return n_key_data;
}
kadm5_ret_t
kadm5_create_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask,
char *password)
{
return
kadm5_create_principal_3(server_handle, entry, mask,
0, NULL, password);
}
kadm5_ret_t
kadm5_create_principal_3(void *server_handle,
kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
char *password)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_policy_ent_rec polent;
krb5_boolean have_polent = FALSE;
krb5_timestamp now;
krb5_tl_data *tl_data_tail;
unsigned int ret;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password);
/*
* Argument sanity checking, and opening up the DB
*/
if (entry == NULL)
return EINVAL;
if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) ||
(mask & KADM5_FAIL_AUTH_COUNT))
return KADM5_BAD_MASK;
if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && entry->policy == NULL)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
/*
* Check to see if the principal exists
*/
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
switch(ret) {
case KADM5_UNK_PRINC:
break;
case 0:
kdb_free_entry(handle, kdb, &adb);
return KADM5_DUP;
default:
return ret;
}
kdb = calloc(1, sizeof(*kdb));
if (kdb == NULL)
return ENOMEM;
memset(&adb, 0, sizeof(osa_princ_ent_rec));
/*
* If a policy was specified, load it.
* If we can not find the one specified return an error
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &polent, &have_polent);
if (ret)
goto cleanup;
}
if (password) {
ret = passwd_check(handle, password, have_polent ? &polent : NULL,
entry->principal);
if (ret)
goto cleanup;
}
/*
* Start populating the various DB fields, using the
* "defaults" for fields that were not specified by the
* mask.
*/
if ((ret = krb5_timeofday(handle->context, &now)))
goto cleanup;
kdb->magic = KRB5_KDB_MAGIC_NUMBER;
kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
else
kdb->attributes = handle->params.flags;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
else
kdb->max_life = handle->params.max_life;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
else
kdb->max_renewable_life = handle->params.max_rlife;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
else
kdb->expiration = handle->params.expiration;
kdb->pw_expiration = 0;
if (have_polent) {
if(polent.pw_max_life)
kdb->pw_expiration = ts_incr(now, polent.pw_max_life);
else
kdb->pw_expiration = 0;
}
if ((mask & KADM5_PW_EXPIRATION))
kdb->pw_expiration = entry->pw_expiration;
kdb->last_success = 0;
kdb->last_failed = 0;
kdb->fail_auth_count = 0;
/* this is kind of gross, but in order to free the tl data, I need
to free the entire kdb entry, and that will try to free the
principal. */
ret = krb5_copy_principal(handle->context, entry->principal, &kdb->princ);
if (ret)
goto cleanup;
if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now)))
goto cleanup;
if (mask & KADM5_TL_DATA) {
/* splice entry->tl_data onto the front of kdb->tl_data */
for (tl_data_tail = entry->tl_data; tl_data_tail;
tl_data_tail = tl_data_tail->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail);
if( ret )
goto cleanup;
}
}
/*
* We need to have setup the TL data, so we have strings, so we can
* check enctype policy, which is why we check/initialize ks_tuple
* this late.
*/
ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto cleanup;
/* initialize the keys */
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto cleanup;
if (mask & KADM5_KEY_DATA) {
/* The client requested no keys for this principal. */
assert(entry->n_key_data == 0);
} else if (password) {
ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple,
new_n_ks_tuple, password,
(mask & KADM5_KVNO)?entry->kvno:1,
FALSE, kdb);
} else {
/* Null password means create with random key (new in 1.8). */
ret = krb5_dbe_crk(handle->context, &master_keyblock,
new_ks_tuple, new_n_ks_tuple, FALSE, kdb);
}
if (ret)
goto cleanup;
/* Record the master key VNO used to encrypt this entry's keys */
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto cleanup;
ret = k5_kadm5_hook_create(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask,
new_n_ks_tuple, new_ks_tuple, password);
if (ret)
goto cleanup;
/* populate the admin-server-specific fields. In the OV server,
this used to be in a separate database. Since there's already
marshalling code for the admin fields, to keep things simple,
I'm going to keep it, and make all the admin stuff occupy a
single tl_data record, */
adb.admin_history_kvno = INITIAL_HIST_KVNO;
if (mask & KADM5_POLICY) {
adb.aux_attributes = KADM5_POLICY;
/* this does *not* need to be strdup'ed, because adb is xdr */
/* encoded in osa_adb_create_princ, and not ever freed */
adb.policy = entry->policy;
}
/* In all cases key and the principal data is set, let the database provider know */
kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ;
/* store the new db entry */
ret = kdb_put_entry(handle, kdb, &adb);
(void) k5_kadm5_hook_create(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask,
new_n_ks_tuple, new_ks_tuple, password);
cleanup:
free(new_ks_tuple);
krb5_db_free_principal(handle->context, kdb);
if (have_polent)
(void) kadm5_free_policy_ent(handle->lhandle, &polent);
return ret;
}
kadm5_ret_t
kadm5_delete_principal(void *server_handle, krb5_principal principal)
{
unsigned int ret;
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = k5_kadm5_hook_remove(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal);
if (ret) {
kdb_free_entry(handle, kdb, &adb);
return ret;
}
ret = kdb_delete_entry(handle, principal);
kdb_free_entry(handle, kdb, &adb);
if (ret == 0)
(void) k5_kadm5_hook_remove(handle->context,
handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal);
return ret;
}
kadm5_ret_t
kadm5_modify_principal(void *server_handle,
kadm5_principal_ent_t entry, long mask)
{
int ret, ret2, i;
kadm5_policy_ent_rec pol;
krb5_boolean have_pol = FALSE;
krb5_db_entry *kdb;
krb5_tl_data *tl_data_orig;
osa_princ_ent_rec adb;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if(entry == NULL)
return EINVAL;
if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) ||
(mask & KADM5_LAST_FAILED))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && entry->policy == NULL)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if (mask & KADM5_TL_DATA) {
tl_data_orig = entry->tl_data;
while (tl_data_orig) {
if (tl_data_orig->tl_data_type < 256)
return KADM5_BAD_TL_TYPE;
tl_data_orig = tl_data_orig->tl_data_next;
}
}
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
if (ret)
return(ret);
/*
* This is pretty much the same as create ...
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &pol, &have_pol);
if (ret)
goto done;
/* set us up to use the new policy */
adb.aux_attributes |= KADM5_POLICY;
if (adb.policy)
free(adb.policy);
adb.policy = strdup(entry->policy);
}
if (have_pol) {
/* set pw_max_life based on new policy */
if (pol.pw_max_life) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(kdb->pw_expiration));
if (ret)
goto done;
kdb->pw_expiration = ts_incr(kdb->pw_expiration, pol.pw_max_life);
} else {
kdb->pw_expiration = 0;
}
}
if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) {
free(adb.policy);
adb.policy = NULL;
adb.aux_attributes &= ~KADM5_POLICY;
kdb->pw_expiration = 0;
}
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
if (mask & KADM5_PW_EXPIRATION)
kdb->pw_expiration = entry->pw_expiration;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
if((mask & KADM5_KVNO)) {
for (i = 0; i < kdb->n_key_data; i++)
kdb->key_data[i].key_data_kvno = entry->kvno;
}
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl;
/* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */
for (tl = entry->tl_data; tl;
tl = tl->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl);
if( ret )
{
goto done;
}
}
}
/*
* Setting entry->fail_auth_count to 0 can be used to manually unlock
* an account. It is not possible to set fail_auth_count to any other
* value using kadmin.
*/
if (mask & KADM5_FAIL_AUTH_COUNT) {
if (entry->fail_auth_count != 0) {
ret = KADM5_BAD_SERVER_PARAMS;
goto done;
}
kdb->fail_auth_count = 0;
}
/* let the mask propagate to the database provider */
kdb->mask = mask;
ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask);
if (ret)
goto done;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret) goto done;
(void) k5_kadm5_hook_modify(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask);
ret = KADM5_OK;
done:
if (have_pol) {
ret2 = kadm5_free_policy_ent(handle->lhandle, &pol);
ret = ret ? ret : ret2;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
kadm5_ret_t
kadm5_rename_principal(void *server_handle,
krb5_principal source, krb5_principal target)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_error_code ret;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (source == NULL || target == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, target, &kdb, &adb)) == 0) {
kdb_free_entry(handle, kdb, &adb);
return(KADM5_DUP);
}
ret = k5_kadm5_hook_rename(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, source, target);
if (ret)
return ret;
ret = krb5_db_rename_principal(handle->context, source, target);
if (ret)
return ret;
/* Update the principal mod data. */
ret = kdb_get_entry(handle, target, &kdb, &adb);
if (ret)
return ret;
kdb->mask = 0;
ret = kdb_put_entry(handle, kdb, &adb);
kdb_free_entry(handle, kdb, &adb);
if (ret)
return ret;
(void) k5_kadm5_hook_rename(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, source, target);
return 0;
}
kadm5_ret_t
kadm5_get_principal(void *server_handle, krb5_principal principal,
kadm5_principal_ent_t entry,
long in_mask)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_error_code ret = 0;
long mask;
int i;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
/*
* In version 1, all the defined fields are always returned.
* entry is a pointer to a kadm5_principal_ent_t_v1 that should be
* filled with allocated memory.
*/
mask = in_mask;
memset(entry, 0, sizeof(*entry));
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return ret;
if ((mask & KADM5_POLICY) &&
adb.policy && (adb.aux_attributes & KADM5_POLICY)) {
if ((entry->policy = strdup(adb.policy)) == NULL) {
ret = ENOMEM;
goto done;
}
}
if (mask & KADM5_AUX_ATTRIBUTES)
entry->aux_attributes = adb.aux_attributes;
if ((mask & KADM5_PRINCIPAL) &&
(ret = krb5_copy_principal(handle->context, kdb->princ,
&entry->principal))) {
goto done;
}
if (mask & KADM5_PRINC_EXPIRE_TIME)
entry->princ_expire_time = kdb->expiration;
if ((mask & KADM5_LAST_PWD_CHANGE) &&
(ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(entry->last_pwd_change)))) {
goto done;
}
if (mask & KADM5_PW_EXPIRATION)
entry->pw_expiration = kdb->pw_expiration;
if (mask & KADM5_MAX_LIFE)
entry->max_life = kdb->max_life;
/* this is a little non-sensical because the function returns two */
/* values that must be checked separately against the mask */
if ((mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME)) {
ret = krb5_dbe_lookup_mod_princ_data(handle->context, kdb,
&(entry->mod_date),
&(entry->mod_name));
if (ret) {
goto done;
}
if (! (mask & KADM5_MOD_TIME))
entry->mod_date = 0;
if (! (mask & KADM5_MOD_NAME)) {
krb5_free_principal(handle->context, entry->mod_name);
entry->mod_name = NULL;
}
}
if (mask & KADM5_ATTRIBUTES)
entry->attributes = kdb->attributes;
if (mask & KADM5_KVNO)
for (entry->kvno = 0, i=0; i<kdb->n_key_data; i++)
if ((krb5_kvno) kdb->key_data[i].key_data_kvno > entry->kvno)
entry->kvno = kdb->key_data[i].key_data_kvno;
if (mask & KADM5_MKVNO) {
ret = krb5_dbe_get_mkvno(handle->context, kdb, &entry->mkvno);
if (ret)
goto done;
}
if (mask & KADM5_MAX_RLIFE)
entry->max_renewable_life = kdb->max_renewable_life;
if (mask & KADM5_LAST_SUCCESS)
entry->last_success = kdb->last_success;
if (mask & KADM5_LAST_FAILED)
entry->last_failed = kdb->last_failed;
if (mask & KADM5_FAIL_AUTH_COUNT)
entry->fail_auth_count = kdb->fail_auth_count;
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl, *tl2;
entry->tl_data = NULL;
tl = kdb->tl_data;
while (tl) {
if (tl->tl_data_type > 255) {
if ((tl2 = dup_tl_data(tl)) == NULL) {
ret = ENOMEM;
goto done;
}
tl2->tl_data_next = entry->tl_data;
entry->tl_data = tl2;
entry->n_tl_data++;
}
tl = tl->tl_data_next;
}
}
if (mask & KADM5_KEY_DATA) {
entry->n_key_data = kdb->n_key_data;
if(entry->n_key_data) {
entry->key_data = k5calloc(entry->n_key_data,
sizeof(krb5_key_data), &ret);
if (entry->key_data == NULL)
goto done;
} else
entry->key_data = NULL;
for (i = 0; i < entry->n_key_data; i++)
ret = krb5_copy_key_data_contents(handle->context,
&kdb->key_data[i],
&entry->key_data[i]);
if (ret)
goto done;
}
ret = KADM5_OK;
done:
if (ret && entry->principal) {
krb5_free_principal(handle->context, entry->principal);
entry->principal = NULL;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
/*
* Function: check_pw_reuse
*
* Purpose: Check if a key appears in a list of keys, in order to
* enforce password history.
*
* Arguments:
*
* context (r) the krb5 context
* hist_keyblock (r) the key that hist_key_data is
* encrypted in
* n_new_key_data (r) length of new_key_data
* new_key_data (r) keys to check against
* pw_hist_data, encrypted in hist_keyblock
* n_pw_hist_data (r) length of pw_hist_data
* pw_hist_data (r) passwords to check new_key_data against
*
* Effects:
* For each new_key in new_key_data:
* decrypt new_key with the master_keyblock
* for each password in pw_hist_data:
* for each hist_key in password:
* decrypt hist_key with hist_keyblock
* compare the new_key and hist_key
*
* Returns krb5 errors, KADM5_PASS_RESUSE if a key in
* new_key_data is the same as a key in pw_hist_data, or 0.
*/
static kadm5_ret_t
check_pw_reuse(krb5_context context,
krb5_keyblock *hist_keyblocks,
int n_new_key_data, krb5_key_data *new_key_data,
unsigned int n_pw_hist_data, osa_pw_hist_ent *pw_hist_data)
{
unsigned int x, y, z;
krb5_keyblock newkey, histkey, *kb;
krb5_key_data *key_data;
krb5_error_code ret;
assert (n_new_key_data >= 0);
for (x = 0; x < (unsigned) n_new_key_data; x++) {
/* Check only entries with the most recent kvno. */
if (new_key_data[x].key_data_kvno != new_key_data[0].key_data_kvno)
break;
ret = krb5_dbe_decrypt_key_data(context, NULL, &(new_key_data[x]),
&newkey, NULL);
if (ret)
return(ret);
for (y = 0; y < n_pw_hist_data; y++) {
for (z = 0; z < (unsigned int) pw_hist_data[y].n_key_data; z++) {
for (kb = hist_keyblocks; kb->enctype != 0; kb++) {
key_data = &pw_hist_data[y].key_data[z];
ret = krb5_dbe_decrypt_key_data(context, kb, key_data,
&histkey, NULL);
if (ret)
continue;
if (newkey.length == histkey.length &&
newkey.enctype == histkey.enctype &&
memcmp(newkey.contents, histkey.contents,
histkey.length) == 0) {
krb5_free_keyblock_contents(context, &histkey);
krb5_free_keyblock_contents(context, &newkey);
return KADM5_PASS_REUSE;
}
krb5_free_keyblock_contents(context, &histkey);
}
}
}
krb5_free_keyblock_contents(context, &newkey);
}
return(0);
}
static void
free_history_entry(krb5_context context, osa_pw_hist_ent *hist)
{
int i;
for (i = 0; i < hist->n_key_data; i++)
krb5_free_key_data_contents(context, &hist->key_data[i]);
free(hist->key_data);
}
/*
* Function: create_history_entry
*
* Purpose: Creates a password history entry from an array of
* key_data.
*
* Arguments:
*
* context (r) krb5_context to use
* mkey (r) master keyblock to decrypt key data with
* hist_key (r) history keyblock to encrypt key data with
* n_key_data (r) number of elements in key_data
* key_data (r) keys to add to the history entry
* hist_out (w) history entry to fill in
*
* Effects:
*
* hist->key_data is allocated to store n_key_data key_datas. Each
* element of key_data is decrypted with master_keyblock, re-encrypted
* in hist_key, and added to hist->key_data. hist->n_key_data is
* set to n_key_data.
*/
static
int create_history_entry(krb5_context context,
krb5_keyblock *hist_key, int n_key_data,
krb5_key_data *key_data, osa_pw_hist_ent *hist_out)
{
int i;
krb5_error_code ret = 0;
krb5_keyblock key;
krb5_keysalt salt;
krb5_ui_2 kvno;
osa_pw_hist_ent hist;
hist_out->key_data = NULL;
hist_out->n_key_data = 0;
if (n_key_data < 0)
return EINVAL;
memset(&key, 0, sizeof(key));
memset(&hist, 0, sizeof(hist));
if (n_key_data == 0)
goto cleanup;
hist.key_data = k5calloc(n_key_data, sizeof(krb5_key_data), &ret);
if (hist.key_data == NULL)
goto cleanup;
/* We only want to store the most recent kvno, and key_data should already
* be sorted in descending order by kvno. */
kvno = key_data[0].key_data_kvno;
for (i = 0; i < n_key_data; i++) {
if (key_data[i].key_data_kvno < kvno)
break;
ret = krb5_dbe_decrypt_key_data(context, NULL,
&key_data[i], &key,
&salt);
if (ret)
goto cleanup;
ret = krb5_dbe_encrypt_key_data(context, hist_key, &key, &salt,
key_data[i].key_data_kvno,
&hist.key_data[hist.n_key_data]);
if (ret)
goto cleanup;
hist.n_key_data++;
krb5_free_keyblock_contents(context, &key);
/* krb5_free_keysalt(context, &salt); */
}
*hist_out = hist;
hist.n_key_data = 0;
hist.key_data = NULL;
cleanup:
krb5_free_keyblock_contents(context, &key);
free_history_entry(context, &hist);
return ret;
}
/*
* Function: add_to_history
*
* Purpose: Adds a password to a principal's password history.
*
* Arguments:
*
* context (r) krb5_context to use
* hist_kvno (r) kvno of current history key
* adb (r/w) admin principal entry to add keys to
* pol (r) adb's policy
* pw (r) keys for the password to add to adb's key history
*
* Effects:
*
* add_to_history adds a single password to adb's password history.
* pw contains n_key_data keys in its key_data, in storage should be
* allocated but not freed by the caller (XXX blech!).
*
* This function maintains adb->old_keys as a circular queue. It
* starts empty, and grows each time this function is called until it
* is pol->pw_history_num items long. adb->old_key_len holds the
* number of allocated entries in the array, and must therefore be [0,
* pol->pw_history_num). adb->old_key_next is the index into the
* array where the next element should be written, and must be [0,
* adb->old_key_len).
*/
static kadm5_ret_t add_to_history(krb5_context context,
krb5_kvno hist_kvno,
osa_princ_ent_t adb,
kadm5_policy_ent_t pol,
osa_pw_hist_ent *pw)
{
osa_pw_hist_ent *histp;
uint32_t nhist;
unsigned int i, knext, nkeys;
nhist = pol->pw_history_num;
/* A history of 1 means just check the current password */
if (nhist <= 1)
return 0;
if (adb->admin_history_kvno != hist_kvno) {
/* The history key has changed since the last password change, so we
* have to reset the password history. */
free(adb->old_keys);
adb->old_keys = NULL;
adb->old_key_len = 0;
adb->old_key_next = 0;
adb->admin_history_kvno = hist_kvno;
}
nkeys = adb->old_key_len;
knext = adb->old_key_next;
/* resize the adb->old_keys array if necessary */
if (nkeys + 1 < nhist) {
if (adb->old_keys == NULL) {
adb->old_keys = (osa_pw_hist_ent *)
malloc((nkeys + 1) * sizeof (osa_pw_hist_ent));
} else {
adb->old_keys = (osa_pw_hist_ent *)
realloc(adb->old_keys,
(nkeys + 1) * sizeof (osa_pw_hist_ent));
}
if (adb->old_keys == NULL)
return(ENOMEM);
memset(&adb->old_keys[nkeys], 0, sizeof(osa_pw_hist_ent));
nkeys = ++adb->old_key_len;
/*
* To avoid losing old keys, shift forward each entry after
* knext.
*/
for (i = nkeys - 1; i > knext; i--) {
adb->old_keys[i] = adb->old_keys[i - 1];
}
memset(&adb->old_keys[knext], 0, sizeof(osa_pw_hist_ent));
} else if (nkeys + 1 > nhist) {
/*
* The policy must have changed! Shrink the array.
* Can't simply realloc() down, since it might be wrapped.
* To understand the arithmetic below, note that we are
* copying into new positions 0 .. N-1 from old positions
* old_key_next-N .. old_key_next-1, modulo old_key_len,
* where N = pw_history_num - 1 is the length of the
* shortened list. Matt Crawford, FNAL
*/
/*
* M = adb->old_key_len, N = pol->pw_history_num - 1
*
* tmp[0] .. tmp[N-1] = old[(knext-N)%M] .. old[(knext-1)%M]
*/
int j;
osa_pw_hist_t tmp;
tmp = (osa_pw_hist_ent *)
malloc((nhist - 1) * sizeof (osa_pw_hist_ent));
if (tmp == NULL)
return ENOMEM;
for (i = 0; i < nhist - 1; i++) {
/*
* Add nkeys once before taking remainder to avoid
* negative values.
*/
j = (i + nkeys + knext - (nhist - 1)) % nkeys;
tmp[i] = adb->old_keys[j];
}
/* Now free the ones we don't keep (the oldest ones) */
for (i = 0; i < nkeys - (nhist - 1); i++) {
j = (i + nkeys + knext) % nkeys;
histp = &adb->old_keys[j];
for (j = 0; j < histp->n_key_data; j++) {
krb5_free_key_data_contents(context, &histp->key_data[j]);
}
free(histp->key_data);
}
free(adb->old_keys);
adb->old_keys = tmp;
nkeys = adb->old_key_len = nhist - 1;
knext = adb->old_key_next = 0;
}
/*
* If nhist decreased since the last password change, and nkeys+1
* is less than the previous nhist, it is possible for knext to
* index into unallocated space. This condition would not be
* caught by the resizing code above.
*/
if (knext + 1 > nkeys)
knext = adb->old_key_next = 0;
/* free the old pw history entry if it contains data */
histp = &adb->old_keys[knext];
for (i = 0; i < (unsigned int) histp->n_key_data; i++)
krb5_free_key_data_contents(context, &histp->key_data[i]);
free(histp->key_data);
/* store the new entry */
adb->old_keys[knext] = *pw;
/* update the next pointer */
if (++adb->old_key_next == nhist - 1)
adb->old_key_next = 0;
return(0);
}
/* FIXME: don't use global variable for this */
krb5_boolean use_password_server = 0;
#ifdef USE_PASSWORD_SERVER
static krb5_boolean
kadm5_use_password_server (void)
{
return use_password_server;
}
#endif
void kadm5_set_use_password_server (void);
void
kadm5_set_use_password_server (void)
{
use_password_server = 1;
}
#ifdef USE_PASSWORD_SERVER
/*
* kadm5_launch_task () runs a program (task_path) to synchronize the
* Apple password server with the Kerberos database. Password server
* programs can receive arguments on the command line (task_argv)
* and a block of data via stdin (data_buffer).
*
* Because a failure to communicate with the tool results in the
* password server falling out of sync with the database,
* kadm5_launch_task() always fails if it can't talk to the tool.
*/
static kadm5_ret_t
kadm5_launch_task (krb5_context context,
const char *task_path, char * const task_argv[],
const char *buffer)
{
kadm5_ret_t ret;
int data_pipe[2];
ret = pipe (data_pipe);
if (ret)
ret = errno;
if (!ret) {
pid_t pid = fork ();
if (pid == -1) {
ret = errno;
close (data_pipe[0]);
close (data_pipe[1]);
} else if (pid == 0) {
/* The child: */
if (dup2 (data_pipe[0], STDIN_FILENO) == -1)
_exit (1);
close (data_pipe[0]);
close (data_pipe[1]);
execv (task_path, task_argv);
_exit (1); /* Fail if execv fails */
} else {
/* The parent: */
int status;
ret = 0;
close (data_pipe[0]);
/* Write out the buffer to the child, add \n */
if (buffer) {
if (krb5_net_write (context, data_pipe[1], buffer, strlen (buffer)) < 0
|| krb5_net_write (context, data_pipe[1], "\n", 1) < 0)
{
/* kill the child to make sure waitpid() won't hang later */
ret = errno;
kill (pid, SIGKILL);
}
}
close (data_pipe[1]);
waitpid (pid, &status, 0);
if (!ret) {
if (WIFEXITED (status)) {
/* child read password and exited. Check the return value. */
if ((WEXITSTATUS (status) != 0) && (WEXITSTATUS (status) != 252)) {
ret = KRB5KDC_ERR_POLICY; /* password change rejected */
}
} else {
/* child read password but crashed or was killed */
ret = KRB5KRB_ERR_GENERIC; /* FIXME: better error */
}
}
}
}
return ret;
}
#endif
kadm5_ret_t
kadm5_chpass_principal(void *server_handle,
krb5_principal principal, char *password)
{
return
kadm5_chpass_principal_3(server_handle, principal, FALSE,
0, NULL, password);
}
kadm5_ret_t
kadm5_chpass_principal_3(void *server_handle,
krb5_principal principal, krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
char *password)
{
krb5_timestamp now;
kadm5_policy_ent_rec pol;
osa_princ_ent_rec adb;
krb5_db_entry *kdb;
int ret, ret2, hist_added;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
osa_pw_hist_ent hist;
krb5_keyblock *act_mkey, *hist_keyblocks = NULL;
krb5_kvno act_kvno, hist_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
hist_added = 0;
memset(&hist, 0, sizeof(hist));
if (principal == NULL || password == NULL)
return EINVAL;
if ((krb5_principal_compare(handle->context,
principal, hist_princ)) == TRUE)
return KADM5_PROTECT_PRINCIPAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
/* Create a password history entry before we change kdb's key_data. */
ret = kdb_get_hist_key(handle, &hist_keyblocks, &hist_kvno);
if (ret)
goto done;
ret = create_history_entry(handle->context, &hist_keyblocks[0],
kdb->n_key_data, kdb->key_data, &hist);
if (ret)
goto done;
}
if ((ret = passwd_check(handle, password, have_pol ? &pol : NULL,
principal)))
goto done;
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
password, 0 /* increment kvno */,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
/* the policy was loaded before */
ret = check_pw_reuse(handle->context, hist_keyblocks,
kdb->n_key_data, kdb->key_data,
1, &hist);
if (ret)
goto done;
if (pol.pw_history_num > 1) {
/* If hist_kvno has changed since the last password change, we
* can't check the history. */
if (adb.admin_history_kvno == hist_kvno) {
ret = check_pw_reuse(handle->context, hist_keyblocks,
kdb->n_key_data, kdb->key_data,
adb.old_key_len, adb.old_keys);
if (ret)
goto done;
}
/* Don't save empty history. */
if (hist.n_key_data > 0) {
ret = add_to_history(handle->context, hist_kvno, &adb, &pol,
&hist);
if (ret)
goto done;
hist_added = 1;
}
}
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
#ifdef USE_PASSWORD_SERVER
if (kadm5_use_password_server () &&
(krb5_princ_size (handle->context, principal) == 1)) {
krb5_data *princ = krb5_princ_component (handle->context, principal, 0);
const char *path = "/usr/sbin/mkpassdb";
char *argv[] = { "mkpassdb", "-setpassword", NULL, NULL };
char *pstring = NULL;
if (!ret) {
pstring = malloc ((princ->length + 1) * sizeof (char));
if (pstring == NULL) { ret = ENOMEM; }
}
if (!ret) {
memcpy (pstring, princ->data, princ->length);
pstring [princ->length] = '\0';
argv[2] = pstring;
ret = kadm5_launch_task (handle->context, path, argv, password);
}
if (pstring != NULL)
free (pstring);
if (ret)
goto done;
}
#endif
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
/* key data and attributes changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_ATTRIBUTES |
KADM5_FAIL_AUTH_COUNT;
/* | KADM5_CPW_FUNCTION */
if (hist_added)
kdb->mask |= KADM5_KEY_HIST;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, password);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, password);
ret = KADM5_OK;
done:
free(new_ks_tuple);
if (!hist_added && hist.key_data)
free_history_entry(handle->context, &hist);
kdb_free_entry(handle, kdb, &adb);
kdb_free_keyblocks(handle, hist_keyblocks);
if (have_pol && (ret2 = kadm5_free_policy_ent(handle->lhandle, &pol))
&& !ret)
ret = ret2;
return ret;
}
kadm5_ret_t
kadm5_randkey_principal(void *server_handle,
krb5_principal principal,
krb5_keyblock **keyblocks,
int *n_keys)
{
return
kadm5_randkey_principal_3(server_handle, principal,
FALSE, 0, NULL,
keyblocks, n_keys);
}
kadm5_ret_t
kadm5_randkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock **keyblocks,
int *n_keys)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_timestamp now;
kadm5_policy_ent_rec pol;
int ret, n_new_keys;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
if (keyblocks)
*keyblocks = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if (krb5_principal_compare(handle->context, principal, hist_princ)) {
/* If changing the history entry, the new entry must have exactly one
* key. */
if (keepold)
return KADM5_PROTECT_PRINCIPAL;
new_n_ks_tuple = 1;
}
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
if (keyblocks) {
/* Return only the new keys added by krb5_dbe_crk. */
n_new_keys = count_new_keys(kdb->n_key_data, kdb->key_data);
ret = decrypt_key_data(handle->context, n_new_keys, kdb->key_data,
keyblocks, n_keys);
if (ret)
goto done;
}
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
/* | KADM5_RANDKEY_USED */;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, NULL);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, NULL);
ret = KADM5_OK;
done:
free(new_ks_tuple);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
/*
* kadm5_setv4key_principal:
*
* Set only ONE key of the principal, removing all others. This key
* must have the DES_CBC_CRC enctype and is entered as having the
* krb4 salttype. This is to enable things like kadmind4 to work.
*/
kadm5_ret_t
kadm5_setv4key_principal(void *server_handle,
krb5_principal principal,
krb5_keyblock *keyblock)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_timestamp now;
kadm5_policy_ent_rec pol;
krb5_keysalt keysalt;
int i, kvno, ret;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_key_data tmp_key_data;
krb5_keyblock *act_mkey;
memset( &tmp_key_data, 0, sizeof(tmp_key_data));
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL || keyblock == NULL)
return EINVAL;
if (hist_princ && /* this will be NULL when initializing the databse */
((krb5_principal_compare(handle->context,
principal, hist_princ)) == TRUE))
return KADM5_PROTECT_PRINCIPAL;
if (keyblock->enctype != ENCTYPE_DES_CBC_CRC)
return KADM5_SETV4KEY_INVAL_ENCTYPE;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
for (kvno = 0, i=0; i<kdb->n_key_data; i++)
if (kdb->key_data[i].key_data_kvno > kvno)
kvno = kdb->key_data[i].key_data_kvno;
if (kdb->key_data != NULL)
cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data);
kdb->key_data = calloc(1, sizeof(krb5_key_data));
if (kdb->key_data == NULL)
return ENOMEM;
kdb->n_key_data = 1;
keysalt.type = KRB5_KDB_SALTTYPE_V4;
/* XXX data.magic? */
keysalt.data.length = 0;
keysalt.data.data = NULL;
ret = kdb_get_active_mkey(handle, NULL, &act_mkey);
if (ret)
goto done;
/* use tmp_key_data as temporary location and reallocate later */
ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey, keyblock,
&keysalt, kvno + 1, kdb->key_data);
if (ret) {
goto done;
}
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
ret = KADM5_OK;
done:
for (i = 0; i < tmp_key_data.key_data_ver; i++) {
if (tmp_key_data.key_data_contents[i]) {
memset (tmp_key_data.key_data_contents[i], 0, tmp_key_data.key_data_length[i]);
free (tmp_key_data.key_data_contents[i]);
}
}
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
kadm5_ret_t
kadm5_setkey_principal(void *server_handle,
krb5_principal principal,
krb5_keyblock *keyblocks,
int n_keys)
{
return
kadm5_setkey_principal_3(server_handle, principal,
FALSE, 0, NULL,
keyblocks, n_keys);
}
kadm5_ret_t
kadm5_setkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock *keyblocks,
int n_keys)
{
kadm5_key_data *key_data;
kadm5_ret_t ret;
int i;
if (keyblocks == NULL)
return EINVAL;
if (n_ks_tuple) {
if (n_ks_tuple != n_keys)
return KADM5_SETKEY3_ETYPE_MISMATCH;
for (i = 0; i < n_ks_tuple; i++) {
if (ks_tuple[i].ks_enctype != keyblocks[i].enctype)
return KADM5_SETKEY3_ETYPE_MISMATCH;
}
}
key_data = calloc(n_keys, sizeof(kadm5_key_data));
if (key_data == NULL)
return ENOMEM;
for (i = 0; i < n_keys; i++) {
key_data[i].key = keyblocks[i];
key_data[i].salt.type =
n_ks_tuple ? ks_tuple[i].ks_salttype : KRB5_KDB_SALTTYPE_NORMAL;
}
ret = kadm5_setkey_principal_4(server_handle, principal, keepold,
key_data, n_keys);
free(key_data);
return ret;
}
/* Create a key/salt list from a key_data array. */
static kadm5_ret_t
make_ks_from_key_data(krb5_context context, kadm5_key_data *key_data,
int n_key_data, krb5_key_salt_tuple **out)
{
int i;
krb5_key_salt_tuple *ks;
*out = NULL;
ks = calloc(n_key_data, sizeof(*ks));
if (ks == NULL)
return ENOMEM;
for (i = 0; i < n_key_data; i++) {
ks[i].ks_enctype = key_data[i].key.enctype;
ks[i].ks_salttype = key_data[i].salt.type;
}
*out = ks;
return 0;
}
kadm5_ret_t
kadm5_setkey_principal_4(void *server_handle, krb5_principal principal,
krb5_boolean keepold, kadm5_key_data *key_data,
int n_key_data)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_timestamp now;
kadm5_policy_ent_rec pol;
krb5_key_data *new_key_data = NULL;
int i, j, ret, n_new_key_data = 0;
krb5_kvno kvno;
krb5_boolean similar, have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_key_salt_tuple *ks_from_keys = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL || key_data == NULL || n_key_data == 0)
return EINVAL;
/* hist_princ will be NULL when initializing the database. */
if (hist_princ != NULL &&
krb5_principal_compare(handle->context, principal, hist_princ))
return KADM5_PROTECT_PRINCIPAL;
/* For now, all keys must have the same kvno. */
kvno = key_data[0].kvno;
for (i = 1; i < n_key_data; i++) {
if (key_data[i].kvno != kvno)
return KADM5_SETKEY_BAD_KVNO;
}
ret = kdb_get_entry(handle, principal, &kdb, &adb);
if (ret)
return ret;
if (kvno == 0) {
/* Pick the next kvno. */
for (i = 0; i < kdb->n_key_data; i++) {
if (kdb->key_data[i].key_data_kvno > kvno)
kvno = kdb->key_data[i].key_data_kvno;
}
kvno++;
} else if (keepold) {
/* Check that the kvno does collide with existing keys. */
for (i = 0; i < kdb->n_key_data; i++) {
if (kdb->key_data[i].key_data_kvno == kvno) {
ret = KADM5_SETKEY_BAD_KVNO;
goto done;
}
}
}
ret = make_ks_from_key_data(handle->context, key_data, n_key_data,
&ks_from_keys);
if (ret)
goto done;
ret = apply_keysalt_policy(handle, adb.policy, n_key_data, ks_from_keys,
NULL, NULL);
free(ks_from_keys);
if (ret)
goto done;
for (i = 0; i < n_key_data; i++) {
for (j = i + 1; j < n_key_data; j++) {
ret = krb5_c_enctype_compare(handle->context,
key_data[i].key.enctype,
key_data[j].key.enctype,
&similar);
if (ret)
goto done;
if (similar) {
if (key_data[i].salt.type == key_data[j].salt.type) {
ret = KADM5_SETKEY_DUP_ENCTYPES;
goto done;
}
}
}
}
n_new_key_data = n_key_data + (keepold ? kdb->n_key_data : 0);
new_key_data = calloc(n_new_key_data, sizeof(krb5_key_data));
if (new_key_data == NULL) {
n_new_key_data = 0;
ret = ENOMEM;
goto done;
}
n_new_key_data = 0;
for (i = 0; i < n_key_data; i++) {
ret = kdb_get_active_mkey(handle, NULL, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey,
&key_data[i].key, &key_data[i].salt,
kvno, &new_key_data[i]);
if (ret)
goto done;
n_new_key_data++;
}
/* Copy old key data if necessary. */
if (keepold) {
memcpy(new_key_data + n_new_key_data, kdb->key_data,
kdb->n_key_data * sizeof(krb5_key_data));
memset(kdb->key_data, 0, kdb->n_key_data * sizeof(krb5_key_data));
/*
* Sort the keys to maintain the defined kvno order. We only need to
* sort if we keep old keys, as otherwise we allow only a single kvno
* to be specified.
*/
krb5_dbe_sort_key_data(new_key_data, n_new_key_data);
}
/* Replace kdb->key_data with the new keys. */
cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data);
kdb->key_data = new_key_data;
kdb->n_key_data = n_new_key_data;
new_key_data = NULL;
n_new_key_data = 0;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if (adb.aux_attributes & KADM5_POLICY) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
if (pol.pw_max_life)
kdb->pw_expiration = ts_incr(now, pol.pw_max_life);
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* Unlock principal on this KDC. */
kdb->fail_auth_count = 0;
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret)
goto done;
ret = KADM5_OK;
done:
cleanup_key_data(handle->context, n_new_key_data, new_key_data);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
/*
* Return the list of keys like kadm5_randkey_principal,
* but don't modify the principal.
*/
kadm5_ret_t
kadm5_get_principal_keys(void *server_handle /* IN */,
krb5_principal principal /* IN */,
krb5_kvno kvno /* IN */,
kadm5_key_data **key_data_out /* OUT */,
int *n_key_data_out /* OUT */)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_ret_t ret;
kadm5_server_handle_t handle = server_handle;
kadm5_key_data *key_data = NULL;
int i, nkeys = 0;
if (principal == NULL || key_data_out == NULL || n_key_data_out == NULL)
return EINVAL;
CHECK_HANDLE(server_handle);
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
key_data = calloc(kdb->n_key_data, sizeof(kadm5_key_data));
if (key_data == NULL) {
ret = ENOMEM;
goto done;
}
for (i = 0, nkeys = 0; i < kdb->n_key_data; i++) {
if (kvno != 0 && kvno != kdb->key_data[i].key_data_kvno)
continue;
key_data[nkeys].kvno = kdb->key_data[i].key_data_kvno;
ret = krb5_dbe_decrypt_key_data(handle->context, NULL,
&kdb->key_data[i],
&key_data[nkeys].key,
&key_data[nkeys].salt);
if (ret)
goto done;
nkeys++;
}
*n_key_data_out = nkeys;
*key_data_out = key_data;
key_data = NULL;
nkeys = 0;
ret = KADM5_OK;
done:
kdb_free_entry(handle, kdb, &adb);
kadm5_free_kadm5_key_data(handle->context, nkeys, key_data);
return ret;
}
/*
* Allocate an array of n_key_data krb5_keyblocks, fill in each
* element with the results of decrypting the nth key in key_data,
* and if n_keys is not NULL fill it in with the
* number of keys decrypted.
*/
static int decrypt_key_data(krb5_context context,
int n_key_data, krb5_key_data *key_data,
krb5_keyblock **keyblocks, int *n_keys)
{
krb5_keyblock *keys;
int ret, i;
keys = (krb5_keyblock *) malloc(n_key_data*sizeof(krb5_keyblock));
if (keys == NULL)
return ENOMEM;
memset(keys, 0, n_key_data*sizeof(krb5_keyblock));
for (i = 0; i < n_key_data; i++) {
ret = krb5_dbe_decrypt_key_data(context, NULL, &key_data[i], &keys[i],
NULL);
if (ret) {
for (; i >= 0; i--) {
if (keys[i].contents) {
memset (keys[i].contents, 0, keys[i].length);
free( keys[i].contents );
}
}
memset(keys, 0, n_key_data*sizeof(krb5_keyblock));
free(keys);
return ret;
}
}
*keyblocks = keys;
if (n_keys)
*n_keys = n_key_data;
return 0;
}
/*
* Function: kadm5_decrypt_key
*
* Purpose: Retrieves and decrypts a principal key.
*
* Arguments:
*
* server_handle (r) kadm5 handle
* entry (r) principal retrieved with kadm5_get_principal
* ktype (r) enctype to search for, or -1 to ignore
* stype (r) salt type to search for, or -1 to ignore
* kvno (r) kvno to search for, -1 for max, 0 for max
* only if it also matches ktype and stype
* keyblock (w) keyblock to fill in
* keysalt (w) keysalt to fill in, or NULL
* kvnop (w) kvno to fill in, or NULL
*
* Effects: Searches the key_data array of entry, which must have been
* retrived with kadm5_get_principal with the KADM5_KEY_DATA mask, to
* find a key with a specified enctype, salt type, and kvno in a
* principal entry. If not found, return ENOENT. Otherwise, decrypt
* it with the master key, and return the key in keyblock, the salt
* in salttype, and the key version number in kvno.
*
* If ktype or stype is -1, it is ignored for the search. If kvno is
* -1, ktype and stype are ignored and the key with the max kvno is
* returned. If kvno is 0, only the key with the max kvno is returned
* and only if it matches the ktype and stype; otherwise, ENOENT is
* returned.
*/
kadm5_ret_t kadm5_decrypt_key(void *server_handle,
kadm5_principal_ent_t entry, krb5_int32
ktype, krb5_int32 stype, krb5_int32
kvno, krb5_keyblock *keyblock,
krb5_keysalt *keysalt, int *kvnop)
{
kadm5_server_handle_t handle = server_handle;
krb5_db_entry dbent;
krb5_key_data *key_data;
krb5_keyblock *mkey_ptr;
int ret;
CHECK_HANDLE(server_handle);
if (entry->n_key_data == 0 || entry->key_data == NULL)
return EINVAL;
/* find_enctype only uses these two fields */
dbent.n_key_data = entry->n_key_data;
dbent.key_data = entry->key_data;
if ((ret = krb5_dbe_find_enctype(handle->context, &dbent, ktype,
stype, kvno, &key_data)))
return ret;
/* find_mkey only uses this field */
dbent.tl_data = entry->tl_data;
if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) {
/* try refreshing master key list */
/* XXX it would nice if we had the mkvno here for optimization */
if (krb5_db_fetch_mkey_list(handle->context, master_princ,
&master_keyblock) == 0) {
if ((ret = krb5_dbe_find_mkey(handle->context, &dbent,
&mkey_ptr))) {
return ret;
}
} else {
return ret;
}
}
if ((ret = krb5_dbe_decrypt_key_data(handle->context, NULL, key_data,
keyblock, keysalt)))
return ret;
/*
* Coerce the enctype of the output keyblock in case we got an
* inexact match on the enctype; this behavior will go away when
* the key storage architecture gets redesigned for 1.3.
*/
if (ktype != -1)
keyblock->enctype = ktype;
if (kvnop)
*kvnop = key_data->key_data_kvno;
return KADM5_OK;
}
kadm5_ret_t
kadm5_purgekeys(void *server_handle,
krb5_principal principal,
int keepkvno)
{
kadm5_server_handle_t handle = server_handle;
kadm5_ret_t ret;
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_key_data *old_keydata;
int n_old_keydata;
int i, j, k;
CHECK_HANDLE(server_handle);
if (principal == NULL)
return EINVAL;
ret = kdb_get_entry(handle, principal, &kdb, &adb);
if (ret)
return(ret);
if (keepkvno <= 0) {
keepkvno = krb5_db_get_key_data_kvno(handle->context, kdb->n_key_data,
kdb->key_data);
}
old_keydata = kdb->key_data;
n_old_keydata = kdb->n_key_data;
kdb->n_key_data = 0;
/* Allocate one extra key_data to avoid allocating 0 bytes. */
kdb->key_data = calloc(n_old_keydata, sizeof(krb5_key_data));
if (kdb->key_data == NULL) {
ret = ENOMEM;
goto done;
}
memset(kdb->key_data, 0, n_old_keydata * sizeof(krb5_key_data));
for (i = 0, j = 0; i < n_old_keydata; i++) {
if (old_keydata[i].key_data_kvno < keepkvno)
continue;
/* Alias the key_data_contents pointers; we null them out in the
* source array immediately after. */
kdb->key_data[j] = old_keydata[i];
for (k = 0; k < old_keydata[i].key_data_ver; k++) {
old_keydata[i].key_data_contents[k] = NULL;
}
j++;
}
kdb->n_key_data = j;
cleanup_key_data(handle->context, n_old_keydata, old_keydata);
kdb->mask = KADM5_KEY_DATA;
ret = kdb_put_entry(handle, kdb, &adb);
if (ret)
goto done;
done:
kdb_free_entry(handle, kdb, &adb);
return ret;
}
kadm5_ret_t
kadm5_get_strings(void *server_handle, krb5_principal principal,
krb5_string_attr **strings_out, int *count_out)
{
kadm5_server_handle_t handle = server_handle;
kadm5_ret_t ret;
krb5_db_entry *kdb = NULL;
*strings_out = NULL;
*count_out = 0;
CHECK_HANDLE(server_handle);
if (principal == NULL)
return EINVAL;
ret = kdb_get_entry(handle, principal, &kdb, NULL);
if (ret)
return ret;
ret = krb5_dbe_get_strings(handle->context, kdb, strings_out, count_out);
kdb_free_entry(handle, kdb, NULL);
return ret;
}
kadm5_ret_t
kadm5_set_string(void *server_handle, krb5_principal principal,
const char *key, const char *value)
{
kadm5_server_handle_t handle = server_handle;
kadm5_ret_t ret;
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
CHECK_HANDLE(server_handle);
if (principal == NULL || key == NULL)
return EINVAL;
ret = kdb_get_entry(handle, principal, &kdb, &adb);
if (ret)
return ret;
ret = krb5_dbe_set_string(handle->context, kdb, key, value);
if (ret)
goto done;
kdb->mask = KADM5_TL_DATA;
ret = kdb_put_entry(handle, kdb, &adb);
done:
kdb_free_entry(handle, kdb, &adb);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_576_0 |
crossvul-cpp_data_good_861_0 | /* $Id: upnpsoap.c,v 1.151 2018/03/13 10:32:53 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/
* (c) 2006-2018 Thomas Bernard
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ctype.h>
#include "macros.h"
#include "config.h"
#include "upnpglobalvars.h"
#include "upnphttp.h"
#include "upnpsoap.h"
#include "upnpreplyparse.h"
#include "upnpredirect.h"
#include "upnppinhole.h"
#include "getifaddr.h"
#include "getifstats.h"
#include "getconnstatus.h"
#include "upnpurns.h"
#include "upnputils.h"
/* utility function */
static int is_numeric(const char * s)
{
while(*s) {
if(*s < '0' || *s > '9') return 0;
s++;
}
return 1;
}
static void
BuildSendAndCloseSoapResp(struct upnphttp * h,
const char * body, int bodylen)
{
static const char beforebody[] =
"<?xml version=\"1.0\"?>\r\n"
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>";
static const char afterbody[] =
"</s:Body>"
"</s:Envelope>\r\n";
int r = BuildHeader_upnphttp(h, 200, "OK", sizeof(beforebody) - 1
+ sizeof(afterbody) - 1 + bodylen );
if(r >= 0) {
memcpy(h->res_buf + h->res_buflen, beforebody, sizeof(beforebody) - 1);
h->res_buflen += sizeof(beforebody) - 1;
memcpy(h->res_buf + h->res_buflen, body, bodylen);
h->res_buflen += bodylen;
memcpy(h->res_buf + h->res_buflen, afterbody, sizeof(afterbody) - 1);
h->res_buflen += sizeof(afterbody) - 1;
} else {
BuildResp2_upnphttp(h, 500, "Internal Server Error", NULL, 0);
}
SendRespAndClose_upnphttp(h);
}
static void
GetConnectionTypeInfo(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetConnectionTypeInfoResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:GetConnectionTypeInfoResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionType>IP_Routed</NewConnectionType>"
"<NewPossibleConnectionTypes>IP_Routed</NewPossibleConnectionTypes>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* maximum value for a UPNP ui4 type variable */
#define UPNP_UI4_MAX (4294967295ul)
static void
GetTotalBytesSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesSent>%lu</NewTotalBytesSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.obytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.obytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalBytesReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalBytesReceived>%lu</NewTotalBytesReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
/* TotalBytesReceived
* This variable represents the cumulative counter for total number of
* bytes received downstream across all connection service instances on
* WANDevice. The count rolls over to 0 after it reaching the maximum
* value (2^32)-1. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ibytes & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ibytes, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsSent(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsSent>%lu</NewTotalPacketsSent>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1",*/
#ifdef UPNP_STRICT
r<0?0:(data.opackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.opackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetTotalPacketsReceived(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewTotalPacketsReceived>%lu</NewTotalPacketsReceived>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct ifdata data;
r = getifstats(ext_if_name, &data);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
#ifdef UPNP_STRICT
r<0?0:(data.ipackets & UPNP_UI4_MAX), action);
#else /* UPNP_STRICT */
r<0?0:data.ipackets, action);
#endif /* UPNP_STRICT */
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetCommonLinkProperties(struct upnphttp * h, const char * action, const char * ns)
{
/* WANAccessType : set depending on the hardware :
* DSL, POTS (plain old Telephone service), Cable, Ethernet */
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewWANAccessType>%s</NewWANAccessType>"
"<NewLayer1UpstreamMaxBitRate>%lu</NewLayer1UpstreamMaxBitRate>"
"<NewLayer1DownstreamMaxBitRate>%lu</NewLayer1DownstreamMaxBitRate>"
"<NewPhysicalLinkStatus>%s</NewPhysicalLinkStatus>"
"</u:%sResponse>";
char body[2048];
int bodylen;
struct ifdata data;
const char * status = "Up"; /* Up, Down (Required),
* Initializing, Unavailable (Optional) */
const char * wan_access_type = "Cable"; /* DSL, POTS, Cable, Ethernet */
char ext_ip_addr[INET_ADDRSTRLEN];
if((downstream_bitrate == 0) || (upstream_bitrate == 0))
{
if(getifstats(ext_if_name, &data) >= 0)
{
if(downstream_bitrate == 0) downstream_bitrate = data.baudrate;
if(upstream_bitrate == 0) upstream_bitrate = data.baudrate;
}
}
if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, NULL, NULL) < 0) {
status = "Down";
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
wan_access_type,
upstream_bitrate, downstream_bitrate,
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetStatusInfo(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewConnectionStatus>%s</NewConnectionStatus>"
"<NewLastConnectionError>ERROR_NONE</NewLastConnectionError>"
"<NewUptime>%ld</NewUptime>"
"</u:%sResponse>";
char body[512];
int bodylen;
time_t uptime;
const char * status;
/* ConnectionStatus possible values :
* Unconfigured, Connecting, Connected, PendingDisconnect,
* Disconnecting, Disconnected */
status = get_wan_connection_status_str(ext_if_name);
uptime = upnp_get_uptime();
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
status, (long)uptime, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetNATRSIPStatus(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:GetNATRSIPStatusResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:GetNATRSIPStatusResponse>";
UNUSED(action);
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRSIPAvailable>0</NewRSIPAvailable>"
"<NewNATEnabled>1</NewNATEnabled>"
"</u:%sResponse>";
char body[512];
int bodylen;
/* 2.2.9. RSIPAvailable
* This variable indicates if Realm-specific IP (RSIP) is available
* as a feature on the InternetGatewayDevice. RSIP is being defined
* in the NAT working group in the IETF to allow host-NATing using
* a standard set of message exchanges. It also allows end-to-end
* applications that otherwise break if NAT is introduced
* (e.g. IPsec-based VPNs).
* A gateway that does not support RSIP should set this variable to 0. */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetExternalIPAddress(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewExternalIPAddress>%s</NewExternalIPAddress>"
"</u:%sResponse>";
char body[512];
int bodylen;
char ext_ip_addr[INET_ADDRSTRLEN];
/* Does that method need to work with IPv6 ?
* There is usually no NAT with IPv6 */
#ifndef MULTIPLE_EXTERNAL_IP
struct in_addr addr;
if(use_ext_ip_addr)
{
strncpy(ext_ip_addr, use_ext_ip_addr, INET_ADDRSTRLEN);
ext_ip_addr[INET_ADDRSTRLEN - 1] = '\0';
}
else if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, &addr, NULL) < 0)
{
syslog(LOG_ERR, "Failed to get ip address for interface %s",
ext_if_name);
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
}
if (addr_is_reserved(&addr))
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
#else
struct lan_addr_s * lan_addr;
strncpy(ext_ip_addr, "0.0.0.0", INET_ADDRSTRLEN);
for(lan_addr = lan_addrs.lh_first; lan_addr != NULL; lan_addr = lan_addr->list.le_next)
{
if( (h->clientaddr.s_addr & lan_addr->mask.s_addr)
== (lan_addr->addr.s_addr & lan_addr->mask.s_addr))
{
strncpy(ext_ip_addr, lan_addr->ext_ip_str, INET_ADDRSTRLEN);
break;
}
}
#endif
if (strcmp(ext_ip_addr, "0.0.0.0") == 0)
{
SoapError(h, 501, "Action Failed");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
ext_ip_addr, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
/* AddPortMapping method of WANIPConnection Service
* Ignored argument : NewEnabled */
static void
AddPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:AddPortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\"/>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\"/>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * ext_port, * protocol, * desc;
char * leaseduration_str;
unsigned int leaseduration;
char * r_host;
unsigned short iport, eport;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
if (int_ip) {
/* trim */
while(int_ip[0] == ' ')
int_ip++;
}
#ifdef UPNP_STRICT
if (!int_ip || int_ip[0] == '\0')
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif
/* IGD 2 MUST support both wildcard and specific IP address values
* for RemoteHost (only the wildcard value was REQUIRED in release 1.0) */
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
#ifndef UPNP_STRICT
/* if <NewInternalClient> arg is empty, use client address
* see https://github.com/miniupnp/miniupnp/issues/236 */
if (!int_ip || int_ip[0] == '\0')
{
int_ip = h->clientaddr_str;
memcpy(&result_ip, &(h->clientaddr), sizeof(struct in_addr));
}
else
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 718, "ConflictInMappingEntry");
return;
}
}
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if (strcmp(ext_port, "*") == 0 || eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 716, "Wildcard not permited in ExtPort");
return;
}
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
#ifdef IGD_V2
/* PortMappingLeaseDuration can be either a value between 1 and
* 604800 seconds or the zero value (for infinite lease time).
* Note that an infinite lease time can be only set by out-of-band
* mechanisms like WWW-administration, remote management or local
* management.
* If a control point uses the value 0 to indicate an infinite lease
* time mapping, it is REQUIRED that gateway uses the maximum value
* instead (e.g. 604800 seconds) */
if(leaseduration == 0 || leaseduration > 604800)
leaseduration = 604800;
#endif
syslog(LOG_INFO, "%s: ext port %hu to %s:%hu protocol %s for: %s leaseduration=%u rhost=%s",
action, eport, int_ip, iport, protocol, desc, leaseduration,
r_host ? r_host : "NULL");
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
ClearNameValueList(&data);
/* possible error codes for AddPortMapping :
* 402 - Invalid Args
* 501 - Action Failed
* 715 - Wildcard not permited in SrcAddr
* 716 - Wildcard not permited in ExtPort
* 718 - ConflictInMappingEntry
* 724 - SamePortValuesRequired (deprecated in IGD v2)
* 725 - OnlyPermanentLeasesSupported
The NAT implementation only supports permanent lease times on
port mappings (deprecated in IGD v2)
* 726 - RemoteHostOnlySupportsWildcard
RemoteHost must be a wildcard and cannot be a specific IP
address or DNS name (deprecated in IGD v2)
* 727 - ExternalPortOnlySupportsWildcard
ExternalPort must be a wildcard and cannot be a specific port
value (deprecated in IGD v2)
* 728 - NoPortMapsAvailable
There are not enough free ports available to complete the mapping
(added in IGD v2)
* 729 - ConflictWithOtherMechanisms (added in IGD v2) */
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -4:
#ifdef IGD_V2
SoapError(h, 729, "ConflictWithOtherMechanisms");
break;
#endif /* IGD_V2 */
case -2: /* already redirected */
case -3: /* not permitted */
SoapError(h, 718, "ConflictInMappingEntry");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
/* AddAnyPortMapping was added in WANIPConnection v2 */
static void
AddAnyPortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewReservedPort>%hu</NewReservedPort>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * int_ip, * int_port, * ext_port, * protocol, * desc;
const char * r_host;
unsigned short iport, eport;
const char * leaseduration_str;
unsigned int leaseduration;
struct hostent *hp; /* getbyhostname() */
char ** ptr; /* getbyhostname() */
struct in_addr result_ip;/*unsigned char result_ip[16];*/ /* inet_pton() */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
int_port = GetValueFromNameValueList(&data, "NewInternalPort");
int_ip = GetValueFromNameValueList(&data, "NewInternalClient");
/* NewEnabled */
desc = GetValueFromNameValueList(&data, "NewPortMappingDescription");
leaseduration_str = GetValueFromNameValueList(&data, "NewLeaseDuration");
leaseduration = leaseduration_str ? atoi(leaseduration_str) : 0;
if(leaseduration == 0)
leaseduration = 604800;
if (!int_ip || !ext_port || !int_port)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
eport = (unsigned short)atoi(ext_port);
iport = (unsigned short)atoi(int_port);
if(iport == 0 || !is_numeric(ext_port)) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET, int_ip, &result_ip) <= 0)
{
hp = gethostbyname(int_ip);
if(hp && hp->h_addrtype == AF_INET)
{
for(ptr = hp->h_addr_list; ptr && *ptr; ptr++)
{
int_ip = inet_ntoa(*((struct in_addr *) *ptr));
result_ip = *((struct in_addr *) *ptr);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
}
/* check if NewInternalAddress is the client address */
if(GETFLAG(SECUREMODEMASK))
{
if(h->clientaddr.s_addr != result_ip.s_addr)
{
syslog(LOG_INFO, "Client %s tried to redirect port to %s",
inet_ntoa(h->clientaddr), int_ip);
ClearNameValueList(&data);
SoapError(h, 606, "Action not authorized");
return;
}
}
/* TODO : accept a different external port
* have some smart strategy to choose the port */
for(;;) {
r = upnp_redirect(r_host, eport, int_ip, iport, protocol, desc, leaseduration);
if(r==-2 && eport < 65535) {
eport++;
} else {
break;
}
}
ClearNameValueList(&data);
switch(r)
{
case 0: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/
eport, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -2: /* already redirected */
SoapError(h, 718, "ConflictInMappingEntry");
break;
case -3: /* not permitted */
SoapError(h, 606, "Action not authorized");
break;
default:
SoapError(h, 501, "ActionFailed");
}
}
static void
GetSpecificPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * r_host, * ext_port, * protocol;
unsigned short eport, iport;
char int_ip[32];
char desc[64];
unsigned int leaseduration = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif
#endif
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/* TODO : add r_host as an input parameter ...
* We prevent several Port Mapping with same external port
* but different remoteHost to be set up, so that is not
* a priority. */
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
NULL, 0,
&leaseduration);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
syslog(LOG_INFO, "%s: rhost='%s' %s %s found => %s:%u desc='%s'",
action,
r_host ? r_host : "NULL", ext_port, protocol, int_ip,
(unsigned int)iport, desc);
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*SERVICE_TYPE_WANIPC*/,
(unsigned int)iport, int_ip, desc, leaseduration,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
static void
DeletePortMapping(struct upnphttp * h, const char * action, const char * ns)
{
int r;
/*static const char resp[] =
"<u:DeletePortMappingResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * ext_port, * protocol;
unsigned short eport;
#ifdef UPNP_STRICT
const char * r_host;
#endif /* UPNP_STRICT */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ext_port = GetValueFromNameValueList(&data, "NewExternalPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
#ifdef UPNP_STRICT
r_host = GetValueFromNameValueList(&data, "NewRemoteHost");
#endif /* UPNP_STRICT */
#ifdef UPNP_STRICT
if(!ext_port || !protocol || !r_host)
#else
if(!ext_port || !protocol)
#endif /* UPNP_STRICT */
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#ifndef SUPPORT_REMOTEHOST
#ifdef UPNP_STRICT
if (r_host && (r_host[0] != '\0') && (0 != strcmp(r_host, "*")))
{
ClearNameValueList(&data);
SoapError(h, 726, "RemoteHostOnlySupportsWildcard");
return;
}
#endif /* UPNP_STRICT */
#endif /* SUPPORT_REMOTEHOST */
eport = (unsigned short)atoi(ext_port);
if(eport == 0)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: external port: %hu, protocol: %s",
action, eport, protocol);
/* if in secure mode, check the IP
* Removing a redirection is not a security threat,
* just an annoyance for the user using it. So this is not
* a priority. */
if(GETFLAG(SECUREMODEMASK))
{
char int_ip[32];
struct in_addr int_ip_addr;
unsigned short iport;
unsigned int leaseduration = 0;
r = upnp_get_redirection_infos(eport, protocol, &iport,
int_ip, sizeof(int_ip),
NULL, 0, NULL, 0,
&leaseduration);
if(r >= 0)
{
if(inet_pton(AF_INET, int_ip, &int_ip_addr) > 0)
{
if(h->clientaddr.s_addr != int_ip_addr.s_addr)
{
SoapError(h, 606, "Action not authorized");
/*SoapError(h, 714, "NoSuchEntryInArray");*/
ClearNameValueList(&data);
return;
}
}
}
}
r = upnp_delete_redirection(eport, protocol);
if(r < 0)
{
SoapError(h, 714, "NoSuchEntryInArray");
}
else
{
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* DeletePortMappingRange was added in IGD spec v2 */
static void
DeletePortMappingRange(struct upnphttp * h, const char * action, const char * ns)
{
int r = -1;
/*static const char resp[] =
"<u:DeletePortMappingRangeResponse "
"xmlns:u=\"" SERVICE_TYPE_WANIPC "\">"
"</u:DeletePortMappingRangeResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * protocol;
const char * startport_s, * endport_s;
unsigned short startport, endport;
/*int manage;*/
unsigned short * port_list;
unsigned int i, number = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage = atoi(GetValueFromNameValueList(&data, "NewManage"));*/
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/* possible errors :
606 - Action not authorized
730 - PortMappingNotFound
733 - InconsistentParameter
*/
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
syslog(LOG_INFO, "%s: deleting external ports: %hu-%hu, protocol: %s",
action, startport, endport, protocol);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &number);
if(number == 0)
{
SoapError(h, 730, "PortMappingNotFound");
ClearNameValueList(&data);
free(port_list);
return;
}
for(i = 0; i < number; i++)
{
r = upnp_delete_redirection(port_list[i], protocol);
syslog(LOG_INFO, "%s: deleting external port: %hu, protocol: %s: %s",
action, port_list[i], protocol, r < 0 ? "failed" : "ok");
}
free(port_list);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetGenericPortMappingEntry(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewRemoteHost>%s</NewRemoteHost>"
"<NewExternalPort>%u</NewExternalPort>"
"<NewProtocol>%s</NewProtocol>"
"<NewInternalPort>%u</NewInternalPort>"
"<NewInternalClient>%s</NewInternalClient>"
"<NewEnabled>1</NewEnabled>"
"<NewPortMappingDescription>%s</NewPortMappingDescription>"
"<NewLeaseDuration>%u</NewLeaseDuration>"
"</u:%sResponse>";
long int index = 0;
unsigned short eport, iport;
const char * m_index;
char * endptr;
char protocol[8], iaddr[32];
char desc[64];
char rhost[40];
unsigned int leaseduration = 0;
struct NameValueParserData data;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
m_index = GetValueFromNameValueList(&data, "NewPortMappingIndex");
if(!m_index)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
errno = 0; /* To distinguish success/failure after call */
index = strtol(m_index, &endptr, 10);
if((errno == ERANGE && (index == LONG_MAX || index == LONG_MIN))
|| (errno != 0 && index == 0) || (m_index == endptr))
{
/* should condition (*endptr != '\0') be also an error ? */
if(m_index == endptr)
syslog(LOG_WARNING, "%s: no digits were found in <%s>",
"GetGenericPortMappingEntry", "NewPortMappingIndex");
else
syslog(LOG_WARNING, "%s: strtol('%s'): %m",
"GetGenericPortMappingEntry", m_index);
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
syslog(LOG_INFO, "%s: index=%d", action, (int)index);
rhost[0] = '\0';
r = upnp_get_redirection_infos_by_index((int)index, &eport, protocol, &iport,
iaddr, sizeof(iaddr),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r < 0)
{
SoapError(h, 713, "SpecifiedArrayIndexInvalid");
}
else
{
int bodylen;
char body[2048];
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*SERVICE_TYPE_WANIPC,*/ rhost,
(unsigned int)eport, protocol, (unsigned int)iport, iaddr, desc,
leaseduration, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
ClearNameValueList(&data);
}
/* GetListOfPortMappings was added in the IGD v2 specification */
static void
GetListOfPortMappings(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp_start[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewPortListing><![CDATA[";
static const char resp_end[] =
"]]></NewPortListing>"
"</u:%sResponse>";
static const char list_start[] =
"<p:PortMappingList xmlns:p=\"urn:schemas-upnp-org:gw:WANIPConnection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:WANIPConnection"
" http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd\">";
static const char list_end[] =
"</p:PortMappingList>";
static const char entry[] =
"<p:PortMappingEntry>"
"<p:NewRemoteHost>%s</p:NewRemoteHost>"
"<p:NewExternalPort>%hu</p:NewExternalPort>"
"<p:NewProtocol>%s</p:NewProtocol>"
"<p:NewInternalPort>%hu</p:NewInternalPort>"
"<p:NewInternalClient>%s</p:NewInternalClient>"
"<p:NewEnabled>1</p:NewEnabled>"
"<p:NewDescription>%s</p:NewDescription>"
"<p:NewLeaseTime>%u</p:NewLeaseTime>"
"</p:PortMappingEntry>";
char * body;
size_t bodyalloc;
int bodylen;
int r = -1;
unsigned short iport;
char int_ip[32];
char desc[64];
char rhost[64];
unsigned int leaseduration = 0;
struct NameValueParserData data;
const char * startport_s, * endport_s;
unsigned short startport, endport;
const char * protocol;
/*int manage;*/
const char * number_s;
int number;
unsigned short * port_list;
unsigned int i, list_size = 0;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
startport_s = GetValueFromNameValueList(&data, "NewStartPort");
endport_s = GetValueFromNameValueList(&data, "NewEndPort");
protocol = GetValueFromNameValueList(&data, "NewProtocol");
/*manage_s = GetValueFromNameValueList(&data, "NewManage");*/
number_s = GetValueFromNameValueList(&data, "NewNumberOfPorts");
if(startport_s == NULL || endport_s == NULL || protocol == NULL ||
number_s == NULL || !is_numeric(number_s) ||
!is_numeric(startport_s) || !is_numeric(endport_s)) {
SoapError(h, 402, "Invalid Args");
ClearNameValueList(&data);
return;
}
startport = (unsigned short)atoi(startport_s);
endport = (unsigned short)atoi(endport_s);
/*manage = atoi(manage_s);*/
number = atoi(number_s);
if(number == 0) number = 1000; /* return up to 1000 mappings by default */
if(startport > endport)
{
SoapError(h, 733, "InconsistentParameter");
ClearNameValueList(&data);
return;
}
/*
build the PortMappingList xml document :
<p:PortMappingList xmlns:p="urn:schemas-upnp-org:gw:WANIPConnection"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:schemas-upnp-org:gw:WANIPConnection
http://www.upnp.org/schemas/gw/WANIPConnection-v2.xsd">
<p:PortMappingEntry>
<p:NewRemoteHost>202.233.2.1</p:NewRemoteHost>
<p:NewExternalPort>2345</p:NewExternalPort>
<p:NewProtocol>TCP</p:NewProtocol>
<p:NewInternalPort>2345</p:NewInternalPort>
<p:NewInternalClient>192.168.1.137</p:NewInternalClient>
<p:NewEnabled>1</p:NewEnabled>
<p:NewDescription>dooom</p:NewDescription>
<p:NewLeaseTime>345</p:NewLeaseTime>
</p:PortMappingEntry>
</p:PortMappingList>
*/
bodyalloc = 4096;
body = malloc(bodyalloc);
if(!body)
{
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
return;
}
bodylen = snprintf(body, bodyalloc, resp_start,
action, ns/*SERVICE_TYPE_WANIPC*/);
if(bodylen < 0)
{
SoapError(h, 501, "ActionFailed");
free(body);
return;
}
memcpy(body+bodylen, list_start, sizeof(list_start));
bodylen += (sizeof(list_start) - 1);
port_list = upnp_get_portmappings_in_range(startport, endport,
protocol, &list_size);
/* loop through port mappings */
for(i = 0; number > 0 && i < list_size; i++)
{
/* have a margin of 1024 bytes to store the new entry */
if((unsigned int)bodylen + 1024 > bodyalloc)
{
char * body_sav = body;
bodyalloc += 4096;
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
free(port_list);
return;
}
}
rhost[0] = '\0';
r = upnp_get_redirection_infos(port_list[i], protocol, &iport,
int_ip, sizeof(int_ip),
desc, sizeof(desc),
rhost, sizeof(rhost),
&leaseduration);
if(r == 0)
{
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, entry,
rhost, port_list[i], protocol,
iport, int_ip, desc, leaseduration);
number--;
}
}
free(port_list);
port_list = NULL;
if((bodylen + sizeof(list_end) + 1024) > bodyalloc)
{
char * body_sav = body;
bodyalloc += (sizeof(list_end) + 1024);
body = realloc(body, bodyalloc);
if(!body)
{
syslog(LOG_CRIT, "realloc(%p, %u) FAILED", body_sav, (unsigned)bodyalloc);
ClearNameValueList(&data);
SoapError(h, 501, "ActionFailed");
free(body_sav);
return;
}
}
memcpy(body+bodylen, list_end, sizeof(list_end));
bodylen += (sizeof(list_end) - 1);
bodylen += snprintf(body+bodylen, bodyalloc-bodylen, resp_end,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
free(body);
ClearNameValueList(&data);
}
#ifdef ENABLE_L3F_SERVICE
static void
SetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
/*static const char resp[] =
"<u:SetDefaultConnectionServiceResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:Layer3Forwarding:1\">"
"</u:SetDefaultConnectionServiceResponse>";*/
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * p;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
p = GetValueFromNameValueList(&data, "NewDefaultConnectionService");
if(p) {
/* 720 InvalidDeviceUUID
* 721 InvalidServiceID
* 723 InvalidConnServiceSelection */
#ifdef UPNP_STRICT
char * service;
service = strchr(p, ',');
if(0 != memcmp(uuidvalue_wcd, p, sizeof("uuid:00000000-0000-0000-0000-000000000000") - 1)) {
SoapError(h, 720, "InvalidDeviceUUID");
} else if(service == NULL || 0 != strcmp(service+1, SERVICE_ID_WANIPC)) {
SoapError(h, 721, "InvalidServiceID");
} else
#endif
{
syslog(LOG_INFO, "%s(%s) : Ignored", action, p);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
} else {
/* missing argument */
SoapError(h, 402, "Invalid Args");
}
ClearNameValueList(&data);
}
static void
GetDefaultConnectionService(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
#ifdef IGD_V2
"<NewDefaultConnectionService>%s:WANConnectionDevice:2,"
#else
"<NewDefaultConnectionService>%s:WANConnectionDevice:1,"
#endif
SERVICE_ID_WANIPC "</NewDefaultConnectionService>"
"</u:%sResponse>";
/* example from UPnP_IGD_Layer3Forwarding 1.0.pdf :
* uuid:44f5824f-c57d-418c-a131-f22b34e14111:WANConnectionDevice:1,
* urn:upnp-org:serviceId:WANPPPConn1 */
char body[1024];
int bodylen;
/* namespace : urn:schemas-upnp-org:service:Layer3Forwarding:1 */
bodylen = snprintf(body, sizeof(body), resp,
action, ns, uuidvalue_wcd, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Added for compliance with WANIPConnection v2 */
static void
SetConnectionType(struct upnphttp * h, const char * action, const char * ns)
{
#ifdef UPNP_STRICT
const char * connection_type;
#endif /* UPNP_STRICT */
struct NameValueParserData data;
UNUSED(action);
UNUSED(ns);
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
#ifdef UPNP_STRICT
connection_type = GetValueFromNameValueList(&data, "NewConnectionType");
if(!connection_type) {
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
#endif /* UPNP_STRICT */
/* Unconfigured, IP_Routed, IP_Bridged */
ClearNameValueList(&data);
/* always return a ReadOnly error */
SoapError(h, 731, "ReadOnly");
}
/* Added for compliance with WANIPConnection v2 */
static void
RequestConnection(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/* Added for compliance with WANIPConnection v2 */
static void
ForceTermination(struct upnphttp * h, const char * action, const char * ns)
{
UNUSED(action);
UNUSED(ns);
SoapError(h, 606, "Action not authorized");
}
/*
If a control point calls QueryStateVariable on a state variable that is not
buffered in memory within (or otherwise available from) the service,
the service must return a SOAP fault with an errorCode of 404 Invalid Var.
QueryStateVariable remains useful as a limited test tool but may not be
part of some future versions of UPnP.
*/
static void
QueryStateVariable(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<return>%s</return>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * var_name;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
/*var_name = GetValueFromNameValueList(&data, "QueryStateVariable"); */
/*var_name = GetValueFromNameValueListIgnoreNS(&data, "varName");*/
var_name = GetValueFromNameValueList(&data, "varName");
/*syslog(LOG_INFO, "QueryStateVariable(%.40s)", var_name); */
if(!var_name)
{
SoapError(h, 402, "Invalid Args");
}
else if(strcmp(var_name, "ConnectionStatus") == 0)
{
const char * status;
status = get_wan_connection_status_str(ext_if_name);
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#if 0
/* not useful */
else if(strcmp(var_name, "ConnectionType") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "IP_Routed");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(strcmp(var_name, "LastConnectionError") == 0)
{
bodylen = snprintf(body, sizeof(body), resp, "ERROR_NONE");
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
else if(strcmp(var_name, "PortMappingNumberOfEntries") == 0)
{
char strn[10];
snprintf(strn, sizeof(strn), "%i",
upnp_get_portmapping_number_of_entries());
bodylen = snprintf(body, sizeof(body), resp,
action, ns,/*"urn:schemas-upnp-org:control-1-0",*/
strn, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else
{
syslog(LOG_NOTICE, "%s: Unknown: %s", action, var_name?var_name:"");
SoapError(h, 404, "Invalid Var");
}
ClearNameValueList(&data);
}
#ifdef ENABLE_6FC_SERVICE
#ifndef ENABLE_IPV6
#error "ENABLE_6FC_SERVICE needs ENABLE_IPV6"
#endif
/* WANIPv6FirewallControl actions */
static void
GetFirewallStatus(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<FirewallEnabled>%d</FirewallEnabled>"
"<InboundPinholeAllowed>%d</InboundPinholeAllowed>"
"</u:%sResponse>";
char body[512];
int bodylen;
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1",*/
GETFLAG(IPV6FCFWDISABLEDMASK) ? 0 : 1,
GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK) ? 0 : 1,
action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static int
CheckStatus(struct upnphttp * h)
{
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return 0;
}
else if(GETFLAG(IPV6FCINBOUNDDISALLOWEDMASK))
{
SoapError(h, 703, "InboundPinholeNotAllowed");
return 0;
}
else
return 1;
}
#if 0
static int connecthostport(const char * host, unsigned short port, char * result)
{
int s, n;
char hostname[INET6_ADDRSTRLEN];
char port_str[8], ifname[8], tmp[4];
struct addrinfo *ai, *p;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
/* hints.ai_flags = AI_ADDRCONFIG; */
#ifdef AI_NUMERICSERV
hints.ai_flags = AI_NUMERICSERV;
#endif
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */
/* hints.ai_protocol = IPPROTO_TCP; */
snprintf(port_str, sizeof(port_str), "%hu", port);
strcpy(hostname, host);
if(!strncmp(host, "fe80", 4))
{
printf("Using an linklocal address\n");
strcpy(ifname, "%");
snprintf(tmp, sizeof(tmp), "%d", linklocal_index);
strcat(ifname, tmp);
strcat(hostname, ifname);
printf("host: %s\n", hostname);
}
n = getaddrinfo(hostname, port_str, &hints, &ai);
if(n != 0)
{
fprintf(stderr, "getaddrinfo() error : %s\n", gai_strerror(n));
return -1;
}
s = -1;
for(p = ai; p; p = p->ai_next)
{
#ifdef DEBUG
char tmp_host[256];
char tmp_service[256];
printf("ai_family=%d ai_socktype=%d ai_protocol=%d ai_addrlen=%d\n ",
p->ai_family, p->ai_socktype, p->ai_protocol, p->ai_addrlen);
getnameinfo(p->ai_addr, p->ai_addrlen, tmp_host, sizeof(tmp_host),
tmp_service, sizeof(tmp_service),
NI_NUMERICHOST | NI_NUMERICSERV);
printf(" host=%s service=%s\n", tmp_host, tmp_service);
#endif
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), result, INET6_ADDRSTRLEN);
return 0;
}
freeaddrinfo(ai);
}
#endif
/* Check the security policy right */
static int
PinholeVerification(struct upnphttp * h, char * int_ip, unsigned short int_port)
{
int n;
char senderAddr[INET6_ADDRSTRLEN]="";
struct addrinfo hints, *ai, *p;
struct in6_addr result_ip;
/* Pinhole InternalClient address must correspond to the action sender */
syslog(LOG_INFO, "Checking internal IP@ and port (Security policy purpose)");
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
/* if ip not valid assume hostname and convert */
if (inet_pton(AF_INET6, int_ip, &result_ip) <= 0)
{
n = getaddrinfo(int_ip, NULL, &hints, &ai);
if(!n && ai->ai_family == AF_INET6)
{
for(p = ai; p; p = p->ai_next)
{
inet_ntop(AF_INET6, (struct in6_addr *) p, int_ip, sizeof(struct in6_addr));
result_ip = *((struct in6_addr *) p);
/* TODO : deal with more than one ip per hostname */
break;
}
}
else
{
syslog(LOG_ERR, "Failed to convert hostname '%s' to ip address", int_ip);
SoapError(h, 402, "Invalid Args");
return -1;
}
freeaddrinfo(p);
}
if(inet_ntop(AF_INET6, &(h->clientaddr_v6), senderAddr, INET6_ADDRSTRLEN) == NULL)
{
syslog(LOG_ERR, "inet_ntop: %m");
}
#ifdef DEBUG
printf("\tPinholeVerification:\n\t\tCompare sender @: %s\n\t\t to intClient @: %s\n", senderAddr, int_ip);
#endif
if(strcmp(senderAddr, int_ip) != 0)
if(h->clientaddr_v6.s6_addr != result_ip.s6_addr)
{
syslog(LOG_INFO, "Client %s tried to access pinhole for internal %s and is not authorized to do it",
senderAddr, int_ip);
SoapError(h, 606, "Action not authorized");
return 0;
}
/* Pinhole InternalPort must be greater than or equal to 1024 */
if (int_port < 1024)
{
syslog(LOG_INFO, "Client %s tried to access pinhole with port < 1024 and is not authorized to do it",
senderAddr);
SoapError(h, 606, "Action not authorized");
return 0;
}
return 1;
}
static void
AddPinhole(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<UniqueID>%d</UniqueID>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * rem_host, * rem_port, * int_ip, * int_port, * protocol, * leaseTime;
int uid = 0;
unsigned short iport, rport;
int ltime;
long proto;
char rem_ip[INET6_ADDRSTRLEN];
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
protocol = GetValueFromNameValueList(&data, "Protocol");
leaseTime = GetValueFromNameValueList(&data, "LeaseTime");
rport = (unsigned short)(rem_port ? atoi(rem_port) : 0);
iport = (unsigned short)(int_port ? atoi(int_port) : 0);
ltime = leaseTime ? atoi(leaseTime) : -1;
errno = 0;
proto = protocol ? strtol(protocol, NULL, 0) : -1;
if(errno != 0 || proto > 65535 || proto < 0)
{
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(iport == 0)
{
SoapError(h, 706, "InternalPortWilcardingNotAllowed");
goto clear_and_exit;
}
/* In particular, [IGD2] RECOMMENDS that unauthenticated and
* unauthorized control points are only allowed to invoke
* this action with:
* - InternalPort value greater than or equal to 1024,
* - InternalClient value equals to the control point's IP address.
* It is REQUIRED that InternalClient cannot be one of IPv6
* addresses used by the gateway. */
if(!int_ip || int_ip[0] == '\0' || 0 == strcmp(int_ip, "*"))
{
SoapError(h, 708, "WildCardNotPermittedInSrcIP");
goto clear_and_exit;
}
/* I guess it is useless to convert int_ip to literal ipv6 address */
if(rem_host)
{
/* trim */
while(isspace(rem_host[0]))
rem_host++;
}
/* rem_host should be converted to literal ipv6 : */
if(rem_host && (rem_host[0] != '\0') && (rem_host[0] != '*'))
{
struct addrinfo *ai, *p;
struct addrinfo hints;
int err;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET6;
/*hints.ai_flags = */
/* hints.ai_protocol = proto; */
err = getaddrinfo(rem_host, rem_port, &hints, &ai);
if(err == 0)
{
/* take the 1st IPv6 address */
for(p = ai; p; p = p->ai_next)
{
if(p->ai_family == AF_INET6)
{
inet_ntop(AF_INET6,
&(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr),
rem_ip, sizeof(rem_ip));
syslog(LOG_INFO, "resolved '%s' to '%s'", rem_host, rem_ip);
rem_host = rem_ip;
break;
}
}
freeaddrinfo(ai);
}
else
{
syslog(LOG_WARNING, "AddPinhole : getaddrinfo(%s) : %s",
rem_host, gai_strerror(err));
#if 0
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
#endif
}
}
if(proto == 65535)
{
SoapError(h, 707, "ProtocolWilcardingNotAllowed");
goto clear_and_exit;
}
if(proto != IPPROTO_UDP && proto != IPPROTO_TCP
#ifdef IPPROTO_UDPITE
&& atoi(protocol) != IPPROTO_UDPLITE
#endif
)
{
SoapError(h, 705, "ProtocolNotSupported");
goto clear_and_exit;
}
if(ltime < 1 || ltime > 86400)
{
syslog(LOG_WARNING, "%s: LeaseTime=%d not supported, (ip=%s)",
action, ltime, int_ip);
SoapError(h, 402, "Invalid Args");
goto clear_and_exit;
}
if(PinholeVerification(h, int_ip, iport) <= 0)
goto clear_and_exit;
syslog(LOG_INFO, "%s: (inbound) from [%s]:%hu to [%s]:%hu with proto %ld during %d sec",
action, rem_host?rem_host:"any",
rport, int_ip, iport,
proto, ltime);
/* In cases where the RemoteHost, RemotePort, InternalPort,
* InternalClient and Protocol are the same than an existing pinhole,
* but LeaseTime is different, the device MUST extend the existing
* pinhole's lease time and return the UniqueID of the existing pinhole. */
r = upnp_add_inboundpinhole(rem_host, rport, int_ip, iport, proto, "IGD2 pinhole", ltime, &uid);
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body),
resp, action,
ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
uid, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -1: /* not permitted */
SoapError(h, 701, "PinholeSpaceExhausted");
break;
default:
SoapError(h, 501, "ActionFailed");
break;
}
/* 606 Action not authorized
* 701 PinholeSpaceExhausted
* 702 FirewallDisabled
* 703 InboundPinholeNotAllowed
* 705 ProtocolNotSupported
* 706 InternalPortWildcardingNotAllowed
* 707 ProtocolWildcardingNotAllowed
* 708 WildCardNotPermittedInSrcIP */
clear_and_exit:
ClearNameValueList(&data);
}
static void
UpdatePinhole(struct upnphttp * h, const char * action, const char * ns)
{
#if 0
static const char resp[] =
"<u:UpdatePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:UpdatePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str, * leaseTime;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
int ltime;
int uid;
int n;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
leaseTime = GetValueFromNameValueList(&data, "NewLeaseTime");
uid = uid_str ? atoi(uid_str) : -1;
ltime = leaseTime ? atoi(leaseTime) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535 || ltime <= 0 || ltime > 86400)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not updating an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) updating lease duration to %d for pinhole with ID: %d",
action, ltime, uid);
n = upnp_update_inboundpinhole(uid, ltime);
if(n == -1)
SoapError(h, 704, "NoSuchEntry");
else if(n < 0)
SoapError(h, 501, "ActionFailed");
else {
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
}
static void
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
static void
DeletePinhole(struct upnphttp * h, const char * action, const char * ns)
{
int n;
#if 0
static const char resp[] =
"<u:DeletePinholeResponse "
"xmlns:u=\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\">"
"</u:DeletePinholeResponse>";
#endif
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
char iaddr[INET6_ADDRSTRLEN];
int proto;
unsigned short iport;
unsigned int leasetime;
int uid;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not deleting an pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, NULL);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return;
}
else if(n == -2)
{
SoapError(h, 704, "NoSuchEntry");
return;
}
else
{
SoapError(h, 501, "ActionFailed");
return;
}
n = upnp_delete_inboundpinhole(uid);
if(n < 0)
{
syslog(LOG_INFO, "%s: (inbound) failed to remove pinhole with ID: %d",
action, uid);
SoapError(h, 501, "ActionFailed");
return;
}
syslog(LOG_INFO, "%s: (inbound) pinhole with ID %d successfully removed",
action, uid);
bodylen = snprintf(body, sizeof(body), resp,
action, ns, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
CheckPinholeWorking(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<IsWorking>%d</IsWorking>"
"</u:%sResponse>";
char body[512];
int bodylen;
int r;
struct NameValueParserData data;
const char * uid_str;
int uid;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not checking a pinhole
* it doesn't have access to, because of its public access */
r = upnp_get_pinhole_info(uid,
NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
NULL, /* proto */
NULL, 0, /* desc, desclen */
NULL, &packets);
if (r >= 0)
{
if(PinholeVerification(h, iaddr, iport) <= 0)
return ;
if(packets == 0)
{
SoapError(h, 709, "NoPacketSent");
return;
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
1, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
else if(r == -2)
SoapError(h, 704, "NoSuchEntry");
else
SoapError(h, 501, "ActionFailed");
}
static void
GetPinholePackets(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<PinholePackets>%u</PinholePackets>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
const char * uid_str;
int n;
char iaddr[INET6_ADDRSTRLEN];
unsigned short iport;
unsigned int packets = 0;
int uid;
int proto;
unsigned int leasetime;
if(CheckStatus(h)==0)
return;
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
uid_str = GetValueFromNameValueList(&data, "UniqueID");
uid = uid_str ? atoi(uid_str) : -1;
ClearNameValueList(&data);
if(uid < 0 || uid > 65535)
{
SoapError(h, 402, "Invalid Args");
return;
}
/* Check that client is not getting infos of a pinhole
* it doesn't have access to, because of its public access */
n = upnp_get_pinhole_info(uid, NULL, 0, NULL,
iaddr, sizeof(iaddr), &iport,
&proto,
NULL, 0, /* desc, desclen */
&leasetime, &packets);
if (n >= 0)
{
if(PinholeVerification(h, iaddr, iport)<=0)
return ;
}
#if 0
else if(r == -4 || r == -1)
{
SoapError(h, 704, "NoSuchEntry");
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
packets, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
#ifdef ENABLE_DP_SERVICE
static void
SendSetupMessage(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutMessage>%s</OutMessage>"
"</u:%sResponse>";
char body[1024];
int bodylen;
struct NameValueParserData data;
const char * ProtocolType; /* string */
const char * InMessage; /* base64 */
const char * OutMessage = ""; /* base64 */
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
ProtocolType = GetValueFromNameValueList(&data, "ProtocolType"); /* string */
InMessage = GetValueFromNameValueList(&data, "InMessage"); /* base64 */
if(ProtocolType == NULL || InMessage == NULL)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
/*if(strcmp(ProtocolType, "DeviceProtection:1") != 0)*/
if(strcmp(ProtocolType, "WPS") != 0)
{
ClearNameValueList(&data);
SoapError(h, 600, "Argument Value Invalid"); /* 703 ? */
return;
}
/* TODO : put here code for WPS */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
OutMessage, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
ClearNameValueList(&data);
}
static void
GetSupportedProtocols(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<ProtocolList><![CDATA[%s]]></ProtocolList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * ProtocolList =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<SupportedProtocols xmlns=\"urn:schemas-upnp-org:gw:DeviceProtection\""
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
" xsi:schemaLocation=\"urn:schemas-upnp-org:gw:DeviceProtection"
" http://www.upnp.org/schemas/gw/DeviceProtection-v1.xsd\">"
"<Introduction><Name>WPS</Name></Introduction>"
"<Login><Name>PKCS5</Name></Login>"
"</SupportedProtocols>";
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
ProtocolList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
static void
GetAssignedRoles(struct upnphttp * h, const char * action, const char * ns)
{
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<RoleList>%s</RoleList>"
"</u:%sResponse>";
char body[1024];
int bodylen;
const char * RoleList = "Public"; /* list of roles separated by spaces */
#ifdef ENABLE_HTTPS
if(h->ssl != NULL) {
/* we should get the Roles of the session (based on client certificate) */
X509 * peercert;
peercert = SSL_get_peer_certificate(h->ssl);
if(peercert != NULL) {
RoleList = "Admin Basic";
X509_free(peercert);
}
}
#endif
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:DeviceProtection:1"*/,
RoleList, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
#endif
/* Windows XP as client send the following requests :
* GetConnectionTypeInfo
* GetNATRSIPStatus
* ? GetTotalBytesSent - WANCommonInterfaceConfig
* ? GetTotalBytesReceived - idem
* ? GetTotalPacketsSent - idem
* ? GetTotalPacketsReceived - idem
* GetCommonLinkProperties - idem
* GetStatusInfo - WANIPConnection
* GetExternalIPAddress
* QueryStateVariable / ConnectionStatus!
*/
static const struct
{
const char * methodName;
void (*methodImpl)(struct upnphttp *, const char *, const char *);
}
soapMethods[] =
{
/* WANCommonInterfaceConfig */
{ "QueryStateVariable", QueryStateVariable},
{ "GetTotalBytesSent", GetTotalBytesSent},
{ "GetTotalBytesReceived", GetTotalBytesReceived},
{ "GetTotalPacketsSent", GetTotalPacketsSent},
{ "GetTotalPacketsReceived", GetTotalPacketsReceived},
{ "GetCommonLinkProperties", GetCommonLinkProperties},
{ "GetStatusInfo", GetStatusInfo},
/* WANIPConnection */
{ "GetConnectionTypeInfo", GetConnectionTypeInfo },
{ "GetNATRSIPStatus", GetNATRSIPStatus},
{ "GetExternalIPAddress", GetExternalIPAddress},
{ "AddPortMapping", AddPortMapping},
{ "DeletePortMapping", DeletePortMapping},
{ "GetGenericPortMappingEntry", GetGenericPortMappingEntry},
{ "GetSpecificPortMappingEntry", GetSpecificPortMappingEntry},
/* Required in WANIPConnection:2 */
{ "SetConnectionType", SetConnectionType},
{ "RequestConnection", RequestConnection},
{ "ForceTermination", ForceTermination},
{ "AddAnyPortMapping", AddAnyPortMapping},
{ "DeletePortMappingRange", DeletePortMappingRange},
{ "GetListOfPortMappings", GetListOfPortMappings},
#ifdef ENABLE_L3F_SERVICE
/* Layer3Forwarding */
{ "SetDefaultConnectionService", SetDefaultConnectionService},
{ "GetDefaultConnectionService", GetDefaultConnectionService},
#endif
#ifdef ENABLE_6FC_SERVICE
/* WANIPv6FirewallControl */
{ "GetFirewallStatus", GetFirewallStatus}, /* Required */
{ "AddPinhole", AddPinhole}, /* Required */
{ "UpdatePinhole", UpdatePinhole}, /* Required */
{ "GetOutboundPinholeTimeout", GetOutboundPinholeTimeout}, /* Optional */
{ "DeletePinhole", DeletePinhole}, /* Required */
{ "CheckPinholeWorking", CheckPinholeWorking}, /* Optional */
{ "GetPinholePackets", GetPinholePackets}, /* Required */
#endif
#ifdef ENABLE_DP_SERVICE
/* DeviceProtection */
{ "SendSetupMessage", SendSetupMessage}, /* Required */
{ "GetSupportedProtocols", GetSupportedProtocols}, /* Required */
{ "GetAssignedRoles", GetAssignedRoles}, /* Required */
#endif
{ 0, 0 }
};
void
ExecuteSoapAction(struct upnphttp * h, const char * action, int n)
{
char * p;
char * p2;
int i, len, methodlen;
char namespace[256];
/* SoapAction example :
* urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo */
p = strchr(action, '#');
if(p && (p - action) < n) {
for(i = 0; i < ((int)sizeof(namespace) - 1) && (action + i) < p; i++)
namespace[i] = action[i];
namespace[i] = '\0';
p++;
p2 = strchr(p, '"');
if(p2 && (p2 - action) <= n)
methodlen = p2 - p;
else
methodlen = n - (p - action);
/*syslog(LOG_DEBUG, "SoapMethod: %.*s %d %d %p %p %d",
methodlen, p, methodlen, n, action, p, (int)(p - action));*/
for(i = 0; soapMethods[i].methodName; i++) {
len = strlen(soapMethods[i].methodName);
if((len == methodlen) && memcmp(p, soapMethods[i].methodName, len) == 0) {
#ifdef DEBUG
syslog(LOG_DEBUG, "Remote Call of SoapMethod '%s' %s",
soapMethods[i].methodName, namespace);
#endif /* DEBUG */
soapMethods[i].methodImpl(h, soapMethods[i].methodName, namespace);
return;
}
}
syslog(LOG_NOTICE, "SoapMethod: Unknown: %.*s %s", methodlen, p, namespace);
} else {
syslog(LOG_NOTICE, "cannot parse SoapAction");
}
SoapError(h, 401, "Invalid Action");
}
/* Standard Errors:
*
* errorCode errorDescription Description
* -------- ---------------- -----------
* 401 Invalid Action No action by that name at this service.
* 402 Invalid Args Could be any of the following: not enough in args,
* too many in args, no in arg by that name,
* one or more in args are of the wrong data type.
* 403 Out of Sync Out of synchronization.
* 501 Action Failed May be returned in current state of service
* prevents invoking that action.
* 600-699 TBD Common action errors. Defined by UPnP Forum
* Technical Committee.
* 700-799 TBD Action-specific errors for standard actions.
* Defined by UPnP Forum working committee.
* 800-899 TBD Action-specific errors for non-standard actions.
* Defined by UPnP vendor.
*/
void
SoapError(struct upnphttp * h, int errCode, const char * errDesc)
{
static const char resp[] =
"<s:Envelope "
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
"<s:Body>"
"<s:Fault>"
"<faultcode>s:Client</faultcode>"
"<faultstring>UPnPError</faultstring>"
"<detail>"
"<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">"
"<errorCode>%d</errorCode>"
"<errorDescription>%s</errorDescription>"
"</UPnPError>"
"</detail>"
"</s:Fault>"
"</s:Body>"
"</s:Envelope>";
char body[2048];
int bodylen;
syslog(LOG_INFO, "Returning UPnPError %d: %s", errCode, errDesc);
bodylen = snprintf(body, sizeof(body), resp, errCode, errDesc);
BuildResp2_upnphttp(h, 500, "Internal Server Error", body, bodylen);
SendRespAndClose_upnphttp(h);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_861_0 |
crossvul-cpp_data_good_3381_0 | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ecma-alloc.h"
#include "ecma-helpers.h"
#include "ecma-function-object.h"
#include "ecma-literal-storage.h"
#include "js-parser-internal.h"
#include "lit-char-helpers.h"
#if JERRY_JS_PARSER
/** \addtogroup parser Parser
* @{
*
* \addtogroup jsparser JavaScript
* @{
*
* \addtogroup jsparser_lexer Lexer
* @{
*/
#define IS_UTF8_INTERMEDIATE_OCTET(byte) (((byte) & LIT_UTF8_EXTRA_BYTE_MASK) == LIT_UTF8_2_BYTE_CODE_POINT_MIN)
/**
* Align column to the next tab position.
*
* @return aligned position
*/
static parser_line_counter_t
align_column_to_tab (parser_line_counter_t column) /**< current column */
{
/* Tab aligns to zero column start position. */
return (parser_line_counter_t) (((column + (8u - 1u)) & ~ECMA_STRING_CONTAINER_MASK) + 1u);
} /* align_column_to_tab */
/**
* Parse hexadecimal character sequence
*
* @return character value
*/
ecma_char_t
lexer_hex_to_character (parser_context_t *context_p, /**< context */
const uint8_t *source_p, /**< current source position */
int length) /**< source length */
{
uint32_t result = 0;
do
{
uint32_t byte = *source_p++;
result <<= 4;
if (byte >= LIT_CHAR_0 && byte <= LIT_CHAR_9)
{
result += byte - LIT_CHAR_0;
}
else
{
byte = LEXER_TO_ASCII_LOWERCASE (byte);
if (byte >= LIT_CHAR_LOWERCASE_A && byte <= LIT_CHAR_LOWERCASE_F)
{
result += byte - (LIT_CHAR_LOWERCASE_A - 10);
}
else
{
parser_raise_error (context_p, PARSER_ERR_INVALID_ESCAPE_SEQUENCE);
}
}
}
while (--length > 0);
return (ecma_char_t) result;
} /* lexer_hex_to_character */
/**
* Skip space mode
*/
typedef enum
{
LEXER_SKIP_SPACES, /**< skip spaces mode */
LEXER_SKIP_SINGLE_LINE_COMMENT, /**< parse single line comment */
LEXER_SKIP_MULTI_LINE_COMMENT, /**< parse multi line comment */
} skip_mode_t;
/**
* Skip spaces.
*/
static void
skip_spaces (parser_context_t *context_p) /**< context */
{
skip_mode_t mode = LEXER_SKIP_SPACES;
const uint8_t *source_end_p = context_p->source_end_p;
context_p->token.was_newline = 0;
while (true)
{
if (context_p->source_p >= source_end_p)
{
if (mode == LEXER_SKIP_MULTI_LINE_COMMENT)
{
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_MULTILINE_COMMENT);
}
return;
}
switch (context_p->source_p[0])
{
case LIT_CHAR_CR:
{
if (context_p->source_p + 1 < source_end_p
&& context_p->source_p[1] == LIT_CHAR_LF)
{
context_p->source_p++;
}
/* FALLTHRU */
}
case LIT_CHAR_LF:
{
context_p->line++;
context_p->column = 0;
context_p->token.was_newline = 1;
if (mode == LEXER_SKIP_SINGLE_LINE_COMMENT)
{
mode = LEXER_SKIP_SPACES;
}
/* FALLTHRU */
}
case LIT_CHAR_VTAB:
case LIT_CHAR_FF:
case LIT_CHAR_SP:
{
context_p->source_p++;
context_p->column++;
continue;
}
case LIT_CHAR_TAB:
{
context_p->column = align_column_to_tab (context_p->column);
context_p->source_p++;
continue;
}
case LIT_CHAR_SLASH:
{
if (mode == LEXER_SKIP_SPACES
&& context_p->source_p + 1 < source_end_p)
{
if (context_p->source_p[1] == LIT_CHAR_SLASH)
{
mode = LEXER_SKIP_SINGLE_LINE_COMMENT;
}
else if (context_p->source_p[1] == LIT_CHAR_ASTERISK)
{
mode = LEXER_SKIP_MULTI_LINE_COMMENT;
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
}
if (mode != LEXER_SKIP_SPACES)
{
context_p->source_p += 2;
PARSER_PLUS_EQUAL_LC (context_p->column, 2);
continue;
}
}
break;
}
case LIT_CHAR_ASTERISK:
{
if (mode == LEXER_SKIP_MULTI_LINE_COMMENT
&& context_p->source_p + 1 < source_end_p
&& context_p->source_p[1] == LIT_CHAR_SLASH)
{
mode = LEXER_SKIP_SPACES;
context_p->source_p += 2;
PARSER_PLUS_EQUAL_LC (context_p->column, 2);
continue;
}
break;
}
case 0xc2:
{
if (context_p->source_p + 1 < source_end_p
&& context_p->source_p[1] == 0xa0)
{
/* Codepoint \u00A0 */
context_p->source_p += 2;
context_p->column++;
continue;
}
break;
}
case LEXER_NEWLINE_LS_PS_BYTE_1:
{
JERRY_ASSERT (context_p->source_p + 2 < source_end_p);
if (LEXER_NEWLINE_LS_PS_BYTE_23 (context_p->source_p))
{
/* Codepoint \u2028 and \u2029 */
context_p->source_p += 3;
context_p->line++;
context_p->column = 1;
context_p->token.was_newline = 1;
if (mode == LEXER_SKIP_SINGLE_LINE_COMMENT)
{
mode = LEXER_SKIP_SPACES;
}
continue;
}
break;
}
case 0xef:
{
if (context_p->source_p + 2 < source_end_p
&& context_p->source_p[1] == 0xbb
&& context_p->source_p[2] == 0xbf)
{
/* Codepoint \uFEFF */
context_p->source_p += 3;
context_p->column++;
continue;
}
break;
}
default:
{
break;
}
}
if (mode == LEXER_SKIP_SPACES)
{
return;
}
context_p->source_p++;
if (context_p->source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (context_p->source_p[0]))
{
context_p->column++;
}
}
} /* skip_spaces */
/**
* Keyword data.
*/
typedef struct
{
const uint8_t *keyword_p; /**< keyword string */
lexer_token_type_t type; /**< keyword token type */
} keyword_string_t;
#define LEXER_KEYWORD(name, type) { (const uint8_t *) (name), (type) }
#define LEXER_KEYWORD_END() { (const uint8_t *) NULL, LEXER_EOS }
/**
* Keywords with 2 characters.
*/
static const keyword_string_t keyword_length_2[4] =
{
LEXER_KEYWORD ("do", LEXER_KEYW_DO),
LEXER_KEYWORD ("if", LEXER_KEYW_IF),
LEXER_KEYWORD ("in", LEXER_KEYW_IN),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 3 characters.
*/
static const keyword_string_t keyword_length_3[6] =
{
LEXER_KEYWORD ("for", LEXER_KEYW_FOR),
LEXER_KEYWORD ("let", LEXER_KEYW_LET),
LEXER_KEYWORD ("new", LEXER_KEYW_NEW),
LEXER_KEYWORD ("try", LEXER_KEYW_TRY),
LEXER_KEYWORD ("var", LEXER_KEYW_VAR),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 4 characters.
*/
static const keyword_string_t keyword_length_4[9] =
{
LEXER_KEYWORD ("case", LEXER_KEYW_CASE),
LEXER_KEYWORD ("else", LEXER_KEYW_ELSE),
LEXER_KEYWORD ("enum", LEXER_KEYW_ENUM),
LEXER_KEYWORD ("null", LEXER_LIT_NULL),
LEXER_KEYWORD ("this", LEXER_KEYW_THIS),
LEXER_KEYWORD ("true", LEXER_LIT_TRUE),
LEXER_KEYWORD ("void", LEXER_KEYW_VOID),
LEXER_KEYWORD ("with", LEXER_KEYW_WITH),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 5 characters.
*/
static const keyword_string_t keyword_length_5[10] =
{
LEXER_KEYWORD ("break", LEXER_KEYW_BREAK),
LEXER_KEYWORD ("catch", LEXER_KEYW_CATCH),
LEXER_KEYWORD ("class", LEXER_KEYW_CLASS),
LEXER_KEYWORD ("const", LEXER_KEYW_CONST),
LEXER_KEYWORD ("false", LEXER_LIT_FALSE),
LEXER_KEYWORD ("super", LEXER_KEYW_SUPER),
LEXER_KEYWORD ("throw", LEXER_KEYW_THROW),
LEXER_KEYWORD ("while", LEXER_KEYW_WHILE),
LEXER_KEYWORD ("yield", LEXER_KEYW_YIELD),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 6 characters.
*/
static const keyword_string_t keyword_length_6[9] =
{
LEXER_KEYWORD ("delete", LEXER_KEYW_DELETE),
LEXER_KEYWORD ("export", LEXER_KEYW_EXPORT),
LEXER_KEYWORD ("import", LEXER_KEYW_IMPORT),
LEXER_KEYWORD ("public", LEXER_KEYW_PUBLIC),
LEXER_KEYWORD ("return", LEXER_KEYW_RETURN),
LEXER_KEYWORD ("static", LEXER_KEYW_STATIC),
LEXER_KEYWORD ("switch", LEXER_KEYW_SWITCH),
LEXER_KEYWORD ("typeof", LEXER_KEYW_TYPEOF),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 7 characters.
*/
static const keyword_string_t keyword_length_7[6] =
{
LEXER_KEYWORD ("default", LEXER_KEYW_DEFAULT),
LEXER_KEYWORD ("extends", LEXER_KEYW_EXTENDS),
LEXER_KEYWORD ("finally", LEXER_KEYW_FINALLY),
LEXER_KEYWORD ("package", LEXER_KEYW_PACKAGE),
LEXER_KEYWORD ("private", LEXER_KEYW_PRIVATE),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 8 characters.
*/
static const keyword_string_t keyword_length_8[4] =
{
LEXER_KEYWORD ("continue", LEXER_KEYW_CONTINUE),
LEXER_KEYWORD ("debugger", LEXER_KEYW_DEBUGGER),
LEXER_KEYWORD ("function", LEXER_KEYW_FUNCTION),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 9 characters.
*/
static const keyword_string_t keyword_length_9[3] =
{
LEXER_KEYWORD ("interface", LEXER_KEYW_INTERFACE),
LEXER_KEYWORD ("protected", LEXER_KEYW_PROTECTED),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 10 characters.
*/
static const keyword_string_t keyword_length_10[3] =
{
LEXER_KEYWORD ("implements", LEXER_KEYW_IMPLEMENTS),
LEXER_KEYWORD ("instanceof", LEXER_KEYW_INSTANCEOF),
LEXER_KEYWORD_END ()
};
/**
* List to the keywords.
*/
static const keyword_string_t * const keyword_string_list[9] =
{
keyword_length_2,
keyword_length_3,
keyword_length_4,
keyword_length_5,
keyword_length_6,
keyword_length_7,
keyword_length_8,
keyword_length_9,
keyword_length_10
};
#undef LEXER_KEYWORD
#undef LEXER_KEYWORD_END
/**
* Parse identifier.
*/
static void
lexer_parse_identifier (parser_context_t *context_p, /**< context */
bool check_keywords) /**< check keywords */
{
/* Only very few identifiers contains \u escape sequences. */
const uint8_t *source_p = context_p->source_p;
const uint8_t *ident_start_p = context_p->source_p;
/* Note: newline or tab cannot be part of an identifier. */
parser_line_counter_t column = context_p->column;
const uint8_t *source_end_p = context_p->source_end_p;
size_t length = 0;
context_p->token.type = LEXER_LITERAL;
context_p->token.literal_is_reserved = false;
context_p->token.lit_location.type = LEXER_IDENT_LITERAL;
context_p->token.lit_location.has_escape = false;
do
{
if (*source_p == LIT_CHAR_BACKSLASH)
{
uint16_t character;
context_p->token.lit_location.has_escape = true;
context_p->source_p = source_p;
context_p->token.column = column;
if ((source_p + 6 > source_end_p) || (source_p[1] != LIT_CHAR_LOWERCASE_U))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNICODE_ESCAPE_SEQUENCE);
}
character = lexer_hex_to_character (context_p, source_p + 2, 4);
if (length == 0)
{
if (!lit_char_is_identifier_start_character (character))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_IDENTIFIER_START);
}
}
else
{
if (!lit_char_is_identifier_part_character (character))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_IDENTIFIER_PART);
}
}
length += lit_char_get_utf8_length (character);
source_p += 6;
PARSER_PLUS_EQUAL_LC (column, 6);
continue;
}
/* Valid identifiers cannot contain 4 byte long utf-8
* characters, since those characters are represented
* by 2 ecmascript (UTF-16) characters, and those
* characters cannot be literal characters. */
JERRY_ASSERT (source_p[0] < LEXER_UTF8_4BYTE_START);
source_p++;
length++;
column++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (source_p[0]))
{
source_p++;
length++;
}
}
while (source_p < source_end_p
&& (lit_char_is_identifier_part (source_p) || *source_p == LIT_CHAR_BACKSLASH));
context_p->source_p = ident_start_p;
context_p->token.column = context_p->column;
if (length > PARSER_MAXIMUM_IDENT_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_TOO_LONG);
}
/* Check keywords (Only if there is no \u escape sequence in the pattern). */
if (check_keywords
&& !context_p->token.lit_location.has_escape
&& (length >= 2 && length <= 10))
{
const keyword_string_t *keyword_p = keyword_string_list[length - 2];
do
{
if (ident_start_p[0] == keyword_p->keyword_p[0]
&& ident_start_p[1] == keyword_p->keyword_p[1]
&& memcmp (ident_start_p, keyword_p->keyword_p, length) == 0)
{
if (keyword_p->type >= LEXER_FIRST_FUTURE_STRICT_RESERVED_WORD)
{
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_STRICT_IDENT_NOT_ALLOWED);
}
context_p->token.literal_is_reserved = true;
break;
}
context_p->token.type = keyword_p->type;
break;
}
keyword_p++;
}
while (keyword_p->type != LEXER_EOS);
}
if (context_p->token.type == LEXER_LITERAL)
{
/* Fill literal data. */
context_p->token.lit_location.char_p = ident_start_p;
context_p->token.lit_location.length = (uint16_t) length;
}
context_p->source_p = source_p;
context_p->column = column;
} /* lexer_parse_identifier */
/**
* Parse string.
*/
static void
lexer_parse_string (parser_context_t *context_p) /**< context */
{
uint8_t str_end_character = context_p->source_p[0];
const uint8_t *source_p = context_p->source_p + 1;
const uint8_t *string_start_p = source_p;
const uint8_t *source_end_p = context_p->source_end_p;
parser_line_counter_t line = context_p->line;
parser_line_counter_t column = (parser_line_counter_t) (context_p->column + 1);
parser_line_counter_t original_line = line;
parser_line_counter_t original_column = column;
size_t length = 0;
uint8_t has_escape = false;
while (true)
{
if (source_p >= source_end_p)
{
context_p->token.line = original_line;
context_p->token.column = (parser_line_counter_t) (original_column - 1);
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_STRING);
}
if (*source_p == str_end_character)
{
break;
}
if (*source_p == LIT_CHAR_BACKSLASH)
{
source_p++;
column++;
if (source_p >= source_end_p)
{
/* Will throw an unterminated string error. */
continue;
}
has_escape = true;
/* Newline is ignored. */
if (*source_p == LIT_CHAR_CR
|| *source_p == LIT_CHAR_LF
|| (*source_p == LEXER_NEWLINE_LS_PS_BYTE_1 && LEXER_NEWLINE_LS_PS_BYTE_23 (source_p)))
{
if (*source_p == LIT_CHAR_CR)
{
source_p++;
if (source_p < source_end_p
&& *source_p == LIT_CHAR_LF)
{
source_p++;
}
}
else if (*source_p == LIT_CHAR_LF)
{
source_p++;
}
else
{
source_p += 3;
}
line++;
column = 1;
continue;
}
/* Except \x, \u, and octal numbers, everything is
* converted to a character which has the same byte length. */
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_3)
{
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_ESCAPE_NOT_ALLOWED);
}
source_p++;
column++;
if (source_p < source_end_p && *source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
source_p++;
column++;
if (source_p < source_end_p && *source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
/* Numbers >= 0x200 (0x80) requires
* two bytes for encoding in UTF-8. */
if (source_p[-2] >= LIT_CHAR_2)
{
length++;
}
source_p++;
column++;
}
}
length++;
continue;
}
if (*source_p >= LIT_CHAR_4 && *source_p <= LIT_CHAR_7)
{
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_ESCAPE_NOT_ALLOWED);
}
source_p++;
column++;
if (source_p < source_end_p && *source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
source_p++;
column++;
}
/* The maximum number is 0x4d so the UTF-8
* representation is always one byte. */
length++;
continue;
}
if (*source_p == LIT_CHAR_LOWERCASE_X || *source_p == LIT_CHAR_LOWERCASE_U)
{
uint8_t hex_part_length = (*source_p == LIT_CHAR_LOWERCASE_X) ? 2 : 4;
context_p->token.line = line;
context_p->token.column = (parser_line_counter_t) (column - 1);
if (source_p + 1 + hex_part_length > source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_ESCAPE_SEQUENCE);
}
length += lit_char_get_utf8_length (lexer_hex_to_character (context_p,
source_p + 1,
hex_part_length));
source_p += hex_part_length + 1;
PARSER_PLUS_EQUAL_LC (column, hex_part_length + 1u);
continue;
}
}
if (*source_p >= LEXER_UTF8_4BYTE_START)
{
/* Processing 4 byte unicode sequence (even if it is
* after a backslash). Always converted to two 3 byte
* long sequence. */
length += 2 * 3;
has_escape = true;
source_p += 4;
column++;
continue;
}
else if (*source_p == LIT_CHAR_CR
|| *source_p == LIT_CHAR_LF
|| (*source_p == LEXER_NEWLINE_LS_PS_BYTE_1 && LEXER_NEWLINE_LS_PS_BYTE_23 (source_p)))
{
context_p->token.line = line;
context_p->token.column = column;
parser_raise_error (context_p, PARSER_ERR_NEWLINE_NOT_ALLOWED);
}
else if (*source_p == LIT_CHAR_TAB)
{
column = align_column_to_tab (column);
/* Subtract -1 because column is increased below. */
column--;
}
source_p++;
column++;
length++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (*source_p))
{
source_p++;
length++;
}
}
if (length > PARSER_MAXIMUM_STRING_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_STRING_TOO_LONG);
}
context_p->token.type = LEXER_LITERAL;
/* Fill literal data. */
context_p->token.lit_location.char_p = string_start_p;
context_p->token.lit_location.length = (uint16_t) length;
context_p->token.lit_location.type = LEXER_STRING_LITERAL;
context_p->token.lit_location.has_escape = has_escape;
context_p->source_p = source_p + 1;
context_p->line = line;
context_p->column = (parser_line_counter_t) (column + 1);
} /* lexer_parse_string */
/**
* Parse number.
*/
static void
lexer_parse_number (parser_context_t *context_p) /**< context */
{
const uint8_t *source_p = context_p->source_p;
const uint8_t *source_end_p = context_p->source_end_p;
bool can_be_float = false;
size_t length;
context_p->token.type = LEXER_LITERAL;
context_p->token.literal_is_reserved = false;
context_p->token.extra_value = LEXER_NUMBER_DECIMAL;
context_p->token.lit_location.char_p = source_p;
context_p->token.lit_location.type = LEXER_NUMBER_LITERAL;
context_p->token.lit_location.has_escape = false;
if (source_p[0] == LIT_CHAR_0
&& source_p + 1 < source_end_p)
{
if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X)
{
context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_hex_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT);
}
do
{
source_p++;
}
while (source_p < source_end_p
&& lit_char_is_hex_digit (source_p[0]));
}
else if (source_p[1] >= LIT_CHAR_0
&& source_p[1] <= LIT_CHAR_7)
{
context_p->token.extra_value = LEXER_NUMBER_OCTAL;
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED);
}
do
{
source_p++;
}
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_7);
if (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_8
&& source_p[0] <= LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);
}
}
else if (source_p[1] >= LIT_CHAR_8
&& source_p[1] <= LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);
}
else
{
can_be_float = true;
source_p++;
}
}
else
{
do
{
source_p++;
}
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_9);
can_be_float = true;
}
if (can_be_float)
{
if (source_p < source_end_p
&& source_p[0] == LIT_CHAR_DOT)
{
source_p++;
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_9)
{
source_p++;
}
}
if (source_p < source_end_p
&& LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E)
{
source_p++;
if (source_p < source_end_p
&& (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS))
{
source_p++;
}
if (source_p >= source_end_p
|| source_p[0] < LIT_CHAR_0
|| source_p[0] > LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT);
}
do
{
source_p++;
}
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_9);
}
}
if (source_p < source_end_p
&& (lit_char_is_identifier_start (source_p) || source_p[0] == LIT_CHAR_BACKSLASH))
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER);
}
length = (size_t) (source_p - context_p->source_p);
if (length > PARSER_MAXIMUM_IDENT_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG);
}
context_p->token.lit_location.length = (uint16_t) length;
PARSER_PLUS_EQUAL_LC (context_p->column, length);
context_p->source_p = source_p;
} /* lexer_parse_number */
#define LEXER_TYPE_A_TOKEN(char1, type1) \
case (uint8_t) (char1) : \
{ \
context_p->token.type = (type1); \
length = 1; \
break; \
}
#define LEXER_TYPE_B_TOKEN(char1, type1, char2, type2) \
case (uint8_t) (char1) : \
{ \
if (length >= 2 && context_p->source_p[1] == (uint8_t) (char2)) \
{ \
context_p->token.type = (type2); \
length = 2; \
break; \
} \
\
context_p->token.type = (type1); \
length = 1; \
break; \
}
#define LEXER_TYPE_C_TOKEN(char1, type1, char2, type2, char3, type3) \
case (uint8_t) (char1) : \
{ \
if (length >= 2) \
{ \
if (context_p->source_p[1] == (uint8_t) (char2)) \
{ \
context_p->token.type = (type2); \
length = 2; \
break; \
} \
\
if (context_p->source_p[1] == (uint8_t) (char3)) \
{ \
context_p->token.type = (type3); \
length = 2; \
break; \
} \
} \
\
context_p->token.type = (type1); \
length = 1; \
break; \
}
#define LEXER_TYPE_D_TOKEN(char1, type1, char2, type2, char3, type3) \
case (uint8_t) (char1) : \
{ \
if (length >= 2 && context_p->source_p[1] == (uint8_t) (char2)) \
{ \
if (length >= 3 && context_p->source_p[2] == (uint8_t) (char3)) \
{ \
context_p->token.type = (type3); \
length = 3; \
break; \
} \
\
context_p->token.type = (type2); \
length = 2; \
break; \
} \
\
context_p->token.type = (type1); \
length = 1; \
break; \
}
/**
* Get next token.
*/
void
lexer_next_token (parser_context_t *context_p) /**< context */
{
size_t length;
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
length = (size_t) (context_p->source_end_p - context_p->source_p);
if (length == 0)
{
context_p->token.type = LEXER_EOS;
return;
}
if (lit_char_is_identifier_start (context_p->source_p)
|| context_p->source_p[0] == LIT_CHAR_BACKSLASH)
{
lexer_parse_identifier (context_p, true);
return;
}
if (context_p->source_p[0] >= LIT_CHAR_0 && context_p->source_p[0] <= LIT_CHAR_9)
{
lexer_parse_number (context_p);
return;
}
switch (context_p->source_p[0])
{
LEXER_TYPE_A_TOKEN (LIT_CHAR_LEFT_BRACE, LEXER_LEFT_BRACE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_LEFT_PAREN, LEXER_LEFT_PAREN);
LEXER_TYPE_A_TOKEN (LIT_CHAR_LEFT_SQUARE, LEXER_LEFT_SQUARE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_RIGHT_BRACE, LEXER_RIGHT_BRACE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_RIGHT_PAREN, LEXER_RIGHT_PAREN);
LEXER_TYPE_A_TOKEN (LIT_CHAR_RIGHT_SQUARE, LEXER_RIGHT_SQUARE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_SEMICOLON, LEXER_SEMICOLON);
LEXER_TYPE_A_TOKEN (LIT_CHAR_COMMA, LEXER_COMMA);
case (uint8_t) LIT_CHAR_DOT :
{
if (length >= 2
&& (context_p->source_p[1] >= LIT_CHAR_0 && context_p->source_p[1] <= LIT_CHAR_9))
{
lexer_parse_number (context_p);
return;
}
context_p->token.type = LEXER_DOT;
length = 1;
break;
}
case (uint8_t) LIT_CHAR_LESS_THAN:
{
if (length >= 2)
{
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_LESS_EQUAL;
length = 2;
break;
}
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_LESS_THAN)
{
if (length >= 3 && context_p->source_p[2] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_ASSIGN_LEFT_SHIFT;
length = 3;
break;
}
context_p->token.type = LEXER_LEFT_SHIFT;
length = 2;
break;
}
}
context_p->token.type = LEXER_LESS;
length = 1;
break;
}
case LIT_CHAR_GREATER_THAN:
{
if (length >= 2)
{
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_GREATER_EQUAL;
length = 2;
break;
}
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_GREATER_THAN)
{
if (length >= 3)
{
if (context_p->source_p[2] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_ASSIGN_RIGHT_SHIFT;
length = 3;
break;
}
if (context_p->source_p[2] == (uint8_t) LIT_CHAR_GREATER_THAN)
{
if (length >= 4 && context_p->source_p[3] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_ASSIGN_UNS_RIGHT_SHIFT;
length = 4;
break;
}
context_p->token.type = LEXER_UNS_RIGHT_SHIFT;
length = 3;
break;
}
}
context_p->token.type = LEXER_RIGHT_SHIFT;
length = 2;
break;
}
}
context_p->token.type = LEXER_GREATER;
length = 1;
break;
}
LEXER_TYPE_D_TOKEN (LIT_CHAR_EQUALS, LEXER_ASSIGN, LIT_CHAR_EQUALS,
LEXER_EQUAL, LIT_CHAR_EQUALS, LEXER_STRICT_EQUAL)
LEXER_TYPE_D_TOKEN (LIT_CHAR_EXCLAMATION, LEXER_LOGICAL_NOT, LIT_CHAR_EQUALS,
LEXER_NOT_EQUAL, LIT_CHAR_EQUALS, LEXER_STRICT_NOT_EQUAL)
LEXER_TYPE_C_TOKEN (LIT_CHAR_PLUS, LEXER_ADD, LIT_CHAR_EQUALS,
LEXER_ASSIGN_ADD, LIT_CHAR_PLUS, LEXER_INCREASE)
LEXER_TYPE_C_TOKEN (LIT_CHAR_MINUS, LEXER_SUBTRACT, LIT_CHAR_EQUALS,
LEXER_ASSIGN_SUBTRACT, LIT_CHAR_MINUS, LEXER_DECREASE)
LEXER_TYPE_B_TOKEN (LIT_CHAR_ASTERISK, LEXER_MULTIPLY, LIT_CHAR_EQUALS,
LEXER_ASSIGN_MULTIPLY)
LEXER_TYPE_B_TOKEN (LIT_CHAR_SLASH, LEXER_DIVIDE, LIT_CHAR_EQUALS,
LEXER_ASSIGN_DIVIDE)
LEXER_TYPE_B_TOKEN (LIT_CHAR_PERCENT, LEXER_MODULO, LIT_CHAR_EQUALS,
LEXER_ASSIGN_MODULO)
LEXER_TYPE_C_TOKEN (LIT_CHAR_AMPERSAND, LEXER_BIT_AND, LIT_CHAR_EQUALS,
LEXER_ASSIGN_BIT_AND, LIT_CHAR_AMPERSAND, LEXER_LOGICAL_AND)
LEXER_TYPE_C_TOKEN (LIT_CHAR_VLINE, LEXER_BIT_OR, LIT_CHAR_EQUALS,
LEXER_ASSIGN_BIT_OR, LIT_CHAR_VLINE, LEXER_LOGICAL_OR)
LEXER_TYPE_B_TOKEN (LIT_CHAR_CIRCUMFLEX, LEXER_BIT_XOR, LIT_CHAR_EQUALS,
LEXER_ASSIGN_BIT_XOR)
LEXER_TYPE_A_TOKEN (LIT_CHAR_TILDE, LEXER_BIT_NOT);
LEXER_TYPE_A_TOKEN (LIT_CHAR_QUESTION, LEXER_QUESTION_MARK);
LEXER_TYPE_A_TOKEN (LIT_CHAR_COLON, LEXER_COLON);
case LIT_CHAR_SINGLE_QUOTE:
case LIT_CHAR_DOUBLE_QUOTE:
{
lexer_parse_string (context_p);
return;
}
default:
{
parser_raise_error (context_p, PARSER_ERR_INVALID_CHARACTER);
}
}
context_p->source_p += length;
PARSER_PLUS_EQUAL_LC (context_p->column, length);
} /* lexer_next_token */
#undef LEXER_TYPE_A_TOKEN
#undef LEXER_TYPE_B_TOKEN
#undef LEXER_TYPE_C_TOKEN
#undef LEXER_TYPE_D_TOKEN
/**
* Search or append the string to the literal pool.
*/
static void
lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
if (length == 0)
{
has_escape = false;
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */
/* Maximum buffer size for identifiers which contains escape sequences. */
#define LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE 48
/**
* Construct a literal object from an identifier.
*/
void
lexer_construct_literal_object (parser_context_t *context_p, /**< context */
lexer_lit_location_t *literal_p, /**< literal location */
uint8_t literal_type) /**< final literal type */
{
uint8_t *destination_start_p;
const uint8_t *source_p;
uint8_t local_byte_array[LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE];
JERRY_ASSERT (literal_p->type == LEXER_IDENT_LITERAL
|| literal_p->type == LEXER_STRING_LITERAL);
JERRY_ASSERT (context_p->allocated_buffer_p == NULL);
destination_start_p = local_byte_array;
source_p = literal_p->char_p;
if (literal_p->has_escape)
{
uint8_t *destination_p;
if (literal_p->length > LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE)
{
destination_start_p = (uint8_t *) parser_malloc_local (context_p, literal_p->length);
context_p->allocated_buffer_p = destination_start_p;
context_p->allocated_buffer_size = literal_p->length;
}
destination_p = destination_start_p;
if (literal_p->type == LEXER_IDENT_LITERAL)
{
const uint8_t *source_end_p = context_p->source_end_p;
JERRY_ASSERT (literal_p->length <= PARSER_MAXIMUM_IDENT_LENGTH);
do
{
if (*source_p == LIT_CHAR_BACKSLASH)
{
destination_p += lit_char_to_utf8_bytes (destination_p,
lexer_hex_to_character (context_p, source_p + 2, 4));
source_p += 6;
continue;
}
*destination_p++ = *source_p++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (*source_p))
{
*destination_p++ = *source_p++;
}
}
while (source_p < source_end_p
&& (lit_char_is_identifier_part (source_p) || *source_p == LIT_CHAR_BACKSLASH));
JERRY_ASSERT (destination_p == destination_start_p + literal_p->length);
}
else
{
uint8_t str_end_character = source_p[-1];
while (true)
{
if (*source_p == str_end_character)
{
break;
}
if (*source_p == LIT_CHAR_BACKSLASH)
{
uint8_t conv_character;
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
/* Newline is ignored. */
if (*source_p == LIT_CHAR_CR
|| *source_p == LIT_CHAR_LF
|| (*source_p == LEXER_NEWLINE_LS_PS_BYTE_1 && LEXER_NEWLINE_LS_PS_BYTE_23 (source_p)))
{
if (*source_p == LIT_CHAR_CR)
{
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p == LIT_CHAR_LF)
{
source_p++;
}
}
else if (*source_p == LIT_CHAR_LF)
{
source_p++;
}
else
{
source_p += 3;
}
continue;
}
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_3)
{
uint32_t octal_number = (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
octal_number = octal_number * 8 + (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
octal_number = octal_number * 8 + (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
}
}
destination_p += lit_char_to_utf8_bytes (destination_p, (uint16_t) octal_number);
continue;
}
if (*source_p >= LIT_CHAR_4 && *source_p <= LIT_CHAR_7)
{
uint32_t octal_number = (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
octal_number = octal_number * 8 + (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
}
*destination_p++ = (uint8_t) octal_number;
continue;
}
if (*source_p == LIT_CHAR_LOWERCASE_X || *source_p == LIT_CHAR_LOWERCASE_U)
{
int hex_part_length = (*source_p == LIT_CHAR_LOWERCASE_X) ? 2 : 4;
JERRY_ASSERT (source_p + 1 + hex_part_length <= context_p->source_end_p);
destination_p += lit_char_to_utf8_bytes (destination_p,
lexer_hex_to_character (context_p,
source_p + 1,
hex_part_length));
source_p += hex_part_length + 1;
continue;
}
conv_character = *source_p;
switch (*source_p)
{
case LIT_CHAR_LOWERCASE_B:
{
conv_character = 0x08;
break;
}
case LIT_CHAR_LOWERCASE_T:
{
conv_character = 0x09;
break;
}
case LIT_CHAR_LOWERCASE_N:
{
conv_character = 0x0a;
break;
}
case LIT_CHAR_LOWERCASE_V:
{
conv_character = 0x0b;
break;
}
case LIT_CHAR_LOWERCASE_F:
{
conv_character = 0x0c;
break;
}
case LIT_CHAR_LOWERCASE_R:
{
conv_character = 0x0d;
break;
}
}
if (conv_character != *source_p)
{
*destination_p++ = conv_character;
source_p++;
continue;
}
}
if (*source_p >= LEXER_UTF8_4BYTE_START)
{
/* Processing 4 byte unicode sequence (even if it is
* after a backslash). Always converted to two 3 byte
* long sequence. */
uint32_t character = ((((uint32_t) source_p[0]) & 0x7) << 18);
character |= ((((uint32_t) source_p[1]) & LIT_UTF8_LAST_6_BITS_MASK) << 12);
character |= ((((uint32_t) source_p[2]) & LIT_UTF8_LAST_6_BITS_MASK) << 6);
character |= (((uint32_t) source_p[3]) & LIT_UTF8_LAST_6_BITS_MASK);
JERRY_ASSERT (character >= 0x10000);
character -= 0x10000;
destination_p += lit_char_to_utf8_bytes (destination_p,
(ecma_char_t) (0xd800 | (character >> 10)));
destination_p += lit_char_to_utf8_bytes (destination_p,
(ecma_char_t) (0xdc00 | (character & LIT_UTF16_LAST_10_BITS_MASK)));
source_p += 4;
continue;
}
*destination_p++ = *source_p++;
/* There is no need to check the source_end_p
* since the string is terminated by a quotation mark. */
while (IS_UTF8_INTERMEDIATE_OCTET (*source_p))
{
*destination_p++ = *source_p++;
}
}
JERRY_ASSERT (destination_p == destination_start_p + literal_p->length);
}
source_p = destination_start_p;
}
lexer_process_char_literal (context_p,
source_p,
literal_p->length,
literal_type,
literal_p->has_escape);
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
if (literal_type == LEXER_IDENT_LITERAL)
{
if ((context_p->status_flags & PARSER_INSIDE_WITH)
&& context_p->lit_object.literal_p->type == LEXER_IDENT_LITERAL)
{
context_p->lit_object.literal_p->status_flags |= LEXER_FLAG_NO_REG_STORE;
}
if (literal_p->length == 4
&& source_p[0] == LIT_CHAR_LOWERCASE_E
&& source_p[3] == LIT_CHAR_LOWERCASE_L
&& source_p[1] == LIT_CHAR_LOWERCASE_V
&& source_p[2] == LIT_CHAR_LOWERCASE_A)
{
context_p->lit_object.type = LEXER_LITERAL_OBJECT_EVAL;
}
if (literal_p->length == 9
&& source_p[0] == LIT_CHAR_LOWERCASE_A
&& source_p[8] == LIT_CHAR_LOWERCASE_S
&& memcmp (source_p + 1, "rgument", 7) == 0)
{
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ARGUMENTS;
if (!(context_p->status_flags & PARSER_ARGUMENTS_NOT_NEEDED))
{
context_p->status_flags |= PARSER_ARGUMENTS_NEEDED | PARSER_LEXICAL_ENV_NEEDED;
context_p->lit_object.literal_p->status_flags |= LEXER_FLAG_NO_REG_STORE;
}
}
}
if (destination_start_p != local_byte_array)
{
JERRY_ASSERT (context_p->allocated_buffer_p == destination_start_p);
context_p->allocated_buffer_p = NULL;
parser_free_local (destination_start_p,
context_p->allocated_buffer_size);
}
JERRY_ASSERT (context_p->allocated_buffer_p == NULL);
} /* lexer_construct_literal_object */
#undef LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE
/**
* Construct a number object.
*
* @return true if number is small number
*/
bool
lexer_construct_number_object (parser_context_t *context_p, /**< context */
bool push_number_allowed, /**< push number support is allowed */
bool is_negative_number) /**< sign is negative */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
ecma_number_t num;
uint32_t literal_index = 0;
uint16_t length = context_p->token.lit_location.length;
if (context_p->token.extra_value != LEXER_NUMBER_OCTAL)
{
num = ecma_utf8_string_to_number (context_p->token.lit_location.char_p,
length);
}
else
{
const uint8_t *src_p = context_p->token.lit_location.char_p;
const uint8_t *src_end_p = src_p + length - 1;
num = 0;
do
{
src_p++;
num = num * 8 + (ecma_number_t) (*src_p - LIT_CHAR_0);
}
while (src_p < src_end_p);
}
if (push_number_allowed)
{
int32_t int_num = (int32_t) num;
if (int_num == num)
{
if (int_num <= CBC_PUSH_NUMBER_BYTE_RANGE_END
&& (int_num != 0 || !is_negative_number))
{
context_p->lit_object.index = (uint16_t) int_num;
return true;
}
}
}
if (is_negative_number)
{
num = -num;
}
jmem_cpointer_t lit_cp = ecma_find_or_create_literal_number (num);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == LEXER_NUMBER_LITERAL
&& literal_p->u.value == lit_cp)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
return false;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = context_p->token.lit_location.length;
literal_p->type = LEXER_UNUSED_LITERAL;
literal_p->status_flags = 0;
context_p->literal_count++;
literal_p->u.value = lit_cp;
literal_p->type = LEXER_NUMBER_LITERAL;
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
return false;
} /* lexer_construct_number_object */
/**
* Construct a function literal object.
*
* @return function object literal index
*/
uint16_t
lexer_construct_function_object (parser_context_t *context_p, /**< context */
uint32_t extra_status_flags) /**< extra status flags */
{
ecma_compiled_code_t *compiled_code_p;
lexer_literal_t *literal_p;
uint16_t result_index;
if (context_p->literal_count >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
if (context_p->status_flags & PARSER_RESOLVE_THIS_FOR_CALLS)
{
extra_status_flags |= PARSER_RESOLVE_THIS_FOR_CALLS;
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->type = LEXER_UNUSED_LITERAL;
literal_p->status_flags = 0;
result_index = context_p->literal_count;
context_p->literal_count++;
compiled_code_p = parser_parse_function (context_p, extra_status_flags);
literal_p->u.bytecode_p = compiled_code_p;
literal_p->type = LEXER_FUNCTION_LITERAL;
return result_index;
} /* lexer_construct_function_object */
/**
* Construct a regular expression object.
*/
void
lexer_construct_regexp_object (parser_context_t *context_p, /**< context */
bool parse_only) /**< parse only */
{
#ifndef CONFIG_DISABLE_REGEXP_BUILTIN
const uint8_t *source_p = context_p->source_p;
const uint8_t *regex_start_p = context_p->source_p;
const uint8_t *regex_end_p = regex_start_p;
const uint8_t *source_end_p = context_p->source_end_p;
parser_line_counter_t column = context_p->column;
lexer_literal_t *literal_p;
bool in_class = false;
uint16_t current_flags;
lit_utf8_size_t length;
JERRY_ASSERT (context_p->token.type == LEXER_DIVIDE
|| context_p->token.type == LEXER_ASSIGN_DIVIDE);
if (context_p->token.type == LEXER_ASSIGN_DIVIDE)
{
regex_start_p--;
}
while (true)
{
if (source_p >= source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_REGEXP);
}
if (!in_class && source_p[0] == LIT_CHAR_SLASH)
{
regex_end_p = source_p;
source_p++;
column++;
break;
}
switch (source_p[0])
{
case LIT_CHAR_CR:
case LIT_CHAR_LF:
case LEXER_NEWLINE_LS_PS_BYTE_1:
{
if (source_p[0] != LEXER_NEWLINE_LS_PS_BYTE_1
|| LEXER_NEWLINE_LS_PS_BYTE_23 (source_p))
{
parser_raise_error (context_p, PARSER_ERR_NEWLINE_NOT_ALLOWED);
}
break;
}
case LIT_CHAR_TAB:
{
column = align_column_to_tab (column);
/* Subtract -1 because column is increased below. */
column--;
break;
}
case LIT_CHAR_LEFT_SQUARE:
{
in_class = true;
break;
}
case LIT_CHAR_RIGHT_SQUARE:
{
in_class = false;
break;
}
case LIT_CHAR_BACKSLASH:
{
if (source_p + 1 >= source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_REGEXP);
}
if (source_p[1] >= 0x20 && source_p[1] <= LIT_UTF8_1_BYTE_CODE_POINT_MAX)
{
source_p++;
column++;
}
}
}
source_p++;
column++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (source_p[0]))
{
source_p++;
}
}
current_flags = 0;
while (source_p < source_end_p)
{
uint32_t flag = 0;
if (source_p[0] == LIT_CHAR_LOWERCASE_G)
{
flag = RE_FLAG_GLOBAL;
}
else if (source_p[0] == LIT_CHAR_LOWERCASE_I)
{
flag = RE_FLAG_IGNORE_CASE;
}
else if (source_p[0] == LIT_CHAR_LOWERCASE_M)
{
flag = RE_FLAG_MULTILINE;
}
if (flag == 0)
{
break;
}
if (current_flags & flag)
{
parser_raise_error (context_p, PARSER_ERR_DUPLICATED_REGEXP_FLAG);
}
current_flags = (uint16_t) (current_flags | flag);
source_p++;
column++;
}
if (source_p < source_end_p
&& lit_char_is_identifier_part (source_p))
{
parser_raise_error (context_p, PARSER_ERR_UNKNOWN_REGEXP_FLAG);
}
context_p->source_p = source_p;
context_p->column = column;
length = (lit_utf8_size_t) (regex_end_p - regex_start_p);
if (length > PARSER_MAXIMUM_STRING_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_REGEXP_TOO_LONG);
}
context_p->column = column;
context_p->source_p = source_p;
if (parse_only)
{
return;
}
if (context_p->literal_count >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = LEXER_UNUSED_LITERAL;
literal_p->status_flags = 0;
context_p->literal_count++;
/* Compile the RegExp literal and store the RegExp bytecode pointer */
const re_compiled_code_t *re_bytecode_p = NULL;
ecma_value_t completion_value;
ecma_string_t *pattern_str_p = ecma_new_ecma_string_from_utf8 (regex_start_p, length);
completion_value = re_compile_bytecode (&re_bytecode_p,
pattern_str_p,
current_flags);
ecma_deref_ecma_string (pattern_str_p);
bool is_throw = ECMA_IS_VALUE_ERROR (completion_value);
ecma_free_value (completion_value);
if (is_throw)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_REGEXP);
}
literal_p->type = LEXER_REGEXP_LITERAL;
literal_p->u.bytecode_p = (ecma_compiled_code_t *) re_bytecode_p;
context_p->token.type = LEXER_LITERAL;
context_p->token.literal_is_reserved = false;
context_p->token.lit_location.type = LEXER_REGEXP_LITERAL;
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) (context_p->literal_count - 1);
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
#else /* CONFIG_DISABLE_REGEXP_BUILTIN */
JERRY_UNUSED (parse_only);
parser_raise_error (context_p, PARSER_ERR_UNSUPPORTED_REGEXP);
#endif /* !CONFIG_DISABLE_REGEXP_BUILTIN */
} /* lexer_construct_regexp_object */
/**
* Next token must be an identifier.
*/
void
lexer_expect_identifier (parser_context_t *context_p, /**< context */
uint8_t literal_type) /**< literal type */
{
JERRY_ASSERT (literal_type == LEXER_STRING_LITERAL
|| literal_type == LEXER_IDENT_LITERAL);
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
if (context_p->source_p < context_p->source_end_p
&& (lit_char_is_identifier_start (context_p->source_p) || context_p->source_p[0] == LIT_CHAR_BACKSLASH))
{
lexer_parse_identifier (context_p, literal_type != LEXER_STRING_LITERAL);
if (context_p->token.type == LEXER_LITERAL)
{
lexer_construct_literal_object (context_p,
&context_p->token.lit_location,
literal_type);
if (literal_type == LEXER_IDENT_LITERAL
&& (context_p->status_flags & PARSER_IS_STRICT)
&& context_p->lit_object.type != LEXER_LITERAL_OBJECT_ANY)
{
parser_error_t error;
if (context_p->lit_object.type == LEXER_LITERAL_OBJECT_EVAL)
{
error = PARSER_ERR_EVAL_NOT_ALLOWED;
}
else
{
JERRY_ASSERT (context_p->lit_object.type == LEXER_LITERAL_OBJECT_ARGUMENTS);
error = PARSER_ERR_ARGUMENTS_NOT_ALLOWED;
}
parser_raise_error (context_p, error);
}
context_p->token.lit_location.type = literal_type;
return;
}
}
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED);
} /* lexer_expect_identifier */
static const lexer_lit_location_t lexer_get_literal =
{
(const uint8_t *) "get", 3, LEXER_IDENT_LITERAL, false
};
static const lexer_lit_location_t lexer_set_literal =
{
(const uint8_t *) "set", 3, LEXER_IDENT_LITERAL, false
};
/**
* Next token must be an identifier.
*/
void
lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */
bool must_be_identifier) /**< only identifiers are accepted */
{
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
if (context_p->source_p < context_p->source_end_p)
{
bool create_literal_object = false;
if (lit_char_is_identifier_start (context_p->source_p) || context_p->source_p[0] == LIT_CHAR_BACKSLASH)
{
lexer_parse_identifier (context_p, false);
if (!must_be_identifier
&& context_p->token.lit_location.length == 3)
{
skip_spaces (context_p);
if (context_p->source_p < context_p->source_end_p
&& context_p->source_p[0] != LIT_CHAR_COLON)
{
if (lexer_compare_identifier_to_current (context_p, &lexer_get_literal))
{
context_p->token.type = LEXER_PROPERTY_GETTER;
return;
}
else if (lexer_compare_identifier_to_current (context_p, &lexer_set_literal))
{
context_p->token.type = LEXER_PROPERTY_SETTER;
return;
}
}
}
create_literal_object = true;
}
else if (context_p->source_p[0] == LIT_CHAR_DOUBLE_QUOTE
|| context_p->source_p[0] == LIT_CHAR_SINGLE_QUOTE)
{
lexer_parse_string (context_p);
create_literal_object = true;
}
else if (!must_be_identifier && context_p->source_p[0] == LIT_CHAR_RIGHT_BRACE)
{
context_p->token.type = LEXER_RIGHT_BRACE;
context_p->source_p += 1;
context_p->column++;
return;
}
else
{
const uint8_t *char_p = context_p->source_p;
if (char_p[0] == LIT_CHAR_DOT)
{
char_p++;
}
if (char_p < context_p->source_end_p
&& char_p[0] >= LIT_CHAR_0
&& char_p[0] <= LIT_CHAR_9)
{
lexer_parse_number (context_p);
lexer_construct_number_object (context_p, false, false);
return;
}
}
if (create_literal_object)
{
lexer_construct_literal_object (context_p,
&context_p->token.lit_location,
LEXER_STRING_LITERAL);
return;
}
}
parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED);
} /* lexer_expect_object_literal_id */
/**
* Next token must be an identifier.
*/
void
lexer_scan_identifier (parser_context_t *context_p, /**< context */
bool propety_name) /**< property name */
{
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
if (context_p->source_p < context_p->source_end_p
&& (lit_char_is_identifier_start (context_p->source_p) || context_p->source_p[0] == LIT_CHAR_BACKSLASH))
{
lexer_parse_identifier (context_p, false);
if (propety_name && context_p->token.lit_location.length == 3)
{
skip_spaces (context_p);
if (context_p->source_p < context_p->source_end_p
&& context_p->source_p[0] != LIT_CHAR_COLON)
{
if (lexer_compare_identifier_to_current (context_p, &lexer_get_literal))
{
context_p->token.type = LEXER_PROPERTY_GETTER;
}
else if (lexer_compare_identifier_to_current (context_p, &lexer_set_literal))
{
context_p->token.type = LEXER_PROPERTY_SETTER;
}
}
}
return;
}
if (propety_name)
{
lexer_next_token (context_p);
if (context_p->token.type == LEXER_LITERAL
|| context_p->token.type == LEXER_RIGHT_BRACE)
{
return;
}
}
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED);
} /* lexer_scan_identifier */
/**
* Compares the given identifier to that which is the current token
* in the parser context.
*
* @return true if the input identifiers are the same
*/
bool
lexer_compare_identifier_to_current (parser_context_t *context_p, /**< context */
const lexer_lit_location_t *right) /**< identifier */
{
lexer_lit_location_t *left = &context_p->token.lit_location;
const uint8_t *left_p;
const uint8_t *right_p;
size_t count;
JERRY_ASSERT (left->length > 0 && right->length > 0);
if (left->length != right->length)
{
return 0;
}
if (!left->has_escape && !right->has_escape)
{
return memcmp (left->char_p, right->char_p, left->length) == 0;
}
left_p = left->char_p;
right_p = right->char_p;
count = left->length;
do
{
uint8_t utf8_buf[3];
size_t utf8_len, offset;
/* Backslash cannot be part of a multibyte UTF-8 character. */
if (*left_p != LIT_CHAR_BACKSLASH && *right_p != LIT_CHAR_BACKSLASH)
{
if (*left_p++ != *right_p++)
{
return false;
}
count--;
continue;
}
if (*left_p == LIT_CHAR_BACKSLASH && *right_p == LIT_CHAR_BACKSLASH)
{
uint16_t left_chr = lexer_hex_to_character (context_p, left_p, 6);
if (left_chr != lexer_hex_to_character (context_p, right_p, 6))
{
return false;
}
left_p += 6;
right_p += 6;
count += lit_char_get_utf8_length (left_chr);
continue;
}
/* One character is encoded as unicode sequence. */
if (*right_p == LIT_CHAR_BACKSLASH)
{
/* The pointers can be swapped. */
const uint8_t *swap_p = left_p;
left_p = right_p;
right_p = swap_p;
}
utf8_len = lit_char_to_utf8_bytes (utf8_buf, lexer_hex_to_character (context_p, left_p, 6));
JERRY_ASSERT (utf8_len > 0);
count -= utf8_len;
offset = 0;
do
{
if (utf8_buf[offset] != *right_p++)
{
return false;
}
offset++;
}
while (offset < utf8_len);
left_p += 6;
}
while (count > 0);
return true;
} /* lexer_compare_identifier_to_current */
/**
* @}
* @}
* @}
*/
#endif /* JERRY_JS_PARSER */
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3381_0 |
crossvul-cpp_data_good_3958_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* OV519 driver
*
* Copyright (C) 2008-2011 Jean-François Moine <moinejf@free.fr>
* Copyright (C) 2009 Hans de Goede <hdegoede@redhat.com>
*
* This module is adapted from the ov51x-jpeg package, which itself
* was adapted from the ov511 driver.
*
* Original copyright for the ov511 driver is:
*
* Copyright (c) 1999-2006 Mark W. McClelland
* Support for OV519, OV8610 Copyright (c) 2003 Joerg Heckenbach
* Many improvements by Bret Wallach <bwallac1@san.rr.com>
* Color fixes by by Orion Sky Lawlor <olawlor@acm.org> (2/26/2000)
* OV7620 fixes by Charl P. Botha <cpbotha@ieee.org>
* Changes by Claudio Matsuoka <claudio@conectiva.com>
*
* ov51x-jpeg original copyright is:
*
* Copyright (c) 2004-2007 Romain Beauxis <toots@rastageeks.org>
* Support for OV7670 sensors was contributed by Sam Skipsey <aoanla@yahoo.com>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "ov519"
#include <linux/input.h>
#include "gspca.h"
/* The jpeg_hdr is used by w996Xcf only */
/* The CONEX_CAM define for jpeg.h needs renaming, now its used here too */
#define CONEX_CAM
#include "jpeg.h"
MODULE_AUTHOR("Jean-Francois Moine <http://moinejf.free.fr>");
MODULE_DESCRIPTION("OV519 USB Camera Driver");
MODULE_LICENSE("GPL");
/* global parameters */
static int frame_rate;
/* Number of times to retry a failed I2C transaction. Increase this if you
* are getting "Failed to read sensor ID..." */
static int i2c_detect_tries = 10;
/* ov519 device descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct v4l2_ctrl *jpegqual;
struct v4l2_ctrl *freq;
struct { /* h/vflip control cluster */
struct v4l2_ctrl *hflip;
struct v4l2_ctrl *vflip;
};
struct { /* autobrightness/brightness control cluster */
struct v4l2_ctrl *autobright;
struct v4l2_ctrl *brightness;
};
u8 revision;
u8 packet_nr;
char bridge;
#define BRIDGE_OV511 0
#define BRIDGE_OV511PLUS 1
#define BRIDGE_OV518 2
#define BRIDGE_OV518PLUS 3
#define BRIDGE_OV519 4 /* = ov530 */
#define BRIDGE_OVFX2 5
#define BRIDGE_W9968CF 6
#define BRIDGE_MASK 7
char invert_led;
#define BRIDGE_INVERT_LED 8
char snapshot_pressed;
char snapshot_needs_reset;
/* Determined by sensor type */
u8 sif;
#define QUALITY_MIN 50
#define QUALITY_MAX 70
#define QUALITY_DEF 50
u8 stopped; /* Streaming is temporarily paused */
u8 first_frame;
u8 frame_rate; /* current Framerate */
u8 clockdiv; /* clockdiv override */
s8 sensor; /* Type of image sensor chip (SEN_*) */
u8 sensor_addr;
u16 sensor_width;
u16 sensor_height;
s16 sensor_reg_cache[256];
u8 jpeg_hdr[JPEG_HDR_SZ];
};
enum sensors {
SEN_OV2610,
SEN_OV2610AE,
SEN_OV3610,
SEN_OV6620,
SEN_OV6630,
SEN_OV66308AF,
SEN_OV7610,
SEN_OV7620,
SEN_OV7620AE,
SEN_OV7640,
SEN_OV7648,
SEN_OV7660,
SEN_OV7670,
SEN_OV76BE,
SEN_OV8610,
SEN_OV9600,
};
/* Note this is a bit of a hack, but the w9968cf driver needs the code for all
the ov sensors which is already present here. When we have the time we
really should move the sensor drivers to v4l2 sub drivers. */
#include "w996Xcf.c"
/* table of the disabled controls */
struct ctrl_valid {
unsigned int has_brightness:1;
unsigned int has_contrast:1;
unsigned int has_exposure:1;
unsigned int has_autogain:1;
unsigned int has_sat:1;
unsigned int has_hvflip:1;
unsigned int has_autobright:1;
unsigned int has_freq:1;
};
static const struct ctrl_valid valid_controls[] = {
[SEN_OV2610] = {
.has_exposure = 1,
.has_autogain = 1,
},
[SEN_OV2610AE] = {
.has_exposure = 1,
.has_autogain = 1,
},
[SEN_OV3610] = {
/* No controls */
},
[SEN_OV6620] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV6630] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV66308AF] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV7610] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV7620] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV7620AE] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV7640] = {
.has_brightness = 1,
.has_sat = 1,
.has_freq = 1,
},
[SEN_OV7648] = {
.has_brightness = 1,
.has_sat = 1,
.has_freq = 1,
},
[SEN_OV7660] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_hvflip = 1,
.has_freq = 1,
},
[SEN_OV7670] = {
.has_brightness = 1,
.has_contrast = 1,
.has_hvflip = 1,
.has_freq = 1,
},
[SEN_OV76BE] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
.has_freq = 1,
},
[SEN_OV8610] = {
.has_brightness = 1,
.has_contrast = 1,
.has_sat = 1,
.has_autobright = 1,
},
[SEN_OV9600] = {
.has_exposure = 1,
.has_autogain = 1,
},
};
static const struct v4l2_pix_format ov519_vga_mode[] = {
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format ov519_sif_mode[] = {
{160, 120, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 3},
{176, 144, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{352, 288, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
/* Note some of the sizeimage values for the ov511 / ov518 may seem
larger then necessary, however they need to be this big as the ov511 /
ov518 always fills the entire isoc frame, using 0 padding bytes when
it doesn't have any data. So with low framerates the amount of data
transferred can become quite large (libv4l will remove all the 0 padding
in userspace). */
static const struct v4l2_pix_format ov518_vga_mode[] = {
{320, 240, V4L2_PIX_FMT_OV518, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{640, 480, V4L2_PIX_FMT_OV518, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 2,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format ov518_sif_mode[] = {
{160, 120, V4L2_PIX_FMT_OV518, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 70000,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 3},
{176, 144, V4L2_PIX_FMT_OV518, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 70000,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{320, 240, V4L2_PIX_FMT_OV518, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{352, 288, V4L2_PIX_FMT_OV518, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format ov511_vga_mode[] = {
{320, 240, V4L2_PIX_FMT_OV511, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{640, 480, V4L2_PIX_FMT_OV511, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 2,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format ov511_sif_mode[] = {
{160, 120, V4L2_PIX_FMT_OV511, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 70000,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 3},
{176, 144, V4L2_PIX_FMT_OV511, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 70000,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{320, 240, V4L2_PIX_FMT_OV511, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{352, 288, V4L2_PIX_FMT_OV511, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format ovfx2_ov2610_mode[] = {
{800, 600, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 800,
.sizeimage = 800 * 600,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1},
{1600, 1200, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 1600,
.sizeimage = 1600 * 1200,
.colorspace = V4L2_COLORSPACE_SRGB},
};
static const struct v4l2_pix_format ovfx2_ov3610_mode[] = {
{640, 480, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1},
{800, 600, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 800,
.sizeimage = 800 * 600,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1},
{1024, 768, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 1024,
.sizeimage = 1024 * 768,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1},
{1600, 1200, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 1600,
.sizeimage = 1600 * 1200,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0},
{2048, 1536, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 2048,
.sizeimage = 2048 * 1536,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0},
};
static const struct v4l2_pix_format ovfx2_ov9600_mode[] = {
{640, 480, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1},
{1280, 1024, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 1280,
.sizeimage = 1280 * 1024,
.colorspace = V4L2_COLORSPACE_SRGB},
};
/* Registers common to OV511 / OV518 */
#define R51x_FIFO_PSIZE 0x30 /* 2 bytes wide w/ OV518(+) */
#define R51x_SYS_RESET 0x50
/* Reset type flags */
#define OV511_RESET_OMNICE 0x08
#define R51x_SYS_INIT 0x53
#define R51x_SYS_SNAP 0x52
#define R51x_SYS_CUST_ID 0x5f
#define R51x_COMP_LUT_BEGIN 0x80
/* OV511 Camera interface register numbers */
#define R511_CAM_DELAY 0x10
#define R511_CAM_EDGE 0x11
#define R511_CAM_PXCNT 0x12
#define R511_CAM_LNCNT 0x13
#define R511_CAM_PXDIV 0x14
#define R511_CAM_LNDIV 0x15
#define R511_CAM_UV_EN 0x16
#define R511_CAM_LINE_MODE 0x17
#define R511_CAM_OPTS 0x18
#define R511_SNAP_FRAME 0x19
#define R511_SNAP_PXCNT 0x1a
#define R511_SNAP_LNCNT 0x1b
#define R511_SNAP_PXDIV 0x1c
#define R511_SNAP_LNDIV 0x1d
#define R511_SNAP_UV_EN 0x1e
#define R511_SNAP_OPTS 0x1f
#define R511_DRAM_FLOW_CTL 0x20
#define R511_FIFO_OPTS 0x31
#define R511_I2C_CTL 0x40
#define R511_SYS_LED_CTL 0x55 /* OV511+ only */
#define R511_COMP_EN 0x78
#define R511_COMP_LUT_EN 0x79
/* OV518 Camera interface register numbers */
#define R518_GPIO_OUT 0x56 /* OV518(+) only */
#define R518_GPIO_CTL 0x57 /* OV518(+) only */
/* OV519 Camera interface register numbers */
#define OV519_R10_H_SIZE 0x10
#define OV519_R11_V_SIZE 0x11
#define OV519_R12_X_OFFSETL 0x12
#define OV519_R13_X_OFFSETH 0x13
#define OV519_R14_Y_OFFSETL 0x14
#define OV519_R15_Y_OFFSETH 0x15
#define OV519_R16_DIVIDER 0x16
#define OV519_R20_DFR 0x20
#define OV519_R25_FORMAT 0x25
/* OV519 System Controller register numbers */
#define OV519_R51_RESET1 0x51
#define OV519_R54_EN_CLK1 0x54
#define OV519_R57_SNAPSHOT 0x57
#define OV519_GPIO_DATA_OUT0 0x71
#define OV519_GPIO_IO_CTRL0 0x72
/*#define OV511_ENDPOINT_ADDRESS 1 * Isoc endpoint number */
/*
* The FX2 chip does not give us a zero length read at end of frame.
* It does, however, give a short read at the end of a frame, if
* necessary, rather than run two frames together.
*
* By choosing the right bulk transfer size, we are guaranteed to always
* get a short read for the last read of each frame. Frame sizes are
* always a composite number (width * height, or a multiple) so if we
* choose a prime number, we are guaranteed that the last read of a
* frame will be short.
*
* But it isn't that easy: the 2.6 kernel requires a multiple of 4KB,
* otherwise EOVERFLOW "babbling" errors occur. I have not been able
* to figure out why. [PMiller]
*
* The constant (13 * 4096) is the largest "prime enough" number less than 64KB.
*
* It isn't enough to know the number of bytes per frame, in case we
* have data dropouts or buffer overruns (even though the FX2 double
* buffers, there are some pretty strict real time constraints for
* isochronous transfer for larger frame sizes).
*/
/*jfm: this value does not work for 800x600 - see isoc_init */
#define OVFX2_BULK_SIZE (13 * 4096)
/* I2C registers */
#define R51x_I2C_W_SID 0x41
#define R51x_I2C_SADDR_3 0x42
#define R51x_I2C_SADDR_2 0x43
#define R51x_I2C_R_SID 0x44
#define R51x_I2C_DATA 0x45
#define R518_I2C_CTL 0x47 /* OV518(+) only */
#define OVFX2_I2C_ADDR 0x00
/* I2C ADDRESSES */
#define OV7xx0_SID 0x42
#define OV_HIRES_SID 0x60 /* OV9xxx / OV2xxx / OV3xxx */
#define OV8xx0_SID 0xa0
#define OV6xx0_SID 0xc0
/* OV7610 registers */
#define OV7610_REG_GAIN 0x00 /* gain setting (5:0) */
#define OV7610_REG_BLUE 0x01 /* blue channel balance */
#define OV7610_REG_RED 0x02 /* red channel balance */
#define OV7610_REG_SAT 0x03 /* saturation */
#define OV8610_REG_HUE 0x04 /* 04 reserved */
#define OV7610_REG_CNT 0x05 /* Y contrast */
#define OV7610_REG_BRT 0x06 /* Y brightness */
#define OV7610_REG_COM_C 0x14 /* misc common regs */
#define OV7610_REG_ID_HIGH 0x1c /* manufacturer ID MSB */
#define OV7610_REG_ID_LOW 0x1d /* manufacturer ID LSB */
#define OV7610_REG_COM_I 0x29 /* misc settings */
/* OV7660 and OV7670 registers */
#define OV7670_R00_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */
#define OV7670_R01_BLUE 0x01 /* blue gain */
#define OV7670_R02_RED 0x02 /* red gain */
#define OV7670_R03_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */
#define OV7670_R04_COM1 0x04 /* Control 1 */
/*#define OV7670_R07_AECHH 0x07 * AEC MS 5 bits */
#define OV7670_R0C_COM3 0x0c /* Control 3 */
#define OV7670_R0D_COM4 0x0d /* Control 4 */
#define OV7670_R0E_COM5 0x0e /* All "reserved" */
#define OV7670_R0F_COM6 0x0f /* Control 6 */
#define OV7670_R10_AECH 0x10 /* More bits of AEC value */
#define OV7670_R11_CLKRC 0x11 /* Clock control */
#define OV7670_R12_COM7 0x12 /* Control 7 */
#define OV7670_COM7_FMT_VGA 0x00
/*#define OV7670_COM7_YUV 0x00 * YUV */
#define OV7670_COM7_FMT_QVGA 0x10 /* QVGA format */
#define OV7670_COM7_FMT_MASK 0x38
#define OV7670_COM7_RESET 0x80 /* Register reset */
#define OV7670_R13_COM8 0x13 /* Control 8 */
#define OV7670_COM8_AEC 0x01 /* Auto exposure enable */
#define OV7670_COM8_AWB 0x02 /* White balance enable */
#define OV7670_COM8_AGC 0x04 /* Auto gain enable */
#define OV7670_COM8_BFILT 0x20 /* Band filter enable */
#define OV7670_COM8_AECSTEP 0x40 /* Unlimited AEC step size */
#define OV7670_COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */
#define OV7670_R14_COM9 0x14 /* Control 9 - gain ceiling */
#define OV7670_R15_COM10 0x15 /* Control 10 */
#define OV7670_R17_HSTART 0x17 /* Horiz start high bits */
#define OV7670_R18_HSTOP 0x18 /* Horiz stop high bits */
#define OV7670_R19_VSTART 0x19 /* Vert start high bits */
#define OV7670_R1A_VSTOP 0x1a /* Vert stop high bits */
#define OV7670_R1E_MVFP 0x1e /* Mirror / vflip */
#define OV7670_MVFP_VFLIP 0x10 /* vertical flip */
#define OV7670_MVFP_MIRROR 0x20 /* Mirror image */
#define OV7670_R24_AEW 0x24 /* AGC upper limit */
#define OV7670_R25_AEB 0x25 /* AGC lower limit */
#define OV7670_R26_VPT 0x26 /* AGC/AEC fast mode op region */
#define OV7670_R32_HREF 0x32 /* HREF pieces */
#define OV7670_R3A_TSLB 0x3a /* lots of stuff */
#define OV7670_R3B_COM11 0x3b /* Control 11 */
#define OV7670_COM11_EXP 0x02
#define OV7670_COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */
#define OV7670_R3C_COM12 0x3c /* Control 12 */
#define OV7670_R3D_COM13 0x3d /* Control 13 */
#define OV7670_COM13_GAMMA 0x80 /* Gamma enable */
#define OV7670_COM13_UVSAT 0x40 /* UV saturation auto adjustment */
#define OV7670_R3E_COM14 0x3e /* Control 14 */
#define OV7670_R3F_EDGE 0x3f /* Edge enhancement factor */
#define OV7670_R40_COM15 0x40 /* Control 15 */
/*#define OV7670_COM15_R00FF 0xc0 * 00 to FF */
#define OV7670_R41_COM16 0x41 /* Control 16 */
#define OV7670_COM16_AWBGAIN 0x08 /* AWB gain enable */
/* end of ov7660 common registers */
#define OV7670_R55_BRIGHT 0x55 /* Brightness */
#define OV7670_R56_CONTRAS 0x56 /* Contrast control */
#define OV7670_R69_GFIX 0x69 /* Fix gain control */
/*#define OV7670_R8C_RGB444 0x8c * RGB 444 control */
#define OV7670_R9F_HAECC1 0x9f /* Hist AEC/AGC control 1 */
#define OV7670_RA0_HAECC2 0xa0 /* Hist AEC/AGC control 2 */
#define OV7670_RA5_BD50MAX 0xa5 /* 50hz banding step limit */
#define OV7670_RA6_HAECC3 0xa6 /* Hist AEC/AGC control 3 */
#define OV7670_RA7_HAECC4 0xa7 /* Hist AEC/AGC control 4 */
#define OV7670_RA8_HAECC5 0xa8 /* Hist AEC/AGC control 5 */
#define OV7670_RA9_HAECC6 0xa9 /* Hist AEC/AGC control 6 */
#define OV7670_RAA_HAECC7 0xaa /* Hist AEC/AGC control 7 */
#define OV7670_RAB_BD60MAX 0xab /* 60hz banding step limit */
struct ov_regvals {
u8 reg;
u8 val;
};
struct ov_i2c_regvals {
u8 reg;
u8 val;
};
/* Settings for OV2610 camera chip */
static const struct ov_i2c_regvals norm_2610[] = {
{ 0x12, 0x80 }, /* reset */
};
static const struct ov_i2c_regvals norm_2610ae[] = {
{0x12, 0x80}, /* reset */
{0x13, 0xcd},
{0x09, 0x01},
{0x0d, 0x00},
{0x11, 0x80},
{0x12, 0x20}, /* 1600x1200 */
{0x33, 0x0c},
{0x35, 0x90},
{0x36, 0x37},
/* ms-win traces */
{0x11, 0x83}, /* clock / 3 ? */
{0x2d, 0x00}, /* 60 Hz filter */
{0x24, 0xb0}, /* normal colors */
{0x25, 0x90},
{0x10, 0x43},
};
static const struct ov_i2c_regvals norm_3620b[] = {
/*
* From the datasheet: "Note that after writing to register COMH
* (0x12) to change the sensor mode, registers related to the
* sensor’s cropping window will be reset back to their default
* values."
*
* "wait 4096 external clock ... to make sure the sensor is
* stable and ready to access registers" i.e. 160us at 24MHz
*/
{ 0x12, 0x80 }, /* COMH reset */
{ 0x12, 0x00 }, /* QXGA, master */
/*
* 11 CLKRC "Clock Rate Control"
* [7] internal frequency doublers: on
* [6] video port mode: master
* [5:0] clock divider: 1
*/
{ 0x11, 0x80 },
/*
* 13 COMI "Common Control I"
* = 192 (0xC0) 11000000
* COMI[7] "AEC speed selection"
* = 1 (0x01) 1....... "Faster AEC correction"
* COMI[6] "AEC speed step selection"
* = 1 (0x01) .1...... "Big steps, fast"
* COMI[5] "Banding filter on off"
* = 0 (0x00) ..0..... "Off"
* COMI[4] "Banding filter option"
* = 0 (0x00) ...0.... "Main clock is 48 MHz and
* the PLL is ON"
* COMI[3] "Reserved"
* = 0 (0x00) ....0...
* COMI[2] "AGC auto manual control selection"
* = 0 (0x00) .....0.. "Manual"
* COMI[1] "AWB auto manual control selection"
* = 0 (0x00) ......0. "Manual"
* COMI[0] "Exposure control"
* = 0 (0x00) .......0 "Manual"
*/
{ 0x13, 0xc0 },
/*
* 09 COMC "Common Control C"
* = 8 (0x08) 00001000
* COMC[7:5] "Reserved"
* = 0 (0x00) 000.....
* COMC[4] "Sleep Mode Enable"
* = 0 (0x00) ...0.... "Normal mode"
* COMC[3:2] "Sensor sampling reset timing selection"
* = 2 (0x02) ....10.. "Longer reset time"
* COMC[1:0] "Output drive current select"
* = 0 (0x00) ......00 "Weakest"
*/
{ 0x09, 0x08 },
/*
* 0C COMD "Common Control D"
* = 8 (0x08) 00001000
* COMD[7] "Reserved"
* = 0 (0x00) 0.......
* COMD[6] "Swap MSB and LSB at the output port"
* = 0 (0x00) .0...... "False"
* COMD[5:3] "Reserved"
* = 1 (0x01) ..001...
* COMD[2] "Output Average On Off"
* = 0 (0x00) .....0.. "Output Normal"
* COMD[1] "Sensor precharge voltage selection"
* = 0 (0x00) ......0. "Selects internal
* reference precharge
* voltage"
* COMD[0] "Snapshot option"
* = 0 (0x00) .......0 "Enable live video output
* after snapshot sequence"
*/
{ 0x0c, 0x08 },
/*
* 0D COME "Common Control E"
* = 161 (0xA1) 10100001
* COME[7] "Output average option"
* = 1 (0x01) 1....... "Output average of 4 pixels"
* COME[6] "Anti-blooming control"
* = 0 (0x00) .0...... "Off"
* COME[5:3] "Reserved"
* = 4 (0x04) ..100...
* COME[2] "Clock output power down pin status"
* = 0 (0x00) .....0.. "Tri-state data output pin
* on power down"
* COME[1] "Data output pin status selection at power down"
* = 0 (0x00) ......0. "Tri-state VSYNC, PCLK,
* HREF, and CHSYNC pins on
* power down"
* COME[0] "Auto zero circuit select"
* = 1 (0x01) .......1 "On"
*/
{ 0x0d, 0xa1 },
/*
* 0E COMF "Common Control F"
* = 112 (0x70) 01110000
* COMF[7] "System clock selection"
* = 0 (0x00) 0....... "Use 24 MHz system clock"
* COMF[6:4] "Reserved"
* = 7 (0x07) .111....
* COMF[3] "Manual auto negative offset canceling selection"
* = 0 (0x00) ....0... "Auto detect negative
* offset and cancel it"
* COMF[2:0] "Reserved"
* = 0 (0x00) .....000
*/
{ 0x0e, 0x70 },
/*
* 0F COMG "Common Control G"
* = 66 (0x42) 01000010
* COMG[7] "Optical black output selection"
* = 0 (0x00) 0....... "Disable"
* COMG[6] "Black level calibrate selection"
* = 1 (0x01) .1...... "Use optical black pixels
* to calibrate"
* COMG[5:4] "Reserved"
* = 0 (0x00) ..00....
* COMG[3] "Channel offset adjustment"
* = 0 (0x00) ....0... "Disable offset adjustment"
* COMG[2] "ADC black level calibration option"
* = 0 (0x00) .....0.. "Use B/G line and G/R
* line to calibrate each
* channel's black level"
* COMG[1] "Reserved"
* = 1 (0x01) ......1.
* COMG[0] "ADC black level calibration enable"
* = 0 (0x00) .......0 "Disable"
*/
{ 0x0f, 0x42 },
/*
* 14 COMJ "Common Control J"
* = 198 (0xC6) 11000110
* COMJ[7:6] "AGC gain ceiling"
* = 3 (0x03) 11...... "8x"
* COMJ[5:4] "Reserved"
* = 0 (0x00) ..00....
* COMJ[3] "Auto banding filter"
* = 0 (0x00) ....0... "Banding filter is always
* on off depending on
* COMI[5] setting"
* COMJ[2] "VSYNC drop option"
* = 1 (0x01) .....1.. "SYNC is dropped if frame
* data is dropped"
* COMJ[1] "Frame data drop"
* = 1 (0x01) ......1. "Drop frame data if
* exposure is not within
* tolerance. In AEC mode,
* data is normally dropped
* when data is out of
* range."
* COMJ[0] "Reserved"
* = 0 (0x00) .......0
*/
{ 0x14, 0xc6 },
/*
* 15 COMK "Common Control K"
* = 2 (0x02) 00000010
* COMK[7] "CHSYNC pin output swap"
* = 0 (0x00) 0....... "CHSYNC"
* COMK[6] "HREF pin output swap"
* = 0 (0x00) .0...... "HREF"
* COMK[5] "PCLK output selection"
* = 0 (0x00) ..0..... "PCLK always output"
* COMK[4] "PCLK edge selection"
* = 0 (0x00) ...0.... "Data valid on falling edge"
* COMK[3] "HREF output polarity"
* = 0 (0x00) ....0... "positive"
* COMK[2] "Reserved"
* = 0 (0x00) .....0..
* COMK[1] "VSYNC polarity"
* = 1 (0x01) ......1. "negative"
* COMK[0] "HSYNC polarity"
* = 0 (0x00) .......0 "positive"
*/
{ 0x15, 0x02 },
/*
* 33 CHLF "Current Control"
* = 9 (0x09) 00001001
* CHLF[7:6] "Sensor current control"
* = 0 (0x00) 00......
* CHLF[5] "Sensor current range control"
* = 0 (0x00) ..0..... "normal range"
* CHLF[4] "Sensor current"
* = 0 (0x00) ...0.... "normal current"
* CHLF[3] "Sensor buffer current control"
* = 1 (0x01) ....1... "half current"
* CHLF[2] "Column buffer current control"
* = 0 (0x00) .....0.. "normal current"
* CHLF[1] "Analog DSP current control"
* = 0 (0x00) ......0. "normal current"
* CHLF[1] "ADC current control"
* = 0 (0x00) ......0. "normal current"
*/
{ 0x33, 0x09 },
/*
* 34 VBLM "Blooming Control"
* = 80 (0x50) 01010000
* VBLM[7] "Hard soft reset switch"
* = 0 (0x00) 0....... "Hard reset"
* VBLM[6:4] "Blooming voltage selection"
* = 5 (0x05) .101....
* VBLM[3:0] "Sensor current control"
* = 0 (0x00) ....0000
*/
{ 0x34, 0x50 },
/*
* 36 VCHG "Sensor Precharge Voltage Control"
* = 0 (0x00) 00000000
* VCHG[7] "Reserved"
* = 0 (0x00) 0.......
* VCHG[6:4] "Sensor precharge voltage control"
* = 0 (0x00) .000....
* VCHG[3:0] "Sensor array common reference"
* = 0 (0x00) ....0000
*/
{ 0x36, 0x00 },
/*
* 37 ADC "ADC Reference Control"
* = 4 (0x04) 00000100
* ADC[7:4] "Reserved"
* = 0 (0x00) 0000....
* ADC[3] "ADC input signal range"
* = 0 (0x00) ....0... "Input signal 1.0x"
* ADC[2:0] "ADC range control"
* = 4 (0x04) .....100
*/
{ 0x37, 0x04 },
/*
* 38 ACOM "Analog Common Ground"
* = 82 (0x52) 01010010
* ACOM[7] "Analog gain control"
* = 0 (0x00) 0....... "Gain 1x"
* ACOM[6] "Analog black level calibration"
* = 1 (0x01) .1...... "On"
* ACOM[5:0] "Reserved"
* = 18 (0x12) ..010010
*/
{ 0x38, 0x52 },
/*
* 3A FREFA "Internal Reference Adjustment"
* = 0 (0x00) 00000000
* FREFA[7:0] "Range"
* = 0 (0x00) 00000000
*/
{ 0x3a, 0x00 },
/*
* 3C FVOPT "Internal Reference Adjustment"
* = 31 (0x1F) 00011111
* FVOPT[7:0] "Range"
* = 31 (0x1F) 00011111
*/
{ 0x3c, 0x1f },
/*
* 44 Undocumented = 0 (0x00) 00000000
* 44[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x44, 0x00 },
/*
* 40 Undocumented = 0 (0x00) 00000000
* 40[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x40, 0x00 },
/*
* 41 Undocumented = 0 (0x00) 00000000
* 41[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x41, 0x00 },
/*
* 42 Undocumented = 0 (0x00) 00000000
* 42[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x42, 0x00 },
/*
* 43 Undocumented = 0 (0x00) 00000000
* 43[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x43, 0x00 },
/*
* 45 Undocumented = 128 (0x80) 10000000
* 45[7:0] "It's a secret"
* = 128 (0x80) 10000000
*/
{ 0x45, 0x80 },
/*
* 48 Undocumented = 192 (0xC0) 11000000
* 48[7:0] "It's a secret"
* = 192 (0xC0) 11000000
*/
{ 0x48, 0xc0 },
/*
* 49 Undocumented = 25 (0x19) 00011001
* 49[7:0] "It's a secret"
* = 25 (0x19) 00011001
*/
{ 0x49, 0x19 },
/*
* 4B Undocumented = 128 (0x80) 10000000
* 4B[7:0] "It's a secret"
* = 128 (0x80) 10000000
*/
{ 0x4b, 0x80 },
/*
* 4D Undocumented = 196 (0xC4) 11000100
* 4D[7:0] "It's a secret"
* = 196 (0xC4) 11000100
*/
{ 0x4d, 0xc4 },
/*
* 35 VREF "Reference Voltage Control"
* = 76 (0x4c) 01001100
* VREF[7:5] "Column high reference control"
* = 2 (0x02) 010..... "higher voltage"
* VREF[4:2] "Column low reference control"
* = 3 (0x03) ...011.. "Highest voltage"
* VREF[1:0] "Reserved"
* = 0 (0x00) ......00
*/
{ 0x35, 0x4c },
/*
* 3D Undocumented = 0 (0x00) 00000000
* 3D[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x3d, 0x00 },
/*
* 3E Undocumented = 0 (0x00) 00000000
* 3E[7:0] "It's a secret"
* = 0 (0x00) 00000000
*/
{ 0x3e, 0x00 },
/*
* 3B FREFB "Internal Reference Adjustment"
* = 24 (0x18) 00011000
* FREFB[7:0] "Range"
* = 24 (0x18) 00011000
*/
{ 0x3b, 0x18 },
/*
* 33 CHLF "Current Control"
* = 25 (0x19) 00011001
* CHLF[7:6] "Sensor current control"
* = 0 (0x00) 00......
* CHLF[5] "Sensor current range control"
* = 0 (0x00) ..0..... "normal range"
* CHLF[4] "Sensor current"
* = 1 (0x01) ...1.... "double current"
* CHLF[3] "Sensor buffer current control"
* = 1 (0x01) ....1... "half current"
* CHLF[2] "Column buffer current control"
* = 0 (0x00) .....0.. "normal current"
* CHLF[1] "Analog DSP current control"
* = 0 (0x00) ......0. "normal current"
* CHLF[1] "ADC current control"
* = 0 (0x00) ......0. "normal current"
*/
{ 0x33, 0x19 },
/*
* 34 VBLM "Blooming Control"
* = 90 (0x5A) 01011010
* VBLM[7] "Hard soft reset switch"
* = 0 (0x00) 0....... "Hard reset"
* VBLM[6:4] "Blooming voltage selection"
* = 5 (0x05) .101....
* VBLM[3:0] "Sensor current control"
* = 10 (0x0A) ....1010
*/
{ 0x34, 0x5a },
/*
* 3B FREFB "Internal Reference Adjustment"
* = 0 (0x00) 00000000
* FREFB[7:0] "Range"
* = 0 (0x00) 00000000
*/
{ 0x3b, 0x00 },
/*
* 33 CHLF "Current Control"
* = 9 (0x09) 00001001
* CHLF[7:6] "Sensor current control"
* = 0 (0x00) 00......
* CHLF[5] "Sensor current range control"
* = 0 (0x00) ..0..... "normal range"
* CHLF[4] "Sensor current"
* = 0 (0x00) ...0.... "normal current"
* CHLF[3] "Sensor buffer current control"
* = 1 (0x01) ....1... "half current"
* CHLF[2] "Column buffer current control"
* = 0 (0x00) .....0.. "normal current"
* CHLF[1] "Analog DSP current control"
* = 0 (0x00) ......0. "normal current"
* CHLF[1] "ADC current control"
* = 0 (0x00) ......0. "normal current"
*/
{ 0x33, 0x09 },
/*
* 34 VBLM "Blooming Control"
* = 80 (0x50) 01010000
* VBLM[7] "Hard soft reset switch"
* = 0 (0x00) 0....... "Hard reset"
* VBLM[6:4] "Blooming voltage selection"
* = 5 (0x05) .101....
* VBLM[3:0] "Sensor current control"
* = 0 (0x00) ....0000
*/
{ 0x34, 0x50 },
/*
* 12 COMH "Common Control H"
* = 64 (0x40) 01000000
* COMH[7] "SRST"
* = 0 (0x00) 0....... "No-op"
* COMH[6:4] "Resolution selection"
* = 4 (0x04) .100.... "XGA"
* COMH[3] "Master slave selection"
* = 0 (0x00) ....0... "Master mode"
* COMH[2] "Internal B/R channel option"
* = 0 (0x00) .....0.. "B/R use same channel"
* COMH[1] "Color bar test pattern"
* = 0 (0x00) ......0. "Off"
* COMH[0] "Reserved"
* = 0 (0x00) .......0
*/
{ 0x12, 0x40 },
/*
* 17 HREFST "Horizontal window start"
* = 31 (0x1F) 00011111
* HREFST[7:0] "Horizontal window start, 8 MSBs"
* = 31 (0x1F) 00011111
*/
{ 0x17, 0x1f },
/*
* 18 HREFEND "Horizontal window end"
* = 95 (0x5F) 01011111
* HREFEND[7:0] "Horizontal Window End, 8 MSBs"
* = 95 (0x5F) 01011111
*/
{ 0x18, 0x5f },
/*
* 19 VSTRT "Vertical window start"
* = 0 (0x00) 00000000
* VSTRT[7:0] "Vertical Window Start, 8 MSBs"
* = 0 (0x00) 00000000
*/
{ 0x19, 0x00 },
/*
* 1A VEND "Vertical window end"
* = 96 (0x60) 01100000
* VEND[7:0] "Vertical Window End, 8 MSBs"
* = 96 (0x60) 01100000
*/
{ 0x1a, 0x60 },
/*
* 32 COMM "Common Control M"
* = 18 (0x12) 00010010
* COMM[7:6] "Pixel clock divide option"
* = 0 (0x00) 00...... "/1"
* COMM[5:3] "Horizontal window end position, 3 LSBs"
* = 2 (0x02) ..010...
* COMM[2:0] "Horizontal window start position, 3 LSBs"
* = 2 (0x02) .....010
*/
{ 0x32, 0x12 },
/*
* 03 COMA "Common Control A"
* = 74 (0x4A) 01001010
* COMA[7:4] "AWB Update Threshold"
* = 4 (0x04) 0100....
* COMA[3:2] "Vertical window end line control 2 LSBs"
* = 2 (0x02) ....10..
* COMA[1:0] "Vertical window start line control 2 LSBs"
* = 2 (0x02) ......10
*/
{ 0x03, 0x4a },
/*
* 11 CLKRC "Clock Rate Control"
* = 128 (0x80) 10000000
* CLKRC[7] "Internal frequency doublers on off seclection"
* = 1 (0x01) 1....... "On"
* CLKRC[6] "Digital video master slave selection"
* = 0 (0x00) .0...... "Master mode, sensor
* provides PCLK"
* CLKRC[5:0] "Clock divider { CLK = PCLK/(1+CLKRC[5:0]) }"
* = 0 (0x00) ..000000
*/
{ 0x11, 0x80 },
/*
* 12 COMH "Common Control H"
* = 0 (0x00) 00000000
* COMH[7] "SRST"
* = 0 (0x00) 0....... "No-op"
* COMH[6:4] "Resolution selection"
* = 0 (0x00) .000.... "QXGA"
* COMH[3] "Master slave selection"
* = 0 (0x00) ....0... "Master mode"
* COMH[2] "Internal B/R channel option"
* = 0 (0x00) .....0.. "B/R use same channel"
* COMH[1] "Color bar test pattern"
* = 0 (0x00) ......0. "Off"
* COMH[0] "Reserved"
* = 0 (0x00) .......0
*/
{ 0x12, 0x00 },
/*
* 12 COMH "Common Control H"
* = 64 (0x40) 01000000
* COMH[7] "SRST"
* = 0 (0x00) 0....... "No-op"
* COMH[6:4] "Resolution selection"
* = 4 (0x04) .100.... "XGA"
* COMH[3] "Master slave selection"
* = 0 (0x00) ....0... "Master mode"
* COMH[2] "Internal B/R channel option"
* = 0 (0x00) .....0.. "B/R use same channel"
* COMH[1] "Color bar test pattern"
* = 0 (0x00) ......0. "Off"
* COMH[0] "Reserved"
* = 0 (0x00) .......0
*/
{ 0x12, 0x40 },
/*
* 17 HREFST "Horizontal window start"
* = 31 (0x1F) 00011111
* HREFST[7:0] "Horizontal window start, 8 MSBs"
* = 31 (0x1F) 00011111
*/
{ 0x17, 0x1f },
/*
* 18 HREFEND "Horizontal window end"
* = 95 (0x5F) 01011111
* HREFEND[7:0] "Horizontal Window End, 8 MSBs"
* = 95 (0x5F) 01011111
*/
{ 0x18, 0x5f },
/*
* 19 VSTRT "Vertical window start"
* = 0 (0x00) 00000000
* VSTRT[7:0] "Vertical Window Start, 8 MSBs"
* = 0 (0x00) 00000000
*/
{ 0x19, 0x00 },
/*
* 1A VEND "Vertical window end"
* = 96 (0x60) 01100000
* VEND[7:0] "Vertical Window End, 8 MSBs"
* = 96 (0x60) 01100000
*/
{ 0x1a, 0x60 },
/*
* 32 COMM "Common Control M"
* = 18 (0x12) 00010010
* COMM[7:6] "Pixel clock divide option"
* = 0 (0x00) 00...... "/1"
* COMM[5:3] "Horizontal window end position, 3 LSBs"
* = 2 (0x02) ..010...
* COMM[2:0] "Horizontal window start position, 3 LSBs"
* = 2 (0x02) .....010
*/
{ 0x32, 0x12 },
/*
* 03 COMA "Common Control A"
* = 74 (0x4A) 01001010
* COMA[7:4] "AWB Update Threshold"
* = 4 (0x04) 0100....
* COMA[3:2] "Vertical window end line control 2 LSBs"
* = 2 (0x02) ....10..
* COMA[1:0] "Vertical window start line control 2 LSBs"
* = 2 (0x02) ......10
*/
{ 0x03, 0x4a },
/*
* 02 RED "Red Gain Control"
* = 175 (0xAF) 10101111
* RED[7] "Action"
* = 1 (0x01) 1....... "gain = 1/(1+bitrev([6:0]))"
* RED[6:0] "Value"
* = 47 (0x2F) .0101111
*/
{ 0x02, 0xaf },
/*
* 2D ADDVSL "VSYNC Pulse Width"
* = 210 (0xD2) 11010010
* ADDVSL[7:0] "VSYNC pulse width, LSB"
* = 210 (0xD2) 11010010
*/
{ 0x2d, 0xd2 },
/*
* 00 GAIN = 24 (0x18) 00011000
* GAIN[7:6] "Reserved"
* = 0 (0x00) 00......
* GAIN[5] "Double"
* = 0 (0x00) ..0..... "False"
* GAIN[4] "Double"
* = 1 (0x01) ...1.... "True"
* GAIN[3:0] "Range"
* = 8 (0x08) ....1000
*/
{ 0x00, 0x18 },
/*
* 01 BLUE "Blue Gain Control"
* = 240 (0xF0) 11110000
* BLUE[7] "Action"
* = 1 (0x01) 1....... "gain = 1/(1+bitrev([6:0]))"
* BLUE[6:0] "Value"
* = 112 (0x70) .1110000
*/
{ 0x01, 0xf0 },
/*
* 10 AEC "Automatic Exposure Control"
* = 10 (0x0A) 00001010
* AEC[7:0] "Automatic Exposure Control, 8 MSBs"
* = 10 (0x0A) 00001010
*/
{ 0x10, 0x0a },
{ 0xe1, 0x67 },
{ 0xe3, 0x03 },
{ 0xe4, 0x26 },
{ 0xe5, 0x3e },
{ 0xf8, 0x01 },
{ 0xff, 0x01 },
};
static const struct ov_i2c_regvals norm_6x20[] = {
{ 0x12, 0x80 }, /* reset */
{ 0x11, 0x01 },
{ 0x03, 0x60 },
{ 0x05, 0x7f }, /* For when autoadjust is off */
{ 0x07, 0xa8 },
/* The ratio of 0x0c and 0x0d controls the white point */
{ 0x0c, 0x24 },
{ 0x0d, 0x24 },
{ 0x0f, 0x15 }, /* COMS */
{ 0x10, 0x75 }, /* AEC Exposure time */
{ 0x12, 0x24 }, /* Enable AGC */
{ 0x14, 0x04 },
/* 0x16: 0x06 helps frame stability with moving objects */
{ 0x16, 0x06 },
/* { 0x20, 0x30 }, * Aperture correction enable */
{ 0x26, 0xb2 }, /* BLC enable */
/* 0x28: 0x05 Selects RGB format if RGB on */
{ 0x28, 0x05 },
{ 0x2a, 0x04 }, /* Disable framerate adjust */
/* { 0x2b, 0xac }, * Framerate; Set 2a[7] first */
{ 0x2d, 0x85 },
{ 0x33, 0xa0 }, /* Color Processing Parameter */
{ 0x34, 0xd2 }, /* Max A/D range */
{ 0x38, 0x8b },
{ 0x39, 0x40 },
{ 0x3c, 0x39 }, /* Enable AEC mode changing */
{ 0x3c, 0x3c }, /* Change AEC mode */
{ 0x3c, 0x24 }, /* Disable AEC mode changing */
{ 0x3d, 0x80 },
/* These next two registers (0x4a, 0x4b) are undocumented.
* They control the color balance */
{ 0x4a, 0x80 },
{ 0x4b, 0x80 },
{ 0x4d, 0xd2 }, /* This reduces noise a bit */
{ 0x4e, 0xc1 },
{ 0x4f, 0x04 },
/* Do 50-53 have any effect? */
/* Toggle 0x12[2] off and on here? */
};
static const struct ov_i2c_regvals norm_6x30[] = {
{ 0x12, 0x80 }, /* Reset */
{ 0x00, 0x1f }, /* Gain */
{ 0x01, 0x99 }, /* Blue gain */
{ 0x02, 0x7c }, /* Red gain */
{ 0x03, 0xc0 }, /* Saturation */
{ 0x05, 0x0a }, /* Contrast */
{ 0x06, 0x95 }, /* Brightness */
{ 0x07, 0x2d }, /* Sharpness */
{ 0x0c, 0x20 },
{ 0x0d, 0x20 },
{ 0x0e, 0xa0 }, /* Was 0x20, bit7 enables a 2x gain which we need */
{ 0x0f, 0x05 },
{ 0x10, 0x9a },
{ 0x11, 0x00 }, /* Pixel clock = fastest */
{ 0x12, 0x24 }, /* Enable AGC and AWB */
{ 0x13, 0x21 },
{ 0x14, 0x80 },
{ 0x15, 0x01 },
{ 0x16, 0x03 },
{ 0x17, 0x38 },
{ 0x18, 0xea },
{ 0x19, 0x04 },
{ 0x1a, 0x93 },
{ 0x1b, 0x00 },
{ 0x1e, 0xc4 },
{ 0x1f, 0x04 },
{ 0x20, 0x20 },
{ 0x21, 0x10 },
{ 0x22, 0x88 },
{ 0x23, 0xc0 }, /* Crystal circuit power level */
{ 0x25, 0x9a }, /* Increase AEC black ratio */
{ 0x26, 0xb2 }, /* BLC enable */
{ 0x27, 0xa2 },
{ 0x28, 0x00 },
{ 0x29, 0x00 },
{ 0x2a, 0x84 }, /* 60 Hz power */
{ 0x2b, 0xa8 }, /* 60 Hz power */
{ 0x2c, 0xa0 },
{ 0x2d, 0x95 }, /* Enable auto-brightness */
{ 0x2e, 0x88 },
{ 0x33, 0x26 },
{ 0x34, 0x03 },
{ 0x36, 0x8f },
{ 0x37, 0x80 },
{ 0x38, 0x83 },
{ 0x39, 0x80 },
{ 0x3a, 0x0f },
{ 0x3b, 0x3c },
{ 0x3c, 0x1a },
{ 0x3d, 0x80 },
{ 0x3e, 0x80 },
{ 0x3f, 0x0e },
{ 0x40, 0x00 }, /* White bal */
{ 0x41, 0x00 }, /* White bal */
{ 0x42, 0x80 },
{ 0x43, 0x3f }, /* White bal */
{ 0x44, 0x80 },
{ 0x45, 0x20 },
{ 0x46, 0x20 },
{ 0x47, 0x80 },
{ 0x48, 0x7f },
{ 0x49, 0x00 },
{ 0x4a, 0x00 },
{ 0x4b, 0x80 },
{ 0x4c, 0xd0 },
{ 0x4d, 0x10 }, /* U = 0.563u, V = 0.714v */
{ 0x4e, 0x40 },
{ 0x4f, 0x07 }, /* UV avg., col. killer: max */
{ 0x50, 0xff },
{ 0x54, 0x23 }, /* Max AGC gain: 18dB */
{ 0x55, 0xff },
{ 0x56, 0x12 },
{ 0x57, 0x81 },
{ 0x58, 0x75 },
{ 0x59, 0x01 }, /* AGC dark current comp.: +1 */
{ 0x5a, 0x2c },
{ 0x5b, 0x0f }, /* AWB chrominance levels */
{ 0x5c, 0x10 },
{ 0x3d, 0x80 },
{ 0x27, 0xa6 },
{ 0x12, 0x20 }, /* Toggle AWB */
{ 0x12, 0x24 },
};
/* Lawrence Glaister <lg@jfm.bc.ca> reports:
*
* Register 0x0f in the 7610 has the following effects:
*
* 0x85 (AEC method 1): Best overall, good contrast range
* 0x45 (AEC method 2): Very overexposed
* 0xa5 (spec sheet default): Ok, but the black level is
* shifted resulting in loss of contrast
* 0x05 (old driver setting): very overexposed, too much
* contrast
*/
static const struct ov_i2c_regvals norm_7610[] = {
{ 0x10, 0xff },
{ 0x16, 0x06 },
{ 0x28, 0x24 },
{ 0x2b, 0xac },
{ 0x12, 0x00 },
{ 0x38, 0x81 },
{ 0x28, 0x24 }, /* 0c */
{ 0x0f, 0x85 }, /* lg's setting */
{ 0x15, 0x01 },
{ 0x20, 0x1c },
{ 0x23, 0x2a },
{ 0x24, 0x10 },
{ 0x25, 0x8a },
{ 0x26, 0xa2 },
{ 0x27, 0xc2 },
{ 0x2a, 0x04 },
{ 0x2c, 0xfe },
{ 0x2d, 0x93 },
{ 0x30, 0x71 },
{ 0x31, 0x60 },
{ 0x32, 0x26 },
{ 0x33, 0x20 },
{ 0x34, 0x48 },
{ 0x12, 0x24 },
{ 0x11, 0x01 },
{ 0x0c, 0x24 },
{ 0x0d, 0x24 },
};
static const struct ov_i2c_regvals norm_7620[] = {
{ 0x12, 0x80 }, /* reset */
{ 0x00, 0x00 }, /* gain */
{ 0x01, 0x80 }, /* blue gain */
{ 0x02, 0x80 }, /* red gain */
{ 0x03, 0xc0 }, /* OV7670_R03_VREF */
{ 0x06, 0x60 },
{ 0x07, 0x00 },
{ 0x0c, 0x24 },
{ 0x0c, 0x24 },
{ 0x0d, 0x24 },
{ 0x11, 0x01 },
{ 0x12, 0x24 },
{ 0x13, 0x01 },
{ 0x14, 0x84 },
{ 0x15, 0x01 },
{ 0x16, 0x03 },
{ 0x17, 0x2f },
{ 0x18, 0xcf },
{ 0x19, 0x06 },
{ 0x1a, 0xf5 },
{ 0x1b, 0x00 },
{ 0x20, 0x18 },
{ 0x21, 0x80 },
{ 0x22, 0x80 },
{ 0x23, 0x00 },
{ 0x26, 0xa2 },
{ 0x27, 0xea },
{ 0x28, 0x22 }, /* Was 0x20, bit1 enables a 2x gain which we need */
{ 0x29, 0x00 },
{ 0x2a, 0x10 },
{ 0x2b, 0x00 },
{ 0x2c, 0x88 },
{ 0x2d, 0x91 },
{ 0x2e, 0x80 },
{ 0x2f, 0x44 },
{ 0x60, 0x27 },
{ 0x61, 0x02 },
{ 0x62, 0x5f },
{ 0x63, 0xd5 },
{ 0x64, 0x57 },
{ 0x65, 0x83 },
{ 0x66, 0x55 },
{ 0x67, 0x92 },
{ 0x68, 0xcf },
{ 0x69, 0x76 },
{ 0x6a, 0x22 },
{ 0x6b, 0x00 },
{ 0x6c, 0x02 },
{ 0x6d, 0x44 },
{ 0x6e, 0x80 },
{ 0x6f, 0x1d },
{ 0x70, 0x8b },
{ 0x71, 0x00 },
{ 0x72, 0x14 },
{ 0x73, 0x54 },
{ 0x74, 0x00 },
{ 0x75, 0x8e },
{ 0x76, 0x00 },
{ 0x77, 0xff },
{ 0x78, 0x80 },
{ 0x79, 0x80 },
{ 0x7a, 0x80 },
{ 0x7b, 0xe2 },
{ 0x7c, 0x00 },
};
/* 7640 and 7648. The defaults should be OK for most registers. */
static const struct ov_i2c_regvals norm_7640[] = {
{ 0x12, 0x80 },
{ 0x12, 0x14 },
};
static const struct ov_regvals init_519_ov7660[] = {
{ 0x5d, 0x03 }, /* Turn off suspend mode */
{ 0x53, 0x9b }, /* 0x9f enables the (unused) microcontroller */
{ 0x54, 0x0f }, /* bit2 (jpeg enable) */
{ 0xa2, 0x20 }, /* a2-a5 are undocumented */
{ 0xa3, 0x18 },
{ 0xa4, 0x04 },
{ 0xa5, 0x28 },
{ 0x37, 0x00 }, /* SetUsbInit */
{ 0x55, 0x02 }, /* 4.096 Mhz audio clock */
/* Enable both fields, YUV Input, disable defect comp (why?) */
{ 0x20, 0x0c }, /* 0x0d does U <-> V swap */
{ 0x21, 0x38 },
{ 0x22, 0x1d },
{ 0x17, 0x50 }, /* undocumented */
{ 0x37, 0x00 }, /* undocumented */
{ 0x40, 0xff }, /* I2C timeout counter */
{ 0x46, 0x00 }, /* I2C clock prescaler */
};
static const struct ov_i2c_regvals norm_7660[] = {
{OV7670_R12_COM7, OV7670_COM7_RESET},
{OV7670_R11_CLKRC, 0x81},
{0x92, 0x00}, /* DM_LNL */
{0x93, 0x00}, /* DM_LNH */
{0x9d, 0x4c}, /* BD50ST */
{0x9e, 0x3f}, /* BD60ST */
{OV7670_R3B_COM11, 0x02},
{OV7670_R13_COM8, 0xf5},
{OV7670_R10_AECH, 0x00},
{OV7670_R00_GAIN, 0x00},
{OV7670_R01_BLUE, 0x7c},
{OV7670_R02_RED, 0x9d},
{OV7670_R12_COM7, 0x00},
{OV7670_R04_COM1, 00},
{OV7670_R18_HSTOP, 0x01},
{OV7670_R17_HSTART, 0x13},
{OV7670_R32_HREF, 0x92},
{OV7670_R19_VSTART, 0x02},
{OV7670_R1A_VSTOP, 0x7a},
{OV7670_R03_VREF, 0x00},
{OV7670_R0E_COM5, 0x04},
{OV7670_R0F_COM6, 0x62},
{OV7670_R15_COM10, 0x00},
{0x16, 0x02}, /* RSVD */
{0x1b, 0x00}, /* PSHFT */
{OV7670_R1E_MVFP, 0x01},
{0x29, 0x3c}, /* RSVD */
{0x33, 0x00}, /* CHLF */
{0x34, 0x07}, /* ARBLM */
{0x35, 0x84}, /* RSVD */
{0x36, 0x00}, /* RSVD */
{0x37, 0x04}, /* ADC */
{0x39, 0x43}, /* OFON */
{OV7670_R3A_TSLB, 0x00},
{OV7670_R3C_COM12, 0x6c},
{OV7670_R3D_COM13, 0x98},
{OV7670_R3F_EDGE, 0x23},
{OV7670_R40_COM15, 0xc1},
{OV7670_R41_COM16, 0x22},
{0x6b, 0x0a}, /* DBLV */
{0xa1, 0x08}, /* RSVD */
{0x69, 0x80}, /* HV */
{0x43, 0xf0}, /* RSVD.. */
{0x44, 0x10},
{0x45, 0x78},
{0x46, 0xa8},
{0x47, 0x60},
{0x48, 0x80},
{0x59, 0xba},
{0x5a, 0x9a},
{0x5b, 0x22},
{0x5c, 0xb9},
{0x5d, 0x9b},
{0x5e, 0x10},
{0x5f, 0xe0},
{0x60, 0x85},
{0x61, 0x60},
{0x9f, 0x9d}, /* RSVD */
{0xa0, 0xa0}, /* DSPC2 */
{0x4f, 0x60}, /* matrix */
{0x50, 0x64},
{0x51, 0x04},
{0x52, 0x18},
{0x53, 0x3c},
{0x54, 0x54},
{0x55, 0x40},
{0x56, 0x40},
{0x57, 0x40},
{0x58, 0x0d}, /* matrix sign */
{0x8b, 0xcc}, /* RSVD */
{0x8c, 0xcc},
{0x8d, 0xcf},
{0x6c, 0x40}, /* gamma curve */
{0x6d, 0xe0},
{0x6e, 0xa0},
{0x6f, 0x80},
{0x70, 0x70},
{0x71, 0x80},
{0x72, 0x60},
{0x73, 0x60},
{0x74, 0x50},
{0x75, 0x40},
{0x76, 0x38},
{0x77, 0x3c},
{0x78, 0x32},
{0x79, 0x1a},
{0x7a, 0x28},
{0x7b, 0x24},
{0x7c, 0x04}, /* gamma curve */
{0x7d, 0x12},
{0x7e, 0x26},
{0x7f, 0x46},
{0x80, 0x54},
{0x81, 0x64},
{0x82, 0x70},
{0x83, 0x7c},
{0x84, 0x86},
{0x85, 0x8e},
{0x86, 0x9c},
{0x87, 0xab},
{0x88, 0xc4},
{0x89, 0xd1},
{0x8a, 0xe5},
{OV7670_R14_COM9, 0x1e},
{OV7670_R24_AEW, 0x80},
{OV7670_R25_AEB, 0x72},
{OV7670_R26_VPT, 0xb3},
{0x62, 0x80}, /* LCC1 */
{0x63, 0x80}, /* LCC2 */
{0x64, 0x06}, /* LCC3 */
{0x65, 0x00}, /* LCC4 */
{0x66, 0x01}, /* LCC5 */
{0x94, 0x0e}, /* RSVD.. */
{0x95, 0x14},
{OV7670_R13_COM8, OV7670_COM8_FASTAEC
| OV7670_COM8_AECSTEP
| OV7670_COM8_BFILT
| 0x10
| OV7670_COM8_AGC
| OV7670_COM8_AWB
| OV7670_COM8_AEC},
{0xa1, 0xc8}
};
static const struct ov_i2c_regvals norm_9600[] = {
{0x12, 0x80},
{0x0c, 0x28},
{0x11, 0x80},
{0x13, 0xb5},
{0x14, 0x3e},
{0x1b, 0x04},
{0x24, 0xb0},
{0x25, 0x90},
{0x26, 0x94},
{0x35, 0x90},
{0x37, 0x07},
{0x38, 0x08},
{0x01, 0x8e},
{0x02, 0x85}
};
/* 7670. Defaults taken from OmniVision provided data,
* as provided by Jonathan Corbet of OLPC */
static const struct ov_i2c_regvals norm_7670[] = {
{ OV7670_R12_COM7, OV7670_COM7_RESET },
{ OV7670_R3A_TSLB, 0x04 }, /* OV */
{ OV7670_R12_COM7, OV7670_COM7_FMT_VGA }, /* VGA */
{ OV7670_R11_CLKRC, 0x01 },
/*
* Set the hardware window. These values from OV don't entirely
* make sense - hstop is less than hstart. But they work...
*/
{ OV7670_R17_HSTART, 0x13 },
{ OV7670_R18_HSTOP, 0x01 },
{ OV7670_R32_HREF, 0xb6 },
{ OV7670_R19_VSTART, 0x02 },
{ OV7670_R1A_VSTOP, 0x7a },
{ OV7670_R03_VREF, 0x0a },
{ OV7670_R0C_COM3, 0x00 },
{ OV7670_R3E_COM14, 0x00 },
/* Mystery scaling numbers */
{ 0x70, 0x3a },
{ 0x71, 0x35 },
{ 0x72, 0x11 },
{ 0x73, 0xf0 },
{ 0xa2, 0x02 },
/* { OV7670_R15_COM10, 0x0 }, */
/* Gamma curve values */
{ 0x7a, 0x20 },
{ 0x7b, 0x10 },
{ 0x7c, 0x1e },
{ 0x7d, 0x35 },
{ 0x7e, 0x5a },
{ 0x7f, 0x69 },
{ 0x80, 0x76 },
{ 0x81, 0x80 },
{ 0x82, 0x88 },
{ 0x83, 0x8f },
{ 0x84, 0x96 },
{ 0x85, 0xa3 },
{ 0x86, 0xaf },
{ 0x87, 0xc4 },
{ 0x88, 0xd7 },
{ 0x89, 0xe8 },
/* AGC and AEC parameters. Note we start by disabling those features,
then turn them only after tweaking the values. */
{ OV7670_R13_COM8, OV7670_COM8_FASTAEC
| OV7670_COM8_AECSTEP
| OV7670_COM8_BFILT },
{ OV7670_R00_GAIN, 0x00 },
{ OV7670_R10_AECH, 0x00 },
{ OV7670_R0D_COM4, 0x40 }, /* magic reserved bit */
{ OV7670_R14_COM9, 0x18 }, /* 4x gain + magic rsvd bit */
{ OV7670_RA5_BD50MAX, 0x05 },
{ OV7670_RAB_BD60MAX, 0x07 },
{ OV7670_R24_AEW, 0x95 },
{ OV7670_R25_AEB, 0x33 },
{ OV7670_R26_VPT, 0xe3 },
{ OV7670_R9F_HAECC1, 0x78 },
{ OV7670_RA0_HAECC2, 0x68 },
{ 0xa1, 0x03 }, /* magic */
{ OV7670_RA6_HAECC3, 0xd8 },
{ OV7670_RA7_HAECC4, 0xd8 },
{ OV7670_RA8_HAECC5, 0xf0 },
{ OV7670_RA9_HAECC6, 0x90 },
{ OV7670_RAA_HAECC7, 0x94 },
{ OV7670_R13_COM8, OV7670_COM8_FASTAEC
| OV7670_COM8_AECSTEP
| OV7670_COM8_BFILT
| OV7670_COM8_AGC
| OV7670_COM8_AEC },
/* Almost all of these are magic "reserved" values. */
{ OV7670_R0E_COM5, 0x61 },
{ OV7670_R0F_COM6, 0x4b },
{ 0x16, 0x02 },
{ OV7670_R1E_MVFP, 0x07 },
{ 0x21, 0x02 },
{ 0x22, 0x91 },
{ 0x29, 0x07 },
{ 0x33, 0x0b },
{ 0x35, 0x0b },
{ 0x37, 0x1d },
{ 0x38, 0x71 },
{ 0x39, 0x2a },
{ OV7670_R3C_COM12, 0x78 },
{ 0x4d, 0x40 },
{ 0x4e, 0x20 },
{ OV7670_R69_GFIX, 0x00 },
{ 0x6b, 0x4a },
{ 0x74, 0x10 },
{ 0x8d, 0x4f },
{ 0x8e, 0x00 },
{ 0x8f, 0x00 },
{ 0x90, 0x00 },
{ 0x91, 0x00 },
{ 0x96, 0x00 },
{ 0x9a, 0x00 },
{ 0xb0, 0x84 },
{ 0xb1, 0x0c },
{ 0xb2, 0x0e },
{ 0xb3, 0x82 },
{ 0xb8, 0x0a },
/* More reserved magic, some of which tweaks white balance */
{ 0x43, 0x0a },
{ 0x44, 0xf0 },
{ 0x45, 0x34 },
{ 0x46, 0x58 },
{ 0x47, 0x28 },
{ 0x48, 0x3a },
{ 0x59, 0x88 },
{ 0x5a, 0x88 },
{ 0x5b, 0x44 },
{ 0x5c, 0x67 },
{ 0x5d, 0x49 },
{ 0x5e, 0x0e },
{ 0x6c, 0x0a },
{ 0x6d, 0x55 },
{ 0x6e, 0x11 },
{ 0x6f, 0x9f }, /* "9e for advance AWB" */
{ 0x6a, 0x40 },
{ OV7670_R01_BLUE, 0x40 },
{ OV7670_R02_RED, 0x60 },
{ OV7670_R13_COM8, OV7670_COM8_FASTAEC
| OV7670_COM8_AECSTEP
| OV7670_COM8_BFILT
| OV7670_COM8_AGC
| OV7670_COM8_AEC
| OV7670_COM8_AWB },
/* Matrix coefficients */
{ 0x4f, 0x80 },
{ 0x50, 0x80 },
{ 0x51, 0x00 },
{ 0x52, 0x22 },
{ 0x53, 0x5e },
{ 0x54, 0x80 },
{ 0x58, 0x9e },
{ OV7670_R41_COM16, OV7670_COM16_AWBGAIN },
{ OV7670_R3F_EDGE, 0x00 },
{ 0x75, 0x05 },
{ 0x76, 0xe1 },
{ 0x4c, 0x00 },
{ 0x77, 0x01 },
{ OV7670_R3D_COM13, OV7670_COM13_GAMMA
| OV7670_COM13_UVSAT
| 2}, /* was 3 */
{ 0x4b, 0x09 },
{ 0xc9, 0x60 },
{ OV7670_R41_COM16, 0x38 },
{ 0x56, 0x40 },
{ 0x34, 0x11 },
{ OV7670_R3B_COM11, OV7670_COM11_EXP|OV7670_COM11_HZAUTO },
{ 0xa4, 0x88 },
{ 0x96, 0x00 },
{ 0x97, 0x30 },
{ 0x98, 0x20 },
{ 0x99, 0x30 },
{ 0x9a, 0x84 },
{ 0x9b, 0x29 },
{ 0x9c, 0x03 },
{ 0x9d, 0x4c },
{ 0x9e, 0x3f },
{ 0x78, 0x04 },
/* Extra-weird stuff. Some sort of multiplexor register */
{ 0x79, 0x01 },
{ 0xc8, 0xf0 },
{ 0x79, 0x0f },
{ 0xc8, 0x00 },
{ 0x79, 0x10 },
{ 0xc8, 0x7e },
{ 0x79, 0x0a },
{ 0xc8, 0x80 },
{ 0x79, 0x0b },
{ 0xc8, 0x01 },
{ 0x79, 0x0c },
{ 0xc8, 0x0f },
{ 0x79, 0x0d },
{ 0xc8, 0x20 },
{ 0x79, 0x09 },
{ 0xc8, 0x80 },
{ 0x79, 0x02 },
{ 0xc8, 0xc0 },
{ 0x79, 0x03 },
{ 0xc8, 0x40 },
{ 0x79, 0x05 },
{ 0xc8, 0x30 },
{ 0x79, 0x26 },
};
static const struct ov_i2c_regvals norm_8610[] = {
{ 0x12, 0x80 },
{ 0x00, 0x00 },
{ 0x01, 0x80 },
{ 0x02, 0x80 },
{ 0x03, 0xc0 },
{ 0x04, 0x30 },
{ 0x05, 0x30 }, /* was 0x10, new from windrv 090403 */
{ 0x06, 0x70 }, /* was 0x80, new from windrv 090403 */
{ 0x0a, 0x86 },
{ 0x0b, 0xb0 },
{ 0x0c, 0x20 },
{ 0x0d, 0x20 },
{ 0x11, 0x01 },
{ 0x12, 0x25 },
{ 0x13, 0x01 },
{ 0x14, 0x04 },
{ 0x15, 0x01 }, /* Lin and Win think different about UV order */
{ 0x16, 0x03 },
{ 0x17, 0x38 }, /* was 0x2f, new from windrv 090403 */
{ 0x18, 0xea }, /* was 0xcf, new from windrv 090403 */
{ 0x19, 0x02 }, /* was 0x06, new from windrv 090403 */
{ 0x1a, 0xf5 },
{ 0x1b, 0x00 },
{ 0x20, 0xd0 }, /* was 0x90, new from windrv 090403 */
{ 0x23, 0xc0 }, /* was 0x00, new from windrv 090403 */
{ 0x24, 0x30 }, /* was 0x1d, new from windrv 090403 */
{ 0x25, 0x50 }, /* was 0x57, new from windrv 090403 */
{ 0x26, 0xa2 },
{ 0x27, 0xea },
{ 0x28, 0x00 },
{ 0x29, 0x00 },
{ 0x2a, 0x80 },
{ 0x2b, 0xc8 }, /* was 0xcc, new from windrv 090403 */
{ 0x2c, 0xac },
{ 0x2d, 0x45 }, /* was 0xd5, new from windrv 090403 */
{ 0x2e, 0x80 },
{ 0x2f, 0x14 }, /* was 0x01, new from windrv 090403 */
{ 0x4c, 0x00 },
{ 0x4d, 0x30 }, /* was 0x10, new from windrv 090403 */
{ 0x60, 0x02 }, /* was 0x01, new from windrv 090403 */
{ 0x61, 0x00 }, /* was 0x09, new from windrv 090403 */
{ 0x62, 0x5f }, /* was 0xd7, new from windrv 090403 */
{ 0x63, 0xff },
{ 0x64, 0x53 }, /* new windrv 090403 says 0x57,
* maybe that's wrong */
{ 0x65, 0x00 },
{ 0x66, 0x55 },
{ 0x67, 0xb0 },
{ 0x68, 0xc0 }, /* was 0xaf, new from windrv 090403 */
{ 0x69, 0x02 },
{ 0x6a, 0x22 },
{ 0x6b, 0x00 },
{ 0x6c, 0x99 }, /* was 0x80, old windrv says 0x00, but
* deleting bit7 colors the first images red */
{ 0x6d, 0x11 }, /* was 0x00, new from windrv 090403 */
{ 0x6e, 0x11 }, /* was 0x00, new from windrv 090403 */
{ 0x6f, 0x01 },
{ 0x70, 0x8b },
{ 0x71, 0x00 },
{ 0x72, 0x14 },
{ 0x73, 0x54 },
{ 0x74, 0x00 },/* 0x60? - was 0x00, new from windrv 090403 */
{ 0x75, 0x0e },
{ 0x76, 0x02 }, /* was 0x02, new from windrv 090403 */
{ 0x77, 0xff },
{ 0x78, 0x80 },
{ 0x79, 0x80 },
{ 0x7a, 0x80 },
{ 0x7b, 0x10 }, /* was 0x13, new from windrv 090403 */
{ 0x7c, 0x00 },
{ 0x7d, 0x08 }, /* was 0x09, new from windrv 090403 */
{ 0x7e, 0x08 }, /* was 0xc0, new from windrv 090403 */
{ 0x7f, 0xfb },
{ 0x80, 0x28 },
{ 0x81, 0x00 },
{ 0x82, 0x23 },
{ 0x83, 0x0b },
{ 0x84, 0x00 },
{ 0x85, 0x62 }, /* was 0x61, new from windrv 090403 */
{ 0x86, 0xc9 },
{ 0x87, 0x00 },
{ 0x88, 0x00 },
{ 0x89, 0x01 },
{ 0x12, 0x20 },
{ 0x12, 0x25 }, /* was 0x24, new from windrv 090403 */
};
static unsigned char ov7670_abs_to_sm(unsigned char v)
{
if (v > 127)
return v & 0x7f;
return (128 - v) | 0x80;
}
/* Write a OV519 register */
static void reg_w(struct sd *sd, u16 index, u16 value)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int ret, req = 0;
if (sd->gspca_dev.usb_err < 0)
return;
/* Avoid things going to fast for the bridge with a xhci host */
udelay(150);
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
req = 2;
break;
case BRIDGE_OVFX2:
req = 0x0a;
/* fall through */
case BRIDGE_W9968CF:
gspca_dbg(gspca_dev, D_USBO, "SET %02x %04x %04x\n",
req, value, index);
ret = usb_control_msg(sd->gspca_dev.dev,
usb_sndctrlpipe(sd->gspca_dev.dev, 0),
req,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, NULL, 0, 500);
goto leave;
default:
req = 1;
}
gspca_dbg(gspca_dev, D_USBO, "SET %02x 0000 %04x %02x\n",
req, index, value);
sd->gspca_dev.usb_buf[0] = value;
ret = usb_control_msg(sd->gspca_dev.dev,
usb_sndctrlpipe(sd->gspca_dev.dev, 0),
req,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index,
sd->gspca_dev.usb_buf, 1, 500);
leave:
if (ret < 0) {
gspca_err(gspca_dev, "reg_w %02x failed %d\n", index, ret);
sd->gspca_dev.usb_err = ret;
return;
}
}
/* Read from a OV519 register, note not valid for the w9968cf!! */
/* returns: negative is error, pos or zero is data */
static int reg_r(struct sd *sd, u16 index)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int ret;
int req;
if (sd->gspca_dev.usb_err < 0)
return -1;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
req = 3;
break;
case BRIDGE_OVFX2:
req = 0x0b;
break;
default:
req = 1;
}
/* Avoid things going to fast for the bridge with a xhci host */
udelay(150);
ret = usb_control_msg(sd->gspca_dev.dev,
usb_rcvctrlpipe(sd->gspca_dev.dev, 0),
req,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, sd->gspca_dev.usb_buf, 1, 500);
if (ret >= 0) {
ret = sd->gspca_dev.usb_buf[0];
gspca_dbg(gspca_dev, D_USBI, "GET %02x 0000 %04x %02x\n",
req, index, ret);
} else {
gspca_err(gspca_dev, "reg_r %02x failed %d\n", index, ret);
sd->gspca_dev.usb_err = ret;
/*
* Make sure the result is zeroed to avoid uninitialized
* values.
*/
gspca_dev->usb_buf[0] = 0;
}
return ret;
}
/* Read 8 values from a OV519 register */
static int reg_r8(struct sd *sd,
u16 index)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int ret;
if (sd->gspca_dev.usb_err < 0)
return -1;
/* Avoid things going to fast for the bridge with a xhci host */
udelay(150);
ret = usb_control_msg(sd->gspca_dev.dev,
usb_rcvctrlpipe(sd->gspca_dev.dev, 0),
1, /* REQ_IO */
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, sd->gspca_dev.usb_buf, 8, 500);
if (ret >= 0) {
ret = sd->gspca_dev.usb_buf[0];
} else {
gspca_err(gspca_dev, "reg_r8 %02x failed %d\n", index, ret);
sd->gspca_dev.usb_err = ret;
/*
* Make sure the buffer is zeroed to avoid uninitialized
* values.
*/
memset(gspca_dev->usb_buf, 0, 8);
}
return ret;
}
/*
* Writes bits at positions specified by mask to an OV51x reg. Bits that are in
* the same position as 1's in "mask" are cleared and set to "value". Bits
* that are in the same position as 0's in "mask" are preserved, regardless
* of their respective state in "value".
*/
static void reg_w_mask(struct sd *sd,
u16 index,
u8 value,
u8 mask)
{
int ret;
u8 oldval;
if (mask != 0xff) {
value &= mask; /* Enforce mask on value */
ret = reg_r(sd, index);
if (ret < 0)
return;
oldval = ret & ~mask; /* Clear the masked bits */
value |= oldval; /* Set the desired bits */
}
reg_w(sd, index, value);
}
/*
* Writes multiple (n) byte value to a single register. Only valid with certain
* registers (0x30 and 0xc4 - 0xce).
*/
static void ov518_reg_w32(struct sd *sd, u16 index, u32 value, int n)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int ret;
if (sd->gspca_dev.usb_err < 0)
return;
*((__le32 *) sd->gspca_dev.usb_buf) = __cpu_to_le32(value);
/* Avoid things going to fast for the bridge with a xhci host */
udelay(150);
ret = usb_control_msg(sd->gspca_dev.dev,
usb_sndctrlpipe(sd->gspca_dev.dev, 0),
1 /* REG_IO */,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index,
sd->gspca_dev.usb_buf, n, 500);
if (ret < 0) {
gspca_err(gspca_dev, "reg_w32 %02x failed %d\n", index, ret);
sd->gspca_dev.usb_err = ret;
}
}
static void ov511_i2c_w(struct sd *sd, u8 reg, u8 value)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int rc, retries;
gspca_dbg(gspca_dev, D_USBO, "ov511_i2c_w %02x %02x\n", reg, value);
/* Three byte write cycle */
for (retries = 6; ; ) {
/* Select camera register */
reg_w(sd, R51x_I2C_SADDR_3, reg);
/* Write "value" to I2C data port of OV511 */
reg_w(sd, R51x_I2C_DATA, value);
/* Initiate 3-byte write cycle */
reg_w(sd, R511_I2C_CTL, 0x01);
do {
rc = reg_r(sd, R511_I2C_CTL);
} while (rc > 0 && ((rc & 1) == 0)); /* Retry until idle */
if (rc < 0)
return;
if ((rc & 2) == 0) /* Ack? */
break;
if (--retries < 0) {
gspca_dbg(gspca_dev, D_USBO, "i2c write retries exhausted\n");
return;
}
}
}
static int ov511_i2c_r(struct sd *sd, u8 reg)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int rc, value, retries;
/* Two byte write cycle */
for (retries = 6; ; ) {
/* Select camera register */
reg_w(sd, R51x_I2C_SADDR_2, reg);
/* Initiate 2-byte write cycle */
reg_w(sd, R511_I2C_CTL, 0x03);
do {
rc = reg_r(sd, R511_I2C_CTL);
} while (rc > 0 && ((rc & 1) == 0)); /* Retry until idle */
if (rc < 0)
return rc;
if ((rc & 2) == 0) /* Ack? */
break;
/* I2C abort */
reg_w(sd, R511_I2C_CTL, 0x10);
if (--retries < 0) {
gspca_dbg(gspca_dev, D_USBI, "i2c write retries exhausted\n");
return -1;
}
}
/* Two byte read cycle */
for (retries = 6; ; ) {
/* Initiate 2-byte read cycle */
reg_w(sd, R511_I2C_CTL, 0x05);
do {
rc = reg_r(sd, R511_I2C_CTL);
} while (rc > 0 && ((rc & 1) == 0)); /* Retry until idle */
if (rc < 0)
return rc;
if ((rc & 2) == 0) /* Ack? */
break;
/* I2C abort */
reg_w(sd, R511_I2C_CTL, 0x10);
if (--retries < 0) {
gspca_dbg(gspca_dev, D_USBI, "i2c read retries exhausted\n");
return -1;
}
}
value = reg_r(sd, R51x_I2C_DATA);
gspca_dbg(gspca_dev, D_USBI, "ov511_i2c_r %02x %02x\n", reg, value);
/* This is needed to make i2c_w() work */
reg_w(sd, R511_I2C_CTL, 0x05);
return value;
}
/*
* The OV518 I2C I/O procedure is different, hence, this function.
* This is normally only called from i2c_w(). Note that this function
* always succeeds regardless of whether the sensor is present and working.
*/
static void ov518_i2c_w(struct sd *sd,
u8 reg,
u8 value)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
gspca_dbg(gspca_dev, D_USBO, "ov518_i2c_w %02x %02x\n", reg, value);
/* Select camera register */
reg_w(sd, R51x_I2C_SADDR_3, reg);
/* Write "value" to I2C data port of OV511 */
reg_w(sd, R51x_I2C_DATA, value);
/* Initiate 3-byte write cycle */
reg_w(sd, R518_I2C_CTL, 0x01);
/* wait for write complete */
msleep(4);
reg_r8(sd, R518_I2C_CTL);
}
/*
* returns: negative is error, pos or zero is data
*
* The OV518 I2C I/O procedure is different, hence, this function.
* This is normally only called from i2c_r(). Note that this function
* always succeeds regardless of whether the sensor is present and working.
*/
static int ov518_i2c_r(struct sd *sd, u8 reg)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int value;
/* Select camera register */
reg_w(sd, R51x_I2C_SADDR_2, reg);
/* Initiate 2-byte write cycle */
reg_w(sd, R518_I2C_CTL, 0x03);
reg_r8(sd, R518_I2C_CTL);
/* Initiate 2-byte read cycle */
reg_w(sd, R518_I2C_CTL, 0x05);
reg_r8(sd, R518_I2C_CTL);
value = reg_r(sd, R51x_I2C_DATA);
gspca_dbg(gspca_dev, D_USBI, "ov518_i2c_r %02x %02x\n", reg, value);
return value;
}
static void ovfx2_i2c_w(struct sd *sd, u8 reg, u8 value)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int ret;
if (sd->gspca_dev.usb_err < 0)
return;
ret = usb_control_msg(sd->gspca_dev.dev,
usb_sndctrlpipe(sd->gspca_dev.dev, 0),
0x02,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
(u16) value, (u16) reg, NULL, 0, 500);
if (ret < 0) {
gspca_err(gspca_dev, "ovfx2_i2c_w %02x failed %d\n", reg, ret);
sd->gspca_dev.usb_err = ret;
}
gspca_dbg(gspca_dev, D_USBO, "ovfx2_i2c_w %02x %02x\n", reg, value);
}
static int ovfx2_i2c_r(struct sd *sd, u8 reg)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int ret;
if (sd->gspca_dev.usb_err < 0)
return -1;
ret = usb_control_msg(sd->gspca_dev.dev,
usb_rcvctrlpipe(sd->gspca_dev.dev, 0),
0x03,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, (u16) reg, sd->gspca_dev.usb_buf, 1, 500);
if (ret >= 0) {
ret = sd->gspca_dev.usb_buf[0];
gspca_dbg(gspca_dev, D_USBI, "ovfx2_i2c_r %02x %02x\n",
reg, ret);
} else {
gspca_err(gspca_dev, "ovfx2_i2c_r %02x failed %d\n", reg, ret);
sd->gspca_dev.usb_err = ret;
}
return ret;
}
static void i2c_w(struct sd *sd, u8 reg, u8 value)
{
if (sd->sensor_reg_cache[reg] == value)
return;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
ov511_i2c_w(sd, reg, value);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
case BRIDGE_OV519:
ov518_i2c_w(sd, reg, value);
break;
case BRIDGE_OVFX2:
ovfx2_i2c_w(sd, reg, value);
break;
case BRIDGE_W9968CF:
w9968cf_i2c_w(sd, reg, value);
break;
}
if (sd->gspca_dev.usb_err >= 0) {
/* Up on sensor reset empty the register cache */
if (reg == 0x12 && (value & 0x80))
memset(sd->sensor_reg_cache, -1,
sizeof(sd->sensor_reg_cache));
else
sd->sensor_reg_cache[reg] = value;
}
}
static int i2c_r(struct sd *sd, u8 reg)
{
int ret = -1;
if (sd->sensor_reg_cache[reg] != -1)
return sd->sensor_reg_cache[reg];
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
ret = ov511_i2c_r(sd, reg);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
case BRIDGE_OV519:
ret = ov518_i2c_r(sd, reg);
break;
case BRIDGE_OVFX2:
ret = ovfx2_i2c_r(sd, reg);
break;
case BRIDGE_W9968CF:
ret = w9968cf_i2c_r(sd, reg);
break;
}
if (ret >= 0)
sd->sensor_reg_cache[reg] = ret;
return ret;
}
/* Writes bits at positions specified by mask to an I2C reg. Bits that are in
* the same position as 1's in "mask" are cleared and set to "value". Bits
* that are in the same position as 0's in "mask" are preserved, regardless
* of their respective state in "value".
*/
static void i2c_w_mask(struct sd *sd,
u8 reg,
u8 value,
u8 mask)
{
int rc;
u8 oldval;
value &= mask; /* Enforce mask on value */
rc = i2c_r(sd, reg);
if (rc < 0)
return;
oldval = rc & ~mask; /* Clear the masked bits */
value |= oldval; /* Set the desired bits */
i2c_w(sd, reg, value);
}
/* Temporarily stops OV511 from functioning. Must do this before changing
* registers while the camera is streaming */
static inline void ov51x_stop(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
gspca_dbg(gspca_dev, D_STREAM, "stopping\n");
sd->stopped = 1;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
reg_w(sd, R51x_SYS_RESET, 0x3d);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
reg_w_mask(sd, R51x_SYS_RESET, 0x3a, 0x3a);
break;
case BRIDGE_OV519:
reg_w(sd, OV519_R51_RESET1, 0x0f);
reg_w(sd, OV519_R51_RESET1, 0x00);
reg_w(sd, 0x22, 0x00); /* FRAR */
break;
case BRIDGE_OVFX2:
reg_w_mask(sd, 0x0f, 0x00, 0x02);
break;
case BRIDGE_W9968CF:
reg_w(sd, 0x3c, 0x0a05); /* stop USB transfer */
break;
}
}
/* Restarts OV511 after ov511_stop() is called. Has no effect if it is not
* actually stopped (for performance). */
static inline void ov51x_restart(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
gspca_dbg(gspca_dev, D_STREAM, "restarting\n");
if (!sd->stopped)
return;
sd->stopped = 0;
/* Reinitialize the stream */
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
reg_w(sd, R51x_SYS_RESET, 0x00);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
reg_w(sd, 0x2f, 0x80);
reg_w(sd, R51x_SYS_RESET, 0x00);
break;
case BRIDGE_OV519:
reg_w(sd, OV519_R51_RESET1, 0x0f);
reg_w(sd, OV519_R51_RESET1, 0x00);
reg_w(sd, 0x22, 0x1d); /* FRAR */
break;
case BRIDGE_OVFX2:
reg_w_mask(sd, 0x0f, 0x02, 0x02);
break;
case BRIDGE_W9968CF:
reg_w(sd, 0x3c, 0x8a05); /* USB FIFO enable */
break;
}
}
static void ov51x_set_slave_ids(struct sd *sd, u8 slave);
/* This does an initial reset of an OmniVision sensor and ensures that I2C
* is synchronized. Returns <0 on failure.
*/
static int init_ov_sensor(struct sd *sd, u8 slave)
{
int i;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
ov51x_set_slave_ids(sd, slave);
/* Reset the sensor */
i2c_w(sd, 0x12, 0x80);
/* Wait for it to initialize */
msleep(150);
for (i = 0; i < i2c_detect_tries; i++) {
if (i2c_r(sd, OV7610_REG_ID_HIGH) == 0x7f &&
i2c_r(sd, OV7610_REG_ID_LOW) == 0xa2) {
gspca_dbg(gspca_dev, D_PROBE, "I2C synced in %d attempt(s)\n",
i);
return 0;
}
/* Reset the sensor */
i2c_w(sd, 0x12, 0x80);
/* Wait for it to initialize */
msleep(150);
/* Dummy read to sync I2C */
if (i2c_r(sd, 0x00) < 0)
return -1;
}
return -1;
}
/* Set the read and write slave IDs. The "slave" argument is the write slave,
* and the read slave will be set to (slave + 1).
* This should not be called from outside the i2c I/O functions.
* Sets I2C read and write slave IDs. Returns <0 for error
*/
static void ov51x_set_slave_ids(struct sd *sd,
u8 slave)
{
switch (sd->bridge) {
case BRIDGE_OVFX2:
reg_w(sd, OVFX2_I2C_ADDR, slave);
return;
case BRIDGE_W9968CF:
sd->sensor_addr = slave;
return;
}
reg_w(sd, R51x_I2C_W_SID, slave);
reg_w(sd, R51x_I2C_R_SID, slave + 1);
}
static void write_regvals(struct sd *sd,
const struct ov_regvals *regvals,
int n)
{
while (--n >= 0) {
reg_w(sd, regvals->reg, regvals->val);
regvals++;
}
}
static void write_i2c_regvals(struct sd *sd,
const struct ov_i2c_regvals *regvals,
int n)
{
while (--n >= 0) {
i2c_w(sd, regvals->reg, regvals->val);
regvals++;
}
}
/****************************************************************************
*
* OV511 and sensor configuration
*
***************************************************************************/
/* This initializes the OV2x10 / OV3610 / OV3620 / OV9600 */
static void ov_hires_configure(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int high, low;
if (sd->bridge != BRIDGE_OVFX2) {
gspca_err(gspca_dev, "error hires sensors only supported with ovfx2\n");
return;
}
gspca_dbg(gspca_dev, D_PROBE, "starting ov hires configuration\n");
/* Detect sensor (sub)type */
high = i2c_r(sd, 0x0a);
low = i2c_r(sd, 0x0b);
/* info("%x, %x", high, low); */
switch (high) {
case 0x96:
switch (low) {
case 0x40:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is a OV2610\n");
sd->sensor = SEN_OV2610;
return;
case 0x41:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is a OV2610AE\n");
sd->sensor = SEN_OV2610AE;
return;
case 0xb1:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is a OV9600\n");
sd->sensor = SEN_OV9600;
return;
}
break;
case 0x36:
if ((low & 0x0f) == 0x00) {
gspca_dbg(gspca_dev, D_PROBE, "Sensor is a OV3610\n");
sd->sensor = SEN_OV3610;
return;
}
break;
}
gspca_err(gspca_dev, "Error unknown sensor type: %02x%02x\n",
high, low);
}
/* This initializes the OV8110, OV8610 sensor. The OV8110 uses
* the same register settings as the OV8610, since they are very similar.
*/
static void ov8xx0_configure(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int rc;
gspca_dbg(gspca_dev, D_PROBE, "starting ov8xx0 configuration\n");
/* Detect sensor (sub)type */
rc = i2c_r(sd, OV7610_REG_COM_I);
if (rc < 0) {
gspca_err(gspca_dev, "Error detecting sensor type\n");
return;
}
if ((rc & 3) == 1)
sd->sensor = SEN_OV8610;
else
gspca_err(gspca_dev, "Unknown image sensor version: %d\n",
rc & 3);
}
/* This initializes the OV7610, OV7620, or OV76BE sensor. The OV76BE uses
* the same register settings as the OV7610, since they are very similar.
*/
static void ov7xx0_configure(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int rc, high, low;
gspca_dbg(gspca_dev, D_PROBE, "starting OV7xx0 configuration\n");
/* Detect sensor (sub)type */
rc = i2c_r(sd, OV7610_REG_COM_I);
/* add OV7670 here
* it appears to be wrongly detected as a 7610 by default */
if (rc < 0) {
gspca_err(gspca_dev, "Error detecting sensor type\n");
return;
}
if ((rc & 3) == 3) {
/* quick hack to make OV7670s work */
high = i2c_r(sd, 0x0a);
low = i2c_r(sd, 0x0b);
/* info("%x, %x", high, low); */
if (high == 0x76 && (low & 0xf0) == 0x70) {
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV76%02x\n",
low);
sd->sensor = SEN_OV7670;
} else {
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV7610\n");
sd->sensor = SEN_OV7610;
}
} else if ((rc & 3) == 1) {
/* I don't know what's different about the 76BE yet. */
if (i2c_r(sd, 0x15) & 1) {
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV7620AE\n");
sd->sensor = SEN_OV7620AE;
} else {
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV76BE\n");
sd->sensor = SEN_OV76BE;
}
} else if ((rc & 3) == 0) {
/* try to read product id registers */
high = i2c_r(sd, 0x0a);
if (high < 0) {
gspca_err(gspca_dev, "Error detecting camera chip PID\n");
return;
}
low = i2c_r(sd, 0x0b);
if (low < 0) {
gspca_err(gspca_dev, "Error detecting camera chip VER\n");
return;
}
if (high == 0x76) {
switch (low) {
case 0x30:
gspca_err(gspca_dev, "Sensor is an OV7630/OV7635\n");
gspca_err(gspca_dev, "7630 is not supported by this driver\n");
return;
case 0x40:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV7645\n");
sd->sensor = SEN_OV7640; /* FIXME */
break;
case 0x45:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV7645B\n");
sd->sensor = SEN_OV7640; /* FIXME */
break;
case 0x48:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV7648\n");
sd->sensor = SEN_OV7648;
break;
case 0x60:
gspca_dbg(gspca_dev, D_PROBE, "Sensor is a OV7660\n");
sd->sensor = SEN_OV7660;
break;
default:
gspca_err(gspca_dev, "Unknown sensor: 0x76%02x\n",
low);
return;
}
} else {
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV7620\n");
sd->sensor = SEN_OV7620;
}
} else {
gspca_err(gspca_dev, "Unknown image sensor version: %d\n",
rc & 3);
}
}
/* This initializes the OV6620, OV6630, OV6630AE, or OV6630AF sensor. */
static void ov6xx0_configure(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int rc;
gspca_dbg(gspca_dev, D_PROBE, "starting OV6xx0 configuration\n");
/* Detect sensor (sub)type */
rc = i2c_r(sd, OV7610_REG_COM_I);
if (rc < 0) {
gspca_err(gspca_dev, "Error detecting sensor type\n");
return;
}
/* Ugh. The first two bits are the version bits, but
* the entire register value must be used. I guess OVT
* underestimated how many variants they would make. */
switch (rc) {
case 0x00:
sd->sensor = SEN_OV6630;
pr_warn("WARNING: Sensor is an OV66308. Your camera may have been misdetected in previous driver versions.\n");
break;
case 0x01:
sd->sensor = SEN_OV6620;
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV6620\n");
break;
case 0x02:
sd->sensor = SEN_OV6630;
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV66308AE\n");
break;
case 0x03:
sd->sensor = SEN_OV66308AF;
gspca_dbg(gspca_dev, D_PROBE, "Sensor is an OV66308AF\n");
break;
case 0x90:
sd->sensor = SEN_OV6630;
pr_warn("WARNING: Sensor is an OV66307. Your camera may have been misdetected in previous driver versions.\n");
break;
default:
gspca_err(gspca_dev, "FATAL: Unknown sensor version: 0x%02x\n",
rc);
return;
}
/* Set sensor-specific vars */
sd->sif = 1;
}
/* Turns on or off the LED. Only has an effect with OV511+/OV518(+)/OV519 */
static void ov51x_led_control(struct sd *sd, int on)
{
if (sd->invert_led)
on = !on;
switch (sd->bridge) {
/* OV511 has no LED control */
case BRIDGE_OV511PLUS:
reg_w(sd, R511_SYS_LED_CTL, on);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
reg_w_mask(sd, R518_GPIO_OUT, 0x02 * on, 0x02);
break;
case BRIDGE_OV519:
reg_w_mask(sd, OV519_GPIO_DATA_OUT0, on, 1);
break;
}
}
static void sd_reset_snapshot(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (!sd->snapshot_needs_reset)
return;
/* Note it is important that we clear sd->snapshot_needs_reset,
before actually clearing the snapshot state in the bridge
otherwise we might race with the pkt_scan interrupt handler */
sd->snapshot_needs_reset = 0;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
reg_w(sd, R51x_SYS_SNAP, 0x02);
reg_w(sd, R51x_SYS_SNAP, 0x00);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
reg_w(sd, R51x_SYS_SNAP, 0x02); /* Reset */
reg_w(sd, R51x_SYS_SNAP, 0x01); /* Enable */
break;
case BRIDGE_OV519:
reg_w(sd, R51x_SYS_RESET, 0x40);
reg_w(sd, R51x_SYS_RESET, 0x00);
break;
}
}
static void ov51x_upload_quan_tables(struct sd *sd)
{
static const unsigned char yQuanTable511[] = {
0, 1, 1, 2, 2, 3, 3, 4,
1, 1, 1, 2, 2, 3, 4, 4,
1, 1, 2, 2, 3, 4, 4, 4,
2, 2, 2, 3, 4, 4, 4, 4,
2, 2, 3, 4, 4, 5, 5, 5,
3, 3, 4, 4, 5, 5, 5, 5,
3, 4, 4, 4, 5, 5, 5, 5,
4, 4, 4, 4, 5, 5, 5, 5
};
static const unsigned char uvQuanTable511[] = {
0, 2, 2, 3, 4, 4, 4, 4,
2, 2, 2, 4, 4, 4, 4, 4,
2, 2, 3, 4, 4, 4, 4, 4,
3, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4
};
/* OV518 quantization tables are 8x4 (instead of 8x8) */
static const unsigned char yQuanTable518[] = {
5, 4, 5, 6, 6, 7, 7, 7,
5, 5, 5, 5, 6, 7, 7, 7,
6, 6, 6, 6, 7, 7, 7, 8,
7, 7, 6, 7, 7, 7, 8, 8
};
static const unsigned char uvQuanTable518[] = {
6, 6, 6, 7, 7, 7, 7, 7,
6, 6, 6, 7, 7, 7, 7, 7,
6, 6, 6, 7, 7, 7, 7, 8,
7, 7, 7, 7, 7, 7, 8, 8
};
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
const unsigned char *pYTable, *pUVTable;
unsigned char val0, val1;
int i, size, reg = R51x_COMP_LUT_BEGIN;
gspca_dbg(gspca_dev, D_PROBE, "Uploading quantization tables\n");
if (sd->bridge == BRIDGE_OV511 || sd->bridge == BRIDGE_OV511PLUS) {
pYTable = yQuanTable511;
pUVTable = uvQuanTable511;
size = 32;
} else {
pYTable = yQuanTable518;
pUVTable = uvQuanTable518;
size = 16;
}
for (i = 0; i < size; i++) {
val0 = *pYTable++;
val1 = *pYTable++;
val0 &= 0x0f;
val1 &= 0x0f;
val0 |= val1 << 4;
reg_w(sd, reg, val0);
val0 = *pUVTable++;
val1 = *pUVTable++;
val0 &= 0x0f;
val1 &= 0x0f;
val0 |= val1 << 4;
reg_w(sd, reg + size, val0);
reg++;
}
}
/* This initializes the OV511/OV511+ and the sensor */
static void ov511_configure(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
/* For 511 and 511+ */
static const struct ov_regvals init_511[] = {
{ R51x_SYS_RESET, 0x7f },
{ R51x_SYS_INIT, 0x01 },
{ R51x_SYS_RESET, 0x7f },
{ R51x_SYS_INIT, 0x01 },
{ R51x_SYS_RESET, 0x3f },
{ R51x_SYS_INIT, 0x01 },
{ R51x_SYS_RESET, 0x3d },
};
static const struct ov_regvals norm_511[] = {
{ R511_DRAM_FLOW_CTL, 0x01 },
{ R51x_SYS_SNAP, 0x00 },
{ R51x_SYS_SNAP, 0x02 },
{ R51x_SYS_SNAP, 0x00 },
{ R511_FIFO_OPTS, 0x1f },
{ R511_COMP_EN, 0x00 },
{ R511_COMP_LUT_EN, 0x03 },
};
static const struct ov_regvals norm_511_p[] = {
{ R511_DRAM_FLOW_CTL, 0xff },
{ R51x_SYS_SNAP, 0x00 },
{ R51x_SYS_SNAP, 0x02 },
{ R51x_SYS_SNAP, 0x00 },
{ R511_FIFO_OPTS, 0xff },
{ R511_COMP_EN, 0x00 },
{ R511_COMP_LUT_EN, 0x03 },
};
static const struct ov_regvals compress_511[] = {
{ 0x70, 0x1f },
{ 0x71, 0x05 },
{ 0x72, 0x06 },
{ 0x73, 0x06 },
{ 0x74, 0x14 },
{ 0x75, 0x03 },
{ 0x76, 0x04 },
{ 0x77, 0x04 },
};
gspca_dbg(gspca_dev, D_PROBE, "Device custom id %x\n",
reg_r(sd, R51x_SYS_CUST_ID));
write_regvals(sd, init_511, ARRAY_SIZE(init_511));
switch (sd->bridge) {
case BRIDGE_OV511:
write_regvals(sd, norm_511, ARRAY_SIZE(norm_511));
break;
case BRIDGE_OV511PLUS:
write_regvals(sd, norm_511_p, ARRAY_SIZE(norm_511_p));
break;
}
/* Init compression */
write_regvals(sd, compress_511, ARRAY_SIZE(compress_511));
ov51x_upload_quan_tables(sd);
}
/* This initializes the OV518/OV518+ and the sensor */
static void ov518_configure(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
/* For 518 and 518+ */
static const struct ov_regvals init_518[] = {
{ R51x_SYS_RESET, 0x40 },
{ R51x_SYS_INIT, 0xe1 },
{ R51x_SYS_RESET, 0x3e },
{ R51x_SYS_INIT, 0xe1 },
{ R51x_SYS_RESET, 0x00 },
{ R51x_SYS_INIT, 0xe1 },
{ 0x46, 0x00 },
{ 0x5d, 0x03 },
};
static const struct ov_regvals norm_518[] = {
{ R51x_SYS_SNAP, 0x02 }, /* Reset */
{ R51x_SYS_SNAP, 0x01 }, /* Enable */
{ 0x31, 0x0f },
{ 0x5d, 0x03 },
{ 0x24, 0x9f },
{ 0x25, 0x90 },
{ 0x20, 0x00 },
{ 0x51, 0x04 },
{ 0x71, 0x19 },
{ 0x2f, 0x80 },
};
static const struct ov_regvals norm_518_p[] = {
{ R51x_SYS_SNAP, 0x02 }, /* Reset */
{ R51x_SYS_SNAP, 0x01 }, /* Enable */
{ 0x31, 0x0f },
{ 0x5d, 0x03 },
{ 0x24, 0x9f },
{ 0x25, 0x90 },
{ 0x20, 0x60 },
{ 0x51, 0x02 },
{ 0x71, 0x19 },
{ 0x40, 0xff },
{ 0x41, 0x42 },
{ 0x46, 0x00 },
{ 0x33, 0x04 },
{ 0x21, 0x19 },
{ 0x3f, 0x10 },
{ 0x2f, 0x80 },
};
/* First 5 bits of custom ID reg are a revision ID on OV518 */
sd->revision = reg_r(sd, R51x_SYS_CUST_ID) & 0x1f;
gspca_dbg(gspca_dev, D_PROBE, "Device revision %d\n", sd->revision);
write_regvals(sd, init_518, ARRAY_SIZE(init_518));
/* Set LED GPIO pin to output mode */
reg_w_mask(sd, R518_GPIO_CTL, 0x00, 0x02);
switch (sd->bridge) {
case BRIDGE_OV518:
write_regvals(sd, norm_518, ARRAY_SIZE(norm_518));
break;
case BRIDGE_OV518PLUS:
write_regvals(sd, norm_518_p, ARRAY_SIZE(norm_518_p));
break;
}
ov51x_upload_quan_tables(sd);
reg_w(sd, 0x2f, 0x80);
}
static void ov519_configure(struct sd *sd)
{
static const struct ov_regvals init_519[] = {
{ 0x5a, 0x6d }, /* EnableSystem */
{ 0x53, 0x9b }, /* don't enable the microcontroller */
{ OV519_R54_EN_CLK1, 0xff }, /* set bit2 to enable jpeg */
{ 0x5d, 0x03 },
{ 0x49, 0x01 },
{ 0x48, 0x00 },
/* Set LED pin to output mode. Bit 4 must be cleared or sensor
* detection will fail. This deserves further investigation. */
{ OV519_GPIO_IO_CTRL0, 0xee },
{ OV519_R51_RESET1, 0x0f },
{ OV519_R51_RESET1, 0x00 },
{ 0x22, 0x00 },
/* windows reads 0x55 at this point*/
};
write_regvals(sd, init_519, ARRAY_SIZE(init_519));
}
static void ovfx2_configure(struct sd *sd)
{
static const struct ov_regvals init_fx2[] = {
{ 0x00, 0x60 },
{ 0x02, 0x01 },
{ 0x0f, 0x1d },
{ 0xe9, 0x82 },
{ 0xea, 0xc7 },
{ 0xeb, 0x10 },
{ 0xec, 0xf6 },
};
sd->stopped = 1;
write_regvals(sd, init_fx2, ARRAY_SIZE(init_fx2));
}
/* set the mode */
/* This function works for ov7660 only */
static void ov519_set_mode(struct sd *sd)
{
static const struct ov_regvals bridge_ov7660[2][10] = {
{{0x10, 0x14}, {0x11, 0x1e}, {0x12, 0x00}, {0x13, 0x00},
{0x14, 0x00}, {0x15, 0x00}, {0x16, 0x00}, {0x20, 0x0c},
{0x25, 0x01}, {0x26, 0x00}},
{{0x10, 0x28}, {0x11, 0x3c}, {0x12, 0x00}, {0x13, 0x00},
{0x14, 0x00}, {0x15, 0x00}, {0x16, 0x00}, {0x20, 0x0c},
{0x25, 0x03}, {0x26, 0x00}}
};
static const struct ov_i2c_regvals sensor_ov7660[2][3] = {
{{0x12, 0x00}, {0x24, 0x00}, {0x0c, 0x0c}},
{{0x12, 0x00}, {0x04, 0x00}, {0x0c, 0x00}}
};
static const struct ov_i2c_regvals sensor_ov7660_2[] = {
{OV7670_R17_HSTART, 0x13},
{OV7670_R18_HSTOP, 0x01},
{OV7670_R32_HREF, 0x92},
{OV7670_R19_VSTART, 0x02},
{OV7670_R1A_VSTOP, 0x7a},
{OV7670_R03_VREF, 0x00},
/* {0x33, 0x00}, */
/* {0x34, 0x07}, */
/* {0x36, 0x00}, */
/* {0x6b, 0x0a}, */
};
write_regvals(sd, bridge_ov7660[sd->gspca_dev.curr_mode],
ARRAY_SIZE(bridge_ov7660[0]));
write_i2c_regvals(sd, sensor_ov7660[sd->gspca_dev.curr_mode],
ARRAY_SIZE(sensor_ov7660[0]));
write_i2c_regvals(sd, sensor_ov7660_2,
ARRAY_SIZE(sensor_ov7660_2));
}
/* set the frame rate */
/* This function works for sensors ov7640, ov7648 ov7660 and ov7670 only */
static void ov519_set_fr(struct sd *sd)
{
int fr;
u8 clock;
/* frame rate table with indices:
* - mode = 0: 320x240, 1: 640x480
* - fr rate = 0: 30, 1: 25, 2: 20, 3: 15, 4: 10, 5: 5
* - reg = 0: bridge a4, 1: bridge 23, 2: sensor 11 (clock)
*/
static const u8 fr_tb[2][6][3] = {
{{0x04, 0xff, 0x00},
{0x04, 0x1f, 0x00},
{0x04, 0x1b, 0x00},
{0x04, 0x15, 0x00},
{0x04, 0x09, 0x00},
{0x04, 0x01, 0x00}},
{{0x0c, 0xff, 0x00},
{0x0c, 0x1f, 0x00},
{0x0c, 0x1b, 0x00},
{0x04, 0xff, 0x01},
{0x04, 0x1f, 0x01},
{0x04, 0x1b, 0x01}},
};
if (frame_rate > 0)
sd->frame_rate = frame_rate;
if (sd->frame_rate >= 30)
fr = 0;
else if (sd->frame_rate >= 25)
fr = 1;
else if (sd->frame_rate >= 20)
fr = 2;
else if (sd->frame_rate >= 15)
fr = 3;
else if (sd->frame_rate >= 10)
fr = 4;
else
fr = 5;
reg_w(sd, 0xa4, fr_tb[sd->gspca_dev.curr_mode][fr][0]);
reg_w(sd, 0x23, fr_tb[sd->gspca_dev.curr_mode][fr][1]);
clock = fr_tb[sd->gspca_dev.curr_mode][fr][2];
if (sd->sensor == SEN_OV7660)
clock |= 0x80; /* enable double clock */
ov518_i2c_w(sd, OV7670_R11_CLKRC, clock);
}
static void setautogain(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w_mask(sd, 0x13, val ? 0x05 : 0x00, 0x05);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam = &gspca_dev->cam;
sd->bridge = id->driver_info & BRIDGE_MASK;
sd->invert_led = (id->driver_info & BRIDGE_INVERT_LED) != 0;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
cam->cam_mode = ov511_vga_mode;
cam->nmodes = ARRAY_SIZE(ov511_vga_mode);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
cam->cam_mode = ov518_vga_mode;
cam->nmodes = ARRAY_SIZE(ov518_vga_mode);
break;
case BRIDGE_OV519:
cam->cam_mode = ov519_vga_mode;
cam->nmodes = ARRAY_SIZE(ov519_vga_mode);
break;
case BRIDGE_OVFX2:
cam->cam_mode = ov519_vga_mode;
cam->nmodes = ARRAY_SIZE(ov519_vga_mode);
cam->bulk_size = OVFX2_BULK_SIZE;
cam->bulk_nurbs = MAX_NURBS;
cam->bulk = 1;
break;
case BRIDGE_W9968CF:
cam->cam_mode = w9968cf_vga_mode;
cam->nmodes = ARRAY_SIZE(w9968cf_vga_mode);
break;
}
sd->frame_rate = 15;
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam = &gspca_dev->cam;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
ov511_configure(gspca_dev);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
ov518_configure(gspca_dev);
break;
case BRIDGE_OV519:
ov519_configure(sd);
break;
case BRIDGE_OVFX2:
ovfx2_configure(sd);
break;
case BRIDGE_W9968CF:
w9968cf_configure(sd);
break;
}
/* The OV519 must be more aggressive about sensor detection since
* I2C write will never fail if the sensor is not present. We have
* to try to initialize the sensor to detect its presence */
sd->sensor = -1;
/* Test for 76xx */
if (init_ov_sensor(sd, OV7xx0_SID) >= 0) {
ov7xx0_configure(sd);
/* Test for 6xx0 */
} else if (init_ov_sensor(sd, OV6xx0_SID) >= 0) {
ov6xx0_configure(sd);
/* Test for 8xx0 */
} else if (init_ov_sensor(sd, OV8xx0_SID) >= 0) {
ov8xx0_configure(sd);
/* Test for 3xxx / 2xxx */
} else if (init_ov_sensor(sd, OV_HIRES_SID) >= 0) {
ov_hires_configure(sd);
} else {
gspca_err(gspca_dev, "Can't determine sensor slave IDs\n");
goto error;
}
if (sd->sensor < 0)
goto error;
ov51x_led_control(sd, 0); /* turn LED off */
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
if (sd->sif) {
cam->cam_mode = ov511_sif_mode;
cam->nmodes = ARRAY_SIZE(ov511_sif_mode);
}
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
if (sd->sif) {
cam->cam_mode = ov518_sif_mode;
cam->nmodes = ARRAY_SIZE(ov518_sif_mode);
}
break;
case BRIDGE_OV519:
if (sd->sif) {
cam->cam_mode = ov519_sif_mode;
cam->nmodes = ARRAY_SIZE(ov519_sif_mode);
}
break;
case BRIDGE_OVFX2:
switch (sd->sensor) {
case SEN_OV2610:
case SEN_OV2610AE:
cam->cam_mode = ovfx2_ov2610_mode;
cam->nmodes = ARRAY_SIZE(ovfx2_ov2610_mode);
break;
case SEN_OV3610:
cam->cam_mode = ovfx2_ov3610_mode;
cam->nmodes = ARRAY_SIZE(ovfx2_ov3610_mode);
break;
case SEN_OV9600:
cam->cam_mode = ovfx2_ov9600_mode;
cam->nmodes = ARRAY_SIZE(ovfx2_ov9600_mode);
break;
default:
if (sd->sif) {
cam->cam_mode = ov519_sif_mode;
cam->nmodes = ARRAY_SIZE(ov519_sif_mode);
}
break;
}
break;
case BRIDGE_W9968CF:
if (sd->sif)
cam->nmodes = ARRAY_SIZE(w9968cf_vga_mode) - 1;
/* w9968cf needs initialisation once the sensor is known */
w9968cf_init(sd);
break;
}
/* initialize the sensor */
switch (sd->sensor) {
case SEN_OV2610:
write_i2c_regvals(sd, norm_2610, ARRAY_SIZE(norm_2610));
/* Enable autogain, autoexpo, awb, bandfilter */
i2c_w_mask(sd, 0x13, 0x27, 0x27);
break;
case SEN_OV2610AE:
write_i2c_regvals(sd, norm_2610ae, ARRAY_SIZE(norm_2610ae));
/* enable autoexpo */
i2c_w_mask(sd, 0x13, 0x05, 0x05);
break;
case SEN_OV3610:
write_i2c_regvals(sd, norm_3620b, ARRAY_SIZE(norm_3620b));
/* Enable autogain, autoexpo, awb, bandfilter */
i2c_w_mask(sd, 0x13, 0x27, 0x27);
break;
case SEN_OV6620:
write_i2c_regvals(sd, norm_6x20, ARRAY_SIZE(norm_6x20));
break;
case SEN_OV6630:
case SEN_OV66308AF:
write_i2c_regvals(sd, norm_6x30, ARRAY_SIZE(norm_6x30));
break;
default:
/* case SEN_OV7610: */
/* case SEN_OV76BE: */
write_i2c_regvals(sd, norm_7610, ARRAY_SIZE(norm_7610));
i2c_w_mask(sd, 0x0e, 0x00, 0x40);
break;
case SEN_OV7620:
case SEN_OV7620AE:
write_i2c_regvals(sd, norm_7620, ARRAY_SIZE(norm_7620));
break;
case SEN_OV7640:
case SEN_OV7648:
write_i2c_regvals(sd, norm_7640, ARRAY_SIZE(norm_7640));
break;
case SEN_OV7660:
i2c_w(sd, OV7670_R12_COM7, OV7670_COM7_RESET);
msleep(14);
reg_w(sd, OV519_R57_SNAPSHOT, 0x23);
write_regvals(sd, init_519_ov7660,
ARRAY_SIZE(init_519_ov7660));
write_i2c_regvals(sd, norm_7660, ARRAY_SIZE(norm_7660));
sd->gspca_dev.curr_mode = 1; /* 640x480 */
ov519_set_mode(sd);
ov519_set_fr(sd);
sd_reset_snapshot(gspca_dev);
ov51x_restart(sd);
ov51x_stop(sd); /* not in win traces */
ov51x_led_control(sd, 0);
break;
case SEN_OV7670:
write_i2c_regvals(sd, norm_7670, ARRAY_SIZE(norm_7670));
break;
case SEN_OV8610:
write_i2c_regvals(sd, norm_8610, ARRAY_SIZE(norm_8610));
break;
case SEN_OV9600:
write_i2c_regvals(sd, norm_9600, ARRAY_SIZE(norm_9600));
/* enable autoexpo */
/* i2c_w_mask(sd, 0x13, 0x05, 0x05); */
break;
}
return gspca_dev->usb_err;
error:
gspca_err(gspca_dev, "OV519 Config failed\n");
return -EINVAL;
}
/* function called at start time before URB creation */
static int sd_isoc_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->bridge) {
case BRIDGE_OVFX2:
if (gspca_dev->pixfmt.width != 800)
gspca_dev->cam.bulk_size = OVFX2_BULK_SIZE;
else
gspca_dev->cam.bulk_size = 7 * 4096;
break;
}
return 0;
}
/* Set up the OV511/OV511+ with the given image parameters.
*
* Do not put any sensor-specific code in here (including I2C I/O functions)
*/
static void ov511_mode_init_regs(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int hsegs, vsegs, packet_size, fps, needed;
int interlaced = 0;
struct usb_host_interface *alt;
struct usb_interface *intf;
intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);
alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);
if (!alt) {
gspca_err(gspca_dev, "Couldn't get altsetting\n");
sd->gspca_dev.usb_err = -EIO;
return;
}
if (alt->desc.bNumEndpoints < 1) {
sd->gspca_dev.usb_err = -ENODEV;
return;
}
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
reg_w(sd, R51x_FIFO_PSIZE, packet_size >> 5);
reg_w(sd, R511_CAM_UV_EN, 0x01);
reg_w(sd, R511_SNAP_UV_EN, 0x01);
reg_w(sd, R511_SNAP_OPTS, 0x03);
/* Here I'm assuming that snapshot size == image size.
* I hope that's always true. --claudio
*/
hsegs = (sd->gspca_dev.pixfmt.width >> 3) - 1;
vsegs = (sd->gspca_dev.pixfmt.height >> 3) - 1;
reg_w(sd, R511_CAM_PXCNT, hsegs);
reg_w(sd, R511_CAM_LNCNT, vsegs);
reg_w(sd, R511_CAM_PXDIV, 0x00);
reg_w(sd, R511_CAM_LNDIV, 0x00);
/* YUV420, low pass filter on */
reg_w(sd, R511_CAM_OPTS, 0x03);
/* Snapshot additions */
reg_w(sd, R511_SNAP_PXCNT, hsegs);
reg_w(sd, R511_SNAP_LNCNT, vsegs);
reg_w(sd, R511_SNAP_PXDIV, 0x00);
reg_w(sd, R511_SNAP_LNDIV, 0x00);
/******** Set the framerate ********/
if (frame_rate > 0)
sd->frame_rate = frame_rate;
switch (sd->sensor) {
case SEN_OV6620:
/* No framerate control, doesn't like higher rates yet */
sd->clockdiv = 3;
break;
/* Note once the FIXME's in mode_init_ov_sensor_regs() are fixed
for more sensors we need to do this for them too */
case SEN_OV7620:
case SEN_OV7620AE:
case SEN_OV7640:
case SEN_OV7648:
case SEN_OV76BE:
if (sd->gspca_dev.pixfmt.width == 320)
interlaced = 1;
/* Fall through */
case SEN_OV6630:
case SEN_OV7610:
case SEN_OV7670:
switch (sd->frame_rate) {
case 30:
case 25:
/* Not enough bandwidth to do 640x480 @ 30 fps */
if (sd->gspca_dev.pixfmt.width != 640) {
sd->clockdiv = 0;
break;
}
/* For 640x480 case */
/* fall through */
default:
/* case 20: */
/* case 15: */
sd->clockdiv = 1;
break;
case 10:
sd->clockdiv = 2;
break;
case 5:
sd->clockdiv = 5;
break;
}
if (interlaced) {
sd->clockdiv = (sd->clockdiv + 1) * 2 - 1;
/* Higher then 10 does not work */
if (sd->clockdiv > 10)
sd->clockdiv = 10;
}
break;
case SEN_OV8610:
/* No framerate control ?? */
sd->clockdiv = 0;
break;
}
/* Check if we have enough bandwidth to disable compression */
fps = (interlaced ? 60 : 30) / (sd->clockdiv + 1) + 1;
needed = fps * sd->gspca_dev.pixfmt.width *
sd->gspca_dev.pixfmt.height * 3 / 2;
/* 1000 isoc packets/sec */
if (needed > 1000 * packet_size) {
/* Enable Y and UV quantization and compression */
reg_w(sd, R511_COMP_EN, 0x07);
reg_w(sd, R511_COMP_LUT_EN, 0x03);
} else {
reg_w(sd, R511_COMP_EN, 0x06);
reg_w(sd, R511_COMP_LUT_EN, 0x00);
}
reg_w(sd, R51x_SYS_RESET, OV511_RESET_OMNICE);
reg_w(sd, R51x_SYS_RESET, 0);
}
/* Sets up the OV518/OV518+ with the given image parameters
*
* OV518 needs a completely different approach, until we can figure out what
* the individual registers do. Also, only 15 FPS is supported now.
*
* Do not put any sensor-specific code in here (including I2C I/O functions)
*/
static void ov518_mode_init_regs(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int hsegs, vsegs, packet_size;
struct usb_host_interface *alt;
struct usb_interface *intf;
intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);
alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);
if (!alt) {
gspca_err(gspca_dev, "Couldn't get altsetting\n");
sd->gspca_dev.usb_err = -EIO;
return;
}
if (alt->desc.bNumEndpoints < 1) {
sd->gspca_dev.usb_err = -ENODEV;
return;
}
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
ov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2);
/******** Set the mode ********/
reg_w(sd, 0x2b, 0);
reg_w(sd, 0x2c, 0);
reg_w(sd, 0x2d, 0);
reg_w(sd, 0x2e, 0);
reg_w(sd, 0x3b, 0);
reg_w(sd, 0x3c, 0);
reg_w(sd, 0x3d, 0);
reg_w(sd, 0x3e, 0);
if (sd->bridge == BRIDGE_OV518) {
/* Set 8-bit (YVYU) input format */
reg_w_mask(sd, 0x20, 0x08, 0x08);
/* Set 12-bit (4:2:0) output format */
reg_w_mask(sd, 0x28, 0x80, 0xf0);
reg_w_mask(sd, 0x38, 0x80, 0xf0);
} else {
reg_w(sd, 0x28, 0x80);
reg_w(sd, 0x38, 0x80);
}
hsegs = sd->gspca_dev.pixfmt.width / 16;
vsegs = sd->gspca_dev.pixfmt.height / 4;
reg_w(sd, 0x29, hsegs);
reg_w(sd, 0x2a, vsegs);
reg_w(sd, 0x39, hsegs);
reg_w(sd, 0x3a, vsegs);
/* Windows driver does this here; who knows why */
reg_w(sd, 0x2f, 0x80);
/******** Set the framerate ********/
if (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 &&
sd->sensor == SEN_OV7620AE)
sd->clockdiv = 0;
else
sd->clockdiv = 1;
/* Mode independent, but framerate dependent, regs */
/* 0x51: Clock divider; Only works on some cams which use 2 crystals */
reg_w(sd, 0x51, 0x04);
reg_w(sd, 0x22, 0x18);
reg_w(sd, 0x23, 0xff);
if (sd->bridge == BRIDGE_OV518PLUS) {
switch (sd->sensor) {
case SEN_OV7620AE:
/*
* HdG: 640x480 needs special handling on device
* revision 2, we check for device revision > 0 to
* avoid regressions, as we don't know the correct
* thing todo for revision 1.
*
* Also this likely means we don't need to
* differentiate between the OV7620 and OV7620AE,
* earlier testing hitting this same problem likely
* happened to be with revision < 2 cams using an
* OV7620 and revision 2 cams using an OV7620AE.
*/
if (sd->revision > 0 &&
sd->gspca_dev.pixfmt.width == 640) {
reg_w(sd, 0x20, 0x60);
reg_w(sd, 0x21, 0x1f);
} else {
reg_w(sd, 0x20, 0x00);
reg_w(sd, 0x21, 0x19);
}
break;
case SEN_OV7620:
reg_w(sd, 0x20, 0x00);
reg_w(sd, 0x21, 0x19);
break;
default:
reg_w(sd, 0x21, 0x19);
}
} else
reg_w(sd, 0x71, 0x17); /* Compression-related? */
/* FIXME: Sensor-specific */
/* Bit 5 is what matters here. Of course, it is "reserved" */
i2c_w(sd, 0x54, 0x23);
reg_w(sd, 0x2f, 0x80);
if (sd->bridge == BRIDGE_OV518PLUS) {
reg_w(sd, 0x24, 0x94);
reg_w(sd, 0x25, 0x90);
ov518_reg_w32(sd, 0xc4, 400, 2); /* 190h */
ov518_reg_w32(sd, 0xc6, 540, 2); /* 21ch */
ov518_reg_w32(sd, 0xc7, 540, 2); /* 21ch */
ov518_reg_w32(sd, 0xc8, 108, 2); /* 6ch */
ov518_reg_w32(sd, 0xca, 131098, 3); /* 2001ah */
ov518_reg_w32(sd, 0xcb, 532, 2); /* 214h */
ov518_reg_w32(sd, 0xcc, 2400, 2); /* 960h */
ov518_reg_w32(sd, 0xcd, 32, 2); /* 20h */
ov518_reg_w32(sd, 0xce, 608, 2); /* 260h */
} else {
reg_w(sd, 0x24, 0x9f);
reg_w(sd, 0x25, 0x90);
ov518_reg_w32(sd, 0xc4, 400, 2); /* 190h */
ov518_reg_w32(sd, 0xc6, 381, 2); /* 17dh */
ov518_reg_w32(sd, 0xc7, 381, 2); /* 17dh */
ov518_reg_w32(sd, 0xc8, 128, 2); /* 80h */
ov518_reg_w32(sd, 0xca, 183331, 3); /* 2cc23h */
ov518_reg_w32(sd, 0xcb, 746, 2); /* 2eah */
ov518_reg_w32(sd, 0xcc, 1750, 2); /* 6d6h */
ov518_reg_w32(sd, 0xcd, 45, 2); /* 2dh */
ov518_reg_w32(sd, 0xce, 851, 2); /* 353h */
}
reg_w(sd, 0x2f, 0x80);
}
/* Sets up the OV519 with the given image parameters
*
* OV519 needs a completely different approach, until we can figure out what
* the individual registers do.
*
* Do not put any sensor-specific code in here (including I2C I/O functions)
*/
static void ov519_mode_init_regs(struct sd *sd)
{
static const struct ov_regvals mode_init_519_ov7670[] = {
{ 0x5d, 0x03 }, /* Turn off suspend mode */
{ 0x53, 0x9f }, /* was 9b in 1.65-1.08 */
{ OV519_R54_EN_CLK1, 0x0f }, /* bit2 (jpeg enable) */
{ 0xa2, 0x20 }, /* a2-a5 are undocumented */
{ 0xa3, 0x18 },
{ 0xa4, 0x04 },
{ 0xa5, 0x28 },
{ 0x37, 0x00 }, /* SetUsbInit */
{ 0x55, 0x02 }, /* 4.096 Mhz audio clock */
/* Enable both fields, YUV Input, disable defect comp (why?) */
{ 0x20, 0x0c },
{ 0x21, 0x38 },
{ 0x22, 0x1d },
{ 0x17, 0x50 }, /* undocumented */
{ 0x37, 0x00 }, /* undocumented */
{ 0x40, 0xff }, /* I2C timeout counter */
{ 0x46, 0x00 }, /* I2C clock prescaler */
{ 0x59, 0x04 }, /* new from windrv 090403 */
{ 0xff, 0x00 }, /* undocumented */
/* windows reads 0x55 at this point, why? */
};
static const struct ov_regvals mode_init_519[] = {
{ 0x5d, 0x03 }, /* Turn off suspend mode */
{ 0x53, 0x9f }, /* was 9b in 1.65-1.08 */
{ OV519_R54_EN_CLK1, 0x0f }, /* bit2 (jpeg enable) */
{ 0xa2, 0x20 }, /* a2-a5 are undocumented */
{ 0xa3, 0x18 },
{ 0xa4, 0x04 },
{ 0xa5, 0x28 },
{ 0x37, 0x00 }, /* SetUsbInit */
{ 0x55, 0x02 }, /* 4.096 Mhz audio clock */
/* Enable both fields, YUV Input, disable defect comp (why?) */
{ 0x22, 0x1d },
{ 0x17, 0x50 }, /* undocumented */
{ 0x37, 0x00 }, /* undocumented */
{ 0x40, 0xff }, /* I2C timeout counter */
{ 0x46, 0x00 }, /* I2C clock prescaler */
{ 0x59, 0x04 }, /* new from windrv 090403 */
{ 0xff, 0x00 }, /* undocumented */
/* windows reads 0x55 at this point, why? */
};
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
/******** Set the mode ********/
switch (sd->sensor) {
default:
write_regvals(sd, mode_init_519, ARRAY_SIZE(mode_init_519));
if (sd->sensor == SEN_OV7640 ||
sd->sensor == SEN_OV7648) {
/* Select 8-bit input mode */
reg_w_mask(sd, OV519_R20_DFR, 0x10, 0x10);
}
break;
case SEN_OV7660:
return; /* done by ov519_set_mode/fr() */
case SEN_OV7670:
write_regvals(sd, mode_init_519_ov7670,
ARRAY_SIZE(mode_init_519_ov7670));
break;
}
reg_w(sd, OV519_R10_H_SIZE, sd->gspca_dev.pixfmt.width >> 4);
reg_w(sd, OV519_R11_V_SIZE, sd->gspca_dev.pixfmt.height >> 3);
if (sd->sensor == SEN_OV7670 &&
sd->gspca_dev.cam.cam_mode[sd->gspca_dev.curr_mode].priv)
reg_w(sd, OV519_R12_X_OFFSETL, 0x04);
else if (sd->sensor == SEN_OV7648 &&
sd->gspca_dev.cam.cam_mode[sd->gspca_dev.curr_mode].priv)
reg_w(sd, OV519_R12_X_OFFSETL, 0x01);
else
reg_w(sd, OV519_R12_X_OFFSETL, 0x00);
reg_w(sd, OV519_R13_X_OFFSETH, 0x00);
reg_w(sd, OV519_R14_Y_OFFSETL, 0x00);
reg_w(sd, OV519_R15_Y_OFFSETH, 0x00);
reg_w(sd, OV519_R16_DIVIDER, 0x00);
reg_w(sd, OV519_R25_FORMAT, 0x03); /* YUV422 */
reg_w(sd, 0x26, 0x00); /* Undocumented */
/******** Set the framerate ********/
if (frame_rate > 0)
sd->frame_rate = frame_rate;
/* FIXME: These are only valid at the max resolution. */
sd->clockdiv = 0;
switch (sd->sensor) {
case SEN_OV7640:
case SEN_OV7648:
switch (sd->frame_rate) {
default:
/* case 30: */
reg_w(sd, 0xa4, 0x0c);
reg_w(sd, 0x23, 0xff);
break;
case 25:
reg_w(sd, 0xa4, 0x0c);
reg_w(sd, 0x23, 0x1f);
break;
case 20:
reg_w(sd, 0xa4, 0x0c);
reg_w(sd, 0x23, 0x1b);
break;
case 15:
reg_w(sd, 0xa4, 0x04);
reg_w(sd, 0x23, 0xff);
sd->clockdiv = 1;
break;
case 10:
reg_w(sd, 0xa4, 0x04);
reg_w(sd, 0x23, 0x1f);
sd->clockdiv = 1;
break;
case 5:
reg_w(sd, 0xa4, 0x04);
reg_w(sd, 0x23, 0x1b);
sd->clockdiv = 1;
break;
}
break;
case SEN_OV8610:
switch (sd->frame_rate) {
default: /* 15 fps */
/* case 15: */
reg_w(sd, 0xa4, 0x06);
reg_w(sd, 0x23, 0xff);
break;
case 10:
reg_w(sd, 0xa4, 0x06);
reg_w(sd, 0x23, 0x1f);
break;
case 5:
reg_w(sd, 0xa4, 0x06);
reg_w(sd, 0x23, 0x1b);
break;
}
break;
case SEN_OV7670: /* guesses, based on 7640 */
gspca_dbg(gspca_dev, D_STREAM, "Setting framerate to %d fps\n",
(sd->frame_rate == 0) ? 15 : sd->frame_rate);
reg_w(sd, 0xa4, 0x10);
switch (sd->frame_rate) {
case 30:
reg_w(sd, 0x23, 0xff);
break;
case 20:
reg_w(sd, 0x23, 0x1b);
break;
default:
/* case 15: */
reg_w(sd, 0x23, 0xff);
sd->clockdiv = 1;
break;
}
break;
}
}
static void mode_init_ov_sensor_regs(struct sd *sd)
{
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
int qvga, xstart, xend, ystart, yend;
u8 v;
qvga = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv & 1;
/******** Mode (VGA/QVGA) and sensor specific regs ********/
switch (sd->sensor) {
case SEN_OV2610:
i2c_w_mask(sd, 0x14, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x28, qvga ? 0x00 : 0x20, 0x20);
i2c_w(sd, 0x24, qvga ? 0x20 : 0x3a);
i2c_w(sd, 0x25, qvga ? 0x30 : 0x60);
i2c_w_mask(sd, 0x2d, qvga ? 0x40 : 0x00, 0x40);
i2c_w_mask(sd, 0x67, qvga ? 0xf0 : 0x90, 0xf0);
i2c_w_mask(sd, 0x74, qvga ? 0x20 : 0x00, 0x20);
return;
case SEN_OV2610AE: {
u8 v;
/* frame rates:
* 10fps / 5 fps for 1600x1200
* 40fps / 20fps for 800x600
*/
v = 80;
if (qvga) {
if (sd->frame_rate < 25)
v = 0x81;
} else {
if (sd->frame_rate < 10)
v = 0x81;
}
i2c_w(sd, 0x11, v);
i2c_w(sd, 0x12, qvga ? 0x60 : 0x20);
return;
}
case SEN_OV3610:
if (qvga) {
xstart = (1040 - gspca_dev->pixfmt.width) / 2 +
(0x1f << 4);
ystart = (776 - gspca_dev->pixfmt.height) / 2;
} else {
xstart = (2076 - gspca_dev->pixfmt.width) / 2 +
(0x10 << 4);
ystart = (1544 - gspca_dev->pixfmt.height) / 2;
}
xend = xstart + gspca_dev->pixfmt.width;
yend = ystart + gspca_dev->pixfmt.height;
/* Writing to the COMH register resets the other windowing regs
to their default values, so we must do this first. */
i2c_w_mask(sd, 0x12, qvga ? 0x40 : 0x00, 0xf0);
i2c_w_mask(sd, 0x32,
(((xend >> 1) & 7) << 3) | ((xstart >> 1) & 7),
0x3f);
i2c_w_mask(sd, 0x03,
(((yend >> 1) & 3) << 2) | ((ystart >> 1) & 3),
0x0f);
i2c_w(sd, 0x17, xstart >> 4);
i2c_w(sd, 0x18, xend >> 4);
i2c_w(sd, 0x19, ystart >> 3);
i2c_w(sd, 0x1a, yend >> 3);
return;
case SEN_OV8610:
/* For OV8610 qvga means qsvga */
i2c_w_mask(sd, OV7610_REG_COM_C, qvga ? (1 << 5) : 0, 1 << 5);
i2c_w_mask(sd, 0x13, 0x00, 0x20); /* Select 16 bit data bus */
i2c_w_mask(sd, 0x12, 0x04, 0x06); /* AWB: 1 Test pattern: 0 */
i2c_w_mask(sd, 0x2d, 0x00, 0x40); /* from windrv 090403 */
i2c_w_mask(sd, 0x28, 0x20, 0x20); /* progressive mode on */
break;
case SEN_OV7610:
i2c_w_mask(sd, 0x14, qvga ? 0x20 : 0x00, 0x20);
i2c_w(sd, 0x35, qvga ? 0x1e : 0x9e);
i2c_w_mask(sd, 0x13, 0x00, 0x20); /* Select 16 bit data bus */
i2c_w_mask(sd, 0x12, 0x04, 0x06); /* AWB: 1 Test pattern: 0 */
break;
case SEN_OV7620:
case SEN_OV7620AE:
case SEN_OV76BE:
i2c_w_mask(sd, 0x14, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x28, qvga ? 0x00 : 0x20, 0x20);
i2c_w(sd, 0x24, qvga ? 0x20 : 0x3a);
i2c_w(sd, 0x25, qvga ? 0x30 : 0x60);
i2c_w_mask(sd, 0x2d, qvga ? 0x40 : 0x00, 0x40);
i2c_w_mask(sd, 0x67, qvga ? 0xb0 : 0x90, 0xf0);
i2c_w_mask(sd, 0x74, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x13, 0x00, 0x20); /* Select 16 bit data bus */
i2c_w_mask(sd, 0x12, 0x04, 0x06); /* AWB: 1 Test pattern: 0 */
if (sd->sensor == SEN_OV76BE)
i2c_w(sd, 0x35, qvga ? 0x1e : 0x9e);
break;
case SEN_OV7640:
case SEN_OV7648:
i2c_w_mask(sd, 0x14, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x28, qvga ? 0x00 : 0x20, 0x20);
/* Setting this undocumented bit in qvga mode removes a very
annoying vertical shaking of the image */
i2c_w_mask(sd, 0x2d, qvga ? 0x40 : 0x00, 0x40);
/* Unknown */
i2c_w_mask(sd, 0x67, qvga ? 0xf0 : 0x90, 0xf0);
/* Allow higher automatic gain (to allow higher framerates) */
i2c_w_mask(sd, 0x74, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x12, 0x04, 0x04); /* AWB: 1 */
break;
case SEN_OV7670:
/* set COM7_FMT_VGA or COM7_FMT_QVGA
* do we need to set anything else?
* HSTART etc are set in set_ov_sensor_window itself */
i2c_w_mask(sd, OV7670_R12_COM7,
qvga ? OV7670_COM7_FMT_QVGA : OV7670_COM7_FMT_VGA,
OV7670_COM7_FMT_MASK);
i2c_w_mask(sd, 0x13, 0x00, 0x20); /* Select 16 bit data bus */
i2c_w_mask(sd, OV7670_R13_COM8, OV7670_COM8_AWB,
OV7670_COM8_AWB);
if (qvga) { /* QVGA from ov7670.c by
* Jonathan Corbet */
xstart = 164;
xend = 28;
ystart = 14;
yend = 494;
} else { /* VGA */
xstart = 158;
xend = 14;
ystart = 10;
yend = 490;
}
/* OV7670 hardware window registers are split across
* multiple locations */
i2c_w(sd, OV7670_R17_HSTART, xstart >> 3);
i2c_w(sd, OV7670_R18_HSTOP, xend >> 3);
v = i2c_r(sd, OV7670_R32_HREF);
v = (v & 0xc0) | ((xend & 0x7) << 3) | (xstart & 0x07);
msleep(10); /* need to sleep between read and write to
* same reg! */
i2c_w(sd, OV7670_R32_HREF, v);
i2c_w(sd, OV7670_R19_VSTART, ystart >> 2);
i2c_w(sd, OV7670_R1A_VSTOP, yend >> 2);
v = i2c_r(sd, OV7670_R03_VREF);
v = (v & 0xc0) | ((yend & 0x3) << 2) | (ystart & 0x03);
msleep(10); /* need to sleep between read and write to
* same reg! */
i2c_w(sd, OV7670_R03_VREF, v);
break;
case SEN_OV6620:
i2c_w_mask(sd, 0x14, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x13, 0x00, 0x20); /* Select 16 bit data bus */
i2c_w_mask(sd, 0x12, 0x04, 0x06); /* AWB: 1 Test pattern: 0 */
break;
case SEN_OV6630:
case SEN_OV66308AF:
i2c_w_mask(sd, 0x14, qvga ? 0x20 : 0x00, 0x20);
i2c_w_mask(sd, 0x12, 0x04, 0x06); /* AWB: 1 Test pattern: 0 */
break;
case SEN_OV9600: {
const struct ov_i2c_regvals *vals;
static const struct ov_i2c_regvals sxga_15[] = {
{0x11, 0x80}, {0x14, 0x3e}, {0x24, 0x85}, {0x25, 0x75}
};
static const struct ov_i2c_regvals sxga_7_5[] = {
{0x11, 0x81}, {0x14, 0x3e}, {0x24, 0x85}, {0x25, 0x75}
};
static const struct ov_i2c_regvals vga_30[] = {
{0x11, 0x81}, {0x14, 0x7e}, {0x24, 0x70}, {0x25, 0x60}
};
static const struct ov_i2c_regvals vga_15[] = {
{0x11, 0x83}, {0x14, 0x3e}, {0x24, 0x80}, {0x25, 0x70}
};
/* frame rates:
* 15fps / 7.5 fps for 1280x1024
* 30fps / 15fps for 640x480
*/
i2c_w_mask(sd, 0x12, qvga ? 0x40 : 0x00, 0x40);
if (qvga)
vals = sd->frame_rate < 30 ? vga_15 : vga_30;
else
vals = sd->frame_rate < 15 ? sxga_7_5 : sxga_15;
write_i2c_regvals(sd, vals, ARRAY_SIZE(sxga_15));
return;
}
default:
return;
}
/******** Clock programming ********/
i2c_w(sd, 0x11, sd->clockdiv);
}
/* this function works for bridge ov519 and sensors ov7660 and ov7670 only */
static void sethvflip(struct gspca_dev *gspca_dev, s32 hflip, s32 vflip)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->gspca_dev.streaming)
reg_w(sd, OV519_R51_RESET1, 0x0f); /* block stream */
i2c_w_mask(sd, OV7670_R1E_MVFP,
OV7670_MVFP_MIRROR * hflip | OV7670_MVFP_VFLIP * vflip,
OV7670_MVFP_MIRROR | OV7670_MVFP_VFLIP);
if (sd->gspca_dev.streaming)
reg_w(sd, OV519_R51_RESET1, 0x00); /* restart stream */
}
static void set_ov_sensor_window(struct sd *sd)
{
struct gspca_dev *gspca_dev;
int qvga, crop;
int hwsbase, hwebase, vwsbase, vwebase, hwscale, vwscale;
/* mode setup is fully handled in mode_init_ov_sensor_regs for these */
switch (sd->sensor) {
case SEN_OV2610:
case SEN_OV2610AE:
case SEN_OV3610:
case SEN_OV7670:
case SEN_OV9600:
mode_init_ov_sensor_regs(sd);
return;
case SEN_OV7660:
ov519_set_mode(sd);
ov519_set_fr(sd);
return;
}
gspca_dev = &sd->gspca_dev;
qvga = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv & 1;
crop = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv & 2;
/* The different sensor ICs handle setting up of window differently.
* IF YOU SET IT WRONG, YOU WILL GET ALL ZERO ISOC DATA FROM OV51x!! */
switch (sd->sensor) {
case SEN_OV8610:
hwsbase = 0x1e;
hwebase = 0x1e;
vwsbase = 0x02;
vwebase = 0x02;
break;
case SEN_OV7610:
case SEN_OV76BE:
hwsbase = 0x38;
hwebase = 0x3a;
vwsbase = vwebase = 0x05;
break;
case SEN_OV6620:
case SEN_OV6630:
case SEN_OV66308AF:
hwsbase = 0x38;
hwebase = 0x3a;
vwsbase = 0x05;
vwebase = 0x06;
if (sd->sensor == SEN_OV66308AF && qvga)
/* HDG: this fixes U and V getting swapped */
hwsbase++;
if (crop) {
hwsbase += 8;
hwebase += 8;
vwsbase += 11;
vwebase += 11;
}
break;
case SEN_OV7620:
case SEN_OV7620AE:
hwsbase = 0x2f; /* From 7620.SET (spec is wrong) */
hwebase = 0x2f;
vwsbase = vwebase = 0x05;
break;
case SEN_OV7640:
case SEN_OV7648:
hwsbase = 0x1a;
hwebase = 0x1a;
vwsbase = vwebase = 0x03;
break;
default:
return;
}
switch (sd->sensor) {
case SEN_OV6620:
case SEN_OV6630:
case SEN_OV66308AF:
if (qvga) { /* QCIF */
hwscale = 0;
vwscale = 0;
} else { /* CIF */
hwscale = 1;
vwscale = 1; /* The datasheet says 0;
* it's wrong */
}
break;
case SEN_OV8610:
if (qvga) { /* QSVGA */
hwscale = 1;
vwscale = 1;
} else { /* SVGA */
hwscale = 2;
vwscale = 2;
}
break;
default: /* SEN_OV7xx0 */
if (qvga) { /* QVGA */
hwscale = 1;
vwscale = 0;
} else { /* VGA */
hwscale = 2;
vwscale = 1;
}
}
mode_init_ov_sensor_regs(sd);
i2c_w(sd, 0x17, hwsbase);
i2c_w(sd, 0x18, hwebase + (sd->sensor_width >> hwscale));
i2c_w(sd, 0x19, vwsbase);
i2c_w(sd, 0x1a, vwebase + (sd->sensor_height >> vwscale));
}
/* -- start the camera -- */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
/* Default for most bridges, allow bridge_mode_init_regs to override */
sd->sensor_width = sd->gspca_dev.pixfmt.width;
sd->sensor_height = sd->gspca_dev.pixfmt.height;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
ov511_mode_init_regs(sd);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
ov518_mode_init_regs(sd);
break;
case BRIDGE_OV519:
ov519_mode_init_regs(sd);
break;
/* case BRIDGE_OVFX2: nothing to do */
case BRIDGE_W9968CF:
w9968cf_mode_init_regs(sd);
break;
}
set_ov_sensor_window(sd);
/* Force clear snapshot state in case the snapshot button was
pressed while we weren't streaming */
sd->snapshot_needs_reset = 1;
sd_reset_snapshot(gspca_dev);
sd->first_frame = 3;
ov51x_restart(sd);
ov51x_led_control(sd, 1);
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
ov51x_stop(sd);
ov51x_led_control(sd, 0);
}
static void sd_stop0(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (!sd->gspca_dev.present)
return;
if (sd->bridge == BRIDGE_W9968CF)
w9968cf_stop0(sd);
#if IS_ENABLED(CONFIG_INPUT)
/* If the last button state is pressed, release it now! */
if (sd->snapshot_pressed) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
sd->snapshot_pressed = 0;
}
#endif
if (sd->bridge == BRIDGE_OV519)
reg_w(sd, OV519_R57_SNAPSHOT, 0x23);
}
static void ov51x_handle_button(struct gspca_dev *gspca_dev, u8 state)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->snapshot_pressed != state) {
#if IS_ENABLED(CONFIG_INPUT)
input_report_key(gspca_dev->input_dev, KEY_CAMERA, state);
input_sync(gspca_dev->input_dev);
#endif
if (state)
sd->snapshot_needs_reset = 1;
sd->snapshot_pressed = state;
} else {
/* On the ov511 / ov519 we need to reset the button state
multiple times, as resetting does not work as long as the
button stays pressed */
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
case BRIDGE_OV519:
if (state)
sd->snapshot_needs_reset = 1;
break;
}
}
}
static void ov511_pkt_scan(struct gspca_dev *gspca_dev,
u8 *in, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
/* SOF/EOF packets have 1st to 8th bytes zeroed and the 9th
* byte non-zero. The EOF packet has image width/height in the
* 10th and 11th bytes. The 9th byte is given as follows:
*
* bit 7: EOF
* 6: compression enabled
* 5: 422/420/400 modes
* 4: 422/420/400 modes
* 3: 1
* 2: snapshot button on
* 1: snapshot frame
* 0: even/odd field
*/
if (!(in[0] | in[1] | in[2] | in[3] | in[4] | in[5] | in[6] | in[7]) &&
(in[8] & 0x08)) {
ov51x_handle_button(gspca_dev, (in[8] >> 2) & 1);
if (in[8] & 0x80) {
/* Frame end */
if ((in[9] + 1) * 8 != gspca_dev->pixfmt.width ||
(in[10] + 1) * 8 != gspca_dev->pixfmt.height) {
gspca_err(gspca_dev, "Invalid frame size, got: %dx%d, requested: %dx%d\n",
(in[9] + 1) * 8, (in[10] + 1) * 8,
gspca_dev->pixfmt.width,
gspca_dev->pixfmt.height);
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
/* Add 11 byte footer to frame, might be useful */
gspca_frame_add(gspca_dev, LAST_PACKET, in, 11);
return;
} else {
/* Frame start */
gspca_frame_add(gspca_dev, FIRST_PACKET, in, 0);
sd->packet_nr = 0;
}
}
/* Ignore the packet number */
len--;
/* intermediate packet */
gspca_frame_add(gspca_dev, INTER_PACKET, in, len);
}
static void ov518_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
/* A false positive here is likely, until OVT gives me
* the definitive SOF/EOF format */
if ((!(data[0] | data[1] | data[2] | data[3] | data[5])) && data[6]) {
ov51x_handle_button(gspca_dev, (data[6] >> 1) & 1);
gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0);
gspca_frame_add(gspca_dev, FIRST_PACKET, NULL, 0);
sd->packet_nr = 0;
}
if (gspca_dev->last_packet_type == DISCARD_PACKET)
return;
/* Does this device use packet numbers ? */
if (len & 7) {
len--;
if (sd->packet_nr == data[len])
sd->packet_nr++;
/* The last few packets of the frame (which are all 0's
except that they may contain part of the footer), are
numbered 0 */
else if (sd->packet_nr == 0 || data[len]) {
gspca_err(gspca_dev, "Invalid packet nr: %d (expect: %d)\n",
(int)data[len], (int)sd->packet_nr);
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
}
/* intermediate packet */
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
static void ov519_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
/* Header of ov519 is 16 bytes:
* Byte Value Description
* 0 0xff magic
* 1 0xff magic
* 2 0xff magic
* 3 0xXX 0x50 = SOF, 0x51 = EOF
* 9 0xXX 0x01 initial frame without data,
* 0x00 standard frame with image
* 14 Lo in EOF: length of image data / 8
* 15 Hi
*/
if (data[0] == 0xff && data[1] == 0xff && data[2] == 0xff) {
switch (data[3]) {
case 0x50: /* start of frame */
/* Don't check the button state here, as the state
usually (always ?) changes at EOF and checking it
here leads to unnecessary snapshot state resets. */
#define HDRSZ 16
data += HDRSZ;
len -= HDRSZ;
#undef HDRSZ
if (data[0] == 0xff || data[1] == 0xd8)
gspca_frame_add(gspca_dev, FIRST_PACKET,
data, len);
else
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
case 0x51: /* end of frame */
ov51x_handle_button(gspca_dev, data[11] & 1);
if (data[9] != 0)
gspca_dev->last_packet_type = DISCARD_PACKET;
gspca_frame_add(gspca_dev, LAST_PACKET,
NULL, 0);
return;
}
}
/* intermediate packet */
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
static void ovfx2_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
/* A short read signals EOF */
if (len < gspca_dev->cam.bulk_size) {
/* If the frame is short, and it is one of the first ones
the sensor and bridge are still syncing, so drop it. */
if (sd->first_frame) {
sd->first_frame--;
if (gspca_dev->image_len <
sd->gspca_dev.pixfmt.width *
sd->gspca_dev.pixfmt.height)
gspca_dev->last_packet_type = DISCARD_PACKET;
}
gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0);
gspca_frame_add(gspca_dev, FIRST_PACKET, NULL, 0);
}
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
switch (sd->bridge) {
case BRIDGE_OV511:
case BRIDGE_OV511PLUS:
ov511_pkt_scan(gspca_dev, data, len);
break;
case BRIDGE_OV518:
case BRIDGE_OV518PLUS:
ov518_pkt_scan(gspca_dev, data, len);
break;
case BRIDGE_OV519:
ov519_pkt_scan(gspca_dev, data, len);
break;
case BRIDGE_OVFX2:
ovfx2_pkt_scan(gspca_dev, data, len);
break;
case BRIDGE_W9968CF:
w9968cf_pkt_scan(gspca_dev, data, len);
break;
}
}
/* -- management routines -- */
static void setbrightness(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct ov_i2c_regvals brit_7660[][7] = {
{{0x0f, 0x6a}, {0x24, 0x40}, {0x25, 0x2b}, {0x26, 0x90},
{0x27, 0xe0}, {0x28, 0xe0}, {0x2c, 0xe0}},
{{0x0f, 0x6a}, {0x24, 0x50}, {0x25, 0x40}, {0x26, 0xa1},
{0x27, 0xc0}, {0x28, 0xc0}, {0x2c, 0xc0}},
{{0x0f, 0x6a}, {0x24, 0x68}, {0x25, 0x58}, {0x26, 0xc2},
{0x27, 0xa0}, {0x28, 0xa0}, {0x2c, 0xa0}},
{{0x0f, 0x6a}, {0x24, 0x70}, {0x25, 0x68}, {0x26, 0xd3},
{0x27, 0x80}, {0x28, 0x80}, {0x2c, 0x80}},
{{0x0f, 0x6a}, {0x24, 0x80}, {0x25, 0x70}, {0x26, 0xd3},
{0x27, 0x20}, {0x28, 0x20}, {0x2c, 0x20}},
{{0x0f, 0x6a}, {0x24, 0x88}, {0x25, 0x78}, {0x26, 0xd3},
{0x27, 0x40}, {0x28, 0x40}, {0x2c, 0x40}},
{{0x0f, 0x6a}, {0x24, 0x90}, {0x25, 0x80}, {0x26, 0xd4},
{0x27, 0x60}, {0x28, 0x60}, {0x2c, 0x60}}
};
switch (sd->sensor) {
case SEN_OV8610:
case SEN_OV7610:
case SEN_OV76BE:
case SEN_OV6620:
case SEN_OV6630:
case SEN_OV66308AF:
case SEN_OV7640:
case SEN_OV7648:
i2c_w(sd, OV7610_REG_BRT, val);
break;
case SEN_OV7620:
case SEN_OV7620AE:
i2c_w(sd, OV7610_REG_BRT, val);
break;
case SEN_OV7660:
write_i2c_regvals(sd, brit_7660[val],
ARRAY_SIZE(brit_7660[0]));
break;
case SEN_OV7670:
/*win trace
* i2c_w_mask(sd, OV7670_R13_COM8, 0, OV7670_COM8_AEC); */
i2c_w(sd, OV7670_R55_BRIGHT, ov7670_abs_to_sm(val));
break;
}
}
static void setcontrast(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct ov_i2c_regvals contrast_7660[][31] = {
{{0x6c, 0xf0}, {0x6d, 0xf0}, {0x6e, 0xf8}, {0x6f, 0xa0},
{0x70, 0x58}, {0x71, 0x38}, {0x72, 0x30}, {0x73, 0x30},
{0x74, 0x28}, {0x75, 0x28}, {0x76, 0x24}, {0x77, 0x24},
{0x78, 0x22}, {0x79, 0x28}, {0x7a, 0x2a}, {0x7b, 0x34},
{0x7c, 0x0f}, {0x7d, 0x1e}, {0x7e, 0x3d}, {0x7f, 0x65},
{0x80, 0x70}, {0x81, 0x77}, {0x82, 0x7d}, {0x83, 0x83},
{0x84, 0x88}, {0x85, 0x8d}, {0x86, 0x96}, {0x87, 0x9f},
{0x88, 0xb0}, {0x89, 0xc4}, {0x8a, 0xd9}},
{{0x6c, 0xf0}, {0x6d, 0xf0}, {0x6e, 0xf8}, {0x6f, 0x94},
{0x70, 0x58}, {0x71, 0x40}, {0x72, 0x30}, {0x73, 0x30},
{0x74, 0x30}, {0x75, 0x30}, {0x76, 0x2c}, {0x77, 0x24},
{0x78, 0x22}, {0x79, 0x28}, {0x7a, 0x2a}, {0x7b, 0x31},
{0x7c, 0x0f}, {0x7d, 0x1e}, {0x7e, 0x3d}, {0x7f, 0x62},
{0x80, 0x6d}, {0x81, 0x75}, {0x82, 0x7b}, {0x83, 0x81},
{0x84, 0x87}, {0x85, 0x8d}, {0x86, 0x98}, {0x87, 0xa1},
{0x88, 0xb2}, {0x89, 0xc6}, {0x8a, 0xdb}},
{{0x6c, 0xf0}, {0x6d, 0xf0}, {0x6e, 0xf0}, {0x6f, 0x84},
{0x70, 0x58}, {0x71, 0x48}, {0x72, 0x40}, {0x73, 0x40},
{0x74, 0x28}, {0x75, 0x28}, {0x76, 0x28}, {0x77, 0x24},
{0x78, 0x26}, {0x79, 0x28}, {0x7a, 0x28}, {0x7b, 0x34},
{0x7c, 0x0f}, {0x7d, 0x1e}, {0x7e, 0x3c}, {0x7f, 0x5d},
{0x80, 0x68}, {0x81, 0x71}, {0x82, 0x79}, {0x83, 0x81},
{0x84, 0x86}, {0x85, 0x8b}, {0x86, 0x95}, {0x87, 0x9e},
{0x88, 0xb1}, {0x89, 0xc5}, {0x8a, 0xd9}},
{{0x6c, 0xf0}, {0x6d, 0xf0}, {0x6e, 0xf0}, {0x6f, 0x70},
{0x70, 0x58}, {0x71, 0x58}, {0x72, 0x48}, {0x73, 0x48},
{0x74, 0x38}, {0x75, 0x40}, {0x76, 0x34}, {0x77, 0x34},
{0x78, 0x2e}, {0x79, 0x28}, {0x7a, 0x24}, {0x7b, 0x22},
{0x7c, 0x0f}, {0x7d, 0x1e}, {0x7e, 0x3c}, {0x7f, 0x58},
{0x80, 0x63}, {0x81, 0x6e}, {0x82, 0x77}, {0x83, 0x80},
{0x84, 0x87}, {0x85, 0x8f}, {0x86, 0x9c}, {0x87, 0xa9},
{0x88, 0xc0}, {0x89, 0xd4}, {0x8a, 0xe6}},
{{0x6c, 0xa0}, {0x6d, 0xf0}, {0x6e, 0x90}, {0x6f, 0x80},
{0x70, 0x70}, {0x71, 0x80}, {0x72, 0x60}, {0x73, 0x60},
{0x74, 0x58}, {0x75, 0x60}, {0x76, 0x4c}, {0x77, 0x38},
{0x78, 0x38}, {0x79, 0x2a}, {0x7a, 0x20}, {0x7b, 0x0e},
{0x7c, 0x0a}, {0x7d, 0x14}, {0x7e, 0x26}, {0x7f, 0x46},
{0x80, 0x54}, {0x81, 0x64}, {0x82, 0x70}, {0x83, 0x7c},
{0x84, 0x87}, {0x85, 0x93}, {0x86, 0xa6}, {0x87, 0xb4},
{0x88, 0xd0}, {0x89, 0xe5}, {0x8a, 0xf5}},
{{0x6c, 0x60}, {0x6d, 0x80}, {0x6e, 0x60}, {0x6f, 0x80},
{0x70, 0x80}, {0x71, 0x80}, {0x72, 0x88}, {0x73, 0x30},
{0x74, 0x70}, {0x75, 0x68}, {0x76, 0x64}, {0x77, 0x50},
{0x78, 0x3c}, {0x79, 0x22}, {0x7a, 0x10}, {0x7b, 0x08},
{0x7c, 0x06}, {0x7d, 0x0e}, {0x7e, 0x1a}, {0x7f, 0x3a},
{0x80, 0x4a}, {0x81, 0x5a}, {0x82, 0x6b}, {0x83, 0x7b},
{0x84, 0x89}, {0x85, 0x96}, {0x86, 0xaf}, {0x87, 0xc3},
{0x88, 0xe1}, {0x89, 0xf2}, {0x8a, 0xfa}},
{{0x6c, 0x20}, {0x6d, 0x40}, {0x6e, 0x20}, {0x6f, 0x60},
{0x70, 0x88}, {0x71, 0xc8}, {0x72, 0xc0}, {0x73, 0xb8},
{0x74, 0xa8}, {0x75, 0xb8}, {0x76, 0x80}, {0x77, 0x5c},
{0x78, 0x26}, {0x79, 0x10}, {0x7a, 0x08}, {0x7b, 0x04},
{0x7c, 0x02}, {0x7d, 0x06}, {0x7e, 0x0a}, {0x7f, 0x22},
{0x80, 0x33}, {0x81, 0x4c}, {0x82, 0x64}, {0x83, 0x7b},
{0x84, 0x90}, {0x85, 0xa7}, {0x86, 0xc7}, {0x87, 0xde},
{0x88, 0xf1}, {0x89, 0xf9}, {0x8a, 0xfd}},
};
switch (sd->sensor) {
case SEN_OV7610:
case SEN_OV6620:
i2c_w(sd, OV7610_REG_CNT, val);
break;
case SEN_OV6630:
case SEN_OV66308AF:
i2c_w_mask(sd, OV7610_REG_CNT, val >> 4, 0x0f);
break;
case SEN_OV8610: {
static const u8 ctab[] = {
0x03, 0x09, 0x0b, 0x0f, 0x53, 0x6f, 0x35, 0x7f
};
/* Use Y gamma control instead. Bit 0 enables it. */
i2c_w(sd, 0x64, ctab[val >> 5]);
break;
}
case SEN_OV7620:
case SEN_OV7620AE: {
static const u8 ctab[] = {
0x01, 0x05, 0x09, 0x11, 0x15, 0x35, 0x37, 0x57,
0x5b, 0xa5, 0xa7, 0xc7, 0xc9, 0xcf, 0xef, 0xff
};
/* Use Y gamma control instead. Bit 0 enables it. */
i2c_w(sd, 0x64, ctab[val >> 4]);
break;
}
case SEN_OV7660:
write_i2c_regvals(sd, contrast_7660[val],
ARRAY_SIZE(contrast_7660[0]));
break;
case SEN_OV7670:
/* check that this isn't just the same as ov7610 */
i2c_w(sd, OV7670_R56_CONTRAS, val >> 1);
break;
}
}
static void setexposure(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w(sd, 0x10, val);
}
static void setcolors(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
static const struct ov_i2c_regvals colors_7660[][6] = {
{{0x4f, 0x28}, {0x50, 0x2a}, {0x51, 0x02}, {0x52, 0x0a},
{0x53, 0x19}, {0x54, 0x23}},
{{0x4f, 0x47}, {0x50, 0x4a}, {0x51, 0x03}, {0x52, 0x11},
{0x53, 0x2c}, {0x54, 0x3e}},
{{0x4f, 0x66}, {0x50, 0x6b}, {0x51, 0x05}, {0x52, 0x19},
{0x53, 0x40}, {0x54, 0x59}},
{{0x4f, 0x84}, {0x50, 0x8b}, {0x51, 0x06}, {0x52, 0x20},
{0x53, 0x53}, {0x54, 0x73}},
{{0x4f, 0xa3}, {0x50, 0xab}, {0x51, 0x08}, {0x52, 0x28},
{0x53, 0x66}, {0x54, 0x8e}},
};
switch (sd->sensor) {
case SEN_OV8610:
case SEN_OV7610:
case SEN_OV76BE:
case SEN_OV6620:
case SEN_OV6630:
case SEN_OV66308AF:
i2c_w(sd, OV7610_REG_SAT, val);
break;
case SEN_OV7620:
case SEN_OV7620AE:
/* Use UV gamma control instead. Bits 0 & 7 are reserved. */
/* rc = ov_i2c_write(sd->dev, 0x62, (val >> 9) & 0x7e);
if (rc < 0)
goto out; */
i2c_w(sd, OV7610_REG_SAT, val);
break;
case SEN_OV7640:
case SEN_OV7648:
i2c_w(sd, OV7610_REG_SAT, val & 0xf0);
break;
case SEN_OV7660:
write_i2c_regvals(sd, colors_7660[val],
ARRAY_SIZE(colors_7660[0]));
break;
case SEN_OV7670:
/* supported later once I work out how to do it
* transparently fail now! */
/* set REG_COM13 values for UV sat auto mode */
break;
}
}
static void setautobright(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w_mask(sd, 0x2d, val ? 0x10 : 0x00, 0x10);
}
static void setfreq_i(struct sd *sd, s32 val)
{
if (sd->sensor == SEN_OV7660
|| sd->sensor == SEN_OV7670) {
switch (val) {
case 0: /* Banding filter disabled */
i2c_w_mask(sd, OV7670_R13_COM8, 0, OV7670_COM8_BFILT);
break;
case 1: /* 50 hz */
i2c_w_mask(sd, OV7670_R13_COM8, OV7670_COM8_BFILT,
OV7670_COM8_BFILT);
i2c_w_mask(sd, OV7670_R3B_COM11, 0x08, 0x18);
break;
case 2: /* 60 hz */
i2c_w_mask(sd, OV7670_R13_COM8, OV7670_COM8_BFILT,
OV7670_COM8_BFILT);
i2c_w_mask(sd, OV7670_R3B_COM11, 0x00, 0x18);
break;
case 3: /* Auto hz - ov7670 only */
i2c_w_mask(sd, OV7670_R13_COM8, OV7670_COM8_BFILT,
OV7670_COM8_BFILT);
i2c_w_mask(sd, OV7670_R3B_COM11, OV7670_COM11_HZAUTO,
0x18);
break;
}
} else {
switch (val) {
case 0: /* Banding filter disabled */
i2c_w_mask(sd, 0x2d, 0x00, 0x04);
i2c_w_mask(sd, 0x2a, 0x00, 0x80);
break;
case 1: /* 50 hz (filter on and framerate adj) */
i2c_w_mask(sd, 0x2d, 0x04, 0x04);
i2c_w_mask(sd, 0x2a, 0x80, 0x80);
/* 20 fps -> 16.667 fps */
if (sd->sensor == SEN_OV6620 ||
sd->sensor == SEN_OV6630 ||
sd->sensor == SEN_OV66308AF)
i2c_w(sd, 0x2b, 0x5e);
else
i2c_w(sd, 0x2b, 0xac);
break;
case 2: /* 60 hz (filter on, ...) */
i2c_w_mask(sd, 0x2d, 0x04, 0x04);
if (sd->sensor == SEN_OV6620 ||
sd->sensor == SEN_OV6630 ||
sd->sensor == SEN_OV66308AF) {
/* 20 fps -> 15 fps */
i2c_w_mask(sd, 0x2a, 0x80, 0x80);
i2c_w(sd, 0x2b, 0xa8);
} else {
/* no framerate adj. */
i2c_w_mask(sd, 0x2a, 0x00, 0x80);
}
break;
}
}
}
static void setfreq(struct gspca_dev *gspca_dev, s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
setfreq_i(sd, val);
/* Ugly but necessary */
if (sd->bridge == BRIDGE_W9968CF)
w9968cf_set_crop_window(sd);
}
static int sd_get_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->bridge != BRIDGE_W9968CF)
return -ENOTTY;
memset(jcomp, 0, sizeof *jcomp);
jcomp->quality = v4l2_ctrl_g_ctrl(sd->jpegqual);
jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT | V4L2_JPEG_MARKER_DQT |
V4L2_JPEG_MARKER_DRI;
return 0;
}
static int sd_set_jcomp(struct gspca_dev *gspca_dev,
const struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->bridge != BRIDGE_W9968CF)
return -ENOTTY;
v4l2_ctrl_s_ctrl(sd->jpegqual, jcomp->quality);
return 0;
}
static int sd_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
switch (ctrl->id) {
case V4L2_CID_AUTOGAIN:
gspca_dev->exposure->val = i2c_r(sd, 0x10);
break;
}
return 0;
}
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (!gspca_dev->streaming)
return 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
setbrightness(gspca_dev, ctrl->val);
break;
case V4L2_CID_CONTRAST:
setcontrast(gspca_dev, ctrl->val);
break;
case V4L2_CID_POWER_LINE_FREQUENCY:
setfreq(gspca_dev, ctrl->val);
break;
case V4L2_CID_AUTOBRIGHTNESS:
if (ctrl->is_new)
setautobright(gspca_dev, ctrl->val);
if (!ctrl->val && sd->brightness->is_new)
setbrightness(gspca_dev, sd->brightness->val);
break;
case V4L2_CID_SATURATION:
setcolors(gspca_dev, ctrl->val);
break;
case V4L2_CID_HFLIP:
sethvflip(gspca_dev, ctrl->val, sd->vflip->val);
break;
case V4L2_CID_AUTOGAIN:
if (ctrl->is_new)
setautogain(gspca_dev, ctrl->val);
if (!ctrl->val && gspca_dev->exposure->is_new)
setexposure(gspca_dev, gspca_dev->exposure->val);
break;
case V4L2_CID_JPEG_COMPRESSION_QUALITY:
return -EBUSY; /* Should never happen, as we grab the ctrl */
}
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.g_volatile_ctrl = sd_g_volatile_ctrl,
.s_ctrl = sd_s_ctrl,
};
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *)gspca_dev;
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 10);
if (valid_controls[sd->sensor].has_brightness)
sd->brightness = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0,
sd->sensor == SEN_OV7660 ? 6 : 255, 1,
sd->sensor == SEN_OV7660 ? 3 : 127);
if (valid_controls[sd->sensor].has_contrast) {
if (sd->sensor == SEN_OV7660)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_CONTRAST, 0, 6, 1, 3);
else
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_CONTRAST, 0, 255, 1,
(sd->sensor == SEN_OV6630 ||
sd->sensor == SEN_OV66308AF) ? 200 : 127);
}
if (valid_controls[sd->sensor].has_sat)
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_SATURATION, 0,
sd->sensor == SEN_OV7660 ? 4 : 255, 1,
sd->sensor == SEN_OV7660 ? 2 : 127);
if (valid_controls[sd->sensor].has_exposure)
gspca_dev->exposure = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_EXPOSURE, 0, 255, 1, 127);
if (valid_controls[sd->sensor].has_hvflip) {
sd->hflip = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
sd->vflip = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
}
if (valid_controls[sd->sensor].has_autobright)
sd->autobright = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_AUTOBRIGHTNESS, 0, 1, 1, 1);
if (valid_controls[sd->sensor].has_autogain)
gspca_dev->autogain = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
if (valid_controls[sd->sensor].has_freq) {
if (sd->sensor == SEN_OV7670)
sd->freq = v4l2_ctrl_new_std_menu(hdl, &sd_ctrl_ops,
V4L2_CID_POWER_LINE_FREQUENCY,
V4L2_CID_POWER_LINE_FREQUENCY_AUTO, 0,
V4L2_CID_POWER_LINE_FREQUENCY_AUTO);
else
sd->freq = v4l2_ctrl_new_std_menu(hdl, &sd_ctrl_ops,
V4L2_CID_POWER_LINE_FREQUENCY,
V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0, 0);
}
if (sd->bridge == BRIDGE_W9968CF)
sd->jpegqual = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_JPEG_COMPRESSION_QUALITY,
QUALITY_MIN, QUALITY_MAX, 1, QUALITY_DEF);
if (hdl->error) {
gspca_err(gspca_dev, "Could not initialize controls\n");
return hdl->error;
}
if (gspca_dev->autogain)
v4l2_ctrl_auto_cluster(3, &gspca_dev->autogain, 0, true);
if (sd->autobright)
v4l2_ctrl_auto_cluster(2, &sd->autobright, 0, false);
if (sd->hflip)
v4l2_ctrl_cluster(2, &sd->hflip);
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.isoc_init = sd_isoc_init,
.start = sd_start,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
.dq_callback = sd_reset_snapshot,
.get_jcomp = sd_get_jcomp,
.set_jcomp = sd_set_jcomp,
#if IS_ENABLED(CONFIG_INPUT)
.other_input = 1,
#endif
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x041e, 0x4003), .driver_info = BRIDGE_W9968CF },
{USB_DEVICE(0x041e, 0x4052),
.driver_info = BRIDGE_OV519 | BRIDGE_INVERT_LED },
{USB_DEVICE(0x041e, 0x405f), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x041e, 0x4060), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x041e, 0x4061), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x041e, 0x4064), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x041e, 0x4067), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x041e, 0x4068), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x045e, 0x028c),
.driver_info = BRIDGE_OV519 | BRIDGE_INVERT_LED },
{USB_DEVICE(0x054c, 0x0154), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x054c, 0x0155), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x05a9, 0x0511), .driver_info = BRIDGE_OV511 },
{USB_DEVICE(0x05a9, 0x0518), .driver_info = BRIDGE_OV518 },
{USB_DEVICE(0x05a9, 0x0519),
.driver_info = BRIDGE_OV519 | BRIDGE_INVERT_LED },
{USB_DEVICE(0x05a9, 0x0530),
.driver_info = BRIDGE_OV519 | BRIDGE_INVERT_LED },
{USB_DEVICE(0x05a9, 0x2800), .driver_info = BRIDGE_OVFX2 },
{USB_DEVICE(0x05a9, 0x4519), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x05a9, 0x8519), .driver_info = BRIDGE_OV519 },
{USB_DEVICE(0x05a9, 0xa511), .driver_info = BRIDGE_OV511PLUS },
{USB_DEVICE(0x05a9, 0xa518), .driver_info = BRIDGE_OV518PLUS },
{USB_DEVICE(0x0813, 0x0002), .driver_info = BRIDGE_OV511PLUS },
{USB_DEVICE(0x0b62, 0x0059), .driver_info = BRIDGE_OVFX2 },
{USB_DEVICE(0x0e96, 0xc001), .driver_info = BRIDGE_OVFX2 },
{USB_DEVICE(0x1046, 0x9967), .driver_info = BRIDGE_W9968CF },
{USB_DEVICE(0x8020, 0xef04), .driver_info = BRIDGE_OVFX2 },
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
module_param(frame_rate, int, 0644);
MODULE_PARM_DESC(frame_rate, "Frame rate (5, 10, 15, 20 or 30 fps)");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3958_0 |
crossvul-cpp_data_good_799_0 | /*
* HEVC video Decoder
*
* Copyright (C) 2012 - 2013 Guillaume Martres
* Copyright (C) 2012 - 2013 Mickael Raulet
* Copyright (C) 2012 - 2013 Gildas Cocherel
* Copyright (C) 2012 - 2013 Wassim Hamidouche
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/attributes.h"
#include "libavutil/common.h"
#include "libavutil/display.h"
#include "libavutil/internal.h"
#include "libavutil/mastering_display_metadata.h"
#include "libavutil/md5.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libavutil/stereo3d.h"
#include "bswapdsp.h"
#include "bytestream.h"
#include "cabac_functions.h"
#include "golomb.h"
#include "hevc.h"
#include "hevc_data.h"
#include "hevc_parse.h"
#include "hevcdec.h"
#include "hwaccel.h"
#include "profiles.h"
const uint8_t ff_hevc_pel_weight[65] = { [2] = 0, [4] = 1, [6] = 2, [8] = 3, [12] = 4, [16] = 5, [24] = 6, [32] = 7, [48] = 8, [64] = 9 };
/**
* NOTE: Each function hls_foo correspond to the function foo in the
* specification (HLS stands for High Level Syntax).
*/
/**
* Section 5.7
*/
/* free everything allocated by pic_arrays_init() */
static void pic_arrays_free(HEVCContext *s)
{
av_freep(&s->sao);
av_freep(&s->deblock);
av_freep(&s->skip_flag);
av_freep(&s->tab_ct_depth);
av_freep(&s->tab_ipm);
av_freep(&s->cbf_luma);
av_freep(&s->is_pcm);
av_freep(&s->qp_y_tab);
av_freep(&s->tab_slice_address);
av_freep(&s->filter_slice_edges);
av_freep(&s->horizontal_bs);
av_freep(&s->vertical_bs);
av_freep(&s->sh.entry_point_offset);
av_freep(&s->sh.size);
av_freep(&s->sh.offset);
av_buffer_pool_uninit(&s->tab_mvf_pool);
av_buffer_pool_uninit(&s->rpl_tab_pool);
}
/* allocate arrays that depend on frame dimensions */
static int pic_arrays_init(HEVCContext *s, const HEVCSPS *sps)
{
int log2_min_cb_size = sps->log2_min_cb_size;
int width = sps->width;
int height = sps->height;
int pic_size_in_ctb = ((width >> log2_min_cb_size) + 1) *
((height >> log2_min_cb_size) + 1);
int ctb_count = sps->ctb_width * sps->ctb_height;
int min_pu_size = sps->min_pu_width * sps->min_pu_height;
s->bs_width = (width >> 2) + 1;
s->bs_height = (height >> 2) + 1;
s->sao = av_mallocz_array(ctb_count, sizeof(*s->sao));
s->deblock = av_mallocz_array(ctb_count, sizeof(*s->deblock));
if (!s->sao || !s->deblock)
goto fail;
s->skip_flag = av_malloc_array(sps->min_cb_height, sps->min_cb_width);
s->tab_ct_depth = av_malloc_array(sps->min_cb_height, sps->min_cb_width);
if (!s->skip_flag || !s->tab_ct_depth)
goto fail;
s->cbf_luma = av_malloc_array(sps->min_tb_width, sps->min_tb_height);
s->tab_ipm = av_mallocz(min_pu_size);
s->is_pcm = av_malloc_array(sps->min_pu_width + 1, sps->min_pu_height + 1);
if (!s->tab_ipm || !s->cbf_luma || !s->is_pcm)
goto fail;
s->filter_slice_edges = av_mallocz(ctb_count);
s->tab_slice_address = av_malloc_array(pic_size_in_ctb,
sizeof(*s->tab_slice_address));
s->qp_y_tab = av_malloc_array(pic_size_in_ctb,
sizeof(*s->qp_y_tab));
if (!s->qp_y_tab || !s->filter_slice_edges || !s->tab_slice_address)
goto fail;
s->horizontal_bs = av_mallocz_array(s->bs_width, s->bs_height);
s->vertical_bs = av_mallocz_array(s->bs_width, s->bs_height);
if (!s->horizontal_bs || !s->vertical_bs)
goto fail;
s->tab_mvf_pool = av_buffer_pool_init(min_pu_size * sizeof(MvField),
av_buffer_allocz);
s->rpl_tab_pool = av_buffer_pool_init(ctb_count * sizeof(RefPicListTab),
av_buffer_allocz);
if (!s->tab_mvf_pool || !s->rpl_tab_pool)
goto fail;
return 0;
fail:
pic_arrays_free(s);
return AVERROR(ENOMEM);
}
static int pred_weight_table(HEVCContext *s, GetBitContext *gb)
{
int i = 0;
int j = 0;
uint8_t luma_weight_l0_flag[16];
uint8_t chroma_weight_l0_flag[16];
uint8_t luma_weight_l1_flag[16];
uint8_t chroma_weight_l1_flag[16];
int luma_log2_weight_denom;
luma_log2_weight_denom = get_ue_golomb_long(gb);
if (luma_log2_weight_denom < 0 || luma_log2_weight_denom > 7) {
av_log(s->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is invalid\n", luma_log2_weight_denom);
return AVERROR_INVALIDDATA;
}
s->sh.luma_log2_weight_denom = av_clip_uintp2(luma_log2_weight_denom, 3);
if (s->ps.sps->chroma_format_idc != 0) {
int64_t chroma_log2_weight_denom = luma_log2_weight_denom + (int64_t)get_se_golomb(gb);
if (chroma_log2_weight_denom < 0 || chroma_log2_weight_denom > 7) {
av_log(s->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %"PRId64" is invalid\n", chroma_log2_weight_denom);
return AVERROR_INVALIDDATA;
}
s->sh.chroma_log2_weight_denom = chroma_log2_weight_denom;
}
for (i = 0; i < s->sh.nb_refs[L0]; i++) {
luma_weight_l0_flag[i] = get_bits1(gb);
if (!luma_weight_l0_flag[i]) {
s->sh.luma_weight_l0[i] = 1 << s->sh.luma_log2_weight_denom;
s->sh.luma_offset_l0[i] = 0;
}
}
if (s->ps.sps->chroma_format_idc != 0) {
for (i = 0; i < s->sh.nb_refs[L0]; i++)
chroma_weight_l0_flag[i] = get_bits1(gb);
} else {
for (i = 0; i < s->sh.nb_refs[L0]; i++)
chroma_weight_l0_flag[i] = 0;
}
for (i = 0; i < s->sh.nb_refs[L0]; i++) {
if (luma_weight_l0_flag[i]) {
int delta_luma_weight_l0 = get_se_golomb(gb);
s->sh.luma_weight_l0[i] = (1 << s->sh.luma_log2_weight_denom) + delta_luma_weight_l0;
s->sh.luma_offset_l0[i] = get_se_golomb(gb);
}
if (chroma_weight_l0_flag[i]) {
for (j = 0; j < 2; j++) {
int delta_chroma_weight_l0 = get_se_golomb(gb);
int delta_chroma_offset_l0 = get_se_golomb(gb);
if ( (int8_t)delta_chroma_weight_l0 != delta_chroma_weight_l0
|| delta_chroma_offset_l0 < -(1<<17) || delta_chroma_offset_l0 > (1<<17)) {
return AVERROR_INVALIDDATA;
}
s->sh.chroma_weight_l0[i][j] = (1 << s->sh.chroma_log2_weight_denom) + delta_chroma_weight_l0;
s->sh.chroma_offset_l0[i][j] = av_clip((delta_chroma_offset_l0 - ((128 * s->sh.chroma_weight_l0[i][j])
>> s->sh.chroma_log2_weight_denom) + 128), -128, 127);
}
} else {
s->sh.chroma_weight_l0[i][0] = 1 << s->sh.chroma_log2_weight_denom;
s->sh.chroma_offset_l0[i][0] = 0;
s->sh.chroma_weight_l0[i][1] = 1 << s->sh.chroma_log2_weight_denom;
s->sh.chroma_offset_l0[i][1] = 0;
}
}
if (s->sh.slice_type == HEVC_SLICE_B) {
for (i = 0; i < s->sh.nb_refs[L1]; i++) {
luma_weight_l1_flag[i] = get_bits1(gb);
if (!luma_weight_l1_flag[i]) {
s->sh.luma_weight_l1[i] = 1 << s->sh.luma_log2_weight_denom;
s->sh.luma_offset_l1[i] = 0;
}
}
if (s->ps.sps->chroma_format_idc != 0) {
for (i = 0; i < s->sh.nb_refs[L1]; i++)
chroma_weight_l1_flag[i] = get_bits1(gb);
} else {
for (i = 0; i < s->sh.nb_refs[L1]; i++)
chroma_weight_l1_flag[i] = 0;
}
for (i = 0; i < s->sh.nb_refs[L1]; i++) {
if (luma_weight_l1_flag[i]) {
int delta_luma_weight_l1 = get_se_golomb(gb);
s->sh.luma_weight_l1[i] = (1 << s->sh.luma_log2_weight_denom) + delta_luma_weight_l1;
s->sh.luma_offset_l1[i] = get_se_golomb(gb);
}
if (chroma_weight_l1_flag[i]) {
for (j = 0; j < 2; j++) {
int delta_chroma_weight_l1 = get_se_golomb(gb);
int delta_chroma_offset_l1 = get_se_golomb(gb);
if ( (int8_t)delta_chroma_weight_l1 != delta_chroma_weight_l1
|| delta_chroma_offset_l1 < -(1<<17) || delta_chroma_offset_l1 > (1<<17)) {
return AVERROR_INVALIDDATA;
}
s->sh.chroma_weight_l1[i][j] = (1 << s->sh.chroma_log2_weight_denom) + delta_chroma_weight_l1;
s->sh.chroma_offset_l1[i][j] = av_clip((delta_chroma_offset_l1 - ((128 * s->sh.chroma_weight_l1[i][j])
>> s->sh.chroma_log2_weight_denom) + 128), -128, 127);
}
} else {
s->sh.chroma_weight_l1[i][0] = 1 << s->sh.chroma_log2_weight_denom;
s->sh.chroma_offset_l1[i][0] = 0;
s->sh.chroma_weight_l1[i][1] = 1 << s->sh.chroma_log2_weight_denom;
s->sh.chroma_offset_l1[i][1] = 0;
}
}
}
return 0;
}
static int decode_lt_rps(HEVCContext *s, LongTermRPS *rps, GetBitContext *gb)
{
const HEVCSPS *sps = s->ps.sps;
int max_poc_lsb = 1 << sps->log2_max_poc_lsb;
int prev_delta_msb = 0;
unsigned int nb_sps = 0, nb_sh;
int i;
rps->nb_refs = 0;
if (!sps->long_term_ref_pics_present_flag)
return 0;
if (sps->num_long_term_ref_pics_sps > 0)
nb_sps = get_ue_golomb_long(gb);
nb_sh = get_ue_golomb_long(gb);
if (nb_sps > sps->num_long_term_ref_pics_sps)
return AVERROR_INVALIDDATA;
if (nb_sh + (uint64_t)nb_sps > FF_ARRAY_ELEMS(rps->poc))
return AVERROR_INVALIDDATA;
rps->nb_refs = nb_sh + nb_sps;
for (i = 0; i < rps->nb_refs; i++) {
uint8_t delta_poc_msb_present;
if (i < nb_sps) {
uint8_t lt_idx_sps = 0;
if (sps->num_long_term_ref_pics_sps > 1)
lt_idx_sps = get_bits(gb, av_ceil_log2(sps->num_long_term_ref_pics_sps));
rps->poc[i] = sps->lt_ref_pic_poc_lsb_sps[lt_idx_sps];
rps->used[i] = sps->used_by_curr_pic_lt_sps_flag[lt_idx_sps];
} else {
rps->poc[i] = get_bits(gb, sps->log2_max_poc_lsb);
rps->used[i] = get_bits1(gb);
}
delta_poc_msb_present = get_bits1(gb);
if (delta_poc_msb_present) {
int64_t delta = get_ue_golomb_long(gb);
int64_t poc;
if (i && i != nb_sps)
delta += prev_delta_msb;
poc = rps->poc[i] + s->poc - delta * max_poc_lsb - s->sh.pic_order_cnt_lsb;
if (poc != (int32_t)poc)
return AVERROR_INVALIDDATA;
rps->poc[i] = poc;
prev_delta_msb = delta;
}
}
return 0;
}
static void export_stream_params(AVCodecContext *avctx, const HEVCParamSets *ps,
const HEVCSPS *sps)
{
const HEVCVPS *vps = (const HEVCVPS*)ps->vps_list[sps->vps_id]->data;
const HEVCWindow *ow = &sps->output_window;
unsigned int num = 0, den = 0;
avctx->pix_fmt = sps->pix_fmt;
avctx->coded_width = sps->width;
avctx->coded_height = sps->height;
avctx->width = sps->width - ow->left_offset - ow->right_offset;
avctx->height = sps->height - ow->top_offset - ow->bottom_offset;
avctx->has_b_frames = sps->temporal_layer[sps->max_sub_layers - 1].num_reorder_pics;
avctx->profile = sps->ptl.general_ptl.profile_idc;
avctx->level = sps->ptl.general_ptl.level_idc;
ff_set_sar(avctx, sps->vui.sar);
if (sps->vui.video_signal_type_present_flag)
avctx->color_range = sps->vui.video_full_range_flag ? AVCOL_RANGE_JPEG
: AVCOL_RANGE_MPEG;
else
avctx->color_range = AVCOL_RANGE_MPEG;
if (sps->vui.colour_description_present_flag) {
avctx->color_primaries = sps->vui.colour_primaries;
avctx->color_trc = sps->vui.transfer_characteristic;
avctx->colorspace = sps->vui.matrix_coeffs;
} else {
avctx->color_primaries = AVCOL_PRI_UNSPECIFIED;
avctx->color_trc = AVCOL_TRC_UNSPECIFIED;
avctx->colorspace = AVCOL_SPC_UNSPECIFIED;
}
if (vps->vps_timing_info_present_flag) {
num = vps->vps_num_units_in_tick;
den = vps->vps_time_scale;
} else if (sps->vui.vui_timing_info_present_flag) {
num = sps->vui.vui_num_units_in_tick;
den = sps->vui.vui_time_scale;
}
if (num != 0 && den != 0)
av_reduce(&avctx->framerate.den, &avctx->framerate.num,
num, den, 1 << 30);
}
static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
{
#define HWACCEL_MAX (CONFIG_HEVC_DXVA2_HWACCEL + \
CONFIG_HEVC_D3D11VA_HWACCEL * 2 + \
CONFIG_HEVC_NVDEC_HWACCEL + \
CONFIG_HEVC_VAAPI_HWACCEL + \
CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL + \
CONFIG_HEVC_VDPAU_HWACCEL)
enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
switch (sps->pix_fmt) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUVJ420P:
#if CONFIG_HEVC_DXVA2_HWACCEL
*fmt++ = AV_PIX_FMT_DXVA2_VLD;
#endif
#if CONFIG_HEVC_D3D11VA_HWACCEL
*fmt++ = AV_PIX_FMT_D3D11VA_VLD;
*fmt++ = AV_PIX_FMT_D3D11;
#endif
#if CONFIG_HEVC_VAAPI_HWACCEL
*fmt++ = AV_PIX_FMT_VAAPI;
#endif
#if CONFIG_HEVC_VDPAU_HWACCEL
*fmt++ = AV_PIX_FMT_VDPAU;
#endif
#if CONFIG_HEVC_NVDEC_HWACCEL
*fmt++ = AV_PIX_FMT_CUDA;
#endif
#if CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL
*fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
#endif
break;
case AV_PIX_FMT_YUV420P10:
#if CONFIG_HEVC_DXVA2_HWACCEL
*fmt++ = AV_PIX_FMT_DXVA2_VLD;
#endif
#if CONFIG_HEVC_D3D11VA_HWACCEL
*fmt++ = AV_PIX_FMT_D3D11VA_VLD;
*fmt++ = AV_PIX_FMT_D3D11;
#endif
#if CONFIG_HEVC_VAAPI_HWACCEL
*fmt++ = AV_PIX_FMT_VAAPI;
#endif
#if CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL
*fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
#endif
#if CONFIG_HEVC_NVDEC_HWACCEL
*fmt++ = AV_PIX_FMT_CUDA;
#endif
break;
case AV_PIX_FMT_YUV420P12:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_YUV444P10:
case AV_PIX_FMT_YUV444P12:
#if CONFIG_HEVC_NVDEC_HWACCEL
*fmt++ = AV_PIX_FMT_CUDA;
#endif
break;
}
*fmt++ = sps->pix_fmt;
*fmt = AV_PIX_FMT_NONE;
return ff_thread_get_format(s->avctx, pix_fmts);
}
static int set_sps(HEVCContext *s, const HEVCSPS *sps,
enum AVPixelFormat pix_fmt)
{
int ret, i;
pic_arrays_free(s);
s->ps.sps = NULL;
s->ps.vps = NULL;
if (!sps)
return 0;
ret = pic_arrays_init(s, sps);
if (ret < 0)
goto fail;
export_stream_params(s->avctx, &s->ps, sps);
s->avctx->pix_fmt = pix_fmt;
ff_hevc_pred_init(&s->hpc, sps->bit_depth);
ff_hevc_dsp_init (&s->hevcdsp, sps->bit_depth);
ff_videodsp_init (&s->vdsp, sps->bit_depth);
for (i = 0; i < 3; i++) {
av_freep(&s->sao_pixel_buffer_h[i]);
av_freep(&s->sao_pixel_buffer_v[i]);
}
if (sps->sao_enabled && !s->avctx->hwaccel) {
int c_count = (sps->chroma_format_idc != 0) ? 3 : 1;
int c_idx;
for(c_idx = 0; c_idx < c_count; c_idx++) {
int w = sps->width >> sps->hshift[c_idx];
int h = sps->height >> sps->vshift[c_idx];
s->sao_pixel_buffer_h[c_idx] =
av_malloc((w * 2 * sps->ctb_height) <<
sps->pixel_shift);
s->sao_pixel_buffer_v[c_idx] =
av_malloc((h * 2 * sps->ctb_width) <<
sps->pixel_shift);
}
}
s->ps.sps = sps;
s->ps.vps = (HEVCVPS*) s->ps.vps_list[s->ps.sps->vps_id]->data;
return 0;
fail:
pic_arrays_free(s);
s->ps.sps = NULL;
return ret;
}
static int hls_slice_header(HEVCContext *s)
{
GetBitContext *gb = &s->HEVClc->gb;
SliceHeader *sh = &s->sh;
int i, ret;
// Coded parameters
sh->first_slice_in_pic_flag = get_bits1(gb);
if (s->ref && sh->first_slice_in_pic_flag) {
av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n");
return 1; // This slice will be skiped later, do not corrupt state
}
if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) {
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
if (IS_IDR(s))
ff_hevc_clear_refs(s);
}
sh->no_output_of_prior_pics_flag = 0;
if (IS_IRAP(s))
sh->no_output_of_prior_pics_flag = get_bits1(gb);
sh->pps_id = get_ue_golomb_long(gb);
if (sh->pps_id >= HEVC_MAX_PPS_COUNT || !s->ps.pps_list[sh->pps_id]) {
av_log(s->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);
return AVERROR_INVALIDDATA;
}
if (!sh->first_slice_in_pic_flag &&
s->ps.pps != (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data) {
av_log(s->avctx, AV_LOG_ERROR, "PPS changed between slices.\n");
return AVERROR_INVALIDDATA;
}
s->ps.pps = (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data;
if (s->nal_unit_type == HEVC_NAL_CRA_NUT && s->last_eos == 1)
sh->no_output_of_prior_pics_flag = 1;
if (s->ps.sps != (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data) {
const HEVCSPS *sps = (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data;
const HEVCSPS *last_sps = s->ps.sps;
enum AVPixelFormat pix_fmt;
if (last_sps && IS_IRAP(s) && s->nal_unit_type != HEVC_NAL_CRA_NUT) {
if (sps->width != last_sps->width || sps->height != last_sps->height ||
sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering !=
last_sps->temporal_layer[last_sps->max_sub_layers - 1].max_dec_pic_buffering)
sh->no_output_of_prior_pics_flag = 0;
}
ff_hevc_clear_refs(s);
ret = set_sps(s, sps, sps->pix_fmt);
if (ret < 0)
return ret;
pix_fmt = get_format(s, sps);
if (pix_fmt < 0)
return pix_fmt;
s->avctx->pix_fmt = pix_fmt;
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
}
sh->dependent_slice_segment_flag = 0;
if (!sh->first_slice_in_pic_flag) {
int slice_address_length;
if (s->ps.pps->dependent_slice_segments_enabled_flag)
sh->dependent_slice_segment_flag = get_bits1(gb);
slice_address_length = av_ceil_log2(s->ps.sps->ctb_width *
s->ps.sps->ctb_height);
sh->slice_segment_addr = get_bitsz(gb, slice_address_length);
if (sh->slice_segment_addr >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid slice segment address: %u.\n",
sh->slice_segment_addr);
return AVERROR_INVALIDDATA;
}
if (!sh->dependent_slice_segment_flag) {
sh->slice_addr = sh->slice_segment_addr;
s->slice_idx++;
}
} else {
sh->slice_segment_addr = sh->slice_addr = 0;
s->slice_idx = 0;
s->slice_initialized = 0;
}
if (!sh->dependent_slice_segment_flag) {
s->slice_initialized = 0;
for (i = 0; i < s->ps.pps->num_extra_slice_header_bits; i++)
skip_bits(gb, 1); // slice_reserved_undetermined_flag[]
sh->slice_type = get_ue_golomb_long(gb);
if (!(sh->slice_type == HEVC_SLICE_I ||
sh->slice_type == HEVC_SLICE_P ||
sh->slice_type == HEVC_SLICE_B)) {
av_log(s->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",
sh->slice_type);
return AVERROR_INVALIDDATA;
}
if (IS_IRAP(s) && sh->slice_type != HEVC_SLICE_I) {
av_log(s->avctx, AV_LOG_ERROR, "Inter slices in an IRAP frame.\n");
return AVERROR_INVALIDDATA;
}
// when flag is not present, picture is inferred to be output
sh->pic_output_flag = 1;
if (s->ps.pps->output_flag_present_flag)
sh->pic_output_flag = get_bits1(gb);
if (s->ps.sps->separate_colour_plane_flag)
sh->colour_plane_id = get_bits(gb, 2);
if (!IS_IDR(s)) {
int poc, pos;
sh->pic_order_cnt_lsb = get_bits(gb, s->ps.sps->log2_max_poc_lsb);
poc = ff_hevc_compute_poc(s->ps.sps, s->pocTid0, sh->pic_order_cnt_lsb, s->nal_unit_type);
if (!sh->first_slice_in_pic_flag && poc != s->poc) {
av_log(s->avctx, AV_LOG_WARNING,
"Ignoring POC change between slices: %d -> %d\n", s->poc, poc);
if (s->avctx->err_recognition & AV_EF_EXPLODE)
return AVERROR_INVALIDDATA;
poc = s->poc;
}
s->poc = poc;
sh->short_term_ref_pic_set_sps_flag = get_bits1(gb);
pos = get_bits_left(gb);
if (!sh->short_term_ref_pic_set_sps_flag) {
ret = ff_hevc_decode_short_term_rps(gb, s->avctx, &sh->slice_rps, s->ps.sps, 1);
if (ret < 0)
return ret;
sh->short_term_rps = &sh->slice_rps;
} else {
int numbits, rps_idx;
if (!s->ps.sps->nb_st_rps) {
av_log(s->avctx, AV_LOG_ERROR, "No ref lists in the SPS.\n");
return AVERROR_INVALIDDATA;
}
numbits = av_ceil_log2(s->ps.sps->nb_st_rps);
rps_idx = numbits > 0 ? get_bits(gb, numbits) : 0;
sh->short_term_rps = &s->ps.sps->st_rps[rps_idx];
}
sh->short_term_ref_pic_set_size = pos - get_bits_left(gb);
pos = get_bits_left(gb);
ret = decode_lt_rps(s, &sh->long_term_rps, gb);
if (ret < 0) {
av_log(s->avctx, AV_LOG_WARNING, "Invalid long term RPS.\n");
if (s->avctx->err_recognition & AV_EF_EXPLODE)
return AVERROR_INVALIDDATA;
}
sh->long_term_ref_pic_set_size = pos - get_bits_left(gb);
if (s->ps.sps->sps_temporal_mvp_enabled_flag)
sh->slice_temporal_mvp_enabled_flag = get_bits1(gb);
else
sh->slice_temporal_mvp_enabled_flag = 0;
} else {
s->sh.short_term_rps = NULL;
s->poc = 0;
}
/* 8.3.1 */
if (sh->first_slice_in_pic_flag && s->temporal_id == 0 &&
s->nal_unit_type != HEVC_NAL_TRAIL_N &&
s->nal_unit_type != HEVC_NAL_TSA_N &&
s->nal_unit_type != HEVC_NAL_STSA_N &&
s->nal_unit_type != HEVC_NAL_RADL_N &&
s->nal_unit_type != HEVC_NAL_RADL_R &&
s->nal_unit_type != HEVC_NAL_RASL_N &&
s->nal_unit_type != HEVC_NAL_RASL_R)
s->pocTid0 = s->poc;
if (s->ps.sps->sao_enabled) {
sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb);
if (s->ps.sps->chroma_format_idc) {
sh->slice_sample_adaptive_offset_flag[1] =
sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb);
}
} else {
sh->slice_sample_adaptive_offset_flag[0] = 0;
sh->slice_sample_adaptive_offset_flag[1] = 0;
sh->slice_sample_adaptive_offset_flag[2] = 0;
}
sh->nb_refs[L0] = sh->nb_refs[L1] = 0;
if (sh->slice_type == HEVC_SLICE_P || sh->slice_type == HEVC_SLICE_B) {
int nb_refs;
sh->nb_refs[L0] = s->ps.pps->num_ref_idx_l0_default_active;
if (sh->slice_type == HEVC_SLICE_B)
sh->nb_refs[L1] = s->ps.pps->num_ref_idx_l1_default_active;
if (get_bits1(gb)) { // num_ref_idx_active_override_flag
sh->nb_refs[L0] = get_ue_golomb_long(gb) + 1;
if (sh->slice_type == HEVC_SLICE_B)
sh->nb_refs[L1] = get_ue_golomb_long(gb) + 1;
}
if (sh->nb_refs[L0] > HEVC_MAX_REFS || sh->nb_refs[L1] > HEVC_MAX_REFS) {
av_log(s->avctx, AV_LOG_ERROR, "Too many refs: %d/%d.\n",
sh->nb_refs[L0], sh->nb_refs[L1]);
return AVERROR_INVALIDDATA;
}
sh->rpl_modification_flag[0] = 0;
sh->rpl_modification_flag[1] = 0;
nb_refs = ff_hevc_frame_nb_refs(s);
if (!nb_refs) {
av_log(s->avctx, AV_LOG_ERROR, "Zero refs for a frame with P or B slices.\n");
return AVERROR_INVALIDDATA;
}
if (s->ps.pps->lists_modification_present_flag && nb_refs > 1) {
sh->rpl_modification_flag[0] = get_bits1(gb);
if (sh->rpl_modification_flag[0]) {
for (i = 0; i < sh->nb_refs[L0]; i++)
sh->list_entry_lx[0][i] = get_bits(gb, av_ceil_log2(nb_refs));
}
if (sh->slice_type == HEVC_SLICE_B) {
sh->rpl_modification_flag[1] = get_bits1(gb);
if (sh->rpl_modification_flag[1] == 1)
for (i = 0; i < sh->nb_refs[L1]; i++)
sh->list_entry_lx[1][i] = get_bits(gb, av_ceil_log2(nb_refs));
}
}
if (sh->slice_type == HEVC_SLICE_B)
sh->mvd_l1_zero_flag = get_bits1(gb);
if (s->ps.pps->cabac_init_present_flag)
sh->cabac_init_flag = get_bits1(gb);
else
sh->cabac_init_flag = 0;
sh->collocated_ref_idx = 0;
if (sh->slice_temporal_mvp_enabled_flag) {
sh->collocated_list = L0;
if (sh->slice_type == HEVC_SLICE_B)
sh->collocated_list = !get_bits1(gb);
if (sh->nb_refs[sh->collocated_list] > 1) {
sh->collocated_ref_idx = get_ue_golomb_long(gb);
if (sh->collocated_ref_idx >= sh->nb_refs[sh->collocated_list]) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid collocated_ref_idx: %d.\n",
sh->collocated_ref_idx);
return AVERROR_INVALIDDATA;
}
}
}
if ((s->ps.pps->weighted_pred_flag && sh->slice_type == HEVC_SLICE_P) ||
(s->ps.pps->weighted_bipred_flag && sh->slice_type == HEVC_SLICE_B)) {
int ret = pred_weight_table(s, gb);
if (ret < 0)
return ret;
}
sh->max_num_merge_cand = 5 - get_ue_golomb_long(gb);
if (sh->max_num_merge_cand < 1 || sh->max_num_merge_cand > 5) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid number of merging MVP candidates: %d.\n",
sh->max_num_merge_cand);
return AVERROR_INVALIDDATA;
}
}
sh->slice_qp_delta = get_se_golomb(gb);
if (s->ps.pps->pic_slice_level_chroma_qp_offsets_present_flag) {
sh->slice_cb_qp_offset = get_se_golomb(gb);
sh->slice_cr_qp_offset = get_se_golomb(gb);
} else {
sh->slice_cb_qp_offset = 0;
sh->slice_cr_qp_offset = 0;
}
if (s->ps.pps->chroma_qp_offset_list_enabled_flag)
sh->cu_chroma_qp_offset_enabled_flag = get_bits1(gb);
else
sh->cu_chroma_qp_offset_enabled_flag = 0;
if (s->ps.pps->deblocking_filter_control_present_flag) {
int deblocking_filter_override_flag = 0;
if (s->ps.pps->deblocking_filter_override_enabled_flag)
deblocking_filter_override_flag = get_bits1(gb);
if (deblocking_filter_override_flag) {
sh->disable_deblocking_filter_flag = get_bits1(gb);
if (!sh->disable_deblocking_filter_flag) {
int beta_offset_div2 = get_se_golomb(gb);
int tc_offset_div2 = get_se_golomb(gb) ;
if (beta_offset_div2 < -6 || beta_offset_div2 > 6 ||
tc_offset_div2 < -6 || tc_offset_div2 > 6) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid deblock filter offsets: %d, %d\n",
beta_offset_div2, tc_offset_div2);
return AVERROR_INVALIDDATA;
}
sh->beta_offset = beta_offset_div2 * 2;
sh->tc_offset = tc_offset_div2 * 2;
}
} else {
sh->disable_deblocking_filter_flag = s->ps.pps->disable_dbf;
sh->beta_offset = s->ps.pps->beta_offset;
sh->tc_offset = s->ps.pps->tc_offset;
}
} else {
sh->disable_deblocking_filter_flag = 0;
sh->beta_offset = 0;
sh->tc_offset = 0;
}
if (s->ps.pps->seq_loop_filter_across_slices_enabled_flag &&
(sh->slice_sample_adaptive_offset_flag[0] ||
sh->slice_sample_adaptive_offset_flag[1] ||
!sh->disable_deblocking_filter_flag)) {
sh->slice_loop_filter_across_slices_enabled_flag = get_bits1(gb);
} else {
sh->slice_loop_filter_across_slices_enabled_flag = s->ps.pps->seq_loop_filter_across_slices_enabled_flag;
}
} else if (!s->slice_initialized) {
av_log(s->avctx, AV_LOG_ERROR, "Independent slice segment missing.\n");
return AVERROR_INVALIDDATA;
}
sh->num_entry_point_offsets = 0;
if (s->ps.pps->tiles_enabled_flag || s->ps.pps->entropy_coding_sync_enabled_flag) {
unsigned num_entry_point_offsets = get_ue_golomb_long(gb);
// It would be possible to bound this tighter but this here is simpler
if (num_entry_point_offsets > get_bits_left(gb)) {
av_log(s->avctx, AV_LOG_ERROR, "num_entry_point_offsets %d is invalid\n", num_entry_point_offsets);
return AVERROR_INVALIDDATA;
}
sh->num_entry_point_offsets = num_entry_point_offsets;
if (sh->num_entry_point_offsets > 0) {
int offset_len = get_ue_golomb_long(gb) + 1;
if (offset_len < 1 || offset_len > 32) {
sh->num_entry_point_offsets = 0;
av_log(s->avctx, AV_LOG_ERROR, "offset_len %d is invalid\n", offset_len);
return AVERROR_INVALIDDATA;
}
av_freep(&sh->entry_point_offset);
av_freep(&sh->offset);
av_freep(&sh->size);
sh->entry_point_offset = av_malloc_array(sh->num_entry_point_offsets, sizeof(unsigned));
sh->offset = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));
sh->size = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));
if (!sh->entry_point_offset || !sh->offset || !sh->size) {
sh->num_entry_point_offsets = 0;
av_log(s->avctx, AV_LOG_ERROR, "Failed to allocate memory\n");
return AVERROR(ENOMEM);
}
for (i = 0; i < sh->num_entry_point_offsets; i++) {
unsigned val = get_bits_long(gb, offset_len);
sh->entry_point_offset[i] = val + 1; // +1; // +1 to get the size
}
if (s->threads_number > 1 && (s->ps.pps->num_tile_rows > 1 || s->ps.pps->num_tile_columns > 1)) {
s->enable_parallel_tiles = 0; // TODO: you can enable tiles in parallel here
s->threads_number = 1;
} else
s->enable_parallel_tiles = 0;
} else
s->enable_parallel_tiles = 0;
}
if (s->ps.pps->slice_header_extension_present_flag) {
unsigned int length = get_ue_golomb_long(gb);
if (length*8LL > get_bits_left(gb)) {
av_log(s->avctx, AV_LOG_ERROR, "too many slice_header_extension_data_bytes\n");
return AVERROR_INVALIDDATA;
}
for (i = 0; i < length; i++)
skip_bits(gb, 8); // slice_header_extension_data_byte
}
// Inferred parameters
sh->slice_qp = 26U + s->ps.pps->pic_init_qp_minus26 + sh->slice_qp_delta;
if (sh->slice_qp > 51 ||
sh->slice_qp < -s->ps.sps->qp_bd_offset) {
av_log(s->avctx, AV_LOG_ERROR,
"The slice_qp %d is outside the valid range "
"[%d, 51].\n",
sh->slice_qp,
-s->ps.sps->qp_bd_offset);
return AVERROR_INVALIDDATA;
}
sh->slice_ctb_addr_rs = sh->slice_segment_addr;
if (!s->sh.slice_ctb_addr_rs && s->sh.dependent_slice_segment_flag) {
av_log(s->avctx, AV_LOG_ERROR, "Impossible slice segment.\n");
return AVERROR_INVALIDDATA;
}
if (get_bits_left(gb) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Overread slice header by %d bits\n", -get_bits_left(gb));
return AVERROR_INVALIDDATA;
}
s->HEVClc->first_qp_group = !s->sh.dependent_slice_segment_flag;
if (!s->ps.pps->cu_qp_delta_enabled_flag)
s->HEVClc->qp_y = s->sh.slice_qp;
s->slice_initialized = 1;
s->HEVClc->tu.cu_qp_offset_cb = 0;
s->HEVClc->tu.cu_qp_offset_cr = 0;
return 0;
}
#define CTB(tab, x, y) ((tab)[(y) * s->ps.sps->ctb_width + (x)])
#define SET_SAO(elem, value) \
do { \
if (!sao_merge_up_flag && !sao_merge_left_flag) \
sao->elem = value; \
else if (sao_merge_left_flag) \
sao->elem = CTB(s->sao, rx-1, ry).elem; \
else if (sao_merge_up_flag) \
sao->elem = CTB(s->sao, rx, ry-1).elem; \
else \
sao->elem = 0; \
} while (0)
static void hls_sao_param(HEVCContext *s, int rx, int ry)
{
HEVCLocalContext *lc = s->HEVClc;
int sao_merge_left_flag = 0;
int sao_merge_up_flag = 0;
SAOParams *sao = &CTB(s->sao, rx, ry);
int c_idx, i;
if (s->sh.slice_sample_adaptive_offset_flag[0] ||
s->sh.slice_sample_adaptive_offset_flag[1]) {
if (rx > 0) {
if (lc->ctb_left_flag)
sao_merge_left_flag = ff_hevc_sao_merge_flag_decode(s);
}
if (ry > 0 && !sao_merge_left_flag) {
if (lc->ctb_up_flag)
sao_merge_up_flag = ff_hevc_sao_merge_flag_decode(s);
}
}
for (c_idx = 0; c_idx < (s->ps.sps->chroma_format_idc ? 3 : 1); c_idx++) {
int log2_sao_offset_scale = c_idx == 0 ? s->ps.pps->log2_sao_offset_scale_luma :
s->ps.pps->log2_sao_offset_scale_chroma;
if (!s->sh.slice_sample_adaptive_offset_flag[c_idx]) {
sao->type_idx[c_idx] = SAO_NOT_APPLIED;
continue;
}
if (c_idx == 2) {
sao->type_idx[2] = sao->type_idx[1];
sao->eo_class[2] = sao->eo_class[1];
} else {
SET_SAO(type_idx[c_idx], ff_hevc_sao_type_idx_decode(s));
}
if (sao->type_idx[c_idx] == SAO_NOT_APPLIED)
continue;
for (i = 0; i < 4; i++)
SET_SAO(offset_abs[c_idx][i], ff_hevc_sao_offset_abs_decode(s));
if (sao->type_idx[c_idx] == SAO_BAND) {
for (i = 0; i < 4; i++) {
if (sao->offset_abs[c_idx][i]) {
SET_SAO(offset_sign[c_idx][i],
ff_hevc_sao_offset_sign_decode(s));
} else {
sao->offset_sign[c_idx][i] = 0;
}
}
SET_SAO(band_position[c_idx], ff_hevc_sao_band_position_decode(s));
} else if (c_idx != 2) {
SET_SAO(eo_class[c_idx], ff_hevc_sao_eo_class_decode(s));
}
// Inferred parameters
sao->offset_val[c_idx][0] = 0;
for (i = 0; i < 4; i++) {
sao->offset_val[c_idx][i + 1] = sao->offset_abs[c_idx][i];
if (sao->type_idx[c_idx] == SAO_EDGE) {
if (i > 1)
sao->offset_val[c_idx][i + 1] = -sao->offset_val[c_idx][i + 1];
} else if (sao->offset_sign[c_idx][i]) {
sao->offset_val[c_idx][i + 1] = -sao->offset_val[c_idx][i + 1];
}
sao->offset_val[c_idx][i + 1] *= 1 << log2_sao_offset_scale;
}
}
}
#undef SET_SAO
#undef CTB
static int hls_cross_component_pred(HEVCContext *s, int idx) {
HEVCLocalContext *lc = s->HEVClc;
int log2_res_scale_abs_plus1 = ff_hevc_log2_res_scale_abs(s, idx);
if (log2_res_scale_abs_plus1 != 0) {
int res_scale_sign_flag = ff_hevc_res_scale_sign_flag(s, idx);
lc->tu.res_scale_val = (1 << (log2_res_scale_abs_plus1 - 1)) *
(1 - 2 * res_scale_sign_flag);
} else {
lc->tu.res_scale_val = 0;
}
return 0;
}
static int hls_transform_unit(HEVCContext *s, int x0, int y0,
int xBase, int yBase, int cb_xBase, int cb_yBase,
int log2_cb_size, int log2_trafo_size,
int blk_idx, int cbf_luma, int *cbf_cb, int *cbf_cr)
{
HEVCLocalContext *lc = s->HEVClc;
const int log2_trafo_size_c = log2_trafo_size - s->ps.sps->hshift[1];
int i;
if (lc->cu.pred_mode == MODE_INTRA) {
int trafo_size = 1 << log2_trafo_size;
ff_hevc_set_neighbour_available(s, x0, y0, trafo_size, trafo_size);
s->hpc.intra_pred[log2_trafo_size - 2](s, x0, y0, 0);
}
if (cbf_luma || cbf_cb[0] || cbf_cr[0] ||
(s->ps.sps->chroma_format_idc == 2 && (cbf_cb[1] || cbf_cr[1]))) {
int scan_idx = SCAN_DIAG;
int scan_idx_c = SCAN_DIAG;
int cbf_chroma = cbf_cb[0] || cbf_cr[0] ||
(s->ps.sps->chroma_format_idc == 2 &&
(cbf_cb[1] || cbf_cr[1]));
if (s->ps.pps->cu_qp_delta_enabled_flag && !lc->tu.is_cu_qp_delta_coded) {
lc->tu.cu_qp_delta = ff_hevc_cu_qp_delta_abs(s);
if (lc->tu.cu_qp_delta != 0)
if (ff_hevc_cu_qp_delta_sign_flag(s) == 1)
lc->tu.cu_qp_delta = -lc->tu.cu_qp_delta;
lc->tu.is_cu_qp_delta_coded = 1;
if (lc->tu.cu_qp_delta < -(26 + s->ps.sps->qp_bd_offset / 2) ||
lc->tu.cu_qp_delta > (25 + s->ps.sps->qp_bd_offset / 2)) {
av_log(s->avctx, AV_LOG_ERROR,
"The cu_qp_delta %d is outside the valid range "
"[%d, %d].\n",
lc->tu.cu_qp_delta,
-(26 + s->ps.sps->qp_bd_offset / 2),
(25 + s->ps.sps->qp_bd_offset / 2));
return AVERROR_INVALIDDATA;
}
ff_hevc_set_qPy(s, cb_xBase, cb_yBase, log2_cb_size);
}
if (s->sh.cu_chroma_qp_offset_enabled_flag && cbf_chroma &&
!lc->cu.cu_transquant_bypass_flag && !lc->tu.is_cu_chroma_qp_offset_coded) {
int cu_chroma_qp_offset_flag = ff_hevc_cu_chroma_qp_offset_flag(s);
if (cu_chroma_qp_offset_flag) {
int cu_chroma_qp_offset_idx = 0;
if (s->ps.pps->chroma_qp_offset_list_len_minus1 > 0) {
cu_chroma_qp_offset_idx = ff_hevc_cu_chroma_qp_offset_idx(s);
av_log(s->avctx, AV_LOG_ERROR,
"cu_chroma_qp_offset_idx not yet tested.\n");
}
lc->tu.cu_qp_offset_cb = s->ps.pps->cb_qp_offset_list[cu_chroma_qp_offset_idx];
lc->tu.cu_qp_offset_cr = s->ps.pps->cr_qp_offset_list[cu_chroma_qp_offset_idx];
} else {
lc->tu.cu_qp_offset_cb = 0;
lc->tu.cu_qp_offset_cr = 0;
}
lc->tu.is_cu_chroma_qp_offset_coded = 1;
}
if (lc->cu.pred_mode == MODE_INTRA && log2_trafo_size < 4) {
if (lc->tu.intra_pred_mode >= 6 &&
lc->tu.intra_pred_mode <= 14) {
scan_idx = SCAN_VERT;
} else if (lc->tu.intra_pred_mode >= 22 &&
lc->tu.intra_pred_mode <= 30) {
scan_idx = SCAN_HORIZ;
}
if (lc->tu.intra_pred_mode_c >= 6 &&
lc->tu.intra_pred_mode_c <= 14) {
scan_idx_c = SCAN_VERT;
} else if (lc->tu.intra_pred_mode_c >= 22 &&
lc->tu.intra_pred_mode_c <= 30) {
scan_idx_c = SCAN_HORIZ;
}
}
lc->tu.cross_pf = 0;
if (cbf_luma)
ff_hevc_hls_residual_coding(s, x0, y0, log2_trafo_size, scan_idx, 0);
if (s->ps.sps->chroma_format_idc && (log2_trafo_size > 2 || s->ps.sps->chroma_format_idc == 3)) {
int trafo_size_h = 1 << (log2_trafo_size_c + s->ps.sps->hshift[1]);
int trafo_size_v = 1 << (log2_trafo_size_c + s->ps.sps->vshift[1]);
lc->tu.cross_pf = (s->ps.pps->cross_component_prediction_enabled_flag && cbf_luma &&
(lc->cu.pred_mode == MODE_INTER ||
(lc->tu.chroma_mode_c == 4)));
if (lc->tu.cross_pf) {
hls_cross_component_pred(s, 0);
}
for (i = 0; i < (s->ps.sps->chroma_format_idc == 2 ? 2 : 1); i++) {
if (lc->cu.pred_mode == MODE_INTRA) {
ff_hevc_set_neighbour_available(s, x0, y0 + (i << log2_trafo_size_c), trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size_c - 2](s, x0, y0 + (i << log2_trafo_size_c), 1);
}
if (cbf_cb[i])
ff_hevc_hls_residual_coding(s, x0, y0 + (i << log2_trafo_size_c),
log2_trafo_size_c, scan_idx_c, 1);
else
if (lc->tu.cross_pf) {
ptrdiff_t stride = s->frame->linesize[1];
int hshift = s->ps.sps->hshift[1];
int vshift = s->ps.sps->vshift[1];
int16_t *coeffs_y = (int16_t*)lc->edge_emu_buffer;
int16_t *coeffs = (int16_t*)lc->edge_emu_buffer2;
int size = 1 << log2_trafo_size_c;
uint8_t *dst = &s->frame->data[1][(y0 >> vshift) * stride +
((x0 >> hshift) << s->ps.sps->pixel_shift)];
for (i = 0; i < (size * size); i++) {
coeffs[i] = ((lc->tu.res_scale_val * coeffs_y[i]) >> 3);
}
s->hevcdsp.add_residual[log2_trafo_size_c-2](dst, coeffs, stride);
}
}
if (lc->tu.cross_pf) {
hls_cross_component_pred(s, 1);
}
for (i = 0; i < (s->ps.sps->chroma_format_idc == 2 ? 2 : 1); i++) {
if (lc->cu.pred_mode == MODE_INTRA) {
ff_hevc_set_neighbour_available(s, x0, y0 + (i << log2_trafo_size_c), trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size_c - 2](s, x0, y0 + (i << log2_trafo_size_c), 2);
}
if (cbf_cr[i])
ff_hevc_hls_residual_coding(s, x0, y0 + (i << log2_trafo_size_c),
log2_trafo_size_c, scan_idx_c, 2);
else
if (lc->tu.cross_pf) {
ptrdiff_t stride = s->frame->linesize[2];
int hshift = s->ps.sps->hshift[2];
int vshift = s->ps.sps->vshift[2];
int16_t *coeffs_y = (int16_t*)lc->edge_emu_buffer;
int16_t *coeffs = (int16_t*)lc->edge_emu_buffer2;
int size = 1 << log2_trafo_size_c;
uint8_t *dst = &s->frame->data[2][(y0 >> vshift) * stride +
((x0 >> hshift) << s->ps.sps->pixel_shift)];
for (i = 0; i < (size * size); i++) {
coeffs[i] = ((lc->tu.res_scale_val * coeffs_y[i]) >> 3);
}
s->hevcdsp.add_residual[log2_trafo_size_c-2](dst, coeffs, stride);
}
}
} else if (s->ps.sps->chroma_format_idc && blk_idx == 3) {
int trafo_size_h = 1 << (log2_trafo_size + 1);
int trafo_size_v = 1 << (log2_trafo_size + s->ps.sps->vshift[1]);
for (i = 0; i < (s->ps.sps->chroma_format_idc == 2 ? 2 : 1); i++) {
if (lc->cu.pred_mode == MODE_INTRA) {
ff_hevc_set_neighbour_available(s, xBase, yBase + (i << log2_trafo_size),
trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size - 2](s, xBase, yBase + (i << log2_trafo_size), 1);
}
if (cbf_cb[i])
ff_hevc_hls_residual_coding(s, xBase, yBase + (i << log2_trafo_size),
log2_trafo_size, scan_idx_c, 1);
}
for (i = 0; i < (s->ps.sps->chroma_format_idc == 2 ? 2 : 1); i++) {
if (lc->cu.pred_mode == MODE_INTRA) {
ff_hevc_set_neighbour_available(s, xBase, yBase + (i << log2_trafo_size),
trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size - 2](s, xBase, yBase + (i << log2_trafo_size), 2);
}
if (cbf_cr[i])
ff_hevc_hls_residual_coding(s, xBase, yBase + (i << log2_trafo_size),
log2_trafo_size, scan_idx_c, 2);
}
}
} else if (s->ps.sps->chroma_format_idc && lc->cu.pred_mode == MODE_INTRA) {
if (log2_trafo_size > 2 || s->ps.sps->chroma_format_idc == 3) {
int trafo_size_h = 1 << (log2_trafo_size_c + s->ps.sps->hshift[1]);
int trafo_size_v = 1 << (log2_trafo_size_c + s->ps.sps->vshift[1]);
ff_hevc_set_neighbour_available(s, x0, y0, trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size_c - 2](s, x0, y0, 1);
s->hpc.intra_pred[log2_trafo_size_c - 2](s, x0, y0, 2);
if (s->ps.sps->chroma_format_idc == 2) {
ff_hevc_set_neighbour_available(s, x0, y0 + (1 << log2_trafo_size_c),
trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size_c - 2](s, x0, y0 + (1 << log2_trafo_size_c), 1);
s->hpc.intra_pred[log2_trafo_size_c - 2](s, x0, y0 + (1 << log2_trafo_size_c), 2);
}
} else if (blk_idx == 3) {
int trafo_size_h = 1 << (log2_trafo_size + 1);
int trafo_size_v = 1 << (log2_trafo_size + s->ps.sps->vshift[1]);
ff_hevc_set_neighbour_available(s, xBase, yBase,
trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size - 2](s, xBase, yBase, 1);
s->hpc.intra_pred[log2_trafo_size - 2](s, xBase, yBase, 2);
if (s->ps.sps->chroma_format_idc == 2) {
ff_hevc_set_neighbour_available(s, xBase, yBase + (1 << (log2_trafo_size)),
trafo_size_h, trafo_size_v);
s->hpc.intra_pred[log2_trafo_size - 2](s, xBase, yBase + (1 << (log2_trafo_size)), 1);
s->hpc.intra_pred[log2_trafo_size - 2](s, xBase, yBase + (1 << (log2_trafo_size)), 2);
}
}
}
return 0;
}
static void set_deblocking_bypass(HEVCContext *s, int x0, int y0, int log2_cb_size)
{
int cb_size = 1 << log2_cb_size;
int log2_min_pu_size = s->ps.sps->log2_min_pu_size;
int min_pu_width = s->ps.sps->min_pu_width;
int x_end = FFMIN(x0 + cb_size, s->ps.sps->width);
int y_end = FFMIN(y0 + cb_size, s->ps.sps->height);
int i, j;
for (j = (y0 >> log2_min_pu_size); j < (y_end >> log2_min_pu_size); j++)
for (i = (x0 >> log2_min_pu_size); i < (x_end >> log2_min_pu_size); i++)
s->is_pcm[i + j * min_pu_width] = 2;
}
static int hls_transform_tree(HEVCContext *s, int x0, int y0,
int xBase, int yBase, int cb_xBase, int cb_yBase,
int log2_cb_size, int log2_trafo_size,
int trafo_depth, int blk_idx,
const int *base_cbf_cb, const int *base_cbf_cr)
{
HEVCLocalContext *lc = s->HEVClc;
uint8_t split_transform_flag;
int cbf_cb[2];
int cbf_cr[2];
int ret;
cbf_cb[0] = base_cbf_cb[0];
cbf_cb[1] = base_cbf_cb[1];
cbf_cr[0] = base_cbf_cr[0];
cbf_cr[1] = base_cbf_cr[1];
if (lc->cu.intra_split_flag) {
if (trafo_depth == 1) {
lc->tu.intra_pred_mode = lc->pu.intra_pred_mode[blk_idx];
if (s->ps.sps->chroma_format_idc == 3) {
lc->tu.intra_pred_mode_c = lc->pu.intra_pred_mode_c[blk_idx];
lc->tu.chroma_mode_c = lc->pu.chroma_mode_c[blk_idx];
} else {
lc->tu.intra_pred_mode_c = lc->pu.intra_pred_mode_c[0];
lc->tu.chroma_mode_c = lc->pu.chroma_mode_c[0];
}
}
} else {
lc->tu.intra_pred_mode = lc->pu.intra_pred_mode[0];
lc->tu.intra_pred_mode_c = lc->pu.intra_pred_mode_c[0];
lc->tu.chroma_mode_c = lc->pu.chroma_mode_c[0];
}
if (log2_trafo_size <= s->ps.sps->log2_max_trafo_size &&
log2_trafo_size > s->ps.sps->log2_min_tb_size &&
trafo_depth < lc->cu.max_trafo_depth &&
!(lc->cu.intra_split_flag && trafo_depth == 0)) {
split_transform_flag = ff_hevc_split_transform_flag_decode(s, log2_trafo_size);
} else {
int inter_split = s->ps.sps->max_transform_hierarchy_depth_inter == 0 &&
lc->cu.pred_mode == MODE_INTER &&
lc->cu.part_mode != PART_2Nx2N &&
trafo_depth == 0;
split_transform_flag = log2_trafo_size > s->ps.sps->log2_max_trafo_size ||
(lc->cu.intra_split_flag && trafo_depth == 0) ||
inter_split;
}
if (s->ps.sps->chroma_format_idc && (log2_trafo_size > 2 || s->ps.sps->chroma_format_idc == 3)) {
if (trafo_depth == 0 || cbf_cb[0]) {
cbf_cb[0] = ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
if (s->ps.sps->chroma_format_idc == 2 && (!split_transform_flag || log2_trafo_size == 3)) {
cbf_cb[1] = ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
}
}
if (trafo_depth == 0 || cbf_cr[0]) {
cbf_cr[0] = ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
if (s->ps.sps->chroma_format_idc == 2 && (!split_transform_flag || log2_trafo_size == 3)) {
cbf_cr[1] = ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
}
}
}
if (split_transform_flag) {
const int trafo_size_split = 1 << (log2_trafo_size - 1);
const int x1 = x0 + trafo_size_split;
const int y1 = y0 + trafo_size_split;
#define SUBDIVIDE(x, y, idx) \
do { \
ret = hls_transform_tree(s, x, y, x0, y0, cb_xBase, cb_yBase, log2_cb_size, \
log2_trafo_size - 1, trafo_depth + 1, idx, \
cbf_cb, cbf_cr); \
if (ret < 0) \
return ret; \
} while (0)
SUBDIVIDE(x0, y0, 0);
SUBDIVIDE(x1, y0, 1);
SUBDIVIDE(x0, y1, 2);
SUBDIVIDE(x1, y1, 3);
#undef SUBDIVIDE
} else {
int min_tu_size = 1 << s->ps.sps->log2_min_tb_size;
int log2_min_tu_size = s->ps.sps->log2_min_tb_size;
int min_tu_width = s->ps.sps->min_tb_width;
int cbf_luma = 1;
if (lc->cu.pred_mode == MODE_INTRA || trafo_depth != 0 ||
cbf_cb[0] || cbf_cr[0] ||
(s->ps.sps->chroma_format_idc == 2 && (cbf_cb[1] || cbf_cr[1]))) {
cbf_luma = ff_hevc_cbf_luma_decode(s, trafo_depth);
}
ret = hls_transform_unit(s, x0, y0, xBase, yBase, cb_xBase, cb_yBase,
log2_cb_size, log2_trafo_size,
blk_idx, cbf_luma, cbf_cb, cbf_cr);
if (ret < 0)
return ret;
// TODO: store cbf_luma somewhere else
if (cbf_luma) {
int i, j;
for (i = 0; i < (1 << log2_trafo_size); i += min_tu_size)
for (j = 0; j < (1 << log2_trafo_size); j += min_tu_size) {
int x_tu = (x0 + j) >> log2_min_tu_size;
int y_tu = (y0 + i) >> log2_min_tu_size;
s->cbf_luma[y_tu * min_tu_width + x_tu] = 1;
}
}
if (!s->sh.disable_deblocking_filter_flag) {
ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_trafo_size);
if (s->ps.pps->transquant_bypass_enable_flag &&
lc->cu.cu_transquant_bypass_flag)
set_deblocking_bypass(s, x0, y0, log2_trafo_size);
}
}
return 0;
}
static int hls_pcm_sample(HEVCContext *s, int x0, int y0, int log2_cb_size)
{
HEVCLocalContext *lc = s->HEVClc;
GetBitContext gb;
int cb_size = 1 << log2_cb_size;
ptrdiff_t stride0 = s->frame->linesize[0];
ptrdiff_t stride1 = s->frame->linesize[1];
ptrdiff_t stride2 = s->frame->linesize[2];
uint8_t *dst0 = &s->frame->data[0][y0 * stride0 + (x0 << s->ps.sps->pixel_shift)];
uint8_t *dst1 = &s->frame->data[1][(y0 >> s->ps.sps->vshift[1]) * stride1 + ((x0 >> s->ps.sps->hshift[1]) << s->ps.sps->pixel_shift)];
uint8_t *dst2 = &s->frame->data[2][(y0 >> s->ps.sps->vshift[2]) * stride2 + ((x0 >> s->ps.sps->hshift[2]) << s->ps.sps->pixel_shift)];
int length = cb_size * cb_size * s->ps.sps->pcm.bit_depth +
(((cb_size >> s->ps.sps->hshift[1]) * (cb_size >> s->ps.sps->vshift[1])) +
((cb_size >> s->ps.sps->hshift[2]) * (cb_size >> s->ps.sps->vshift[2]))) *
s->ps.sps->pcm.bit_depth_chroma;
const uint8_t *pcm = skip_bytes(&lc->cc, (length + 7) >> 3);
int ret;
if (!s->sh.disable_deblocking_filter_flag)
ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size);
ret = init_get_bits(&gb, pcm, length);
if (ret < 0)
return ret;
s->hevcdsp.put_pcm(dst0, stride0, cb_size, cb_size, &gb, s->ps.sps->pcm.bit_depth);
if (s->ps.sps->chroma_format_idc) {
s->hevcdsp.put_pcm(dst1, stride1,
cb_size >> s->ps.sps->hshift[1],
cb_size >> s->ps.sps->vshift[1],
&gb, s->ps.sps->pcm.bit_depth_chroma);
s->hevcdsp.put_pcm(dst2, stride2,
cb_size >> s->ps.sps->hshift[2],
cb_size >> s->ps.sps->vshift[2],
&gb, s->ps.sps->pcm.bit_depth_chroma);
}
return 0;
}
/**
* 8.5.3.2.2.1 Luma sample unidirectional interpolation process
*
* @param s HEVC decoding context
* @param dst target buffer for block data at block position
* @param dststride stride of the dst buffer
* @param ref reference picture buffer at origin (0, 0)
* @param mv motion vector (relative to block position) to get pixel data from
* @param x_off horizontal position of block from origin (0, 0)
* @param y_off vertical position of block from origin (0, 0)
* @param block_w width of block
* @param block_h height of block
* @param luma_weight weighting factor applied to the luma prediction
* @param luma_offset additive offset applied to the luma prediction value
*/
static void luma_mc_uni(HEVCContext *s, uint8_t *dst, ptrdiff_t dststride,
AVFrame *ref, const Mv *mv, int x_off, int y_off,
int block_w, int block_h, int luma_weight, int luma_offset)
{
HEVCLocalContext *lc = s->HEVClc;
uint8_t *src = ref->data[0];
ptrdiff_t srcstride = ref->linesize[0];
int pic_width = s->ps.sps->width;
int pic_height = s->ps.sps->height;
int mx = mv->x & 3;
int my = mv->y & 3;
int weight_flag = (s->sh.slice_type == HEVC_SLICE_P && s->ps.pps->weighted_pred_flag) ||
(s->sh.slice_type == HEVC_SLICE_B && s->ps.pps->weighted_bipred_flag);
int idx = ff_hevc_pel_weight[block_w];
x_off += mv->x >> 2;
y_off += mv->y >> 2;
src += y_off * srcstride + (x_off * (1 << s->ps.sps->pixel_shift));
if (x_off < QPEL_EXTRA_BEFORE || y_off < QPEL_EXTRA_AFTER ||
x_off >= pic_width - block_w - QPEL_EXTRA_AFTER ||
y_off >= pic_height - block_h - QPEL_EXTRA_AFTER) {
const ptrdiff_t edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;
int offset = QPEL_EXTRA_BEFORE * srcstride + (QPEL_EXTRA_BEFORE << s->ps.sps->pixel_shift);
int buf_offset = QPEL_EXTRA_BEFORE * edge_emu_stride + (QPEL_EXTRA_BEFORE << s->ps.sps->pixel_shift);
s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src - offset,
edge_emu_stride, srcstride,
block_w + QPEL_EXTRA,
block_h + QPEL_EXTRA,
x_off - QPEL_EXTRA_BEFORE, y_off - QPEL_EXTRA_BEFORE,
pic_width, pic_height);
src = lc->edge_emu_buffer + buf_offset;
srcstride = edge_emu_stride;
}
if (!weight_flag)
s->hevcdsp.put_hevc_qpel_uni[idx][!!my][!!mx](dst, dststride, src, srcstride,
block_h, mx, my, block_w);
else
s->hevcdsp.put_hevc_qpel_uni_w[idx][!!my][!!mx](dst, dststride, src, srcstride,
block_h, s->sh.luma_log2_weight_denom,
luma_weight, luma_offset, mx, my, block_w);
}
/**
* 8.5.3.2.2.1 Luma sample bidirectional interpolation process
*
* @param s HEVC decoding context
* @param dst target buffer for block data at block position
* @param dststride stride of the dst buffer
* @param ref0 reference picture0 buffer at origin (0, 0)
* @param mv0 motion vector0 (relative to block position) to get pixel data from
* @param x_off horizontal position of block from origin (0, 0)
* @param y_off vertical position of block from origin (0, 0)
* @param block_w width of block
* @param block_h height of block
* @param ref1 reference picture1 buffer at origin (0, 0)
* @param mv1 motion vector1 (relative to block position) to get pixel data from
* @param current_mv current motion vector structure
*/
static void luma_mc_bi(HEVCContext *s, uint8_t *dst, ptrdiff_t dststride,
AVFrame *ref0, const Mv *mv0, int x_off, int y_off,
int block_w, int block_h, AVFrame *ref1, const Mv *mv1, struct MvField *current_mv)
{
HEVCLocalContext *lc = s->HEVClc;
ptrdiff_t src0stride = ref0->linesize[0];
ptrdiff_t src1stride = ref1->linesize[0];
int pic_width = s->ps.sps->width;
int pic_height = s->ps.sps->height;
int mx0 = mv0->x & 3;
int my0 = mv0->y & 3;
int mx1 = mv1->x & 3;
int my1 = mv1->y & 3;
int weight_flag = (s->sh.slice_type == HEVC_SLICE_P && s->ps.pps->weighted_pred_flag) ||
(s->sh.slice_type == HEVC_SLICE_B && s->ps.pps->weighted_bipred_flag);
int x_off0 = x_off + (mv0->x >> 2);
int y_off0 = y_off + (mv0->y >> 2);
int x_off1 = x_off + (mv1->x >> 2);
int y_off1 = y_off + (mv1->y >> 2);
int idx = ff_hevc_pel_weight[block_w];
uint8_t *src0 = ref0->data[0] + y_off0 * src0stride + (int)((unsigned)x_off0 << s->ps.sps->pixel_shift);
uint8_t *src1 = ref1->data[0] + y_off1 * src1stride + (int)((unsigned)x_off1 << s->ps.sps->pixel_shift);
if (x_off0 < QPEL_EXTRA_BEFORE || y_off0 < QPEL_EXTRA_AFTER ||
x_off0 >= pic_width - block_w - QPEL_EXTRA_AFTER ||
y_off0 >= pic_height - block_h - QPEL_EXTRA_AFTER) {
const ptrdiff_t edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;
int offset = QPEL_EXTRA_BEFORE * src0stride + (QPEL_EXTRA_BEFORE << s->ps.sps->pixel_shift);
int buf_offset = QPEL_EXTRA_BEFORE * edge_emu_stride + (QPEL_EXTRA_BEFORE << s->ps.sps->pixel_shift);
s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src0 - offset,
edge_emu_stride, src0stride,
block_w + QPEL_EXTRA,
block_h + QPEL_EXTRA,
x_off0 - QPEL_EXTRA_BEFORE, y_off0 - QPEL_EXTRA_BEFORE,
pic_width, pic_height);
src0 = lc->edge_emu_buffer + buf_offset;
src0stride = edge_emu_stride;
}
if (x_off1 < QPEL_EXTRA_BEFORE || y_off1 < QPEL_EXTRA_AFTER ||
x_off1 >= pic_width - block_w - QPEL_EXTRA_AFTER ||
y_off1 >= pic_height - block_h - QPEL_EXTRA_AFTER) {
const ptrdiff_t edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;
int offset = QPEL_EXTRA_BEFORE * src1stride + (QPEL_EXTRA_BEFORE << s->ps.sps->pixel_shift);
int buf_offset = QPEL_EXTRA_BEFORE * edge_emu_stride + (QPEL_EXTRA_BEFORE << s->ps.sps->pixel_shift);
s->vdsp.emulated_edge_mc(lc->edge_emu_buffer2, src1 - offset,
edge_emu_stride, src1stride,
block_w + QPEL_EXTRA,
block_h + QPEL_EXTRA,
x_off1 - QPEL_EXTRA_BEFORE, y_off1 - QPEL_EXTRA_BEFORE,
pic_width, pic_height);
src1 = lc->edge_emu_buffer2 + buf_offset;
src1stride = edge_emu_stride;
}
s->hevcdsp.put_hevc_qpel[idx][!!my0][!!mx0](lc->tmp, src0, src0stride,
block_h, mx0, my0, block_w);
if (!weight_flag)
s->hevcdsp.put_hevc_qpel_bi[idx][!!my1][!!mx1](dst, dststride, src1, src1stride, lc->tmp,
block_h, mx1, my1, block_w);
else
s->hevcdsp.put_hevc_qpel_bi_w[idx][!!my1][!!mx1](dst, dststride, src1, src1stride, lc->tmp,
block_h, s->sh.luma_log2_weight_denom,
s->sh.luma_weight_l0[current_mv->ref_idx[0]],
s->sh.luma_weight_l1[current_mv->ref_idx[1]],
s->sh.luma_offset_l0[current_mv->ref_idx[0]],
s->sh.luma_offset_l1[current_mv->ref_idx[1]],
mx1, my1, block_w);
}
/**
* 8.5.3.2.2.2 Chroma sample uniprediction interpolation process
*
* @param s HEVC decoding context
* @param dst1 target buffer for block data at block position (U plane)
* @param dst2 target buffer for block data at block position (V plane)
* @param dststride stride of the dst1 and dst2 buffers
* @param ref reference picture buffer at origin (0, 0)
* @param mv motion vector (relative to block position) to get pixel data from
* @param x_off horizontal position of block from origin (0, 0)
* @param y_off vertical position of block from origin (0, 0)
* @param block_w width of block
* @param block_h height of block
* @param chroma_weight weighting factor applied to the chroma prediction
* @param chroma_offset additive offset applied to the chroma prediction value
*/
static void chroma_mc_uni(HEVCContext *s, uint8_t *dst0,
ptrdiff_t dststride, uint8_t *src0, ptrdiff_t srcstride, int reflist,
int x_off, int y_off, int block_w, int block_h, struct MvField *current_mv, int chroma_weight, int chroma_offset)
{
HEVCLocalContext *lc = s->HEVClc;
int pic_width = s->ps.sps->width >> s->ps.sps->hshift[1];
int pic_height = s->ps.sps->height >> s->ps.sps->vshift[1];
const Mv *mv = ¤t_mv->mv[reflist];
int weight_flag = (s->sh.slice_type == HEVC_SLICE_P && s->ps.pps->weighted_pred_flag) ||
(s->sh.slice_type == HEVC_SLICE_B && s->ps.pps->weighted_bipred_flag);
int idx = ff_hevc_pel_weight[block_w];
int hshift = s->ps.sps->hshift[1];
int vshift = s->ps.sps->vshift[1];
intptr_t mx = av_mod_uintp2(mv->x, 2 + hshift);
intptr_t my = av_mod_uintp2(mv->y, 2 + vshift);
intptr_t _mx = mx << (1 - hshift);
intptr_t _my = my << (1 - vshift);
x_off += mv->x >> (2 + hshift);
y_off += mv->y >> (2 + vshift);
src0 += y_off * srcstride + (x_off * (1 << s->ps.sps->pixel_shift));
if (x_off < EPEL_EXTRA_BEFORE || y_off < EPEL_EXTRA_AFTER ||
x_off >= pic_width - block_w - EPEL_EXTRA_AFTER ||
y_off >= pic_height - block_h - EPEL_EXTRA_AFTER) {
const int edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;
int offset0 = EPEL_EXTRA_BEFORE * (srcstride + (1 << s->ps.sps->pixel_shift));
int buf_offset0 = EPEL_EXTRA_BEFORE *
(edge_emu_stride + (1 << s->ps.sps->pixel_shift));
s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src0 - offset0,
edge_emu_stride, srcstride,
block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
x_off - EPEL_EXTRA_BEFORE,
y_off - EPEL_EXTRA_BEFORE,
pic_width, pic_height);
src0 = lc->edge_emu_buffer + buf_offset0;
srcstride = edge_emu_stride;
}
if (!weight_flag)
s->hevcdsp.put_hevc_epel_uni[idx][!!my][!!mx](dst0, dststride, src0, srcstride,
block_h, _mx, _my, block_w);
else
s->hevcdsp.put_hevc_epel_uni_w[idx][!!my][!!mx](dst0, dststride, src0, srcstride,
block_h, s->sh.chroma_log2_weight_denom,
chroma_weight, chroma_offset, _mx, _my, block_w);
}
/**
* 8.5.3.2.2.2 Chroma sample bidirectional interpolation process
*
* @param s HEVC decoding context
* @param dst target buffer for block data at block position
* @param dststride stride of the dst buffer
* @param ref0 reference picture0 buffer at origin (0, 0)
* @param mv0 motion vector0 (relative to block position) to get pixel data from
* @param x_off horizontal position of block from origin (0, 0)
* @param y_off vertical position of block from origin (0, 0)
* @param block_w width of block
* @param block_h height of block
* @param ref1 reference picture1 buffer at origin (0, 0)
* @param mv1 motion vector1 (relative to block position) to get pixel data from
* @param current_mv current motion vector structure
* @param cidx chroma component(cb, cr)
*/
static void chroma_mc_bi(HEVCContext *s, uint8_t *dst0, ptrdiff_t dststride, AVFrame *ref0, AVFrame *ref1,
int x_off, int y_off, int block_w, int block_h, struct MvField *current_mv, int cidx)
{
HEVCLocalContext *lc = s->HEVClc;
uint8_t *src1 = ref0->data[cidx+1];
uint8_t *src2 = ref1->data[cidx+1];
ptrdiff_t src1stride = ref0->linesize[cidx+1];
ptrdiff_t src2stride = ref1->linesize[cidx+1];
int weight_flag = (s->sh.slice_type == HEVC_SLICE_P && s->ps.pps->weighted_pred_flag) ||
(s->sh.slice_type == HEVC_SLICE_B && s->ps.pps->weighted_bipred_flag);
int pic_width = s->ps.sps->width >> s->ps.sps->hshift[1];
int pic_height = s->ps.sps->height >> s->ps.sps->vshift[1];
Mv *mv0 = ¤t_mv->mv[0];
Mv *mv1 = ¤t_mv->mv[1];
int hshift = s->ps.sps->hshift[1];
int vshift = s->ps.sps->vshift[1];
intptr_t mx0 = av_mod_uintp2(mv0->x, 2 + hshift);
intptr_t my0 = av_mod_uintp2(mv0->y, 2 + vshift);
intptr_t mx1 = av_mod_uintp2(mv1->x, 2 + hshift);
intptr_t my1 = av_mod_uintp2(mv1->y, 2 + vshift);
intptr_t _mx0 = mx0 << (1 - hshift);
intptr_t _my0 = my0 << (1 - vshift);
intptr_t _mx1 = mx1 << (1 - hshift);
intptr_t _my1 = my1 << (1 - vshift);
int x_off0 = x_off + (mv0->x >> (2 + hshift));
int y_off0 = y_off + (mv0->y >> (2 + vshift));
int x_off1 = x_off + (mv1->x >> (2 + hshift));
int y_off1 = y_off + (mv1->y >> (2 + vshift));
int idx = ff_hevc_pel_weight[block_w];
src1 += y_off0 * src1stride + (int)((unsigned)x_off0 << s->ps.sps->pixel_shift);
src2 += y_off1 * src2stride + (int)((unsigned)x_off1 << s->ps.sps->pixel_shift);
if (x_off0 < EPEL_EXTRA_BEFORE || y_off0 < EPEL_EXTRA_AFTER ||
x_off0 >= pic_width - block_w - EPEL_EXTRA_AFTER ||
y_off0 >= pic_height - block_h - EPEL_EXTRA_AFTER) {
const int edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;
int offset1 = EPEL_EXTRA_BEFORE * (src1stride + (1 << s->ps.sps->pixel_shift));
int buf_offset1 = EPEL_EXTRA_BEFORE *
(edge_emu_stride + (1 << s->ps.sps->pixel_shift));
s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src1 - offset1,
edge_emu_stride, src1stride,
block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
x_off0 - EPEL_EXTRA_BEFORE,
y_off0 - EPEL_EXTRA_BEFORE,
pic_width, pic_height);
src1 = lc->edge_emu_buffer + buf_offset1;
src1stride = edge_emu_stride;
}
if (x_off1 < EPEL_EXTRA_BEFORE || y_off1 < EPEL_EXTRA_AFTER ||
x_off1 >= pic_width - block_w - EPEL_EXTRA_AFTER ||
y_off1 >= pic_height - block_h - EPEL_EXTRA_AFTER) {
const int edge_emu_stride = EDGE_EMU_BUFFER_STRIDE << s->ps.sps->pixel_shift;
int offset1 = EPEL_EXTRA_BEFORE * (src2stride + (1 << s->ps.sps->pixel_shift));
int buf_offset1 = EPEL_EXTRA_BEFORE *
(edge_emu_stride + (1 << s->ps.sps->pixel_shift));
s->vdsp.emulated_edge_mc(lc->edge_emu_buffer2, src2 - offset1,
edge_emu_stride, src2stride,
block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
x_off1 - EPEL_EXTRA_BEFORE,
y_off1 - EPEL_EXTRA_BEFORE,
pic_width, pic_height);
src2 = lc->edge_emu_buffer2 + buf_offset1;
src2stride = edge_emu_stride;
}
s->hevcdsp.put_hevc_epel[idx][!!my0][!!mx0](lc->tmp, src1, src1stride,
block_h, _mx0, _my0, block_w);
if (!weight_flag)
s->hevcdsp.put_hevc_epel_bi[idx][!!my1][!!mx1](dst0, s->frame->linesize[cidx+1],
src2, src2stride, lc->tmp,
block_h, _mx1, _my1, block_w);
else
s->hevcdsp.put_hevc_epel_bi_w[idx][!!my1][!!mx1](dst0, s->frame->linesize[cidx+1],
src2, src2stride, lc->tmp,
block_h,
s->sh.chroma_log2_weight_denom,
s->sh.chroma_weight_l0[current_mv->ref_idx[0]][cidx],
s->sh.chroma_weight_l1[current_mv->ref_idx[1]][cidx],
s->sh.chroma_offset_l0[current_mv->ref_idx[0]][cidx],
s->sh.chroma_offset_l1[current_mv->ref_idx[1]][cidx],
_mx1, _my1, block_w);
}
static void hevc_await_progress(HEVCContext *s, HEVCFrame *ref,
const Mv *mv, int y0, int height)
{
if (s->threads_type == FF_THREAD_FRAME ) {
int y = FFMAX(0, (mv->y >> 2) + y0 + height + 9);
ff_thread_await_progress(&ref->tf, y, 0);
}
}
static void hevc_luma_mv_mvp_mode(HEVCContext *s, int x0, int y0, int nPbW,
int nPbH, int log2_cb_size, int part_idx,
int merge_idx, MvField *mv)
{
HEVCLocalContext *lc = s->HEVClc;
enum InterPredIdc inter_pred_idc = PRED_L0;
int mvp_flag;
ff_hevc_set_neighbour_available(s, x0, y0, nPbW, nPbH);
mv->pred_flag = 0;
if (s->sh.slice_type == HEVC_SLICE_B)
inter_pred_idc = ff_hevc_inter_pred_idc_decode(s, nPbW, nPbH);
if (inter_pred_idc != PRED_L1) {
if (s->sh.nb_refs[L0])
mv->ref_idx[0]= ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L0]);
mv->pred_flag = PF_L0;
ff_hevc_hls_mvd_coding(s, x0, y0, 0);
mvp_flag = ff_hevc_mvp_lx_flag_decode(s);
ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
part_idx, merge_idx, mv, mvp_flag, 0);
mv->mv[0].x += lc->pu.mvd.x;
mv->mv[0].y += lc->pu.mvd.y;
}
if (inter_pred_idc != PRED_L0) {
if (s->sh.nb_refs[L1])
mv->ref_idx[1]= ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L1]);
if (s->sh.mvd_l1_zero_flag == 1 && inter_pred_idc == PRED_BI) {
AV_ZERO32(&lc->pu.mvd);
} else {
ff_hevc_hls_mvd_coding(s, x0, y0, 1);
}
mv->pred_flag += PF_L1;
mvp_flag = ff_hevc_mvp_lx_flag_decode(s);
ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
part_idx, merge_idx, mv, mvp_flag, 1);
mv->mv[1].x += lc->pu.mvd.x;
mv->mv[1].y += lc->pu.mvd.y;
}
}
static void hls_prediction_unit(HEVCContext *s, int x0, int y0,
int nPbW, int nPbH,
int log2_cb_size, int partIdx, int idx)
{
#define POS(c_idx, x, y) \
&s->frame->data[c_idx][((y) >> s->ps.sps->vshift[c_idx]) * s->frame->linesize[c_idx] + \
(((x) >> s->ps.sps->hshift[c_idx]) << s->ps.sps->pixel_shift)]
HEVCLocalContext *lc = s->HEVClc;
int merge_idx = 0;
struct MvField current_mv = {{{ 0 }}};
int min_pu_width = s->ps.sps->min_pu_width;
MvField *tab_mvf = s->ref->tab_mvf;
RefPicList *refPicList = s->ref->refPicList;
HEVCFrame *ref0 = NULL, *ref1 = NULL;
uint8_t *dst0 = POS(0, x0, y0);
uint8_t *dst1 = POS(1, x0, y0);
uint8_t *dst2 = POS(2, x0, y0);
int log2_min_cb_size = s->ps.sps->log2_min_cb_size;
int min_cb_width = s->ps.sps->min_cb_width;
int x_cb = x0 >> log2_min_cb_size;
int y_cb = y0 >> log2_min_cb_size;
int x_pu, y_pu;
int i, j;
int skip_flag = SAMPLE_CTB(s->skip_flag, x_cb, y_cb);
if (!skip_flag)
lc->pu.merge_flag = ff_hevc_merge_flag_decode(s);
if (skip_flag || lc->pu.merge_flag) {
if (s->sh.max_num_merge_cand > 1)
merge_idx = ff_hevc_merge_idx_decode(s);
else
merge_idx = 0;
ff_hevc_luma_mv_merge_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
partIdx, merge_idx, ¤t_mv);
} else {
hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
partIdx, merge_idx, ¤t_mv);
}
x_pu = x0 >> s->ps.sps->log2_min_pu_size;
y_pu = y0 >> s->ps.sps->log2_min_pu_size;
for (j = 0; j < nPbH >> s->ps.sps->log2_min_pu_size; j++)
for (i = 0; i < nPbW >> s->ps.sps->log2_min_pu_size; i++)
tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv;
if (current_mv.pred_flag & PF_L0) {
ref0 = refPicList[0].ref[current_mv.ref_idx[0]];
if (!ref0)
return;
hevc_await_progress(s, ref0, ¤t_mv.mv[0], y0, nPbH);
}
if (current_mv.pred_flag & PF_L1) {
ref1 = refPicList[1].ref[current_mv.ref_idx[1]];
if (!ref1)
return;
hevc_await_progress(s, ref1, ¤t_mv.mv[1], y0, nPbH);
}
if (current_mv.pred_flag == PF_L0) {
int x0_c = x0 >> s->ps.sps->hshift[1];
int y0_c = y0 >> s->ps.sps->vshift[1];
int nPbW_c = nPbW >> s->ps.sps->hshift[1];
int nPbH_c = nPbH >> s->ps.sps->vshift[1];
luma_mc_uni(s, dst0, s->frame->linesize[0], ref0->frame,
¤t_mv.mv[0], x0, y0, nPbW, nPbH,
s->sh.luma_weight_l0[current_mv.ref_idx[0]],
s->sh.luma_offset_l0[current_mv.ref_idx[0]]);
if (s->ps.sps->chroma_format_idc) {
chroma_mc_uni(s, dst1, s->frame->linesize[1], ref0->frame->data[1], ref0->frame->linesize[1],
0, x0_c, y0_c, nPbW_c, nPbH_c, ¤t_mv,
s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0]);
chroma_mc_uni(s, dst2, s->frame->linesize[2], ref0->frame->data[2], ref0->frame->linesize[2],
0, x0_c, y0_c, nPbW_c, nPbH_c, ¤t_mv,
s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1]);
}
} else if (current_mv.pred_flag == PF_L1) {
int x0_c = x0 >> s->ps.sps->hshift[1];
int y0_c = y0 >> s->ps.sps->vshift[1];
int nPbW_c = nPbW >> s->ps.sps->hshift[1];
int nPbH_c = nPbH >> s->ps.sps->vshift[1];
luma_mc_uni(s, dst0, s->frame->linesize[0], ref1->frame,
¤t_mv.mv[1], x0, y0, nPbW, nPbH,
s->sh.luma_weight_l1[current_mv.ref_idx[1]],
s->sh.luma_offset_l1[current_mv.ref_idx[1]]);
if (s->ps.sps->chroma_format_idc) {
chroma_mc_uni(s, dst1, s->frame->linesize[1], ref1->frame->data[1], ref1->frame->linesize[1],
1, x0_c, y0_c, nPbW_c, nPbH_c, ¤t_mv,
s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0]);
chroma_mc_uni(s, dst2, s->frame->linesize[2], ref1->frame->data[2], ref1->frame->linesize[2],
1, x0_c, y0_c, nPbW_c, nPbH_c, ¤t_mv,
s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1]);
}
} else if (current_mv.pred_flag == PF_BI) {
int x0_c = x0 >> s->ps.sps->hshift[1];
int y0_c = y0 >> s->ps.sps->vshift[1];
int nPbW_c = nPbW >> s->ps.sps->hshift[1];
int nPbH_c = nPbH >> s->ps.sps->vshift[1];
luma_mc_bi(s, dst0, s->frame->linesize[0], ref0->frame,
¤t_mv.mv[0], x0, y0, nPbW, nPbH,
ref1->frame, ¤t_mv.mv[1], ¤t_mv);
if (s->ps.sps->chroma_format_idc) {
chroma_mc_bi(s, dst1, s->frame->linesize[1], ref0->frame, ref1->frame,
x0_c, y0_c, nPbW_c, nPbH_c, ¤t_mv, 0);
chroma_mc_bi(s, dst2, s->frame->linesize[2], ref0->frame, ref1->frame,
x0_c, y0_c, nPbW_c, nPbH_c, ¤t_mv, 1);
}
}
}
/**
* 8.4.1
*/
static int luma_intra_pred_mode(HEVCContext *s, int x0, int y0, int pu_size,
int prev_intra_luma_pred_flag)
{
HEVCLocalContext *lc = s->HEVClc;
int x_pu = x0 >> s->ps.sps->log2_min_pu_size;
int y_pu = y0 >> s->ps.sps->log2_min_pu_size;
int min_pu_width = s->ps.sps->min_pu_width;
int size_in_pus = pu_size >> s->ps.sps->log2_min_pu_size;
int x0b = av_mod_uintp2(x0, s->ps.sps->log2_ctb_size);
int y0b = av_mod_uintp2(y0, s->ps.sps->log2_ctb_size);
int cand_up = (lc->ctb_up_flag || y0b) ?
s->tab_ipm[(y_pu - 1) * min_pu_width + x_pu] : INTRA_DC;
int cand_left = (lc->ctb_left_flag || x0b) ?
s->tab_ipm[y_pu * min_pu_width + x_pu - 1] : INTRA_DC;
int y_ctb = (y0 >> (s->ps.sps->log2_ctb_size)) << (s->ps.sps->log2_ctb_size);
MvField *tab_mvf = s->ref->tab_mvf;
int intra_pred_mode;
int candidate[3];
int i, j;
// intra_pred_mode prediction does not cross vertical CTB boundaries
if ((y0 - 1) < y_ctb)
cand_up = INTRA_DC;
if (cand_left == cand_up) {
if (cand_left < 2) {
candidate[0] = INTRA_PLANAR;
candidate[1] = INTRA_DC;
candidate[2] = INTRA_ANGULAR_26;
} else {
candidate[0] = cand_left;
candidate[1] = 2 + ((cand_left - 2 - 1 + 32) & 31);
candidate[2] = 2 + ((cand_left - 2 + 1) & 31);
}
} else {
candidate[0] = cand_left;
candidate[1] = cand_up;
if (candidate[0] != INTRA_PLANAR && candidate[1] != INTRA_PLANAR) {
candidate[2] = INTRA_PLANAR;
} else if (candidate[0] != INTRA_DC && candidate[1] != INTRA_DC) {
candidate[2] = INTRA_DC;
} else {
candidate[2] = INTRA_ANGULAR_26;
}
}
if (prev_intra_luma_pred_flag) {
intra_pred_mode = candidate[lc->pu.mpm_idx];
} else {
if (candidate[0] > candidate[1])
FFSWAP(uint8_t, candidate[0], candidate[1]);
if (candidate[0] > candidate[2])
FFSWAP(uint8_t, candidate[0], candidate[2]);
if (candidate[1] > candidate[2])
FFSWAP(uint8_t, candidate[1], candidate[2]);
intra_pred_mode = lc->pu.rem_intra_luma_pred_mode;
for (i = 0; i < 3; i++)
if (intra_pred_mode >= candidate[i])
intra_pred_mode++;
}
/* write the intra prediction units into the mv array */
if (!size_in_pus)
size_in_pus = 1;
for (i = 0; i < size_in_pus; i++) {
memset(&s->tab_ipm[(y_pu + i) * min_pu_width + x_pu],
intra_pred_mode, size_in_pus);
for (j = 0; j < size_in_pus; j++) {
tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].pred_flag = PF_INTRA;
}
}
return intra_pred_mode;
}
static av_always_inline void set_ct_depth(HEVCContext *s, int x0, int y0,
int log2_cb_size, int ct_depth)
{
int length = (1 << log2_cb_size) >> s->ps.sps->log2_min_cb_size;
int x_cb = x0 >> s->ps.sps->log2_min_cb_size;
int y_cb = y0 >> s->ps.sps->log2_min_cb_size;
int y;
for (y = 0; y < length; y++)
memset(&s->tab_ct_depth[(y_cb + y) * s->ps.sps->min_cb_width + x_cb],
ct_depth, length);
}
static const uint8_t tab_mode_idx[] = {
0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20,
21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31};
static void intra_prediction_unit(HEVCContext *s, int x0, int y0,
int log2_cb_size)
{
HEVCLocalContext *lc = s->HEVClc;
static const uint8_t intra_chroma_table[4] = { 0, 26, 10, 1 };
uint8_t prev_intra_luma_pred_flag[4];
int split = lc->cu.part_mode == PART_NxN;
int pb_size = (1 << log2_cb_size) >> split;
int side = split + 1;
int chroma_mode;
int i, j;
for (i = 0; i < side; i++)
for (j = 0; j < side; j++)
prev_intra_luma_pred_flag[2 * i + j] = ff_hevc_prev_intra_luma_pred_flag_decode(s);
for (i = 0; i < side; i++) {
for (j = 0; j < side; j++) {
if (prev_intra_luma_pred_flag[2 * i + j])
lc->pu.mpm_idx = ff_hevc_mpm_idx_decode(s);
else
lc->pu.rem_intra_luma_pred_mode = ff_hevc_rem_intra_luma_pred_mode_decode(s);
lc->pu.intra_pred_mode[2 * i + j] =
luma_intra_pred_mode(s, x0 + pb_size * j, y0 + pb_size * i, pb_size,
prev_intra_luma_pred_flag[2 * i + j]);
}
}
if (s->ps.sps->chroma_format_idc == 3) {
for (i = 0; i < side; i++) {
for (j = 0; j < side; j++) {
lc->pu.chroma_mode_c[2 * i + j] = chroma_mode = ff_hevc_intra_chroma_pred_mode_decode(s);
if (chroma_mode != 4) {
if (lc->pu.intra_pred_mode[2 * i + j] == intra_chroma_table[chroma_mode])
lc->pu.intra_pred_mode_c[2 * i + j] = 34;
else
lc->pu.intra_pred_mode_c[2 * i + j] = intra_chroma_table[chroma_mode];
} else {
lc->pu.intra_pred_mode_c[2 * i + j] = lc->pu.intra_pred_mode[2 * i + j];
}
}
}
} else if (s->ps.sps->chroma_format_idc == 2) {
int mode_idx;
lc->pu.chroma_mode_c[0] = chroma_mode = ff_hevc_intra_chroma_pred_mode_decode(s);
if (chroma_mode != 4) {
if (lc->pu.intra_pred_mode[0] == intra_chroma_table[chroma_mode])
mode_idx = 34;
else
mode_idx = intra_chroma_table[chroma_mode];
} else {
mode_idx = lc->pu.intra_pred_mode[0];
}
lc->pu.intra_pred_mode_c[0] = tab_mode_idx[mode_idx];
} else if (s->ps.sps->chroma_format_idc != 0) {
chroma_mode = ff_hevc_intra_chroma_pred_mode_decode(s);
if (chroma_mode != 4) {
if (lc->pu.intra_pred_mode[0] == intra_chroma_table[chroma_mode])
lc->pu.intra_pred_mode_c[0] = 34;
else
lc->pu.intra_pred_mode_c[0] = intra_chroma_table[chroma_mode];
} else {
lc->pu.intra_pred_mode_c[0] = lc->pu.intra_pred_mode[0];
}
}
}
static void intra_prediction_unit_default_value(HEVCContext *s,
int x0, int y0,
int log2_cb_size)
{
HEVCLocalContext *lc = s->HEVClc;
int pb_size = 1 << log2_cb_size;
int size_in_pus = pb_size >> s->ps.sps->log2_min_pu_size;
int min_pu_width = s->ps.sps->min_pu_width;
MvField *tab_mvf = s->ref->tab_mvf;
int x_pu = x0 >> s->ps.sps->log2_min_pu_size;
int y_pu = y0 >> s->ps.sps->log2_min_pu_size;
int j, k;
if (size_in_pus == 0)
size_in_pus = 1;
for (j = 0; j < size_in_pus; j++)
memset(&s->tab_ipm[(y_pu + j) * min_pu_width + x_pu], INTRA_DC, size_in_pus);
if (lc->cu.pred_mode == MODE_INTRA)
for (j = 0; j < size_in_pus; j++)
for (k = 0; k < size_in_pus; k++)
tab_mvf[(y_pu + j) * min_pu_width + x_pu + k].pred_flag = PF_INTRA;
}
static int hls_coding_unit(HEVCContext *s, int x0, int y0, int log2_cb_size)
{
int cb_size = 1 << log2_cb_size;
HEVCLocalContext *lc = s->HEVClc;
int log2_min_cb_size = s->ps.sps->log2_min_cb_size;
int length = cb_size >> log2_min_cb_size;
int min_cb_width = s->ps.sps->min_cb_width;
int x_cb = x0 >> log2_min_cb_size;
int y_cb = y0 >> log2_min_cb_size;
int idx = log2_cb_size - 2;
int qp_block_mask = (1<<(s->ps.sps->log2_ctb_size - s->ps.pps->diff_cu_qp_delta_depth)) - 1;
int x, y, ret;
lc->cu.x = x0;
lc->cu.y = y0;
lc->cu.pred_mode = MODE_INTRA;
lc->cu.part_mode = PART_2Nx2N;
lc->cu.intra_split_flag = 0;
SAMPLE_CTB(s->skip_flag, x_cb, y_cb) = 0;
for (x = 0; x < 4; x++)
lc->pu.intra_pred_mode[x] = 1;
if (s->ps.pps->transquant_bypass_enable_flag) {
lc->cu.cu_transquant_bypass_flag = ff_hevc_cu_transquant_bypass_flag_decode(s);
if (lc->cu.cu_transquant_bypass_flag)
set_deblocking_bypass(s, x0, y0, log2_cb_size);
} else
lc->cu.cu_transquant_bypass_flag = 0;
if (s->sh.slice_type != HEVC_SLICE_I) {
uint8_t skip_flag = ff_hevc_skip_flag_decode(s, x0, y0, x_cb, y_cb);
x = y_cb * min_cb_width + x_cb;
for (y = 0; y < length; y++) {
memset(&s->skip_flag[x], skip_flag, length);
x += min_cb_width;
}
lc->cu.pred_mode = skip_flag ? MODE_SKIP : MODE_INTER;
} else {
x = y_cb * min_cb_width + x_cb;
for (y = 0; y < length; y++) {
memset(&s->skip_flag[x], 0, length);
x += min_cb_width;
}
}
if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) {
hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0, idx);
intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
if (!s->sh.disable_deblocking_filter_flag)
ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size);
} else {
int pcm_flag = 0;
if (s->sh.slice_type != HEVC_SLICE_I)
lc->cu.pred_mode = ff_hevc_pred_mode_decode(s);
if (lc->cu.pred_mode != MODE_INTRA ||
log2_cb_size == s->ps.sps->log2_min_cb_size) {
lc->cu.part_mode = ff_hevc_part_mode_decode(s, log2_cb_size);
lc->cu.intra_split_flag = lc->cu.part_mode == PART_NxN &&
lc->cu.pred_mode == MODE_INTRA;
}
if (lc->cu.pred_mode == MODE_INTRA) {
if (lc->cu.part_mode == PART_2Nx2N && s->ps.sps->pcm_enabled_flag &&
log2_cb_size >= s->ps.sps->pcm.log2_min_pcm_cb_size &&
log2_cb_size <= s->ps.sps->pcm.log2_max_pcm_cb_size) {
pcm_flag = ff_hevc_pcm_flag_decode(s);
}
if (pcm_flag) {
intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
ret = hls_pcm_sample(s, x0, y0, log2_cb_size);
if (s->ps.sps->pcm.loop_filter_disable_flag)
set_deblocking_bypass(s, x0, y0, log2_cb_size);
if (ret < 0)
return ret;
} else {
intra_prediction_unit(s, x0, y0, log2_cb_size);
}
} else {
intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
switch (lc->cu.part_mode) {
case PART_2Nx2N:
hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0, idx);
break;
case PART_2NxN:
hls_prediction_unit(s, x0, y0, cb_size, cb_size / 2, log2_cb_size, 0, idx);
hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size, cb_size / 2, log2_cb_size, 1, idx);
break;
case PART_Nx2N:
hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size, log2_cb_size, 0, idx - 1);
hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size, log2_cb_size, 1, idx - 1);
break;
case PART_2NxnU:
hls_prediction_unit(s, x0, y0, cb_size, cb_size / 4, log2_cb_size, 0, idx);
hls_prediction_unit(s, x0, y0 + cb_size / 4, cb_size, cb_size * 3 / 4, log2_cb_size, 1, idx);
break;
case PART_2NxnD:
hls_prediction_unit(s, x0, y0, cb_size, cb_size * 3 / 4, log2_cb_size, 0, idx);
hls_prediction_unit(s, x0, y0 + cb_size * 3 / 4, cb_size, cb_size / 4, log2_cb_size, 1, idx);
break;
case PART_nLx2N:
hls_prediction_unit(s, x0, y0, cb_size / 4, cb_size, log2_cb_size, 0, idx - 2);
hls_prediction_unit(s, x0 + cb_size / 4, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 1, idx - 2);
break;
case PART_nRx2N:
hls_prediction_unit(s, x0, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 0, idx - 2);
hls_prediction_unit(s, x0 + cb_size * 3 / 4, y0, cb_size / 4, cb_size, log2_cb_size, 1, idx - 2);
break;
case PART_NxN:
hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size / 2, log2_cb_size, 0, idx - 1);
hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size / 2, log2_cb_size, 1, idx - 1);
hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 2, idx - 1);
hls_prediction_unit(s, x0 + cb_size / 2, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 3, idx - 1);
break;
}
}
if (!pcm_flag) {
int rqt_root_cbf = 1;
if (lc->cu.pred_mode != MODE_INTRA &&
!(lc->cu.part_mode == PART_2Nx2N && lc->pu.merge_flag)) {
rqt_root_cbf = ff_hevc_no_residual_syntax_flag_decode(s);
}
if (rqt_root_cbf) {
const static int cbf[2] = { 0 };
lc->cu.max_trafo_depth = lc->cu.pred_mode == MODE_INTRA ?
s->ps.sps->max_transform_hierarchy_depth_intra + lc->cu.intra_split_flag :
s->ps.sps->max_transform_hierarchy_depth_inter;
ret = hls_transform_tree(s, x0, y0, x0, y0, x0, y0,
log2_cb_size,
log2_cb_size, 0, 0, cbf, cbf);
if (ret < 0)
return ret;
} else {
if (!s->sh.disable_deblocking_filter_flag)
ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size);
}
}
}
if (s->ps.pps->cu_qp_delta_enabled_flag && lc->tu.is_cu_qp_delta_coded == 0)
ff_hevc_set_qPy(s, x0, y0, log2_cb_size);
x = y_cb * min_cb_width + x_cb;
for (y = 0; y < length; y++) {
memset(&s->qp_y_tab[x], lc->qp_y, length);
x += min_cb_width;
}
if(((x0 + (1<<log2_cb_size)) & qp_block_mask) == 0 &&
((y0 + (1<<log2_cb_size)) & qp_block_mask) == 0) {
lc->qPy_pred = lc->qp_y;
}
set_ct_depth(s, x0, y0, log2_cb_size, lc->ct_depth);
return 0;
}
static int hls_coding_quadtree(HEVCContext *s, int x0, int y0,
int log2_cb_size, int cb_depth)
{
HEVCLocalContext *lc = s->HEVClc;
const int cb_size = 1 << log2_cb_size;
int ret;
int split_cu;
lc->ct_depth = cb_depth;
if (x0 + cb_size <= s->ps.sps->width &&
y0 + cb_size <= s->ps.sps->height &&
log2_cb_size > s->ps.sps->log2_min_cb_size) {
split_cu = ff_hevc_split_coding_unit_flag_decode(s, cb_depth, x0, y0);
} else {
split_cu = (log2_cb_size > s->ps.sps->log2_min_cb_size);
}
if (s->ps.pps->cu_qp_delta_enabled_flag &&
log2_cb_size >= s->ps.sps->log2_ctb_size - s->ps.pps->diff_cu_qp_delta_depth) {
lc->tu.is_cu_qp_delta_coded = 0;
lc->tu.cu_qp_delta = 0;
}
if (s->sh.cu_chroma_qp_offset_enabled_flag &&
log2_cb_size >= s->ps.sps->log2_ctb_size - s->ps.pps->diff_cu_chroma_qp_offset_depth) {
lc->tu.is_cu_chroma_qp_offset_coded = 0;
}
if (split_cu) {
int qp_block_mask = (1<<(s->ps.sps->log2_ctb_size - s->ps.pps->diff_cu_qp_delta_depth)) - 1;
const int cb_size_split = cb_size >> 1;
const int x1 = x0 + cb_size_split;
const int y1 = y0 + cb_size_split;
int more_data = 0;
more_data = hls_coding_quadtree(s, x0, y0, log2_cb_size - 1, cb_depth + 1);
if (more_data < 0)
return more_data;
if (more_data && x1 < s->ps.sps->width) {
more_data = hls_coding_quadtree(s, x1, y0, log2_cb_size - 1, cb_depth + 1);
if (more_data < 0)
return more_data;
}
if (more_data && y1 < s->ps.sps->height) {
more_data = hls_coding_quadtree(s, x0, y1, log2_cb_size - 1, cb_depth + 1);
if (more_data < 0)
return more_data;
}
if (more_data && x1 < s->ps.sps->width &&
y1 < s->ps.sps->height) {
more_data = hls_coding_quadtree(s, x1, y1, log2_cb_size - 1, cb_depth + 1);
if (more_data < 0)
return more_data;
}
if(((x0 + (1<<log2_cb_size)) & qp_block_mask) == 0 &&
((y0 + (1<<log2_cb_size)) & qp_block_mask) == 0)
lc->qPy_pred = lc->qp_y;
if (more_data)
return ((x1 + cb_size_split) < s->ps.sps->width ||
(y1 + cb_size_split) < s->ps.sps->height);
else
return 0;
} else {
ret = hls_coding_unit(s, x0, y0, log2_cb_size);
if (ret < 0)
return ret;
if ((!((x0 + cb_size) %
(1 << (s->ps.sps->log2_ctb_size))) ||
(x0 + cb_size >= s->ps.sps->width)) &&
(!((y0 + cb_size) %
(1 << (s->ps.sps->log2_ctb_size))) ||
(y0 + cb_size >= s->ps.sps->height))) {
int end_of_slice_flag = ff_hevc_end_of_slice_flag_decode(s);
return !end_of_slice_flag;
} else {
return 1;
}
}
return 0;
}
static void hls_decode_neighbour(HEVCContext *s, int x_ctb, int y_ctb,
int ctb_addr_ts)
{
HEVCLocalContext *lc = s->HEVClc;
int ctb_size = 1 << s->ps.sps->log2_ctb_size;
int ctb_addr_rs = s->ps.pps->ctb_addr_ts_to_rs[ctb_addr_ts];
int ctb_addr_in_slice = ctb_addr_rs - s->sh.slice_addr;
s->tab_slice_address[ctb_addr_rs] = s->sh.slice_addr;
if (s->ps.pps->entropy_coding_sync_enabled_flag) {
if (x_ctb == 0 && (y_ctb & (ctb_size - 1)) == 0)
lc->first_qp_group = 1;
lc->end_of_tiles_x = s->ps.sps->width;
} else if (s->ps.pps->tiles_enabled_flag) {
if (ctb_addr_ts && s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[ctb_addr_ts - 1]) {
int idxX = s->ps.pps->col_idxX[x_ctb >> s->ps.sps->log2_ctb_size];
lc->end_of_tiles_x = x_ctb + (s->ps.pps->column_width[idxX] << s->ps.sps->log2_ctb_size);
lc->first_qp_group = 1;
}
} else {
lc->end_of_tiles_x = s->ps.sps->width;
}
lc->end_of_tiles_y = FFMIN(y_ctb + ctb_size, s->ps.sps->height);
lc->boundary_flags = 0;
if (s->ps.pps->tiles_enabled_flag) {
if (x_ctb > 0 && s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[s->ps.pps->ctb_addr_rs_to_ts[ctb_addr_rs - 1]])
lc->boundary_flags |= BOUNDARY_LEFT_TILE;
if (x_ctb > 0 && s->tab_slice_address[ctb_addr_rs] != s->tab_slice_address[ctb_addr_rs - 1])
lc->boundary_flags |= BOUNDARY_LEFT_SLICE;
if (y_ctb > 0 && s->ps.pps->tile_id[ctb_addr_ts] != s->ps.pps->tile_id[s->ps.pps->ctb_addr_rs_to_ts[ctb_addr_rs - s->ps.sps->ctb_width]])
lc->boundary_flags |= BOUNDARY_UPPER_TILE;
if (y_ctb > 0 && s->tab_slice_address[ctb_addr_rs] != s->tab_slice_address[ctb_addr_rs - s->ps.sps->ctb_width])
lc->boundary_flags |= BOUNDARY_UPPER_SLICE;
} else {
if (ctb_addr_in_slice <= 0)
lc->boundary_flags |= BOUNDARY_LEFT_SLICE;
if (ctb_addr_in_slice < s->ps.sps->ctb_width)
lc->boundary_flags |= BOUNDARY_UPPER_SLICE;
}
lc->ctb_left_flag = ((x_ctb > 0) && (ctb_addr_in_slice > 0) && !(lc->boundary_flags & BOUNDARY_LEFT_TILE));
lc->ctb_up_flag = ((y_ctb > 0) && (ctb_addr_in_slice >= s->ps.sps->ctb_width) && !(lc->boundary_flags & BOUNDARY_UPPER_TILE));
lc->ctb_up_right_flag = ((y_ctb > 0) && (ctb_addr_in_slice+1 >= s->ps.sps->ctb_width) && (s->ps.pps->tile_id[ctb_addr_ts] == s->ps.pps->tile_id[s->ps.pps->ctb_addr_rs_to_ts[ctb_addr_rs+1 - s->ps.sps->ctb_width]]));
lc->ctb_up_left_flag = ((x_ctb > 0) && (y_ctb > 0) && (ctb_addr_in_slice-1 >= s->ps.sps->ctb_width) && (s->ps.pps->tile_id[ctb_addr_ts] == s->ps.pps->tile_id[s->ps.pps->ctb_addr_rs_to_ts[ctb_addr_rs-1 - s->ps.sps->ctb_width]]));
}
static int hls_decode_entry(AVCodecContext *avctxt, void *isFilterThread)
{
HEVCContext *s = avctxt->priv_data;
int ctb_size = 1 << s->ps.sps->log2_ctb_size;
int more_data = 1;
int x_ctb = 0;
int y_ctb = 0;
int ctb_addr_ts = s->ps.pps->ctb_addr_rs_to_ts[s->sh.slice_ctb_addr_rs];
int ret;
if (!ctb_addr_ts && s->sh.dependent_slice_segment_flag) {
av_log(s->avctx, AV_LOG_ERROR, "Impossible initial tile.\n");
return AVERROR_INVALIDDATA;
}
if (s->sh.dependent_slice_segment_flag) {
int prev_rs = s->ps.pps->ctb_addr_ts_to_rs[ctb_addr_ts - 1];
if (s->tab_slice_address[prev_rs] != s->sh.slice_addr) {
av_log(s->avctx, AV_LOG_ERROR, "Previous slice segment missing\n");
return AVERROR_INVALIDDATA;
}
}
while (more_data && ctb_addr_ts < s->ps.sps->ctb_size) {
int ctb_addr_rs = s->ps.pps->ctb_addr_ts_to_rs[ctb_addr_ts];
x_ctb = (ctb_addr_rs % ((s->ps.sps->width + ctb_size - 1) >> s->ps.sps->log2_ctb_size)) << s->ps.sps->log2_ctb_size;
y_ctb = (ctb_addr_rs / ((s->ps.sps->width + ctb_size - 1) >> s->ps.sps->log2_ctb_size)) << s->ps.sps->log2_ctb_size;
hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);
ret = ff_hevc_cabac_init(s, ctb_addr_ts);
if (ret < 0) {
s->tab_slice_address[ctb_addr_rs] = -1;
return ret;
}
hls_sao_param(s, x_ctb >> s->ps.sps->log2_ctb_size, y_ctb >> s->ps.sps->log2_ctb_size);
s->deblock[ctb_addr_rs].beta_offset = s->sh.beta_offset;
s->deblock[ctb_addr_rs].tc_offset = s->sh.tc_offset;
s->filter_slice_edges[ctb_addr_rs] = s->sh.slice_loop_filter_across_slices_enabled_flag;
more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->ps.sps->log2_ctb_size, 0);
if (more_data < 0) {
s->tab_slice_address[ctb_addr_rs] = -1;
return more_data;
}
ctb_addr_ts++;
ff_hevc_save_states(s, ctb_addr_ts);
ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);
}
if (x_ctb + ctb_size >= s->ps.sps->width &&
y_ctb + ctb_size >= s->ps.sps->height)
ff_hevc_hls_filter(s, x_ctb, y_ctb, ctb_size);
return ctb_addr_ts;
}
static int hls_slice_data(HEVCContext *s)
{
int arg[2];
int ret[2];
arg[0] = 0;
arg[1] = 1;
s->avctx->execute(s->avctx, hls_decode_entry, arg, ret , 1, sizeof(int));
return ret[0];
}
static int hls_decode_entry_wpp(AVCodecContext *avctxt, void *input_ctb_row, int job, int self_id)
{
HEVCContext *s1 = avctxt->priv_data, *s;
HEVCLocalContext *lc;
int ctb_size = 1<< s1->ps.sps->log2_ctb_size;
int more_data = 1;
int *ctb_row_p = input_ctb_row;
int ctb_row = ctb_row_p[job];
int ctb_addr_rs = s1->sh.slice_ctb_addr_rs + ctb_row * ((s1->ps.sps->width + ctb_size - 1) >> s1->ps.sps->log2_ctb_size);
int ctb_addr_ts = s1->ps.pps->ctb_addr_rs_to_ts[ctb_addr_rs];
int thread = ctb_row % s1->threads_number;
int ret;
s = s1->sList[self_id];
lc = s->HEVClc;
if(ctb_row) {
ret = init_get_bits8(&lc->gb, s->data + s->sh.offset[ctb_row - 1], s->sh.size[ctb_row - 1]);
if (ret < 0)
goto error;
ff_init_cabac_decoder(&lc->cc, s->data + s->sh.offset[(ctb_row)-1], s->sh.size[ctb_row - 1]);
}
while(more_data && ctb_addr_ts < s->ps.sps->ctb_size) {
int x_ctb = (ctb_addr_rs % s->ps.sps->ctb_width) << s->ps.sps->log2_ctb_size;
int y_ctb = (ctb_addr_rs / s->ps.sps->ctb_width) << s->ps.sps->log2_ctb_size;
hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);
ff_thread_await_progress2(s->avctx, ctb_row, thread, SHIFT_CTB_WPP);
if (atomic_load(&s1->wpp_err)) {
ff_thread_report_progress2(s->avctx, ctb_row , thread, SHIFT_CTB_WPP);
return 0;
}
ret = ff_hevc_cabac_init(s, ctb_addr_ts);
if (ret < 0)
goto error;
hls_sao_param(s, x_ctb >> s->ps.sps->log2_ctb_size, y_ctb >> s->ps.sps->log2_ctb_size);
more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->ps.sps->log2_ctb_size, 0);
if (more_data < 0) {
ret = more_data;
goto error;
}
ctb_addr_ts++;
ff_hevc_save_states(s, ctb_addr_ts);
ff_thread_report_progress2(s->avctx, ctb_row, thread, 1);
ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);
if (!more_data && (x_ctb+ctb_size) < s->ps.sps->width && ctb_row != s->sh.num_entry_point_offsets) {
atomic_store(&s1->wpp_err, 1);
ff_thread_report_progress2(s->avctx, ctb_row ,thread, SHIFT_CTB_WPP);
return 0;
}
if ((x_ctb+ctb_size) >= s->ps.sps->width && (y_ctb+ctb_size) >= s->ps.sps->height ) {
ff_hevc_hls_filter(s, x_ctb, y_ctb, ctb_size);
ff_thread_report_progress2(s->avctx, ctb_row , thread, SHIFT_CTB_WPP);
return ctb_addr_ts;
}
ctb_addr_rs = s->ps.pps->ctb_addr_ts_to_rs[ctb_addr_ts];
x_ctb+=ctb_size;
if(x_ctb >= s->ps.sps->width) {
break;
}
}
ff_thread_report_progress2(s->avctx, ctb_row ,thread, SHIFT_CTB_WPP);
return 0;
error:
s->tab_slice_address[ctb_addr_rs] = -1;
atomic_store(&s1->wpp_err, 1);
ff_thread_report_progress2(s->avctx, ctb_row ,thread, SHIFT_CTB_WPP);
return ret;
}
static int hls_slice_data_wpp(HEVCContext *s, const H2645NAL *nal)
{
const uint8_t *data = nal->data;
int length = nal->size;
HEVCLocalContext *lc = s->HEVClc;
int *ret = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));
int *arg = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));
int64_t offset;
int64_t startheader, cmpt = 0;
int i, j, res = 0;
if (!ret || !arg) {
av_free(ret);
av_free(arg);
return AVERROR(ENOMEM);
}
if (s->sh.slice_ctb_addr_rs + s->sh.num_entry_point_offsets * s->ps.sps->ctb_width >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) {
av_log(s->avctx, AV_LOG_ERROR, "WPP ctb addresses are wrong (%d %d %d %d)\n",
s->sh.slice_ctb_addr_rs, s->sh.num_entry_point_offsets,
s->ps.sps->ctb_width, s->ps.sps->ctb_height
);
res = AVERROR_INVALIDDATA;
goto error;
}
ff_alloc_entries(s->avctx, s->sh.num_entry_point_offsets + 1);
if (!s->sList[1]) {
for (i = 1; i < s->threads_number; i++) {
s->sList[i] = av_malloc(sizeof(HEVCContext));
memcpy(s->sList[i], s, sizeof(HEVCContext));
s->HEVClcList[i] = av_mallocz(sizeof(HEVCLocalContext));
s->sList[i]->HEVClc = s->HEVClcList[i];
}
}
offset = (lc->gb.index >> 3);
for (j = 0, cmpt = 0, startheader = offset + s->sh.entry_point_offset[0]; j < nal->skipped_bytes; j++) {
if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {
startheader--;
cmpt++;
}
}
for (i = 1; i < s->sh.num_entry_point_offsets; i++) {
offset += (s->sh.entry_point_offset[i - 1] - cmpt);
for (j = 0, cmpt = 0, startheader = offset
+ s->sh.entry_point_offset[i]; j < nal->skipped_bytes; j++) {
if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {
startheader--;
cmpt++;
}
}
s->sh.size[i - 1] = s->sh.entry_point_offset[i] - cmpt;
s->sh.offset[i - 1] = offset;
}
if (s->sh.num_entry_point_offsets != 0) {
offset += s->sh.entry_point_offset[s->sh.num_entry_point_offsets - 1] - cmpt;
if (length < offset) {
av_log(s->avctx, AV_LOG_ERROR, "entry_point_offset table is corrupted\n");
res = AVERROR_INVALIDDATA;
goto error;
}
s->sh.size[s->sh.num_entry_point_offsets - 1] = length - offset;
s->sh.offset[s->sh.num_entry_point_offsets - 1] = offset;
}
s->data = data;
for (i = 1; i < s->threads_number; i++) {
s->sList[i]->HEVClc->first_qp_group = 1;
s->sList[i]->HEVClc->qp_y = s->sList[0]->HEVClc->qp_y;
memcpy(s->sList[i], s, sizeof(HEVCContext));
s->sList[i]->HEVClc = s->HEVClcList[i];
}
atomic_store(&s->wpp_err, 0);
ff_reset_entries(s->avctx);
for (i = 0; i <= s->sh.num_entry_point_offsets; i++) {
arg[i] = i;
ret[i] = 0;
}
if (s->ps.pps->entropy_coding_sync_enabled_flag)
s->avctx->execute2(s->avctx, hls_decode_entry_wpp, arg, ret, s->sh.num_entry_point_offsets + 1);
for (i = 0; i <= s->sh.num_entry_point_offsets; i++)
res += ret[i];
error:
av_free(ret);
av_free(arg);
return res;
}
static int set_side_data(HEVCContext *s)
{
AVFrame *out = s->ref->frame;
if (s->sei.frame_packing.present &&
s->sei.frame_packing.arrangement_type >= 3 &&
s->sei.frame_packing.arrangement_type <= 5 &&
s->sei.frame_packing.content_interpretation_type > 0 &&
s->sei.frame_packing.content_interpretation_type < 3) {
AVStereo3D *stereo = av_stereo3d_create_side_data(out);
if (!stereo)
return AVERROR(ENOMEM);
switch (s->sei.frame_packing.arrangement_type) {
case 3:
if (s->sei.frame_packing.quincunx_subsampling)
stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
else
stereo->type = AV_STEREO3D_SIDEBYSIDE;
break;
case 4:
stereo->type = AV_STEREO3D_TOPBOTTOM;
break;
case 5:
stereo->type = AV_STEREO3D_FRAMESEQUENCE;
break;
}
if (s->sei.frame_packing.content_interpretation_type == 2)
stereo->flags = AV_STEREO3D_FLAG_INVERT;
if (s->sei.frame_packing.arrangement_type == 5) {
if (s->sei.frame_packing.current_frame_is_frame0_flag)
stereo->view = AV_STEREO3D_VIEW_LEFT;
else
stereo->view = AV_STEREO3D_VIEW_RIGHT;
}
}
if (s->sei.display_orientation.present &&
(s->sei.display_orientation.anticlockwise_rotation ||
s->sei.display_orientation.hflip || s->sei.display_orientation.vflip)) {
double angle = s->sei.display_orientation.anticlockwise_rotation * 360 / (double) (1 << 16);
AVFrameSideData *rotation = av_frame_new_side_data(out,
AV_FRAME_DATA_DISPLAYMATRIX,
sizeof(int32_t) * 9);
if (!rotation)
return AVERROR(ENOMEM);
av_display_rotation_set((int32_t *)rotation->data, angle);
av_display_matrix_flip((int32_t *)rotation->data,
s->sei.display_orientation.hflip,
s->sei.display_orientation.vflip);
}
// Decrement the mastering display flag when IRAP frame has no_rasl_output_flag=1
// so the side data persists for the entire coded video sequence.
if (s->sei.mastering_display.present > 0 &&
IS_IRAP(s) && s->no_rasl_output_flag) {
s->sei.mastering_display.present--;
}
if (s->sei.mastering_display.present) {
// HEVC uses a g,b,r ordering, which we convert to a more natural r,g,b
const int mapping[3] = {2, 0, 1};
const int chroma_den = 50000;
const int luma_den = 10000;
int i;
AVMasteringDisplayMetadata *metadata =
av_mastering_display_metadata_create_side_data(out);
if (!metadata)
return AVERROR(ENOMEM);
for (i = 0; i < 3; i++) {
const int j = mapping[i];
metadata->display_primaries[i][0].num = s->sei.mastering_display.display_primaries[j][0];
metadata->display_primaries[i][0].den = chroma_den;
metadata->display_primaries[i][1].num = s->sei.mastering_display.display_primaries[j][1];
metadata->display_primaries[i][1].den = chroma_den;
}
metadata->white_point[0].num = s->sei.mastering_display.white_point[0];
metadata->white_point[0].den = chroma_den;
metadata->white_point[1].num = s->sei.mastering_display.white_point[1];
metadata->white_point[1].den = chroma_den;
metadata->max_luminance.num = s->sei.mastering_display.max_luminance;
metadata->max_luminance.den = luma_den;
metadata->min_luminance.num = s->sei.mastering_display.min_luminance;
metadata->min_luminance.den = luma_den;
metadata->has_luminance = 1;
metadata->has_primaries = 1;
av_log(s->avctx, AV_LOG_DEBUG, "Mastering Display Metadata:\n");
av_log(s->avctx, AV_LOG_DEBUG,
"r(%5.4f,%5.4f) g(%5.4f,%5.4f) b(%5.4f %5.4f) wp(%5.4f, %5.4f)\n",
av_q2d(metadata->display_primaries[0][0]),
av_q2d(metadata->display_primaries[0][1]),
av_q2d(metadata->display_primaries[1][0]),
av_q2d(metadata->display_primaries[1][1]),
av_q2d(metadata->display_primaries[2][0]),
av_q2d(metadata->display_primaries[2][1]),
av_q2d(metadata->white_point[0]), av_q2d(metadata->white_point[1]));
av_log(s->avctx, AV_LOG_DEBUG,
"min_luminance=%f, max_luminance=%f\n",
av_q2d(metadata->min_luminance), av_q2d(metadata->max_luminance));
}
// Decrement the mastering display flag when IRAP frame has no_rasl_output_flag=1
// so the side data persists for the entire coded video sequence.
if (s->sei.content_light.present > 0 &&
IS_IRAP(s) && s->no_rasl_output_flag) {
s->sei.content_light.present--;
}
if (s->sei.content_light.present) {
AVContentLightMetadata *metadata =
av_content_light_metadata_create_side_data(out);
if (!metadata)
return AVERROR(ENOMEM);
metadata->MaxCLL = s->sei.content_light.max_content_light_level;
metadata->MaxFALL = s->sei.content_light.max_pic_average_light_level;
av_log(s->avctx, AV_LOG_DEBUG, "Content Light Level Metadata:\n");
av_log(s->avctx, AV_LOG_DEBUG, "MaxCLL=%d, MaxFALL=%d\n",
metadata->MaxCLL, metadata->MaxFALL);
}
if (s->sei.a53_caption.a53_caption) {
AVFrameSideData* sd = av_frame_new_side_data(out,
AV_FRAME_DATA_A53_CC,
s->sei.a53_caption.a53_caption_size);
if (sd)
memcpy(sd->data, s->sei.a53_caption.a53_caption, s->sei.a53_caption.a53_caption_size);
av_freep(&s->sei.a53_caption.a53_caption);
s->sei.a53_caption.a53_caption_size = 0;
s->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
}
if (s->sei.alternative_transfer.present &&
av_color_transfer_name(s->sei.alternative_transfer.preferred_transfer_characteristics) &&
s->sei.alternative_transfer.preferred_transfer_characteristics != AVCOL_TRC_UNSPECIFIED) {
s->avctx->color_trc = out->color_trc = s->sei.alternative_transfer.preferred_transfer_characteristics;
}
return 0;
}
static int hevc_frame_start(HEVCContext *s)
{
HEVCLocalContext *lc = s->HEVClc;
int pic_size_in_ctb = ((s->ps.sps->width >> s->ps.sps->log2_min_cb_size) + 1) *
((s->ps.sps->height >> s->ps.sps->log2_min_cb_size) + 1);
int ret;
memset(s->horizontal_bs, 0, s->bs_width * s->bs_height);
memset(s->vertical_bs, 0, s->bs_width * s->bs_height);
memset(s->cbf_luma, 0, s->ps.sps->min_tb_width * s->ps.sps->min_tb_height);
memset(s->is_pcm, 0, (s->ps.sps->min_pu_width + 1) * (s->ps.sps->min_pu_height + 1));
memset(s->tab_slice_address, -1, pic_size_in_ctb * sizeof(*s->tab_slice_address));
s->is_decoded = 0;
s->first_nal_type = s->nal_unit_type;
s->no_rasl_output_flag = IS_IDR(s) || IS_BLA(s) || (s->nal_unit_type == HEVC_NAL_CRA_NUT && s->last_eos);
if (s->ps.pps->tiles_enabled_flag)
lc->end_of_tiles_x = s->ps.pps->column_width[0] << s->ps.sps->log2_ctb_size;
ret = ff_hevc_set_new_ref(s, &s->frame, s->poc);
if (ret < 0)
goto fail;
ret = ff_hevc_frame_rps(s);
if (ret < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Error constructing the frame RPS.\n");
goto fail;
}
s->ref->frame->key_frame = IS_IRAP(s);
ret = set_side_data(s);
if (ret < 0)
goto fail;
s->frame->pict_type = 3 - s->sh.slice_type;
if (!IS_IRAP(s))
ff_hevc_bump_frame(s);
av_frame_unref(s->output_frame);
ret = ff_hevc_output_frame(s, s->output_frame, 0);
if (ret < 0)
goto fail;
if (!s->avctx->hwaccel)
ff_thread_finish_setup(s->avctx);
return 0;
fail:
if (s->ref)
ff_hevc_unref_frame(s, s->ref, ~0);
s->ref = NULL;
return ret;
}
static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal)
{
HEVCLocalContext *lc = s->HEVClc;
GetBitContext *gb = &lc->gb;
int ctb_addr_ts, ret;
*gb = nal->gb;
s->nal_unit_type = nal->type;
s->temporal_id = nal->temporal_id;
switch (s->nal_unit_type) {
case HEVC_NAL_VPS:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_SPS:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps,
s->apply_defdispwin);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_PPS:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_SEI_PREFIX:
case HEVC_NAL_SEI_SUFFIX:
if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) {
ret = s->avctx->hwaccel->decode_params(s->avctx,
nal->type,
nal->raw_data,
nal->raw_size);
if (ret < 0)
goto fail;
}
ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type);
if (ret < 0)
goto fail;
break;
case HEVC_NAL_TRAIL_R:
case HEVC_NAL_TRAIL_N:
case HEVC_NAL_TSA_N:
case HEVC_NAL_TSA_R:
case HEVC_NAL_STSA_N:
case HEVC_NAL_STSA_R:
case HEVC_NAL_BLA_W_LP:
case HEVC_NAL_BLA_W_RADL:
case HEVC_NAL_BLA_N_LP:
case HEVC_NAL_IDR_W_RADL:
case HEVC_NAL_IDR_N_LP:
case HEVC_NAL_CRA_NUT:
case HEVC_NAL_RADL_N:
case HEVC_NAL_RADL_R:
case HEVC_NAL_RASL_N:
case HEVC_NAL_RASL_R:
ret = hls_slice_header(s);
if (ret < 0)
return ret;
if (ret == 1) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
if (
(s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) ||
(s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) ||
(s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) {
break;
}
if (s->sh.first_slice_in_pic_flag) {
if (s->max_ra == INT_MAX) {
if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) {
s->max_ra = s->poc;
} else {
if (IS_IDR(s))
s->max_ra = INT_MIN;
}
}
if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) &&
s->poc <= s->max_ra) {
s->is_decoded = 0;
break;
} else {
if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra)
s->max_ra = INT_MIN;
}
s->overlap ++;
ret = hevc_frame_start(s);
if (ret < 0)
return ret;
} else if (!s->ref) {
av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n");
goto fail;
}
if (s->nal_unit_type != s->first_nal_type) {
av_log(s->avctx, AV_LOG_ERROR,
"Non-matching NAL types of the VCL NALUs: %d %d\n",
s->first_nal_type, s->nal_unit_type);
return AVERROR_INVALIDDATA;
}
if (!s->sh.dependent_slice_segment_flag &&
s->sh.slice_type != HEVC_SLICE_I) {
ret = ff_hevc_slice_rpl(s);
if (ret < 0) {
av_log(s->avctx, AV_LOG_WARNING,
"Error constructing the reference lists for the current slice.\n");
goto fail;
}
}
if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) {
ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0);
if (ret < 0)
goto fail;
}
if (s->avctx->hwaccel) {
ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size);
if (ret < 0)
goto fail;
} else {
if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0)
ctb_addr_ts = hls_slice_data_wpp(s, nal);
else
ctb_addr_ts = hls_slice_data(s);
if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) {
s->is_decoded = 1;
}
if (ctb_addr_ts < 0) {
ret = ctb_addr_ts;
goto fail;
}
}
break;
case HEVC_NAL_EOS_NUT:
case HEVC_NAL_EOB_NUT:
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
break;
case HEVC_NAL_AUD:
case HEVC_NAL_FD_NUT:
break;
default:
av_log(s->avctx, AV_LOG_INFO,
"Skipping NAL unit %d\n", s->nal_unit_type);
}
return 0;
fail:
if (s->avctx->err_recognition & AV_EF_EXPLODE)
return ret;
return 0;
}
static int decode_nal_units(HEVCContext *s, const uint8_t *buf, int length)
{
int i, ret = 0;
int eos_at_start = 1;
s->ref = NULL;
s->last_eos = s->eos;
s->eos = 0;
s->overlap = 0;
/* split the input packet into NAL units, so we know the upper bound on the
* number of slices in the frame */
ret = ff_h2645_packet_split(&s->pkt, buf, length, s->avctx, s->is_nalff,
s->nal_length_size, s->avctx->codec_id, 1, 0);
if (ret < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error splitting the input into NAL units.\n");
return ret;
}
for (i = 0; i < s->pkt.nb_nals; i++) {
if (s->pkt.nals[i].type == HEVC_NAL_EOB_NUT ||
s->pkt.nals[i].type == HEVC_NAL_EOS_NUT) {
if (eos_at_start) {
s->last_eos = 1;
} else {
s->eos = 1;
}
} else {
eos_at_start = 0;
}
}
/* decode the NAL units */
for (i = 0; i < s->pkt.nb_nals; i++) {
H2645NAL *nal = &s->pkt.nals[i];
if (s->avctx->skip_frame >= AVDISCARD_ALL ||
(s->avctx->skip_frame >= AVDISCARD_NONREF
&& ff_hevc_nal_is_nonref(nal->type)))
continue;
ret = decode_nal_unit(s, nal);
if (ret >= 0 && s->overlap > 2)
ret = AVERROR_INVALIDDATA;
if (ret < 0) {
av_log(s->avctx, AV_LOG_WARNING,
"Error parsing NAL unit #%d.\n", i);
goto fail;
}
}
fail:
if (s->ref && s->threads_type == FF_THREAD_FRAME)
ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);
return ret;
}
static void print_md5(void *log_ctx, int level, uint8_t md5[16])
{
int i;
for (i = 0; i < 16; i++)
av_log(log_ctx, level, "%02"PRIx8, md5[i]);
}
static int verify_md5(HEVCContext *s, AVFrame *frame)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
int pixel_shift;
int i, j;
if (!desc)
return AVERROR(EINVAL);
pixel_shift = desc->comp[0].depth > 8;
av_log(s->avctx, AV_LOG_DEBUG, "Verifying checksum for frame with POC %d: ",
s->poc);
/* the checksums are LE, so we have to byteswap for >8bpp formats
* on BE arches */
#if HAVE_BIGENDIAN
if (pixel_shift && !s->checksum_buf) {
av_fast_malloc(&s->checksum_buf, &s->checksum_buf_size,
FFMAX3(frame->linesize[0], frame->linesize[1],
frame->linesize[2]));
if (!s->checksum_buf)
return AVERROR(ENOMEM);
}
#endif
for (i = 0; frame->data[i]; i++) {
int width = s->avctx->coded_width;
int height = s->avctx->coded_height;
int w = (i == 1 || i == 2) ? (width >> desc->log2_chroma_w) : width;
int h = (i == 1 || i == 2) ? (height >> desc->log2_chroma_h) : height;
uint8_t md5[16];
av_md5_init(s->md5_ctx);
for (j = 0; j < h; j++) {
const uint8_t *src = frame->data[i] + j * frame->linesize[i];
#if HAVE_BIGENDIAN
if (pixel_shift) {
s->bdsp.bswap16_buf((uint16_t *) s->checksum_buf,
(const uint16_t *) src, w);
src = s->checksum_buf;
}
#endif
av_md5_update(s->md5_ctx, src, w << pixel_shift);
}
av_md5_final(s->md5_ctx, md5);
if (!memcmp(md5, s->sei.picture_hash.md5[i], 16)) {
av_log (s->avctx, AV_LOG_DEBUG, "plane %d - correct ", i);
print_md5(s->avctx, AV_LOG_DEBUG, md5);
av_log (s->avctx, AV_LOG_DEBUG, "; ");
} else {
av_log (s->avctx, AV_LOG_ERROR, "mismatching checksum of plane %d - ", i);
print_md5(s->avctx, AV_LOG_ERROR, md5);
av_log (s->avctx, AV_LOG_ERROR, " != ");
print_md5(s->avctx, AV_LOG_ERROR, s->sei.picture_hash.md5[i]);
av_log (s->avctx, AV_LOG_ERROR, "\n");
return AVERROR_INVALIDDATA;
}
}
av_log(s->avctx, AV_LOG_DEBUG, "\n");
return 0;
}
static int hevc_decode_extradata(HEVCContext *s, uint8_t *buf, int length, int first)
{
int ret, i;
ret = ff_hevc_decode_extradata(buf, length, &s->ps, &s->sei, &s->is_nalff,
&s->nal_length_size, s->avctx->err_recognition,
s->apply_defdispwin, s->avctx);
if (ret < 0)
return ret;
/* export stream parameters from the first SPS */
for (i = 0; i < FF_ARRAY_ELEMS(s->ps.sps_list); i++) {
if (first && s->ps.sps_list[i]) {
const HEVCSPS *sps = (const HEVCSPS*)s->ps.sps_list[i]->data;
export_stream_params(s->avctx, &s->ps, sps);
break;
}
}
return 0;
}
static int hevc_decode_frame(AVCodecContext *avctx, void *data, int *got_output,
AVPacket *avpkt)
{
int ret;
int new_extradata_size;
uint8_t *new_extradata;
HEVCContext *s = avctx->priv_data;
if (!avpkt->size) {
ret = ff_hevc_output_frame(s, data, 1);
if (ret < 0)
return ret;
*got_output = ret;
return 0;
}
new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
&new_extradata_size);
if (new_extradata && new_extradata_size > 0) {
ret = hevc_decode_extradata(s, new_extradata, new_extradata_size, 0);
if (ret < 0)
return ret;
}
s->ref = NULL;
ret = decode_nal_units(s, avpkt->data, avpkt->size);
if (ret < 0)
return ret;
if (avctx->hwaccel) {
if (s->ref && (ret = avctx->hwaccel->end_frame(avctx)) < 0) {
av_log(avctx, AV_LOG_ERROR,
"hardware accelerator failed to decode picture\n");
ff_hevc_unref_frame(s, s->ref, ~0);
return ret;
}
} else {
/* verify the SEI checksum */
if (avctx->err_recognition & AV_EF_CRCCHECK && s->is_decoded &&
s->sei.picture_hash.is_md5) {
ret = verify_md5(s, s->ref->frame);
if (ret < 0 && avctx->err_recognition & AV_EF_EXPLODE) {
ff_hevc_unref_frame(s, s->ref, ~0);
return ret;
}
}
}
s->sei.picture_hash.is_md5 = 0;
if (s->is_decoded) {
av_log(avctx, AV_LOG_DEBUG, "Decoded frame with POC %d.\n", s->poc);
s->is_decoded = 0;
}
if (s->output_frame->buf[0]) {
av_frame_move_ref(data, s->output_frame);
*got_output = 1;
}
return avpkt->size;
}
static int hevc_ref_frame(HEVCContext *s, HEVCFrame *dst, HEVCFrame *src)
{
int ret;
ret = ff_thread_ref_frame(&dst->tf, &src->tf);
if (ret < 0)
return ret;
dst->tab_mvf_buf = av_buffer_ref(src->tab_mvf_buf);
if (!dst->tab_mvf_buf)
goto fail;
dst->tab_mvf = src->tab_mvf;
dst->rpl_tab_buf = av_buffer_ref(src->rpl_tab_buf);
if (!dst->rpl_tab_buf)
goto fail;
dst->rpl_tab = src->rpl_tab;
dst->rpl_buf = av_buffer_ref(src->rpl_buf);
if (!dst->rpl_buf)
goto fail;
dst->poc = src->poc;
dst->ctb_count = src->ctb_count;
dst->flags = src->flags;
dst->sequence = src->sequence;
if (src->hwaccel_picture_private) {
dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
if (!dst->hwaccel_priv_buf)
goto fail;
dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
}
return 0;
fail:
ff_hevc_unref_frame(s, dst, ~0);
return AVERROR(ENOMEM);
}
static av_cold int hevc_decode_free(AVCodecContext *avctx)
{
HEVCContext *s = avctx->priv_data;
int i;
pic_arrays_free(s);
av_freep(&s->md5_ctx);
av_freep(&s->cabac_state);
for (i = 0; i < 3; i++) {
av_freep(&s->sao_pixel_buffer_h[i]);
av_freep(&s->sao_pixel_buffer_v[i]);
}
av_frame_free(&s->output_frame);
for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
ff_hevc_unref_frame(s, &s->DPB[i], ~0);
av_frame_free(&s->DPB[i].frame);
}
ff_hevc_ps_uninit(&s->ps);
av_freep(&s->sh.entry_point_offset);
av_freep(&s->sh.offset);
av_freep(&s->sh.size);
for (i = 1; i < s->threads_number; i++) {
HEVCLocalContext *lc = s->HEVClcList[i];
if (lc) {
av_freep(&s->HEVClcList[i]);
av_freep(&s->sList[i]);
}
}
if (s->HEVClc == s->HEVClcList[0])
s->HEVClc = NULL;
av_freep(&s->HEVClcList[0]);
ff_h2645_packet_uninit(&s->pkt);
return 0;
}
static av_cold int hevc_init_context(AVCodecContext *avctx)
{
HEVCContext *s = avctx->priv_data;
int i;
s->avctx = avctx;
s->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
if (!s->HEVClc)
goto fail;
s->HEVClcList[0] = s->HEVClc;
s->sList[0] = s;
s->cabac_state = av_malloc(HEVC_CONTEXTS);
if (!s->cabac_state)
goto fail;
s->output_frame = av_frame_alloc();
if (!s->output_frame)
goto fail;
for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
s->DPB[i].frame = av_frame_alloc();
if (!s->DPB[i].frame)
goto fail;
s->DPB[i].tf.f = s->DPB[i].frame;
}
s->max_ra = INT_MAX;
s->md5_ctx = av_md5_alloc();
if (!s->md5_ctx)
goto fail;
ff_bswapdsp_init(&s->bdsp);
s->context_initialized = 1;
s->eos = 0;
ff_hevc_reset_sei(&s->sei);
return 0;
fail:
hevc_decode_free(avctx);
return AVERROR(ENOMEM);
}
#if HAVE_THREADS
static int hevc_update_thread_context(AVCodecContext *dst,
const AVCodecContext *src)
{
HEVCContext *s = dst->priv_data;
HEVCContext *s0 = src->priv_data;
int i, ret;
if (!s->context_initialized) {
ret = hevc_init_context(dst);
if (ret < 0)
return ret;
}
for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
ff_hevc_unref_frame(s, &s->DPB[i], ~0);
if (s0->DPB[i].frame->buf[0]) {
ret = hevc_ref_frame(s, &s->DPB[i], &s0->DPB[i]);
if (ret < 0)
return ret;
}
}
if (s->ps.sps != s0->ps.sps)
s->ps.sps = NULL;
for (i = 0; i < FF_ARRAY_ELEMS(s->ps.vps_list); i++) {
av_buffer_unref(&s->ps.vps_list[i]);
if (s0->ps.vps_list[i]) {
s->ps.vps_list[i] = av_buffer_ref(s0->ps.vps_list[i]);
if (!s->ps.vps_list[i])
return AVERROR(ENOMEM);
}
}
for (i = 0; i < FF_ARRAY_ELEMS(s->ps.sps_list); i++) {
av_buffer_unref(&s->ps.sps_list[i]);
if (s0->ps.sps_list[i]) {
s->ps.sps_list[i] = av_buffer_ref(s0->ps.sps_list[i]);
if (!s->ps.sps_list[i])
return AVERROR(ENOMEM);
}
}
for (i = 0; i < FF_ARRAY_ELEMS(s->ps.pps_list); i++) {
av_buffer_unref(&s->ps.pps_list[i]);
if (s0->ps.pps_list[i]) {
s->ps.pps_list[i] = av_buffer_ref(s0->ps.pps_list[i]);
if (!s->ps.pps_list[i])
return AVERROR(ENOMEM);
}
}
if (s->ps.sps != s0->ps.sps)
if ((ret = set_sps(s, s0->ps.sps, src->pix_fmt)) < 0)
return ret;
s->seq_decode = s0->seq_decode;
s->seq_output = s0->seq_output;
s->pocTid0 = s0->pocTid0;
s->max_ra = s0->max_ra;
s->eos = s0->eos;
s->no_rasl_output_flag = s0->no_rasl_output_flag;
s->is_nalff = s0->is_nalff;
s->nal_length_size = s0->nal_length_size;
s->threads_number = s0->threads_number;
s->threads_type = s0->threads_type;
if (s0->eos) {
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
}
s->sei.frame_packing = s0->sei.frame_packing;
s->sei.display_orientation = s0->sei.display_orientation;
s->sei.mastering_display = s0->sei.mastering_display;
s->sei.content_light = s0->sei.content_light;
s->sei.alternative_transfer = s0->sei.alternative_transfer;
return 0;
}
#endif
static av_cold int hevc_decode_init(AVCodecContext *avctx)
{
HEVCContext *s = avctx->priv_data;
int ret;
avctx->internal->allocate_progress = 1;
ret = hevc_init_context(avctx);
if (ret < 0)
return ret;
s->enable_parallel_tiles = 0;
s->sei.picture_timing.picture_struct = 0;
s->eos = 1;
atomic_init(&s->wpp_err, 0);
if(avctx->active_thread_type & FF_THREAD_SLICE)
s->threads_number = avctx->thread_count;
else
s->threads_number = 1;
if (avctx->extradata_size > 0 && avctx->extradata) {
ret = hevc_decode_extradata(s, avctx->extradata, avctx->extradata_size, 1);
if (ret < 0) {
hevc_decode_free(avctx);
return ret;
}
}
if((avctx->active_thread_type & FF_THREAD_FRAME) && avctx->thread_count > 1)
s->threads_type = FF_THREAD_FRAME;
else
s->threads_type = FF_THREAD_SLICE;
return 0;
}
#if HAVE_THREADS
static av_cold int hevc_init_thread_copy(AVCodecContext *avctx)
{
HEVCContext *s = avctx->priv_data;
int ret;
memset(s, 0, sizeof(*s));
ret = hevc_init_context(avctx);
if (ret < 0)
return ret;
return 0;
}
#endif
static void hevc_decode_flush(AVCodecContext *avctx)
{
HEVCContext *s = avctx->priv_data;
ff_hevc_flush_dpb(s);
s->max_ra = INT_MAX;
s->eos = 1;
}
#define OFFSET(x) offsetof(HEVCContext, x)
#define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
static const AVOption options[] = {
{ "apply_defdispwin", "Apply default display window from VUI", OFFSET(apply_defdispwin),
AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, PAR },
{ "strict-displaywin", "stricly apply default display window size", OFFSET(apply_defdispwin),
AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, PAR },
{ NULL },
};
static const AVClass hevc_decoder_class = {
.class_name = "HEVC decoder",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_hevc_decoder = {
.name = "hevc",
.long_name = NULL_IF_CONFIG_SMALL("HEVC (High Efficiency Video Coding)"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_HEVC,
.priv_data_size = sizeof(HEVCContext),
.priv_class = &hevc_decoder_class,
.init = hevc_decode_init,
.close = hevc_decode_free,
.decode = hevc_decode_frame,
.flush = hevc_decode_flush,
.update_thread_context = ONLY_IF_THREADS_ENABLED(hevc_update_thread_context),
.init_thread_copy = ONLY_IF_THREADS_ENABLED(hevc_init_thread_copy),
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_FRAME_THREADS,
.caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_EXPORTS_CROPPING,
.profiles = NULL_IF_CONFIG_SMALL(ff_hevc_profiles),
.hw_configs = (const AVCodecHWConfigInternal*[]) {
#if CONFIG_HEVC_DXVA2_HWACCEL
HWACCEL_DXVA2(hevc),
#endif
#if CONFIG_HEVC_D3D11VA_HWACCEL
HWACCEL_D3D11VA(hevc),
#endif
#if CONFIG_HEVC_D3D11VA2_HWACCEL
HWACCEL_D3D11VA2(hevc),
#endif
#if CONFIG_HEVC_NVDEC_HWACCEL
HWACCEL_NVDEC(hevc),
#endif
#if CONFIG_HEVC_VAAPI_HWACCEL
HWACCEL_VAAPI(hevc),
#endif
#if CONFIG_HEVC_VDPAU_HWACCEL
HWACCEL_VDPAU(hevc),
#endif
#if CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL
HWACCEL_VIDEOTOOLBOX(hevc),
#endif
NULL
},
};
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_799_0 |
crossvul-cpp_data_good_1211_0 | /*
* Copyright (c) 2006 Oracle. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/module.h>
#include <net/tcp.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/tcp.h>
#include "rds.h"
#include "tcp.h"
/* only for info exporting */
static DEFINE_SPINLOCK(rds_tcp_tc_list_lock);
static LIST_HEAD(rds_tcp_tc_list);
static unsigned int rds_tcp_tc_count;
/* Track rds_tcp_connection structs so they can be cleaned up */
static DEFINE_SPINLOCK(rds_tcp_conn_lock);
static LIST_HEAD(rds_tcp_conn_list);
static struct kmem_cache *rds_tcp_conn_slab;
#define RDS_TCP_DEFAULT_BUFSIZE (128 * 1024)
/* doing it this way avoids calling tcp_sk() */
void rds_tcp_nonagle(struct socket *sock)
{
mm_segment_t oldfs = get_fs();
int val = 1;
set_fs(KERNEL_DS);
sock->ops->setsockopt(sock, SOL_TCP, TCP_NODELAY, (char __user *)&val,
sizeof(val));
set_fs(oldfs);
}
/* All module specific customizations to the RDS-TCP socket should be done in
* rds_tcp_tune() and applied after socket creation. In general these
* customizations should be tunable via module_param()
*/
void rds_tcp_tune(struct socket *sock)
{
rds_tcp_nonagle(sock);
}
u32 rds_tcp_snd_nxt(struct rds_tcp_connection *tc)
{
return tcp_sk(tc->t_sock->sk)->snd_nxt;
}
u32 rds_tcp_snd_una(struct rds_tcp_connection *tc)
{
return tcp_sk(tc->t_sock->sk)->snd_una;
}
void rds_tcp_restore_callbacks(struct socket *sock,
struct rds_tcp_connection *tc)
{
rdsdebug("restoring sock %p callbacks from tc %p\n", sock, tc);
write_lock_bh(&sock->sk->sk_callback_lock);
/* done under the callback_lock to serialize with write_space */
spin_lock(&rds_tcp_tc_list_lock);
list_del_init(&tc->t_list_item);
rds_tcp_tc_count--;
spin_unlock(&rds_tcp_tc_list_lock);
tc->t_sock = NULL;
sock->sk->sk_write_space = tc->t_orig_write_space;
sock->sk->sk_data_ready = tc->t_orig_data_ready;
sock->sk->sk_state_change = tc->t_orig_state_change;
sock->sk->sk_user_data = NULL;
write_unlock_bh(&sock->sk->sk_callback_lock);
}
/*
* This is the only path that sets tc->t_sock. Send and receive trust that
* it is set. The RDS_CONN_CONNECTED bit protects those paths from being
* called while it isn't set.
*/
void rds_tcp_set_callbacks(struct socket *sock, struct rds_connection *conn)
{
struct rds_tcp_connection *tc = conn->c_transport_data;
rdsdebug("setting sock %p callbacks to tc %p\n", sock, tc);
write_lock_bh(&sock->sk->sk_callback_lock);
/* done under the callback_lock to serialize with write_space */
spin_lock(&rds_tcp_tc_list_lock);
list_add_tail(&tc->t_list_item, &rds_tcp_tc_list);
rds_tcp_tc_count++;
spin_unlock(&rds_tcp_tc_list_lock);
/* accepted sockets need our listen data ready undone */
if (sock->sk->sk_data_ready == rds_tcp_listen_data_ready)
sock->sk->sk_data_ready = sock->sk->sk_user_data;
tc->t_sock = sock;
tc->conn = conn;
tc->t_orig_data_ready = sock->sk->sk_data_ready;
tc->t_orig_write_space = sock->sk->sk_write_space;
tc->t_orig_state_change = sock->sk->sk_state_change;
sock->sk->sk_user_data = conn;
sock->sk->sk_data_ready = rds_tcp_data_ready;
sock->sk->sk_write_space = rds_tcp_write_space;
sock->sk->sk_state_change = rds_tcp_state_change;
write_unlock_bh(&sock->sk->sk_callback_lock);
}
static void rds_tcp_tc_info(struct socket *sock, unsigned int len,
struct rds_info_iterator *iter,
struct rds_info_lengths *lens)
{
struct rds_info_tcp_socket tsinfo;
struct rds_tcp_connection *tc;
unsigned long flags;
struct sockaddr_in sin;
int sinlen;
spin_lock_irqsave(&rds_tcp_tc_list_lock, flags);
if (len / sizeof(tsinfo) < rds_tcp_tc_count)
goto out;
list_for_each_entry(tc, &rds_tcp_tc_list, t_list_item) {
sock->ops->getname(sock, (struct sockaddr *)&sin, &sinlen, 0);
tsinfo.local_addr = sin.sin_addr.s_addr;
tsinfo.local_port = sin.sin_port;
sock->ops->getname(sock, (struct sockaddr *)&sin, &sinlen, 1);
tsinfo.peer_addr = sin.sin_addr.s_addr;
tsinfo.peer_port = sin.sin_port;
tsinfo.hdr_rem = tc->t_tinc_hdr_rem;
tsinfo.data_rem = tc->t_tinc_data_rem;
tsinfo.last_sent_nxt = tc->t_last_sent_nxt;
tsinfo.last_expected_una = tc->t_last_expected_una;
tsinfo.last_seen_una = tc->t_last_seen_una;
rds_info_copy(iter, &tsinfo, sizeof(tsinfo));
}
out:
lens->nr = rds_tcp_tc_count;
lens->each = sizeof(tsinfo);
spin_unlock_irqrestore(&rds_tcp_tc_list_lock, flags);
}
static int rds_tcp_laddr_check(struct net *net, __be32 addr)
{
if (inet_addr_type(net, addr) == RTN_LOCAL)
return 0;
return -EADDRNOTAVAIL;
}
static int rds_tcp_conn_alloc(struct rds_connection *conn, gfp_t gfp)
{
struct rds_tcp_connection *tc;
tc = kmem_cache_alloc(rds_tcp_conn_slab, gfp);
if (!tc)
return -ENOMEM;
tc->t_sock = NULL;
tc->t_tinc = NULL;
tc->t_tinc_hdr_rem = sizeof(struct rds_header);
tc->t_tinc_data_rem = 0;
conn->c_transport_data = tc;
spin_lock_irq(&rds_tcp_conn_lock);
list_add_tail(&tc->t_tcp_node, &rds_tcp_conn_list);
spin_unlock_irq(&rds_tcp_conn_lock);
rdsdebug("alloced tc %p\n", conn->c_transport_data);
return 0;
}
static void rds_tcp_conn_free(void *arg)
{
struct rds_tcp_connection *tc = arg;
unsigned long flags;
rdsdebug("freeing tc %p\n", tc);
spin_lock_irqsave(&rds_tcp_conn_lock, flags);
list_del(&tc->t_tcp_node);
spin_unlock_irqrestore(&rds_tcp_conn_lock, flags);
kmem_cache_free(rds_tcp_conn_slab, tc);
}
static void rds_tcp_destroy_conns(void)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
/* avoid calling conn_destroy with irqs off */
spin_lock_irq(&rds_tcp_conn_lock);
list_splice(&rds_tcp_conn_list, &tmp_list);
INIT_LIST_HEAD(&rds_tcp_conn_list);
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) {
if (tc->conn->c_passive)
rds_conn_destroy(tc->conn->c_passive);
rds_conn_destroy(tc->conn);
}
}
static void rds_tcp_exit(void);
struct rds_transport rds_tcp_transport = {
.laddr_check = rds_tcp_laddr_check,
.xmit_prepare = rds_tcp_xmit_prepare,
.xmit_complete = rds_tcp_xmit_complete,
.xmit = rds_tcp_xmit,
.recv = rds_tcp_recv,
.conn_alloc = rds_tcp_conn_alloc,
.conn_free = rds_tcp_conn_free,
.conn_connect = rds_tcp_conn_connect,
.conn_shutdown = rds_tcp_conn_shutdown,
.inc_copy_to_user = rds_tcp_inc_copy_to_user,
.inc_free = rds_tcp_inc_free,
.stats_info_copy = rds_tcp_stats_info_copy,
.exit = rds_tcp_exit,
.t_owner = THIS_MODULE,
.t_name = "tcp",
.t_type = RDS_TRANS_TCP,
.t_prefer_loopback = 1,
};
static int rds_tcp_netid;
/* per-network namespace private data for this module */
struct rds_tcp_net {
struct socket *rds_tcp_listen_sock;
struct work_struct rds_tcp_accept_w;
};
static void rds_tcp_accept_worker(struct work_struct *work)
{
struct rds_tcp_net *rtn = container_of(work,
struct rds_tcp_net,
rds_tcp_accept_w);
while (rds_tcp_accept_one(rtn->rds_tcp_listen_sock) == 0)
cond_resched();
}
void rds_tcp_accept_work(struct sock *sk)
{
struct net *net = sock_net(sk);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
queue_work(rds_wq, &rtn->rds_tcp_accept_w);
}
static __net_init int rds_tcp_init_net(struct net *net)
{
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
rtn->rds_tcp_listen_sock = rds_tcp_listen_init(net);
if (!rtn->rds_tcp_listen_sock) {
pr_warn("could not set up listen sock\n");
return -EAFNOSUPPORT;
}
INIT_WORK(&rtn->rds_tcp_accept_w, rds_tcp_accept_worker);
return 0;
}
static void __net_exit rds_tcp_exit_net(struct net *net)
{
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
/* If rds_tcp_exit_net() is called as a result of netns deletion,
* the rds_tcp_kill_sock() device notifier would already have cleaned
* up the listen socket, thus there is no work to do in this function.
*
* If rds_tcp_exit_net() is called as a result of module unload,
* i.e., due to rds_tcp_exit() -> unregister_pernet_subsys(), then
* we do need to clean up the listen socket here.
*/
if (rtn->rds_tcp_listen_sock) {
rds_tcp_listen_stop(rtn->rds_tcp_listen_sock);
rtn->rds_tcp_listen_sock = NULL;
flush_work(&rtn->rds_tcp_accept_w);
}
}
static struct pernet_operations rds_tcp_net_ops = {
.init = rds_tcp_init_net,
.exit = rds_tcp_exit_net,
.id = &rds_tcp_netid,
.size = sizeof(struct rds_tcp_net),
};
static void rds_tcp_kill_sock(struct net *net)
{
struct rds_tcp_connection *tc, *_tc;
struct sock *sk;
LIST_HEAD(tmp_list);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
rds_tcp_listen_stop(rtn->rds_tcp_listen_sock);
rtn->rds_tcp_listen_sock = NULL;
flush_work(&rtn->rds_tcp_accept_w);
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
struct net *c_net = read_pnet(&tc->conn->c_net);
if (net != c_net)
continue;
list_move_tail(&tc->t_tcp_node, &tmp_list);
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) {
if (tc->t_sock) {
sk = tc->t_sock->sk;
sk->sk_prot->disconnect(sk, 0);
tcp_done(sk);
}
if (tc->conn->c_passive)
rds_conn_destroy(tc->conn->c_passive);
rds_conn_destroy(tc->conn);
}
}
static int rds_tcp_dev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
/* rds-tcp registers as a pernet subys, so the ->exit will only
* get invoked after network acitivity has quiesced. We need to
* clean up all sockets to quiesce network activity, and use
* the unregistration of the per-net loopback device as a trigger
* to start that cleanup.
*/
if (event == NETDEV_UNREGISTER_FINAL &&
dev->ifindex == LOOPBACK_IFINDEX)
rds_tcp_kill_sock(dev_net(dev));
return NOTIFY_DONE;
}
static struct notifier_block rds_tcp_dev_notifier = {
.notifier_call = rds_tcp_dev_event,
.priority = -10, /* must be called after other network notifiers */
};
static void rds_tcp_exit(void)
{
rds_info_deregister_func(RDS_INFO_TCP_SOCKETS, rds_tcp_tc_info);
unregister_pernet_subsys(&rds_tcp_net_ops);
if (unregister_netdevice_notifier(&rds_tcp_dev_notifier))
pr_warn("could not unregister rds_tcp_dev_notifier\n");
rds_tcp_destroy_conns();
rds_trans_unregister(&rds_tcp_transport);
rds_tcp_recv_exit();
kmem_cache_destroy(rds_tcp_conn_slab);
}
module_exit(rds_tcp_exit);
static int rds_tcp_init(void)
{
int ret;
rds_tcp_conn_slab = kmem_cache_create("rds_tcp_connection",
sizeof(struct rds_tcp_connection),
0, 0, NULL);
if (!rds_tcp_conn_slab) {
ret = -ENOMEM;
goto out;
}
ret = register_netdevice_notifier(&rds_tcp_dev_notifier);
if (ret) {
pr_warn("could not register rds_tcp_dev_notifier\n");
goto out;
}
ret = register_pernet_subsys(&rds_tcp_net_ops);
if (ret)
goto out_slab;
ret = rds_tcp_recv_init();
if (ret)
goto out_pernet;
ret = rds_trans_register(&rds_tcp_transport);
if (ret)
goto out_recv;
rds_info_register_func(RDS_INFO_TCP_SOCKETS, rds_tcp_tc_info);
goto out;
out_recv:
rds_tcp_recv_exit();
out_pernet:
unregister_pernet_subsys(&rds_tcp_net_ops);
out_slab:
kmem_cache_destroy(rds_tcp_conn_slab);
out:
return ret;
}
module_init(rds_tcp_init);
MODULE_AUTHOR("Oracle Corporation <rds-devel@oss.oracle.com>");
MODULE_DESCRIPTION("RDS: TCP transport");
MODULE_LICENSE("Dual BSD/GPL");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_1211_0 |
crossvul-cpp_data_good_2839_0 | /*
* Cryptographic API.
*
* RNG operations.
*
* Copyright (c) 2008 Neil Horman <nhorman@tuxdriver.com>
* Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <linux/atomic.h>
#include <crypto/internal/rng.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/random.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/cryptouser.h>
#include <net/netlink.h>
#include "internal.h"
static DEFINE_MUTEX(crypto_default_rng_lock);
struct crypto_rng *crypto_default_rng;
EXPORT_SYMBOL_GPL(crypto_default_rng);
static int crypto_default_rng_refcnt;
static inline struct crypto_rng *__crypto_rng_cast(struct crypto_tfm *tfm)
{
return container_of(tfm, struct crypto_rng, base);
}
int crypto_rng_reset(struct crypto_rng *tfm, const u8 *seed, unsigned int slen)
{
u8 *buf = NULL;
int err;
if (!seed && slen) {
buf = kmalloc(slen, GFP_KERNEL);
if (!buf)
return -ENOMEM;
get_random_bytes(buf, slen);
seed = buf;
}
err = crypto_rng_alg(tfm)->seed(tfm, seed, slen);
kfree(buf);
return err;
}
EXPORT_SYMBOL_GPL(crypto_rng_reset);
static int crypto_rng_init_tfm(struct crypto_tfm *tfm)
{
return 0;
}
static unsigned int seedsize(struct crypto_alg *alg)
{
struct rng_alg *ralg = container_of(alg, struct rng_alg, base);
return ralg->seedsize;
}
#ifdef CONFIG_NET
static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_rng rrng;
strncpy(rrng.type, "rng", sizeof(rrng.type));
rrng.seedsize = seedsize(alg);
if (nla_put(skb, CRYPTOCFGA_REPORT_RNG,
sizeof(struct crypto_report_rng), &rrng))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
#else
static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)
{
return -ENOSYS;
}
#endif
static void crypto_rng_show(struct seq_file *m, struct crypto_alg *alg)
__attribute__ ((unused));
static void crypto_rng_show(struct seq_file *m, struct crypto_alg *alg)
{
seq_printf(m, "type : rng\n");
seq_printf(m, "seedsize : %u\n", seedsize(alg));
}
static const struct crypto_type crypto_rng_type = {
.extsize = crypto_alg_extsize,
.init_tfm = crypto_rng_init_tfm,
#ifdef CONFIG_PROC_FS
.show = crypto_rng_show,
#endif
.report = crypto_rng_report,
.maskclear = ~CRYPTO_ALG_TYPE_MASK,
.maskset = CRYPTO_ALG_TYPE_MASK,
.type = CRYPTO_ALG_TYPE_RNG,
.tfmsize = offsetof(struct crypto_rng, base),
};
struct crypto_rng *crypto_alloc_rng(const char *alg_name, u32 type, u32 mask)
{
return crypto_alloc_tfm(alg_name, &crypto_rng_type, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_alloc_rng);
int crypto_get_default_rng(void)
{
struct crypto_rng *rng;
int err;
mutex_lock(&crypto_default_rng_lock);
if (!crypto_default_rng) {
rng = crypto_alloc_rng("stdrng", 0, 0);
err = PTR_ERR(rng);
if (IS_ERR(rng))
goto unlock;
err = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));
if (err) {
crypto_free_rng(rng);
goto unlock;
}
crypto_default_rng = rng;
}
crypto_default_rng_refcnt++;
err = 0;
unlock:
mutex_unlock(&crypto_default_rng_lock);
return err;
}
EXPORT_SYMBOL_GPL(crypto_get_default_rng);
void crypto_put_default_rng(void)
{
mutex_lock(&crypto_default_rng_lock);
if (!--crypto_default_rng_refcnt) {
crypto_free_rng(crypto_default_rng);
crypto_default_rng = NULL;
}
mutex_unlock(&crypto_default_rng_lock);
}
EXPORT_SYMBOL_GPL(crypto_put_default_rng);
int crypto_register_rng(struct rng_alg *alg)
{
struct crypto_alg *base = &alg->base;
if (alg->seedsize > PAGE_SIZE / 8)
return -EINVAL;
base->cra_type = &crypto_rng_type;
base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK;
base->cra_flags |= CRYPTO_ALG_TYPE_RNG;
return crypto_register_alg(base);
}
EXPORT_SYMBOL_GPL(crypto_register_rng);
void crypto_unregister_rng(struct rng_alg *alg)
{
crypto_unregister_alg(&alg->base);
}
EXPORT_SYMBOL_GPL(crypto_unregister_rng);
int crypto_register_rngs(struct rng_alg *algs, int count)
{
int i, ret;
for (i = 0; i < count; i++) {
ret = crypto_register_rng(algs + i);
if (ret)
goto err;
}
return 0;
err:
for (--i; i >= 0; --i)
crypto_unregister_rng(algs + i);
return ret;
}
EXPORT_SYMBOL_GPL(crypto_register_rngs);
void crypto_unregister_rngs(struct rng_alg *algs, int count)
{
int i;
for (i = count - 1; i >= 0; --i)
crypto_unregister_rng(algs + i);
}
EXPORT_SYMBOL_GPL(crypto_unregister_rngs);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Random Number Generator");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_2839_0 |
crossvul-cpp_data_bad_4058_0 | /* -=- sraRegion.c
* Copyright (c) 2001 James "Wez" Weatherall, Johannes E. Schindelin
*
* A general purpose region clipping library
* Only deals with rectangular regions, though.
*/
#include <rfb/rfb.h>
#include <rfb/rfbregion.h>
/* -=- Internal Span structure */
struct sraRegion;
typedef struct sraSpan {
struct sraSpan *_next;
struct sraSpan *_prev;
int start;
int end;
struct sraRegion *subspan;
} sraSpan;
typedef struct sraRegion {
sraSpan front;
sraSpan back;
} sraSpanList;
/* -=- Span routines */
sraSpanList *sraSpanListDup(const sraSpanList *src);
void sraSpanListDestroy(sraSpanList *list);
static sraSpan *
sraSpanCreate(int start, int end, const sraSpanList *subspan) {
sraSpan *item = (sraSpan*)malloc(sizeof(sraSpan));
if (!item) return NULL;
item->_next = item->_prev = NULL;
item->start = start;
item->end = end;
item->subspan = sraSpanListDup(subspan);
return item;
}
static sraSpan *
sraSpanDup(const sraSpan *src) {
sraSpan *span;
if (!src) return NULL;
span = sraSpanCreate(src->start, src->end, src->subspan);
return span;
}
static void
sraSpanInsertAfter(sraSpan *newspan, sraSpan *after) {
newspan->_next = after->_next;
newspan->_prev = after;
after->_next->_prev = newspan;
after->_next = newspan;
}
static void
sraSpanInsertBefore(sraSpan *newspan, sraSpan *before) {
newspan->_next = before;
newspan->_prev = before->_prev;
before->_prev->_next = newspan;
before->_prev = newspan;
}
static void
sraSpanRemove(sraSpan *span) {
span->_prev->_next = span->_next;
span->_next->_prev = span->_prev;
}
static void
sraSpanDestroy(sraSpan *span) {
if (span->subspan) sraSpanListDestroy(span->subspan);
free(span);
}
#ifdef DEBUG
static void
sraSpanCheck(const sraSpan *span, const char *text) {
/* Check the span is valid! */
if (span->start == span->end) {
printf(text);
printf(":%d-%d\n", span->start, span->end);
}
}
#endif
/* -=- SpanList routines */
static void sraSpanPrint(const sraSpan *s);
static void
sraSpanListPrint(const sraSpanList *l) {
sraSpan *curr;
if (!l) {
printf("NULL");
return;
}
curr = l->front._next;
printf("[");
while (curr != &(l->back)) {
sraSpanPrint(curr);
curr = curr->_next;
}
printf("]");
}
void
sraSpanPrint(const sraSpan *s) {
printf("(%d-%d)", (s->start), (s->end));
if (s->subspan)
sraSpanListPrint(s->subspan);
}
static sraSpanList *
sraSpanListCreate(void) {
sraSpanList *item = (sraSpanList*)malloc(sizeof(sraSpanList));
if (!item) return NULL;
item->front._next = &(item->back);
item->front._prev = NULL;
item->back._prev = &(item->front);
item->back._next = NULL;
return item;
}
sraSpanList *
sraSpanListDup(const sraSpanList *src) {
sraSpanList *newlist;
sraSpan *newspan, *curr;
if (!src) return NULL;
newlist = sraSpanListCreate();
curr = src->front._next;
while (curr != &(src->back)) {
newspan = sraSpanDup(curr);
sraSpanInsertBefore(newspan, &(newlist->back));
curr = curr->_next;
}
return newlist;
}
void
sraSpanListDestroy(sraSpanList *list) {
sraSpan *curr, *next;
while (list->front._next != &(list->back)) {
curr = list->front._next;
next = curr->_next;
sraSpanRemove(curr);
sraSpanDestroy(curr);
curr = next;
}
free(list);
}
static void
sraSpanListMakeEmpty(sraSpanList *list) {
sraSpan *curr, *next;
while (list->front._next != &(list->back)) {
curr = list->front._next;
next = curr->_next;
sraSpanRemove(curr);
sraSpanDestroy(curr);
curr = next;
}
list->front._next = &(list->back);
list->front._prev = NULL;
list->back._prev = &(list->front);
list->back._next = NULL;
}
static rfbBool
sraSpanListEqual(const sraSpanList *s1, const sraSpanList *s2) {
sraSpan *sp1, *sp2;
if (!s1) {
if (!s2) {
return 1;
} else {
rfbErr("sraSpanListEqual:incompatible spans (only one NULL!)\n");
return FALSE;
}
}
sp1 = s1->front._next;
sp2 = s2->front._next;
while ((sp1 != &(s1->back)) &&
(sp2 != &(s2->back))) {
if ((sp1->start != sp2->start) ||
(sp1->end != sp2->end) ||
(!sraSpanListEqual(sp1->subspan, sp2->subspan))) {
return 0;
}
sp1 = sp1->_next;
sp2 = sp2->_next;
}
if ((sp1 == &(s1->back)) && (sp2 == &(s2->back))) {
return 1;
} else {
return 0;
}
}
static rfbBool
sraSpanListEmpty(const sraSpanList *list) {
return (list->front._next == &(list->back));
}
static unsigned long
sraSpanListCount(const sraSpanList *list) {
sraSpan *curr = list->front._next;
unsigned long count = 0;
while (curr != &(list->back)) {
if (curr->subspan) {
count += sraSpanListCount(curr->subspan);
} else {
count += 1;
}
curr = curr->_next;
}
return count;
}
static void
sraSpanMergePrevious(sraSpan *dest) {
sraSpan *prev = dest->_prev;
while ((prev->_prev) &&
(prev->end == dest->start) &&
(sraSpanListEqual(prev->subspan, dest->subspan))) {
/*
printf("merge_prev:");
sraSpanPrint(prev);
printf(" & ");
sraSpanPrint(dest);
printf("\n");
*/
dest->start = prev->start;
sraSpanRemove(prev);
sraSpanDestroy(prev);
prev = dest->_prev;
}
}
static void
sraSpanMergeNext(sraSpan *dest) {
sraSpan *next = dest->_next;
while ((next->_next) &&
(next->start == dest->end) &&
(sraSpanListEqual(next->subspan, dest->subspan))) {
/*
printf("merge_next:");
sraSpanPrint(dest);
printf(" & ");
sraSpanPrint(next);
printf("\n");
*/
dest->end = next->end;
sraSpanRemove(next);
sraSpanDestroy(next);
next = dest->_next;
}
}
static void
sraSpanListOr(sraSpanList *dest, const sraSpanList *src) {
sraSpan *d_curr, *s_curr;
int s_start, s_end;
if (!dest) {
if (!src) {
return;
} else {
rfbErr("sraSpanListOr:incompatible spans (only one NULL!)\n");
return;
}
}
d_curr = dest->front._next;
s_curr = src->front._next;
s_start = s_curr->start;
s_end = s_curr->end;
while (s_curr != &(src->back)) {
/* - If we are at end of destination list OR
If the new span comes before the next destination one */
if ((d_curr == &(dest->back)) ||
(d_curr->start >= s_end)) {
/* - Add the span */
sraSpanInsertBefore(sraSpanCreate(s_start, s_end,
s_curr->subspan),
d_curr);
if (d_curr != &(dest->back))
sraSpanMergePrevious(d_curr);
s_curr = s_curr->_next;
s_start = s_curr->start;
s_end = s_curr->end;
} else {
/* - If the new span overlaps the existing one */
if ((s_start < d_curr->end) &&
(s_end > d_curr->start)) {
/* - Insert new span before the existing destination one? */
if (s_start < d_curr->start) {
sraSpanInsertBefore(sraSpanCreate(s_start,
d_curr->start,
s_curr->subspan),
d_curr);
sraSpanMergePrevious(d_curr);
}
/* Split the existing span if necessary */
if (s_end < d_curr->end) {
sraSpanInsertAfter(sraSpanCreate(s_end,
d_curr->end,
d_curr->subspan),
d_curr);
d_curr->end = s_end;
}
if (s_start > d_curr->start) {
sraSpanInsertBefore(sraSpanCreate(d_curr->start,
s_start,
d_curr->subspan),
d_curr);
d_curr->start = s_start;
}
/* Recursively OR subspans */
sraSpanListOr(d_curr->subspan, s_curr->subspan);
/* Merge this span with previous or next? */
if (d_curr->_prev != &(dest->front))
sraSpanMergePrevious(d_curr);
if (d_curr->_next != &(dest->back))
sraSpanMergeNext(d_curr);
/* Move onto the next pair to compare */
if (s_end > d_curr->end) {
s_start = d_curr->end;
d_curr = d_curr->_next;
} else {
s_curr = s_curr->_next;
s_start = s_curr->start;
s_end = s_curr->end;
}
} else {
/* - No overlap. Move to the next destination span */
d_curr = d_curr->_next;
}
}
}
}
static rfbBool
sraSpanListAnd(sraSpanList *dest, const sraSpanList *src) {
sraSpan *d_curr, *s_curr, *d_next;
if (!dest) {
if (!src) {
return 1;
} else {
rfbErr("sraSpanListAnd:incompatible spans (only one NULL!)\n");
return FALSE;
}
}
d_curr = dest->front._next;
s_curr = src->front._next;
while ((s_curr != &(src->back)) && (d_curr != &(dest->back))) {
/* - If we haven't reached a destination span yet then move on */
if (d_curr->start >= s_curr->end) {
s_curr = s_curr->_next;
continue;
}
/* - If we are beyond the current destination span then remove it */
if (d_curr->end <= s_curr->start) {
sraSpan *next = d_curr->_next;
sraSpanRemove(d_curr);
sraSpanDestroy(d_curr);
d_curr = next;
continue;
}
/* - If we partially overlap a span then split it up or remove bits */
if (s_curr->start > d_curr->start) {
/* - The top bit of the span does not match */
d_curr->start = s_curr->start;
}
if (s_curr->end < d_curr->end) {
/* - The end of the span does not match */
sraSpanInsertAfter(sraSpanCreate(s_curr->end,
d_curr->end,
d_curr->subspan),
d_curr);
d_curr->end = s_curr->end;
}
/* - Now recursively process the affected span */
if (!sraSpanListAnd(d_curr->subspan, s_curr->subspan)) {
/* - The destination subspan is now empty, so we should remove it */
sraSpan *next = d_curr->_next;
sraSpanRemove(d_curr);
sraSpanDestroy(d_curr);
d_curr = next;
} else {
/* Merge this span with previous or next? */
if (d_curr->_prev != &(dest->front))
sraSpanMergePrevious(d_curr);
/* - Move on to the next span */
d_next = d_curr;
if (s_curr->end >= d_curr->end) {
d_next = d_curr->_next;
}
if (s_curr->end <= d_curr->end) {
s_curr = s_curr->_next;
}
d_curr = d_next;
}
}
while (d_curr != &(dest->back)) {
sraSpan *next = d_curr->_next;
sraSpanRemove(d_curr);
sraSpanDestroy(d_curr);
d_curr=next;
}
return !sraSpanListEmpty(dest);
}
static rfbBool
sraSpanListSubtract(sraSpanList *dest, const sraSpanList *src) {
sraSpan *d_curr, *s_curr;
if (!dest) {
if (!src) {
return 1;
} else {
rfbErr("sraSpanListSubtract:incompatible spans (only one NULL!)\n");
return FALSE;
}
}
d_curr = dest->front._next;
s_curr = src->front._next;
while ((s_curr != &(src->back)) && (d_curr != &(dest->back))) {
/* - If we haven't reached a destination span yet then move on */
if (d_curr->start >= s_curr->end) {
s_curr = s_curr->_next;
continue;
}
/* - If we are beyond the current destination span then skip it */
if (d_curr->end <= s_curr->start) {
d_curr = d_curr->_next;
continue;
}
/* - If we partially overlap the current span then split it up */
if (s_curr->start > d_curr->start) {
sraSpanInsertBefore(sraSpanCreate(d_curr->start,
s_curr->start,
d_curr->subspan),
d_curr);
d_curr->start = s_curr->start;
}
if (s_curr->end < d_curr->end) {
sraSpanInsertAfter(sraSpanCreate(s_curr->end,
d_curr->end,
d_curr->subspan),
d_curr);
d_curr->end = s_curr->end;
}
/* - Now recursively process the affected span */
if ((!d_curr->subspan) || !sraSpanListSubtract(d_curr->subspan, s_curr->subspan)) {
/* - The destination subspan is now empty, so we should remove it */
sraSpan *next = d_curr->_next;
sraSpanRemove(d_curr);
sraSpanDestroy(d_curr);
d_curr = next;
} else {
/* Merge this span with previous or next? */
if (d_curr->_prev != &(dest->front))
sraSpanMergePrevious(d_curr);
if (d_curr->_next != &(dest->back))
sraSpanMergeNext(d_curr);
/* - Move on to the next span */
if (s_curr->end > d_curr->end) {
d_curr = d_curr->_next;
} else {
s_curr = s_curr->_next;
}
}
}
return !sraSpanListEmpty(dest);
}
/* -=- Region routines */
sraRegion *
sraRgnCreate(void) {
return (sraRegion*)sraSpanListCreate();
}
sraRegion *
sraRgnCreateRect(int x1, int y1, int x2, int y2) {
sraSpanList *vlist, *hlist;
sraSpan *vspan, *hspan;
/* - Build the horizontal portion of the span */
hlist = sraSpanListCreate();
hspan = sraSpanCreate(x1, x2, NULL);
sraSpanInsertAfter(hspan, &(hlist->front));
/* - Build the vertical portion of the span */
vlist = sraSpanListCreate();
vspan = sraSpanCreate(y1, y2, hlist);
sraSpanInsertAfter(vspan, &(vlist->front));
sraSpanListDestroy(hlist);
return (sraRegion*)vlist;
}
sraRegion *
sraRgnCreateRgn(const sraRegion *src) {
return (sraRegion*)sraSpanListDup((sraSpanList*)src);
}
void
sraRgnDestroy(sraRegion *rgn) {
sraSpanListDestroy((sraSpanList*)rgn);
}
void
sraRgnMakeEmpty(sraRegion *rgn) {
sraSpanListMakeEmpty((sraSpanList*)rgn);
}
/* -=- Boolean Region ops */
rfbBool
sraRgnAnd(sraRegion *dst, const sraRegion *src) {
return sraSpanListAnd((sraSpanList*)dst, (sraSpanList*)src);
}
void
sraRgnOr(sraRegion *dst, const sraRegion *src) {
sraSpanListOr((sraSpanList*)dst, (sraSpanList*)src);
}
rfbBool
sraRgnSubtract(sraRegion *dst, const sraRegion *src) {
return sraSpanListSubtract((sraSpanList*)dst, (sraSpanList*)src);
}
void
sraRgnOffset(sraRegion *dst, int dx, int dy) {
sraSpan *vcurr, *hcurr;
vcurr = ((sraSpanList*)dst)->front._next;
while (vcurr != &(((sraSpanList*)dst)->back)) {
vcurr->start += dy;
vcurr->end += dy;
hcurr = vcurr->subspan->front._next;
while (hcurr != &(vcurr->subspan->back)) {
hcurr->start += dx;
hcurr->end += dx;
hcurr = hcurr->_next;
}
vcurr = vcurr->_next;
}
}
sraRegion *sraRgnBBox(const sraRegion *src) {
int xmin=((unsigned int)(int)-1)>>1,ymin=xmin,xmax=1-xmin,ymax=xmax;
sraSpan *vcurr, *hcurr;
if(!src)
return sraRgnCreate();
vcurr = ((sraSpanList*)src)->front._next;
while (vcurr != &(((sraSpanList*)src)->back)) {
if(vcurr->start<ymin)
ymin=vcurr->start;
if(vcurr->end>ymax)
ymax=vcurr->end;
hcurr = vcurr->subspan->front._next;
while (hcurr != &(vcurr->subspan->back)) {
if(hcurr->start<xmin)
xmin=hcurr->start;
if(hcurr->end>xmax)
xmax=hcurr->end;
hcurr = hcurr->_next;
}
vcurr = vcurr->_next;
}
if(xmax<xmin || ymax<ymin)
return sraRgnCreate();
return sraRgnCreateRect(xmin,ymin,xmax,ymax);
}
rfbBool
sraRgnPopRect(sraRegion *rgn, sraRect *rect, unsigned long flags) {
sraSpan *vcurr, *hcurr;
sraSpan *vend, *hend;
rfbBool right2left = (flags & 2) == 2;
rfbBool bottom2top = (flags & 1) == 1;
/* - Pick correct order */
if (bottom2top) {
vcurr = ((sraSpanList*)rgn)->back._prev;
vend = &(((sraSpanList*)rgn)->front);
} else {
vcurr = ((sraSpanList*)rgn)->front._next;
vend = &(((sraSpanList*)rgn)->back);
}
if (vcurr != vend) {
rect->y1 = vcurr->start;
rect->y2 = vcurr->end;
/* - Pick correct order */
if (right2left) {
hcurr = vcurr->subspan->back._prev;
hend = &(vcurr->subspan->front);
} else {
hcurr = vcurr->subspan->front._next;
hend = &(vcurr->subspan->back);
}
if (hcurr != hend) {
rect->x1 = hcurr->start;
rect->x2 = hcurr->end;
sraSpanRemove(hcurr);
sraSpanDestroy(hcurr);
if (sraSpanListEmpty(vcurr->subspan)) {
sraSpanRemove(vcurr);
sraSpanDestroy(vcurr);
}
#if 0
printf("poprect:(%dx%d)-(%dx%d)\n",
rect->x1, rect->y1, rect->x2, rect->y2);
#endif
return 1;
}
}
return 0;
}
unsigned long
sraRgnCountRects(const sraRegion *rgn) {
unsigned long count = sraSpanListCount((sraSpanList*)rgn);
return count;
}
rfbBool
sraRgnEmpty(const sraRegion *rgn) {
return sraSpanListEmpty((sraSpanList*)rgn);
}
/* iterator stuff */
sraRectangleIterator *sraRgnGetIterator(sraRegion *s)
{
/* these values have to be multiples of 4 */
#define DEFSIZE 4
#define DEFSTEP 8
sraRectangleIterator *i =
(sraRectangleIterator*)malloc(sizeof(sraRectangleIterator));
if(!i)
return NULL;
/* we have to recurse eventually. So, the first sPtr is the pointer to
the sraSpan in the first level. the second sPtr is the pointer to
the sraRegion.back. The third and fourth sPtr are for the second
recursion level and so on. */
i->sPtrs = (sraSpan**)malloc(sizeof(sraSpan*)*DEFSIZE);
if(!i->sPtrs) {
free(i);
return NULL;
}
i->ptrSize = DEFSIZE;
i->sPtrs[0] = &(s->front);
i->sPtrs[1] = &(s->back);
i->ptrPos = 0;
i->reverseX = 0;
i->reverseY = 0;
return i;
}
sraRectangleIterator *sraRgnGetReverseIterator(sraRegion *s,rfbBool reverseX,rfbBool reverseY)
{
sraRectangleIterator *i = sraRgnGetIterator(s);
if(reverseY) {
i->sPtrs[1] = &(s->front);
i->sPtrs[0] = &(s->back);
}
i->reverseX = reverseX;
i->reverseY = reverseY;
return(i);
}
static rfbBool sraReverse(sraRectangleIterator *i)
{
return( ((i->ptrPos&2) && i->reverseX) ||
(!(i->ptrPos&2) && i->reverseY));
}
static sraSpan* sraNextSpan(sraRectangleIterator *i)
{
if(sraReverse(i))
return(i->sPtrs[i->ptrPos]->_prev);
else
return(i->sPtrs[i->ptrPos]->_next);
}
rfbBool sraRgnIteratorNext(sraRectangleIterator* i,sraRect* r)
{
/* is the subspan finished? */
while(sraNextSpan(i) == i->sPtrs[i->ptrPos+1]) {
i->ptrPos -= 2;
if(i->ptrPos < 0) /* the end */
return(0);
}
i->sPtrs[i->ptrPos] = sraNextSpan(i);
/* is this a new subspan? */
while(i->sPtrs[i->ptrPos]->subspan) {
if(i->ptrPos+2 > i->ptrSize) { /* array is too small */
i->ptrSize += DEFSTEP;
i->sPtrs = (sraSpan**)realloc(i->sPtrs, sizeof(sraSpan*)*i->ptrSize);
}
i->ptrPos += 2;
if(sraReverse(i)) {
i->sPtrs[i->ptrPos] = i->sPtrs[i->ptrPos-2]->subspan->back._prev;
i->sPtrs[i->ptrPos+1] = &(i->sPtrs[i->ptrPos-2]->subspan->front);
} else {
i->sPtrs[i->ptrPos] = i->sPtrs[i->ptrPos-2]->subspan->front._next;
i->sPtrs[i->ptrPos+1] = &(i->sPtrs[i->ptrPos-2]->subspan->back);
}
}
if((i->ptrPos%4)!=2) {
rfbErr("sraRgnIteratorNext: offset is wrong (%d%%4!=2)\n",i->ptrPos);
return FALSE;
}
r->y1 = i->sPtrs[i->ptrPos-2]->start;
r->y2 = i->sPtrs[i->ptrPos-2]->end;
r->x1 = i->sPtrs[i->ptrPos]->start;
r->x2 = i->sPtrs[i->ptrPos]->end;
return(-1);
}
void sraRgnReleaseIterator(sraRectangleIterator* i)
{
free(i->sPtrs);
free(i);
}
void
sraRgnPrint(const sraRegion *rgn) {
sraSpanListPrint((sraSpanList*)rgn);
}
rfbBool
sraClipRect(int *x, int *y, int *w, int *h,
int cx, int cy, int cw, int ch) {
if (*x < cx) {
*w -= (cx-*x);
*x = cx;
}
if (*y < cy) {
*h -= (cy-*y);
*y = cy;
}
if (*x+*w > cx+cw) {
*w = (cx+cw)-*x;
}
if (*y+*h > cy+ch) {
*h = (cy+ch)-*y;
}
return (*w>0) && (*h>0);
}
rfbBool
sraClipRect2(int *x, int *y, int *x2, int *y2,
int cx, int cy, int cx2, int cy2) {
if (*x < cx)
*x = cx;
if (*y < cy)
*y = cy;
if (*x >= cx2)
*x = cx2-1;
if (*y >= cy2)
*y = cy2-1;
if (*x2 <= cx)
*x2 = cx+1;
if (*y2 <= cy)
*y2 = cy+1;
if (*x2 > cx2)
*x2 = cx2;
if (*y2 > cy2)
*y2 = cy2;
return (*x2>*x) && (*y2>*y);
}
/* test */
#ifdef SRA_TEST
/* pipe the output to sort|uniq -u and you'll get the errors. */
int main(int argc, char** argv)
{
sraRegionPtr region, region1, region2;
sraRectangleIterator* i;
sraRect rect;
rfbBool b;
region = sraRgnCreateRect(10, 10, 600, 300);
region1 = sraRgnCreateRect(40, 50, 350, 200);
region2 = sraRgnCreateRect(0, 0, 20, 40);
sraRgnPrint(region);
printf("\n[(10-300)[(10-600)]]\n\n");
b = sraRgnSubtract(region, region1);
printf("%s ",b?"true":"false");
sraRgnPrint(region);
printf("\ntrue [(10-50)[(10-600)](50-200)[(10-40)(350-600)](200-300)[(10-600)]]\n\n");
sraRgnOr(region, region2);
printf("%ld\n6\n\n", sraRgnCountRects(region));
i = sraRgnGetIterator(region);
while(sraRgnIteratorNext(i, &rect))
printf("%dx%d+%d+%d ",
rect.x2-rect.x1,rect.y2-rect.y1,
rect.x1,rect.y1);
sraRgnReleaseIterator(i);
printf("\n20x10+0+0 600x30+0+10 590x10+10+40 30x150+10+50 250x150+350+50 590x100+10+200 \n\n");
i = sraRgnGetReverseIterator(region,1,0);
while(sraRgnIteratorNext(i, &rect))
printf("%dx%d+%d+%d ",
rect.x2-rect.x1,rect.y2-rect.y1,
rect.x1,rect.y1);
sraRgnReleaseIterator(i);
printf("\n20x10+0+0 600x30+0+10 590x10+10+40 250x150+350+50 30x150+10+50 590x100+10+200 \n\n");
i = sraRgnGetReverseIterator(region,1,1);
while(sraRgnIteratorNext(i, &rect))
printf("%dx%d+%d+%d ",
rect.x2-rect.x1,rect.y2-rect.y1,
rect.x1,rect.y1);
sraRgnReleaseIterator(i);
printf("\n590x100+10+200 250x150+350+50 30x150+10+50 590x10+10+40 600x30+0+10 20x10+0+0 \n\n");
sraRgnDestroy(region);
sraRgnDestroy(region1);
sraRgnDestroy(region2);
return(0);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_4058_0 |
crossvul-cpp_data_good_3060_9 | /* RxRPC key management
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* RxRPC keys should have a description of describing their purpose:
* "afs@CAMBRIDGE.REDHAT.COM>
*/
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/key-type.h>
#include <linux/crypto.h>
#include <linux/ctype.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include <keys/rxrpc-type.h>
#include <keys/user-type.h>
#include "ar-internal.h"
static int rxrpc_vet_description_s(const char *);
static int rxrpc_preparse(struct key_preparsed_payload *);
static int rxrpc_preparse_s(struct key_preparsed_payload *);
static void rxrpc_free_preparse(struct key_preparsed_payload *);
static void rxrpc_free_preparse_s(struct key_preparsed_payload *);
static void rxrpc_destroy(struct key *);
static void rxrpc_destroy_s(struct key *);
static void rxrpc_describe(const struct key *, struct seq_file *);
static long rxrpc_read(const struct key *, char __user *, size_t);
/*
* rxrpc defined keys take an arbitrary string as the description and an
* arbitrary blob of data as the payload
*/
struct key_type key_type_rxrpc = {
.name = "rxrpc",
.preparse = rxrpc_preparse,
.free_preparse = rxrpc_free_preparse,
.instantiate = generic_key_instantiate,
.destroy = rxrpc_destroy,
.describe = rxrpc_describe,
.read = rxrpc_read,
};
EXPORT_SYMBOL(key_type_rxrpc);
/*
* rxrpc server defined keys take "<serviceId>:<securityIndex>" as the
* description and an 8-byte decryption key as the payload
*/
struct key_type key_type_rxrpc_s = {
.name = "rxrpc_s",
.vet_description = rxrpc_vet_description_s,
.preparse = rxrpc_preparse_s,
.free_preparse = rxrpc_free_preparse_s,
.instantiate = generic_key_instantiate,
.destroy = rxrpc_destroy_s,
.describe = rxrpc_describe,
};
/*
* Vet the description for an RxRPC server key
*/
static int rxrpc_vet_description_s(const char *desc)
{
unsigned long num;
char *p;
num = simple_strtoul(desc, &p, 10);
if (*p != ':' || num > 65535)
return -EINVAL;
num = simple_strtoul(p + 1, &p, 10);
if (*p || num < 1 || num > 255)
return -EINVAL;
return 0;
}
/*
* parse an RxKAD type XDR format token
* - the caller guarantees we have at least 4 words
*/
static int rxrpc_preparse_xdr_rxkad(struct key_preparsed_payload *prep,
size_t datalen,
const __be32 *xdr, unsigned int toklen)
{
struct rxrpc_key_token *token, **pptoken;
size_t plen;
u32 tktlen;
_enter(",{%x,%x,%x,%x},%u",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), ntohl(xdr[3]),
toklen);
if (toklen <= 8 * 4)
return -EKEYREJECTED;
tktlen = ntohl(xdr[7]);
_debug("tktlen: %x", tktlen);
if (tktlen > AFSTOKEN_RK_TIX_MAX)
return -EKEYREJECTED;
if (toklen < 8 * 4 + tktlen)
return -EKEYREJECTED;
plen = sizeof(*token) + sizeof(*token->kad) + tktlen;
prep->quotalen = datalen + plen;
plen -= sizeof(*token);
token = kzalloc(sizeof(*token), GFP_KERNEL);
if (!token)
return -ENOMEM;
token->kad = kzalloc(plen, GFP_KERNEL);
if (!token->kad) {
kfree(token);
return -ENOMEM;
}
token->security_index = RXRPC_SECURITY_RXKAD;
token->kad->ticket_len = tktlen;
token->kad->vice_id = ntohl(xdr[0]);
token->kad->kvno = ntohl(xdr[1]);
token->kad->start = ntohl(xdr[4]);
token->kad->expiry = ntohl(xdr[5]);
token->kad->primary_flag = ntohl(xdr[6]);
memcpy(&token->kad->session_key, &xdr[2], 8);
memcpy(&token->kad->ticket, &xdr[8], tktlen);
_debug("SCIX: %u", token->security_index);
_debug("TLEN: %u", token->kad->ticket_len);
_debug("EXPY: %x", token->kad->expiry);
_debug("KVNO: %u", token->kad->kvno);
_debug("PRIM: %u", token->kad->primary_flag);
_debug("SKEY: %02x%02x%02x%02x%02x%02x%02x%02x",
token->kad->session_key[0], token->kad->session_key[1],
token->kad->session_key[2], token->kad->session_key[3],
token->kad->session_key[4], token->kad->session_key[5],
token->kad->session_key[6], token->kad->session_key[7]);
if (token->kad->ticket_len >= 8)
_debug("TCKT: %02x%02x%02x%02x%02x%02x%02x%02x",
token->kad->ticket[0], token->kad->ticket[1],
token->kad->ticket[2], token->kad->ticket[3],
token->kad->ticket[4], token->kad->ticket[5],
token->kad->ticket[6], token->kad->ticket[7]);
/* count the number of tokens attached */
prep->type_data[0] = (void *)((unsigned long)prep->type_data[0] + 1);
/* attach the data */
for (pptoken = (struct rxrpc_key_token **)&prep->payload[0];
*pptoken;
pptoken = &(*pptoken)->next)
continue;
*pptoken = token;
if (token->kad->expiry < prep->expiry)
prep->expiry = token->kad->expiry;
_leave(" = 0");
return 0;
}
static void rxrpc_free_krb5_principal(struct krb5_principal *princ)
{
int loop;
if (princ->name_parts) {
for (loop = princ->n_name_parts - 1; loop >= 0; loop--)
kfree(princ->name_parts[loop]);
kfree(princ->name_parts);
}
kfree(princ->realm);
}
static void rxrpc_free_krb5_tagged(struct krb5_tagged_data *td)
{
kfree(td->data);
}
/*
* free up an RxK5 token
*/
static void rxrpc_rxk5_free(struct rxk5_key *rxk5)
{
int loop;
rxrpc_free_krb5_principal(&rxk5->client);
rxrpc_free_krb5_principal(&rxk5->server);
rxrpc_free_krb5_tagged(&rxk5->session);
if (rxk5->addresses) {
for (loop = rxk5->n_addresses - 1; loop >= 0; loop--)
rxrpc_free_krb5_tagged(&rxk5->addresses[loop]);
kfree(rxk5->addresses);
}
if (rxk5->authdata) {
for (loop = rxk5->n_authdata - 1; loop >= 0; loop--)
rxrpc_free_krb5_tagged(&rxk5->authdata[loop]);
kfree(rxk5->authdata);
}
kfree(rxk5->ticket);
kfree(rxk5->ticket2);
kfree(rxk5);
}
/*
* extract a krb5 principal
*/
static int rxrpc_krb5_decode_principal(struct krb5_principal *princ,
const __be32 **_xdr,
unsigned int *_toklen)
{
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, n_parts, loop, tmp;
/* there must be at least one name, and at least #names+1 length
* words */
if (toklen <= 12)
return -EINVAL;
_enter(",{%x,%x,%x},%u",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), toklen);
n_parts = ntohl(*xdr++);
toklen -= 4;
if (n_parts <= 0 || n_parts > AFSTOKEN_K5_COMPONENTS_MAX)
return -EINVAL;
princ->n_name_parts = n_parts;
if (toklen <= (n_parts + 1) * 4)
return -EINVAL;
princ->name_parts = kcalloc(n_parts, sizeof(char *), GFP_KERNEL);
if (!princ->name_parts)
return -ENOMEM;
for (loop = 0; loop < n_parts; loop++) {
if (toklen < 4)
return -EINVAL;
tmp = ntohl(*xdr++);
toklen -= 4;
if (tmp <= 0 || tmp > AFSTOKEN_STRING_MAX)
return -EINVAL;
if (tmp > toklen)
return -EINVAL;
princ->name_parts[loop] = kmalloc(tmp + 1, GFP_KERNEL);
if (!princ->name_parts[loop])
return -ENOMEM;
memcpy(princ->name_parts[loop], xdr, tmp);
princ->name_parts[loop][tmp] = 0;
tmp = (tmp + 3) & ~3;
toklen -= tmp;
xdr += tmp >> 2;
}
if (toklen < 4)
return -EINVAL;
tmp = ntohl(*xdr++);
toklen -= 4;
if (tmp <= 0 || tmp > AFSTOKEN_K5_REALM_MAX)
return -EINVAL;
if (tmp > toklen)
return -EINVAL;
princ->realm = kmalloc(tmp + 1, GFP_KERNEL);
if (!princ->realm)
return -ENOMEM;
memcpy(princ->realm, xdr, tmp);
princ->realm[tmp] = 0;
tmp = (tmp + 3) & ~3;
toklen -= tmp;
xdr += tmp >> 2;
_debug("%s/...@%s", princ->name_parts[0], princ->realm);
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* extract a piece of krb5 tagged data
*/
static int rxrpc_krb5_decode_tagged_data(struct krb5_tagged_data *td,
size_t max_data_size,
const __be32 **_xdr,
unsigned int *_toklen)
{
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, len;
/* there must be at least one tag and one length word */
if (toklen <= 8)
return -EINVAL;
_enter(",%zu,{%x,%x},%u",
max_data_size, ntohl(xdr[0]), ntohl(xdr[1]), toklen);
td->tag = ntohl(*xdr++);
len = ntohl(*xdr++);
toklen -= 8;
if (len > max_data_size)
return -EINVAL;
td->data_len = len;
if (len > 0) {
td->data = kmemdup(xdr, len, GFP_KERNEL);
if (!td->data)
return -ENOMEM;
len = (len + 3) & ~3;
toklen -= len;
xdr += len >> 2;
}
_debug("tag %x len %x", td->tag, td->data_len);
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* extract an array of tagged data
*/
static int rxrpc_krb5_decode_tagged_array(struct krb5_tagged_data **_td,
u8 *_n_elem,
u8 max_n_elem,
size_t max_elem_size,
const __be32 **_xdr,
unsigned int *_toklen)
{
struct krb5_tagged_data *td;
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, n_elem, loop;
int ret;
/* there must be at least one count */
if (toklen < 4)
return -EINVAL;
_enter(",,%u,%zu,{%x},%u",
max_n_elem, max_elem_size, ntohl(xdr[0]), toklen);
n_elem = ntohl(*xdr++);
toklen -= 4;
if (n_elem < 0 || n_elem > max_n_elem)
return -EINVAL;
*_n_elem = n_elem;
if (n_elem > 0) {
if (toklen <= (n_elem + 1) * 4)
return -EINVAL;
_debug("n_elem %d", n_elem);
td = kcalloc(n_elem, sizeof(struct krb5_tagged_data),
GFP_KERNEL);
if (!td)
return -ENOMEM;
*_td = td;
for (loop = 0; loop < n_elem; loop++) {
ret = rxrpc_krb5_decode_tagged_data(&td[loop],
max_elem_size,
&xdr, &toklen);
if (ret < 0)
return ret;
}
}
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* extract a krb5 ticket
*/
static int rxrpc_krb5_decode_ticket(u8 **_ticket, u16 *_tktlen,
const __be32 **_xdr, unsigned int *_toklen)
{
const __be32 *xdr = *_xdr;
unsigned int toklen = *_toklen, len;
/* there must be at least one length word */
if (toklen <= 4)
return -EINVAL;
_enter(",{%x},%u", ntohl(xdr[0]), toklen);
len = ntohl(*xdr++);
toklen -= 4;
if (len > AFSTOKEN_K5_TIX_MAX)
return -EINVAL;
*_tktlen = len;
_debug("ticket len %u", len);
if (len > 0) {
*_ticket = kmemdup(xdr, len, GFP_KERNEL);
if (!*_ticket)
return -ENOMEM;
len = (len + 3) & ~3;
toklen -= len;
xdr += len >> 2;
}
*_xdr = xdr;
*_toklen = toklen;
_leave(" = 0 [toklen=%u]", toklen);
return 0;
}
/*
* parse an RxK5 type XDR format token
* - the caller guarantees we have at least 4 words
*/
static int rxrpc_preparse_xdr_rxk5(struct key_preparsed_payload *prep,
size_t datalen,
const __be32 *xdr, unsigned int toklen)
{
struct rxrpc_key_token *token, **pptoken;
struct rxk5_key *rxk5;
const __be32 *end_xdr = xdr + (toklen >> 2);
int ret;
_enter(",{%x,%x,%x,%x},%u",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), ntohl(xdr[3]),
toklen);
/* reserve some payload space for this subkey - the length of the token
* is a reasonable approximation */
prep->quotalen = datalen + toklen;
token = kzalloc(sizeof(*token), GFP_KERNEL);
if (!token)
return -ENOMEM;
rxk5 = kzalloc(sizeof(*rxk5), GFP_KERNEL);
if (!rxk5) {
kfree(token);
return -ENOMEM;
}
token->security_index = RXRPC_SECURITY_RXK5;
token->k5 = rxk5;
/* extract the principals */
ret = rxrpc_krb5_decode_principal(&rxk5->client, &xdr, &toklen);
if (ret < 0)
goto error;
ret = rxrpc_krb5_decode_principal(&rxk5->server, &xdr, &toklen);
if (ret < 0)
goto error;
/* extract the session key and the encoding type (the tag field ->
* ENCTYPE_xxx) */
ret = rxrpc_krb5_decode_tagged_data(&rxk5->session, AFSTOKEN_DATA_MAX,
&xdr, &toklen);
if (ret < 0)
goto error;
if (toklen < 4 * 8 + 2 * 4)
goto inval;
rxk5->authtime = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->starttime = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->endtime = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->renew_till = be64_to_cpup((const __be64 *) xdr);
xdr += 2;
rxk5->is_skey = ntohl(*xdr++);
rxk5->flags = ntohl(*xdr++);
toklen -= 4 * 8 + 2 * 4;
_debug("times: a=%llx s=%llx e=%llx rt=%llx",
rxk5->authtime, rxk5->starttime, rxk5->endtime,
rxk5->renew_till);
_debug("is_skey=%x flags=%x", rxk5->is_skey, rxk5->flags);
/* extract the permitted client addresses */
ret = rxrpc_krb5_decode_tagged_array(&rxk5->addresses,
&rxk5->n_addresses,
AFSTOKEN_K5_ADDRESSES_MAX,
AFSTOKEN_DATA_MAX,
&xdr, &toklen);
if (ret < 0)
goto error;
ASSERTCMP((end_xdr - xdr) << 2, ==, toklen);
/* extract the tickets */
ret = rxrpc_krb5_decode_ticket(&rxk5->ticket, &rxk5->ticket_len,
&xdr, &toklen);
if (ret < 0)
goto error;
ret = rxrpc_krb5_decode_ticket(&rxk5->ticket2, &rxk5->ticket2_len,
&xdr, &toklen);
if (ret < 0)
goto error;
ASSERTCMP((end_xdr - xdr) << 2, ==, toklen);
/* extract the typed auth data */
ret = rxrpc_krb5_decode_tagged_array(&rxk5->authdata,
&rxk5->n_authdata,
AFSTOKEN_K5_AUTHDATA_MAX,
AFSTOKEN_BDATALN_MAX,
&xdr, &toklen);
if (ret < 0)
goto error;
ASSERTCMP((end_xdr - xdr) << 2, ==, toklen);
if (toklen != 0)
goto inval;
/* attach the payload */
for (pptoken = (struct rxrpc_key_token **)&prep->payload[0];
*pptoken;
pptoken = &(*pptoken)->next)
continue;
*pptoken = token;
if (token->kad->expiry < prep->expiry)
prep->expiry = token->kad->expiry;
_leave(" = 0");
return 0;
inval:
ret = -EINVAL;
error:
rxrpc_rxk5_free(rxk5);
kfree(token);
_leave(" = %d", ret);
return ret;
}
/*
* attempt to parse the data as the XDR format
* - the caller guarantees we have more than 7 words
*/
static int rxrpc_preparse_xdr(struct key_preparsed_payload *prep)
{
const __be32 *xdr = prep->data, *token;
const char *cp;
unsigned int len, tmp, loop, ntoken, toklen, sec_ix;
size_t datalen = prep->datalen;
int ret;
_enter(",{%x,%x,%x,%x},%zu",
ntohl(xdr[0]), ntohl(xdr[1]), ntohl(xdr[2]), ntohl(xdr[3]),
prep->datalen);
if (datalen > AFSTOKEN_LENGTH_MAX)
goto not_xdr;
/* XDR is an array of __be32's */
if (datalen & 3)
goto not_xdr;
/* the flags should be 0 (the setpag bit must be handled by
* userspace) */
if (ntohl(*xdr++) != 0)
goto not_xdr;
datalen -= 4;
/* check the cell name */
len = ntohl(*xdr++);
if (len < 1 || len > AFSTOKEN_CELL_MAX)
goto not_xdr;
datalen -= 4;
tmp = (len + 3) & ~3;
if (tmp > datalen)
goto not_xdr;
cp = (const char *) xdr;
for (loop = 0; loop < len; loop++)
if (!isprint(cp[loop]))
goto not_xdr;
if (len < tmp)
for (; loop < tmp; loop++)
if (cp[loop])
goto not_xdr;
_debug("cellname: [%u/%u] '%*.*s'",
len, tmp, len, len, (const char *) xdr);
datalen -= tmp;
xdr += tmp >> 2;
/* get the token count */
if (datalen < 12)
goto not_xdr;
ntoken = ntohl(*xdr++);
datalen -= 4;
_debug("ntoken: %x", ntoken);
if (ntoken < 1 || ntoken > AFSTOKEN_MAX)
goto not_xdr;
/* check each token wrapper */
token = xdr;
loop = ntoken;
do {
if (datalen < 8)
goto not_xdr;
toklen = ntohl(*xdr++);
sec_ix = ntohl(*xdr);
datalen -= 4;
_debug("token: [%x/%zx] %x", toklen, datalen, sec_ix);
if (toklen < 20 || toklen > datalen)
goto not_xdr;
datalen -= (toklen + 3) & ~3;
xdr += (toklen + 3) >> 2;
} while (--loop > 0);
_debug("remainder: %zu", datalen);
if (datalen != 0)
goto not_xdr;
/* okay: we're going to assume it's valid XDR format
* - we ignore the cellname, relying on the key to be correctly named
*/
do {
xdr = token;
toklen = ntohl(*xdr++);
token = xdr + ((toklen + 3) >> 2);
sec_ix = ntohl(*xdr++);
toklen -= 4;
_debug("TOKEN type=%u [%p-%p]", sec_ix, xdr, token);
switch (sec_ix) {
case RXRPC_SECURITY_RXKAD:
ret = rxrpc_preparse_xdr_rxkad(prep, datalen, xdr, toklen);
if (ret != 0)
goto error;
break;
case RXRPC_SECURITY_RXK5:
ret = rxrpc_preparse_xdr_rxk5(prep, datalen, xdr, toklen);
if (ret != 0)
goto error;
break;
default:
ret = -EPROTONOSUPPORT;
goto error;
}
} while (--ntoken > 0);
_leave(" = 0");
return 0;
not_xdr:
_leave(" = -EPROTO");
return -EPROTO;
error:
_leave(" = %d", ret);
return ret;
}
/*
* Preparse an rxrpc defined key.
*
* Data should be of the form:
* OFFSET LEN CONTENT
* 0 4 key interface version number
* 4 2 security index (type)
* 6 2 ticket length
* 8 4 key expiry time (time_t)
* 12 4 kvno
* 16 8 session key
* 24 [len] ticket
*
* if no data is provided, then a no-security key is made
*/
static int rxrpc_preparse(struct key_preparsed_payload *prep)
{
const struct rxrpc_key_data_v1 *v1;
struct rxrpc_key_token *token, **pp;
size_t plen;
u32 kver;
int ret;
_enter("%zu", prep->datalen);
/* handle a no-security key */
if (!prep->data && prep->datalen == 0)
return 0;
/* determine if the XDR payload format is being used */
if (prep->datalen > 7 * 4) {
ret = rxrpc_preparse_xdr(prep);
if (ret != -EPROTO)
return ret;
}
/* get the key interface version number */
ret = -EINVAL;
if (prep->datalen <= 4 || !prep->data)
goto error;
memcpy(&kver, prep->data, sizeof(kver));
prep->data += sizeof(kver);
prep->datalen -= sizeof(kver);
_debug("KEY I/F VERSION: %u", kver);
ret = -EKEYREJECTED;
if (kver != 1)
goto error;
/* deal with a version 1 key */
ret = -EINVAL;
if (prep->datalen < sizeof(*v1))
goto error;
v1 = prep->data;
if (prep->datalen != sizeof(*v1) + v1->ticket_length)
goto error;
_debug("SCIX: %u", v1->security_index);
_debug("TLEN: %u", v1->ticket_length);
_debug("EXPY: %x", v1->expiry);
_debug("KVNO: %u", v1->kvno);
_debug("SKEY: %02x%02x%02x%02x%02x%02x%02x%02x",
v1->session_key[0], v1->session_key[1],
v1->session_key[2], v1->session_key[3],
v1->session_key[4], v1->session_key[5],
v1->session_key[6], v1->session_key[7]);
if (v1->ticket_length >= 8)
_debug("TCKT: %02x%02x%02x%02x%02x%02x%02x%02x",
v1->ticket[0], v1->ticket[1],
v1->ticket[2], v1->ticket[3],
v1->ticket[4], v1->ticket[5],
v1->ticket[6], v1->ticket[7]);
ret = -EPROTONOSUPPORT;
if (v1->security_index != RXRPC_SECURITY_RXKAD)
goto error;
plen = sizeof(*token->kad) + v1->ticket_length;
prep->quotalen = plen + sizeof(*token);
ret = -ENOMEM;
token = kzalloc(sizeof(*token), GFP_KERNEL);
if (!token)
goto error;
token->kad = kzalloc(plen, GFP_KERNEL);
if (!token->kad)
goto error_free;
token->security_index = RXRPC_SECURITY_RXKAD;
token->kad->ticket_len = v1->ticket_length;
token->kad->expiry = v1->expiry;
token->kad->kvno = v1->kvno;
memcpy(&token->kad->session_key, &v1->session_key, 8);
memcpy(&token->kad->ticket, v1->ticket, v1->ticket_length);
/* count the number of tokens attached */
prep->type_data[0] = (void *)((unsigned long)prep->type_data[0] + 1);
/* attach the data */
pp = (struct rxrpc_key_token **)&prep->payload[0];
while (*pp)
pp = &(*pp)->next;
*pp = token;
if (token->kad->expiry < prep->expiry)
prep->expiry = token->kad->expiry;
token = NULL;
ret = 0;
error_free:
kfree(token);
error:
return ret;
}
/*
* Free token list.
*/
static void rxrpc_free_token_list(struct rxrpc_key_token *token)
{
struct rxrpc_key_token *next;
for (; token; token = next) {
next = token->next;
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
kfree(token->kad);
break;
case RXRPC_SECURITY_RXK5:
if (token->k5)
rxrpc_rxk5_free(token->k5);
break;
default:
printk(KERN_ERR "Unknown token type %x on rxrpc key\n",
token->security_index);
BUG();
}
kfree(token);
}
}
/*
* Clean up preparse data.
*/
static void rxrpc_free_preparse(struct key_preparsed_payload *prep)
{
rxrpc_free_token_list(prep->payload[0]);
}
/*
* Preparse a server secret key.
*
* The data should be the 8-byte secret key.
*/
static int rxrpc_preparse_s(struct key_preparsed_payload *prep)
{
struct crypto_blkcipher *ci;
_enter("%zu", prep->datalen);
if (prep->datalen != 8)
return -EINVAL;
memcpy(&prep->type_data, prep->data, 8);
ci = crypto_alloc_blkcipher("pcbc(des)", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(ci)) {
_leave(" = %ld", PTR_ERR(ci));
return PTR_ERR(ci);
}
if (crypto_blkcipher_setkey(ci, prep->data, 8) < 0)
BUG();
prep->payload[0] = ci;
_leave(" = 0");
return 0;
}
/*
* Clean up preparse data.
*/
static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)
{
if (prep->payload[0])
crypto_free_blkcipher(prep->payload[0]);
}
/*
* dispose of the data dangling from the corpse of a rxrpc key
*/
static void rxrpc_destroy(struct key *key)
{
rxrpc_free_token_list(key->payload.data);
}
/*
* dispose of the data dangling from the corpse of a rxrpc key
*/
static void rxrpc_destroy_s(struct key *key)
{
if (key->payload.data) {
crypto_free_blkcipher(key->payload.data);
key->payload.data = NULL;
}
}
/*
* describe the rxrpc key
*/
static void rxrpc_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
}
/*
* grab the security key for a socket
*/
int rxrpc_request_key(struct rxrpc_sock *rx, char __user *optval, int optlen)
{
struct key *key;
char *description;
_enter("");
if (optlen <= 0 || optlen > PAGE_SIZE - 1)
return -EINVAL;
description = kmalloc(optlen + 1, GFP_KERNEL);
if (!description)
return -ENOMEM;
if (copy_from_user(description, optval, optlen)) {
kfree(description);
return -EFAULT;
}
description[optlen] = 0;
key = request_key(&key_type_rxrpc, description, NULL);
if (IS_ERR(key)) {
kfree(description);
_leave(" = %ld", PTR_ERR(key));
return PTR_ERR(key);
}
rx->key = key;
kfree(description);
_leave(" = 0 [key %x]", key->serial);
return 0;
}
/*
* grab the security keyring for a server socket
*/
int rxrpc_server_keyring(struct rxrpc_sock *rx, char __user *optval,
int optlen)
{
struct key *key;
char *description;
_enter("");
if (optlen <= 0 || optlen > PAGE_SIZE - 1)
return -EINVAL;
description = kmalloc(optlen + 1, GFP_KERNEL);
if (!description)
return -ENOMEM;
if (copy_from_user(description, optval, optlen)) {
kfree(description);
return -EFAULT;
}
description[optlen] = 0;
key = request_key(&key_type_keyring, description, NULL);
if (IS_ERR(key)) {
kfree(description);
_leave(" = %ld", PTR_ERR(key));
return PTR_ERR(key);
}
rx->securities = key;
kfree(description);
_leave(" = 0 [key %x]", key->serial);
return 0;
}
/*
* generate a server data key
*/
int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
const void *session_key,
time_t expiry,
u32 kvno)
{
const struct cred *cred = current_cred();
struct key *key;
int ret;
struct {
u32 kver;
struct rxrpc_key_data_v1 v1;
} data;
_enter("");
key = key_alloc(&key_type_rxrpc, "x",
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,
KEY_ALLOC_NOT_IN_QUOTA);
if (IS_ERR(key)) {
_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
return -ENOMEM;
}
_debug("key %d", key_serial(key));
data.kver = 1;
data.v1.security_index = RXRPC_SECURITY_RXKAD;
data.v1.ticket_length = 0;
data.v1.expiry = expiry;
data.v1.kvno = 0;
memcpy(&data.v1.session_key, session_key, sizeof(data.v1.session_key));
ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
if (ret < 0)
goto error;
conn->key = key;
_leave(" = 0 [%d]", key_serial(key));
return 0;
error:
key_revoke(key);
key_put(key);
_leave(" = -ENOMEM [ins %d]", ret);
return -ENOMEM;
}
EXPORT_SYMBOL(rxrpc_get_server_data_key);
/**
* rxrpc_get_null_key - Generate a null RxRPC key
* @keyname: The name to give the key.
*
* Generate a null RxRPC key that can be used to indicate anonymous security is
* required for a particular domain.
*/
struct key *rxrpc_get_null_key(const char *keyname)
{
const struct cred *cred = current_cred();
struct key *key;
int ret;
key = key_alloc(&key_type_rxrpc, keyname,
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
KEY_POS_SEARCH, KEY_ALLOC_NOT_IN_QUOTA);
if (IS_ERR(key))
return key;
ret = key_instantiate_and_link(key, NULL, 0, NULL, NULL);
if (ret < 0) {
key_revoke(key);
key_put(key);
return ERR_PTR(ret);
}
return key;
}
EXPORT_SYMBOL(rxrpc_get_null_key);
/*
* read the contents of an rxrpc key
* - this returns the result in XDR form
*/
static long rxrpc_read(const struct key *key,
char __user *buffer, size_t buflen)
{
const struct rxrpc_key_token *token;
const struct krb5_principal *princ;
size_t size;
__be32 __user *xdr, *oldxdr;
u32 cnlen, toksize, ntoks, tok, zero;
u16 toksizes[AFSTOKEN_MAX];
int loop;
_enter("");
/* we don't know what form we should return non-AFS keys in */
if (memcmp(key->description, "afs@", 4) != 0)
return -EOPNOTSUPP;
cnlen = strlen(key->description + 4);
#define RND(X) (((X) + 3) & ~3)
/* AFS keys we return in XDR form, so we need to work out the size of
* the XDR */
size = 2 * 4; /* flags, cellname len */
size += RND(cnlen); /* cellname */
size += 1 * 4; /* token count */
ntoks = 0;
for (token = key->payload.data; token; token = token->next) {
toksize = 4; /* sec index */
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
toksize += 8 * 4; /* viceid, kvno, key*2, begin,
* end, primary, tktlen */
toksize += RND(token->kad->ticket_len);
break;
case RXRPC_SECURITY_RXK5:
princ = &token->k5->client;
toksize += 4 + princ->n_name_parts * 4;
for (loop = 0; loop < princ->n_name_parts; loop++)
toksize += RND(strlen(princ->name_parts[loop]));
toksize += 4 + RND(strlen(princ->realm));
princ = &token->k5->server;
toksize += 4 + princ->n_name_parts * 4;
for (loop = 0; loop < princ->n_name_parts; loop++)
toksize += RND(strlen(princ->name_parts[loop]));
toksize += 4 + RND(strlen(princ->realm));
toksize += 8 + RND(token->k5->session.data_len);
toksize += 4 * 8 + 2 * 4;
toksize += 4 + token->k5->n_addresses * 8;
for (loop = 0; loop < token->k5->n_addresses; loop++)
toksize += RND(token->k5->addresses[loop].data_len);
toksize += 4 + RND(token->k5->ticket_len);
toksize += 4 + RND(token->k5->ticket2_len);
toksize += 4 + token->k5->n_authdata * 8;
for (loop = 0; loop < token->k5->n_authdata; loop++)
toksize += RND(token->k5->authdata[loop].data_len);
break;
default: /* we have a ticket we can't encode */
BUG();
continue;
}
_debug("token[%u]: toksize=%u", ntoks, toksize);
ASSERTCMP(toksize, <=, AFSTOKEN_LENGTH_MAX);
toksizes[ntoks++] = toksize;
size += toksize + 4; /* each token has a length word */
}
#undef RND
if (!buffer || buflen < size)
return size;
xdr = (__be32 __user *) buffer;
zero = 0;
#define ENCODE(x) \
do { \
__be32 y = htonl(x); \
if (put_user(y, xdr++) < 0) \
goto fault; \
} while(0)
#define ENCODE_DATA(l, s) \
do { \
u32 _l = (l); \
ENCODE(l); \
if (copy_to_user(xdr, (s), _l) != 0) \
goto fault; \
if (_l & 3 && \
copy_to_user((u8 *)xdr + _l, &zero, 4 - (_l & 3)) != 0) \
goto fault; \
xdr += (_l + 3) >> 2; \
} while(0)
#define ENCODE64(x) \
do { \
__be64 y = cpu_to_be64(x); \
if (copy_to_user(xdr, &y, 8) != 0) \
goto fault; \
xdr += 8 >> 2; \
} while(0)
#define ENCODE_STR(s) \
do { \
const char *_s = (s); \
ENCODE_DATA(strlen(_s), _s); \
} while(0)
ENCODE(0); /* flags */
ENCODE_DATA(cnlen, key->description + 4); /* cellname */
ENCODE(ntoks);
tok = 0;
for (token = key->payload.data; token; token = token->next) {
toksize = toksizes[tok++];
ENCODE(toksize);
oldxdr = xdr;
ENCODE(token->security_index);
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
ENCODE(token->kad->vice_id);
ENCODE(token->kad->kvno);
ENCODE_DATA(8, token->kad->session_key);
ENCODE(token->kad->start);
ENCODE(token->kad->expiry);
ENCODE(token->kad->primary_flag);
ENCODE_DATA(token->kad->ticket_len, token->kad->ticket);
break;
case RXRPC_SECURITY_RXK5:
princ = &token->k5->client;
ENCODE(princ->n_name_parts);
for (loop = 0; loop < princ->n_name_parts; loop++)
ENCODE_STR(princ->name_parts[loop]);
ENCODE_STR(princ->realm);
princ = &token->k5->server;
ENCODE(princ->n_name_parts);
for (loop = 0; loop < princ->n_name_parts; loop++)
ENCODE_STR(princ->name_parts[loop]);
ENCODE_STR(princ->realm);
ENCODE(token->k5->session.tag);
ENCODE_DATA(token->k5->session.data_len,
token->k5->session.data);
ENCODE64(token->k5->authtime);
ENCODE64(token->k5->starttime);
ENCODE64(token->k5->endtime);
ENCODE64(token->k5->renew_till);
ENCODE(token->k5->is_skey);
ENCODE(token->k5->flags);
ENCODE(token->k5->n_addresses);
for (loop = 0; loop < token->k5->n_addresses; loop++) {
ENCODE(token->k5->addresses[loop].tag);
ENCODE_DATA(token->k5->addresses[loop].data_len,
token->k5->addresses[loop].data);
}
ENCODE_DATA(token->k5->ticket_len, token->k5->ticket);
ENCODE_DATA(token->k5->ticket2_len, token->k5->ticket2);
ENCODE(token->k5->n_authdata);
for (loop = 0; loop < token->k5->n_authdata; loop++) {
ENCODE(token->k5->authdata[loop].tag);
ENCODE_DATA(token->k5->authdata[loop].data_len,
token->k5->authdata[loop].data);
}
break;
default:
BUG();
break;
}
ASSERTCMP((unsigned long)xdr - (unsigned long)oldxdr, ==,
toksize);
}
#undef ENCODE_STR
#undef ENCODE_DATA
#undef ENCODE64
#undef ENCODE
ASSERTCMP(tok, ==, ntoks);
ASSERTCMP((char __user *) xdr - buffer, ==, size);
_leave(" = %zu", size);
return size;
fault:
_leave(" = -EFAULT");
return -EFAULT;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3060_9 |
crossvul-cpp_data_good_5217_1 | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* Copyright 2016 Syneto S.R.L. All rights reserved.
*/
/*
* The flush SMB is sent to ensure all data and allocation information
* for the corresponding file has been written to stable storage. This
* is a synchronous request. The response should not be sent until the
* writes are complete.
*
* The SmbFlush request is described in CIFS/1.0 1996 Section 3.9.14.
*
* CIFS/1.0 June 13, 1996
* Heizer, et al
* draft-heizer-cifs-v1-spec-00.txt
*/
#include <smbsrv/smb_kproto.h>
#include <smbsrv/smb_fsops.h>
/*
* smb_com_flush
*
* Flush any cached data for a specified file, or for all files that
* this client has open, to stable storage. If the fid is valid (i.e.
* not 0xFFFF), we flush only that file. Otherwise we flush all files
* associated with this client.
*
* We need to protect the list because there's a good chance we'll
* block during the flush operation.
*/
smb_sdrc_t
smb_pre_flush(smb_request_t *sr)
{
int rc;
rc = smbsr_decode_vwv(sr, "w", &sr->smb_fid);
DTRACE_SMB_1(op__Flush__start, smb_request_t *, sr);
return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR);
}
void
smb_post_flush(smb_request_t *sr)
{
DTRACE_SMB_1(op__Flush__done, smb_request_t *, sr);
}
smb_sdrc_t
smb_com_flush(smb_request_t *sr)
{
smb_ofile_t *file;
smb_llist_t *flist;
int rc;
if (smb_flush_required == 0) {
rc = smbsr_encode_empty_result(sr);
return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR);
}
if (sr->smb_fid != 0xffff) {
smbsr_lookup_file(sr);
if (sr->fid_ofile == NULL) {
smbsr_error(sr, NT_STATUS_INVALID_HANDLE,
ERRDOS, ERRbadfid);
return (SDRC_ERROR);
}
smb_ofile_flush(sr, sr->fid_ofile);
} else {
flist = &sr->tid_tree->t_ofile_list;
smb_llist_enter(flist, RW_READER);
file = smb_llist_head(flist);
while (file) {
mutex_enter(&file->f_mutex);
smb_ofile_flush(sr, file);
mutex_exit(&file->f_mutex);
file = smb_llist_next(flist, file);
}
smb_llist_exit(flist);
}
rc = smbsr_encode_empty_result(sr);
return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5217_1 |
crossvul-cpp_data_bad_4032_0 | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jcontext.h"
#include "js-parser-internal.h"
#include "js-scanner-internal.h"
#include "lit-char-helpers.h"
#if ENABLED (JERRY_PARSER)
/** \addtogroup parser Parser
* @{
*
* \addtogroup jsparser JavaScript
* @{
*
* \addtogroup jsparser_scanner Scanner
* @{
*/
/**
* Scan return types.
*/
typedef enum
{
SCAN_NEXT_TOKEN, /**< get next token after return */
SCAN_KEEP_TOKEN, /**< keep the current token after return */
} scan_return_types_t;
/**
* Checks whether token type is "of".
*/
#if ENABLED (JERRY_ES2015)
#define SCANNER_IDENTIFIER_IS_OF() (lexer_token_is_identifier (context_p, "of", 2))
#else
#define SCANNER_IDENTIFIER_IS_OF() (false)
#endif /* ENABLED (JERRY_ES2015) */
#if ENABLED (JERRY_ES2015)
JERRY_STATIC_ASSERT (SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (SCANNER_LITERAL_POOL_GENERATOR)
== SCAN_STACK_COMPUTED_GENERATOR,
scanner_invalid_conversion_from_literal_pool_generator_to_computed_generator);
JERRY_STATIC_ASSERT (SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (SCANNER_LITERAL_POOL_ASYNC)
== SCAN_STACK_COMPUTED_ASYNC,
scanner_invalid_conversion_from_literal_pool_async_to_computed_async);
JERRY_STATIC_ASSERT (SCANNER_FROM_COMPUTED_TO_LITERAL_POOL (SCAN_STACK_COMPUTED_GENERATOR)
== SCANNER_LITERAL_POOL_GENERATOR,
scanner_invalid_conversion_from_computed_generator_to_literal_pool_generator);
JERRY_STATIC_ASSERT (SCANNER_FROM_COMPUTED_TO_LITERAL_POOL (SCAN_STACK_COMPUTED_ASYNC)
== SCANNER_LITERAL_POOL_ASYNC,
scanner_invalid_conversion_from_computed_async_to_literal_pool_async);
#endif /* ENABLED (JERRY_ES2015) */
/**
* Scan primary expression.
*
* @return SCAN_NEXT_TOKEN to read the next token, or SCAN_KEEP_TOKEN to do nothing
*/
static scan_return_types_t
scanner_scan_primary_expression (parser_context_t *context_p, /**< context */
scanner_context_t *scanner_context_p, /* scanner context */
lexer_token_type_t type, /**< current token type */
scan_stack_modes_t stack_top) /**< current stack top */
{
switch (type)
{
case LEXER_KEYW_NEW:
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW;
#if ENABLED (JERRY_ES2015)
if (scanner_try_scan_new_target (context_p))
{
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
}
#endif /* ENABLED (JERRY_ES2015) */
break;
}
case LEXER_DIVIDE:
case LEXER_ASSIGN_DIVIDE:
{
lexer_construct_regexp_object (context_p, true);
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
break;
}
case LEXER_KEYW_FUNCTION:
{
uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;
#if ENABLED (JERRY_ES2015)
if (scanner_context_p->async_source_p != NULL)
{
status_flags |= SCANNER_LITERAL_POOL_ASYNC;
}
if (lexer_consume_generator (context_p))
{
status_flags |= SCANNER_LITERAL_POOL_GENERATOR;
}
#endif /* ENABLED (JERRY_ES2015) */
scanner_push_literal_pool (context_p, scanner_context_p, status_flags);
lexer_next_token (context_p);
if (context_p->token.type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
lexer_next_token (context_p);
}
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_EXPRESSION);
scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
return SCAN_KEEP_TOKEN;
}
case LEXER_LEFT_PAREN:
{
scanner_scan_bracket (context_p, scanner_context_p);
return SCAN_KEEP_TOKEN;
}
case LEXER_LEFT_SQUARE:
{
#if ENABLED (JERRY_ES2015)
scanner_push_destructuring_pattern (context_p, scanner_context_p, SCANNER_BINDING_NONE, false);
#endif /* ENABLED (JERRY_ES2015) */
parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
case LEXER_LEFT_BRACE:
{
#if ENABLED (JERRY_ES2015)
scanner_push_destructuring_pattern (context_p, scanner_context_p, SCANNER_BINDING_NONE, false);
#endif /* ENABLED (JERRY_ES2015) */
parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);
scanner_context_p->mode = SCAN_MODE_PROPERTY_NAME;
return SCAN_KEEP_TOKEN;
}
#if ENABLED (JERRY_ES2015)
case LEXER_TEMPLATE_LITERAL:
{
if (context_p->source_p[-1] != LIT_CHAR_GRAVE_ACCENT)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_TEMPLATE_STRING);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
/* The string is a normal string literal. */
/* FALLTHRU */
}
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_LITERAL:
{
#if ENABLED (JERRY_ES2015)
const uint8_t *source_p = context_p->source_p;
if (context_p->token.lit_location.type == LEXER_IDENT_LITERAL
&& lexer_check_arrow (context_p))
{
scanner_scan_simple_arrow (context_p, scanner_context_p, source_p);
return SCAN_KEEP_TOKEN;
}
else if (JERRY_UNLIKELY (lexer_token_is_async (context_p)))
{
scanner_context_p->async_source_p = source_p;
scanner_check_async_function (context_p, scanner_context_p);
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
scanner_add_reference (context_p, scanner_context_p);
}
/* FALLTHRU */
}
case LEXER_KEYW_THIS:
case LEXER_KEYW_SUPER:
case LEXER_LIT_TRUE:
case LEXER_LIT_FALSE:
case LEXER_LIT_NULL:
{
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
break;
}
#if ENABLED (JERRY_ES2015)
case LEXER_KEYW_CLASS:
{
scanner_push_class_declaration (context_p, scanner_context_p, SCAN_STACK_CLASS_EXPRESSION);
if (context_p->token.type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
return SCAN_KEEP_TOKEN;
}
break;
}
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_RIGHT_SQUARE:
{
if (stack_top != SCAN_STACK_ARRAY_LITERAL)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
return SCAN_KEEP_TOKEN;
}
#if ENABLED (JERRY_ES2015)
case LEXER_THREE_DOTS:
{
/* Elision or spread arguments */
if (stack_top != SCAN_STACK_PAREN_EXPRESSION && stack_top != SCAN_STACK_ARRAY_LITERAL)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_COMMA:
{
if (stack_top != SCAN_STACK_ARRAY_LITERAL)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
#if ENABLED (JERRY_ES2015)
if (scanner_context_p->binding_type != SCANNER_BINDING_NONE)
{
scanner_context_p->mode = SCAN_MODE_BINDING;
}
#endif /* ENABLED (JERRY_ES2015) */
break;
}
#if ENABLED (JERRY_ES2015)
case LEXER_KEYW_YIELD:
{
lexer_next_token (context_p);
if (lexer_check_yield_no_arg (context_p))
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
}
if (context_p->token.type == LEXER_MULTIPLY)
{
return SCAN_NEXT_TOKEN;
}
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_RIGHT_PAREN:
{
if (stack_top == SCAN_STACK_PAREN_EXPRESSION)
{
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
parser_stack_pop_uint8 (context_p);
break;
}
/* FALLTHRU */
}
default:
{
scanner_raise_error (context_p);
}
}
return SCAN_NEXT_TOKEN;
} /* scanner_scan_primary_expression */
/**
* Scan the tokens after the primary expression.
*
* @return true for break, false for fall through
*/
static bool
scanner_scan_post_primary_expression (parser_context_t *context_p, /**< context */
scanner_context_t *scanner_context_p, /**< scanner context */
lexer_token_type_t type, /**< current token type */
scan_stack_modes_t stack_top) /**< current stack top */
{
switch (type)
{
case LEXER_DOT:
{
lexer_scan_identifier (context_p);
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
return true;
}
case LEXER_LEFT_PAREN:
{
parser_stack_push_uint8 (context_p, SCAN_STACK_PAREN_EXPRESSION);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return true;
}
#if ENABLED (JERRY_ES2015)
case LEXER_TEMPLATE_LITERAL:
{
if (JERRY_UNLIKELY (context_p->source_p[-1] != LIT_CHAR_GRAVE_ACCENT))
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
parser_stack_push_uint8 (context_p, SCAN_STACK_TAGGED_TEMPLATE_LITERAL);
}
return true;
}
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_LEFT_SQUARE:
{
parser_stack_push_uint8 (context_p, SCAN_STACK_PROPERTY_ACCESSOR);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return true;
}
case LEXER_INCREASE:
case LEXER_DECREASE:
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
if (context_p->token.flags & LEXER_WAS_NEWLINE)
{
return false;
}
lexer_next_token (context_p);
type = (lexer_token_type_t) context_p->token.type;
if (type != LEXER_QUESTION_MARK)
{
break;
}
/* FALLTHRU */
}
case LEXER_QUESTION_MARK:
{
parser_stack_push_uint8 (context_p, SCAN_STACK_COLON_EXPRESSION);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return true;
}
default:
{
break;
}
}
if (LEXER_IS_BINARY_OP_TOKEN (type)
&& (type != LEXER_KEYW_IN || !SCANNER_IS_FOR_START (stack_top)))
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return true;
}
return false;
} /* scanner_scan_post_primary_expression */
/**
* Scan the tokens after the primary expression.
*
* @return SCAN_NEXT_TOKEN to read the next token, or SCAN_KEEP_TOKEN to do nothing
*/
static scan_return_types_t
scanner_scan_primary_expression_end (parser_context_t *context_p, /**< context */
scanner_context_t *scanner_context_p, /**< scanner context */
lexer_token_type_t type, /**< current token type */
scan_stack_modes_t stack_top) /**< current stack top */
{
if (type == LEXER_COMMA)
{
switch (stack_top)
{
case SCAN_STACK_VAR:
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_LET:
case SCAN_STACK_CONST:
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_STACK_FOR_VAR_START:
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_FOR_LET_START:
case SCAN_STACK_FOR_CONST_START:
#endif /* ENABLED (JERRY_ES2015) */
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_COLON_EXPRESSION:
{
scanner_raise_error (context_p);
break;
}
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_BINDING_INIT:
case SCAN_STACK_BINDING_LIST_INIT:
{
break;
}
case SCAN_STACK_ARROW_ARGUMENTS:
{
lexer_next_token (context_p);
scanner_check_arrow_arg (context_p, scanner_context_p);
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_ARROW_EXPRESSION:
{
break;
}
case SCAN_STACK_FUNCTION_PARAMETERS:
{
scanner_context_p->mode = SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS;
parser_stack_pop_uint8 (context_p);
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_ARRAY_LITERAL:
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
if (scanner_context_p->binding_type != SCANNER_BINDING_NONE)
{
scanner_context_p->mode = SCAN_MODE_BINDING;
}
return SCAN_NEXT_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_STACK_OBJECT_LITERAL:
{
scanner_context_p->mode = SCAN_MODE_PROPERTY_NAME;
return SCAN_KEEP_TOKEN;
}
default:
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
}
}
switch (stack_top)
{
case SCAN_STACK_WITH_EXPRESSION:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
parser_stack_pop_uint8 (context_p);
uint16_t status_flags = scanner_context_p->active_literal_pool_p->status_flags;
parser_stack_push_uint8 (context_p, (status_flags & SCANNER_LITERAL_POOL_IN_WITH) ? 1 : 0);
parser_stack_push_uint8 (context_p, SCAN_STACK_WITH_STATEMENT);
status_flags |= SCANNER_LITERAL_POOL_IN_WITH;
scanner_context_p->active_literal_pool_p->status_flags = status_flags;
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_DO_EXPRESSION:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_WHILE_EXPRESSION:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
scanner_source_start_t source_start;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));
scanner_location_info_t *location_info_p;
location_info_p = (scanner_location_info_t *) scanner_insert_info (context_p,
source_start.source_p,
sizeof (scanner_location_info_t));
location_info_p->info.type = SCANNER_TYPE_WHILE;
scanner_get_location (&location_info_p->location, context_p);
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_PAREN_EXPRESSION:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
parser_stack_pop_uint8 (context_p);
#if ENABLED (JERRY_ES2015)
if (context_p->stack_top_uint8 == SCAN_STACK_USE_ASYNC)
{
scanner_add_async_literal (context_p, scanner_context_p);
}
#endif /* ENABLED (JERRY_ES2015) */
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_STATEMENT_WITH_EXPR:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
parser_stack_pop_uint8 (context_p);
#if ENABLED (JERRY_ES2015)
if (context_p->stack_top_uint8 == SCAN_STACK_IF_STATEMENT)
{
scanner_check_function_after_if (context_p, scanner_context_p);
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_NEXT_TOKEN;
}
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_BINDING_LIST_INIT:
{
parser_stack_pop_uint8 (context_p);
JERRY_ASSERT (context_p->stack_top_uint8 == SCAN_STACK_ARRAY_LITERAL
|| context_p->stack_top_uint8 == SCAN_STACK_OBJECT_LITERAL
|| context_p->stack_top_uint8 == SCAN_STACK_LET
|| context_p->stack_top_uint8 == SCAN_STACK_CONST
|| context_p->stack_top_uint8 == SCAN_STACK_FOR_LET_START
|| context_p->stack_top_uint8 == SCAN_STACK_FOR_CONST_START
|| context_p->stack_top_uint8 == SCAN_STACK_FUNCTION_PARAMETERS
|| context_p->stack_top_uint8 == SCAN_STACK_ARROW_ARGUMENTS);
scanner_binding_item_t *item_p = scanner_context_p->active_binding_list_p->items_p;
while (item_p != NULL)
{
if (item_p->literal_p->type & SCANNER_LITERAL_IS_USED)
{
item_p->literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
}
item_p = item_p->next_p;
}
scanner_pop_binding_list (scanner_context_p);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_BINDING_INIT:
{
scanner_binding_literal_t binding_literal;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &binding_literal, sizeof (scanner_binding_literal_t));
JERRY_ASSERT (context_p->stack_top_uint8 == SCAN_STACK_ARRAY_LITERAL
|| context_p->stack_top_uint8 == SCAN_STACK_OBJECT_LITERAL
|| context_p->stack_top_uint8 == SCAN_STACK_LET
|| context_p->stack_top_uint8 == SCAN_STACK_CONST
|| context_p->stack_top_uint8 == SCAN_STACK_FOR_LET_START
|| context_p->stack_top_uint8 == SCAN_STACK_FOR_CONST_START
|| context_p->stack_top_uint8 == SCAN_STACK_FUNCTION_PARAMETERS
|| context_p->stack_top_uint8 == SCAN_STACK_ARROW_ARGUMENTS);
JERRY_ASSERT ((stack_top != SCAN_STACK_ARRAY_LITERAL && stack_top != SCAN_STACK_OBJECT_LITERAL)
|| SCANNER_NEEDS_BINDING_LIST (scanner_context_p->binding_type));
if (binding_literal.literal_p->type & SCANNER_LITERAL_IS_USED)
{
binding_literal.literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_STACK_VAR:
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_LET:
case SCAN_STACK_CONST:
#endif /* ENABLED (JERRY_ES2015) */
{
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
scanner_context_p->active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
parser_stack_pop_uint8 (context_p);
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_FOR_VAR_START:
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_FOR_LET_START:
case SCAN_STACK_FOR_CONST_START:
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_STACK_FOR_START:
{
if (type == LEXER_KEYW_IN || SCANNER_IDENTIFIER_IS_OF ())
{
scanner_for_statement_t for_statement;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &for_statement, sizeof (scanner_for_statement_t));
scanner_location_info_t *location_info;
location_info = (scanner_location_info_t *) scanner_insert_info (context_p,
for_statement.u.source_p,
sizeof (scanner_location_info_t));
#if ENABLED (JERRY_ES2015)
location_info->info.type = (type == LEXER_KEYW_IN) ? SCANNER_TYPE_FOR_IN : SCANNER_TYPE_FOR_OF;
if (stack_top == SCAN_STACK_FOR_LET_START || stack_top == SCAN_STACK_FOR_CONST_START)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_PRIVATE_BLOCK_EARLY);
}
#else /* !ENABLED (JERRY_ES2015) */
location_info->info.type = SCANNER_TYPE_FOR_IN;
#endif /* ENABLED (JERRY_ES2015) */
scanner_get_location (&location_info->location, context_p);
parser_stack_push_uint8 (context_p, SCAN_STACK_STATEMENT_WITH_EXPR);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
if (type != LEXER_SEMICOLON)
{
break;
}
scanner_for_statement_t for_statement;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, NULL, sizeof (scanner_for_statement_t));
#if ENABLED (JERRY_ES2015)
if (stack_top == SCAN_STACK_FOR_LET_START || stack_top == SCAN_STACK_FOR_CONST_START)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_PRIVATE_BLOCK);
}
#endif /* ENABLED (JERRY_ES2015) */
for_statement.u.source_p = context_p->source_p;
parser_stack_push (context_p, &for_statement, sizeof (scanner_for_statement_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_FOR_CONDITION);
lexer_next_token (context_p);
if (context_p->token.type != LEXER_SEMICOLON)
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_KEEP_TOKEN;
}
type = LEXER_SEMICOLON;
/* FALLTHRU */
}
case SCAN_STACK_FOR_CONDITION:
{
if (type != LEXER_SEMICOLON)
{
break;
}
scanner_for_statement_t for_statement;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &for_statement, sizeof (scanner_for_statement_t));
scanner_for_info_t *for_info_p;
for_info_p = (scanner_for_info_t *) scanner_insert_info (context_p,
for_statement.u.source_p,
sizeof (scanner_for_info_t));
for_info_p->info.type = SCANNER_TYPE_FOR;
scanner_get_location (&for_info_p->expression_location, context_p);
for_info_p->end_location.source_p = NULL;
for_statement.u.for_info_p = for_info_p;
parser_stack_push (context_p, &for_statement, sizeof (scanner_for_statement_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_FOR_EXPRESSION);
lexer_next_token (context_p);
if (context_p->token.type != LEXER_RIGHT_PAREN)
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_KEEP_TOKEN;
}
type = LEXER_RIGHT_PAREN;
/* FALLTHRU */
}
case SCAN_STACK_FOR_EXPRESSION:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
scanner_for_statement_t for_statement;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &for_statement, sizeof (scanner_for_statement_t));
scanner_get_location (&for_statement.u.for_info_p->end_location, context_p);
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_SWITCH_EXPRESSION:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_BRACE)
{
break;
}
#if ENABLED (JERRY_ES2015)
scanner_literal_pool_t *literal_pool_p;
literal_pool_p = scanner_push_literal_pool (context_p, scanner_context_p, SCANNER_LITERAL_POOL_BLOCK);
literal_pool_p->source_p = context_p->source_p - 1;
#endif /* ENABLED (JERRY_ES2015) */
parser_stack_pop_uint8 (context_p);
scanner_switch_statement_t switch_statement = scanner_context_p->active_switch_statement;
parser_stack_push (context_p, &switch_statement, sizeof (scanner_switch_statement_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_SWITCH_BLOCK);
scanner_switch_info_t *switch_info_p;
switch_info_p = (scanner_switch_info_t *) scanner_insert_info (context_p,
context_p->source_p,
sizeof (scanner_switch_info_t));
switch_info_p->info.type = SCANNER_TYPE_SWITCH;
switch_info_p->case_p = NULL;
scanner_context_p->active_switch_statement.last_case_p = &switch_info_p->case_p;
lexer_next_token (context_p);
if (context_p->token.type != LEXER_RIGHT_BRACE
&& context_p->token.type != LEXER_KEYW_CASE
&& context_p->token.type != LEXER_KEYW_DEFAULT)
{
break;
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_CASE_STATEMENT:
{
if (type != LEXER_COLON)
{
break;
}
scanner_source_start_t source_start;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));
scanner_location_info_t *location_info_p;
location_info_p = (scanner_location_info_t *) scanner_insert_info (context_p,
source_start.source_p,
sizeof (scanner_location_info_t));
location_info_p->info.type = SCANNER_TYPE_CASE;
scanner_get_location (&location_info_p->location, context_p);
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_COLON_EXPRESSION:
{
if (type != LEXER_COLON)
{
break;
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
parser_stack_pop_uint8 (context_p);
return SCAN_NEXT_TOKEN;
}
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_ARRAY_LITERAL:
case SCAN_STACK_OBJECT_LITERAL:
{
if (((stack_top == SCAN_STACK_ARRAY_LITERAL) && (type != LEXER_RIGHT_SQUARE))
|| ((stack_top == SCAN_STACK_OBJECT_LITERAL) && (type != LEXER_RIGHT_BRACE)))
{
break;
}
scanner_source_start_t source_start;
uint8_t binding_type = scanner_context_p->binding_type;
parser_stack_pop_uint8 (context_p);
scanner_context_p->binding_type = context_p->stack_top_uint8;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));
lexer_next_token (context_p);
if (binding_type == SCANNER_BINDING_CATCH && context_p->stack_top_uint8 == SCAN_STACK_CATCH_STATEMENT)
{
scanner_pop_binding_list (scanner_context_p);
if (context_p->token.type != LEXER_RIGHT_PAREN)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_BRACE)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
return SCAN_NEXT_TOKEN;
}
if (context_p->token.type != LEXER_ASSIGN)
{
if (SCANNER_NEEDS_BINDING_LIST (binding_type))
{
scanner_pop_binding_list (scanner_context_p);
}
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
return SCAN_KEEP_TOKEN;
}
scanner_location_info_t *location_info_p;
location_info_p = (scanner_location_info_t *) scanner_insert_info (context_p,
source_start.source_p,
sizeof (scanner_location_info_t));
location_info_p->info.type = SCANNER_TYPE_INITIALIZER;
scanner_get_location (&location_info_p->location, context_p);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
if (SCANNER_NEEDS_BINDING_LIST (binding_type))
{
scanner_binding_item_t *item_p = scanner_context_p->active_binding_list_p->items_p;
while (item_p != NULL)
{
item_p->literal_p->type &= (uint8_t) ~SCANNER_LITERAL_IS_USED;
item_p = item_p->next_p;
}
parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_LIST_INIT);
}
return SCAN_NEXT_TOKEN;
}
#else /* !ENABLED (JERRY_ES2015) */
case SCAN_STACK_ARRAY_LITERAL:
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_STACK_PROPERTY_ACCESSOR:
{
if (type != LEXER_RIGHT_SQUARE)
{
break;
}
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
parser_stack_pop_uint8 (context_p);
return SCAN_NEXT_TOKEN;
}
#if !ENABLED (JERRY_ES2015)
case SCAN_STACK_OBJECT_LITERAL:
{
if (type != LEXER_RIGHT_BRACE)
{
break;
}
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
parser_stack_pop_uint8 (context_p);
return SCAN_NEXT_TOKEN;
}
#endif /* !ENABLED (JERRY_ES2015) */
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_COMPUTED_PROPERTY:
{
if (type != LEXER_RIGHT_SQUARE)
{
break;
}
lexer_next_token (context_p);
parser_stack_pop_uint8 (context_p);
stack_top = (scan_stack_modes_t) context_p->stack_top_uint8;
if (stack_top == SCAN_STACK_FUNCTION_PROPERTY)
{
scanner_push_literal_pool (context_p, scanner_context_p, SCANNER_LITERAL_POOL_FUNCTION);
scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
return SCAN_KEEP_TOKEN;
}
JERRY_ASSERT (stack_top == SCAN_STACK_OBJECT_LITERAL);
if (context_p->token.type == LEXER_LEFT_PAREN)
{
scanner_push_literal_pool (context_p, scanner_context_p, SCANNER_LITERAL_POOL_FUNCTION);
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);
scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
return SCAN_KEEP_TOKEN;
}
if (context_p->token.type != LEXER_COLON)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
if (scanner_context_p->binding_type != SCANNER_BINDING_NONE)
{
scanner_context_p->mode = SCAN_MODE_BINDING;
}
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_COMPUTED_GENERATOR:
case SCAN_STACK_COMPUTED_ASYNC:
case SCAN_STACK_COMPUTED_ASYNC_GENERATOR:
{
if (type != LEXER_RIGHT_SQUARE)
{
break;
}
lexer_next_token (context_p);
parser_stack_pop_uint8 (context_p);
JERRY_ASSERT (context_p->stack_top_uint8 == SCAN_STACK_OBJECT_LITERAL
|| context_p->stack_top_uint8 == SCAN_STACK_FUNCTION_PROPERTY);
uint16_t status_flags = (uint16_t) (SCANNER_LITERAL_POOL_FUNCTION
| SCANNER_LITERAL_POOL_GENERATOR
| SCANNER_FROM_COMPUTED_TO_LITERAL_POOL (stack_top));
scanner_push_literal_pool (context_p, scanner_context_p, status_flags);
scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_TEMPLATE_STRING:
case SCAN_STACK_TAGGED_TEMPLATE_LITERAL:
{
if (type != LEXER_RIGHT_BRACE)
{
break;
}
context_p->source_p--;
context_p->column--;
lexer_parse_string (context_p, LEXER_STRING_NO_OPTS);
if (context_p->source_p[-1] != LIT_CHAR_GRAVE_ACCENT)
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
}
else
{
parser_stack_pop_uint8 (context_p);
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
}
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_ARROW_ARGUMENTS:
{
if (type != LEXER_RIGHT_PAREN)
{
break;
}
scanner_check_arrow (context_p, scanner_context_p);
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_ARROW_EXPRESSION:
{
scanner_pop_literal_pool (context_p, scanner_context_p);
parser_stack_pop_uint8 (context_p);
lexer_update_await_yield (context_p, context_p->status_flags);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_CLASS_EXTENDS:
{
if (type != LEXER_LEFT_BRACE)
{
break;
}
scanner_context_p->mode = SCAN_MODE_CLASS_METHOD;
parser_stack_pop_uint8 (context_p);
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_FUNCTION_PARAMETERS:
{
parser_stack_pop_uint8 (context_p);
if (type != LEXER_RIGHT_PAREN
&& (type != LEXER_EOS || context_p->stack_top_uint8 != SCAN_STACK_SCRIPT_FUNCTION))
{
break;
}
scanner_context_p->mode = SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS;
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
default:
{
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
return SCAN_KEEP_TOKEN;
}
}
scanner_raise_error (context_p);
return SCAN_NEXT_TOKEN;
} /* scanner_scan_primary_expression_end */
/**
* Scan statements.
*
* @return SCAN_NEXT_TOKEN to read the next token, or SCAN_KEEP_TOKEN to do nothing
*/
static scan_return_types_t
scanner_scan_statement (parser_context_t *context_p, /**< context */
scanner_context_t *scanner_context_p, /**< scanner context */
lexer_token_type_t type, /**< current token type */
scan_stack_modes_t stack_top) /**< current stack top */
{
switch (type)
{
case LEXER_SEMICOLON:
{
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
return SCAN_KEEP_TOKEN;
}
case LEXER_LEFT_BRACE:
{
#if ENABLED (JERRY_ES2015)
scanner_literal_pool_t *literal_pool_p;
literal_pool_p = scanner_push_literal_pool (context_p,
scanner_context_p,
SCANNER_LITERAL_POOL_BLOCK);
literal_pool_p->source_p = context_p->source_p;
#endif /* ENABLED (JERRY_ES2015) */
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
parser_stack_push_uint8 (context_p, SCAN_STACK_BLOCK_STATEMENT);
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_DO:
{
scanner_context_p->mode = SCAN_MODE_STATEMENT;
parser_stack_push_uint8 (context_p, SCAN_STACK_DO_STATEMENT);
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_TRY:
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_BRACE)
{
scanner_raise_error (context_p);
}
#if ENABLED (JERRY_ES2015)
scanner_literal_pool_t *literal_pool_p;
literal_pool_p = scanner_push_literal_pool (context_p,
scanner_context_p,
SCANNER_LITERAL_POOL_BLOCK);
literal_pool_p->source_p = context_p->source_p;
#endif /* ENABLED (JERRY_ES2015) */
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
parser_stack_push_uint8 (context_p, SCAN_STACK_TRY_STATEMENT);
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_DEBUGGER:
{
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_IF:
case LEXER_KEYW_WITH:
case LEXER_KEYW_SWITCH:
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_PAREN)
{
scanner_raise_error (context_p);
}
uint8_t mode = SCAN_STACK_STATEMENT_WITH_EXPR;
if (type == LEXER_KEYW_IF)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_IF_STATEMENT);
}
else if (type == LEXER_KEYW_WITH)
{
mode = SCAN_STACK_WITH_EXPRESSION;
}
else if (type == LEXER_KEYW_SWITCH)
{
mode = SCAN_STACK_SWITCH_EXPRESSION;
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
parser_stack_push_uint8 (context_p, mode);
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_WHILE:
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_PAREN)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
scanner_source_start_t source_start;
source_start.source_p = context_p->source_p;
parser_stack_push (context_p, &source_start, sizeof (scanner_source_start_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_WHILE_EXPRESSION);
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_FOR:
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_PAREN)
{
scanner_raise_error (context_p);
}
scanner_for_statement_t for_statement;
for_statement.u.source_p = context_p->source_p;
uint8_t stack_mode = SCAN_STACK_FOR_START;
scan_return_types_t return_type = SCAN_KEEP_TOKEN;
lexer_next_token (context_p);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
#if ENABLED (JERRY_ES2015)
const uint8_t *source_p = context_p->source_p;
#endif /* ENABLED (JERRY_ES2015) */
switch (context_p->token.type)
{
case LEXER_SEMICOLON:
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
break;
}
case LEXER_KEYW_VAR:
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
stack_mode = SCAN_STACK_FOR_VAR_START;
return_type = SCAN_NEXT_TOKEN;
break;
}
#if ENABLED (JERRY_ES2015)
case LEXER_LITERAL:
{
if (!lexer_token_is_let (context_p))
{
break;
}
parser_line_counter_t line = context_p->line;
parser_line_counter_t column = context_p->column;
if (lexer_check_arrow (context_p))
{
context_p->source_p = source_p;
context_p->line = line;
context_p->column = column;
context_p->token.flags &= (uint8_t) ~LEXER_NO_SKIP_SPACES;
break;
}
lexer_next_token (context_p);
type = (lexer_token_type_t) context_p->token.type;
if (type != LEXER_LEFT_SQUARE
&& type != LEXER_LEFT_BRACE
&& (type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL))
{
scanner_info_t *info_p = scanner_insert_info (context_p, source_p, sizeof (scanner_info_t));
info_p->type = SCANNER_TYPE_LET_EXPRESSION;
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
break;
}
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
/* FALLTHRU */
}
case LEXER_KEYW_LET:
case LEXER_KEYW_CONST:
{
scanner_literal_pool_t *literal_pool_p;
literal_pool_p = scanner_push_literal_pool (context_p, scanner_context_p, SCANNER_LITERAL_POOL_BLOCK);
literal_pool_p->source_p = source_p;
if (scanner_context_p->mode == SCAN_MODE_PRIMARY_EXPRESSION)
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
return_type = SCAN_NEXT_TOKEN;
}
stack_mode = ((context_p->token.type == LEXER_KEYW_CONST) ? SCAN_STACK_FOR_CONST_START
: SCAN_STACK_FOR_LET_START);
break;
}
#endif /* ENABLED (JERRY_ES2015) */
}
parser_stack_push (context_p, &for_statement, sizeof (scanner_for_statement_t));
parser_stack_push_uint8 (context_p, stack_mode);
return return_type;
}
case LEXER_KEYW_VAR:
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
parser_stack_push_uint8 (context_p, SCAN_STACK_VAR);
return SCAN_NEXT_TOKEN;
}
#if ENABLED (JERRY_ES2015)
case LEXER_KEYW_LET:
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
parser_stack_push_uint8 (context_p, SCAN_STACK_LET);
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_CONST:
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
parser_stack_push_uint8 (context_p, SCAN_STACK_CONST);
return SCAN_NEXT_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_KEYW_THROW:
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_RETURN:
{
lexer_next_token (context_p);
if (!(context_p->token.flags & LEXER_WAS_NEWLINE)
&& context_p->token.type != LEXER_SEMICOLON
&& context_p->token.type != LEXER_EOS
&& context_p->token.type != LEXER_RIGHT_BRACE)
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_KEEP_TOKEN;
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
return SCAN_KEEP_TOKEN;
}
case LEXER_KEYW_BREAK:
case LEXER_KEYW_CONTINUE:
{
lexer_next_token (context_p);
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
if (!(context_p->token.flags & LEXER_WAS_NEWLINE)
&& context_p->token.type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
return SCAN_NEXT_TOKEN;
}
return SCAN_KEEP_TOKEN;
}
case LEXER_KEYW_CASE:
case LEXER_KEYW_DEFAULT:
{
if (stack_top != SCAN_STACK_SWITCH_BLOCK)
{
scanner_raise_error (context_p);
}
scanner_case_info_t *case_info_p;
case_info_p = (scanner_case_info_t *) scanner_malloc (context_p, sizeof (scanner_case_info_t));
*(scanner_context_p->active_switch_statement.last_case_p) = case_info_p;
scanner_context_p->active_switch_statement.last_case_p = &case_info_p->next_p;
case_info_p->next_p = NULL;
scanner_get_location (&case_info_p->location, context_p);
if (type == LEXER_KEYW_DEFAULT)
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_COLON)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
return SCAN_NEXT_TOKEN;
}
scanner_source_start_t source_start;
source_start.source_p = context_p->source_p;
parser_stack_push (context_p, &source_start, sizeof (scanner_source_start_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_CASE_STATEMENT);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_FUNCTION:
{
#if ENABLED (JERRY_ES2015)
uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION | SCANNER_LITERAL_POOL_FUNCTION_STATEMENT;
if (scanner_context_p->async_source_p != NULL)
{
scanner_context_p->status_flags |= SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION;
status_flags |= SCANNER_LITERAL_POOL_ASYNC;
}
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_MULTIPLY)
{
status_flags |= SCANNER_LITERAL_POOL_GENERATOR;
lexer_next_token (context_p);
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, scanner_context_p);
#if ENABLED (JERRY_ES2015)
const uint8_t mask = (SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_FUNC | SCANNER_LITERAL_IS_LOCAL);
if ((literal_p->type & SCANNER_LITERAL_IS_LOCAL)
&& (literal_p->type & mask) != (SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_DESTRUCTURED_ARG)
&& (literal_p->type & mask) != (SCANNER_LITERAL_IS_FUNC | SCANNER_LITERAL_IS_FUNC_DECLARATION))
{
scanner_raise_redeclaration_error (context_p);
}
literal_p->type |= SCANNER_LITERAL_IS_FUNC | SCANNER_LITERAL_IS_FUNC_DECLARATION;
scanner_context_p->status_flags &= (uint16_t) ~SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION;
#else
literal_p->type |= SCANNER_LITERAL_IS_VAR | SCANNER_LITERAL_IS_FUNC;
uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;
#endif /* ENABLED (JERRY_ES2015) */
scanner_push_literal_pool (context_p, scanner_context_p, status_flags);
scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_STATEMENT);
return SCAN_NEXT_TOKEN;
}
#if ENABLED (JERRY_ES2015)
case LEXER_KEYW_CLASS:
{
scanner_push_class_declaration (context_p, scanner_context_p, SCAN_STACK_CLASS_STATEMENT);
if (context_p->token.type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, scanner_context_p);
scanner_detect_invalid_let (context_p, literal_p);
literal_p->type |= SCANNER_LITERAL_IS_LET;
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
if (scanner_context_p->active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT)
{
literal_p->type |= SCANNER_LITERAL_NO_REG;
scanner_context_p->active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;
}
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
return SCAN_NEXT_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
case LEXER_KEYW_IMPORT:
{
if (stack_top != SCAN_STACK_SCRIPT)
{
scanner_raise_error (context_p);
}
context_p->global_status_flags |= ECMA_PARSE_MODULE;
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
lexer_next_token (context_p);
if (context_p->token.type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_STRING_LITERAL)
{
return SCAN_NEXT_TOKEN;
}
bool parse_imports = true;
if (context_p->token.type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, scanner_context_p);
#if ENABLED (JERRY_ES2015)
scanner_detect_invalid_let (context_p, literal_p);
literal_p->type |= SCANNER_LITERAL_IS_LOCAL | SCANNER_LITERAL_NO_REG;
#else /* !ENABLED (JERRY_ES2015) */
literal_p->type |= SCANNER_LITERAL_IS_VAR | SCANNER_LITERAL_NO_REG;
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
if (context_p->token.type == LEXER_COMMA)
{
lexer_next_token (context_p);
}
else
{
parse_imports = false;
}
}
if (parse_imports)
{
if (context_p->token.type == LEXER_MULTIPLY)
{
lexer_next_token (context_p);
if (!lexer_token_is_identifier (context_p, "as", 2))
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, scanner_context_p);
#if ENABLED (JERRY_ES2015)
scanner_detect_invalid_let (context_p, literal_p);
literal_p->type |= SCANNER_LITERAL_IS_LOCAL | SCANNER_LITERAL_NO_REG;
#else /* !ENABLED (JERRY_ES2015) */
literal_p->type |= SCANNER_LITERAL_IS_VAR | SCANNER_LITERAL_NO_REG;
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
}
else if (context_p->token.type == LEXER_LEFT_BRACE)
{
lexer_next_token (context_p);
while (context_p->token.type != LEXER_RIGHT_BRACE)
{
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
#if ENABLED (JERRY_ES2015)
const uint8_t *source_p = context_p->source_p;
#endif /* ENABLED (JERRY_ES2015) */
if (lexer_check_next_character (context_p, LIT_CHAR_LOWERCASE_A))
{
lexer_next_token (context_p);
if (!lexer_token_is_identifier (context_p, "as", 2))
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
#if ENABLED (JERRY_ES2015)
source_p = context_p->source_p;
#endif /* ENABLED (JERRY_ES2015) */
}
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, scanner_context_p);
#if ENABLED (JERRY_ES2015)
if (literal_p->type & (SCANNER_LITERAL_IS_ARG
| SCANNER_LITERAL_IS_VAR
| SCANNER_LITERAL_IS_LOCAL))
{
context_p->source_p = source_p;
scanner_raise_redeclaration_error (context_p);
}
if (literal_p->type & SCANNER_LITERAL_IS_FUNC)
{
literal_p->type &= (uint8_t) ~SCANNER_LITERAL_IS_FUNC;
}
literal_p->type |= SCANNER_LITERAL_IS_LOCAL | SCANNER_LITERAL_NO_REG;
#else /* !ENABLED (JERRY_ES2015) */
literal_p->type |= SCANNER_LITERAL_IS_VAR | SCANNER_LITERAL_NO_REG;
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
if (context_p->token.type != LEXER_RIGHT_BRACE)
{
if (context_p->token.type != LEXER_COMMA)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
}
}
lexer_next_token (context_p);
}
else
{
scanner_raise_error (context_p);
}
}
if (!lexer_token_is_identifier (context_p, "from", 4))
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL
&& context_p->token.lit_location.type != LEXER_STRING_LITERAL)
{
scanner_raise_error (context_p);
}
return SCAN_NEXT_TOKEN;
}
case LEXER_KEYW_EXPORT:
{
if (stack_top != SCAN_STACK_SCRIPT)
{
scanner_raise_error (context_p);
}
context_p->global_status_flags |= ECMA_PARSE_MODULE;
lexer_next_token (context_p);
if (context_p->token.type == LEXER_KEYW_DEFAULT)
{
lexer_next_token (context_p);
if (context_p->token.type == LEXER_KEYW_FUNCTION)
{
lexer_next_token (context_p);
if (context_p->token.type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
lexer_lit_location_t *location_p = scanner_add_literal (context_p, scanner_context_p);
#if ENABLED (JERRY_ES2015)
if (location_p->type & SCANNER_LITERAL_IS_LOCAL
&& !(location_p->type & SCANNER_LITERAL_IS_FUNC))
{
scanner_raise_redeclaration_error (context_p);
}
location_p->type |= SCANNER_LITERAL_IS_FUNC | SCANNER_LITERAL_IS_LET;
#else /* !ENABLED (JERRY_ES2015) */
location_p->type |= SCANNER_LITERAL_IS_VAR | SCANNER_LITERAL_IS_FUNC;
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
}
else
{
lexer_lit_location_t *location_p;
location_p = scanner_add_custom_literal (context_p,
scanner_context_p->active_literal_pool_p,
&lexer_default_literal);
#if ENABLED (JERRY_ES2015)
location_p->type |= SCANNER_LITERAL_IS_FUNC | SCANNER_LITERAL_IS_LET;
#else /* !ENABLED (JERRY_ES2015) */
location_p->type |= SCANNER_LITERAL_IS_VAR | SCANNER_LITERAL_IS_FUNC;
#endif /* ENABLED (JERRY_ES2015) */
}
scanner_push_literal_pool (context_p, scanner_context_p, SCANNER_LITERAL_POOL_FUNCTION);
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_STATEMENT);
scanner_context_p->mode = SCAN_MODE_FUNCTION_ARGUMENTS;
return SCAN_KEEP_TOKEN;
}
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_KEYW_CLASS)
{
scanner_push_class_declaration (context_p, scanner_context_p, SCAN_STACK_CLASS_STATEMENT);
if (context_p->token.type == LEXER_LITERAL && context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, scanner_context_p);
scanner_detect_invalid_let (context_p, literal_p);
literal_p->type |= SCANNER_LITERAL_IS_LET | SCANNER_LITERAL_NO_REG;
return SCAN_NEXT_TOKEN;
}
lexer_lit_location_t *literal_p;
literal_p = scanner_add_custom_literal (context_p,
scanner_context_p->active_literal_pool_p,
&lexer_default_literal);
literal_p->type |= SCANNER_LITERAL_IS_LET | SCANNER_LITERAL_NO_REG;
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
/* Assignment expression. */
lexer_lit_location_t *location_p;
location_p = scanner_add_custom_literal (context_p,
scanner_context_p->active_literal_pool_p,
&lexer_default_literal);
location_p->type |= SCANNER_LITERAL_IS_VAR;
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
if (context_p->token.type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
return SCAN_KEEP_TOKEN;
}
location_p = scanner_add_literal (context_p, scanner_context_p);
location_p->type |= SCANNER_LITERAL_IS_VAR;
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_END;
if (context_p->token.type == LEXER_MULTIPLY)
{
lexer_next_token (context_p);
if (!lexer_token_is_identifier (context_p, "from", 4))
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_STRING_LITERAL)
{
scanner_raise_error (context_p);
}
return SCAN_NEXT_TOKEN;
}
if (context_p->token.type == LEXER_LEFT_BRACE)
{
lexer_next_token (context_p);
while (context_p->token.type != LEXER_RIGHT_BRACE)
{
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (lexer_token_is_identifier (context_p, "as", 2))
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
}
if (context_p->token.type != LEXER_RIGHT_BRACE)
{
if (context_p->token.type != LEXER_COMMA)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
}
}
lexer_next_token (context_p);
if (!lexer_token_is_identifier (context_p, "from", 4))
{
return SCAN_KEEP_TOKEN;
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_STRING_LITERAL)
{
scanner_raise_error (context_p);
}
return SCAN_NEXT_TOKEN;
}
switch (context_p->token.type)
{
#if ENABLED (JERRY_ES2015)
case LEXER_KEYW_CLASS:
case LEXER_KEYW_LET:
case LEXER_KEYW_CONST:
#endif /* ENABLED (JERRY_ES2015) */
case LEXER_KEYW_VAR:
{
scanner_context_p->active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_IN_EXPORT;
break;
}
}
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
default:
{
break;
}
}
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
if (type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL)
{
if (JERRY_UNLIKELY (lexer_check_next_character (context_p, LIT_CHAR_COLON)))
{
lexer_consume_next_character (context_p);
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_NEXT_TOKEN;
}
JERRY_ASSERT (context_p->token.flags & LEXER_NO_SKIP_SPACES);
#if ENABLED (JERRY_ES2015)
/* The colon needs to be checked first because the parser also checks
* it first, and this check skips the spaces which affects source_p. */
if (JERRY_UNLIKELY (lexer_check_arrow (context_p)))
{
scanner_scan_simple_arrow (context_p, scanner_context_p, context_p->source_p);
return SCAN_KEEP_TOKEN;
}
if (JERRY_UNLIKELY (lexer_token_is_let (context_p)))
{
lexer_lit_location_t let_literal = context_p->token.lit_location;
const uint8_t *source_p = context_p->source_p;
lexer_next_token (context_p);
type = (lexer_token_type_t) context_p->token.type;
if (type == LEXER_LEFT_SQUARE
|| type == LEXER_LEFT_BRACE
|| (type == LEXER_LITERAL && context_p->token.lit_location.type == LEXER_IDENT_LITERAL))
{
scanner_context_p->mode = SCAN_MODE_VAR_STATEMENT;
parser_stack_push_uint8 (context_p, SCAN_STACK_LET);
return SCAN_KEEP_TOKEN;
}
scanner_info_t *info_p = scanner_insert_info (context_p, source_p, sizeof (scanner_info_t));
info_p->type = SCANNER_TYPE_LET_EXPRESSION;
lexer_lit_location_t *lit_location_p = scanner_add_custom_literal (context_p,
scanner_context_p->active_literal_pool_p,
&let_literal);
lit_location_p->type |= SCANNER_LITERAL_IS_USED;
if (scanner_context_p->active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)
{
lit_location_p->type |= SCANNER_LITERAL_NO_REG;
}
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
return SCAN_KEEP_TOKEN;
}
if (JERRY_UNLIKELY (lexer_token_is_async (context_p)))
{
scanner_context_p->async_source_p = context_p->source_p;
if (scanner_check_async_function (context_p, scanner_context_p))
{
scanner_context_p->mode = SCAN_MODE_STATEMENT;
}
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
scanner_add_reference (context_p, scanner_context_p);
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
return SCAN_KEEP_TOKEN;
} /* scanner_scan_statement */
/**
* Scan statement terminator.
*
* @return SCAN_NEXT_TOKEN to read the next token, or SCAN_KEEP_TOKEN to do nothing
*/
static scan_return_types_t
scanner_scan_statement_end (parser_context_t *context_p, /**< context */
scanner_context_t *scanner_context_p, /**< scanner context */
lexer_token_type_t type) /**< current token type */
{
bool terminator_found = false;
if (type == LEXER_SEMICOLON)
{
lexer_next_token (context_p);
terminator_found = true;
}
while (true)
{
type = (lexer_token_type_t) context_p->token.type;
switch (context_p->stack_top_uint8)
{
case SCAN_STACK_SCRIPT:
case SCAN_STACK_SCRIPT_FUNCTION:
{
if (type == LEXER_EOS)
{
return SCAN_NEXT_TOKEN;
}
break;
}
case SCAN_STACK_BLOCK_STATEMENT:
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_CLASS_STATEMENT:
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_STACK_FUNCTION_STATEMENT:
{
if (type != LEXER_RIGHT_BRACE)
{
break;
}
#if ENABLED (JERRY_ES2015)
if (context_p->stack_top_uint8 != SCAN_STACK_CLASS_STATEMENT)
{
scanner_pop_literal_pool (context_p, scanner_context_p);
}
#else /* !ENABLED (JERRY_ES2015) */
if (context_p->stack_top_uint8 == SCAN_STACK_FUNCTION_STATEMENT)
{
scanner_pop_literal_pool (context_p, scanner_context_p);
}
#endif /* ENABLED (JERRY_ES2015) */
terminator_found = true;
parser_stack_pop_uint8 (context_p);
lexer_next_token (context_p);
continue;
}
case SCAN_STACK_FUNCTION_EXPRESSION:
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_FUNCTION_ARROW:
#endif /* ENABLED (JERRY_ES2015) */
{
if (type != LEXER_RIGHT_BRACE)
{
break;
}
scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
#if ENABLED (JERRY_ES2015)
if (context_p->stack_top_uint8 == SCAN_STACK_FUNCTION_ARROW)
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
}
#endif /* ENABLED (JERRY_ES2015) */
scanner_pop_literal_pool (context_p, scanner_context_p);
parser_stack_pop_uint8 (context_p);
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_FUNCTION_PROPERTY:
{
if (type != LEXER_RIGHT_BRACE)
{
break;
}
scanner_pop_literal_pool (context_p, scanner_context_p);
parser_stack_pop_uint8 (context_p);
#if ENABLED (JERRY_ES2015)
if (context_p->stack_top_uint8 == SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR
|| context_p->stack_top_uint8 == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)
{
scanner_context_p->mode = SCAN_MODE_CLASS_METHOD;
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
JERRY_ASSERT (context_p->stack_top_uint8 == SCAN_STACK_OBJECT_LITERAL);
lexer_next_token (context_p);
if (context_p->token.type == LEXER_RIGHT_BRACE)
{
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
return SCAN_KEEP_TOKEN;
}
if (context_p->token.type != LEXER_COMMA)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_PROPERTY_NAME;
return SCAN_KEEP_TOKEN;
}
case SCAN_STACK_SWITCH_BLOCK:
{
if (type != LEXER_RIGHT_BRACE)
{
break;
}
scanner_switch_statement_t switch_statement;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &switch_statement, sizeof (scanner_switch_statement_t));
scanner_context_p->active_switch_statement = switch_statement;
#if ENABLED (JERRY_ES2015)
scanner_pop_literal_pool (context_p, scanner_context_p);
#endif /* ENABLED (JERRY_ES2015) */
terminator_found = true;
lexer_next_token (context_p);
continue;
}
case SCAN_STACK_IF_STATEMENT:
{
parser_stack_pop_uint8 (context_p);
if (type == LEXER_KEYW_ELSE
&& (terminator_found || (context_p->token.flags & LEXER_WAS_NEWLINE)))
{
#if ENABLED (JERRY_ES2015)
scanner_check_function_after_if (context_p, scanner_context_p);
return SCAN_KEEP_TOKEN;
#else /* !ENABLED (JERRY_ES2015) */
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_NEXT_TOKEN;
#endif /* ENABLED (JERRY_ES2015) */
}
continue;
}
case SCAN_STACK_WITH_STATEMENT:
{
scanner_literal_pool_t *literal_pool_p = scanner_context_p->active_literal_pool_p;
JERRY_ASSERT (literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH);
parser_stack_pop_uint8 (context_p);
if (context_p->stack_top_uint8 == 0)
{
literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_WITH;
}
parser_stack_pop_uint8 (context_p);
continue;
}
case SCAN_STACK_DO_STATEMENT:
{
parser_stack_pop_uint8 (context_p);
if (type != LEXER_KEYW_WHILE
|| (!terminator_found && !(context_p->token.flags & LEXER_WAS_NEWLINE)))
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_PAREN)
{
scanner_raise_error (context_p);
}
parser_stack_push_uint8 (context_p, SCAN_STACK_DO_EXPRESSION);
scanner_context_p->mode = SCAN_MODE_PRIMARY_EXPRESSION;
return SCAN_NEXT_TOKEN;
}
case SCAN_STACK_DO_EXPRESSION:
{
parser_stack_pop_uint8 (context_p);
terminator_found = true;
continue;
}
#if ENABLED (JERRY_ES2015)
case SCAN_STACK_PRIVATE_BLOCK_EARLY:
{
parser_list_iterator_t literal_iterator;
lexer_lit_location_t *literal_p;
parser_list_iterator_init (&scanner_context_p->active_literal_pool_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_lit_location_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if ((literal_p->type & (SCANNER_LITERAL_IS_LET | SCANNER_LITERAL_IS_CONST))
&& literal_p->type & SCANNER_LITERAL_NO_REG)
{
literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
}
}
/* FALLTHRU */
}
case SCAN_STACK_PRIVATE_BLOCK:
{
parser_stack_pop_uint8 (context_p);
scanner_pop_literal_pool (context_p, scanner_context_p);
continue;
}
#endif /* ENABLED (JERRY_ES2015) */
default:
{
JERRY_ASSERT (context_p->stack_top_uint8 == SCAN_STACK_TRY_STATEMENT
|| context_p->stack_top_uint8 == SCAN_STACK_CATCH_STATEMENT);
if (type != LEXER_RIGHT_BRACE)
{
break;
}
uint8_t stack_top = context_p->stack_top_uint8;
parser_stack_pop_uint8 (context_p);
lexer_next_token (context_p);
#if ENABLED (JERRY_ES2015)
scanner_pop_literal_pool (context_p, scanner_context_p);
#else /* !ENABLED (JERRY_ES2015) */
if (stack_top == SCAN_STACK_CATCH_STATEMENT)
{
scanner_pop_literal_pool (context_p, scanner_context_p);
}
#endif /* ENABLED (JERRY_ES2015) */
/* A finally statement is optional after a try or catch statement. */
if (context_p->token.type == LEXER_KEYW_FINALLY)
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_BRACE)
{
scanner_raise_error (context_p);
}
#if ENABLED (JERRY_ES2015)
scanner_literal_pool_t *literal_pool_p;
literal_pool_p = scanner_push_literal_pool (context_p,
scanner_context_p,
SCANNER_LITERAL_POOL_BLOCK);
literal_pool_p->source_p = context_p->source_p;
#endif /* ENABLED (JERRY_ES2015) */
parser_stack_push_uint8 (context_p, SCAN_STACK_BLOCK_STATEMENT);
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
return SCAN_NEXT_TOKEN;
}
if (stack_top == SCAN_STACK_CATCH_STATEMENT)
{
terminator_found = true;
continue;
}
/* A catch statement must be present after a try statement unless a finally is provided. */
if (context_p->token.type != LEXER_KEYW_CATCH)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_PAREN)
{
scanner_raise_error (context_p);
}
scanner_literal_pool_t *literal_pool_p;
literal_pool_p = scanner_push_literal_pool (context_p, scanner_context_p, SCANNER_LITERAL_POOL_BLOCK);
literal_pool_p->source_p = context_p->source_p;
lexer_next_token (context_p);
parser_stack_push_uint8 (context_p, SCAN_STACK_CATCH_STATEMENT);
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)
{
scanner_push_destructuring_pattern (context_p, scanner_context_p, SCANNER_BINDING_CATCH, false);
if (context_p->token.type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);
scanner_context_p->mode = SCAN_MODE_BINDING;
return SCAN_NEXT_TOKEN;
}
parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);
scanner_context_p->mode = SCAN_MODE_PROPERTY_NAME;
return SCAN_KEEP_TOKEN;
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_lit_location_t *lit_location_p = scanner_add_literal (context_p, scanner_context_p);
lit_location_p->type |= SCANNER_LITERAL_IS_LOCAL;
lexer_next_token (context_p);
if (context_p->token.type != LEXER_RIGHT_PAREN)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_BRACE)
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR;
return SCAN_NEXT_TOKEN;
}
}
if (!terminator_found && !(context_p->token.flags & LEXER_WAS_NEWLINE))
{
scanner_raise_error (context_p);
}
scanner_context_p->mode = SCAN_MODE_STATEMENT;
return SCAN_KEEP_TOKEN;
}
} /* scanner_scan_statement_end */
/**
* Scan the whole source code.
*/
void JERRY_ATTR_NOINLINE
scanner_scan_all (parser_context_t *context_p, /**< context */
const uint8_t *arg_list_p, /**< function argument list */
const uint8_t *arg_list_end_p, /**< end of argument list */
const uint8_t *source_p, /**< valid UTF-8 source code */
const uint8_t *source_end_p) /**< end of source code */
{
scanner_context_t scanner_context;
#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)
if (context_p->is_show_opcodes)
{
JERRY_DEBUG_MSG ("\n--- Scanning start ---\n\n");
}
#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */
scanner_context.context_status_flags = context_p->status_flags;
scanner_context.status_flags = SCANNER_CONTEXT_NO_FLAGS;
#if ENABLED (JERRY_DEBUGGER)
if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED)
{
scanner_context.status_flags |= SCANNER_CONTEXT_DEBUGGER_ENABLED;
}
#endif /* ENABLED (JERRY_DEBUGGER) */
#if ENABLED (JERRY_ES2015)
scanner_context.binding_type = SCANNER_BINDING_NONE;
scanner_context.active_binding_list_p = NULL;
#endif /* ENABLED (JERRY_ES2015) */
scanner_context.active_literal_pool_p = NULL;
scanner_context.active_switch_statement.last_case_p = NULL;
scanner_context.end_arguments_p = NULL;
#if ENABLED (JERRY_ES2015)
scanner_context.async_source_p = NULL;
#endif /* ENABLED (JERRY_ES2015) */
/* This assignment must be here because of Apple compilers. */
context_p->u.scanner_context_p = &scanner_context;
parser_stack_init (context_p);
PARSER_TRY (context_p->try_buffer)
{
context_p->line = 1;
context_p->column = 1;
if (arg_list_p == NULL)
{
context_p->source_p = source_p;
context_p->source_end_p = source_end_p;
uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION_WITHOUT_ARGUMENTS | SCANNER_LITERAL_POOL_CAN_EVAL;
if (context_p->status_flags & PARSER_IS_STRICT)
{
status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;
}
scanner_literal_pool_t *literal_pool_p = scanner_push_literal_pool (context_p, &scanner_context, status_flags);
literal_pool_p->source_p = source_p;
parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT);
lexer_next_token (context_p);
scanner_check_directives (context_p, &scanner_context);
}
else
{
context_p->source_p = arg_list_p;
context_p->source_end_p = arg_list_end_p;
uint16_t status_flags = SCANNER_LITERAL_POOL_FUNCTION;
if (context_p->status_flags & PARSER_IS_STRICT)
{
status_flags |= SCANNER_LITERAL_POOL_IS_STRICT;
}
#if ENABLED (JERRY_ES2015)
if (context_p->status_flags & PARSER_IS_GENERATOR_FUNCTION)
{
status_flags |= SCANNER_LITERAL_POOL_GENERATOR;
}
#endif /* ENABLED (JERRY_ES2015) */
scanner_push_literal_pool (context_p, &scanner_context, status_flags);
scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;
parser_stack_push_uint8 (context_p, SCAN_STACK_SCRIPT_FUNCTION);
/* Faking the first token. */
context_p->token.type = LEXER_LEFT_PAREN;
}
while (true)
{
lexer_token_type_t type = (lexer_token_type_t) context_p->token.type;
scan_stack_modes_t stack_top = (scan_stack_modes_t) context_p->stack_top_uint8;
switch (scanner_context.mode)
{
case SCAN_MODE_PRIMARY_EXPRESSION:
{
if (type == LEXER_ADD
|| type == LEXER_SUBTRACT
|| LEXER_IS_UNARY_OP_TOKEN (type))
{
break;
}
/* FALLTHRU */
}
case SCAN_MODE_PRIMARY_EXPRESSION_AFTER_NEW:
{
if (scanner_scan_primary_expression (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)
{
continue;
}
break;
}
#if ENABLED (JERRY_ES2015)
case SCAN_MODE_CLASS_DECLARATION:
{
if (context_p->token.type == LEXER_KEYW_EXTENDS)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_CLASS_EXTENDS);
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
else if (context_p->token.type != LEXER_LEFT_BRACE)
{
scanner_raise_error (context_p);
}
scanner_context.mode = SCAN_MODE_CLASS_METHOD;
/* FALLTHRU */
}
case SCAN_MODE_CLASS_METHOD:
{
JERRY_ASSERT (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR
|| stack_top == SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);
lexer_skip_empty_statements (context_p);
lexer_scan_identifier (context_p);
if (context_p->token.type == LEXER_RIGHT_BRACE)
{
scanner_source_start_t source_start;
parser_stack_pop_uint8 (context_p);
if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)
{
parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));
}
stack_top = context_p->stack_top_uint8;
JERRY_ASSERT (stack_top == SCAN_STACK_CLASS_STATEMENT || stack_top == SCAN_STACK_CLASS_EXPRESSION);
if (stack_top == SCAN_STACK_CLASS_STATEMENT)
{
/* The token is kept to disallow consuming a semicolon after it. */
scanner_context.mode = SCAN_MODE_STATEMENT_END;
continue;
}
scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
parser_stack_pop_uint8 (context_p);
break;
}
if (context_p->token.type == LEXER_LITERAL
&& LEXER_IS_IDENT_OR_STRING (context_p->token.lit_location.type)
&& lexer_compare_literal_to_string (context_p, "constructor", 11))
{
if (stack_top == SCAN_STACK_IMPLICIT_CLASS_CONSTRUCTOR)
{
scanner_source_start_t source_start;
parser_stack_pop_uint8 (context_p);
parser_stack_pop (context_p, &source_start, sizeof (scanner_source_start_t));
scanner_info_t *info_p = scanner_insert_info (context_p, source_start.source_p, sizeof (scanner_info_t));
info_p->type = SCANNER_TYPE_CLASS_CONSTRUCTOR;
parser_stack_push_uint8 (context_p, SCAN_STACK_EXPLICIT_CLASS_CONSTRUCTOR);
}
}
if (lexer_token_is_identifier (context_p, "static", 6))
{
lexer_scan_identifier (context_p);
}
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);
scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;
uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;
if (lexer_token_is_identifier (context_p, "get", 3)
|| lexer_token_is_identifier (context_p, "set", 3))
{
lexer_scan_identifier (context_p);
if (context_p->token.type == LEXER_LEFT_PAREN)
{
scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);
continue;
}
}
else if (lexer_token_is_identifier (context_p, "async", 5))
{
lexer_scan_identifier (context_p);
if (context_p->token.type == LEXER_LEFT_PAREN)
{
scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);
continue;
}
literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;
if (context_p->token.type == LEXER_MULTIPLY)
{
lexer_scan_identifier (context_p);
literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;
}
}
else if (context_p->token.type == LEXER_MULTIPLY)
{
lexer_scan_identifier (context_p);
literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;
}
if (context_p->token.type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
if (context_p->token.type != LEXER_LITERAL)
{
scanner_raise_error (context_p);
}
if (literal_pool_flags & SCANNER_LITERAL_POOL_GENERATOR)
{
context_p->status_flags |= PARSER_IS_GENERATOR_FUNCTION;
}
scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);
lexer_next_token (context_p);
continue;
}
#endif /* ENABLED (JERRY_ES2015) */
case SCAN_MODE_POST_PRIMARY_EXPRESSION:
{
if (scanner_scan_post_primary_expression (context_p, &scanner_context, type, stack_top))
{
break;
}
type = (lexer_token_type_t) context_p->token.type;
/* FALLTHRU */
}
case SCAN_MODE_PRIMARY_EXPRESSION_END:
{
if (scanner_scan_primary_expression_end (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)
{
continue;
}
break;
}
case SCAN_MODE_STATEMENT_OR_TERMINATOR:
{
if (type == LEXER_RIGHT_BRACE || type == LEXER_EOS)
{
scanner_context.mode = SCAN_MODE_STATEMENT_END;
continue;
}
/* FALLTHRU */
}
case SCAN_MODE_STATEMENT:
{
if (scanner_scan_statement (context_p, &scanner_context, type, stack_top) != SCAN_NEXT_TOKEN)
{
continue;
}
break;
}
case SCAN_MODE_STATEMENT_END:
{
if (scanner_scan_statement_end (context_p, &scanner_context, type) != SCAN_NEXT_TOKEN)
{
continue;
}
if (context_p->token.type == LEXER_EOS)
{
goto scan_completed;
}
break;
}
case SCAN_MODE_VAR_STATEMENT:
{
#if ENABLED (JERRY_ES2015)
if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)
{
uint8_t binding_type = SCANNER_BINDING_VAR;
if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)
{
binding_type = SCANNER_BINDING_LET;
}
else if (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START)
{
binding_type = SCANNER_BINDING_CONST;
}
scanner_push_destructuring_pattern (context_p, &scanner_context, binding_type, false);
if (type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);
scanner_context.mode = SCAN_MODE_BINDING;
break;
}
parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);
scanner_context.mode = SCAN_MODE_PROPERTY_NAME;
continue;
}
#endif /* ENABLED (JERRY_ES2015) */
if (type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);
#if ENABLED (JERRY_ES2015)
if (stack_top != SCAN_STACK_VAR && stack_top != SCAN_STACK_FOR_VAR_START)
{
scanner_detect_invalid_let (context_p, literal_p);
if (stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_FOR_LET_START)
{
literal_p->type |= SCANNER_LITERAL_IS_LET;
}
else
{
JERRY_ASSERT (stack_top == SCAN_STACK_CONST || stack_top == SCAN_STACK_FOR_CONST_START);
literal_p->type |= SCANNER_LITERAL_IS_CONST;
}
lexer_next_token (context_p);
if (literal_p->type & SCANNER_LITERAL_IS_USED)
{
literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
}
else if (context_p->token.type == LEXER_ASSIGN)
{
scanner_binding_literal_t binding_literal;
binding_literal.literal_p = literal_p;
parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);
}
}
else
{
if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))
{
scanner_detect_invalid_var (context_p, &scanner_context, literal_p);
literal_p->type |= SCANNER_LITERAL_IS_VAR;
if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)
{
literal_p->type |= SCANNER_LITERAL_NO_REG;
}
}
lexer_next_token (context_p);
}
#else /* !ENABLED (JERRY_ES2015) */
literal_p->type |= SCANNER_LITERAL_IS_VAR;
if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)
{
literal_p->type |= SCANNER_LITERAL_NO_REG;
}
lexer_next_token (context_p);
#endif /* ENABLED (JERRY_ES2015) */
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT)
{
literal_p->type |= SCANNER_LITERAL_NO_REG;
}
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
switch (context_p->token.type)
{
case LEXER_ASSIGN:
{
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
/* FALLTHRU */
}
case LEXER_COMMA:
{
lexer_next_token (context_p);
continue;
}
}
if (SCANNER_IS_FOR_START (stack_top))
{
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
JERRY_ASSERT (!(scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_EXPORT));
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
if (context_p->token.type != LEXER_SEMICOLON
&& context_p->token.type != LEXER_KEYW_IN
&& !SCANNER_IDENTIFIER_IS_OF ())
{
scanner_raise_error (context_p);
}
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
continue;
}
#if ENABLED (JERRY_ES2015)
JERRY_ASSERT (stack_top == SCAN_STACK_VAR || stack_top == SCAN_STACK_LET || stack_top == SCAN_STACK_CONST);
#else /* !ENABLED (JERRY_ES2015) */
JERRY_ASSERT (stack_top == SCAN_STACK_VAR);
#endif /* ENABLED (JERRY_ES2015) */
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
scanner_context.active_literal_pool_p->status_flags &= (uint16_t) ~SCANNER_LITERAL_POOL_IN_EXPORT;
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
scanner_context.mode = SCAN_MODE_STATEMENT_END;
parser_stack_pop_uint8 (context_p);
continue;
}
case SCAN_MODE_FUNCTION_ARGUMENTS:
{
JERRY_ASSERT (stack_top == SCAN_STACK_SCRIPT_FUNCTION
|| stack_top == SCAN_STACK_FUNCTION_STATEMENT
|| stack_top == SCAN_STACK_FUNCTION_EXPRESSION
|| stack_top == SCAN_STACK_FUNCTION_PROPERTY);
scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;
JERRY_ASSERT (literal_pool_p != NULL && (literal_pool_p->status_flags & SCANNER_LITERAL_POOL_FUNCTION));
literal_pool_p->source_p = context_p->source_p;
#if ENABLED (JERRY_ES2015)
if (JERRY_UNLIKELY (scanner_context.async_source_p != NULL))
{
literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ASYNC;
literal_pool_p->source_p = scanner_context.async_source_p;
scanner_context.async_source_p = NULL;
}
#endif /* ENABLED (JERRY_ES2015) */
if (type != LEXER_LEFT_PAREN)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
#if ENABLED (JERRY_ES2015)
/* FALLTHRU */
}
case SCAN_MODE_CONTINUE_FUNCTION_ARGUMENTS:
{
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type != LEXER_RIGHT_PAREN && context_p->token.type != LEXER_EOS)
{
#if ENABLED (JERRY_ES2015)
lexer_lit_location_t *argument_literal_p;
#endif /* ENABLED (JERRY_ES2015) */
while (true)
{
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_THREE_DOTS)
{
scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;
lexer_next_token (context_p);
}
if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)
{
argument_literal_p = NULL;
break;
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_raise_error (context_p);
}
#if ENABLED (JERRY_ES2015)
argument_literal_p = scanner_append_argument (context_p, &scanner_context);
#else /* !ENABLED (JERRY_ES2015) */
scanner_append_argument (context_p, &scanner_context);
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
if (context_p->token.type != LEXER_COMMA)
{
break;
}
lexer_next_token (context_p);
}
#if ENABLED (JERRY_ES2015)
if (argument_literal_p == NULL)
{
scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);
scanner_append_hole (context_p, &scanner_context);
scanner_push_destructuring_pattern (context_p, &scanner_context, SCANNER_BINDING_ARG, false);
if (context_p->token.type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);
scanner_context.mode = SCAN_MODE_BINDING;
break;
}
parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);
scanner_context.mode = SCAN_MODE_PROPERTY_NAME;
continue;
}
if (context_p->token.type == LEXER_ASSIGN)
{
scanner_context.active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_ARGUMENTS_UNMAPPED;
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PARAMETERS);
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
if (argument_literal_p->type & SCANNER_LITERAL_IS_USED)
{
JERRY_ASSERT (argument_literal_p->type & SCANNER_LITERAL_EARLY_CREATE);
break;
}
scanner_binding_literal_t binding_literal;
binding_literal.literal_p = argument_literal_p;
parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);
break;
}
#endif /* ENABLED (JERRY_ES2015) */
}
if (context_p->token.type == LEXER_EOS && stack_top == SCAN_STACK_SCRIPT_FUNCTION)
{
/* End of argument parsing. */
scanner_info_t *scanner_info_p = (scanner_info_t *) scanner_malloc (context_p, sizeof (scanner_info_t));
scanner_info_p->next_p = context_p->next_scanner_info_p;
scanner_info_p->source_p = NULL;
scanner_info_p->type = SCANNER_TYPE_END_ARGUMENTS;
scanner_context.end_arguments_p = scanner_info_p;
context_p->next_scanner_info_p = scanner_info_p;
context_p->source_p = source_p;
context_p->source_end_p = source_end_p;
context_p->line = 1;
context_p->column = 1;
scanner_filter_arguments (context_p, &scanner_context);
lexer_next_token (context_p);
scanner_check_directives (context_p, &scanner_context);
continue;
}
if (context_p->token.type != LEXER_RIGHT_PAREN)
{
scanner_raise_error (context_p);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LEFT_BRACE)
{
scanner_raise_error (context_p);
}
scanner_filter_arguments (context_p, &scanner_context);
lexer_next_token (context_p);
scanner_check_directives (context_p, &scanner_context);
continue;
}
case SCAN_MODE_PROPERTY_NAME:
{
JERRY_ASSERT (stack_top == SCAN_STACK_OBJECT_LITERAL);
if (lexer_scan_identifier (context_p))
{
lexer_check_property_modifier (context_p);
}
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_COMPUTED_PROPERTY);
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type == LEXER_RIGHT_BRACE)
{
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
continue;
}
if (context_p->token.type == LEXER_PROPERTY_GETTER
#if ENABLED (JERRY_ES2015)
|| context_p->token.type == LEXER_KEYW_ASYNC
|| context_p->token.type == LEXER_MULTIPLY
#endif /* ENABLED (JERRY_ES2015) */
|| context_p->token.type == LEXER_PROPERTY_SETTER)
{
uint16_t literal_pool_flags = SCANNER_LITERAL_POOL_FUNCTION;
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_MULTIPLY)
{
literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;
}
else if (context_p->token.type == LEXER_KEYW_ASYNC)
{
literal_pool_flags |= SCANNER_LITERAL_POOL_ASYNC;
if (lexer_consume_generator (context_p))
{
literal_pool_flags |= SCANNER_LITERAL_POOL_GENERATOR;
}
}
#endif /* ENABLED (JERRY_ES2015) */
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);
lexer_scan_identifier (context_p);
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCANNER_FROM_LITERAL_POOL_TO_COMPUTED (literal_pool_flags));
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type != LEXER_LITERAL)
{
scanner_raise_error (context_p);
}
scanner_push_literal_pool (context_p, &scanner_context, literal_pool_flags);
scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;
break;
}
if (context_p->token.type != LEXER_LITERAL)
{
scanner_raise_error (context_p);
}
#if ENABLED (JERRY_ES2015)
parser_line_counter_t start_line = context_p->token.line;
parser_line_counter_t start_column = context_p->token.column;
bool is_ident = (context_p->token.lit_location.type == LEXER_IDENT_LITERAL);
#endif /* ENABLED (JERRY_ES2015) */
lexer_next_token (context_p);
#if ENABLED (JERRY_ES2015)
if (context_p->token.type == LEXER_LEFT_PAREN)
{
scanner_push_literal_pool (context_p, &scanner_context, SCANNER_LITERAL_POOL_FUNCTION);
parser_stack_push_uint8 (context_p, SCAN_STACK_FUNCTION_PROPERTY);
scanner_context.mode = SCAN_MODE_FUNCTION_ARGUMENTS;
continue;
}
if (is_ident
&& (context_p->token.type == LEXER_COMMA
|| context_p->token.type == LEXER_RIGHT_BRACE
|| context_p->token.type == LEXER_ASSIGN))
{
context_p->source_p = context_p->token.lit_location.char_p;
context_p->line = start_line;
context_p->column = start_column;
lexer_next_token (context_p);
JERRY_ASSERT (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type == LEXER_IDENT_LITERAL);
if (context_p->token.type != LEXER_LITERAL)
{
scanner_raise_error (context_p);
}
if (scanner_context.binding_type != SCANNER_BINDING_NONE)
{
scanner_context.mode = SCAN_MODE_BINDING;
continue;
}
scanner_add_reference (context_p, &scanner_context);
lexer_next_token (context_p);
if (context_p->token.type == LEXER_ASSIGN)
{
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION_END;
continue;
}
#endif /* ENABLED (JERRY_ES2015) */
if (context_p->token.type != LEXER_COLON)
{
scanner_raise_error (context_p);
}
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
#if ENABLED (JERRY_ES2015)
if (scanner_context.binding_type != SCANNER_BINDING_NONE)
{
scanner_context.mode = SCAN_MODE_BINDING;
}
#endif /* ENABLED (JERRY_ES2015) */
break;
}
#if ENABLED (JERRY_ES2015)
case SCAN_MODE_BINDING:
{
JERRY_ASSERT (scanner_context.binding_type == SCANNER_BINDING_VAR
|| scanner_context.binding_type == SCANNER_BINDING_LET
|| scanner_context.binding_type == SCANNER_BINDING_CATCH
|| scanner_context.binding_type == SCANNER_BINDING_CONST
|| scanner_context.binding_type == SCANNER_BINDING_ARG
|| scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG);
if (type == LEXER_THREE_DOTS)
{
lexer_next_token (context_p);
type = (lexer_token_type_t) context_p->token.type;
}
if (type == LEXER_LEFT_SQUARE || type == LEXER_LEFT_BRACE)
{
scanner_push_destructuring_pattern (context_p, &scanner_context, scanner_context.binding_type, true);
if (type == LEXER_LEFT_SQUARE)
{
parser_stack_push_uint8 (context_p, SCAN_STACK_ARRAY_LITERAL);
break;
}
parser_stack_push_uint8 (context_p, SCAN_STACK_OBJECT_LITERAL);
scanner_context.mode = SCAN_MODE_PROPERTY_NAME;
continue;
}
if (type != LEXER_LITERAL || context_p->token.lit_location.type != LEXER_IDENT_LITERAL)
{
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
continue;
}
lexer_lit_location_t *literal_p = scanner_add_literal (context_p, &scanner_context);
scanner_context.mode = SCAN_MODE_POST_PRIMARY_EXPRESSION;
if (scanner_context.binding_type == SCANNER_BINDING_VAR)
{
if (!(literal_p->type & SCANNER_LITERAL_IS_VAR))
{
scanner_detect_invalid_var (context_p, &scanner_context, literal_p);
literal_p->type |= SCANNER_LITERAL_IS_VAR;
if (scanner_context.active_literal_pool_p->status_flags & SCANNER_LITERAL_POOL_IN_WITH)
{
literal_p->type |= SCANNER_LITERAL_NO_REG;
}
}
break;
}
if (scanner_context.binding_type == SCANNER_BINDING_ARROW_ARG)
{
literal_p->type |= SCANNER_LITERAL_IS_ARG | SCANNER_LITERAL_IS_ARROW_DESTRUCTURED_ARG;
if (literal_p->type & SCANNER_LITERAL_IS_USED)
{
literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
break;
}
}
else
{
scanner_detect_invalid_let (context_p, literal_p);
if (scanner_context.binding_type <= SCANNER_BINDING_CATCH)
{
JERRY_ASSERT ((scanner_context.binding_type == SCANNER_BINDING_LET)
|| (scanner_context.binding_type == SCANNER_BINDING_CATCH));
literal_p->type |= SCANNER_LITERAL_IS_LET;
}
else
{
literal_p->type |= SCANNER_LITERAL_IS_CONST;
if (scanner_context.binding_type == SCANNER_BINDING_ARG)
{
literal_p->type |= SCANNER_LITERAL_IS_ARG;
if (literal_p->type & SCANNER_LITERAL_IS_USED)
{
literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
break;
}
}
}
if (literal_p->type & SCANNER_LITERAL_IS_USED)
{
literal_p->type |= SCANNER_LITERAL_EARLY_CREATE;
break;
}
}
scanner_binding_item_t *binding_item_p;
binding_item_p = (scanner_binding_item_t *) scanner_malloc (context_p, sizeof (scanner_binding_item_t));
binding_item_p->next_p = scanner_context.active_binding_list_p->items_p;
binding_item_p->literal_p = literal_p;
scanner_context.active_binding_list_p->items_p = binding_item_p;
lexer_next_token (context_p);
if (context_p->token.type != LEXER_ASSIGN)
{
continue;
}
scanner_binding_literal_t binding_literal;
binding_literal.literal_p = literal_p;
parser_stack_push (context_p, &binding_literal, sizeof (scanner_binding_literal_t));
parser_stack_push_uint8 (context_p, SCAN_STACK_BINDING_INIT);
scanner_context.mode = SCAN_MODE_PRIMARY_EXPRESSION;
break;
}
#endif /* ENABLED (JERRY_ES2015) */
}
lexer_next_token (context_p);
}
scan_completed:
if (context_p->stack_top_uint8 != SCAN_STACK_SCRIPT
&& context_p->stack_top_uint8 != SCAN_STACK_SCRIPT_FUNCTION)
{
scanner_raise_error (context_p);
}
scanner_pop_literal_pool (context_p, &scanner_context);
#if ENABLED (JERRY_ES2015)
JERRY_ASSERT (scanner_context.active_binding_list_p == NULL);
#endif /* ENABLED (JERRY_ES2015) */
JERRY_ASSERT (scanner_context.active_literal_pool_p == NULL);
#ifndef JERRY_NDEBUG
scanner_context.context_status_flags |= PARSER_SCANNING_SUCCESSFUL;
#endif /* !JERRY_NDEBUG */
}
PARSER_CATCH
{
/* Ignore the errors thrown by the lexer. */
if (context_p->error != PARSER_ERR_OUT_OF_MEMORY)
{
context_p->error = PARSER_ERR_NO_ERROR;
}
#if ENABLED (JERRY_ES2015)
while (scanner_context.active_binding_list_p != NULL)
{
scanner_pop_binding_list (&scanner_context);
}
#endif /* ENABLED (JERRY_ES2015) */
/* The following code may allocate memory, so it is enclosed in a try/catch. */
PARSER_TRY (context_p->try_buffer)
{
#if ENABLED (JERRY_ES2015)
if (scanner_context.status_flags & SCANNER_CONTEXT_THROW_ERR_ASYNC_FUNCTION)
{
JERRY_ASSERT (scanner_context.async_source_p != NULL);
scanner_info_t *info_p;
info_p = scanner_insert_info (context_p, scanner_context.async_source_p, sizeof (scanner_info_t));
info_p->type = SCANNER_TYPE_ERR_ASYNC_FUNCTION;
}
#endif /* ENABLED (JERRY_ES2015) */
while (scanner_context.active_literal_pool_p != NULL)
{
scanner_pop_literal_pool (context_p, &scanner_context);
}
}
PARSER_CATCH
{
JERRY_ASSERT (context_p->error == PARSER_ERR_NO_ERROR);
while (scanner_context.active_literal_pool_p != NULL)
{
scanner_literal_pool_t *literal_pool_p = scanner_context.active_literal_pool_p;
scanner_context.active_literal_pool_p = literal_pool_p->prev_p;
parser_list_free (&literal_pool_p->literal_pool);
scanner_free (literal_pool_p, sizeof (scanner_literal_pool_t));
}
}
PARSER_TRY_END
#if ENABLED (JERRY_ES2015)
context_p->status_flags &= (uint32_t) ~PARSER_IS_GENERATOR_FUNCTION;
#endif /* ENABLED (JERRY_ES2015) */
}
PARSER_TRY_END
context_p->status_flags = scanner_context.context_status_flags;
scanner_reverse_info_list (context_p);
#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE)
if (context_p->is_show_opcodes)
{
scanner_info_t *info_p = context_p->next_scanner_info_p;
const uint8_t *source_start_p = (arg_list_p == NULL) ? source_p : arg_list_p;
while (info_p->type != SCANNER_TYPE_END)
{
const char *name_p = NULL;
bool print_location = false;
switch (info_p->type)
{
case SCANNER_TYPE_END_ARGUMENTS:
{
JERRY_DEBUG_MSG (" END_ARGUMENTS\n");
source_start_p = source_p;
break;
}
case SCANNER_TYPE_FUNCTION:
case SCANNER_TYPE_BLOCK:
{
const uint8_t *prev_source_p = info_p->source_p - 1;
const uint8_t *data_p;
if (info_p->type == SCANNER_TYPE_FUNCTION)
{
data_p = (const uint8_t *) (info_p + 1);
JERRY_DEBUG_MSG (" FUNCTION: flags: 0x%x declarations: %d",
(int) info_p->u8_arg,
(int) info_p->u16_arg);
}
else
{
data_p = (const uint8_t *) (info_p + 1);
JERRY_DEBUG_MSG (" BLOCK:");
}
JERRY_DEBUG_MSG (" source:%d\n", (int) (info_p->source_p - source_start_p));
while (data_p[0] != SCANNER_STREAM_TYPE_END)
{
switch (data_p[0] & SCANNER_STREAM_TYPE_MASK)
{
case SCANNER_STREAM_TYPE_VAR:
{
JERRY_DEBUG_MSG (" VAR ");
break;
}
#if ENABLED (JERRY_ES2015)
case SCANNER_STREAM_TYPE_LET:
{
JERRY_DEBUG_MSG (" LET ");
break;
}
case SCANNER_STREAM_TYPE_CONST:
{
JERRY_DEBUG_MSG (" CONST ");
break;
}
case SCANNER_STREAM_TYPE_LOCAL:
{
JERRY_DEBUG_MSG (" LOCAL ");
break;
}
#endif /* ENABLED (JERRY_ES2015) */
#if ENABLED (JERRY_ES2015_MODULE_SYSTEM)
case SCANNER_STREAM_TYPE_IMPORT:
{
JERRY_DEBUG_MSG (" IMPORT ");
break;
}
#endif /* ENABLED (JERRY_ES2015_MODULE_SYSTEM) */
case SCANNER_STREAM_TYPE_ARG:
{
JERRY_DEBUG_MSG (" ARG ");
break;
}
#if ENABLED (JERRY_ES2015)
case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG:
{
JERRY_DEBUG_MSG (" DESTRUCTURED_ARG ");
break;
}
#endif /* ENABLED (JERRY_ES2015) */
case SCANNER_STREAM_TYPE_ARG_FUNC:
{
JERRY_DEBUG_MSG (" ARG_FUNC ");
break;
}
#if ENABLED (JERRY_ES2015)
case SCANNER_STREAM_TYPE_DESTRUCTURED_ARG_FUNC:
{
JERRY_DEBUG_MSG (" DESTRUCTURED_ARG_FUNC ");
break;
}
#endif /* ENABLED (JERRY_ES2015) */
case SCANNER_STREAM_TYPE_FUNC:
{
JERRY_DEBUG_MSG (" FUNC ");
break;
}
default:
{
JERRY_ASSERT ((data_p[0] & SCANNER_STREAM_TYPE_MASK) == SCANNER_STREAM_TYPE_HOLE);
JERRY_DEBUG_MSG (" HOLE\n");
data_p++;
continue;
}
}
size_t length;
if (!(data_p[0] & SCANNER_STREAM_UINT16_DIFF))
{
if (data_p[2] != 0)
{
prev_source_p += data_p[2];
length = 2 + 1;
}
else
{
memcpy (&prev_source_p, data_p + 2 + 1, sizeof (const uint8_t *));
length = 2 + 1 + sizeof (const uint8_t *);
}
}
else
{
int32_t diff = ((int32_t) data_p[2]) | ((int32_t) data_p[3]) << 8;
if (diff <= UINT8_MAX)
{
diff = -diff;
}
prev_source_p += diff;
length = 2 + 2;
}
#if ENABLED (JERRY_ES2015)
if (data_p[0] & SCANNER_STREAM_EARLY_CREATE)
{
JERRY_ASSERT (data_p[0] & SCANNER_STREAM_NO_REG);
JERRY_DEBUG_MSG ("*");
}
#endif /* ENABLED (JERRY_ES2015) */
if (data_p[0] & SCANNER_STREAM_NO_REG)
{
JERRY_DEBUG_MSG ("* ");
}
JERRY_DEBUG_MSG ("'%.*s'\n", data_p[1], (char *) prev_source_p);
prev_source_p += data_p[1];
data_p += length;
}
break;
}
case SCANNER_TYPE_WHILE:
{
name_p = "WHILE";
print_location = true;
break;
}
case SCANNER_TYPE_FOR:
{
scanner_for_info_t *for_info_p = (scanner_for_info_t *) info_p;
JERRY_DEBUG_MSG (" FOR: source:%d expression:%d[%d:%d] end:%d[%d:%d]\n",
(int) (for_info_p->info.source_p - source_start_p),
(int) (for_info_p->expression_location.source_p - source_start_p),
(int) for_info_p->expression_location.line,
(int) for_info_p->expression_location.column,
(int) (for_info_p->end_location.source_p - source_start_p),
(int) for_info_p->end_location.line,
(int) for_info_p->end_location.column);
break;
}
case SCANNER_TYPE_FOR_IN:
{
name_p = "FOR-IN";
print_location = true;
break;
}
#if ENABLED (JERRY_ES2015)
case SCANNER_TYPE_FOR_OF:
{
name_p = "FOR-OF";
print_location = true;
break;
}
#endif /* ENABLED (JERRY_ES2015) */
case SCANNER_TYPE_SWITCH:
{
JERRY_DEBUG_MSG (" SWITCH: source:%d\n",
(int) (info_p->source_p - source_start_p));
scanner_case_info_t *current_case_p = ((scanner_switch_info_t *) info_p)->case_p;
while (current_case_p != NULL)
{
JERRY_DEBUG_MSG (" CASE: location:%d[%d:%d]\n",
(int) (current_case_p->location.source_p - source_start_p),
(int) current_case_p->location.line,
(int) current_case_p->location.column);
current_case_p = current_case_p->next_p;
}
break;
}
case SCANNER_TYPE_CASE:
{
name_p = "CASE";
print_location = true;
break;
}
#if ENABLED (JERRY_ES2015)
case SCANNER_TYPE_INITIALIZER:
{
name_p = "INITIALIZER";
print_location = true;
break;
}
case SCANNER_TYPE_CLASS_CONSTRUCTOR:
{
JERRY_DEBUG_MSG (" CLASS-CONSTRUCTOR: source:%d\n",
(int) (info_p->source_p - source_start_p));
print_location = false;
break;
}
case SCANNER_TYPE_LET_EXPRESSION:
{
JERRY_DEBUG_MSG (" LET_EXPRESSION: source:%d\n",
(int) (info_p->source_p - source_start_p));
break;
}
case SCANNER_TYPE_ERR_REDECLARED:
{
JERRY_DEBUG_MSG (" ERR_REDECLARED: source:%d\n",
(int) (info_p->source_p - source_start_p));
break;
}
case SCANNER_TYPE_ERR_ASYNC_FUNCTION:
{
JERRY_DEBUG_MSG (" ERR_ASYNC_FUNCTION: source:%d\n",
(int) (info_p->source_p - source_start_p));
break;
}
#endif /* ENABLED (JERRY_ES2015) */
}
if (print_location)
{
scanner_location_info_t *location_info_p = (scanner_location_info_t *) info_p;
JERRY_DEBUG_MSG (" %s: source:%d location:%d[%d:%d]\n",
name_p,
(int) (location_info_p->info.source_p - source_start_p),
(int) (location_info_p->location.source_p - source_start_p),
(int) location_info_p->location.line,
(int) location_info_p->location.column);
}
info_p = info_p->next_p;
}
JERRY_DEBUG_MSG ("\n--- Scanning end ---\n\n");
}
#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */
parser_stack_free (context_p);
} /* scanner_scan_all */
/**
* @}
* @}
* @}
*/
#endif /* ENABLED (JERRY_PARSER) */
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_4032_0 |
crossvul-cpp_data_bad_828_0 | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* memcached - memory caching daemon
*
* http://www.memcached.org/
*
* Copyright 2003 Danga Interactive, Inc. All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*
* Authors:
* Anatoly Vorobey <mellon@pobox.com>
* Brad Fitzpatrick <brad@danga.com>
*/
#include "memcached.h"
#ifdef EXTSTORE
#include "storage.h"
#endif
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <ctype.h>
#include <stdarg.h>
/* some POSIX systems need the following definition
* to get mlockall flags out of sys/mman.h. */
#ifndef _P1003_1B_VISIBLE
#define _P1003_1B_VISIBLE
#endif
/* need this to get IOV_MAX on some platforms. */
#ifndef __need_IOV_MAX
#define __need_IOV_MAX
#endif
#include <pwd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <limits.h>
#include <sysexits.h>
#include <stddef.h>
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#endif
#ifdef TLS
#include "tls.h"
#endif
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
/* FreeBSD 4.x doesn't have IOV_MAX exposed. */
#ifndef IOV_MAX
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__)
# define IOV_MAX 1024
/* GNU/Hurd don't set MAXPATHLEN
* http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */
#ifndef MAXPATHLEN
#define MAXPATHLEN 4096
#endif
#endif
#endif
/*
* forward declarations
*/
static void drive_machine(conn *c);
static int new_socket(struct addrinfo *ai);
static int try_read_command(conn *c);
static ssize_t tcp_read(conn *arg, void *buf, size_t count);
static ssize_t tcp_sendmsg(conn *arg, struct msghdr *msg, int flags);
static ssize_t tcp_write(conn *arg, void *buf, size_t count);
enum try_read_result {
READ_DATA_RECEIVED,
READ_NO_DATA_RECEIVED,
READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */
READ_MEMORY_ERROR /** failed to allocate more memory */
};
static enum try_read_result try_read_network(conn *c);
static enum try_read_result try_read_udp(conn *c);
static void conn_set_state(conn *c, enum conn_states state);
static int start_conn_timeout_thread();
/* stats */
static void stats_init(void);
static void server_stats(ADD_STAT add_stats, conn *c);
static void process_stat_settings(ADD_STAT add_stats, void *c);
static void conn_to_str(const conn *c, char *buf);
/* defaults */
static void settings_init(void);
/* event handling, network IO */
static void event_handler(const int fd, const short which, void *arg);
static void conn_close(conn *c);
static void conn_init(void);
static bool update_event(conn *c, const int new_flags);
static void complete_nread(conn *c);
static void process_command(conn *c, char *command);
static void write_and_free(conn *c, char *buf, int bytes);
static int ensure_iov_space(conn *c);
static int add_iov(conn *c, const void *buf, int len);
static int add_chunked_item_iovs(conn *c, item *it, int len);
static int add_msghdr(conn *c);
static void write_bin_error(conn *c, protocol_binary_response_status err,
const char *errstr, int swallow);
static void write_bin_miss_response(conn *c, char *key, size_t nkey);
#ifdef EXTSTORE
static void _get_extstore_cb(void *e, obj_io *io, int ret);
static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt);
#endif
static void conn_free(conn *c);
/** exported globals **/
struct stats stats;
struct stats_state stats_state;
struct settings settings;
time_t process_started; /* when the process was started */
conn **conns;
struct slab_rebalance slab_rebal;
volatile int slab_rebalance_signal;
#ifdef EXTSTORE
/* hoping this is temporary; I'd prefer to cut globals, but will complete this
* battle another day.
*/
void *ext_storage;
#endif
/** file scope variables **/
static conn *listen_conn = NULL;
static int max_fds;
static struct event_base *main_base;
enum transmit_result {
TRANSMIT_COMPLETE, /** All done writing. */
TRANSMIT_INCOMPLETE, /** More data remaining to write. */
TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */
TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */
};
/* Default methods to read from/ write to a socket */
ssize_t tcp_read(conn *c, void *buf, size_t count) {
assert (c != NULL);
return read(c->sfd, buf, count);
}
ssize_t tcp_sendmsg(conn *c, struct msghdr *msg, int flags) {
assert (c != NULL);
return sendmsg(c->sfd, msg, flags);
}
ssize_t tcp_write(conn *c, void *buf, size_t count) {
assert (c != NULL);
return write(c->sfd, buf, count);
}
static enum transmit_result transmit(conn *c);
/* This reduces the latency without adding lots of extra wiring to be able to
* notify the listener thread of when to listen again.
* Also, the clock timer could be broken out into its own thread and we
* can block the listener via a condition.
*/
static volatile bool allow_new_conns = true;
static struct event maxconnsevent;
static void maxconns_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 0, .tv_usec = 10000};
if (fd == -42 || allow_new_conns == false) {
/* reschedule in 10ms if we need to keep polling */
evtimer_set(&maxconnsevent, maxconns_handler, 0);
event_base_set(main_base, &maxconnsevent);
evtimer_add(&maxconnsevent, &t);
} else {
evtimer_del(&maxconnsevent);
accept_new_conns(true);
}
}
#define REALTIME_MAXDELTA 60*60*24*30
/*
* given time value that's either unix time or delta from current unix time, return
* unix time. Use the fact that delta can't exceed one month (and real time value can't
* be that low).
*/
static rel_time_t realtime(const time_t exptime) {
/* no. of seconds in 30 days - largest possible delta exptime */
if (exptime == 0) return 0; /* 0 means never expire */
if (exptime > REALTIME_MAXDELTA) {
/* if item expiration is at/before the server started, give it an
expiration time of 1 second after the server started.
(because 0 means don't expire). without this, we'd
underflow and wrap around to some large value way in the
future, effectively making items expiring in the past
really expiring never */
if (exptime <= process_started)
return (rel_time_t)1;
return (rel_time_t)(exptime - process_started);
} else {
return (rel_time_t)(exptime + current_time);
}
}
static void stats_init(void) {
memset(&stats, 0, sizeof(struct stats));
memset(&stats_state, 0, sizeof(struct stats_state));
stats_state.accepting_conns = true; /* assuming we start in this state. */
/* make the time we started always be 2 seconds before we really
did, so time(0) - time.started is never zero. if so, things
like 'settings.oldest_live' which act as booleans as well as
values are now false in boolean context... */
process_started = time(0) - ITEM_UPDATE_INTERVAL - 2;
stats_prefix_init();
}
static void stats_reset(void) {
STATS_LOCK();
memset(&stats, 0, sizeof(struct stats));
stats_prefix_clear();
STATS_UNLOCK();
threadlocal_stats_reset();
item_stats_reset();
}
static void settings_init(void) {
settings.use_cas = true;
settings.access = 0700;
settings.port = 11211;
settings.udpport = 0;
#ifdef TLS
settings.ssl_enabled = false;
settings.ssl_ctx = NULL;
settings.ssl_chain_cert = NULL;
settings.ssl_key = NULL;
settings.ssl_verify_mode = SSL_VERIFY_NONE;
settings.ssl_keyformat = SSL_FILETYPE_PEM;
settings.ssl_ciphers = NULL;
settings.ssl_ca_cert = NULL;
settings.ssl_last_cert_refresh_time = current_time;
settings.ssl_wbuf_size = 16 * 1024; // default is 16KB (SSL max frame size is 17KB)
#endif
/* By default this string should be NULL for getaddrinfo() */
settings.inter = NULL;
settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */
settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */
settings.verbose = 0;
settings.oldest_live = 0;
settings.oldest_cas = 0; /* supplements accuracy of oldest_live */
settings.evict_to_free = 1; /* push old items out of cache when memory runs out */
settings.socketpath = NULL; /* by default, not using a unix socket */
settings.factor = 1.25;
settings.chunk_size = 48; /* space for a modest key and value */
settings.num_threads = 4; /* N workers */
settings.num_threads_per_udp = 0;
settings.prefix_delimiter = ':';
settings.detail_enabled = 0;
settings.reqs_per_event = 20;
settings.backlog = 1024;
settings.binding_protocol = negotiating_prot;
settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */
settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */
settings.slab_chunk_size_max = settings.slab_page_size / 2;
settings.sasl = false;
settings.maxconns_fast = true;
settings.lru_crawler = false;
settings.lru_crawler_sleep = 100;
settings.lru_crawler_tocrawl = 0;
settings.lru_maintainer_thread = false;
settings.lru_segmented = true;
settings.hot_lru_pct = 20;
settings.warm_lru_pct = 40;
settings.hot_max_factor = 0.2;
settings.warm_max_factor = 2.0;
settings.inline_ascii_response = false;
settings.temp_lru = false;
settings.temporary_ttl = 61;
settings.idle_timeout = 0; /* disabled */
settings.hashpower_init = 0;
settings.slab_reassign = true;
settings.slab_automove = 1;
settings.slab_automove_ratio = 0.8;
settings.slab_automove_window = 30;
settings.shutdown_command = false;
settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT;
settings.flush_enabled = true;
settings.dump_enabled = true;
settings.crawls_persleep = 1000;
settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE;
settings.logger_buf_size = LOGGER_BUF_SIZE;
settings.drop_privileges = false;
#ifdef MEMCACHED_DEBUG
settings.relaxed_privileges = false;
#endif
}
/*
* Adds a message header to a connection.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int add_msghdr(conn *c)
{
struct msghdr *msg;
assert(c != NULL);
if (c->msgsize == c->msgused) {
msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr));
if (! msg) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->msglist = msg;
c->msgsize *= 2;
}
msg = c->msglist + c->msgused;
/* this wipes msg_iovlen, msg_control, msg_controllen, and
msg_flags, the last 3 of which aren't defined on solaris: */
memset(msg, 0, sizeof(struct msghdr));
msg->msg_iov = &c->iov[c->iovused];
if (IS_UDP(c->transport) && c->request_addr_size > 0) {
msg->msg_name = &c->request_addr;
msg->msg_namelen = c->request_addr_size;
}
c->msgbytes = 0;
c->msgused++;
if (IS_UDP(c->transport)) {
/* Leave room for the UDP header, which we'll fill in later. */
return add_iov(c, NULL, UDP_HEADER_SIZE);
}
return 0;
}
extern pthread_mutex_t conn_lock;
/* Connection timeout thread bits */
static pthread_t conn_timeout_tid;
#define CONNS_PER_SLICE 100
#define TIMEOUT_MSG_SIZE (1 + sizeof(int))
static void *conn_timeout_thread(void *arg) {
int i;
conn *c;
char buf[TIMEOUT_MSG_SIZE];
rel_time_t oldest_last_cmd;
int sleep_time;
useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE);
while(1) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread at top of connection list\n");
oldest_last_cmd = current_time;
for (i = 0; i < max_fds; i++) {
if ((i % CONNS_PER_SLICE) == 0) {
if (settings.verbose > 2)
fprintf(stderr, "idle timeout thread sleeping for %ulus\n",
(unsigned int)timeslice);
usleep(timeslice);
}
if (!conns[i])
continue;
c = conns[i];
if (!IS_TCP(c->transport))
continue;
if (c->state != conn_new_cmd && c->state != conn_read)
continue;
if ((current_time - c->last_cmd_time) > settings.idle_timeout) {
buf[0] = 't';
memcpy(&buf[1], &i, sizeof(int));
if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE)
!= TIMEOUT_MSG_SIZE)
perror("Failed to write timeout to notify pipe");
} else {
if (c->last_cmd_time < oldest_last_cmd)
oldest_last_cmd = c->last_cmd_time;
}
}
/* This is the soonest we could have another connection time out */
sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1;
if (sleep_time <= 0)
sleep_time = 1;
if (settings.verbose > 2)
fprintf(stderr,
"idle timeout thread finished pass, sleeping for %ds\n",
sleep_time);
usleep((useconds_t) sleep_time * 1000000);
}
return NULL;
}
static int start_conn_timeout_thread() {
int ret;
if (settings.idle_timeout == 0)
return -1;
if ((ret = pthread_create(&conn_timeout_tid, NULL,
conn_timeout_thread, NULL)) != 0) {
fprintf(stderr, "Can't create idle connection timeout thread: %s\n",
strerror(ret));
return -1;
}
return 0;
}
/*
* Initializes the connections array. We don't actually allocate connection
* structures until they're needed, so as to avoid wasting memory when the
* maximum connection count is much higher than the actual number of
* connections.
*
* This does end up wasting a few pointers' worth of memory for FDs that are
* used for things other than connections, but that's worth it in exchange for
* being able to directly index the conns array by FD.
*/
static void conn_init(void) {
/* We're unlikely to see an FD much higher than maxconns. */
int next_fd = dup(1);
int headroom = 10; /* account for extra unexpected open FDs */
struct rlimit rl;
max_fds = settings.maxconns + headroom + next_fd;
/* But if possible, get the actual highest FD we can possibly ever see. */
if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
max_fds = rl.rlim_max;
} else {
fprintf(stderr, "Failed to query maximum file descriptor; "
"falling back to maxconns\n");
}
close(next_fd);
if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) {
fprintf(stderr, "Failed to allocate connection structures\n");
/* This is unrecoverable so bail out early. */
exit(1);
}
}
static const char *prot_text(enum protocol prot) {
char *rv = "unknown";
switch(prot) {
case ascii_prot:
rv = "ascii";
break;
case binary_prot:
rv = "binary";
break;
case negotiating_prot:
rv = "auto-negotiate";
break;
}
return rv;
}
void conn_close_idle(conn *c) {
if (settings.idle_timeout > 0 &&
(current_time - c->last_cmd_time) > settings.idle_timeout) {
if (c->state != conn_new_cmd && c->state != conn_read) {
if (settings.verbose > 1)
fprintf(stderr,
"fd %d wants to timeout, but isn't in read state", c->sfd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, "Closing idle fd %d\n", c->sfd);
c->thread->stats.idle_kicks++;
conn_set_state(c, conn_closing);
drive_machine(c);
}
}
/* bring conn back from a sidethread. could have had its event base moved. */
void conn_worker_readd(conn *c) {
c->ev_flags = EV_READ | EV_PERSIST;
event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c);
event_base_set(c->thread->base, &c->event);
c->state = conn_new_cmd;
// TODO: call conn_cleanup/fail/etc
if (event_add(&c->event, 0) == -1) {
perror("event_add");
}
#ifdef EXTSTORE
// If we had IO objects, process
if (c->io_wraplist) {
//assert(c->io_wrapleft == 0); // assert no more to process
conn_set_state(c, conn_mwrite);
drive_machine(c);
}
#endif
}
conn *conn_new(const int sfd, enum conn_states init_state,
const int event_flags,
const int read_buffer_size, enum network_transport transport,
struct event_base *base, void *ssl) {
conn *c;
assert(sfd >= 0 && sfd < max_fds);
c = conns[sfd];
if (NULL == c) {
if (!(c = (conn *)calloc(1, sizeof(conn)))) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate connection object\n");
return NULL;
}
MEMCACHED_CONN_CREATE(c);
c->read = NULL;
c->sendmsg = NULL;
c->write = NULL;
c->rbuf = c->wbuf = 0;
c->ilist = 0;
c->suffixlist = 0;
c->iov = 0;
c->msglist = 0;
c->hdrbuf = 0;
c->rsize = read_buffer_size;
c->wsize = DATA_BUFFER_SIZE;
c->isize = ITEM_LIST_INITIAL;
c->suffixsize = SUFFIX_LIST_INITIAL;
c->iovsize = IOV_LIST_INITIAL;
c->msgsize = MSG_LIST_INITIAL;
c->hdrsize = 0;
c->rbuf = (char *)malloc((size_t)c->rsize);
c->wbuf = (char *)malloc((size_t)c->wsize);
c->ilist = (item **)malloc(sizeof(item *) * c->isize);
c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize);
c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize);
c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize);
if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 ||
c->msglist == 0 || c->suffixlist == 0) {
conn_free(c);
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
fprintf(stderr, "Failed to allocate buffers for connection\n");
return NULL;
}
STATS_LOCK();
stats_state.conn_structs++;
STATS_UNLOCK();
c->sfd = sfd;
conns[sfd] = c;
}
c->transport = transport;
c->protocol = settings.binding_protocol;
/* unix socket mode doesn't need this, so zeroed out. but why
* is this done for every command? presumably for UDP
* mode. */
if (!settings.socketpath) {
c->request_addr_size = sizeof(c->request_addr);
} else {
c->request_addr_size = 0;
}
if (transport == tcp_transport && init_state == conn_new_cmd) {
if (getpeername(sfd, (struct sockaddr *) &c->request_addr,
&c->request_addr_size)) {
perror("getpeername");
memset(&c->request_addr, 0, sizeof(c->request_addr));
}
}
if (settings.verbose > 1) {
if (init_state == conn_listening) {
fprintf(stderr, "<%d server listening (%s)\n", sfd,
prot_text(c->protocol));
} else if (IS_UDP(transport)) {
fprintf(stderr, "<%d server listening (udp)\n", sfd);
} else if (c->protocol == negotiating_prot) {
fprintf(stderr, "<%d new auto-negotiating client connection\n",
sfd);
} else if (c->protocol == ascii_prot) {
fprintf(stderr, "<%d new ascii client connection.\n", sfd);
} else if (c->protocol == binary_prot) {
fprintf(stderr, "<%d new binary client connection.\n", sfd);
} else {
fprintf(stderr, "<%d new unknown (%d) client connection\n",
sfd, c->protocol);
assert(false);
}
}
#ifdef TLS
c->ssl = NULL;
c->ssl_wbuf = NULL;
c->ssl_enabled = false;
#endif
c->state = init_state;
c->rlbytes = 0;
c->cmd = -1;
c->rbytes = c->wbytes = 0;
c->wcurr = c->wbuf;
c->rcurr = c->rbuf;
c->ritem = 0;
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
c->ileft = 0;
c->suffixleft = 0;
c->iovused = 0;
c->msgcurr = 0;
c->msgused = 0;
c->sasl_started = false;
c->authenticated = false;
c->last_cmd_time = current_time; /* initialize for idle kicker */
#ifdef EXTSTORE
c->io_wraplist = NULL;
c->io_wrapleft = 0;
#endif
c->write_and_go = init_state;
c->write_and_free = 0;
c->item = 0;
c->noreply = false;
#ifdef TLS
if (ssl) {
c->ssl = (SSL*)ssl;
c->read = ssl_read;
c->sendmsg = ssl_sendmsg;
c->write = ssl_write;
c->ssl_enabled = true;
SSL_set_info_callback(c->ssl, ssl_callback);
} else
#else
// This must be NULL if TLS is not enabled.
assert(ssl == NULL);
#endif
{
c->read = tcp_read;
c->sendmsg = tcp_sendmsg;
c->write = tcp_write;
}
event_set(&c->event, sfd, event_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = event_flags;
if (event_add(&c->event, 0) == -1) {
perror("event_add");
return NULL;
}
STATS_LOCK();
stats_state.curr_conns++;
stats.total_conns++;
STATS_UNLOCK();
MEMCACHED_CONN_ALLOCATE(c->sfd);
return c;
}
#ifdef EXTSTORE
static void recache_or_free(conn *c, io_wrap *wrap) {
item *it;
it = (item *)wrap->io.buf;
bool do_free = true;
if (wrap->active) {
// If request never dispatched, free the read buffer but leave the
// item header alone.
do_free = false;
size_t ntotal = ITEM_ntotal(wrap->hdr_it);
slabs_free(it, ntotal, slabs_clsid(ntotal));
c->io_wrapleft--;
assert(c->io_wrapleft >= 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_aborted_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
} else if (wrap->miss) {
// If request was ultimately a miss, unlink the header.
do_free = false;
size_t ntotal = ITEM_ntotal(wrap->hdr_it);
item_unlink(wrap->hdr_it);
slabs_free(it, ntotal, slabs_clsid(ntotal));
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.miss_from_extstore++;
if (wrap->badcrc)
c->thread->stats.badcrc_from_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
} else if (settings.ext_recache_rate) {
// hashvalue is cuddled during store
uint32_t hv = (uint32_t)it->time;
// opt to throw away rather than wait on a lock.
void *hold_lock = item_trylock(hv);
if (hold_lock != NULL) {
item *h_it = wrap->hdr_it;
uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE;
// Item must be recently hit at least twice to recache.
if (((h_it->it_flags & flags) == flags) &&
h_it->time > current_time - ITEM_UPDATE_INTERVAL &&
c->recache_counter++ % settings.ext_recache_rate == 0) {
do_free = false;
// In case it's been updated.
it->exptime = h_it->exptime;
it->it_flags &= ~ITEM_LINKED;
it->refcount = 0;
it->h_next = NULL; // might not be necessary.
STORAGE_delete(c->thread->storage, h_it);
item_replace(h_it, it, hv);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.recache_from_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
if (hold_lock)
item_trylock_unlock(hold_lock);
}
if (do_free)
slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it));
wrap->io.buf = NULL; // sanity.
wrap->io.next = NULL;
wrap->next = NULL;
wrap->active = false;
// TODO: reuse lock and/or hv.
item_remove(wrap->hdr_it);
}
#endif
static void conn_release_items(conn *c) {
assert(c != NULL);
if (c->item) {
item_remove(c->item);
c->item = 0;
}
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
if (c->suffixleft != 0) {
for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) {
do_cache_free(c->thread->suffix_cache, *(c->suffixcurr));
}
}
#ifdef EXTSTORE
if (c->io_wraplist) {
io_wrap *tmp = c->io_wraplist;
while (tmp) {
io_wrap *next = tmp->next;
recache_or_free(c, tmp);
do_cache_free(c->thread->io_cache, tmp); // lockless
tmp = next;
}
c->io_wraplist = NULL;
}
#endif
c->icurr = c->ilist;
c->suffixcurr = c->suffixlist;
}
static void conn_cleanup(conn *c) {
assert(c != NULL);
conn_release_items(c);
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
if (c->sasl_conn) {
assert(settings.sasl);
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
}
if (IS_UDP(c->transport)) {
conn_set_state(c, conn_read);
}
}
/*
* Frees a connection.
*/
void conn_free(conn *c) {
if (c) {
assert(c != NULL);
assert(c->sfd >= 0 && c->sfd < max_fds);
MEMCACHED_CONN_DESTROY(c);
conns[c->sfd] = NULL;
if (c->hdrbuf)
free(c->hdrbuf);
if (c->msglist)
free(c->msglist);
if (c->rbuf)
free(c->rbuf);
if (c->wbuf)
free(c->wbuf);
if (c->ilist)
free(c->ilist);
if (c->suffixlist)
free(c->suffixlist);
if (c->iov)
free(c->iov);
#ifdef TLS
if (c->ssl_wbuf)
c->ssl_wbuf = NULL;
#endif
free(c);
}
}
static void conn_close(conn *c) {
assert(c != NULL);
/* delete the event, the socket and the conn */
event_del(&c->event);
if (settings.verbose > 1)
fprintf(stderr, "<%d connection closed.\n", c->sfd);
conn_cleanup(c);
MEMCACHED_CONN_RELEASE(c->sfd);
conn_set_state(c, conn_closed);
#ifdef TLS
if (c->ssl) {
SSL_shutdown(c->ssl);
SSL_free(c->ssl);
}
#endif
close(c->sfd);
pthread_mutex_lock(&conn_lock);
allow_new_conns = true;
pthread_mutex_unlock(&conn_lock);
STATS_LOCK();
stats_state.curr_conns--;
STATS_UNLOCK();
return;
}
/*
* Shrinks a connection's buffers if they're too big. This prevents
* periodic large "get" requests from permanently chewing lots of server
* memory.
*
* This should only be called in between requests since it can wipe output
* buffers!
*/
static void conn_shrink(conn *c) {
assert(c != NULL);
if (IS_UDP(c->transport))
return;
if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) {
char *newbuf;
if (c->rcurr != c->rbuf)
memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
if (newbuf) {
c->rbuf = newbuf;
c->rsize = DATA_BUFFER_SIZE;
}
/* TODO check other branch... */
c->rcurr = c->rbuf;
}
if (c->isize > ITEM_LIST_HIGHWAT) {
item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0]));
if (newbuf) {
c->ilist = newbuf;
c->isize = ITEM_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->msgsize > MSG_LIST_HIGHWAT) {
struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0]));
if (newbuf) {
c->msglist = newbuf;
c->msgsize = MSG_LIST_INITIAL;
}
/* TODO check error condition? */
}
if (c->iovsize > IOV_LIST_HIGHWAT) {
struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0]));
if (newbuf) {
c->iov = newbuf;
c->iovsize = IOV_LIST_INITIAL;
}
/* TODO check return value */
}
}
/**
* Convert a state name to a human readable form.
*/
static const char *state_text(enum conn_states state) {
const char* const statenames[] = { "conn_listening",
"conn_new_cmd",
"conn_waiting",
"conn_read",
"conn_parse_cmd",
"conn_write",
"conn_nread",
"conn_swallow",
"conn_closing",
"conn_mwrite",
"conn_closed",
"conn_watch" };
return statenames[state];
}
/*
* Sets a connection's current state in the state machine. Any special
* processing that needs to happen on certain state transitions can
* happen here.
*/
static void conn_set_state(conn *c, enum conn_states state) {
assert(c != NULL);
assert(state >= conn_listening && state < conn_max_state);
if (state != c->state) {
if (settings.verbose > 2) {
fprintf(stderr, "%d: going from %s to %s\n",
c->sfd, state_text(c->state),
state_text(state));
}
if (state == conn_write || state == conn_mwrite) {
MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes);
}
c->state = state;
}
}
/*
* Ensures that there is room for another struct iovec in a connection's
* iov list.
*
* Returns 0 on success, -1 on out-of-memory.
*/
static int ensure_iov_space(conn *c) {
assert(c != NULL);
if (c->iovused >= c->iovsize) {
int i, iovnum;
struct iovec *new_iov = (struct iovec *)realloc(c->iov,
(c->iovsize * 2) * sizeof(struct iovec));
if (! new_iov) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->iov = new_iov;
c->iovsize *= 2;
/* Point all the msghdr structures at the new list. */
for (i = 0, iovnum = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov = &c->iov[iovnum];
iovnum += c->msglist[i].msg_iovlen;
}
}
return 0;
}
/*
* Adds data to the list of pending data that will be written out to a
* connection.
*
* Returns 0 on success, -1 on out-of-memory.
* Note: This is a hot path for at least ASCII protocol. While there is
* redundant code in splitting TCP/UDP handling, any reduction in steps has a
* large impact for TCP connections.
*/
static int add_iov(conn *c, const void *buf, int len) {
struct msghdr *m;
int leftover;
assert(c != NULL);
if (IS_UDP(c->transport)) {
do {
m = &c->msglist[c->msgused - 1];
/*
* Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes.
*/
/* We may need to start a new msghdr if this one is full. */
if (m->msg_iovlen == IOV_MAX ||
(c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
/* If the fragment is too big to fit in the datagram, split it up */
if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) {
leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE;
len -= leftover;
} else {
leftover = 0;
}
m = &c->msglist[c->msgused - 1];
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
buf = ((char *)buf) + len;
len = leftover;
} while (leftover > 0);
} else {
/* Optimized path for TCP connections */
m = &c->msglist[c->msgused - 1];
if (m->msg_iovlen == IOV_MAX) {
add_msghdr(c);
m = &c->msglist[c->msgused - 1];
}
if (ensure_iov_space(c) != 0)
return -1;
m->msg_iov[m->msg_iovlen].iov_base = (void *)buf;
m->msg_iov[m->msg_iovlen].iov_len = len;
c->msgbytes += len;
c->iovused++;
m->msg_iovlen++;
}
return 0;
}
static int add_chunked_item_iovs(conn *c, item *it, int len) {
assert(it->it_flags & ITEM_CHUNKED);
item_chunk *ch = (item_chunk *) ITEM_schunk(it);
while (ch) {
int todo = (len > ch->used) ? ch->used : len;
if (add_iov(c, ch->data, todo) != 0) {
return -1;
}
ch = ch->next;
len -= todo;
}
return 0;
}
/*
* Constructs a set of UDP headers and attaches them to the outgoing messages.
*/
static int build_udp_headers(conn *c) {
int i;
unsigned char *hdr;
assert(c != NULL);
if (c->msgused > c->hdrsize) {
void *new_hdrbuf;
if (c->hdrbuf) {
new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE);
} else {
new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE);
}
if (! new_hdrbuf) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
c->hdrbuf = (unsigned char *)new_hdrbuf;
c->hdrsize = c->msgused * 2;
}
hdr = c->hdrbuf;
for (i = 0; i < c->msgused; i++) {
c->msglist[i].msg_iov[0].iov_base = (void*)hdr;
c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE;
*hdr++ = c->request_id / 256;
*hdr++ = c->request_id % 256;
*hdr++ = i / 256;
*hdr++ = i % 256;
*hdr++ = c->msgused / 256;
*hdr++ = c->msgused % 256;
*hdr++ = 0;
*hdr++ = 0;
assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE);
}
return 0;
}
static void out_string(conn *c, const char *str) {
size_t len;
assert(c != NULL);
if (c->noreply) {
if (settings.verbose > 1)
fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str);
c->noreply = false;
conn_set_state(c, conn_new_cmd);
return;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d %s\n", c->sfd, str);
/* Nuke a partial output... */
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
add_msghdr(c);
len = strlen(str);
if ((len + 2) > c->wsize) {
/* ought to be always enough. just fail for simplicity */
str = "SERVER_ERROR output line too long";
len = strlen(str);
}
memcpy(c->wbuf, str, len);
memcpy(c->wbuf + len, "\r\n", 2);
c->wbytes = len + 2;
c->wcurr = c->wbuf;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
return;
}
/*
* Outputs a protocol-specific "out of memory" error. For ASCII clients,
* this is equivalent to out_string().
*/
static void out_of_memory(conn *c, char *ascii_error) {
const static char error_prefix[] = "SERVER_ERROR ";
const static int error_prefix_len = sizeof(error_prefix) - 1;
if (c->protocol == binary_prot) {
/* Strip off the generic error prefix; it's irrelevant in binary */
if (!strncmp(ascii_error, error_prefix, error_prefix_len)) {
ascii_error += error_prefix_len;
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0);
} else {
out_string(c, ascii_error);
}
}
/*
* we get here after reading the value in set/add/replace commands. The command
* has been stored in c->cmd, and the item is ready in c->item.
*/
static void complete_nread_ascii(conn *c) {
assert(c != NULL);
item *it = c->item;
int comm = c->cmd;
enum store_item_type ret;
bool is_valid = false;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if ((it->it_flags & ITEM_CHUNKED) == 0) {
if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) {
is_valid = true;
}
} else {
char buf[2];
/* should point to the final item chunk */
item_chunk *ch = (item_chunk *) c->ritem;
assert(ch->used != 0);
/* :( We need to look at the last two bytes. This could span two
* chunks.
*/
if (ch->used > 1) {
buf[0] = ch->data[ch->used - 2];
buf[1] = ch->data[ch->used - 1];
} else {
assert(ch->prev);
assert(ch->used == 1);
buf[0] = ch->prev->data[ch->prev->used - 1];
buf[1] = ch->data[ch->used - 1];
}
if (strncmp(buf, "\r\n", 2) == 0) {
is_valid = true;
} else {
assert(1 == 0);
}
}
if (!is_valid) {
out_string(c, "CLIENT_ERROR bad data chunk");
} else {
ret = store_item(it, comm, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == 1) ? it->nbytes : -1, cas);
break;
case NREAD_CAS:
MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes,
cas);
break;
}
#endif
switch (ret) {
case STORED:
out_string(c, "STORED");
break;
case EXISTS:
out_string(c, "EXISTS");
break;
case NOT_FOUND:
out_string(c, "NOT_FOUND");
break;
case NOT_STORED:
out_string(c, "NOT_STORED");
break;
default:
out_string(c, "SERVER_ERROR Unhandled storage type.");
}
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
/**
* get a pointer to the start of the request struct for the current command
*/
static void* binary_get_request(conn *c) {
char *ret = c->rcurr;
ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen +
c->binary_header.request.extlen);
assert(ret >= c->rbuf);
return ret;
}
/**
* get a pointer to the key in this request
*/
static char* binary_get_key(conn *c) {
return c->rcurr - (c->binary_header.request.keylen);
}
static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) {
protocol_binary_response_header* header;
assert(c);
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
/* This should never run out of memory because iov and msg lists
* have minimum sizes big enough to hold an error response.
*/
out_of_memory(c, "SERVER_ERROR out of memory adding binary header");
return;
}
header = (protocol_binary_response_header *)c->wbuf;
header->response.magic = (uint8_t)PROTOCOL_BINARY_RES;
header->response.opcode = c->binary_header.request.opcode;
header->response.keylen = (uint16_t)htons(key_len);
header->response.extlen = (uint8_t)hdr_len;
header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
header->response.status = (uint16_t)htons(err);
header->response.bodylen = htonl(body_len);
header->response.opaque = c->opaque;
header->response.cas = htonll(c->cas);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d Writing bin response:", c->sfd);
for (ii = 0; ii < sizeof(header->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n>%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", header->bytes[ii]);
}
fprintf(stderr, "\n");
}
add_iov(c, c->wbuf, sizeof(header->response));
}
/**
* Writes a binary error response. If errstr is supplied, it is used as the
* error text; otherwise a generic description of the error status code is
* included.
*/
static void write_bin_error(conn *c, protocol_binary_response_status err,
const char *errstr, int swallow) {
size_t len;
if (!errstr) {
switch (err) {
case PROTOCOL_BINARY_RESPONSE_ENOMEM:
errstr = "Out of memory";
break;
case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
errstr = "Unknown command";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
errstr = "Not found";
break;
case PROTOCOL_BINARY_RESPONSE_EINVAL:
errstr = "Invalid arguments";
break;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
errstr = "Data exists for key.";
break;
case PROTOCOL_BINARY_RESPONSE_E2BIG:
errstr = "Too large.";
break;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL:
errstr = "Non-numeric server-side value for incr or decr";
break;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
errstr = "Not stored.";
break;
case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR:
errstr = "Auth failure.";
break;
default:
assert(false);
errstr = "UNHANDLED ERROR";
fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err);
}
}
if (settings.verbose > 1) {
fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr);
}
len = strlen(errstr);
add_bin_header(c, err, 0, 0, len);
if (len > 0) {
add_iov(c, errstr, len);
}
conn_set_state(c, conn_mwrite);
if(swallow > 0) {
c->sbytes = swallow;
c->write_and_go = conn_swallow;
} else {
c->write_and_go = conn_new_cmd;
}
}
/* Form and send a response to a command over the binary protocol */
static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) {
if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET ||
c->cmd == PROTOCOL_BINARY_CMD_GETK) {
add_bin_header(c, 0, hlen, keylen, dlen);
if(dlen > 0) {
add_iov(c, d, dlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
conn_set_state(c, conn_new_cmd);
}
}
static void complete_incr_bin(conn *c) {
item *it;
char *key;
size_t nkey;
/* Weird magic in add_delta forces me to pad here */
char tmpbuf[INCR_MAX_STORAGE_LEN];
uint64_t cas = 0;
protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf;
protocol_binary_request_incr* req = binary_get_request(c);
assert(c != NULL);
assert(c->wsize >= sizeof(*rsp));
/* fix byteorder in the request */
req->message.body.delta = ntohll(req->message.body.delta);
req->message.body.initial = ntohll(req->message.body.initial);
req->message.body.expiration = ntohl(req->message.body.expiration);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int i;
fprintf(stderr, "incr ");
for (i = 0; i < nkey; i++) {
fprintf(stderr, "%c", key[i]);
}
fprintf(stderr, " %lld, %llu, %d\n",
(long long)req->message.body.delta,
(long long)req->message.body.initial,
req->message.body.expiration);
}
if (c->binary_header.request.cas != 0) {
cas = c->binary_header.request.cas;
}
switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT,
req->message.body.delta, tmpbuf,
&cas)) {
case OK:
rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10));
if (cas) {
c->cas = cas;
}
write_bin_response(c, &rsp->message.body, 0, 0,
sizeof(rsp->message.body.value));
break;
case NON_NUMERIC:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0);
break;
case EOM:
out_of_memory(c, "SERVER_ERROR Out of memory incrementing value");
break;
case DELTA_ITEM_NOT_FOUND:
if (req->message.body.expiration != 0xffffffff) {
/* Save some room for the response */
rsp->message.body.value = htonll(req->message.body.initial);
snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu",
(unsigned long long)req->message.body.initial);
int res = strlen(tmpbuf);
it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration),
res + 2);
if (it != NULL) {
memcpy(ITEM_data(it), tmpbuf, res);
memcpy(ITEM_data(it) + res, "\r\n", 2);
if (store_item(it, NREAD_ADD, c)) {
c->cas = ITEM_get_cas(it);
write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value));
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED,
NULL, 0);
}
item_remove(it); /* release our reference */
} else {
out_of_memory(c,
"SERVER_ERROR Out of memory allocating new item");
}
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
}
break;
case DELTA_ITEM_CAS_MISMATCH:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
break;
}
}
static void complete_update_bin(conn *c) {
protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL;
enum store_item_type ret = NOT_STORED;
assert(c != NULL);
item *it = c->item;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We don't actually receive the trailing two characters in the bin
* protocol, so we're going to just set them here */
if ((it->it_flags & ITEM_CHUNKED) == 0) {
*(ITEM_data(it) + it->nbytes - 2) = '\r';
*(ITEM_data(it) + it->nbytes - 1) = '\n';
} else {
assert(c->ritem);
item_chunk *ch = (item_chunk *) c->ritem;
if (ch->size == ch->used)
ch = ch->next;
assert(ch->size - ch->used >= 2);
ch->data[ch->used] = '\r';
ch->data[ch->used + 1] = '\n';
ch->used += 2;
}
ret = store_item(it, c->cmd, c);
#ifdef ENABLE_DTRACE
uint64_t cas = ITEM_get_cas(it);
switch (c->cmd) {
case NREAD_ADD:
MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_REPLACE:
MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_APPEND:
MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_PREPEND:
MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
case NREAD_SET:
MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey,
(ret == STORED) ? it->nbytes : -1, cas);
break;
}
#endif
switch (ret) {
case STORED:
/* Stored */
write_bin_response(c, NULL, 0, 0, 0);
break;
case EXISTS:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
break;
case NOT_FOUND:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
break;
case NOT_STORED:
case TOO_LARGE:
case NO_MEMORY:
if (c->cmd == NREAD_ADD) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;
} else if(c->cmd == NREAD_REPLACE) {
eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED;
}
write_bin_error(c, eno, NULL, 0);
}
item_remove(c->item); /* release the c->item reference */
c->item = 0;
}
static void write_bin_miss_response(conn *c, char *key, size_t nkey) {
if (nkey) {
char *ofs = c->wbuf + sizeof(protocol_binary_response_header);
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
0, nkey, nkey);
memcpy(ofs, key, nkey);
add_iov(c, ofs, nkey);
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT,
NULL, 0);
}
}
static void process_bin_get_or_touch(conn *c) {
item *it;
protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf;
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH ||
c->cmd == PROTOCOL_BINARY_CMD_GAT ||
c->cmd == PROTOCOL_BINARY_CMD_GATK);
int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK ||
c->cmd == PROTOCOL_BINARY_CMD_GATK);
int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH);
bool failed = false;
if (settings.verbose > 1) {
fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET");
if (fwrite(key, 1, nkey, stderr)) {}
fputc('\n', stderr);
}
if (should_touch) {
protocol_binary_request_touch *t = binary_get_request(c);
time_t exptime = ntohl(t->message.body.expiration);
it = item_touch(key, nkey, realtime(exptime), c);
} else {
it = item_get(key, nkey, c, DO_UPDATE);
}
if (it) {
/* the length has two unnecessary bytes ("\r\n") */
uint16_t keylen = 0;
uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2);
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
} else {
c->thread->stats.get_cmds++;
c->thread->stats.lru_hits[it->slabs_clsid]++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
if (should_touch) {
MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
} else {
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
}
if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) {
bodylen -= it->nbytes - 2;
} else if (should_return_key) {
bodylen += nkey;
keylen = nkey;
}
add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen);
rsp->message.header.response.cas = htonll(ITEM_get_cas(it));
// add the flags
FLAGS_CONV(settings.inline_ascii_response, it, rsp->message.body.flags);
rsp->message.body.flags = htonl(rsp->message.body.flags);
add_iov(c, &rsp->message.body, sizeof(rsp->message.body));
if (should_return_key) {
add_iov(c, ITEM_key(it), nkey);
}
if (should_return_value) {
/* Add the data minus the CRLF */
#ifdef EXTSTORE
if (it->it_flags & ITEM_HDR) {
int iovcnt = 4;
int iovst = c->iovused - 3;
if (!should_return_key) {
iovcnt = 3;
iovst = c->iovused - 2;
}
if (_get_extstore(c, it, iovst, iovcnt) != 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_oom_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
failed = true;
}
} else if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes - 2);
} else {
add_chunked_item_iovs(c, it, it->nbytes - 2);
}
#else
if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes - 2);
} else {
add_chunked_item_iovs(c, it, it->nbytes - 2);
}
#endif
}
if (!failed) {
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
/* Remember this command so we can garbage collect it later */
#ifdef EXTSTORE
if ((it->it_flags & ITEM_HDR) != 0 && should_return_value) {
// Only have extstore clean if header and returning value.
c->item = NULL;
} else {
c->item = it;
}
#else
c->item = it;
#endif
} else {
item_remove(it);
}
} else {
failed = true;
}
if (failed) {
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
} else {
c->thread->stats.get_cmds++;
c->thread->stats.get_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
if (should_touch) {
MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0);
} else {
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
if (c->noreply) {
conn_set_state(c, conn_new_cmd);
} else {
if (should_return_key) {
write_bin_miss_response(c, key, nkey);
} else {
write_bin_miss_response(c, NULL, 0);
}
}
}
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
}
static void append_bin_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *buf = c->stats.buffer + c->stats.offset;
uint32_t bodylen = klen + vlen;
protocol_binary_response_header header = {
.response.magic = (uint8_t)PROTOCOL_BINARY_RES,
.response.opcode = PROTOCOL_BINARY_CMD_STAT,
.response.keylen = (uint16_t)htons(klen),
.response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES,
.response.bodylen = htonl(bodylen),
.response.opaque = c->opaque
};
memcpy(buf, header.bytes, sizeof(header.response));
buf += sizeof(header.response);
if (klen > 0) {
memcpy(buf, key, klen);
buf += klen;
if (vlen > 0) {
memcpy(buf, val, vlen);
}
}
c->stats.offset += sizeof(header.response) + bodylen;
}
static void append_ascii_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
conn *c) {
char *pos = c->stats.buffer + c->stats.offset;
uint32_t nbytes = 0;
int remaining = c->stats.size - c->stats.offset;
int room = remaining - 1;
if (klen == 0 && vlen == 0) {
nbytes = snprintf(pos, room, "END\r\n");
} else if (vlen == 0) {
nbytes = snprintf(pos, room, "STAT %s\r\n", key);
} else {
nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val);
}
c->stats.offset += nbytes;
}
static bool grow_stats_buf(conn *c, size_t needed) {
size_t nsize = c->stats.size;
size_t available = nsize - c->stats.offset;
bool rv = true;
/* Special case: No buffer -- need to allocate fresh */
if (c->stats.buffer == NULL) {
nsize = 1024;
available = c->stats.size = c->stats.offset = 0;
}
while (needed > available) {
assert(nsize > 0);
nsize = nsize << 1;
available = nsize - c->stats.offset;
}
if (nsize != c->stats.size) {
char *ptr = realloc(c->stats.buffer, nsize);
if (ptr) {
c->stats.buffer = ptr;
c->stats.size = nsize;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
rv = false;
}
}
return rv;
}
static void append_stats(const char *key, const uint16_t klen,
const char *val, const uint32_t vlen,
const void *cookie)
{
/* value without a key is invalid */
if (klen == 0 && vlen > 0) {
return ;
}
conn *c = (conn*)cookie;
if (c->protocol == binary_prot) {
size_t needed = vlen + klen + sizeof(protocol_binary_response_header);
if (!grow_stats_buf(c, needed)) {
return ;
}
append_bin_stats(key, klen, val, vlen, c);
} else {
size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n"
if (!grow_stats_buf(c, needed)) {
return ;
}
append_ascii_stats(key, klen, val, vlen, c);
}
assert(c->stats.offset <= c->stats.size);
}
static void process_bin_stat(conn *c) {
char *subcommand = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "<%d STATS ", c->sfd);
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", subcommand[ii]);
}
fprintf(stderr, "\n");
}
if (nkey == 0) {
/* request all statistics */
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strncmp(subcommand, "reset", 5) == 0) {
stats_reset();
} else if (strncmp(subcommand, "settings", 8) == 0) {
process_stat_settings(&append_stats, c);
} else if (strncmp(subcommand, "detail", 6) == 0) {
char *subcmd_pos = subcommand + 6;
if (strncmp(subcmd_pos, " dump", 5) == 0) {
int len;
char *dump_buf = stats_prefix_dump(&len);
if (dump_buf == NULL || len <= 0) {
out_of_memory(c, "SERVER_ERROR Out of memory generating stats");
if (dump_buf != NULL)
free(dump_buf);
return;
} else {
append_stats("detailed", strlen("detailed"), dump_buf, len, c);
free(dump_buf);
}
} else if (strncmp(subcmd_pos, " on", 3) == 0) {
settings.detail_enabled = 1;
} else if (strncmp(subcmd_pos, " off", 4) == 0) {
settings.detail_enabled = 0;
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
return;
}
} else {
if (get_stats(subcommand, nkey, &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR Out of memory generating stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
}
return;
}
/* Append termination package and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) {
assert(c);
c->substate = next_substate;
c->rlbytes = c->keylen + extra;
/* Ok... do we have room for the extras and the key in the input buffer? */
ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf;
if (c->rlbytes > c->rsize - offset) {
size_t nsize = c->rsize;
size_t size = c->rlbytes + sizeof(protocol_binary_request_header);
while (size > nsize) {
nsize *= 2;
}
if (nsize != c->rsize) {
if (settings.verbose > 1) {
fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n",
c->sfd, (unsigned long)c->rsize, (unsigned long)nsize);
}
char *newm = realloc(c->rbuf, nsize);
if (newm == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
if (settings.verbose) {
fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n",
c->sfd);
}
conn_set_state(c, conn_closing);
return;
}
c->rbuf= newm;
/* rcurr should point to the same offset in the packet */
c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header);
c->rsize = nsize;
}
if (c->rbuf != c->rcurr) {
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Repack input buffer\n", c->sfd);
}
}
}
/* preserve the header in the buffer.. */
c->ritem = c->rcurr + sizeof(protocol_binary_request_header);
conn_set_state(c, conn_nread);
}
/* Just write an error message and disconnect the client */
static void handle_binary_protocol_error(conn *c) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0);
if (settings.verbose) {
fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n",
c->binary_header.request.opcode, c->sfd);
}
c->write_and_go = conn_closing;
}
static void init_sasl_conn(conn *c) {
assert(c);
/* should something else be returned? */
if (!settings.sasl)
return;
c->authenticated = false;
if (!c->sasl_conn) {
int result=sasl_server_new("memcached",
NULL,
my_sasl_hostname[0] ? my_sasl_hostname : NULL,
NULL, NULL,
NULL, 0, &c->sasl_conn);
if (result != SASL_OK) {
if (settings.verbose) {
fprintf(stderr, "Failed to initialize SASL conn.\n");
}
c->sasl_conn = NULL;
}
}
}
static void bin_list_sasl_mechs(conn *c) {
// Guard against a disabled SASL.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
init_sasl_conn(c);
const char *result_string = NULL;
unsigned int string_length = 0;
int result=sasl_listmech(c->sasl_conn, NULL,
"", /* What to prepend the string with */
" ", /* What to separate mechanisms with */
"", /* What to append to the string */
&result_string, &string_length,
NULL);
if (result != SASL_OK) {
/* Perhaps there's a better error for this... */
if (settings.verbose) {
fprintf(stderr, "Failed to list SASL mechanisms.\n");
}
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
return;
}
write_bin_response(c, (char*)result_string, 0, 0, string_length);
}
static void process_bin_sasl_auth(conn *c) {
// Guard for handling disabled SASL on the server.
if (!settings.sasl) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
c->binary_header.request.bodylen
- c->binary_header.request.keylen);
return;
}
assert(c->binary_header.request.extlen == 0);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > MAX_SASL_MECH_LEN) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
return;
}
char *key = binary_get_key(c);
assert(key);
item *it = item_alloc(key, nkey, 0, 0, vlen+2);
/* Can't use a chunked item for SASL authentication. */
if (it == 0 || (it->it_flags & ITEM_CHUNKED)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen);
c->write_and_go = conn_swallow;
return;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_reading_sasl_auth_data;
}
static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
if (nkey > ((item*) c->item)->nkey) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
item_unlink(c->item);
return;
}
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
if (vlen > ((item*) c->item)->nbytes) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen);
c->write_and_go = conn_swallow;
item_unlink(c->item);
return;
}
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
c->sasl_started = (result == SASL_OK || result == SASL_CONTINUE);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (!c->sasl_started) {
if (settings.verbose) {
fprintf(stderr, "%d: SASL_STEP called but sasl_server_start "
"not called for this connection!\n", c->sfd);
}
break;
}
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
c->authenticated = true;
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.auth_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.auth_cmds++;
c->thread->stats.auth_errors++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
}
static bool authenticated(conn *c) {
assert(settings.sasl);
bool rv = false;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */
rv = true;
break;
default:
rv = c->authenticated;
}
if (settings.verbose > 1) {
fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n",
c->cmd, rv ? "true" : "false");
}
return rv;
}
static void dispatch_bin_command(conn *c) {
int protocol_error = 0;
uint8_t extlen = c->binary_header.request.extlen;
uint16_t keylen = c->binary_header.request.keylen;
uint32_t bodylen = c->binary_header.request.bodylen;
if (keylen > bodylen || keylen + extlen > bodylen) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0);
c->write_and_go = conn_closing;
return;
}
if (settings.sasl && !authenticated(c)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
c->write_and_go = conn_closing;
return;
}
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
c->noreply = true;
/* binprot supports 16bit keys, but internals are still 8bit */
if (keylen > KEY_MAX_LENGTH) {
handle_binary_protocol_error(c);
return;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SETQ:
c->cmd = PROTOCOL_BINARY_CMD_SET;
break;
case PROTOCOL_BINARY_CMD_ADDQ:
c->cmd = PROTOCOL_BINARY_CMD_ADD;
break;
case PROTOCOL_BINARY_CMD_REPLACEQ:
c->cmd = PROTOCOL_BINARY_CMD_REPLACE;
break;
case PROTOCOL_BINARY_CMD_DELETEQ:
c->cmd = PROTOCOL_BINARY_CMD_DELETE;
break;
case PROTOCOL_BINARY_CMD_INCREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_INCREMENT;
break;
case PROTOCOL_BINARY_CMD_DECREMENTQ:
c->cmd = PROTOCOL_BINARY_CMD_DECREMENT;
break;
case PROTOCOL_BINARY_CMD_QUITQ:
c->cmd = PROTOCOL_BINARY_CMD_QUIT;
break;
case PROTOCOL_BINARY_CMD_FLUSHQ:
c->cmd = PROTOCOL_BINARY_CMD_FLUSH;
break;
case PROTOCOL_BINARY_CMD_APPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPENDQ:
c->cmd = PROTOCOL_BINARY_CMD_PREPEND;
break;
case PROTOCOL_BINARY_CMD_GETQ:
c->cmd = PROTOCOL_BINARY_CMD_GET;
break;
case PROTOCOL_BINARY_CMD_GETKQ:
c->cmd = PROTOCOL_BINARY_CMD_GETK;
break;
case PROTOCOL_BINARY_CMD_GATQ:
c->cmd = PROTOCOL_BINARY_CMD_GAT;
break;
case PROTOCOL_BINARY_CMD_GATKQ:
c->cmd = PROTOCOL_BINARY_CMD_GATK;
break;
default:
c->noreply = false;
}
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_VERSION:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, VERSION, 0, 0, strlen(VERSION));
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_FLUSH:
if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) {
bin_read_key(c, bin_read_flush_exptime, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_NOOP:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_REPLACE:
if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) {
bin_read_key(c, bin_reading_set_header, 8);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */
case PROTOCOL_BINARY_CMD_GETK:
if (extlen == 0 && bodylen == keylen && keylen > 0) {
bin_read_key(c, bin_reading_get_key, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_DELETE:
if (keylen > 0 && extlen == 0 && bodylen == keylen) {
bin_read_key(c, bin_reading_del_header, extlen);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_INCREMENT:
case PROTOCOL_BINARY_CMD_DECREMENT:
if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) {
bin_read_key(c, bin_reading_incr_header, 20);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_APPEND:
case PROTOCOL_BINARY_CMD_PREPEND:
if (keylen > 0 && extlen == 0) {
bin_read_key(c, bin_reading_set_header, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_STAT:
if (extlen == 0) {
bin_read_key(c, bin_reading_stat, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_QUIT:
if (keylen == 0 && extlen == 0 && bodylen == 0) {
write_bin_response(c, NULL, 0, 0, 0);
c->write_and_go = conn_closing;
if (c->noreply) {
conn_set_state(c, conn_closing);
}
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS:
if (extlen == 0 && keylen == 0 && bodylen == 0) {
bin_list_sasl_mechs(c);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_SASL_AUTH:
case PROTOCOL_BINARY_CMD_SASL_STEP:
if (extlen == 0 && keylen != 0) {
bin_read_key(c, bin_reading_sasl_auth, 0);
} else {
protocol_error = 1;
}
break;
case PROTOCOL_BINARY_CMD_TOUCH:
case PROTOCOL_BINARY_CMD_GAT:
case PROTOCOL_BINARY_CMD_GATQ:
case PROTOCOL_BINARY_CMD_GATK:
case PROTOCOL_BINARY_CMD_GATKQ:
if (extlen == 4 && keylen != 0) {
bin_read_key(c, bin_reading_touch_key, 4);
} else {
protocol_error = 1;
}
break;
default:
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL,
bodylen);
}
if (protocol_error)
handle_binary_protocol_error(c);
}
static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* This error generating method eats the swallow value. Add here. */
c->sbytes = vlen;
status = NO_MEMORY;
}
/* FIXME: losing c->cmd since it's translated below. refactor? */
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, 0, key, nkey, req->message.body.expiration,
ITEM_clsid(it));
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
#ifdef NEED_ALIGN
if (it->it_flags & ITEM_CHUNKED) {
c->ritem = ITEM_schunk(it);
} else {
c->ritem = ITEM_data(it);
}
#else
c->ritem = ITEM_data(it);
#endif
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_append_prepend(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
vlen = c->binary_header.request.bodylen - nkey;
if (settings.verbose > 1) {
fprintf(stderr, "Value len is %d\n", vlen);
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, 0, 0, vlen+2);
if (it == 0) {
if (! item_size_ok(nkey, 0, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* OOM calls eat the swallow value. Add here. */
c->sbytes = vlen;
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_APPEND:
c->cmd = NREAD_APPEND;
break;
case PROTOCOL_BINARY_CMD_PREPEND:
c->cmd = NREAD_PREPEND;
break;
default:
assert(0);
}
c->item = it;
#ifdef NEED_ALIGN
if (it->it_flags & ITEM_CHUNKED) {
c->ritem = ITEM_schunk(it);
} else {
c->ritem = ITEM_data(it);
}
#else
c->ritem = ITEM_data(it);
#endif
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
static void process_bin_flush(conn *c) {
time_t exptime = 0;
protocol_binary_request_flush* req = binary_get_request(c);
rel_time_t new_oldest = 0;
if (!settings.flush_enabled) {
// flush_all is not allowed but we log it on stats
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0);
return;
}
if (c->binary_header.request.extlen == sizeof(req->message.body)) {
exptime = ntohl(req->message.body.expiration);
}
if (exptime > 0) {
new_oldest = realtime(exptime);
} else {
new_oldest = current_time;
}
if (settings.use_cas) {
settings.oldest_live = new_oldest - 1;
if (settings.oldest_live <= current_time)
settings.oldest_cas = get_cas_id();
} else {
settings.oldest_live = new_oldest;
}
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
write_bin_response(c, NULL, 0, 0, 0);
}
static void process_bin_delete(conn *c) {
item *it;
uint32_t hv;
protocol_binary_request_delete* req = binary_get_request(c);
char* key = binary_get_key(c);
size_t nkey = c->binary_header.request.keylen;
assert(c != NULL);
if (settings.verbose > 1) {
int ii;
fprintf(stderr, "Deleting ");
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv);
if (it) {
uint64_t cas = ntohll(req->message.header.request.cas);
if (cas == 0 || cas == ITEM_get_cas(it)) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
do_item_unlink(it, hv);
STORAGE_delete(c->thread->storage, it);
write_bin_response(c, NULL, 0, 0, 0);
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0);
}
do_item_remove(it); /* release our reference */
} else {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
item_unlock(hv);
}
static void complete_nread_binary(conn *c) {
assert(c != NULL);
assert(c->cmd >= 0);
switch(c->substate) {
case bin_reading_set_header:
if (c->cmd == PROTOCOL_BINARY_CMD_APPEND ||
c->cmd == PROTOCOL_BINARY_CMD_PREPEND) {
process_bin_append_prepend(c);
} else {
process_bin_update(c);
}
break;
case bin_read_set_value:
complete_update_bin(c);
break;
case bin_reading_get_key:
case bin_reading_touch_key:
process_bin_get_or_touch(c);
break;
case bin_reading_stat:
process_bin_stat(c);
break;
case bin_reading_del_header:
process_bin_delete(c);
break;
case bin_reading_incr_header:
complete_incr_bin(c);
break;
case bin_read_flush_exptime:
process_bin_flush(c);
break;
case bin_reading_sasl_auth:
process_bin_sasl_auth(c);
break;
case bin_reading_sasl_auth_data:
process_bin_complete_sasl_auth(c);
break;
default:
fprintf(stderr, "Not handling substate %d\n", c->substate);
assert(0);
}
}
static void reset_cmd_handler(conn *c) {
c->cmd = -1;
c->substate = bin_no_state;
if(c->item != NULL) {
item_remove(c->item);
c->item = NULL;
}
conn_shrink(c);
if (c->rbytes > 0) {
conn_set_state(c, conn_parse_cmd);
} else {
conn_set_state(c, conn_waiting);
}
}
static void complete_nread(conn *c) {
assert(c != NULL);
assert(c->protocol == ascii_prot
|| c->protocol == binary_prot);
if (c->protocol == ascii_prot) {
complete_nread_ascii(c);
} else if (c->protocol == binary_prot) {
complete_nread_binary(c);
}
}
/* Destination must always be chunked */
/* This should be part of item.c */
static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) {
item_chunk *dch = (item_chunk *) ITEM_schunk(d_it);
/* Advance dch until we find free space */
while (dch->size == dch->used) {
if (dch->next) {
dch = dch->next;
} else {
break;
}
}
if (s_it->it_flags & ITEM_CHUNKED) {
int remain = len;
item_chunk *sch = (item_chunk *) ITEM_schunk(s_it);
int copied = 0;
/* Fills dch's to capacity, not straight copy sch in case data is
* being added or removed (ie append/prepend)
*/
while (sch && dch && remain) {
assert(dch->used <= dch->size);
int todo = (dch->size - dch->used < sch->used - copied)
? dch->size - dch->used : sch->used - copied;
if (remain < todo)
todo = remain;
memcpy(dch->data + dch->used, sch->data + copied, todo);
dch->used += todo;
copied += todo;
remain -= todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, remain);
if (tch) {
dch = tch;
} else {
return -1;
}
}
assert(copied <= sch->used);
if (copied == sch->used) {
copied = 0;
sch = sch->next;
}
}
/* assert that the destination had enough space for the source */
assert(remain == 0);
} else {
int done = 0;
/* Fill dch's via a non-chunked item. */
while (len > done && dch) {
int todo = (dch->size - dch->used < len - done)
? dch->size - dch->used : len - done;
//assert(dch->size - dch->used != 0);
memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo);
done += todo;
dch->used += todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, len - done);
if (tch) {
dch = tch;
} else {
return -1;
}
}
}
assert(len == done);
}
return 0;
}
static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) {
if (comm == NREAD_APPEND) {
if (new_it->it_flags & ITEM_CHUNKED) {
if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 ||
_store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) {
return -1;
}
} else {
memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes);
memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes);
}
} else {
/* NREAD_PREPEND */
if (new_it->it_flags & ITEM_CHUNKED) {
if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 ||
_store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) {
return -1;
}
} else {
memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes);
memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes);
}
}
return 0;
}
/*
* Stores an item in the cache according to the semantics of one of the set
* commands. In threaded mode, this is protected by the cache lock.
*
* Returns the state of storage.
*/
enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) {
char *key = ITEM_key(it);
item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE);
enum store_item_type stored = NOT_STORED;
item *new_it = NULL;
uint32_t flags;
if (old_it != NULL && comm == NREAD_ADD) {
/* add only adds a nonexistent item, but promote to head of LRU */
do_item_update(old_it);
} else if (!old_it && (comm == NREAD_REPLACE
|| comm == NREAD_APPEND || comm == NREAD_PREPEND))
{
/* replace only replaces an existing value; don't store */
} else if (comm == NREAD_CAS) {
/* validate cas operation */
if(old_it == NULL) {
// LRU expired
stored = NOT_FOUND;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.cas_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
}
else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) {
// cas validates
// it and old_it may belong to different classes.
// I'm updating the stats for the one that's getting pushed out
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
STORAGE_delete(c->thread->storage, old_it);
item_replace(old_it, it, hv);
stored = STORED;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if(settings.verbose > 1) {
fprintf(stderr, "CAS: failure: expected %llu, got %llu\n",
(unsigned long long)ITEM_get_cas(old_it),
(unsigned long long)ITEM_get_cas(it));
}
stored = EXISTS;
}
} else {
int failed_alloc = 0;
/*
* Append - combine new and old record into single one. Here it's
* atomic and thread-safe.
*/
if (comm == NREAD_APPEND || comm == NREAD_PREPEND) {
/*
* Validate CAS
*/
if (ITEM_get_cas(it) != 0) {
// CAS much be equal
if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) {
stored = EXISTS;
}
}
#ifdef EXTSTORE
if ((old_it->it_flags & ITEM_HDR) != 0) {
/* block append/prepend from working with extstore-d items.
* also don't replace the header with the append chunk
* accidentally, so mark as a failed_alloc.
*/
failed_alloc = 1;
} else
#endif
if (stored == NOT_STORED) {
/* we have it and old_it here - alloc memory to hold both */
/* flags was already lost - so recover them from ITEM_suffix(it) */
FLAGS_CONV(settings.inline_ascii_response, old_it, flags);
new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */);
/* copy data from it and old_it to new_it */
if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) {
failed_alloc = 1;
stored = NOT_STORED;
// failed data copy, free up.
if (new_it != NULL)
item_remove(new_it);
} else {
it = new_it;
}
}
}
if (stored == NOT_STORED && failed_alloc == 0) {
if (old_it != NULL) {
STORAGE_delete(c->thread->storage, old_it);
item_replace(old_it, it, hv);
} else {
do_item_link(it, hv);
}
c->cas = ITEM_get_cas(it);
stored = STORED;
}
}
if (old_it != NULL)
do_item_remove(old_it); /* release our reference */
if (new_it != NULL)
do_item_remove(new_it);
if (stored == STORED) {
c->cas = ITEM_get_cas(it);
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL,
stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it));
return stored;
}
typedef struct token_s {
char *value;
size_t length;
} token_t;
#define COMMAND_TOKEN 0
#define SUBCOMMAND_TOKEN 1
#define KEY_TOKEN 1
#define MAX_TOKENS 8
/*
* Tokenize the command string by replacing whitespace with '\0' and update
* the token array tokens with pointer to start of each token and length.
* Returns total number of tokens. The last valid token is the terminal
* token (value points to the first unprocessed character of the string and
* length zero).
*
* Usage example:
*
* while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
* for(int ix = 0; tokens[ix].length != 0; ix++) {
* ...
* }
* ncommand = tokens[ix].value - command;
* command = tokens[ix].value;
* }
*/
static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) {
char *s, *e;
size_t ntokens = 0;
size_t len = strlen(command);
unsigned int i = 0;
assert(command != NULL && tokens != NULL && max_tokens > 1);
s = e = command;
for (i = 0; i < len; i++) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
if (ntokens == max_tokens - 1) {
e++;
s = e; /* so we don't add an extra token */
break;
}
}
s = e + 1;
}
e++;
}
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
/* set up a connection to write a buffer then free it, used for stats */
static void write_and_free(conn *c, char *buf, int bytes) {
if (buf) {
c->write_and_free = buf;
c->wcurr = buf;
c->wbytes = bytes;
conn_set_state(c, conn_write);
c->write_and_go = conn_new_cmd;
} else {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
}
}
static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens)
{
int noreply_index = ntokens - 2;
/*
NOTE: this function is not the first place where we are going to
send the reply. We could send it instead from process_command()
if the request line has wrong number of tokens. However parsing
malformed line for "noreply" option is not reliable anyway, so
it can't be helped.
*/
if (tokens[noreply_index].value
&& strcmp(tokens[noreply_index].value, "noreply") == 0) {
c->noreply = true;
}
return c->noreply;
}
void append_stat(const char *name, ADD_STAT add_stats, conn *c,
const char *fmt, ...) {
char val_str[STAT_VAL_LEN];
int vlen;
va_list ap;
assert(name);
assert(add_stats);
assert(c);
assert(fmt);
va_start(ap, fmt);
vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap);
va_end(ap);
add_stats(name, strlen(name), val_str, vlen, c);
}
inline static void process_stats_detail(conn *c, const char *command) {
assert(c != NULL);
if (strcmp(command, "on") == 0) {
settings.detail_enabled = 1;
out_string(c, "OK");
}
else if (strcmp(command, "off") == 0) {
settings.detail_enabled = 0;
out_string(c, "OK");
}
else if (strcmp(command, "dump") == 0) {
int len;
char *stats = stats_prefix_dump(&len);
write_and_free(c, stats, len);
}
else {
out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump");
}
}
/* return server specific stats only */
static void server_stats(ADD_STAT add_stats, conn *c) {
pid_t pid = getpid();
rel_time_t now = current_time;
struct thread_stats thread_stats;
threadlocal_stats_aggregate(&thread_stats);
struct slab_stats slab_stats;
slab_stats_aggregate(&thread_stats, &slab_stats);
#ifdef EXTSTORE
struct extstore_stats st;
#endif
#ifndef WIN32
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
#endif /* !WIN32 */
STATS_LOCK();
APPEND_STAT("pid", "%lu", (long)pid);
APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL);
APPEND_STAT("time", "%ld", now + (long)process_started);
APPEND_STAT("version", "%s", VERSION);
APPEND_STAT("libevent", "%s", event_get_version());
APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *)));
#ifndef WIN32
append_stat("rusage_user", add_stats, c, "%ld.%06ld",
(long)usage.ru_utime.tv_sec,
(long)usage.ru_utime.tv_usec);
append_stat("rusage_system", add_stats, c, "%ld.%06ld",
(long)usage.ru_stime.tv_sec,
(long)usage.ru_stime.tv_usec);
#endif /* !WIN32 */
APPEND_STAT("max_connections", "%d", settings.maxconns);
APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1);
APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns);
if (settings.maxconns_fast) {
APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns);
}
APPEND_STAT("connection_structures", "%u", stats_state.conn_structs);
APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds);
APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds);
APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds);
APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds);
APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds);
APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits);
APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses);
APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired);
APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed);
#ifdef EXTSTORE
if (c->thread->storage) {
APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore);
APPEND_STAT("get_aborted_extstore", "%llu", (unsigned long long)thread_stats.get_aborted_extstore);
APPEND_STAT("get_oom_extstore", "%llu", (unsigned long long)thread_stats.get_oom_extstore);
APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore);
APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore);
APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore);
}
#endif
APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses);
APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits);
APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses);
APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits);
APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses);
APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits);
APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses);
APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits);
APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval);
APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits);
APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses);
APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds);
APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors);
if (settings.idle_timeout) {
APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks);
}
APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read);
APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written);
APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns);
APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num);
APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us);
APPEND_STAT("threads", "%d", settings.num_threads);
APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields);
APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level);
APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes);
APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding);
if (settings.slab_reassign) {
APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues);
APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues);
APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem);
APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim);
APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items);
APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes);
APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running);
APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved);
}
if (settings.lru_crawler) {
APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running);
APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts);
}
if (settings.lru_maintainer_thread) {
APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles);
}
APPEND_STAT("malloc_fails", "%llu",
(unsigned long long)stats.malloc_fails);
APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped);
APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written);
APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped);
APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent);
STATS_UNLOCK();
#ifdef EXTSTORE
if (c->thread->storage) {
STATS_LOCK();
APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost);
APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues);
APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped);
STATS_UNLOCK();
extstore_get_stats(c->thread->storage, &st);
APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs);
APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions);
APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims);
APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free);
APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used);
APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted);
APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read);
APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written);
APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used);
APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted);
APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written);
APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read);
APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used);
APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented);
APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size));
APPEND_STAT("extstore_io_queue", "%llu", (unsigned long long)(st.io_queue));
}
#endif
#ifdef TLS
if (settings.ssl_enabled) {
SSL_LOCK();
APPEND_STAT("time_since_server_cert_refresh", "%u", now - settings.ssl_last_cert_refresh_time);
SSL_UNLOCK();
}
#endif
}
static void process_stat_settings(ADD_STAT add_stats, void *c) {
assert(add_stats);
APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes);
APPEND_STAT("maxconns", "%d", settings.maxconns);
APPEND_STAT("tcpport", "%d", settings.port);
APPEND_STAT("udpport", "%d", settings.udpport);
APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL");
APPEND_STAT("verbosity", "%d", settings.verbose);
APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live);
APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off");
APPEND_STAT("domain_socket", "%s",
settings.socketpath ? settings.socketpath : "NULL");
APPEND_STAT("umask", "%o", settings.access);
APPEND_STAT("growth_factor", "%.2f", settings.factor);
APPEND_STAT("chunk_size", "%d", settings.chunk_size);
APPEND_STAT("num_threads", "%d", settings.num_threads);
APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp);
APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter);
APPEND_STAT("detail_enabled", "%s",
settings.detail_enabled ? "yes" : "no");
APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event);
APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no");
APPEND_STAT("tcp_backlog", "%d", settings.backlog);
APPEND_STAT("binding_protocol", "%s",
prot_text(settings.binding_protocol));
APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no");
APPEND_STAT("item_size_max", "%d", settings.item_size_max);
APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no");
APPEND_STAT("hashpower_init", "%d", settings.hashpower_init);
APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no");
APPEND_STAT("slab_automove", "%d", settings.slab_automove);
APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio);
APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window);
APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max);
APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no");
APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep);
APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl);
APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time);
APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no");
APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no");
APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm);
APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no");
APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no");
APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct);
APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct);
APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor);
APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor);
APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no");
APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl);
APPEND_STAT("idle_timeout", "%d", settings.idle_timeout);
APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size);
APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size);
APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no");
APPEND_STAT("inline_ascii_response", "%s", settings.inline_ascii_response ? "yes" : "no");
#ifdef HAVE_DROP_PRIVILEGES
APPEND_STAT("drop_privileges", "%s", settings.drop_privileges ? "yes" : "no");
#endif
#ifdef EXTSTORE
APPEND_STAT("ext_item_size", "%u", settings.ext_item_size);
APPEND_STAT("ext_item_age", "%u", settings.ext_item_age);
APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl);
APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate);
APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size);
APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under);
APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under);
APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag);
APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio);
APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no");
#endif
#ifdef TLS
APPEND_STAT("ssl_enabled", "%s", settings.ssl_enabled ? "yes" : "no");
APPEND_STAT("ssl_chain_cert", "%s", settings.ssl_chain_cert);
APPEND_STAT("ssl_key", "%s", settings.ssl_key);
APPEND_STAT("ssl_verify_mode", "%d", settings.ssl_verify_mode);
APPEND_STAT("ssl_keyformat", "%d", settings.ssl_keyformat);
APPEND_STAT("ssl_ciphers", "%s", settings.ssl_ciphers ? settings.ssl_ciphers : "NULL");
APPEND_STAT("ssl_ca_cert", "%s", settings.ssl_ca_cert ? settings.ssl_ca_cert : "NULL");
APPEND_STAT("ssl_wbuf_size", "%u", settings.ssl_wbuf_size);
#endif
}
static void conn_to_str(const conn *c, char *buf) {
char addr_text[MAXPATHLEN];
if (!c) {
strcpy(buf, "<null>");
} else if (c->state == conn_closed) {
strcpy(buf, "<closed>");
} else {
const char *protoname = "?";
struct sockaddr_in6 local_addr;
struct sockaddr *addr = (void *)&c->request_addr;
int af;
unsigned short port = 0;
/* For listen ports and idle UDP ports, show listen address */
if (c->state == conn_listening ||
(IS_UDP(c->transport) &&
c->state == conn_read)) {
socklen_t local_addr_len = sizeof(local_addr);
if (getsockname(c->sfd,
(struct sockaddr *)&local_addr,
&local_addr_len) == 0) {
addr = (struct sockaddr *)&local_addr;
}
}
af = addr->sa_family;
addr_text[0] = '\0';
switch (af) {
case AF_INET:
(void) inet_ntop(af,
&((struct sockaddr_in *)addr)->sin_addr,
addr_text,
sizeof(addr_text) - 1);
port = ntohs(((struct sockaddr_in *)addr)->sin_port);
protoname = IS_UDP(c->transport) ? "udp" : "tcp";
break;
case AF_INET6:
addr_text[0] = '[';
addr_text[1] = '\0';
if (inet_ntop(af,
&((struct sockaddr_in6 *)addr)->sin6_addr,
addr_text + 1,
sizeof(addr_text) - 2)) {
strcat(addr_text, "]");
}
port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
protoname = IS_UDP(c->transport) ? "udp6" : "tcp6";
break;
case AF_UNIX:
strncpy(addr_text,
((struct sockaddr_un *)addr)->sun_path,
sizeof(addr_text) - 1);
addr_text[sizeof(addr_text)-1] = '\0';
protoname = "unix";
break;
}
if (strlen(addr_text) < 2) {
/* Most likely this is a connected UNIX-domain client which
* has no peer socket address, but there's no portable way
* to tell for sure.
*/
sprintf(addr_text, "<AF %d>", af);
}
if (port) {
sprintf(buf, "%s:%s:%u", protoname, addr_text, port);
} else {
sprintf(buf, "%s:%s", protoname, addr_text);
}
}
}
static void process_stats_conns(ADD_STAT add_stats, void *c) {
int i;
char key_str[STAT_KEY_LEN];
char val_str[STAT_VAL_LEN];
char conn_name[MAXPATHLEN + sizeof("unix:") + sizeof("65535")];
int klen = 0, vlen = 0;
assert(add_stats);
for (i = 0; i < max_fds; i++) {
if (conns[i]) {
/* This is safe to do unlocked because conns are never freed; the
* worst that'll happen will be a minor inconsistency in the
* output -- not worth the complexity of the locking that'd be
* required to prevent it.
*/
if (conns[i]->state != conn_closed) {
conn_to_str(conns[i], conn_name);
APPEND_NUM_STAT(i, "addr", "%s", conn_name);
APPEND_NUM_STAT(i, "state", "%s",
state_text(conns[i]->state));
APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d",
current_time - conns[i]->last_cmd_time);
}
}
}
}
#ifdef EXTSTORE
static void process_extstore_stats(ADD_STAT add_stats, conn *c) {
int i;
char key_str[STAT_KEY_LEN];
char val_str[STAT_VAL_LEN];
int klen = 0, vlen = 0;
struct extstore_stats st;
assert(add_stats);
void *storage = c->thread->storage;
extstore_get_stats(storage, &st);
st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data));
extstore_get_page_data(storage, &st);
for (i = 0; i < st.page_count; i++) {
APPEND_NUM_STAT(i, "version", "%llu",
(unsigned long long) st.page_data[i].version);
APPEND_NUM_STAT(i, "bytes", "%llu",
(unsigned long long) st.page_data[i].bytes_used);
APPEND_NUM_STAT(i, "bucket", "%u",
st.page_data[i].bucket);
APPEND_NUM_STAT(i, "free_bucket", "%u",
st.page_data[i].free_bucket);
}
}
#endif
static void process_stat(conn *c, token_t *tokens, const size_t ntokens) {
const char *subcommand = tokens[SUBCOMMAND_TOKEN].value;
assert(c != NULL);
if (ntokens < 2) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (ntokens == 2) {
server_stats(&append_stats, c);
(void)get_stats(NULL, 0, &append_stats, c);
} else if (strcmp(subcommand, "reset") == 0) {
stats_reset();
out_string(c, "RESET");
return ;
} else if (strcmp(subcommand, "detail") == 0) {
/* NOTE: how to tackle detail with binary? */
if (ntokens < 4)
process_stats_detail(c, ""); /* outputs the error message */
else
process_stats_detail(c, tokens[2].value);
/* Output already generated */
return ;
} else if (strcmp(subcommand, "settings") == 0) {
process_stat_settings(&append_stats, c);
} else if (strcmp(subcommand, "cachedump") == 0) {
char *buf;
unsigned int bytes, id, limit = 0;
if (!settings.dump_enabled) {
out_string(c, "CLIENT_ERROR stats cachedump not allowed");
return;
}
if (ntokens < 5) {
out_string(c, "CLIENT_ERROR bad command line");
return;
}
if (!safe_strtoul(tokens[2].value, &id) ||
!safe_strtoul(tokens[3].value, &limit)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (id >= MAX_NUMBER_OF_SLAB_CLASSES) {
out_string(c, "CLIENT_ERROR Illegal slab id");
return;
}
buf = item_cachedump(id, limit, &bytes);
write_and_free(c, buf, bytes);
return ;
} else if (strcmp(subcommand, "conns") == 0) {
process_stats_conns(&append_stats, c);
#ifdef EXTSTORE
} else if (strcmp(subcommand, "extstore") == 0) {
process_extstore_stats(&append_stats, c);
#endif
} else {
/* getting here means that the subcommand is either engine specific or
is invalid. query the engine and see. */
if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) {
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
} else {
out_string(c, "ERROR");
}
return ;
}
/* append terminator and start the transfer */
append_stats(NULL, 0, NULL, 0, c);
if (c->stats.buffer == NULL) {
out_of_memory(c, "SERVER_ERROR out of memory writing stats");
} else {
write_and_free(c, c->stats.buffer, c->stats.offset);
c->stats.buffer = NULL;
}
}
/* nsuffix == 0 means use no storage for client flags */
static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) {
char *p = suffix;
if (!settings.inline_ascii_response) {
*p = ' ';
p++;
if (it->nsuffix == 0) {
*p = '0';
p++;
} else {
p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p);
}
*p = ' ';
p = itoa_u32(nbytes-2, p+1);
} else {
p = suffix;
}
if (return_cas) {
*p = ' ';
p = itoa_u64(ITEM_get_cas(it), p+1);
}
*p = '\r';
*(p+1) = '\n';
*(p+2) = '\0';
return (p - suffix) + 2;
}
#define IT_REFCOUNT_LIMIT 60000
static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) {
item *it;
if (should_touch) {
it = item_touch(key, nkey, exptime, c);
} else {
it = item_get(key, nkey, c, DO_UPDATE);
}
if (it && it->refcount > IT_REFCOUNT_LIMIT) {
item_remove(it);
it = NULL;
}
return it;
}
static inline int _ascii_get_expand_ilist(conn *c, int i) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return -1;
}
}
return 0;
}
static inline char *_ascii_get_suffix_buf(conn *c, int i) {
char *suffix;
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
return NULL;
}
}
suffix = do_cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix");
return NULL;
}
*(c->suffixlist + i) = suffix;
return suffix;
}
#ifdef EXTSTORE
// FIXME: This runs in the IO thread. to get better IO performance this should
// simply mark the io wrapper with the return value and decrement wrapleft, if
// zero redispatching. Still a bit of work being done in the side thread but
// minimized at least.
static void _get_extstore_cb(void *e, obj_io *io, int ret) {
// FIXME: assumes success
io_wrap *wrap = (io_wrap *)io->data;
conn *c = wrap->c;
assert(wrap->active == true);
item *read_it = (item *)io->buf;
bool miss = false;
// TODO: How to do counters for hit/misses?
if (ret < 1) {
miss = true;
} else {
uint32_t crc2;
uint32_t crc = (uint32_t) read_it->exptime;
int x;
// item is chunked, crc the iov's
if (io->iov != NULL) {
// first iov is the header, which we don't use beyond crc
crc2 = crc32c(0, (char *)io->iov[0].iov_base+STORE_OFFSET, io->iov[0].iov_len-STORE_OFFSET);
// make sure it's not sent. hack :(
io->iov[0].iov_len = 0;
for (x = 1; x < io->iovcnt; x++) {
crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len);
}
} else {
crc2 = crc32c(0, (char *)read_it+STORE_OFFSET, io->len-STORE_OFFSET);
}
if (crc != crc2) {
miss = true;
wrap->badcrc = true;
}
}
if (miss) {
int i;
struct iovec *v;
// TODO: This should be movable to the worker thread.
if (c->protocol == binary_prot) {
protocol_binary_response_header *header =
(protocol_binary_response_header *)c->wbuf;
// this zeroes out the iovecs since binprot never stacks them.
if (header->response.keylen) {
write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey);
} else {
write_bin_miss_response(c, 0, 0);
}
} else {
for (i = 0; i < wrap->iovec_count; i++) {
v = &c->iov[wrap->iovec_start + i];
v->iov_len = 0;
v->iov_base = NULL;
}
}
wrap->miss = true;
} else {
assert(read_it->slabs_clsid != 0);
// kill \r\n for binprot
if (io->iov == NULL) {
c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it);
if (c->protocol == binary_prot)
c->iov[wrap->iovec_data].iov_len -= 2;
} else {
// FIXME: Might need to go back and ensure chunked binprots don't
// ever span two chunks for the final \r\n
if (c->protocol == binary_prot) {
if (io->iov[io->iovcnt-1].iov_len >= 2) {
io->iov[io->iovcnt-1].iov_len -= 2;
} else {
io->iov[io->iovcnt-1].iov_len = 0;
io->iov[io->iovcnt-2].iov_len -= 1;
}
}
}
wrap->miss = false;
// iov_len is already set
// TODO: Should do that here instead and cuddle in the wrap object
}
c->io_wrapleft--;
wrap->active = false;
//assert(c->io_wrapleft >= 0);
// All IO's have returned, lets re-attach this connection to our original
// thread.
if (c->io_wrapleft == 0) {
assert(c->io_queued == true);
c->io_queued = false;
redispatch_conn(c);
}
}
// FIXME: This completely breaks UDP support.
static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) {
#ifdef NEED_ALIGN
item_hdr hdr;
memcpy(&hdr, ITEM_data(it), sizeof(hdr));
#else
item_hdr *hdr = (item_hdr *)ITEM_data(it);
#endif
size_t ntotal = ITEM_ntotal(it);
unsigned int clsid = slabs_clsid(ntotal);
item *new_it;
bool chunked = false;
if (ntotal > settings.slab_chunk_size_max) {
// Pull a chunked item header.
uint32_t flags;
FLAGS_CONV(settings.inline_ascii_response, it, flags);
new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes);
assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED));
chunked = true;
} else {
new_it = do_item_alloc_pull(ntotal, clsid);
}
if (new_it == NULL)
return -1;
assert(!c->io_queued); // FIXME: debugging.
// so we can free the chunk on a miss
new_it->slabs_clsid = clsid;
io_wrap *io = do_cache_alloc(c->thread->io_cache);
io->active = true;
io->miss = false;
io->badcrc = false;
// io_wrap owns the reference for this object now.
io->hdr_it = it;
// FIXME: error handling.
// The offsets we'll wipe on a miss.
io->iovec_start = iovst;
io->iovec_count = iovcnt;
// This is probably super dangerous. keep it at 0 and fill into wrap
// object?
if (chunked) {
unsigned int ciovcnt = 1;
size_t remain = new_it->nbytes;
item_chunk *chunk = (item_chunk *) ITEM_schunk(new_it);
io->io.iov = &c->iov[c->iovused];
// fill the header so we can get the full data + crc back.
add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes);
while (remain > 0) {
chunk = do_item_alloc_chunk(chunk, remain);
if (chunk == NULL) {
item_remove(new_it);
do_cache_free(c->thread->io_cache, io);
return -1;
}
add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size);
chunk->used = (remain < chunk->size) ? remain : chunk->size;
remain -= chunk->size;
ciovcnt++;
}
io->io.iovcnt = ciovcnt;
// header object was already accounted for, remove one from total
io->iovec_count += ciovcnt-1;
} else {
io->io.iov = NULL;
io->iovec_data = c->iovused;
add_iov(c, "", it->nbytes);
}
io->io.buf = (void *)new_it;
// The offset we'll fill in on a hit.
io->c = c;
// We need to stack the sub-struct IO's together as well.
if (c->io_wraplist) {
io->io.next = &c->io_wraplist->io;
} else {
io->io.next = NULL;
}
// IO queue for this connection.
io->next = c->io_wraplist;
c->io_wraplist = io;
assert(c->io_wrapleft >= 0);
c->io_wrapleft++;
// reference ourselves for the callback.
io->io.data = (void *)io;
// Now, fill in io->io based on what was in our header.
#ifdef NEED_ALIGN
io->io.page_version = hdr.page_version;
io->io.page_id = hdr.page_id;
io->io.offset = hdr.offset;
#else
io->io.page_version = hdr->page_version;
io->io.page_id = hdr->page_id;
io->io.offset = hdr->offset;
#endif
io->io.len = ntotal;
io->io.mode = OBJ_IO_READ;
io->io.cb = _get_extstore_cb;
//fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data);
// FIXME: This stat needs to move to reflect # of flash hits vs misses
// for now it's a good gauge on how often we request out to flash at
// least.
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
return 0;
}
#endif
/* ntokens is overwritten here... shrug.. */
static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) {
char *key;
size_t nkey;
int i = 0;
int si = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
int32_t exptime_int = 0;
rel_time_t exptime = 0;
bool fail_length = false;
assert(c != NULL);
if (should_touch) {
// For get and touch commands, use first token as exptime
if (!safe_strtol(tokens[1].value, &exptime_int)) {
out_string(c, "CLIENT_ERROR invalid exptime argument");
return;
}
key_token++;
exptime = realtime(exptime_int);
}
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if (nkey > KEY_MAX_LENGTH) {
fail_length = true;
goto stop;
}
it = limited_get(key, nkey, c, exptime, should_touch);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (_ascii_get_expand_ilist(c, i) != 0) {
item_remove(it);
goto stop;
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas || !settings.inline_ascii_response)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
int nbytes;
suffix = _ascii_get_suffix_buf(c, si);
if (suffix == NULL) {
item_remove(it);
goto stop;
}
si++;
nbytes = it->nbytes;
int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes);
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
(settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) ||
add_iov(c, suffix, suffix_len) != 0)
{
item_remove(it);
goto stop;
}
#ifdef EXTSTORE
if (it->it_flags & ITEM_HDR) {
if (_get_extstore(c, it, c->iovused-3, 4) != 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_oom_extstore++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_remove(it);
goto stop;
}
} else if ((it->it_flags & ITEM_CHUNKED) == 0) {
#else
if ((it->it_flags & ITEM_CHUNKED) == 0) {
#endif
add_iov(c, ITEM_data(it), it->nbytes);
} else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
goto stop;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0)
{
item_remove(it);
goto stop;
}
if ((it->it_flags & ITEM_CHUNKED) == 0)
{
if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
goto stop;
}
} else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 ||
add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
goto stop;
}
}
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d sending key ", c->sfd);
for (ii = 0; ii < it->nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
} else {
c->thread->stats.lru_hits[it->slabs_clsid]++;
c->thread->stats.get_cmds++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
#ifdef EXTSTORE
/* If ITEM_HDR, an io_wrap owns the reference. */
if ((it->it_flags & ITEM_HDR) == 0) {
*(c->ilist + i) = it;
i++;
}
#else
*(c->ilist + i) = it;
i++;
#endif
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
if (should_touch) {
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
} else {
c->thread->stats.get_misses++;
c->thread->stats.get_cmds++;
}
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
pthread_mutex_unlock(&c->thread->stats.mutex);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
stop:
c->icurr = c->ilist;
c->ileft = i;
if (return_cas || !settings.inline_ascii_response) {
c->suffixcurr = c->suffixlist;
c->suffixleft = si;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
if (fail_length) {
out_string(c, "CLIENT_ERROR bad command line format");
} else {
out_of_memory(c, "SERVER_ERROR out of memory writing get response");
}
conn_release_items(c);
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
}
static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) {
char *key;
size_t nkey;
unsigned int flags;
int32_t exptime_int = 0;
time_t exptime;
int vlen;
uint64_t req_cas_id=0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags)
&& safe_strtol(tokens[3].value, &exptime_int)
&& safe_strtol(tokens[4].value, (int32_t *)&vlen))) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
/* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */
exptime = exptime_int;
/* Negative exptimes can underflow and end up immortal. realtime() will
immediately expire values that are greater than REALTIME_MAXDELTA, but less
than process_started, so lets aim for that. */
if (exptime < 0)
exptime = REALTIME_MAXDELTA + 1;
// does cas value exist?
if (handle_cas) {
if (!safe_strtoull(tokens[5].value, &req_cas_id)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
if (vlen < 0 || vlen > (INT_MAX - 2)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
vlen += 2;
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, flags, realtime(exptime), vlen);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, flags, vlen)) {
out_string(c, "SERVER_ERROR object too large for cache");
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR out of memory storing object");
status = NO_MEMORY;
}
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, comm, key, nkey, 0, 0);
/* swallow the data line */
c->write_and_go = conn_swallow;
c->sbytes = vlen;
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (comm == NREAD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
STORAGE_delete(c->thread->storage, it);
item_remove(it);
}
}
return;
}
ITEM_set_cas(it, req_cas_id);
c->item = it;
#ifdef NEED_ALIGN
if (it->it_flags & ITEM_CHUNKED) {
c->ritem = ITEM_schunk(it);
} else {
c->ritem = ITEM_data(it);
}
#else
c->ritem = ITEM_data(it);
#endif
c->rlbytes = it->nbytes;
c->cmd = comm;
conn_set_state(c, conn_nread);
}
static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
int32_t exptime_int = 0;
item *it;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtol(tokens[2].value, &exptime_int)) {
out_string(c, "CLIENT_ERROR invalid exptime argument");
return;
}
it = item_touch(key, nkey, realtime(exptime_int), c);
if (it) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.touch_cmds++;
c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "TOUCHED");
item_remove(it);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.touch_cmds++;
c->thread->stats.touch_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
}
static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) {
char temp[INCR_MAX_STORAGE_LEN];
uint64_t delta;
char *key;
size_t nkey;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if (!safe_strtoull(tokens[2].value, &delta)) {
out_string(c, "CLIENT_ERROR invalid numeric delta argument");
return;
}
switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) {
case OK:
out_string(c, temp);
break;
case NON_NUMERIC:
out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value");
break;
case EOM:
out_of_memory(c, "SERVER_ERROR out of memory");
break;
case DELTA_ITEM_NOT_FOUND:
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.incr_misses++;
} else {
c->thread->stats.decr_misses++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
break;
case DELTA_ITEM_CAS_MISMATCH:
break; /* Should never get here */
}
}
/*
* adds a delta value to a numeric item.
*
* c connection requesting the operation
* it item to adjust
* incr true to increment value, false to decrement
* delta amount to adjust value by
* buf buffer for response string
*
* returns a response string to send back to the client.
*/
enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey,
const bool incr, const int64_t delta,
char *buf, uint64_t *cas,
const uint32_t hv) {
char *ptr;
uint64_t value;
int res;
item *it;
it = do_item_get(key, nkey, hv, c, DONT_UPDATE);
if (!it) {
return DELTA_ITEM_NOT_FOUND;
}
/* Can't delta zero byte values. 2-byte are the "\r\n" */
/* Also can't delta for chunked items. Too large to be a number */
#ifdef EXTSTORE
if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) {
#else
if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) {
#endif
do_item_remove(it);
return NON_NUMERIC;
}
if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) {
do_item_remove(it);
return DELTA_ITEM_CAS_MISMATCH;
}
ptr = ITEM_data(it);
if (!safe_strtoull(ptr, &value)) {
do_item_remove(it);
return NON_NUMERIC;
}
if (incr) {
value += delta;
MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value);
} else {
if(delta > value) {
value = 0;
} else {
value -= delta;
}
MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value);
}
pthread_mutex_lock(&c->thread->stats.mutex);
if (incr) {
c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++;
} else {
c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++;
}
pthread_mutex_unlock(&c->thread->stats.mutex);
snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value);
res = strlen(buf);
/* refcount == 2 means we are the only ones holding the item, and it is
* linked. We hold the item's lock in this function, so refcount cannot
* increase. */
if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */
/* When changing the value without replacing the item, we
need to update the CAS on the existing item. */
/* We also need to fiddle it in the sizes tracker in case the tracking
* was enabled at runtime, since it relies on the CAS value to know
* whether to remove an item or not. */
item_stats_sizes_remove(it);
ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0);
item_stats_sizes_add(it);
memcpy(ITEM_data(it), buf, res);
memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2);
do_item_update(it);
} else if (it->refcount > 1) {
item *new_it;
uint32_t flags;
FLAGS_CONV(settings.inline_ascii_response, it, flags);
new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2);
if (new_it == 0) {
do_item_remove(it);
return EOM;
}
memcpy(ITEM_data(new_it), buf, res);
memcpy(ITEM_data(new_it) + res, "\r\n", 2);
item_replace(it, new_it, hv);
// Overwrite the older item's CAS with our new CAS since we're
// returning the CAS of the old item below.
ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0);
do_item_remove(new_it); /* release our reference */
} else {
/* Should never get here. This means we somehow fetched an unlinked
* item. TODO: Add a counter? */
if (settings.verbose) {
fprintf(stderr, "Tried to do incr/decr on invalid item\n");
}
if (it->refcount == 1)
do_item_remove(it);
return DELTA_ITEM_NOT_FOUND;
}
if (cas) {
*cas = ITEM_get_cas(it); /* swap the incoming CAS value */
}
do_item_remove(it); /* release our reference */
return OK;
}
static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) {
char *key;
size_t nkey;
item *it;
uint32_t hv;
assert(c != NULL);
if (ntokens > 3) {
bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0;
bool sets_noreply = set_noreply_maybe(c, tokens, ntokens);
bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply))
|| (ntokens == 5 && hold_is_zero && sets_noreply);
if (!valid) {
out_string(c, "CLIENT_ERROR bad command line format. "
"Usage: delete <key> [noreply]");
return;
}
}
key = tokens[KEY_TOKEN].value;
nkey = tokens[KEY_TOKEN].length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (settings.detail_enabled) {
stats_prefix_record_delete(key, nkey);
}
it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv);
if (it) {
MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++;
pthread_mutex_unlock(&c->thread->stats.mutex);
do_item_unlink(it, hv);
STORAGE_delete(c->thread->storage, it);
do_item_remove(it); /* release our reference */
out_string(c, "DELETED");
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.delete_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
out_string(c, "NOT_FOUND");
}
item_unlock(hv);
}
static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
level = strtoul(tokens[1].value, NULL, 10);
settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level;
out_string(c, "OK");
return;
}
#ifdef MEMCACHED_DEBUG
static void process_misbehave_command(conn *c) {
int allowed = 0;
// try opening new TCP socket
int i = socket(AF_INET, SOCK_STREAM, 0);
if (i != -1) {
allowed++;
close(i);
}
// try executing new commands
i = system("sleep 0");
if (i != -1) {
allowed++;
}
if (allowed) {
out_string(c, "ERROR");
} else {
out_string(c, "OK");
}
}
#endif
static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) {
unsigned int level;
double ratio;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (strcmp(tokens[2].value, "ratio") == 0) {
if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) {
out_string(c, "ERROR");
return;
}
settings.slab_automove_ratio = ratio;
} else {
level = strtoul(tokens[2].value, NULL, 10);
if (level == 0) {
settings.slab_automove = 0;
} else if (level == 1 || level == 2) {
settings.slab_automove = level;
} else {
out_string(c, "ERROR");
return;
}
}
out_string(c, "OK");
return;
}
/* TODO: decide on syntax for sampling? */
static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) {
uint16_t f = 0;
int x;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (ntokens > 2) {
for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) {
if ((strcmp(tokens[x].value, "rawcmds") == 0)) {
f |= LOG_RAWCMDS;
} else if ((strcmp(tokens[x].value, "evictions") == 0)) {
f |= LOG_EVICTIONS;
} else if ((strcmp(tokens[x].value, "fetchers") == 0)) {
f |= LOG_FETCHERS;
} else if ((strcmp(tokens[x].value, "mutations") == 0)) {
f |= LOG_MUTATIONS;
} else if ((strcmp(tokens[x].value, "sysevents") == 0)) {
f |= LOG_SYSEVENTS;
} else {
out_string(c, "ERROR");
return;
}
}
} else {
f |= LOG_FETCHERS;
}
switch(logger_add_watcher(c, c->sfd, f)) {
case LOGGER_ADD_WATCHER_TOO_MANY:
out_string(c, "WATCHER_TOO_MANY log watcher limit reached");
break;
case LOGGER_ADD_WATCHER_FAILED:
out_string(c, "WATCHER_FAILED failed to add log watcher");
break;
case LOGGER_ADD_WATCHER_OK:
conn_set_state(c, conn_watch);
event_del(&c->event);
break;
}
}
static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t memlimit;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (!safe_strtoul(tokens[1].value, &memlimit)) {
out_string(c, "ERROR");
} else {
if (memlimit < 8) {
out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m");
} else {
if (memlimit > 1000000000) {
out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes");
} else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) {
if (settings.verbose > 0) {
fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit);
}
out_string(c, "OK");
} else {
out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust");
}
}
}
}
static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t pct_hot;
uint32_t pct_warm;
double hot_factor;
int32_t ttl;
double factor;
set_noreply_maybe(c, tokens, ntokens);
if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) {
if (!safe_strtoul(tokens[2].value, &pct_hot) ||
!safe_strtoul(tokens[3].value, &pct_warm) ||
!safe_strtod(tokens[4].value, &hot_factor) ||
!safe_strtod(tokens[5].value, &factor)) {
out_string(c, "ERROR");
} else {
if (pct_hot + pct_warm > 80) {
out_string(c, "ERROR hot and warm pcts must not exceed 80");
} else if (factor <= 0 || hot_factor <= 0) {
out_string(c, "ERROR hot/warm age factors must be greater than 0");
} else {
settings.hot_lru_pct = pct_hot;
settings.warm_lru_pct = pct_warm;
settings.hot_max_factor = hot_factor;
settings.warm_max_factor = factor;
out_string(c, "OK");
}
}
} else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 3 &&
settings.lru_maintainer_thread) {
if (strcmp(tokens[2].value, "flat") == 0) {
settings.lru_segmented = false;
out_string(c, "OK");
} else if (strcmp(tokens[2].value, "segmented") == 0) {
settings.lru_segmented = true;
out_string(c, "OK");
} else {
out_string(c, "ERROR");
}
} else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 3 &&
settings.lru_maintainer_thread) {
if (!safe_strtol(tokens[2].value, &ttl)) {
out_string(c, "ERROR");
} else {
if (ttl < 0) {
settings.temp_lru = false;
} else {
settings.temp_lru = true;
settings.temporary_ttl = ttl;
}
out_string(c, "OK");
}
} else {
out_string(c, "ERROR");
}
}
#ifdef EXTSTORE
static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) {
set_noreply_maybe(c, tokens, ntokens);
bool ok = true;
if (ntokens < 4) {
ok = false;
} else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) {
/* per-slab-class free chunk setting. */
unsigned int clsid = 0;
unsigned int limit = 0;
if (!safe_strtoul(tokens[2].value, &clsid) ||
!safe_strtoul(tokens[3].value, &limit)) {
ok = false;
} else {
if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) {
settings.ext_free_memchunks[clsid] = limit;
} else {
ok = false;
}
}
} else if (strcmp(tokens[1].value, "item_size") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_item_size))
ok = false;
} else if (strcmp(tokens[1].value, "item_age") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_item_age))
ok = false;
} else if (strcmp(tokens[1].value, "low_ttl") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl))
ok = false;
} else if (strcmp(tokens[1].value, "recache_rate") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate))
ok = false;
} else if (strcmp(tokens[1].value, "compact_under") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under))
ok = false;
} else if (strcmp(tokens[1].value, "drop_under") == 0) {
if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under))
ok = false;
} else if (strcmp(tokens[1].value, "max_frag") == 0) {
if (!safe_strtod(tokens[2].value, &settings.ext_max_frag))
ok = false;
} else if (strcmp(tokens[1].value, "drop_unread") == 0) {
unsigned int v;
if (!safe_strtoul(tokens[2].value, &v)) {
ok = false;
} else {
settings.ext_drop_unread = v == 0 ? false : true;
}
} else {
ok = false;
}
if (!ok) {
out_string(c, "ERROR");
} else {
out_string(c, "OK");
}
}
#endif
static void process_command(conn *c, char *command) {
token_t tokens[MAX_TOKENS];
size_t ntokens;
int comm;
assert(c != NULL);
MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes);
if (settings.verbose > 1)
fprintf(stderr, "<%d %s\n", c->sfd, command);
/*
* for commands set/add/replace, we build an item and read the data
* directly into it, then continue in nread_complete().
*/
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_of_memory(c, "SERVER_ERROR out of memory preparing response");
return;
}
ntokens = tokenize_command(command, tokens, MAX_TOKENS);
if (ntokens >= 3 &&
((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) ||
(strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) {
process_get_command(c, tokens, ntokens, false, false);
} else if ((ntokens == 6 || ntokens == 7) &&
((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) ||
(strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) {
process_update_command(c, tokens, ntokens, comm, false);
} else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) {
process_update_command(c, tokens, ntokens, comm, true);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 1);
} else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) {
process_get_command(c, tokens, ntokens, true, false);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) {
process_arithmetic_command(c, tokens, ntokens, 0);
} else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) {
process_delete_command(c, tokens, ntokens);
} else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) {
process_touch_command(c, tokens, ntokens);
} else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) {
process_get_command(c, tokens, ntokens, false, true);
} else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) {
process_get_command(c, tokens, ntokens, true, true);
} else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) {
process_stat(c, tokens, ntokens);
} else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) {
time_t exptime = 0;
rel_time_t new_oldest = 0;
set_noreply_maybe(c, tokens, ntokens);
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.flush_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (!settings.flush_enabled) {
// flush_all is not allowed but we log it on stats
out_string(c, "CLIENT_ERROR flush_all not allowed");
return;
}
if (ntokens != (c->noreply ? 3 : 2)) {
exptime = strtol(tokens[1].value, NULL, 10);
if(errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
}
/*
If exptime is zero realtime() would return zero too, and
realtime(exptime) - 1 would overflow to the max unsigned
value. So we process exptime == 0 the same way we do when
no delay is given at all.
*/
if (exptime > 0) {
new_oldest = realtime(exptime);
} else { /* exptime == 0 */
new_oldest = current_time;
}
if (settings.use_cas) {
settings.oldest_live = new_oldest - 1;
if (settings.oldest_live <= current_time)
settings.oldest_cas = get_cas_id();
} else {
settings.oldest_live = new_oldest;
}
out_string(c, "OK");
return;
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) {
out_string(c, "VERSION " VERSION);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) {
conn_set_state(c, conn_closing);
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) {
if (settings.shutdown_command) {
conn_set_state(c, conn_closing);
raise(SIGINT);
} else {
out_string(c, "ERROR: shutdown not enabled");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) {
if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) {
int src, dst, rv;
if (settings.slab_reassign == false) {
out_string(c, "CLIENT_ERROR slab reassignment disabled");
return;
}
src = strtol(tokens[2].value, NULL, 10);
dst = strtol(tokens[3].value, NULL, 10);
if (errno == ERANGE) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
rv = slabs_reassign(src, dst);
switch (rv) {
case REASSIGN_OK:
out_string(c, "OK");
break;
case REASSIGN_RUNNING:
out_string(c, "BUSY currently processing reassign request");
break;
case REASSIGN_BADCLASS:
out_string(c, "BADCLASS invalid src or dst class id");
break;
case REASSIGN_NOSPARE:
out_string(c, "NOSPARE source class has no spare pages");
break;
case REASSIGN_SRC_DST_SAME:
out_string(c, "SAME src and dst class are identical");
break;
}
return;
} else if (ntokens >= 4 &&
(strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) {
process_slabs_automove_command(c, tokens, ntokens);
} else {
out_string(c, "ERROR");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) {
if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) {
int rv;
if (settings.lru_crawler == false) {
out_string(c, "CLIENT_ERROR lru crawler disabled");
return;
}
rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0,
settings.lru_crawler_tocrawl);
switch(rv) {
case CRAWLER_OK:
out_string(c, "OK");
break;
case CRAWLER_RUNNING:
out_string(c, "BUSY currently processing crawler request");
break;
case CRAWLER_BADCLASS:
out_string(c, "BADCLASS invalid class id");
break;
case CRAWLER_NOTSTARTED:
out_string(c, "NOTSTARTED no items to crawl");
break;
case CRAWLER_ERROR:
out_string(c, "ERROR an unknown error happened");
break;
}
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) {
if (settings.lru_crawler == false) {
out_string(c, "CLIENT_ERROR lru crawler disabled");
return;
}
if (!settings.dump_enabled) {
out_string(c, "ERROR metadump not allowed");
return;
}
int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP,
c, c->sfd, LRU_CRAWLER_CAP_REMAINING);
switch(rv) {
case CRAWLER_OK:
out_string(c, "OK");
// TODO: Don't reuse conn_watch here.
conn_set_state(c, conn_watch);
event_del(&c->event);
break;
case CRAWLER_RUNNING:
out_string(c, "BUSY currently processing crawler request");
break;
case CRAWLER_BADCLASS:
out_string(c, "BADCLASS invalid class id");
break;
case CRAWLER_NOTSTARTED:
out_string(c, "NOTSTARTED no items to crawl");
break;
case CRAWLER_ERROR:
out_string(c, "ERROR an unknown error happened");
break;
}
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) {
uint32_t tocrawl;
if (!safe_strtoul(tokens[2].value, &tocrawl)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
settings.lru_crawler_tocrawl = tocrawl;
out_string(c, "OK");
return;
} else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) {
uint32_t tosleep;
if (!safe_strtoul(tokens[2].value, &tosleep)) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
if (tosleep > 1000000) {
out_string(c, "CLIENT_ERROR sleep must be one second or less");
return;
}
settings.lru_crawler_sleep = tosleep;
out_string(c, "OK");
return;
} else if (ntokens == 3) {
if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) {
if (start_item_crawler_thread() == 0) {
out_string(c, "OK");
} else {
out_string(c, "ERROR failed to start lru crawler thread");
}
} else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) {
if (stop_item_crawler_thread() == 0) {
out_string(c, "OK");
} else {
out_string(c, "ERROR failed to stop lru crawler thread");
}
} else {
out_string(c, "ERROR");
}
return;
} else {
out_string(c, "ERROR");
}
} else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) {
process_watch_command(c, tokens, ntokens);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) {
process_memlimit_command(c, tokens, ntokens);
} else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) {
process_verbosity_command(c, tokens, ntokens);
} else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) {
process_lru_command(c, tokens, ntokens);
#ifdef MEMCACHED_DEBUG
// commands which exist only for testing the memcached's security protection
} else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) {
process_misbehave_command(c);
#endif
#ifdef EXTSTORE
} else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) {
process_extstore_command(c, tokens, ntokens);
#endif
#ifdef TLS
} else if (ntokens == 2 && strcmp(tokens[COMMAND_TOKEN].value, "refresh_certs") == 0) {
set_noreply_maybe(c, tokens, ntokens);
char *errmsg = NULL;
if (refresh_certs(&errmsg)) {
out_string(c, "OK");
} else {
write_and_free(c, errmsg, strlen(errmsg));
}
return;
#endif
} else {
if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) {
conn_set_state(c, conn_closing);
} else {
out_string(c, "ERROR");
}
}
return;
}
/*
* if we have a complete line in the buffer, process it.
*/
static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_of_memory(c,
"SERVER_ERROR Out of memory allocating headers");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (ptr - c->rcurr > 100 ||
(strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
c->last_cmd_time = current_time;
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
/*
* read a UDP request.
*/
static enum try_read_result try_read_udp(conn *c) {
int res;
assert(c != NULL);
c->request_addr_size = sizeof(c->request_addr);
res = recvfrom(c->sfd, c->rbuf, c->rsize,
0, (struct sockaddr *)&c->request_addr,
&c->request_addr_size);
if (res > 8) {
unsigned char *buf = (unsigned char *)c->rbuf;
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* Beginning of UDP packet is the request ID; save it. */
c->request_id = buf[0] * 256 + buf[1];
/* If this is a multi-packet request, drop it. */
if (buf[4] != 0 || buf[5] != 1) {
out_string(c, "SERVER_ERROR multi-packet request not supported");
return READ_NO_DATA_RECEIVED;
}
/* Don't care about any of the rest of the header. */
res -= 8;
memmove(c->rbuf, c->rbuf + 8, res);
c->rbytes = res;
c->rcurr = c->rbuf;
return READ_DATA_RECEIVED;
}
return READ_NO_DATA_RECEIVED;
}
/*
* read from network as much as we can, handle buffer overflow and connection
* close.
* before reading, move the remaining incomplete fragment of a command
* (if any) to the beginning of the buffer.
*
* To protect us from someone flooding a connection with bogus data causing
* the connection to eat up all available memory, break out and start looking
* at the data I've got after a number of reallocs...
*
* @return enum try_read_result
*/
static enum try_read_result try_read_network(conn *c) {
enum try_read_result gotdata = READ_NO_DATA_RECEIVED;
int res;
int num_allocs = 0;
assert(c != NULL);
if (c->rcurr != c->rbuf) {
if (c->rbytes != 0) /* otherwise there's nothing to copy */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
}
while (1) {
if (c->rbytes >= c->rsize) {
if (num_allocs == 4) {
return gotdata;
}
++num_allocs;
char *new_rbuf = realloc(c->rbuf, c->rsize * 2);
if (!new_rbuf) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
if (settings.verbose > 0) {
fprintf(stderr, "Couldn't realloc input buffer\n");
}
c->rbytes = 0; /* ignore what we read */
out_of_memory(c, "SERVER_ERROR out of memory reading request");
c->write_and_go = conn_closing;
return READ_MEMORY_ERROR;
}
c->rcurr = c->rbuf = new_rbuf;
c->rsize *= 2;
}
int avail = c->rsize - c->rbytes;
res = c->read(c, c->rbuf + c->rbytes, avail);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
gotdata = READ_DATA_RECEIVED;
c->rbytes += res;
if (res == avail) {
continue;
} else {
break;
}
}
if (res == 0) {
return READ_ERROR;
}
if (res == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return READ_ERROR;
}
}
return gotdata;
}
static bool update_event(conn *c, const int new_flags) {
assert(c != NULL);
struct event_base *base = c->event.ev_base;
if (c->ev_flags == new_flags)
return true;
if (event_del(&c->event) == -1) return false;
event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c);
event_base_set(base, &c->event);
c->ev_flags = new_flags;
if (event_add(&c->event, 0) == -1) return false;
return true;
}
/*
* Sets whether we are listening for new connections or not.
*/
void do_accept_new_conns(const bool do_accept) {
conn *next;
for (next = listen_conn; next; next = next->next) {
if (do_accept) {
update_event(next, EV_READ | EV_PERSIST);
if (listen(next->sfd, settings.backlog) != 0) {
perror("listen");
}
}
else {
update_event(next, 0);
if (listen(next->sfd, 0) != 0) {
perror("listen");
}
}
}
if (do_accept) {
struct timeval maxconns_exited;
uint64_t elapsed_us;
gettimeofday(&maxconns_exited,NULL);
STATS_LOCK();
elapsed_us =
(maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000
+ (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec);
stats.time_in_listen_disabled_us += elapsed_us;
stats_state.accepting_conns = true;
STATS_UNLOCK();
} else {
STATS_LOCK();
stats_state.accepting_conns = false;
gettimeofday(&stats.maxconns_entered,NULL);
stats.listen_disabled_num++;
STATS_UNLOCK();
allow_new_conns = false;
maxconns_handler(-42, 0, 0);
}
}
/*
* Transmit the next chunk of data from our list of msgbuf structures.
*
* Returns:
* TRANSMIT_COMPLETE All done writing.
* TRANSMIT_INCOMPLETE More data remaining to write.
* TRANSMIT_SOFT_ERROR Can't write any more right now.
* TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
*/
static enum transmit_result transmit(conn *c) {
assert(c != NULL);
if (c->msgcurr < c->msgused &&
c->msglist[c->msgcurr].msg_iovlen == 0) {
/* Finished writing the current msg; advance to the next. */
c->msgcurr++;
}
if (c->msgcurr < c->msgused) {
ssize_t res;
struct msghdr *m = &c->msglist[c->msgcurr];
res = c->sendmsg(c, m, 0);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_written += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
/* We've written some of the data. Remove the completed
iovec entries from the list of pending writes. */
while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) {
res -= m->msg_iov->iov_len;
m->msg_iovlen--;
m->msg_iov++;
}
/* Might have written just part of the last iovec entry;
adjust it so the next write will do the rest. */
if (res > 0) {
m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res;
m->msg_iov->iov_len -= res;
}
return TRANSMIT_INCOMPLETE;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
}
return TRANSMIT_SOFT_ERROR;
}
/* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK,
we have a real error, on which we close the connection */
if (settings.verbose > 0)
perror("Failed to write, and not due to blocking");
if (IS_UDP(c->transport))
conn_set_state(c, conn_read);
else
conn_set_state(c, conn_closing);
return TRANSMIT_HARD_ERROR;
} else {
return TRANSMIT_COMPLETE;
}
}
/* Does a looped read to fill data chunks */
/* TODO: restrict number of times this can loop.
* Also, benchmark using readv's.
*/
static int read_into_chunked_item(conn *c) {
int total = 0;
int res;
assert(c->rcurr != c->ritem);
while (c->rlbytes > 0) {
item_chunk *ch = (item_chunk *)c->ritem;
if (ch->size == ch->used) {
// FIXME: ch->next is currently always 0. remove this?
if (ch->next) {
c->ritem = (char *) ch->next;
} else {
/* Allocate next chunk. Binary protocol needs 2b for \r\n */
c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes +
((c->protocol == binary_prot) ? 2 : 0));
if (!c->ritem) {
// We failed an allocation. Let caller handle cleanup.
total = -2;
break;
}
// ritem has new chunk, restart the loop.
continue;
//assert(c->rlbytes == 0);
}
}
int unused = ch->size - ch->used;
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
total = 0;
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
tocopy = tocopy > unused ? unused : tocopy;
if (c->ritem != c->rcurr) {
memmove(ch->data + ch->used, c->rcurr, tocopy);
}
total += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
ch->used += tocopy;
if (c->rlbytes == 0) {
break;
}
} else {
/* now try reading from the socket */
res = c->read(c, ch->data + ch->used,
(unused > c->rlbytes ? c->rlbytes : unused));
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
ch->used += res;
total += res;
c->rlbytes -= res;
} else {
/* Reset total to the latest result so caller can handle it */
total = res;
break;
}
}
}
/* At some point I will be able to ditch the \r\n from item storage and
remove all of these kludges.
The above binprot check ensures inline space for \r\n, but if we do
exactly enough allocs there will be no additional chunk for \r\n.
*/
if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) {
item_chunk *ch = (item_chunk *)c->ritem;
if (ch->size - ch->used < 2) {
c->ritem = (char *) do_item_alloc_chunk(ch, 2);
if (!c->ritem) {
total = -2;
}
}
}
return total;
}
static void drive_machine(conn *c) {
bool stop = false;
int sfd;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
const char *str;
#ifdef HAVE_ACCEPT4
static int use_accept4 = 1;
#else
static int use_accept4 = 0;
#endif
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
#ifdef HAVE_ACCEPT4
if (use_accept4) {
sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK);
} else {
sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen);
}
#else
sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen);
#endif
if (sfd == -1) {
if (use_accept4 && errno == ENOSYS) {
use_accept4 = 0;
continue;
}
perror(use_accept4 ? "accept4()" : "accept()");
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if (!use_accept4) {
if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
}
if (settings.maxconns_fast &&
stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) {
str = "ERROR Too many open connections\r\n";
res = write(sfd, str, strlen(str));
close(sfd);
STATS_LOCK();
stats.rejected_conns++;
STATS_UNLOCK();
} else {
void *ssl_v = NULL;
#ifdef TLS
SSL *ssl = NULL;
if (c->ssl_enabled) {
assert(IS_TCP(c->transport) && settings.ssl_enabled);
if (settings.ssl_ctx == NULL) {
if (settings.verbose) {
fprintf(stderr, "SSL context is not initialized\n");
}
close(sfd);
break;
}
SSL_LOCK();
ssl = SSL_new(settings.ssl_ctx);
SSL_UNLOCK();
if (ssl == NULL) {
if (settings.verbose) {
fprintf(stderr, "Failed to created the SSL object\n");
}
close(sfd);
break;
}
SSL_set_fd(ssl, sfd);
int ret = SSL_accept(ssl);
if (ret < 0) {
int err = SSL_get_error(ssl, ret);
if (err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL) {
if (settings.verbose) {
fprintf(stderr, "SSL connection failed with error code : %d : %s\n", err, strerror(errno));
}
close(sfd);
break;
}
}
}
ssl_v = (void*) ssl;
#endif
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, c->transport, ssl_v);
}
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* Check if rbytes < 0, to prevent crash */
if (c->rlbytes < 0) {
if (settings.verbose) {
fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes);
}
conn_set_state(c, conn_closing);
break;
}
if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) {
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = c->read(c, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
} else {
res = read_into_chunked_item(c);
if (res > 0)
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* Memory allocation failure */
if (res == -2) {
out_of_memory(c, "SERVER_ERROR Out of memory during read");
c->sbytes = c->rlbytes;
c->write_and_go = conn_swallow;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes <= 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = c->read(c, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
#ifdef EXTSTORE
/* have side IO's that must process before transmit() can run.
* remove the connection from the worker thread and dispatch the
* IO queue
*/
if (c->io_wrapleft) {
assert(c->io_queued == false);
assert(c->io_wraplist != NULL);
// TODO: create proper state for this condition
conn_set_state(c, conn_watch);
event_del(&c->event);
c->io_queued = true;
extstore_submit(c->thread->storage, &c->io_wraplist->io);
stop = true;
break;
}
#endif
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
conn_release_items(c);
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_closed:
/* This only happens if dormando is an idiot. */
abort();
break;
case conn_watch:
/* We handed off our connection to the logger thread. */
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
}
void event_handler(const int fd, const short which, void *arg) {
conn *c;
c = (conn *)arg;
assert(c != NULL);
c->which = which;
/* sanity */
if (fd != c->sfd) {
if (settings.verbose > 0)
fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n");
conn_close(c);
return;
}
drive_machine(c);
/* wait for next event */
return;
}
static int new_socket(struct addrinfo *ai) {
int sfd;
int flags;
if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
/*
* Sets a socket's send buffer size to the maximum allowed by the system.
*/
static void maximize_sndbuf(const int sfd) {
socklen_t intsize = sizeof(int);
int last_good = 0;
int min, max, avg;
int old_size;
/* Start with the default size. */
if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) {
if (settings.verbose > 0)
perror("getsockopt(SO_SNDBUF)");
return;
}
/* Binary-search for the real maximum. */
min = old_size;
max = MAX_SENDBUF_SIZE;
while (min <= max) {
avg = ((unsigned int)(min + max)) / 2;
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) {
last_good = avg;
min = avg + 1;
} else {
max = avg - 1;
}
}
if (settings.verbose > 1)
fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good);
}
/**
* Create a socket and bind it to a specific port number
* @param interface the interface to bind to
* @param port the port number to bind to
* @param transport the transport protocol (TCP / UDP)
* @param portnumber_file A filepointer to write the port numbers to
* when they are successfully added to the list of ports we
* listen on.
*/
static int server_socket(const char *interface,
int port,
enum network_transport transport,
FILE *portnumber_file, bool ssl_enabled) {
int sfd;
struct linger ling = {0, 0};
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = { .ai_flags = AI_PASSIVE,
.ai_family = AF_UNSPEC };
char port_buf[NI_MAXSERV];
int error;
int success = 0;
int flags =1;
hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM;
if (port == -1) {
port = 0;
}
snprintf(port_buf, sizeof(port_buf), "%d", port);
error= getaddrinfo(interface, port_buf, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM)
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
else
perror("getaddrinfo()");
return 1;
}
for (next= ai; next; next= next->ai_next) {
conn *listen_conn_add;
if ((sfd = new_socket(next)) == -1) {
/* getaddrinfo can return "junk" addresses,
* we make sure at least one works before erroring.
*/
if (errno == EMFILE) {
/* ...unless we're out of fds */
perror("server_socket");
exit(EX_OSERR);
}
continue;
}
#ifdef IPV6_V6ONLY
if (next->ai_family == AF_INET6) {
error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags));
if (error != 0) {
perror("setsockopt");
close(sfd);
continue;
}
}
#endif
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
if (IS_UDP(transport)) {
maximize_sndbuf(sfd);
} else {
error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
if (error != 0)
perror("setsockopt");
error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
if (error != 0)
perror("setsockopt");
}
if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
if (errno != EADDRINUSE) {
perror("bind()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
close(sfd);
continue;
} else {
success++;
if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
freeaddrinfo(ai);
return 1;
}
if (portnumber_file != NULL &&
(next->ai_addr->sa_family == AF_INET ||
next->ai_addr->sa_family == AF_INET6)) {
union {
struct sockaddr_in in;
struct sockaddr_in6 in6;
} my_sockaddr;
socklen_t len = sizeof(my_sockaddr);
if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
if (next->ai_addr->sa_family == AF_INET) {
fprintf(portnumber_file, "%s INET: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in.sin_port));
} else {
fprintf(portnumber_file, "%s INET6: %u\n",
IS_UDP(transport) ? "UDP" : "TCP",
ntohs(my_sockaddr.in6.sin6_port));
}
}
}
}
if (IS_UDP(transport)) {
int c;
for (c = 0; c < settings.num_threads_per_udp; c++) {
/* Allocate one UDP file descriptor per worker thread;
* this allows "stats conns" to separately list multiple
* parallel UDP requests in progress.
*
* The dispatch code round-robins new connection requests
* among threads, so this is guaranteed to assign one
* FD to each thread.
*/
int per_thread_fd = c ? dup(sfd) : sfd;
dispatch_conn_new(per_thread_fd, conn_read,
EV_READ | EV_PERSIST,
UDP_READ_BUFFER_SIZE, transport, NULL);
}
} else {
if (!(listen_conn_add = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
transport, main_base, NULL))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
#ifdef TLS
listen_conn_add->ssl_enabled = ssl_enabled;
#else
assert(ssl_enabled == false);
#endif
listen_conn_add->next = listen_conn;
listen_conn = listen_conn_add;
}
}
freeaddrinfo(ai);
/* Return zero iff we detected no errors in starting up connections */
return success == 0;
}
static int server_sockets(int port, enum network_transport transport,
FILE *portnumber_file) {
bool ssl_enabled = false;
#ifdef TLS
const char *notls = "notls";
ssl_enabled = settings.ssl_enabled;
#endif
if (settings.inter == NULL) {
return server_socket(settings.inter, port, transport, portnumber_file, ssl_enabled);
} else {
// tokenize them and bind to each one of them..
char *b;
int ret = 0;
char *list = strdup(settings.inter);
if (list == NULL) {
fprintf(stderr, "Failed to allocate memory for parsing server interface string\n");
return 1;
}
for (char *p = strtok_r(list, ";,", &b);
p != NULL;
p = strtok_r(NULL, ";,", &b)) {
int the_port = port;
#ifdef TLS
ssl_enabled = settings.ssl_enabled;
// "notls" option is valid only when memcached is run with SSL enabled.
if (strncmp(p, notls, strlen(notls)) == 0) {
if (!settings.ssl_enabled) {
fprintf(stderr, "'notls' option is valid only when SSL is enabled\n");
return 1;
}
ssl_enabled = false;
p += strlen(notls) + 1;
}
#endif
char *h = NULL;
if (*p == '[') {
// expecting it to be an IPv6 address enclosed in []
// i.e. RFC3986 style recommended by RFC5952
char *e = strchr(p, ']');
if (e == NULL) {
fprintf(stderr, "Invalid IPV6 address: \"%s\"", p);
free(list);
return 1;
}
h = ++p; // skip the opening '['
*e = '\0';
p = ++e; // skip the closing ']'
}
char *s = strchr(p, ':');
if (s != NULL) {
// If no more semicolons - attempt to treat as port number.
// Otherwise the only valid option is an unenclosed IPv6 without port, until
// of course there was an RFC3986 IPv6 address previously specified -
// in such a case there is no good option, will just send it to fail as port number.
if (strchr(s + 1, ':') == NULL || h != NULL) {
*s = '\0';
++s;
if (!safe_strtol(s, &the_port)) {
fprintf(stderr, "Invalid port number: \"%s\"", s);
free(list);
return 1;
}
}
}
if (h != NULL)
p = h;
if (strcmp(p, "*") == 0) {
p = NULL;
}
ret |= server_socket(p, the_port, transport, portnumber_file, ssl_enabled);
}
free(list);
return ret;
}
}
static int new_socket_unix(void) {
int sfd;
int flags;
if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket()");
return -1;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
return -1;
}
return sfd;
}
static int server_socket_unix(const char *path, int access_mask) {
int sfd;
struct linger ling = {0, 0};
struct sockaddr_un addr;
struct stat tstat;
int flags =1;
int old_umask;
if (!path) {
return 1;
}
if ((sfd = new_socket_unix()) == -1) {
return 1;
}
/*
* Clean up a previous socket file if we left it around
*/
if (lstat(path, &tstat) == 0) {
if (S_ISSOCK(tstat.st_mode))
unlink(path);
}
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/*
* the memset call clears nonstandard fields in some implementations
* that otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
assert(strcmp(addr.sun_path, path) == 0);
old_umask = umask( ~(access_mask&0777));
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind()");
close(sfd);
umask(old_umask);
return 1;
}
umask(old_umask);
if (listen(sfd, settings.backlog) == -1) {
perror("listen()");
close(sfd);
return 1;
}
if (!(listen_conn = conn_new(sfd, conn_listening,
EV_READ | EV_PERSIST, 1,
local_transport, main_base, NULL))) {
fprintf(stderr, "failed to create listening connection\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*
* We keep the current time of day in a global variable that's updated by a
* timer event. This saves us a bunch of time() system calls (we really only
* need to get the time once a second, whereas there can be tens of thousands
* of requests a second) and allows us to use server-start-relative timestamps
* rather than absolute UNIX timestamps, a space savings on systems where
* sizeof(time_t) > sizeof(unsigned int).
*/
volatile rel_time_t current_time;
static struct event clockevent;
/* libevent uses a monotonic clock when available for event scheduling. Aside
* from jitter, simply ticking our internal timer here is accurate enough.
* Note that users who are setting explicit dates for expiration times *must*
* ensure their clocks are correct before starting memcached. */
static void clock_handler(const int fd, const short which, void *arg) {
struct timeval t = {.tv_sec = 1, .tv_usec = 0};
static bool initialized = false;
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
static bool monotonic = false;
static time_t monotonic_start;
#endif
if (initialized) {
/* only delete the event if it's actually there. */
evtimer_del(&clockevent);
} else {
initialized = true;
/* process_started is initialized to time() - 2. We initialize to 1 so
* flush_all won't underflow during tests. */
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
monotonic = true;
monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2;
}
#endif
}
// While we're here, check for hash table expansion.
// This function should be quick to avoid delaying the timer.
assoc_start_expand(stats_state.curr_items);
evtimer_set(&clockevent, clock_handler, 0);
event_base_set(main_base, &clockevent);
evtimer_add(&clockevent, &t);
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
if (monotonic) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
return;
current_time = (rel_time_t) (ts.tv_sec - monotonic_start);
return;
}
#endif
{
struct timeval tv;
gettimeofday(&tv, NULL);
current_time = (rel_time_t) (tv.tv_sec - process_started);
}
}
static void usage(void) {
printf(PACKAGE " " VERSION "\n");
printf("-p, --port=<num> TCP port to listen on (default: 11211)\n"
"-U, --udp-port=<num> UDP port to listen on (default: 0, off)\n"
"-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n"
"-A, --enable-shutdown enable ascii \"shutdown\" command\n"
"-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n"
"-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n"
#ifdef TLS
" if TLS/SSL is enabled, 'notls' prefix can be used to\n"
" disable for specific listeners (-l notls:<ip>:<port>) \n"
#endif
"-d, --daemon run as a daemon\n"
"-r, --enable-coredumps maximize core file limit\n"
"-u, --user=<user> assume identity of <username> (only when run as root)\n"
"-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n"
"-M, --disable-evictions return error on memory exhausted instead of evicting\n"
"-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n"
"-k, --lock-memory lock down all paged memory\n"
"-v, --verbose verbose (print errors/warnings while in event loop)\n"
"-vv very verbose (also print client commands/responses)\n"
"-vvv extremely verbose (internal state transitions)\n"
"-h, --help print this help and exit\n"
"-i, --license print memcached and libevent license\n"
"-V, --version print version and exit\n"
"-P, --pidfile=<file> save PID in <file>, only used with -d option\n"
"-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n"
"-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n");
printf("-L, --enable-largepages try to use large memory pages (if available)\n");
printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n"
" This is used for per-prefix stats reporting. The default is\n"
" \":\" (colon). If this option is specified, stats collection\n"
" is turned on automatically; if not, then it may be turned on\n"
" by sending the \"stats detail on\" command to the server.\n");
printf("-t, --threads=<num> number of threads to use (default: 4)\n");
printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n"
" requests processed per connection to prevent \n"
" starvation (default: 20)\n");
printf("-C, --disable-cas disable use of CAS\n");
printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n");
printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n");
printf("-I, --max-item-size=<num> adjusts max item size\n"
" (default: 1mb, min: 1k, max: 128m)\n");
#ifdef ENABLE_SASL
printf("-S, --enable-sasl turn on Sasl authentication\n");
#endif
printf("-F, --disable-flush-all disable flush_all command\n");
printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n");
#ifdef TLS
printf("-Z, --enable-ssl enable TLS/SSL\n");
#endif
printf("-o, --extended comma separated list of extended options\n"
" most options have a 'no_' prefix to disable\n"
" - maxconns_fast: immediately close new connections after limit\n"
" - hashpower: an integer multiplier for how large the hash\n"
" table should be. normally grows at runtime.\n"
" set based on \"STAT hash_power_level\"\n"
" - tail_repair_time: time in seconds for how long to wait before\n"
" forcefully killing LRU tail item.\n"
" disabled by default; very dangerous option.\n"
" - hash_algorithm: the hash table algorithm\n"
" default is murmur3 hash. options: jenkins, murmur3\n"
" - lru_crawler: enable LRU Crawler background thread\n"
" - lru_crawler_sleep: microseconds to sleep between items\n"
" default is 100.\n"
" - lru_crawler_tocrawl: max items to crawl per slab per run\n"
" default is 0 (unlimited)\n"
" - lru_maintainer: enable new LRU system + background thread\n"
" - hot_lru_pct: pct of slab memory to reserve for hot lru.\n"
" (requires lru_maintainer)\n"
" - warm_lru_pct: pct of slab memory to reserve for warm lru.\n"
" (requires lru_maintainer)\n"
" - hot_max_factor: items idle > cold lru age * drop from hot lru.\n"
" - warm_max_factor: items idle > cold lru age * this drop from warm.\n"
" - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n"
" (requires lru_maintainer)\n"
" - idle_timeout: timeout for idle connections\n"
" - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n"
" - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n"
" - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n"
" read by background thread, then written to watchers.\n"
" - track_sizes: enable dynamic reports for 'stats sizes' command.\n"
" - no_inline_ascii_resp: save up to 24 bytes per item.\n"
" small perf hit in ASCII, no perf difference in\n"
" binary protocol. speeds up all sets.\n"
" - no_hashexpand: disables hash table expansion (dangerous)\n"
" - modern: enables options which will be default in future.\n"
" currently: nothing\n"
" - no_modern: uses defaults of previous major version (1.4.x)\n"
#ifdef HAVE_DROP_PRIVILEGES
" - drop_privileges: enable dropping extra syscall privileges\n"
" - no_drop_privileges: disable drop_privileges in case it causes issues with\n"
" some customisation.\n"
#ifdef MEMCACHED_DEBUG
" - relaxed_privileges: Running tests requires extra privileges.\n"
#endif
#endif
#ifdef EXTSTORE
" - ext_path: file to write to for external storage.\n"
" ie: ext_path=/mnt/d1/extstore:1G\n"
" - ext_page_size: size in megabytes of storage pages.\n"
" - ext_wbuf_size: size in megabytes of page write buffers.\n"
" - ext_threads: number of IO threads to run.\n"
" - ext_item_size: store items larger than this (bytes)\n"
" - ext_item_age: store items idle at least this long\n"
" - ext_low_ttl: consider TTLs lower than this specially\n"
" - ext_drop_unread: don't re-write unread values during compaction\n"
" - ext_recache_rate: recache an item every N accesses\n"
" - ext_compact_under: compact when fewer than this many free pages\n"
" - ext_drop_under: drop COLD items when fewer than this many free pages\n"
" - ext_max_frag: max page fragmentation to tolerage\n"
" - slab_automove_freeratio: ratio of memory to hold free as buffer.\n"
" (see doc/storage.txt for more info)\n"
#endif
#ifdef TLS
" - ssl_chain_cert: certificate chain file in PEM format\n"
" - ssl_key: private key, if not part of the -ssl_chain_cert\n"
" - ssl_keyformat: private key format (PEM, DER or ENGINE) PEM default\n"
" - ssl_verify_mode: peer certificate verification mode, default is 0(None).\n"
" valid values are 0(None), 1(Request), 2(Require)\n"
" or 3(Once)\n"
" - ssl_ciphers: specify cipher list to be used\n"
" - ssl_ca_cert: PEM format file of acceptable client CA's\n"
" - ssl_wbuf_size: size in kilobytes of per-connection SSL output buffer\n"
#endif
);
return;
}
static void usage_license(void) {
printf(PACKAGE " " VERSION "\n\n");
printf(
"Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are\n"
"met:\n"
"\n"
" * Redistributions of source code must retain the above copyright\n"
"notice, this list of conditions and the following disclaimer.\n"
"\n"
" * Redistributions in binary form must reproduce the above\n"
"copyright notice, this list of conditions and the following disclaimer\n"
"in the documentation and/or other materials provided with the\n"
"distribution.\n"
"\n"
" * Neither the name of the Danga Interactive nor the names of its\n"
"contributors may be used to endorse or promote products derived from\n"
"this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
"\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
"\n"
"\n"
"This product includes software developed by Niels Provos.\n"
"\n"
"[ libevent ]\n"
"\n"
"Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n"
"All rights reserved.\n"
"\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions\n"
"are met:\n"
"1. Redistributions of source code must retain the above copyright\n"
" notice, this list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright\n"
" notice, this list of conditions and the following disclaimer in the\n"
" documentation and/or other materials provided with the distribution.\n"
"3. All advertising materials mentioning features or use of this software\n"
" must display the following acknowledgement:\n"
" This product includes software developed by Niels Provos.\n"
"4. The name of the author may not be used to endorse or promote products\n"
" derived from this software without specific prior written permission.\n"
"\n"
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n"
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
);
return;
}
static void save_pid(const char *pid_file) {
FILE *fp;
if (access(pid_file, F_OK) == 0) {
if ((fp = fopen(pid_file, "r")) != NULL) {
char buffer[1024];
if (fgets(buffer, sizeof(buffer), fp) != NULL) {
unsigned int pid;
if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) {
fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid);
}
}
fclose(fp);
}
}
/* Create the pid file first with a temporary name, then
* atomically move the file to the real name to avoid a race with
* another process opening the file to read the pid, but finding
* it empty.
*/
char tmp_pid_file[1024];
snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file);
if ((fp = fopen(tmp_pid_file, "w")) == NULL) {
vperror("Could not open the pid file %s for writing", tmp_pid_file);
return;
}
fprintf(fp,"%ld\n", (long)getpid());
if (fclose(fp) == -1) {
vperror("Could not close the pid file %s", tmp_pid_file);
}
if (rename(tmp_pid_file, pid_file) != 0) {
vperror("Could not rename the pid file from %s to %s",
tmp_pid_file, pid_file);
}
}
static void remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
vperror("Could not remove the pid file %s", pid_file);
}
}
static void sig_handler(const int sig) {
printf("Signal handled: %s.\n", strsignal(sig));
exit(EXIT_SUCCESS);
}
#ifndef HAVE_SIGIGNORE
static int sigignore(int sig) {
struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 };
if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) {
return -1;
}
return 0;
}
#endif
/*
* On systems that supports multiple page sizes we may reduce the
* number of TLB-misses by using the biggest available page size
*/
static int enable_large_pages(void) {
#if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL)
int ret = -1;
size_t sizes[32];
int avail = getpagesizes(sizes, 32);
if (avail != -1) {
size_t max = sizes[0];
struct memcntl_mha arg = {0};
int ii;
for (ii = 1; ii < avail; ++ii) {
if (max < sizes[ii]) {
max = sizes[ii];
}
}
arg.mha_flags = 0;
arg.mha_pagesize = max;
arg.mha_cmd = MHA_MAPSIZE_BSSBRK;
if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) {
fprintf(stderr, "Failed to set large pages: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
} else {
ret = 0;
}
} else {
fprintf(stderr, "Failed to get supported pagesizes: %s\n",
strerror(errno));
fprintf(stderr, "Will use default page size\n");
}
return ret;
#elif defined(__linux__) && defined(MADV_HUGEPAGE)
/* check if transparent hugepages is compiled into the kernel */
struct stat st;
int ret = stat("/sys/kernel/mm/transparent_hugepage/enabled", &st);
if (ret || !(st.st_mode & S_IFREG)) {
fprintf(stderr, "Transparent huge pages support not detected.\n");
fprintf(stderr, "Will use default page size.\n");
return -1;
}
return 0;
#elif defined(__FreeBSD__)
int spages;
size_t spagesl = sizeof(spages);
if (sysctlbyname("vm.pmap.pg_ps_enabled", &spages,
&spagesl, NULL, 0) != 0) {
fprintf(stderr, "Could not evaluate the presence of superpages features.");
return -1;
}
if (spages != 1) {
fprintf(stderr, "Superpages support not detected.\n");
fprintf(stderr, "Will use default page size.\n");
return -1;
}
return 0;
#else
return -1;
#endif
}
/**
* Do basic sanity check of the runtime environment
* @return true if no errors found, false if we can't use this env
*/
static bool sanitycheck(void) {
/* One of our biggest problems is old and bogus libevents */
const char *ever = event_get_version();
if (ever != NULL) {
if (strncmp(ever, "1.", 2) == 0) {
/* Require at least 1.3 (that's still a couple of years old) */
if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) {
fprintf(stderr, "You are using libevent %s.\nPlease upgrade to"
" a more recent version (1.3 or newer)\n",
event_get_version());
return false;
}
}
}
return true;
}
static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) {
char *b = NULL;
uint32_t size = 0;
int i = 0;
uint32_t last_size = 0;
if (strlen(s) < 1)
return false;
for (char *p = strtok_r(s, "-", &b);
p != NULL;
p = strtok_r(NULL, "-", &b)) {
if (!safe_strtoul(p, &size) || size < settings.chunk_size
|| size > settings.slab_chunk_size_max) {
fprintf(stderr, "slab size %u is out of valid range\n", size);
return false;
}
if (last_size >= size) {
fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size);
return false;
}
if (size <= last_size + CHUNK_ALIGN_BYTES) {
fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n",
size, CHUNK_ALIGN_BYTES);
return false;
}
slab_sizes[i++] = size;
last_size = size;
if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) {
fprintf(stderr, "too many slab classes specified\n");
return false;
}
}
slab_sizes[i] = 0;
return true;
}
int main (int argc, char **argv) {
int c;
bool lock_memory = false;
bool do_daemonize = false;
bool preallocate = false;
int maxcore = 0;
char *username = NULL;
char *pid_file = NULL;
struct passwd *pw;
struct rlimit rlim;
char *buf;
char unit = '\0';
int size_max = 0;
int retval = EXIT_SUCCESS;
bool protocol_specified = false;
bool tcp_specified = false;
bool udp_specified = false;
bool start_lru_maintainer = true;
bool start_lru_crawler = true;
bool start_assoc_maint = true;
enum hashfunc_type hash_type = MURMUR3_HASH;
uint32_t tocrawl;
uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES];
bool use_slab_sizes = false;
char *slab_sizes_unparsed = NULL;
bool slab_chunk_size_changed = false;
#ifdef EXTSTORE
void *storage = NULL;
struct extstore_conf_file *storage_file = NULL;
struct extstore_conf ext_cf;
#endif
char *subopts, *subopts_orig;
char *subopts_value;
enum {
MAXCONNS_FAST = 0,
HASHPOWER_INIT,
NO_HASHEXPAND,
SLAB_REASSIGN,
SLAB_AUTOMOVE,
SLAB_AUTOMOVE_RATIO,
SLAB_AUTOMOVE_WINDOW,
TAIL_REPAIR_TIME,
HASH_ALGORITHM,
LRU_CRAWLER,
LRU_CRAWLER_SLEEP,
LRU_CRAWLER_TOCRAWL,
LRU_MAINTAINER,
HOT_LRU_PCT,
WARM_LRU_PCT,
HOT_MAX_FACTOR,
WARM_MAX_FACTOR,
TEMPORARY_TTL,
IDLE_TIMEOUT,
WATCHER_LOGBUF_SIZE,
WORKER_LOGBUF_SIZE,
SLAB_SIZES,
SLAB_CHUNK_MAX,
TRACK_SIZES,
NO_INLINE_ASCII_RESP,
MODERN,
NO_MODERN,
NO_CHUNKED_ITEMS,
NO_SLAB_REASSIGN,
NO_SLAB_AUTOMOVE,
NO_MAXCONNS_FAST,
INLINE_ASCII_RESP,
NO_LRU_CRAWLER,
NO_LRU_MAINTAINER,
NO_DROP_PRIVILEGES,
DROP_PRIVILEGES,
#ifdef TLS
SSL_CERT,
SSL_KEY,
SSL_VERIFY_MODE,
SSL_KEYFORM,
SSL_CIPHERS,
SSL_CA_CERT,
SSL_WBUF_SIZE,
#endif
#ifdef MEMCACHED_DEBUG
RELAXED_PRIVILEGES,
#endif
#ifdef EXTSTORE
EXT_PAGE_SIZE,
EXT_WBUF_SIZE,
EXT_THREADS,
EXT_IO_DEPTH,
EXT_PATH,
EXT_ITEM_SIZE,
EXT_ITEM_AGE,
EXT_LOW_TTL,
EXT_RECACHE_RATE,
EXT_COMPACT_UNDER,
EXT_DROP_UNDER,
EXT_MAX_FRAG,
EXT_DROP_UNREAD,
SLAB_AUTOMOVE_FREERATIO,
#endif
};
char *const subopts_tokens[] = {
[MAXCONNS_FAST] = "maxconns_fast",
[HASHPOWER_INIT] = "hashpower",
[NO_HASHEXPAND] = "no_hashexpand",
[SLAB_REASSIGN] = "slab_reassign",
[SLAB_AUTOMOVE] = "slab_automove",
[SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio",
[SLAB_AUTOMOVE_WINDOW] = "slab_automove_window",
[TAIL_REPAIR_TIME] = "tail_repair_time",
[HASH_ALGORITHM] = "hash_algorithm",
[LRU_CRAWLER] = "lru_crawler",
[LRU_CRAWLER_SLEEP] = "lru_crawler_sleep",
[LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl",
[LRU_MAINTAINER] = "lru_maintainer",
[HOT_LRU_PCT] = "hot_lru_pct",
[WARM_LRU_PCT] = "warm_lru_pct",
[HOT_MAX_FACTOR] = "hot_max_factor",
[WARM_MAX_FACTOR] = "warm_max_factor",
[TEMPORARY_TTL] = "temporary_ttl",
[IDLE_TIMEOUT] = "idle_timeout",
[WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size",
[WORKER_LOGBUF_SIZE] = "worker_logbuf_size",
[SLAB_SIZES] = "slab_sizes",
[SLAB_CHUNK_MAX] = "slab_chunk_max",
[TRACK_SIZES] = "track_sizes",
[NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp",
[MODERN] = "modern",
[NO_MODERN] = "no_modern",
[NO_CHUNKED_ITEMS] = "no_chunked_items",
[NO_SLAB_REASSIGN] = "no_slab_reassign",
[NO_SLAB_AUTOMOVE] = "no_slab_automove",
[NO_MAXCONNS_FAST] = "no_maxconns_fast",
[INLINE_ASCII_RESP] = "inline_ascii_resp",
[NO_LRU_CRAWLER] = "no_lru_crawler",
[NO_LRU_MAINTAINER] = "no_lru_maintainer",
[NO_DROP_PRIVILEGES] = "no_drop_privileges",
[DROP_PRIVILEGES] = "drop_privileges",
#ifdef TLS
[SSL_CERT] = "ssl_chain_cert",
[SSL_KEY] = "ssl_key",
[SSL_VERIFY_MODE] = "ssl_verify_mode",
[SSL_KEYFORM] = "ssl_keyformat",
[SSL_CIPHERS] = "ssl_ciphers",
[SSL_CA_CERT] = "ssl_ca_cert",
[SSL_WBUF_SIZE] = "ssl_wbuf_size",
#endif
#ifdef MEMCACHED_DEBUG
[RELAXED_PRIVILEGES] = "relaxed_privileges",
#endif
#ifdef EXTSTORE
[EXT_PAGE_SIZE] = "ext_page_size",
[EXT_WBUF_SIZE] = "ext_wbuf_size",
[EXT_THREADS] = "ext_threads",
[EXT_IO_DEPTH] = "ext_io_depth",
[EXT_PATH] = "ext_path",
[EXT_ITEM_SIZE] = "ext_item_size",
[EXT_ITEM_AGE] = "ext_item_age",
[EXT_LOW_TTL] = "ext_low_ttl",
[EXT_RECACHE_RATE] = "ext_recache_rate",
[EXT_COMPACT_UNDER] = "ext_compact_under",
[EXT_DROP_UNDER] = "ext_drop_under",
[EXT_MAX_FRAG] = "ext_max_frag",
[EXT_DROP_UNREAD] = "ext_drop_unread",
[SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio",
#endif
NULL
};
if (!sanitycheck()) {
return EX_OSERR;
}
/* handle SIGINT, SIGTERM */
signal(SIGINT, sig_handler);
signal(SIGTERM, sig_handler);
/* init settings */
settings_init();
#ifdef EXTSTORE
settings.ext_item_size = 512;
settings.ext_item_age = UINT_MAX;
settings.ext_low_ttl = 0;
settings.ext_recache_rate = 2000;
settings.ext_max_frag = 0.8;
settings.ext_drop_unread = false;
settings.ext_wbuf_size = 1024 * 1024 * 4;
settings.ext_compact_under = 0;
settings.ext_drop_under = 0;
settings.slab_automove_freeratio = 0.01;
ext_cf.page_size = 1024 * 1024 * 64;
ext_cf.wbuf_size = settings.ext_wbuf_size;
ext_cf.io_threadcount = 1;
ext_cf.io_depth = 1;
ext_cf.page_buckets = 4;
ext_cf.wbuf_count = ext_cf.page_buckets;
#endif
/* Run regardless of initializing it later */
init_lru_maintainer();
/* set stderr non-buffering (for running under, say, daemontools) */
setbuf(stderr, NULL);
char *shortopts =
"a:" /* access mask for unix socket */
"A" /* enable admin shutdown command */
"Z" /* enable SSL */
"p:" /* TCP port number to listen on */
"s:" /* unix socket path to listen on */
"U:" /* UDP port number to listen on */
"m:" /* max memory to use for items in megabytes */
"M" /* return error on memory exhausted */
"c:" /* max simultaneous connections */
"k" /* lock down all paged memory */
"hiV" /* help, licence info, version */
"r" /* maximize core file limit */
"v" /* verbose */
"d" /* daemon mode */
"l:" /* interface to listen on */
"u:" /* user identity to run as */
"P:" /* save PID in file */
"f:" /* factor? */
"n:" /* minimum space allocated for key+value+flags */
"t:" /* threads */
"D:" /* prefix delimiter? */
"L" /* Large memory pages */
"R:" /* max requests per event */
"C" /* Disable use of CAS */
"b:" /* backlog queue limit */
"B:" /* Binding protocol */
"I:" /* Max item size */
"S" /* Sasl ON */
"F" /* Disable flush_all */
"X" /* Disable dump commands */
"o:" /* Extended generic options */
;
/* process arguments */
#ifdef HAVE_GETOPT_LONG
const struct option longopts[] = {
{"unix-mask", required_argument, 0, 'a'},
{"enable-shutdown", no_argument, 0, 'A'},
{"enable-ssl", no_argument, 0, 'Z'},
{"port", required_argument, 0, 'p'},
{"unix-socket", required_argument, 0, 's'},
{"udp-port", required_argument, 0, 'U'},
{"memory-limit", required_argument, 0, 'm'},
{"disable-evictions", no_argument, 0, 'M'},
{"conn-limit", required_argument, 0, 'c'},
{"lock-memory", no_argument, 0, 'k'},
{"help", no_argument, 0, 'h'},
{"license", no_argument, 0, 'i'},
{"version", no_argument, 0, 'V'},
{"enable-coredumps", no_argument, 0, 'r'},
{"verbose", optional_argument, 0, 'v'},
{"daemon", no_argument, 0, 'd'},
{"listen", required_argument, 0, 'l'},
{"user", required_argument, 0, 'u'},
{"pidfile", required_argument, 0, 'P'},
{"slab-growth-factor", required_argument, 0, 'f'},
{"slab-min-size", required_argument, 0, 'n'},
{"threads", required_argument, 0, 't'},
{"enable-largepages", no_argument, 0, 'L'},
{"max-reqs-per-event", required_argument, 0, 'R'},
{"disable-cas", no_argument, 0, 'C'},
{"listen-backlog", required_argument, 0, 'b'},
{"protocol", required_argument, 0, 'B'},
{"max-item-size", required_argument, 0, 'I'},
{"enable-sasl", no_argument, 0, 'S'},
{"disable-flush-all", no_argument, 0, 'F'},
{"disable-dumping", no_argument, 0, 'X'},
{"extended", required_argument, 0, 'o'},
{0, 0, 0, 0}
};
int optindex;
while (-1 != (c = getopt_long(argc, argv, shortopts,
longopts, &optindex))) {
#else
while (-1 != (c = getopt(argc, argv, shortopts))) {
#endif
switch (c) {
case 'A':
/* enables "shutdown" command */
settings.shutdown_command = true;
break;
case 'Z':
/* enable secure communication*/
#ifdef TLS
settings.ssl_enabled = true;
#else
fprintf(stderr, "This server is not built with TLS support.\n");
exit(EX_USAGE);
#endif
break;
case 'a':
/* access for unix domain socket, as octal mask (like chmod)*/
settings.access= strtol(optarg,NULL,8);
break;
case 'U':
settings.udpport = atoi(optarg);
udp_specified = true;
break;
case 'p':
settings.port = atoi(optarg);
tcp_specified = true;
break;
case 's':
settings.socketpath = optarg;
break;
case 'm':
settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
break;
case 'M':
settings.evict_to_free = 0;
break;
case 'c':
settings.maxconns = atoi(optarg);
if (settings.maxconns <= 0) {
fprintf(stderr, "Maximum connections must be greater than 0\n");
return 1;
}
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'i':
usage_license();
exit(EXIT_SUCCESS);
case 'V':
printf(PACKAGE " " VERSION "\n");
exit(EXIT_SUCCESS);
case 'k':
lock_memory = true;
break;
case 'v':
settings.verbose++;
break;
case 'l':
if (settings.inter != NULL) {
if (strstr(settings.inter, optarg) != NULL) {
break;
}
size_t len = strlen(settings.inter) + strlen(optarg) + 2;
char *p = malloc(len);
if (p == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
return 1;
}
snprintf(p, len, "%s,%s", settings.inter, optarg);
free(settings.inter);
settings.inter = p;
} else {
settings.inter= strdup(optarg);
}
break;
case 'd':
do_daemonize = true;
break;
case 'r':
maxcore = 1;
break;
case 'R':
settings.reqs_per_event = atoi(optarg);
if (settings.reqs_per_event == 0) {
fprintf(stderr, "Number of requests per event must be greater than 0\n");
return 1;
}
break;
case 'u':
username = optarg;
break;
case 'P':
pid_file = optarg;
break;
case 'f':
settings.factor = atof(optarg);
if (settings.factor <= 1.0) {
fprintf(stderr, "Factor must be greater than 1\n");
return 1;
}
break;
case 'n':
settings.chunk_size = atoi(optarg);
if (settings.chunk_size == 0) {
fprintf(stderr, "Chunk size must be greater than 0\n");
return 1;
}
break;
case 't':
settings.num_threads = atoi(optarg);
if (settings.num_threads <= 0) {
fprintf(stderr, "Number of threads must be greater than 0\n");
return 1;
}
/* There're other problems when you get above 64 threads.
* In the future we should portably detect # of cores for the
* default.
*/
if (settings.num_threads > 64) {
fprintf(stderr, "WARNING: Setting a high number of worker"
"threads is not recommended.\n"
" Set this value to the number of cores in"
" your machine or less.\n");
}
break;
case 'D':
if (! optarg || ! optarg[0]) {
fprintf(stderr, "No delimiter specified\n");
return 1;
}
settings.prefix_delimiter = optarg[0];
settings.detail_enabled = 1;
break;
case 'L' :
if (enable_large_pages() == 0) {
preallocate = true;
} else {
fprintf(stderr, "Cannot enable large pages on this system\n"
"(There is no support as of this version)\n");
return 1;
}
break;
case 'C' :
settings.use_cas = false;
break;
case 'b' :
settings.backlog = atoi(optarg);
break;
case 'B':
protocol_specified = true;
if (strcmp(optarg, "auto") == 0) {
settings.binding_protocol = negotiating_prot;
} else if (strcmp(optarg, "binary") == 0) {
settings.binding_protocol = binary_prot;
} else if (strcmp(optarg, "ascii") == 0) {
settings.binding_protocol = ascii_prot;
} else {
fprintf(stderr, "Invalid value for binding protocol: %s\n"
" -- should be one of auto, binary, or ascii\n", optarg);
exit(EX_USAGE);
}
break;
case 'I':
buf = strdup(optarg);
unit = buf[strlen(buf)-1];
if (unit == 'k' || unit == 'm' ||
unit == 'K' || unit == 'M') {
buf[strlen(buf)-1] = '\0';
size_max = atoi(buf);
if (unit == 'k' || unit == 'K')
size_max *= 1024;
if (unit == 'm' || unit == 'M')
size_max *= 1024 * 1024;
settings.item_size_max = size_max;
} else {
settings.item_size_max = atoi(buf);
}
free(buf);
break;
case 'S': /* set Sasl authentication to true. Default is false */
#ifndef ENABLE_SASL
fprintf(stderr, "This server is not built with SASL support.\n");
exit(EX_USAGE);
#endif
settings.sasl = true;
break;
case 'F' :
settings.flush_enabled = false;
break;
case 'X' :
settings.dump_enabled = false;
break;
case 'o': /* It's sub-opts time! */
subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */
while (*subopts != '\0') {
switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) {
case MAXCONNS_FAST:
settings.maxconns_fast = true;
break;
case HASHPOWER_INIT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for hashpower\n");
return 1;
}
settings.hashpower_init = atoi(subopts_value);
if (settings.hashpower_init < 12) {
fprintf(stderr, "Initial hashtable multiplier of %d is too low\n",
settings.hashpower_init);
return 1;
} else if (settings.hashpower_init > 32) {
fprintf(stderr, "Initial hashtable multiplier of %d is too high\n"
"Choose a value based on \"STAT hash_power_level\" from a running instance\n",
settings.hashpower_init);
return 1;
}
break;
case NO_HASHEXPAND:
start_assoc_maint = false;
break;
case SLAB_REASSIGN:
settings.slab_reassign = true;
break;
case SLAB_AUTOMOVE:
if (subopts_value == NULL) {
settings.slab_automove = 1;
break;
}
settings.slab_automove = atoi(subopts_value);
if (settings.slab_automove < 0 || settings.slab_automove > 2) {
fprintf(stderr, "slab_automove must be between 0 and 2\n");
return 1;
}
break;
case SLAB_AUTOMOVE_RATIO:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_ratio argument\n");
return 1;
}
settings.slab_automove_ratio = atof(subopts_value);
if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) {
fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n");
return 1;
}
break;
case SLAB_AUTOMOVE_WINDOW:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_window argument\n");
return 1;
}
settings.slab_automove_window = atoi(subopts_value);
if (settings.slab_automove_window < 3) {
fprintf(stderr, "slab_automove_window must be > 2\n");
return 1;
}
break;
case TAIL_REPAIR_TIME:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for tail_repair_time\n");
return 1;
}
settings.tail_repair_time = atoi(subopts_value);
if (settings.tail_repair_time < 10) {
fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n");
return 1;
}
break;
case HASH_ALGORITHM:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hash_algorithm argument\n");
return 1;
};
if (strcmp(subopts_value, "jenkins") == 0) {
hash_type = JENKINS_HASH;
} else if (strcmp(subopts_value, "murmur3") == 0) {
hash_type = MURMUR3_HASH;
} else {
fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n");
return 1;
}
break;
case LRU_CRAWLER:
start_lru_crawler = true;
break;
case LRU_CRAWLER_SLEEP:
if (subopts_value == NULL) {
fprintf(stderr, "Missing lru_crawler_sleep value\n");
return 1;
}
settings.lru_crawler_sleep = atoi(subopts_value);
if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) {
fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n");
return 1;
}
break;
case LRU_CRAWLER_TOCRAWL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing lru_crawler_tocrawl value\n");
return 1;
}
if (!safe_strtoul(subopts_value, &tocrawl)) {
fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n");
return 1;
}
settings.lru_crawler_tocrawl = tocrawl;
break;
case LRU_MAINTAINER:
start_lru_maintainer = true;
settings.lru_segmented = true;
break;
case HOT_LRU_PCT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hot_lru_pct argument\n");
return 1;
}
settings.hot_lru_pct = atoi(subopts_value);
if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) {
fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n");
return 1;
}
break;
case WARM_LRU_PCT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing warm_lru_pct argument\n");
return 1;
}
settings.warm_lru_pct = atoi(subopts_value);
if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) {
fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n");
return 1;
}
break;
case HOT_MAX_FACTOR:
if (subopts_value == NULL) {
fprintf(stderr, "Missing hot_max_factor argument\n");
return 1;
}
settings.hot_max_factor = atof(subopts_value);
if (settings.hot_max_factor <= 0) {
fprintf(stderr, "hot_max_factor must be > 0\n");
return 1;
}
break;
case WARM_MAX_FACTOR:
if (subopts_value == NULL) {
fprintf(stderr, "Missing warm_max_factor argument\n");
return 1;
}
settings.warm_max_factor = atof(subopts_value);
if (settings.warm_max_factor <= 0) {
fprintf(stderr, "warm_max_factor must be > 0\n");
return 1;
}
break;
case TEMPORARY_TTL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing temporary_ttl argument\n");
return 1;
}
settings.temp_lru = true;
settings.temporary_ttl = atoi(subopts_value);
break;
case IDLE_TIMEOUT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing numeric argument for idle_timeout\n");
return 1;
}
settings.idle_timeout = atoi(subopts_value);
break;
case WATCHER_LOGBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing watcher_logbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) {
fprintf(stderr, "could not parse argument to watcher_logbuf_size\n");
return 1;
}
settings.logger_watcher_buf_size *= 1024; /* kilobytes */
break;
case WORKER_LOGBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing worker_logbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) {
fprintf(stderr, "could not parse argument to worker_logbuf_size\n");
return 1;
}
settings.logger_buf_size *= 1024; /* kilobytes */
case SLAB_SIZES:
slab_sizes_unparsed = subopts_value;
break;
case SLAB_CHUNK_MAX:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_chunk_max argument\n");
}
if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) {
fprintf(stderr, "could not parse argument to slab_chunk_max\n");
}
slab_chunk_size_changed = true;
break;
case TRACK_SIZES:
item_stats_sizes_init();
break;
case NO_INLINE_ASCII_RESP:
settings.inline_ascii_response = false;
break;
case INLINE_ASCII_RESP:
settings.inline_ascii_response = true;
break;
case NO_CHUNKED_ITEMS:
settings.slab_chunk_size_max = settings.slab_page_size;
break;
case NO_SLAB_REASSIGN:
settings.slab_reassign = false;
break;
case NO_SLAB_AUTOMOVE:
settings.slab_automove = 0;
break;
case NO_MAXCONNS_FAST:
settings.maxconns_fast = false;
break;
case NO_LRU_CRAWLER:
settings.lru_crawler = false;
start_lru_crawler = false;
break;
case NO_LRU_MAINTAINER:
start_lru_maintainer = false;
settings.lru_segmented = false;
break;
#ifdef TLS
case SSL_CERT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_chain_cert argument\n");
return 1;
}
settings.ssl_chain_cert = strdup(subopts_value);
break;
case SSL_KEY:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_key argument\n");
return 1;
}
settings.ssl_key = strdup(subopts_value);
break;
case SSL_VERIFY_MODE:
{
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_verify_mode argument\n");
return 1;
}
int verify = 0;
if (!safe_strtol(subopts_value, &verify)) {
fprintf(stderr, "could not parse argument to ssl_verify_mode\n");
return 1;
}
switch(verify) {
case 0:
settings.ssl_verify_mode = SSL_VERIFY_NONE;
break;
case 1:
settings.ssl_verify_mode = SSL_VERIFY_PEER;
break;
case 2:
settings.ssl_verify_mode = SSL_VERIFY_PEER |
SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
break;
case 3:
settings.ssl_verify_mode = SSL_VERIFY_PEER |
SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
SSL_VERIFY_CLIENT_ONCE;
break;
default:
fprintf(stderr, "Invalid ssl_verify_mode. Use help to see valid options.\n");
return 1;
}
break;
}
case SSL_KEYFORM:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_keyformat argument\n");
return 1;
}
if (!safe_strtol(subopts_value, &settings.ssl_keyformat)) {
fprintf(stderr, "could not parse argument to ssl_keyformat\n");
return 1;
}
break;
case SSL_CIPHERS:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_ciphers argument\n");
return 1;
}
settings.ssl_ciphers = strdup(subopts_value);
break;
case SSL_CA_CERT:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_ca_cert argument\n");
return 1;
}
settings.ssl_ca_cert = strdup(subopts_value);
break;
case SSL_WBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ssl_wbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ssl_wbuf_size)) {
fprintf(stderr, "could not parse argument to ssl_wbuf_size\n");
return 1;
}
settings.ssl_wbuf_size *= 1024; /* kilobytes */
break;
#endif
#ifdef EXTSTORE
case EXT_PAGE_SIZE:
if (storage_file) {
fprintf(stderr, "Must specify ext_page_size before any ext_path arguments\n");
return 1;
}
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_page_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.page_size)) {
fprintf(stderr, "could not parse argument to ext_page_size\n");
return 1;
}
ext_cf.page_size *= 1024 * 1024; /* megabytes */
break;
case EXT_WBUF_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_wbuf_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) {
fprintf(stderr, "could not parse argument to ext_wbuf_size\n");
return 1;
}
ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */
settings.ext_wbuf_size = ext_cf.wbuf_size;
break;
case EXT_THREADS:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_threads argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) {
fprintf(stderr, "could not parse argument to ext_threads\n");
return 1;
}
break;
case EXT_IO_DEPTH:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_io_depth argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) {
fprintf(stderr, "could not parse argument to ext_io_depth\n");
return 1;
}
break;
case EXT_ITEM_SIZE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_item_size argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_item_size)) {
fprintf(stderr, "could not parse argument to ext_item_size\n");
return 1;
}
break;
case EXT_ITEM_AGE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_item_age argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_item_age)) {
fprintf(stderr, "could not parse argument to ext_item_age\n");
return 1;
}
break;
case EXT_LOW_TTL:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_low_ttl argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) {
fprintf(stderr, "could not parse argument to ext_low_ttl\n");
return 1;
}
break;
case EXT_RECACHE_RATE:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_recache_rate argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) {
fprintf(stderr, "could not parse argument to ext_recache_rate\n");
return 1;
}
break;
case EXT_COMPACT_UNDER:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_compact_under argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) {
fprintf(stderr, "could not parse argument to ext_compact_under\n");
return 1;
}
break;
case EXT_DROP_UNDER:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_drop_under argument\n");
return 1;
}
if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) {
fprintf(stderr, "could not parse argument to ext_drop_under\n");
return 1;
}
break;
case EXT_MAX_FRAG:
if (subopts_value == NULL) {
fprintf(stderr, "Missing ext_max_frag argument\n");
return 1;
}
if (!safe_strtod(subopts_value, &settings.ext_max_frag)) {
fprintf(stderr, "could not parse argument to ext_max_frag\n");
return 1;
}
break;
case SLAB_AUTOMOVE_FREERATIO:
if (subopts_value == NULL) {
fprintf(stderr, "Missing slab_automove_freeratio argument\n");
return 1;
}
if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) {
fprintf(stderr, "could not parse argument to slab_automove_freeratio\n");
return 1;
}
break;
case EXT_DROP_UNREAD:
settings.ext_drop_unread = true;
break;
case EXT_PATH:
if (subopts_value) {
struct extstore_conf_file *tmp = storage_conf_parse(subopts_value, ext_cf.page_size);
if (tmp == NULL) {
fprintf(stderr, "failed to parse ext_path argument\n");
return 1;
}
if (storage_file != NULL) {
tmp->next = storage_file;
}
storage_file = tmp;
} else {
fprintf(stderr, "missing argument to ext_path, ie: ext_path=/d/file:5G\n");
return 1;
}
break;
#endif
case MODERN:
/* currently no new defaults */
break;
case NO_MODERN:
if (!slab_chunk_size_changed) {
settings.slab_chunk_size_max = settings.slab_page_size;
}
settings.slab_reassign = false;
settings.slab_automove = 0;
settings.maxconns_fast = false;
settings.inline_ascii_response = true;
settings.lru_segmented = false;
hash_type = JENKINS_HASH;
start_lru_crawler = false;
start_lru_maintainer = false;
break;
case NO_DROP_PRIVILEGES:
settings.drop_privileges = false;
break;
case DROP_PRIVILEGES:
settings.drop_privileges = true;
break;
#ifdef MEMCACHED_DEBUG
case RELAXED_PRIVILEGES:
settings.relaxed_privileges = true;
break;
#endif
default:
printf("Illegal suboption \"%s\"\n", subopts_value);
return 1;
}
}
free(subopts_orig);
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
return 1;
}
}
if (settings.item_size_max < 1024) {
fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > (settings.maxbytes / 2)) {
fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > (1024 * 1024 * 1024)) {
fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n");
exit(EX_USAGE);
}
if (settings.item_size_max > 1024 * 1024) {
if (!slab_chunk_size_changed) {
// Ideal new default is 16k, but needs stitching.
settings.slab_chunk_size_max = settings.slab_page_size / 2;
}
}
if (settings.slab_chunk_size_max > settings.item_size_max) {
fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n",
settings.slab_chunk_size_max, settings.item_size_max);
exit(EX_USAGE);
}
if (settings.item_size_max % settings.slab_chunk_size_max != 0) {
fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n",
settings.item_size_max, settings.slab_chunk_size_max);
exit(EX_USAGE);
}
if (settings.slab_page_size % settings.slab_chunk_size_max != 0) {
fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n",
settings.slab_chunk_size_max, settings.slab_page_size);
exit(EX_USAGE);
}
#ifdef EXTSTORE
if (storage_file) {
if (settings.item_size_max > ext_cf.wbuf_size) {
fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n",
settings.item_size_max, ext_cf.wbuf_size);
exit(EX_USAGE);
}
/* This is due to the suffix header being generated with the wrong length
* value for the ITEM_HDR replacement. The cuddled nbytes no longer
* matches, so we end up losing a few bytes on readback.
*/
if (settings.inline_ascii_response) {
fprintf(stderr, "Cannot use inline_ascii_response with extstore enabled\n");
exit(EX_USAGE);
}
if (settings.udpport) {
fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n");
exit(EX_USAGE);
}
}
#endif
// Reserve this for the new default. If factor size hasn't changed, use
// new default.
/*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) {
settings.factor = 1.08;
}*/
if (slab_sizes_unparsed != NULL) {
if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) {
use_slab_sizes = true;
} else {
exit(EX_USAGE);
}
}
if (settings.hot_lru_pct + settings.warm_lru_pct > 80) {
fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n");
exit(EX_USAGE);
}
if (settings.temp_lru && !start_lru_maintainer) {
fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n");
exit(EX_USAGE);
}
if (hash_init(hash_type) != 0) {
fprintf(stderr, "Failed to initialize hash_algorithm!\n");
exit(EX_USAGE);
}
/*
* Use one workerthread to serve each UDP port if the user specified
* multiple ports
*/
if (settings.inter != NULL && strchr(settings.inter, ',')) {
settings.num_threads_per_udp = 1;
} else {
settings.num_threads_per_udp = settings.num_threads;
}
if (settings.sasl) {
if (!protocol_specified) {
settings.binding_protocol = binary_prot;
} else {
if (settings.binding_protocol != binary_prot) {
fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n");
exit(EX_USAGE);
}
}
}
if (udp_specified && settings.udpport != 0 && !tcp_specified) {
settings.port = settings.udpport;
}
#ifdef TLS
/*
* Setup SSL if enabled
*/
if (settings.ssl_enabled) {
if (!settings.port) {
fprintf(stderr, "ERROR: You cannot enable SSL without a TCP port.\n");
exit(EX_USAGE);
}
// openssl init methods.
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
// Initiate the SSL context.
ssl_init();
}
#endif
if (maxcore != 0) {
struct rlimit rlim_new;
/*
* First try raising to infinity; if that fails, try bringing
* the soft limit to the hard.
*/
if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) {
/* failed. try raising just to the old max */
rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max;
(void)setrlimit(RLIMIT_CORE, &rlim_new);
}
}
/*
* getrlimit again to see what we ended up with. Only fail if
* the soft limit ends up 0, because then no core files will be
* created at all.
*/
if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) {
fprintf(stderr, "failed to ensure corefile creation\n");
exit(EX_OSERR);
}
}
/*
* If needed, increase rlimits to allow as many connections
* as needed.
*/
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to getrlimit number of files\n");
exit(EX_OSERR);
} else {
rlim.rlim_cur = settings.maxconns;
rlim.rlim_max = settings.maxconns;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n");
exit(EX_OSERR);
}
}
/* lose root privileges if we have them */
if (getuid() == 0 || geteuid() == 0) {
if (username == 0 || *username == '\0') {
fprintf(stderr, "can't run as root without the -u switch\n");
exit(EX_USAGE);
}
if ((pw = getpwnam(username)) == 0) {
fprintf(stderr, "can't find the user %s to switch to\n", username);
exit(EX_NOUSER);
}
if (setgroups(0, NULL) < 0) {
fprintf(stderr, "failed to drop supplementary groups\n");
exit(EX_OSERR);
}
if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
fprintf(stderr, "failed to assume identity of user %s\n", username);
exit(EX_OSERR);
}
}
/* Initialize Sasl if -S was specified */
if (settings.sasl) {
init_sasl();
}
/* daemonize if requested */
/* if we want to ensure our ability to dump core, don't chdir to / */
if (do_daemonize) {
if (sigignore(SIGHUP) == -1) {
perror("Failed to ignore SIGHUP");
}
if (daemonize(maxcore, settings.verbose) == -1) {
fprintf(stderr, "failed to daemon() in order to daemonize\n");
exit(EXIT_FAILURE);
}
}
/* lock paged memory if needed */
if (lock_memory) {
#ifdef HAVE_MLOCKALL
int res = mlockall(MCL_CURRENT | MCL_FUTURE);
if (res != 0) {
fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n",
strerror(errno));
}
#else
fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n");
#endif
}
/* initialize main thread libevent instance */
#if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101
/* If libevent version is larger/equal to 2.0.2-alpha, use newer version */
struct event_config *ev_config;
ev_config = event_config_new();
event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK);
main_base = event_base_new_with_config(ev_config);
event_config_free(ev_config);
#else
/* Otherwise, use older API */
main_base = event_init();
#endif
/* initialize other stuff */
logger_init();
stats_init();
assoc_init(settings.hashpower_init);
conn_init();
slabs_init(settings.maxbytes, settings.factor, preallocate,
use_slab_sizes ? slab_sizes : NULL);
#ifdef EXTSTORE
if (storage_file) {
enum extstore_res eres;
if (settings.ext_compact_under == 0) {
settings.ext_compact_under = storage_file->page_count / 4;
/* Only rescues non-COLD items if below this threshold */
settings.ext_drop_under = storage_file->page_count / 4;
}
crc32c_init();
/* Init free chunks to zero. */
for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) {
settings.ext_free_memchunks[x] = 0;
}
storage = extstore_init(storage_file, &ext_cf, &eres);
if (storage == NULL) {
fprintf(stderr, "Failed to initialize external storage: %s\n",
extstore_err(eres));
if (eres == EXTSTORE_INIT_OPEN_FAIL) {
perror("extstore open");
}
exit(EXIT_FAILURE);
}
ext_storage = storage;
/* page mover algorithm for extstore needs memory prefilled */
slabs_prefill_global();
}
#endif
/*
* ignore SIGPIPE signals; we can use errno == EPIPE if we
* need that information
*/
if (sigignore(SIGPIPE) == -1) {
perror("failed to ignore SIGPIPE; sigaction");
exit(EX_OSERR);
}
/* start up worker threads if MT mode */
#ifdef EXTSTORE
slabs_set_storage(storage);
memcached_thread_init(settings.num_threads, storage);
init_lru_crawler(storage);
#else
memcached_thread_init(settings.num_threads, NULL);
init_lru_crawler(NULL);
#endif
if (start_assoc_maint && start_assoc_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (start_lru_crawler && start_item_crawler_thread() != 0) {
fprintf(stderr, "Failed to enable LRU crawler thread\n");
exit(EXIT_FAILURE);
}
#ifdef EXTSTORE
if (storage && start_storage_compact_thread(storage) != 0) {
fprintf(stderr, "Failed to start storage compaction thread\n");
exit(EXIT_FAILURE);
}
if (storage && start_storage_write_thread(storage) != 0) {
fprintf(stderr, "Failed to start storage writer thread\n");
exit(EXIT_FAILURE);
}
if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) {
#else
if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) {
#endif
fprintf(stderr, "Failed to enable LRU maintainer thread\n");
return 1;
}
if (settings.slab_reassign &&
start_slab_maintenance_thread() == -1) {
exit(EXIT_FAILURE);
}
if (settings.idle_timeout && start_conn_timeout_thread() == -1) {
exit(EXIT_FAILURE);
}
/* initialise clock event */
clock_handler(0, 0, 0);
/* create unix mode sockets after dropping privileges */
if (settings.socketpath != NULL) {
errno = 0;
if (server_socket_unix(settings.socketpath,settings.access)) {
vperror("failed to listen on UNIX socket: %s", settings.socketpath);
exit(EX_OSERR);
}
}
/* create the listening socket, bind it, and init */
if (settings.socketpath == NULL) {
const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME");
char *temp_portnumber_filename = NULL;
size_t len;
FILE *portnumber_file = NULL;
if (portnumber_filename != NULL) {
len = strlen(portnumber_filename)+4+1;
temp_portnumber_filename = malloc(len);
snprintf(temp_portnumber_filename,
len,
"%s.lck", portnumber_filename);
portnumber_file = fopen(temp_portnumber_filename, "a");
if (portnumber_file == NULL) {
fprintf(stderr, "Failed to open \"%s\": %s\n",
temp_portnumber_filename, strerror(errno));
}
}
errno = 0;
if (settings.port && server_sockets(settings.port, tcp_transport,
portnumber_file)) {
vperror("failed to listen on TCP port %d", settings.port);
exit(EX_OSERR);
}
/*
* initialization order: first create the listening sockets
* (may need root on low ports), then drop root if needed,
* then daemonize if needed, then init libevent (in some cases
* descriptors created by libevent wouldn't survive forking).
*/
/* create the UDP listening socket and bind it */
errno = 0;
if (settings.udpport && server_sockets(settings.udpport, udp_transport,
portnumber_file)) {
vperror("failed to listen on UDP port %d", settings.udpport);
exit(EX_OSERR);
}
if (portnumber_file) {
fclose(portnumber_file);
rename(temp_portnumber_filename, portnumber_filename);
}
if (temp_portnumber_filename)
free(temp_portnumber_filename);
}
/* Give the sockets a moment to open. I know this is dumb, but the error
* is only an advisory.
*/
usleep(1000);
if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) {
fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n");
exit(EXIT_FAILURE);
}
if (pid_file != NULL) {
save_pid(pid_file);
}
/* Drop privileges no longer needed */
if (settings.drop_privileges) {
drop_privileges();
}
/* Initialize the uriencode lookup table. */
uriencode_init();
/* enter the event loop */
if (event_base_loop(main_base, 0) != 0) {
retval = EXIT_FAILURE;
}
stop_assoc_maintenance_thread();
/* remove the PID file if we're a daemon */
if (do_daemonize)
remove_pidfile(pid_file);
/* Clean up strdup() call for bind() address */
if (settings.inter)
free(settings.inter);
/* cleanup base */
event_base_free(main_base);
return retval;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_828_0 |
crossvul-cpp_data_good_3060_0 | /* Asymmetric public-key cryptography key type
*
* See Documentation/security/asymmetric-keys.txt
*
* Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "asymmetric_keys.h"
MODULE_LICENSE("GPL");
static LIST_HEAD(asymmetric_key_parsers);
static DECLARE_RWSEM(asymmetric_key_parsers_sem);
/*
* Match asymmetric key id with partial match
* @id: key id to match in a form "id:<id>"
*/
int asymmetric_keyid_match(const char *kid, const char *id)
{
size_t idlen, kidlen;
if (!kid || !id)
return 0;
/* make it possible to use id as in the request: "id:<id>" */
if (strncmp(id, "id:", 3) == 0)
id += 3;
/* Anything after here requires a partial match on the ID string */
idlen = strlen(id);
kidlen = strlen(kid);
if (idlen > kidlen)
return 0;
kid += kidlen - idlen;
if (strcasecmp(id, kid) != 0)
return 0;
return 1;
}
EXPORT_SYMBOL_GPL(asymmetric_keyid_match);
/*
* Match asymmetric keys on (part of) their name
* We have some shorthand methods for matching keys. We allow:
*
* "<desc>" - request a key by description
* "id:<id>" - request a key matching the ID
* "<subtype>:<id>" - request a key of a subtype
*/
static int asymmetric_key_cmp(const struct key *key,
const struct key_match_data *match_data)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *description = match_data->raw_data;
const char *spec = description;
const char *id;
ptrdiff_t speclen;
if (!subtype || !spec || !*spec)
return 0;
/* See if the full key description matches as is */
if (key->description && strcmp(key->description, description) == 0)
return 1;
/* All tests from here on break the criterion description into a
* specifier, a colon and then an identifier.
*/
id = strchr(spec, ':');
if (!id)
return 0;
speclen = id - spec;
id++;
if (speclen == 2 && memcmp(spec, "id", 2) == 0)
return asymmetric_keyid_match(asymmetric_key_id(key), id);
if (speclen == subtype->name_len &&
memcmp(spec, subtype->name, speclen) == 0)
return 1;
return 0;
}
/*
* Preparse the match criterion. If we don't set lookup_type and cmp,
* the default will be an exact match on the key description.
*
* There are some specifiers for matching key IDs rather than by the key
* description:
*
* "id:<id>" - request a key by any available ID
*
* These have to be searched by iteration rather than by direct lookup because
* the key is hashed according to its description.
*/
static int asymmetric_key_match_preparse(struct key_match_data *match_data)
{
match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
match_data->cmp = asymmetric_key_cmp;
return 0;
}
/*
* Free the preparsed the match criterion.
*/
static void asymmetric_key_match_free(struct key_match_data *match_data)
{
}
/*
* Describe the asymmetric key
*/
static void asymmetric_key_describe(const struct key *key, struct seq_file *m)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *kid = asymmetric_key_id(key);
size_t n;
seq_puts(m, key->description);
if (subtype) {
seq_puts(m, ": ");
subtype->describe(key, m);
if (kid) {
seq_putc(m, ' ');
n = strlen(kid);
if (n <= 8)
seq_puts(m, kid);
else
seq_puts(m, kid + n - 8);
}
seq_puts(m, " [");
/* put something here to indicate the key's capabilities */
seq_putc(m, ']');
}
}
/*
* Preparse a asymmetric payload to get format the contents appropriately for the
* internal payload to cut down on the number of scans of the data performed.
*
* We also generate a proposed description from the contents of the key that
* can be used to name the key if the user doesn't want to provide one.
*/
static int asymmetric_key_preparse(struct key_preparsed_payload *prep)
{
struct asymmetric_key_parser *parser;
int ret;
pr_devel("==>%s()\n", __func__);
if (prep->datalen == 0)
return -EINVAL;
down_read(&asymmetric_key_parsers_sem);
ret = -EBADMSG;
list_for_each_entry(parser, &asymmetric_key_parsers, link) {
pr_debug("Trying parser '%s'\n", parser->name);
ret = parser->parse(prep);
if (ret != -EBADMSG) {
pr_debug("Parser recognised the format (ret %d)\n",
ret);
break;
}
}
up_read(&asymmetric_key_parsers_sem);
pr_devel("<==%s() = %d\n", __func__, ret);
return ret;
}
/*
* Clean up the preparse data
*/
static void asymmetric_key_free_preparse(struct key_preparsed_payload *prep)
{
struct asymmetric_key_subtype *subtype = prep->type_data[0];
pr_devel("==>%s()\n", __func__);
if (subtype) {
subtype->destroy(prep->payload[0]);
module_put(subtype->owner);
}
kfree(prep->type_data[1]);
kfree(prep->description);
}
/*
* dispose of the data dangling from the corpse of a asymmetric key
*/
static void asymmetric_key_destroy(struct key *key)
{
struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
if (subtype) {
subtype->destroy(key->payload.data);
module_put(subtype->owner);
key->type_data.p[0] = NULL;
}
kfree(key->type_data.p[1]);
key->type_data.p[1] = NULL;
}
struct key_type key_type_asymmetric = {
.name = "asymmetric",
.preparse = asymmetric_key_preparse,
.free_preparse = asymmetric_key_free_preparse,
.instantiate = generic_key_instantiate,
.match_preparse = asymmetric_key_match_preparse,
.match_free = asymmetric_key_match_free,
.destroy = asymmetric_key_destroy,
.describe = asymmetric_key_describe,
};
EXPORT_SYMBOL_GPL(key_type_asymmetric);
/**
* register_asymmetric_key_parser - Register a asymmetric key blob parser
* @parser: The parser to register
*/
int register_asymmetric_key_parser(struct asymmetric_key_parser *parser)
{
struct asymmetric_key_parser *cursor;
int ret;
down_write(&asymmetric_key_parsers_sem);
list_for_each_entry(cursor, &asymmetric_key_parsers, link) {
if (strcmp(cursor->name, parser->name) == 0) {
pr_err("Asymmetric key parser '%s' already registered\n",
parser->name);
ret = -EEXIST;
goto out;
}
}
list_add_tail(&parser->link, &asymmetric_key_parsers);
pr_notice("Asymmetric key parser '%s' registered\n", parser->name);
ret = 0;
out:
up_write(&asymmetric_key_parsers_sem);
return ret;
}
EXPORT_SYMBOL_GPL(register_asymmetric_key_parser);
/**
* unregister_asymmetric_key_parser - Unregister a asymmetric key blob parser
* @parser: The parser to unregister
*/
void unregister_asymmetric_key_parser(struct asymmetric_key_parser *parser)
{
down_write(&asymmetric_key_parsers_sem);
list_del(&parser->link);
up_write(&asymmetric_key_parsers_sem);
pr_notice("Asymmetric key parser '%s' unregistered\n", parser->name);
}
EXPORT_SYMBOL_GPL(unregister_asymmetric_key_parser);
/*
* Module stuff
*/
static int __init asymmetric_key_init(void)
{
return register_key_type(&key_type_asymmetric);
}
static void __exit asymmetric_key_cleanup(void)
{
unregister_key_type(&key_type_asymmetric);
}
module_init(asymmetric_key_init);
module_exit(asymmetric_key_cleanup);
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3060_0 |
crossvul-cpp_data_bad_5209_0 | /*
* Copyright (c) 2006 - 2009 Mellanox Technology Inc. All rights reserved.
* Copyright (C) 2008 - 2011 Bart Van Assche <bvanassche@acm.org>.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/kthread.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <scsi/scsi_proto.h>
#include <scsi/scsi_tcq.h>
#include <target/target_core_base.h>
#include <target/target_core_fabric.h>
#include "ib_srpt.h"
/* Name of this kernel module. */
#define DRV_NAME "ib_srpt"
#define DRV_VERSION "2.0.0"
#define DRV_RELDATE "2011-02-14"
#define SRPT_ID_STRING "Linux SRP target"
#undef pr_fmt
#define pr_fmt(fmt) DRV_NAME " " fmt
MODULE_AUTHOR("Vu Pham and Bart Van Assche");
MODULE_DESCRIPTION("InfiniBand SCSI RDMA Protocol target "
"v" DRV_VERSION " (" DRV_RELDATE ")");
MODULE_LICENSE("Dual BSD/GPL");
/*
* Global Variables
*/
static u64 srpt_service_guid;
static DEFINE_SPINLOCK(srpt_dev_lock); /* Protects srpt_dev_list. */
static LIST_HEAD(srpt_dev_list); /* List of srpt_device structures. */
static unsigned srp_max_req_size = DEFAULT_MAX_REQ_SIZE;
module_param(srp_max_req_size, int, 0444);
MODULE_PARM_DESC(srp_max_req_size,
"Maximum size of SRP request messages in bytes.");
static int srpt_srq_size = DEFAULT_SRPT_SRQ_SIZE;
module_param(srpt_srq_size, int, 0444);
MODULE_PARM_DESC(srpt_srq_size,
"Shared receive queue (SRQ) size.");
static int srpt_get_u64_x(char *buffer, struct kernel_param *kp)
{
return sprintf(buffer, "0x%016llx", *(u64 *)kp->arg);
}
module_param_call(srpt_service_guid, NULL, srpt_get_u64_x, &srpt_service_guid,
0444);
MODULE_PARM_DESC(srpt_service_guid,
"Using this value for ioc_guid, id_ext, and cm_listen_id"
" instead of using the node_guid of the first HCA.");
static struct ib_client srpt_client;
static void srpt_release_channel(struct srpt_rdma_ch *ch);
static int srpt_queue_status(struct se_cmd *cmd);
static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc);
static void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc);
/**
* opposite_dma_dir() - Swap DMA_TO_DEVICE and DMA_FROM_DEVICE.
*/
static inline
enum dma_data_direction opposite_dma_dir(enum dma_data_direction dir)
{
switch (dir) {
case DMA_TO_DEVICE: return DMA_FROM_DEVICE;
case DMA_FROM_DEVICE: return DMA_TO_DEVICE;
default: return dir;
}
}
/**
* srpt_sdev_name() - Return the name associated with the HCA.
*
* Examples are ib0, ib1, ...
*/
static inline const char *srpt_sdev_name(struct srpt_device *sdev)
{
return sdev->device->name;
}
static enum rdma_ch_state srpt_get_ch_state(struct srpt_rdma_ch *ch)
{
unsigned long flags;
enum rdma_ch_state state;
spin_lock_irqsave(&ch->spinlock, flags);
state = ch->state;
spin_unlock_irqrestore(&ch->spinlock, flags);
return state;
}
static enum rdma_ch_state
srpt_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state new_state)
{
unsigned long flags;
enum rdma_ch_state prev;
spin_lock_irqsave(&ch->spinlock, flags);
prev = ch->state;
ch->state = new_state;
spin_unlock_irqrestore(&ch->spinlock, flags);
return prev;
}
/**
* srpt_test_and_set_ch_state() - Test and set the channel state.
*
* Returns true if and only if the channel state has been set to the new state.
*/
static bool
srpt_test_and_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state old,
enum rdma_ch_state new)
{
unsigned long flags;
enum rdma_ch_state prev;
spin_lock_irqsave(&ch->spinlock, flags);
prev = ch->state;
if (prev == old)
ch->state = new;
spin_unlock_irqrestore(&ch->spinlock, flags);
return prev == old;
}
/**
* srpt_event_handler() - Asynchronous IB event callback function.
*
* Callback function called by the InfiniBand core when an asynchronous IB
* event occurs. This callback may occur in interrupt context. See also
* section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
* Architecture Specification.
*/
static void srpt_event_handler(struct ib_event_handler *handler,
struct ib_event *event)
{
struct srpt_device *sdev;
struct srpt_port *sport;
sdev = ib_get_client_data(event->device, &srpt_client);
if (!sdev || sdev->device != event->device)
return;
pr_debug("ASYNC event= %d on device= %s\n", event->event,
srpt_sdev_name(sdev));
switch (event->event) {
case IB_EVENT_PORT_ERR:
if (event->element.port_num <= sdev->device->phys_port_cnt) {
sport = &sdev->port[event->element.port_num - 1];
sport->lid = 0;
sport->sm_lid = 0;
}
break;
case IB_EVENT_PORT_ACTIVE:
case IB_EVENT_LID_CHANGE:
case IB_EVENT_PKEY_CHANGE:
case IB_EVENT_SM_CHANGE:
case IB_EVENT_CLIENT_REREGISTER:
case IB_EVENT_GID_CHANGE:
/* Refresh port data asynchronously. */
if (event->element.port_num <= sdev->device->phys_port_cnt) {
sport = &sdev->port[event->element.port_num - 1];
if (!sport->lid && !sport->sm_lid)
schedule_work(&sport->work);
}
break;
default:
pr_err("received unrecognized IB event %d\n",
event->event);
break;
}
}
/**
* srpt_srq_event() - SRQ event callback function.
*/
static void srpt_srq_event(struct ib_event *event, void *ctx)
{
pr_info("SRQ event %d\n", event->event);
}
/**
* srpt_qp_event() - QP event callback function.
*/
static void srpt_qp_event(struct ib_event *event, struct srpt_rdma_ch *ch)
{
pr_debug("QP event %d on cm_id=%p sess_name=%s state=%d\n",
event->event, ch->cm_id, ch->sess_name, srpt_get_ch_state(ch));
switch (event->event) {
case IB_EVENT_COMM_EST:
ib_cm_notify(ch->cm_id, event->event);
break;
case IB_EVENT_QP_LAST_WQE_REACHED:
if (srpt_test_and_set_ch_state(ch, CH_DRAINING,
CH_RELEASING))
srpt_release_channel(ch);
else
pr_debug("%s: state %d - ignored LAST_WQE.\n",
ch->sess_name, srpt_get_ch_state(ch));
break;
default:
pr_err("received unrecognized IB QP event %d\n", event->event);
break;
}
}
/**
* srpt_set_ioc() - Helper function for initializing an IOUnitInfo structure.
*
* @slot: one-based slot number.
* @value: four-bit value.
*
* Copies the lowest four bits of value in element slot of the array of four
* bit elements called c_list (controller list). The index slot is one-based.
*/
static void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
{
u16 id;
u8 tmp;
id = (slot - 1) / 2;
if (slot & 0x1) {
tmp = c_list[id] & 0xf;
c_list[id] = (value << 4) | tmp;
} else {
tmp = c_list[id] & 0xf0;
c_list[id] = (value & 0xf) | tmp;
}
}
/**
* srpt_get_class_port_info() - Copy ClassPortInfo to a management datagram.
*
* See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
* Specification.
*/
static void srpt_get_class_port_info(struct ib_dm_mad *mad)
{
struct ib_class_port_info *cif;
cif = (struct ib_class_port_info *)mad->data;
memset(cif, 0, sizeof *cif);
cif->base_version = 1;
cif->class_version = 1;
cif->resp_time_value = 20;
mad->mad_hdr.status = 0;
}
/**
* srpt_get_iou() - Write IOUnitInfo to a management datagram.
*
* See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
* Specification. See also section B.7, table B.6 in the SRP r16a document.
*/
static void srpt_get_iou(struct ib_dm_mad *mad)
{
struct ib_dm_iou_info *ioui;
u8 slot;
int i;
ioui = (struct ib_dm_iou_info *)mad->data;
ioui->change_id = cpu_to_be16(1);
ioui->max_controllers = 16;
/* set present for slot 1 and empty for the rest */
srpt_set_ioc(ioui->controller_list, 1, 1);
for (i = 1, slot = 2; i < 16; i++, slot++)
srpt_set_ioc(ioui->controller_list, slot, 0);
mad->mad_hdr.status = 0;
}
/**
* srpt_get_ioc() - Write IOControllerprofile to a management datagram.
*
* See also section 16.3.3.4 IOControllerProfile in the InfiniBand
* Architecture Specification. See also section B.7, table B.7 in the SRP
* r16a document.
*/
static void srpt_get_ioc(struct srpt_port *sport, u32 slot,
struct ib_dm_mad *mad)
{
struct srpt_device *sdev = sport->sdev;
struct ib_dm_ioc_profile *iocp;
iocp = (struct ib_dm_ioc_profile *)mad->data;
if (!slot || slot > 16) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
return;
}
if (slot > 2) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_NO_IOC);
return;
}
memset(iocp, 0, sizeof *iocp);
strcpy(iocp->id_string, SRPT_ID_STRING);
iocp->guid = cpu_to_be64(srpt_service_guid);
iocp->vendor_id = cpu_to_be32(sdev->device->attrs.vendor_id);
iocp->device_id = cpu_to_be32(sdev->device->attrs.vendor_part_id);
iocp->device_version = cpu_to_be16(sdev->device->attrs.hw_ver);
iocp->subsys_vendor_id = cpu_to_be32(sdev->device->attrs.vendor_id);
iocp->subsys_device_id = 0x0;
iocp->io_class = cpu_to_be16(SRP_REV16A_IB_IO_CLASS);
iocp->io_subclass = cpu_to_be16(SRP_IO_SUBCLASS);
iocp->protocol = cpu_to_be16(SRP_PROTOCOL);
iocp->protocol_version = cpu_to_be16(SRP_PROTOCOL_VERSION);
iocp->send_queue_depth = cpu_to_be16(sdev->srq_size);
iocp->rdma_read_depth = 4;
iocp->send_size = cpu_to_be32(srp_max_req_size);
iocp->rdma_size = cpu_to_be32(min(sport->port_attrib.srp_max_rdma_size,
1U << 24));
iocp->num_svc_entries = 1;
iocp->op_cap_mask = SRP_SEND_TO_IOC | SRP_SEND_FROM_IOC |
SRP_RDMA_READ_FROM_IOC | SRP_RDMA_WRITE_FROM_IOC;
mad->mad_hdr.status = 0;
}
/**
* srpt_get_svc_entries() - Write ServiceEntries to a management datagram.
*
* See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
* Specification. See also section B.7, table B.8 in the SRP r16a document.
*/
static void srpt_get_svc_entries(u64 ioc_guid,
u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
{
struct ib_dm_svc_entries *svc_entries;
WARN_ON(!ioc_guid);
if (!slot || slot > 16) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
return;
}
if (slot > 2 || lo > hi || hi > 1) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_NO_IOC);
return;
}
svc_entries = (struct ib_dm_svc_entries *)mad->data;
memset(svc_entries, 0, sizeof *svc_entries);
svc_entries->service_entries[0].id = cpu_to_be64(ioc_guid);
snprintf(svc_entries->service_entries[0].name,
sizeof(svc_entries->service_entries[0].name),
"%s%016llx",
SRP_SERVICE_NAME_PREFIX,
ioc_guid);
mad->mad_hdr.status = 0;
}
/**
* srpt_mgmt_method_get() - Process a received management datagram.
* @sp: source port through which the MAD has been received.
* @rq_mad: received MAD.
* @rsp_mad: response MAD.
*/
static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
struct ib_dm_mad *rsp_mad)
{
u16 attr_id;
u32 slot;
u8 hi, lo;
attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
switch (attr_id) {
case DM_ATTR_CLASS_PORT_INFO:
srpt_get_class_port_info(rsp_mad);
break;
case DM_ATTR_IOU_INFO:
srpt_get_iou(rsp_mad);
break;
case DM_ATTR_IOC_PROFILE:
slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
srpt_get_ioc(sp, slot, rsp_mad);
break;
case DM_ATTR_SVC_ENTRIES:
slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
hi = (u8) ((slot >> 8) & 0xff);
lo = (u8) (slot & 0xff);
slot = (u16) ((slot >> 16) & 0xffff);
srpt_get_svc_entries(srpt_service_guid,
slot, hi, lo, rsp_mad);
break;
default:
rsp_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
break;
}
}
/**
* srpt_mad_send_handler() - Post MAD-send callback function.
*/
static void srpt_mad_send_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_send_wc *mad_wc)
{
ib_destroy_ah(mad_wc->send_buf->ah);
ib_free_send_mad(mad_wc->send_buf);
}
/**
* srpt_mad_recv_handler() - MAD reception callback function.
*/
static void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_send_buf *send_buf,
struct ib_mad_recv_wc *mad_wc)
{
struct srpt_port *sport = (struct srpt_port *)mad_agent->context;
struct ib_ah *ah;
struct ib_mad_send_buf *rsp;
struct ib_dm_mad *dm_mad;
if (!mad_wc || !mad_wc->recv_buf.mad)
return;
ah = ib_create_ah_from_wc(mad_agent->qp->pd, mad_wc->wc,
mad_wc->recv_buf.grh, mad_agent->port_num);
if (IS_ERR(ah))
goto err;
BUILD_BUG_ON(offsetof(struct ib_dm_mad, data) != IB_MGMT_DEVICE_HDR);
rsp = ib_create_send_mad(mad_agent, mad_wc->wc->src_qp,
mad_wc->wc->pkey_index, 0,
IB_MGMT_DEVICE_HDR, IB_MGMT_DEVICE_DATA,
GFP_KERNEL,
IB_MGMT_BASE_VERSION);
if (IS_ERR(rsp))
goto err_rsp;
rsp->ah = ah;
dm_mad = rsp->mad;
memcpy(dm_mad, mad_wc->recv_buf.mad, sizeof *dm_mad);
dm_mad->mad_hdr.method = IB_MGMT_METHOD_GET_RESP;
dm_mad->mad_hdr.status = 0;
switch (mad_wc->recv_buf.mad->mad_hdr.method) {
case IB_MGMT_METHOD_GET:
srpt_mgmt_method_get(sport, mad_wc->recv_buf.mad, dm_mad);
break;
case IB_MGMT_METHOD_SET:
dm_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
break;
default:
dm_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD);
break;
}
if (!ib_post_send_mad(rsp, NULL)) {
ib_free_recv_mad(mad_wc);
/* will destroy_ah & free_send_mad in send completion */
return;
}
ib_free_send_mad(rsp);
err_rsp:
ib_destroy_ah(ah);
err:
ib_free_recv_mad(mad_wc);
}
/**
* srpt_refresh_port() - Configure a HCA port.
*
* Enable InfiniBand management datagram processing, update the cached sm_lid,
* lid and gid values, and register a callback function for processing MADs
* on the specified port.
*
* Note: It is safe to call this function more than once for the same port.
*/
static int srpt_refresh_port(struct srpt_port *sport)
{
struct ib_mad_reg_req reg_req;
struct ib_port_modify port_modify;
struct ib_port_attr port_attr;
int ret;
memset(&port_modify, 0, sizeof port_modify);
port_modify.set_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
port_modify.clr_port_cap_mask = 0;
ret = ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
if (ret)
goto err_mod_port;
ret = ib_query_port(sport->sdev->device, sport->port, &port_attr);
if (ret)
goto err_query_port;
sport->sm_lid = port_attr.sm_lid;
sport->lid = port_attr.lid;
ret = ib_query_gid(sport->sdev->device, sport->port, 0, &sport->gid,
NULL);
if (ret)
goto err_query_port;
if (!sport->mad_agent) {
memset(®_req, 0, sizeof reg_req);
reg_req.mgmt_class = IB_MGMT_CLASS_DEVICE_MGMT;
reg_req.mgmt_class_version = IB_MGMT_BASE_VERSION;
set_bit(IB_MGMT_METHOD_GET, reg_req.method_mask);
set_bit(IB_MGMT_METHOD_SET, reg_req.method_mask);
sport->mad_agent = ib_register_mad_agent(sport->sdev->device,
sport->port,
IB_QPT_GSI,
®_req, 0,
srpt_mad_send_handler,
srpt_mad_recv_handler,
sport, 0);
if (IS_ERR(sport->mad_agent)) {
ret = PTR_ERR(sport->mad_agent);
sport->mad_agent = NULL;
goto err_query_port;
}
}
return 0;
err_query_port:
port_modify.set_port_cap_mask = 0;
port_modify.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
err_mod_port:
return ret;
}
/**
* srpt_unregister_mad_agent() - Unregister MAD callback functions.
*
* Note: It is safe to call this function more than once for the same device.
*/
static void srpt_unregister_mad_agent(struct srpt_device *sdev)
{
struct ib_port_modify port_modify = {
.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP,
};
struct srpt_port *sport;
int i;
for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
sport = &sdev->port[i - 1];
WARN_ON(sport->port != i);
if (ib_modify_port(sdev->device, i, 0, &port_modify) < 0)
pr_err("disabling MAD processing failed.\n");
if (sport->mad_agent) {
ib_unregister_mad_agent(sport->mad_agent);
sport->mad_agent = NULL;
}
}
}
/**
* srpt_alloc_ioctx() - Allocate an SRPT I/O context structure.
*/
static struct srpt_ioctx *srpt_alloc_ioctx(struct srpt_device *sdev,
int ioctx_size, int dma_size,
enum dma_data_direction dir)
{
struct srpt_ioctx *ioctx;
ioctx = kmalloc(ioctx_size, GFP_KERNEL);
if (!ioctx)
goto err;
ioctx->buf = kmalloc(dma_size, GFP_KERNEL);
if (!ioctx->buf)
goto err_free_ioctx;
ioctx->dma = ib_dma_map_single(sdev->device, ioctx->buf, dma_size, dir);
if (ib_dma_mapping_error(sdev->device, ioctx->dma))
goto err_free_buf;
return ioctx;
err_free_buf:
kfree(ioctx->buf);
err_free_ioctx:
kfree(ioctx);
err:
return NULL;
}
/**
* srpt_free_ioctx() - Free an SRPT I/O context structure.
*/
static void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx,
int dma_size, enum dma_data_direction dir)
{
if (!ioctx)
return;
ib_dma_unmap_single(sdev->device, ioctx->dma, dma_size, dir);
kfree(ioctx->buf);
kfree(ioctx);
}
/**
* srpt_alloc_ioctx_ring() - Allocate a ring of SRPT I/O context structures.
* @sdev: Device to allocate the I/O context ring for.
* @ring_size: Number of elements in the I/O context ring.
* @ioctx_size: I/O context size.
* @dma_size: DMA buffer size.
* @dir: DMA data direction.
*/
static struct srpt_ioctx **srpt_alloc_ioctx_ring(struct srpt_device *sdev,
int ring_size, int ioctx_size,
int dma_size, enum dma_data_direction dir)
{
struct srpt_ioctx **ring;
int i;
WARN_ON(ioctx_size != sizeof(struct srpt_recv_ioctx)
&& ioctx_size != sizeof(struct srpt_send_ioctx));
ring = kmalloc(ring_size * sizeof(ring[0]), GFP_KERNEL);
if (!ring)
goto out;
for (i = 0; i < ring_size; ++i) {
ring[i] = srpt_alloc_ioctx(sdev, ioctx_size, dma_size, dir);
if (!ring[i])
goto err;
ring[i]->index = i;
}
goto out;
err:
while (--i >= 0)
srpt_free_ioctx(sdev, ring[i], dma_size, dir);
kfree(ring);
ring = NULL;
out:
return ring;
}
/**
* srpt_free_ioctx_ring() - Free the ring of SRPT I/O context structures.
*/
static void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring,
struct srpt_device *sdev, int ring_size,
int dma_size, enum dma_data_direction dir)
{
int i;
for (i = 0; i < ring_size; ++i)
srpt_free_ioctx(sdev, ioctx_ring[i], dma_size, dir);
kfree(ioctx_ring);
}
/**
* srpt_get_cmd_state() - Get the state of a SCSI command.
*/
static enum srpt_command_state srpt_get_cmd_state(struct srpt_send_ioctx *ioctx)
{
enum srpt_command_state state;
unsigned long flags;
BUG_ON(!ioctx);
spin_lock_irqsave(&ioctx->spinlock, flags);
state = ioctx->state;
spin_unlock_irqrestore(&ioctx->spinlock, flags);
return state;
}
/**
* srpt_set_cmd_state() - Set the state of a SCSI command.
*
* Does not modify the state of aborted commands. Returns the previous command
* state.
*/
static enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx,
enum srpt_command_state new)
{
enum srpt_command_state previous;
unsigned long flags;
BUG_ON(!ioctx);
spin_lock_irqsave(&ioctx->spinlock, flags);
previous = ioctx->state;
if (previous != SRPT_STATE_DONE)
ioctx->state = new;
spin_unlock_irqrestore(&ioctx->spinlock, flags);
return previous;
}
/**
* srpt_test_and_set_cmd_state() - Test and set the state of a command.
*
* Returns true if and only if the previous command state was equal to 'old'.
*/
static bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx,
enum srpt_command_state old,
enum srpt_command_state new)
{
enum srpt_command_state previous;
unsigned long flags;
WARN_ON(!ioctx);
WARN_ON(old == SRPT_STATE_DONE);
WARN_ON(new == SRPT_STATE_NEW);
spin_lock_irqsave(&ioctx->spinlock, flags);
previous = ioctx->state;
if (previous == old)
ioctx->state = new;
spin_unlock_irqrestore(&ioctx->spinlock, flags);
return previous == old;
}
/**
* srpt_post_recv() - Post an IB receive request.
*/
static int srpt_post_recv(struct srpt_device *sdev,
struct srpt_recv_ioctx *ioctx)
{
struct ib_sge list;
struct ib_recv_wr wr, *bad_wr;
BUG_ON(!sdev);
list.addr = ioctx->ioctx.dma;
list.length = srp_max_req_size;
list.lkey = sdev->pd->local_dma_lkey;
ioctx->ioctx.cqe.done = srpt_recv_done;
wr.wr_cqe = &ioctx->ioctx.cqe;
wr.next = NULL;
wr.sg_list = &list;
wr.num_sge = 1;
return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
}
/**
* srpt_post_send() - Post an IB send request.
*
* Returns zero upon success and a non-zero value upon failure.
*/
static int srpt_post_send(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx, int len)
{
struct ib_sge list;
struct ib_send_wr wr, *bad_wr;
struct srpt_device *sdev = ch->sport->sdev;
int ret;
atomic_inc(&ch->req_lim);
ret = -ENOMEM;
if (unlikely(atomic_dec_return(&ch->sq_wr_avail) < 0)) {
pr_warn("IB send queue full (needed 1)\n");
goto out;
}
ib_dma_sync_single_for_device(sdev->device, ioctx->ioctx.dma, len,
DMA_TO_DEVICE);
list.addr = ioctx->ioctx.dma;
list.length = len;
list.lkey = sdev->pd->local_dma_lkey;
ioctx->ioctx.cqe.done = srpt_send_done;
wr.next = NULL;
wr.wr_cqe = &ioctx->ioctx.cqe;
wr.sg_list = &list;
wr.num_sge = 1;
wr.opcode = IB_WR_SEND;
wr.send_flags = IB_SEND_SIGNALED;
ret = ib_post_send(ch->qp, &wr, &bad_wr);
out:
if (ret < 0) {
atomic_inc(&ch->sq_wr_avail);
atomic_dec(&ch->req_lim);
}
return ret;
}
/**
* srpt_get_desc_tbl() - Parse the data descriptors of an SRP_CMD request.
* @ioctx: Pointer to the I/O context associated with the request.
* @srp_cmd: Pointer to the SRP_CMD request data.
* @dir: Pointer to the variable to which the transfer direction will be
* written.
* @data_len: Pointer to the variable to which the total data length of all
* descriptors in the SRP_CMD request will be written.
*
* This function initializes ioctx->nrbuf and ioctx->r_bufs.
*
* Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
* -ENOMEM when memory allocation fails and zero upon success.
*/
static int srpt_get_desc_tbl(struct srpt_send_ioctx *ioctx,
struct srp_cmd *srp_cmd,
enum dma_data_direction *dir, u64 *data_len)
{
struct srp_indirect_buf *idb;
struct srp_direct_buf *db;
unsigned add_cdb_offset;
int ret;
/*
* The pointer computations below will only be compiled correctly
* if srp_cmd::add_data is declared as s8*, u8*, s8[] or u8[], so check
* whether srp_cmd::add_data has been declared as a byte pointer.
*/
BUILD_BUG_ON(!__same_type(srp_cmd->add_data[0], (s8)0)
&& !__same_type(srp_cmd->add_data[0], (u8)0));
BUG_ON(!dir);
BUG_ON(!data_len);
ret = 0;
*data_len = 0;
/*
* The lower four bits of the buffer format field contain the DATA-IN
* buffer descriptor format, and the highest four bits contain the
* DATA-OUT buffer descriptor format.
*/
*dir = DMA_NONE;
if (srp_cmd->buf_fmt & 0xf)
/* DATA-IN: transfer data from target to initiator (read). */
*dir = DMA_FROM_DEVICE;
else if (srp_cmd->buf_fmt >> 4)
/* DATA-OUT: transfer data from initiator to target (write). */
*dir = DMA_TO_DEVICE;
/*
* According to the SRP spec, the lower two bits of the 'ADDITIONAL
* CDB LENGTH' field are reserved and the size in bytes of this field
* is four times the value specified in bits 3..7. Hence the "& ~3".
*/
add_cdb_offset = srp_cmd->add_cdb_len & ~3;
if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
ioctx->n_rbuf = 1;
ioctx->rbufs = &ioctx->single_rbuf;
db = (struct srp_direct_buf *)(srp_cmd->add_data
+ add_cdb_offset);
memcpy(ioctx->rbufs, db, sizeof *db);
*data_len = be32_to_cpu(db->len);
} else if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_INDIRECT) ||
((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_INDIRECT)) {
idb = (struct srp_indirect_buf *)(srp_cmd->add_data
+ add_cdb_offset);
ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof *db;
if (ioctx->n_rbuf >
(srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
pr_err("received unsupported SRP_CMD request"
" type (%u out + %u in != %u / %zu)\n",
srp_cmd->data_out_desc_cnt,
srp_cmd->data_in_desc_cnt,
be32_to_cpu(idb->table_desc.len),
sizeof(*db));
ioctx->n_rbuf = 0;
ret = -EINVAL;
goto out;
}
if (ioctx->n_rbuf == 1)
ioctx->rbufs = &ioctx->single_rbuf;
else {
ioctx->rbufs =
kmalloc(ioctx->n_rbuf * sizeof *db, GFP_ATOMIC);
if (!ioctx->rbufs) {
ioctx->n_rbuf = 0;
ret = -ENOMEM;
goto out;
}
}
db = idb->desc_list;
memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof *db);
*data_len = be32_to_cpu(idb->len);
}
out:
return ret;
}
/**
* srpt_init_ch_qp() - Initialize queue pair attributes.
*
* Initialized the attributes of queue pair 'qp' by allowing local write,
* remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.
*/
static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
struct ib_qp_attr *attr;
int ret;
attr = kzalloc(sizeof *attr, GFP_KERNEL);
if (!attr)
return -ENOMEM;
attr->qp_state = IB_QPS_INIT;
attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ |
IB_ACCESS_REMOTE_WRITE;
attr->port_num = ch->sport->port;
attr->pkey_index = 0;
ret = ib_modify_qp(qp, attr,
IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
IB_QP_PKEY_INDEX);
kfree(attr);
return ret;
}
/**
* srpt_ch_qp_rtr() - Change the state of a channel to 'ready to receive' (RTR).
* @ch: channel of the queue pair.
* @qp: queue pair to change the state of.
*
* Returns zero upon success and a negative value upon failure.
*
* Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
* If this structure ever becomes larger, it might be necessary to allocate
* it dynamically instead of on the stack.
*/
static int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
struct ib_qp_attr qp_attr;
int attr_mask;
int ret;
qp_attr.qp_state = IB_QPS_RTR;
ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
if (ret)
goto out;
qp_attr.max_dest_rd_atomic = 4;
ret = ib_modify_qp(qp, &qp_attr, attr_mask);
out:
return ret;
}
/**
* srpt_ch_qp_rts() - Change the state of a channel to 'ready to send' (RTS).
* @ch: channel of the queue pair.
* @qp: queue pair to change the state of.
*
* Returns zero upon success and a negative value upon failure.
*
* Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
* If this structure ever becomes larger, it might be necessary to allocate
* it dynamically instead of on the stack.
*/
static int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
struct ib_qp_attr qp_attr;
int attr_mask;
int ret;
qp_attr.qp_state = IB_QPS_RTS;
ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
if (ret)
goto out;
qp_attr.max_rd_atomic = 4;
ret = ib_modify_qp(qp, &qp_attr, attr_mask);
out:
return ret;
}
/**
* srpt_ch_qp_err() - Set the channel queue pair state to 'error'.
*/
static int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
{
struct ib_qp_attr qp_attr;
qp_attr.qp_state = IB_QPS_ERR;
return ib_modify_qp(ch->qp, &qp_attr, IB_QP_STATE);
}
/**
* srpt_unmap_sg_to_ib_sge() - Unmap an IB SGE list.
*/
static void srpt_unmap_sg_to_ib_sge(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
struct scatterlist *sg;
enum dma_data_direction dir;
BUG_ON(!ch);
BUG_ON(!ioctx);
BUG_ON(ioctx->n_rdma && !ioctx->rdma_wrs);
while (ioctx->n_rdma)
kfree(ioctx->rdma_wrs[--ioctx->n_rdma].wr.sg_list);
kfree(ioctx->rdma_wrs);
ioctx->rdma_wrs = NULL;
if (ioctx->mapped_sg_count) {
sg = ioctx->sg;
WARN_ON(!sg);
dir = ioctx->cmd.data_direction;
BUG_ON(dir == DMA_NONE);
ib_dma_unmap_sg(ch->sport->sdev->device, sg, ioctx->sg_cnt,
opposite_dma_dir(dir));
ioctx->mapped_sg_count = 0;
}
}
/**
* srpt_map_sg_to_ib_sge() - Map an SG list to an IB SGE list.
*/
static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
struct ib_device *dev = ch->sport->sdev->device;
struct se_cmd *cmd;
struct scatterlist *sg, *sg_orig;
int sg_cnt;
enum dma_data_direction dir;
struct ib_rdma_wr *riu;
struct srp_direct_buf *db;
dma_addr_t dma_addr;
struct ib_sge *sge;
u64 raddr;
u32 rsize;
u32 tsize;
u32 dma_len;
int count, nrdma;
int i, j, k;
BUG_ON(!ch);
BUG_ON(!ioctx);
cmd = &ioctx->cmd;
dir = cmd->data_direction;
BUG_ON(dir == DMA_NONE);
ioctx->sg = sg = sg_orig = cmd->t_data_sg;
ioctx->sg_cnt = sg_cnt = cmd->t_data_nents;
count = ib_dma_map_sg(ch->sport->sdev->device, sg, sg_cnt,
opposite_dma_dir(dir));
if (unlikely(!count))
return -EAGAIN;
ioctx->mapped_sg_count = count;
if (ioctx->rdma_wrs && ioctx->n_rdma_wrs)
nrdma = ioctx->n_rdma_wrs;
else {
nrdma = (count + SRPT_DEF_SG_PER_WQE - 1) / SRPT_DEF_SG_PER_WQE
+ ioctx->n_rbuf;
ioctx->rdma_wrs = kcalloc(nrdma, sizeof(*ioctx->rdma_wrs),
GFP_KERNEL);
if (!ioctx->rdma_wrs)
goto free_mem;
ioctx->n_rdma_wrs = nrdma;
}
db = ioctx->rbufs;
tsize = cmd->data_length;
dma_len = ib_sg_dma_len(dev, &sg[0]);
riu = ioctx->rdma_wrs;
/*
* For each remote desc - calculate the #ib_sge.
* If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
* each remote desc rdma_iu is required a rdma wr;
* else
* we need to allocate extra rdma_iu to carry extra #ib_sge in
* another rdma wr
*/
for (i = 0, j = 0;
j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
rsize = be32_to_cpu(db->len);
raddr = be64_to_cpu(db->va);
riu->remote_addr = raddr;
riu->rkey = be32_to_cpu(db->key);
riu->wr.num_sge = 0;
/* calculate how many sge required for this remote_buf */
while (rsize > 0 && tsize > 0) {
if (rsize >= dma_len) {
tsize -= dma_len;
rsize -= dma_len;
raddr += dma_len;
if (tsize > 0) {
++j;
if (j < count) {
sg = sg_next(sg);
dma_len = ib_sg_dma_len(
dev, sg);
}
}
} else {
tsize -= rsize;
dma_len -= rsize;
rsize = 0;
}
++riu->wr.num_sge;
if (rsize > 0 &&
riu->wr.num_sge == SRPT_DEF_SG_PER_WQE) {
++ioctx->n_rdma;
riu->wr.sg_list = kmalloc_array(riu->wr.num_sge,
sizeof(*riu->wr.sg_list),
GFP_KERNEL);
if (!riu->wr.sg_list)
goto free_mem;
++riu;
riu->wr.num_sge = 0;
riu->remote_addr = raddr;
riu->rkey = be32_to_cpu(db->key);
}
}
++ioctx->n_rdma;
riu->wr.sg_list = kmalloc_array(riu->wr.num_sge,
sizeof(*riu->wr.sg_list),
GFP_KERNEL);
if (!riu->wr.sg_list)
goto free_mem;
}
db = ioctx->rbufs;
tsize = cmd->data_length;
riu = ioctx->rdma_wrs;
sg = sg_orig;
dma_len = ib_sg_dma_len(dev, &sg[0]);
dma_addr = ib_sg_dma_address(dev, &sg[0]);
/* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
for (i = 0, j = 0;
j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
rsize = be32_to_cpu(db->len);
sge = riu->wr.sg_list;
k = 0;
while (rsize > 0 && tsize > 0) {
sge->addr = dma_addr;
sge->lkey = ch->sport->sdev->pd->local_dma_lkey;
if (rsize >= dma_len) {
sge->length =
(tsize < dma_len) ? tsize : dma_len;
tsize -= dma_len;
rsize -= dma_len;
if (tsize > 0) {
++j;
if (j < count) {
sg = sg_next(sg);
dma_len = ib_sg_dma_len(
dev, sg);
dma_addr = ib_sg_dma_address(
dev, sg);
}
}
} else {
sge->length = (tsize < rsize) ? tsize : rsize;
tsize -= rsize;
dma_len -= rsize;
dma_addr += rsize;
rsize = 0;
}
++k;
if (k == riu->wr.num_sge && rsize > 0 && tsize > 0) {
++riu;
sge = riu->wr.sg_list;
k = 0;
} else if (rsize > 0 && tsize > 0)
++sge;
}
}
return 0;
free_mem:
srpt_unmap_sg_to_ib_sge(ch, ioctx);
return -ENOMEM;
}
/**
* srpt_get_send_ioctx() - Obtain an I/O context for sending to the initiator.
*/
static struct srpt_send_ioctx *srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
{
struct srpt_send_ioctx *ioctx;
unsigned long flags;
BUG_ON(!ch);
ioctx = NULL;
spin_lock_irqsave(&ch->spinlock, flags);
if (!list_empty(&ch->free_list)) {
ioctx = list_first_entry(&ch->free_list,
struct srpt_send_ioctx, free_list);
list_del(&ioctx->free_list);
}
spin_unlock_irqrestore(&ch->spinlock, flags);
if (!ioctx)
return ioctx;
BUG_ON(ioctx->ch != ch);
spin_lock_init(&ioctx->spinlock);
ioctx->state = SRPT_STATE_NEW;
ioctx->n_rbuf = 0;
ioctx->rbufs = NULL;
ioctx->n_rdma = 0;
ioctx->n_rdma_wrs = 0;
ioctx->rdma_wrs = NULL;
ioctx->mapped_sg_count = 0;
init_completion(&ioctx->tx_done);
ioctx->queue_status_only = false;
/*
* transport_init_se_cmd() does not initialize all fields, so do it
* here.
*/
memset(&ioctx->cmd, 0, sizeof(ioctx->cmd));
memset(&ioctx->sense_data, 0, sizeof(ioctx->sense_data));
return ioctx;
}
/**
* srpt_abort_cmd() - Abort a SCSI command.
* @ioctx: I/O context associated with the SCSI command.
* @context: Preferred execution context.
*/
static int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
{
enum srpt_command_state state;
unsigned long flags;
BUG_ON(!ioctx);
/*
* If the command is in a state where the target core is waiting for
* the ib_srpt driver, change the state to the next state. Changing
* the state of the command from SRPT_STATE_NEED_DATA to
* SRPT_STATE_DATA_IN ensures that srpt_xmit_response() will call this
* function a second time.
*/
spin_lock_irqsave(&ioctx->spinlock, flags);
state = ioctx->state;
switch (state) {
case SRPT_STATE_NEED_DATA:
ioctx->state = SRPT_STATE_DATA_IN;
break;
case SRPT_STATE_DATA_IN:
case SRPT_STATE_CMD_RSP_SENT:
case SRPT_STATE_MGMT_RSP_SENT:
ioctx->state = SRPT_STATE_DONE;
break;
default:
break;
}
spin_unlock_irqrestore(&ioctx->spinlock, flags);
if (state == SRPT_STATE_DONE) {
struct srpt_rdma_ch *ch = ioctx->ch;
BUG_ON(ch->sess == NULL);
target_put_sess_cmd(&ioctx->cmd);
goto out;
}
pr_debug("Aborting cmd with state %d and tag %lld\n", state,
ioctx->cmd.tag);
switch (state) {
case SRPT_STATE_NEW:
case SRPT_STATE_DATA_IN:
case SRPT_STATE_MGMT:
/*
* Do nothing - defer abort processing until
* srpt_queue_response() is invoked.
*/
WARN_ON(!transport_check_aborted_status(&ioctx->cmd, false));
break;
case SRPT_STATE_NEED_DATA:
/* DMA_TO_DEVICE (write) - RDMA read error. */
/* XXX(hch): this is a horrible layering violation.. */
spin_lock_irqsave(&ioctx->cmd.t_state_lock, flags);
ioctx->cmd.transport_state &= ~CMD_T_ACTIVE;
spin_unlock_irqrestore(&ioctx->cmd.t_state_lock, flags);
break;
case SRPT_STATE_CMD_RSP_SENT:
/*
* SRP_RSP sending failed or the SRP_RSP send completion has
* not been received in time.
*/
srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
target_put_sess_cmd(&ioctx->cmd);
break;
case SRPT_STATE_MGMT_RSP_SENT:
srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
target_put_sess_cmd(&ioctx->cmd);
break;
default:
WARN(1, "Unexpected command state (%d)", state);
break;
}
out:
return state;
}
/**
* XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
* the data that has been transferred via IB RDMA had to be postponed until the
* check_stop_free() callback. None of this is necessary anymore and needs to
* be cleaned up.
*/
static void srpt_rdma_read_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_send_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe);
WARN_ON(ioctx->n_rdma <= 0);
atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
if (unlikely(wc->status != IB_WC_SUCCESS)) {
pr_info("RDMA_READ for ioctx 0x%p failed with status %d\n",
ioctx, wc->status);
srpt_abort_cmd(ioctx);
return;
}
if (srpt_test_and_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA,
SRPT_STATE_DATA_IN))
target_execute_cmd(&ioctx->cmd);
else
pr_err("%s[%d]: wrong state = %d\n", __func__,
__LINE__, srpt_get_cmd_state(ioctx));
}
static void srpt_rdma_write_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_send_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe);
if (unlikely(wc->status != IB_WC_SUCCESS)) {
pr_info("RDMA_WRITE for ioctx 0x%p failed with status %d\n",
ioctx, wc->status);
srpt_abort_cmd(ioctx);
}
}
/**
* srpt_build_cmd_rsp() - Build an SRP_RSP response.
* @ch: RDMA channel through which the request has been received.
* @ioctx: I/O context associated with the SRP_CMD request. The response will
* be built in the buffer ioctx->buf points at and hence this function will
* overwrite the request data.
* @tag: tag of the request for which this response is being generated.
* @status: value for the STATUS field of the SRP_RSP information unit.
*
* Returns the size in bytes of the SRP_RSP response.
*
* An SRP_RSP response contains a SCSI status or service response. See also
* section 6.9 in the SRP r16a document for the format of an SRP_RSP
* response. See also SPC-2 for more information about sense data.
*/
static int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx, u64 tag,
int status)
{
struct srp_rsp *srp_rsp;
const u8 *sense_data;
int sense_data_len, max_sense_len;
/*
* The lowest bit of all SAM-3 status codes is zero (see also
* paragraph 5.3 in SAM-3).
*/
WARN_ON(status & 1);
srp_rsp = ioctx->ioctx.buf;
BUG_ON(!srp_rsp);
sense_data = ioctx->sense_data;
sense_data_len = ioctx->cmd.scsi_sense_length;
WARN_ON(sense_data_len > sizeof(ioctx->sense_data));
memset(srp_rsp, 0, sizeof *srp_rsp);
srp_rsp->opcode = SRP_RSP;
srp_rsp->req_lim_delta =
cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
srp_rsp->tag = tag;
srp_rsp->status = status;
if (sense_data_len) {
BUILD_BUG_ON(MIN_MAX_RSP_SIZE <= sizeof(*srp_rsp));
max_sense_len = ch->max_ti_iu_len - sizeof(*srp_rsp);
if (sense_data_len > max_sense_len) {
pr_warn("truncated sense data from %d to %d"
" bytes\n", sense_data_len, max_sense_len);
sense_data_len = max_sense_len;
}
srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
srp_rsp->sense_data_len = cpu_to_be32(sense_data_len);
memcpy(srp_rsp + 1, sense_data, sense_data_len);
}
return sizeof(*srp_rsp) + sense_data_len;
}
/**
* srpt_build_tskmgmt_rsp() - Build a task management response.
* @ch: RDMA channel through which the request has been received.
* @ioctx: I/O context in which the SRP_RSP response will be built.
* @rsp_code: RSP_CODE that will be stored in the response.
* @tag: Tag of the request for which this response is being generated.
*
* Returns the size in bytes of the SRP_RSP response.
*
* An SRP_RSP response contains a SCSI status or service response. See also
* section 6.9 in the SRP r16a document for the format of an SRP_RSP
* response.
*/
static int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx,
u8 rsp_code, u64 tag)
{
struct srp_rsp *srp_rsp;
int resp_data_len;
int resp_len;
resp_data_len = 4;
resp_len = sizeof(*srp_rsp) + resp_data_len;
srp_rsp = ioctx->ioctx.buf;
BUG_ON(!srp_rsp);
memset(srp_rsp, 0, sizeof *srp_rsp);
srp_rsp->opcode = SRP_RSP;
srp_rsp->req_lim_delta =
cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
srp_rsp->tag = tag;
srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
srp_rsp->resp_data_len = cpu_to_be32(resp_data_len);
srp_rsp->data[3] = rsp_code;
return resp_len;
}
#define NO_SUCH_LUN ((uint64_t)-1LL)
/*
* SCSI LUN addressing method. See also SAM-2 and the section about
* eight byte LUNs.
*/
enum scsi_lun_addr_method {
SCSI_LUN_ADDR_METHOD_PERIPHERAL = 0,
SCSI_LUN_ADDR_METHOD_FLAT = 1,
SCSI_LUN_ADDR_METHOD_LUN = 2,
SCSI_LUN_ADDR_METHOD_EXTENDED_LUN = 3,
};
/*
* srpt_unpack_lun() - Convert from network LUN to linear LUN.
*
* Convert an 2-byte, 4-byte, 6-byte or 8-byte LUN structure in network byte
* order (big endian) to a linear LUN. Supports three LUN addressing methods:
* peripheral, flat and logical unit. See also SAM-2, section 4.9.4 (page 40).
*/
static uint64_t srpt_unpack_lun(const uint8_t *lun, int len)
{
uint64_t res = NO_SUCH_LUN;
int addressing_method;
if (unlikely(len < 2)) {
pr_err("Illegal LUN length %d, expected 2 bytes or more\n",
len);
goto out;
}
switch (len) {
case 8:
if ((*((__be64 *)lun) &
cpu_to_be64(0x0000FFFFFFFFFFFFLL)) != 0)
goto out_err;
break;
case 4:
if (*((__be16 *)&lun[2]) != 0)
goto out_err;
break;
case 6:
if (*((__be32 *)&lun[2]) != 0)
goto out_err;
break;
case 2:
break;
default:
goto out_err;
}
addressing_method = (*lun) >> 6; /* highest two bits of byte 0 */
switch (addressing_method) {
case SCSI_LUN_ADDR_METHOD_PERIPHERAL:
case SCSI_LUN_ADDR_METHOD_FLAT:
case SCSI_LUN_ADDR_METHOD_LUN:
res = *(lun + 1) | (((*lun) & 0x3f) << 8);
break;
case SCSI_LUN_ADDR_METHOD_EXTENDED_LUN:
default:
pr_err("Unimplemented LUN addressing method %u\n",
addressing_method);
break;
}
out:
return res;
out_err:
pr_err("Support for multi-level LUNs has not yet been implemented\n");
goto out;
}
static int srpt_check_stop_free(struct se_cmd *cmd)
{
struct srpt_send_ioctx *ioctx = container_of(cmd,
struct srpt_send_ioctx, cmd);
return target_put_sess_cmd(&ioctx->cmd);
}
/**
* srpt_handle_cmd() - Process SRP_CMD.
*/
static int srpt_handle_cmd(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct se_cmd *cmd;
struct srp_cmd *srp_cmd;
uint64_t unpacked_lun;
u64 data_len;
enum dma_data_direction dir;
sense_reason_t ret;
int rc;
BUG_ON(!send_ioctx);
srp_cmd = recv_ioctx->ioctx.buf;
cmd = &send_ioctx->cmd;
cmd->tag = srp_cmd->tag;
switch (srp_cmd->task_attr) {
case SRP_CMD_SIMPLE_Q:
cmd->sam_task_attr = TCM_SIMPLE_TAG;
break;
case SRP_CMD_ORDERED_Q:
default:
cmd->sam_task_attr = TCM_ORDERED_TAG;
break;
case SRP_CMD_HEAD_OF_Q:
cmd->sam_task_attr = TCM_HEAD_TAG;
break;
case SRP_CMD_ACA:
cmd->sam_task_attr = TCM_ACA_TAG;
break;
}
if (srpt_get_desc_tbl(send_ioctx, srp_cmd, &dir, &data_len)) {
pr_err("0x%llx: parsing SRP descriptor table failed.\n",
srp_cmd->tag);
ret = TCM_INVALID_CDB_FIELD;
goto send_sense;
}
unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_cmd->lun,
sizeof(srp_cmd->lun));
rc = target_submit_cmd(cmd, ch->sess, srp_cmd->cdb,
&send_ioctx->sense_data[0], unpacked_lun, data_len,
TCM_SIMPLE_TAG, dir, TARGET_SCF_ACK_KREF);
if (rc != 0) {
ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
goto send_sense;
}
return 0;
send_sense:
transport_send_check_condition_and_sense(cmd, ret, 0);
return -1;
}
/**
* srpt_rx_mgmt_fn_tag() - Process a task management function by tag.
* @ch: RDMA channel of the task management request.
* @fn: Task management function to perform.
* @req_tag: Tag of the SRP task management request.
* @mgmt_ioctx: I/O context of the task management request.
*
* Returns zero if the target core will process the task management
* request asynchronously.
*
* Note: It is assumed that the initiator serializes tag-based task management
* requests.
*/
static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)
{
struct srpt_device *sdev;
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *target;
int ret, i;
ret = -EINVAL;
ch = ioctx->ch;
BUG_ON(!ch);
BUG_ON(!ch->sport);
sdev = ch->sport->sdev;
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
for (i = 0; i < ch->rq_size; ++i) {
target = ch->ioctx_ring[i];
if (target->cmd.se_lun == ioctx->cmd.se_lun &&
target->cmd.tag == tag &&
srpt_get_cmd_state(target) != SRPT_STATE_DONE) {
ret = 0;
/* now let the target core abort &target->cmd; */
break;
}
}
spin_unlock_irq(&sdev->spinlock);
return ret;
}
static int srp_tmr_to_tcm(int fn)
{
switch (fn) {
case SRP_TSK_ABORT_TASK:
return TMR_ABORT_TASK;
case SRP_TSK_ABORT_TASK_SET:
return TMR_ABORT_TASK_SET;
case SRP_TSK_CLEAR_TASK_SET:
return TMR_CLEAR_TASK_SET;
case SRP_TSK_LUN_RESET:
return TMR_LUN_RESET;
case SRP_TSK_CLEAR_ACA:
return TMR_CLEAR_ACA;
default:
return -1;
}
}
/**
* srpt_handle_tsk_mgmt() - Process an SRP_TSK_MGMT information unit.
*
* Returns 0 if and only if the request will be processed by the target core.
*
* For more information about SRP_TSK_MGMT information units, see also section
* 6.7 in the SRP r16a document.
*/
static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct srp_tsk_mgmt *srp_tsk;
struct se_cmd *cmd;
struct se_session *sess = ch->sess;
uint64_t unpacked_lun;
uint32_t tag = 0;
int tcm_tmr;
int rc;
BUG_ON(!send_ioctx);
srp_tsk = recv_ioctx->ioctx.buf;
cmd = &send_ioctx->cmd;
pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
" cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
send_ioctx->cmd.tag = srp_tsk->tag;
tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
if (tcm_tmr < 0) {
send_ioctx->cmd.se_tmr_req->response =
TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
goto fail;
}
unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,
sizeof(srp_tsk->lun));
if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {
rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);
if (rc < 0) {
send_ioctx->cmd.se_tmr_req->response =
TMR_TASK_DOES_NOT_EXIST;
goto fail;
}
tag = srp_tsk->task_tag;
}
rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,
srp_tsk, tcm_tmr, GFP_KERNEL, tag,
TARGET_SCF_ACK_KREF);
if (rc != 0) {
send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
goto fail;
}
return;
fail:
transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
}
/**
* srpt_handle_new_iu() - Process a newly received information unit.
* @ch: RDMA channel through which the information unit has been received.
* @ioctx: SRPT I/O context associated with the information unit.
*/
static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct srp_cmd *srp_cmd;
enum rdma_ch_state ch_state;
BUG_ON(!ch);
BUG_ON(!recv_ioctx);
ib_dma_sync_single_for_cpu(ch->sport->sdev->device,
recv_ioctx->ioctx.dma, srp_max_req_size,
DMA_FROM_DEVICE);
ch_state = srpt_get_ch_state(ch);
if (unlikely(ch_state == CH_CONNECTING)) {
list_add_tail(&recv_ioctx->wait_list, &ch->cmd_wait_list);
goto out;
}
if (unlikely(ch_state != CH_LIVE))
goto out;
srp_cmd = recv_ioctx->ioctx.buf;
if (srp_cmd->opcode == SRP_CMD || srp_cmd->opcode == SRP_TSK_MGMT) {
if (!send_ioctx)
send_ioctx = srpt_get_send_ioctx(ch);
if (unlikely(!send_ioctx)) {
list_add_tail(&recv_ioctx->wait_list,
&ch->cmd_wait_list);
goto out;
}
}
switch (srp_cmd->opcode) {
case SRP_CMD:
srpt_handle_cmd(ch, recv_ioctx, send_ioctx);
break;
case SRP_TSK_MGMT:
srpt_handle_tsk_mgmt(ch, recv_ioctx, send_ioctx);
break;
case SRP_I_LOGOUT:
pr_err("Not yet implemented: SRP_I_LOGOUT\n");
break;
case SRP_CRED_RSP:
pr_debug("received SRP_CRED_RSP\n");
break;
case SRP_AER_RSP:
pr_debug("received SRP_AER_RSP\n");
break;
case SRP_RSP:
pr_err("Received SRP_RSP\n");
break;
default:
pr_err("received IU with unknown opcode 0x%x\n",
srp_cmd->opcode);
break;
}
srpt_post_recv(ch->sport->sdev, recv_ioctx);
out:
return;
}
static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_recv_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_recv_ioctx, ioctx.cqe);
if (wc->status == IB_WC_SUCCESS) {
int req_lim;
req_lim = atomic_dec_return(&ch->req_lim);
if (unlikely(req_lim < 0))
pr_err("req_lim = %d < 0\n", req_lim);
srpt_handle_new_iu(ch, ioctx, NULL);
} else {
pr_info("receiving failed for ioctx %p with status %d\n",
ioctx, wc->status);
}
}
/**
* Note: Although this has not yet been observed during tests, at least in
* theory it is possible that the srpt_get_send_ioctx() call invoked by
* srpt_handle_new_iu() fails. This is possible because the req_lim_delta
* value in each response is set to one, and it is possible that this response
* makes the initiator send a new request before the send completion for that
* response has been processed. This could e.g. happen if the call to
* srpt_put_send_iotcx() is delayed because of a higher priority interrupt or
* if IB retransmission causes generation of the send completion to be
* delayed. Incoming information units for which srpt_get_send_ioctx() fails
* are queued on cmd_wait_list. The code below processes these delayed
* requests one at a time.
*/
static void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_send_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_send_ioctx, ioctx.cqe);
enum srpt_command_state state;
state = srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
WARN_ON(state != SRPT_STATE_CMD_RSP_SENT &&
state != SRPT_STATE_MGMT_RSP_SENT);
atomic_inc(&ch->sq_wr_avail);
if (wc->status != IB_WC_SUCCESS) {
pr_info("sending response for ioctx 0x%p failed"
" with status %d\n", ioctx, wc->status);
atomic_dec(&ch->req_lim);
srpt_abort_cmd(ioctx);
goto out;
}
if (state != SRPT_STATE_DONE) {
srpt_unmap_sg_to_ib_sge(ch, ioctx);
transport_generic_free_cmd(&ioctx->cmd, 0);
} else {
pr_err("IB completion has been received too late for"
" wr_id = %u.\n", ioctx->ioctx.index);
}
out:
while (!list_empty(&ch->cmd_wait_list) &&
srpt_get_ch_state(ch) == CH_LIVE &&
(ioctx = srpt_get_send_ioctx(ch)) != NULL) {
struct srpt_recv_ioctx *recv_ioctx;
recv_ioctx = list_first_entry(&ch->cmd_wait_list,
struct srpt_recv_ioctx,
wait_list);
list_del(&recv_ioctx->wait_list);
srpt_handle_new_iu(ch, recv_ioctx, ioctx);
}
}
/**
* srpt_create_ch_ib() - Create receive and send completion queues.
*/
static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
{
struct ib_qp_init_attr *qp_init;
struct srpt_port *sport = ch->sport;
struct srpt_device *sdev = sport->sdev;
u32 srp_sq_size = sport->port_attrib.srp_sq_size;
int ret;
WARN_ON(ch->rq_size < 1);
ret = -ENOMEM;
qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
if (!qp_init)
goto out;
retry:
ch->cq = ib_alloc_cq(sdev->device, ch, ch->rq_size + srp_sq_size,
0 /* XXX: spread CQs */, IB_POLL_WORKQUEUE);
if (IS_ERR(ch->cq)) {
ret = PTR_ERR(ch->cq);
pr_err("failed to create CQ cqe= %d ret= %d\n",
ch->rq_size + srp_sq_size, ret);
goto out;
}
qp_init->qp_context = (void *)ch;
qp_init->event_handler
= (void(*)(struct ib_event *, void*))srpt_qp_event;
qp_init->send_cq = ch->cq;
qp_init->recv_cq = ch->cq;
qp_init->srq = sdev->srq;
qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
qp_init->qp_type = IB_QPT_RC;
qp_init->cap.max_send_wr = srp_sq_size;
qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
ch->qp = ib_create_qp(sdev->pd, qp_init);
if (IS_ERR(ch->qp)) {
ret = PTR_ERR(ch->qp);
if (ret == -ENOMEM) {
srp_sq_size /= 2;
if (srp_sq_size >= MIN_SRPT_SQ_SIZE) {
ib_destroy_cq(ch->cq);
goto retry;
}
}
pr_err("failed to create_qp ret= %d\n", ret);
goto err_destroy_cq;
}
atomic_set(&ch->sq_wr_avail, qp_init->cap.max_send_wr);
pr_debug("%s: max_cqe= %d max_sge= %d sq_size = %d cm_id= %p\n",
__func__, ch->cq->cqe, qp_init->cap.max_send_sge,
qp_init->cap.max_send_wr, ch->cm_id);
ret = srpt_init_ch_qp(ch, ch->qp);
if (ret)
goto err_destroy_qp;
out:
kfree(qp_init);
return ret;
err_destroy_qp:
ib_destroy_qp(ch->qp);
err_destroy_cq:
ib_free_cq(ch->cq);
goto out;
}
static void srpt_destroy_ch_ib(struct srpt_rdma_ch *ch)
{
ib_destroy_qp(ch->qp);
ib_free_cq(ch->cq);
}
/**
* __srpt_close_ch() - Close an RDMA channel by setting the QP error state.
*
* Reset the QP and make sure all resources associated with the channel will
* be deallocated at an appropriate time.
*
* Note: The caller must hold ch->sport->sdev->spinlock.
*/
static void __srpt_close_ch(struct srpt_rdma_ch *ch)
{
enum rdma_ch_state prev_state;
unsigned long flags;
spin_lock_irqsave(&ch->spinlock, flags);
prev_state = ch->state;
switch (prev_state) {
case CH_CONNECTING:
case CH_LIVE:
ch->state = CH_DISCONNECTING;
break;
default:
break;
}
spin_unlock_irqrestore(&ch->spinlock, flags);
switch (prev_state) {
case CH_CONNECTING:
ib_send_cm_rej(ch->cm_id, IB_CM_REJ_NO_RESOURCES, NULL, 0,
NULL, 0);
/* fall through */
case CH_LIVE:
if (ib_send_cm_dreq(ch->cm_id, NULL, 0) < 0)
pr_err("sending CM DREQ failed.\n");
break;
case CH_DISCONNECTING:
break;
case CH_DRAINING:
case CH_RELEASING:
break;
}
}
/**
* srpt_close_ch() - Close an RDMA channel.
*/
static void srpt_close_ch(struct srpt_rdma_ch *ch)
{
struct srpt_device *sdev;
sdev = ch->sport->sdev;
spin_lock_irq(&sdev->spinlock);
__srpt_close_ch(ch);
spin_unlock_irq(&sdev->spinlock);
}
/**
* srpt_shutdown_session() - Whether or not a session may be shut down.
*/
static int srpt_shutdown_session(struct se_session *se_sess)
{
struct srpt_rdma_ch *ch = se_sess->fabric_sess_ptr;
unsigned long flags;
spin_lock_irqsave(&ch->spinlock, flags);
if (ch->in_shutdown) {
spin_unlock_irqrestore(&ch->spinlock, flags);
return true;
}
ch->in_shutdown = true;
target_sess_cmd_list_set_waiting(se_sess);
spin_unlock_irqrestore(&ch->spinlock, flags);
return true;
}
/**
* srpt_drain_channel() - Drain a channel by resetting the IB queue pair.
* @cm_id: Pointer to the CM ID of the channel to be drained.
*
* Note: Must be called from inside srpt_cm_handler to avoid a race between
* accessing sdev->spinlock and the call to kfree(sdev) in srpt_remove_one()
* (the caller of srpt_cm_handler holds the cm_id spinlock; srpt_remove_one()
* waits until all target sessions for the associated IB device have been
* unregistered and target session registration involves a call to
* ib_destroy_cm_id(), which locks the cm_id spinlock and hence waits until
* this function has finished).
*/
static void srpt_drain_channel(struct ib_cm_id *cm_id)
{
struct srpt_device *sdev;
struct srpt_rdma_ch *ch;
int ret;
bool do_reset = false;
WARN_ON_ONCE(irqs_disabled());
sdev = cm_id->context;
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
list_for_each_entry(ch, &sdev->rch_list, list) {
if (ch->cm_id == cm_id) {
do_reset = srpt_test_and_set_ch_state(ch,
CH_CONNECTING, CH_DRAINING) ||
srpt_test_and_set_ch_state(ch,
CH_LIVE, CH_DRAINING) ||
srpt_test_and_set_ch_state(ch,
CH_DISCONNECTING, CH_DRAINING);
break;
}
}
spin_unlock_irq(&sdev->spinlock);
if (do_reset) {
if (ch->sess)
srpt_shutdown_session(ch->sess);
ret = srpt_ch_qp_err(ch);
if (ret < 0)
pr_err("Setting queue pair in error state"
" failed: %d\n", ret);
}
}
/**
* srpt_find_channel() - Look up an RDMA channel.
* @cm_id: Pointer to the CM ID of the channel to be looked up.
*
* Return NULL if no matching RDMA channel has been found.
*/
static struct srpt_rdma_ch *srpt_find_channel(struct srpt_device *sdev,
struct ib_cm_id *cm_id)
{
struct srpt_rdma_ch *ch;
bool found;
WARN_ON_ONCE(irqs_disabled());
BUG_ON(!sdev);
found = false;
spin_lock_irq(&sdev->spinlock);
list_for_each_entry(ch, &sdev->rch_list, list) {
if (ch->cm_id == cm_id) {
found = true;
break;
}
}
spin_unlock_irq(&sdev->spinlock);
return found ? ch : NULL;
}
/**
* srpt_release_channel() - Release channel resources.
*
* Schedules the actual release because:
* - Calling the ib_destroy_cm_id() call from inside an IB CM callback would
* trigger a deadlock.
* - It is not safe to call TCM transport_* functions from interrupt context.
*/
static void srpt_release_channel(struct srpt_rdma_ch *ch)
{
schedule_work(&ch->release_work);
}
static void srpt_release_channel_work(struct work_struct *w)
{
struct srpt_rdma_ch *ch;
struct srpt_device *sdev;
struct se_session *se_sess;
ch = container_of(w, struct srpt_rdma_ch, release_work);
pr_debug("ch = %p; ch->sess = %p; release_done = %p\n", ch, ch->sess,
ch->release_done);
sdev = ch->sport->sdev;
BUG_ON(!sdev);
se_sess = ch->sess;
BUG_ON(!se_sess);
target_wait_for_sess_cmds(se_sess);
transport_deregister_session_configfs(se_sess);
transport_deregister_session(se_sess);
ch->sess = NULL;
ib_destroy_cm_id(ch->cm_id);
srpt_destroy_ch_ib(ch);
srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
ch->sport->sdev, ch->rq_size,
ch->rsp_size, DMA_TO_DEVICE);
spin_lock_irq(&sdev->spinlock);
list_del(&ch->list);
spin_unlock_irq(&sdev->spinlock);
if (ch->release_done)
complete(ch->release_done);
wake_up(&sdev->ch_releaseQ);
kfree(ch);
}
/**
* srpt_cm_req_recv() - Process the event IB_CM_REQ_RECEIVED.
*
* Ownership of the cm_id is transferred to the target session if this
* functions returns zero. Otherwise the caller remains the owner of cm_id.
*/
static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
struct ib_cm_req_event_param *param,
void *private_data)
{
struct srpt_device *sdev = cm_id->context;
struct srpt_port *sport = &sdev->port[param->port - 1];
struct srp_login_req *req;
struct srp_login_rsp *rsp;
struct srp_login_rej *rej;
struct ib_cm_rep_param *rep_param;
struct srpt_rdma_ch *ch, *tmp_ch;
struct se_node_acl *se_acl;
u32 it_iu_len;
int i, ret = 0;
unsigned char *p;
WARN_ON_ONCE(irqs_disabled());
if (WARN_ON(!sdev || !private_data))
return -EINVAL;
req = (struct srp_login_req *)private_data;
it_iu_len = be32_to_cpu(req->req_it_iu_len);
pr_info("Received SRP_LOGIN_REQ with i_port_id 0x%llx:0x%llx,"
" t_port_id 0x%llx:0x%llx and it_iu_len %d on port %d"
" (guid=0x%llx:0x%llx)\n",
be64_to_cpu(*(__be64 *)&req->initiator_port_id[0]),
be64_to_cpu(*(__be64 *)&req->initiator_port_id[8]),
be64_to_cpu(*(__be64 *)&req->target_port_id[0]),
be64_to_cpu(*(__be64 *)&req->target_port_id[8]),
it_iu_len,
param->port,
be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[0]),
be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[8]));
rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
rej = kzalloc(sizeof *rej, GFP_KERNEL);
rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
if (!rsp || !rej || !rep_param) {
ret = -ENOMEM;
goto out;
}
if (it_iu_len > srp_max_req_size || it_iu_len < 64) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
ret = -EINVAL;
pr_err("rejected SRP_LOGIN_REQ because its"
" length (%d bytes) is out of range (%d .. %d)\n",
it_iu_len, 64, srp_max_req_size);
goto reject;
}
if (!sport->enabled) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
ret = -EINVAL;
pr_err("rejected SRP_LOGIN_REQ because the target port"
" has not yet been enabled\n");
goto reject;
}
if ((req->req_flags & SRP_MTCH_ACTION) == SRP_MULTICHAN_SINGLE) {
rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
spin_lock_irq(&sdev->spinlock);
list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
&& !memcmp(ch->t_port_id, req->target_port_id, 16)
&& param->port == ch->sport->port
&& param->listen_id == ch->sport->sdev->cm_id
&& ch->cm_id) {
enum rdma_ch_state ch_state;
ch_state = srpt_get_ch_state(ch);
if (ch_state != CH_CONNECTING
&& ch_state != CH_LIVE)
continue;
/* found an existing channel */
pr_debug("Found existing channel %s"
" cm_id= %p state= %d\n",
ch->sess_name, ch->cm_id, ch_state);
__srpt_close_ch(ch);
rsp->rsp_flags =
SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
}
}
spin_unlock_irq(&sdev->spinlock);
} else
rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
if (*(__be64 *)req->target_port_id != cpu_to_be64(srpt_service_guid)
|| *(__be64 *)(req->target_port_id + 8) !=
cpu_to_be64(srpt_service_guid)) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
ret = -ENOMEM;
pr_err("rejected SRP_LOGIN_REQ because it"
" has an invalid target port identifier.\n");
goto reject;
}
ch = kzalloc(sizeof *ch, GFP_KERNEL);
if (!ch) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_err("rejected SRP_LOGIN_REQ because no memory.\n");
ret = -ENOMEM;
goto reject;
}
INIT_WORK(&ch->release_work, srpt_release_channel_work);
memcpy(ch->i_port_id, req->initiator_port_id, 16);
memcpy(ch->t_port_id, req->target_port_id, 16);
ch->sport = &sdev->port[param->port - 1];
ch->cm_id = cm_id;
/*
* Avoid QUEUE_FULL conditions by limiting the number of buffers used
* for the SRP protocol to the command queue size.
*/
ch->rq_size = SRPT_RQ_SIZE;
spin_lock_init(&ch->spinlock);
ch->state = CH_CONNECTING;
INIT_LIST_HEAD(&ch->cmd_wait_list);
ch->rsp_size = ch->sport->port_attrib.srp_max_rsp_size;
ch->ioctx_ring = (struct srpt_send_ioctx **)
srpt_alloc_ioctx_ring(ch->sport->sdev, ch->rq_size,
sizeof(*ch->ioctx_ring[0]),
ch->rsp_size, DMA_TO_DEVICE);
if (!ch->ioctx_ring)
goto free_ch;
INIT_LIST_HEAD(&ch->free_list);
for (i = 0; i < ch->rq_size; i++) {
ch->ioctx_ring[i]->ch = ch;
list_add_tail(&ch->ioctx_ring[i]->free_list, &ch->free_list);
}
ret = srpt_create_ch_ib(ch);
if (ret) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_err("rejected SRP_LOGIN_REQ because creating"
" a new RDMA channel failed.\n");
goto free_ring;
}
ret = srpt_ch_qp_rtr(ch, ch->qp);
if (ret) {
rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_err("rejected SRP_LOGIN_REQ because enabling"
" RTR failed (error code = %d)\n", ret);
goto destroy_ib;
}
/*
* Use the initator port identifier as the session name, when
* checking against se_node_acl->initiatorname[] this can be
* with or without preceeding '0x'.
*/
snprintf(ch->sess_name, sizeof(ch->sess_name), "0x%016llx%016llx",
be64_to_cpu(*(__be64 *)ch->i_port_id),
be64_to_cpu(*(__be64 *)(ch->i_port_id + 8)));
pr_debug("registering session %s\n", ch->sess_name);
p = &ch->sess_name[0];
ch->sess = transport_init_session(TARGET_PROT_NORMAL);
if (IS_ERR(ch->sess)) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_debug("Failed to create session\n");
goto destroy_ib;
}
try_again:
se_acl = core_tpg_get_initiator_node_acl(&sport->port_tpg_1, p);
if (!se_acl) {
pr_info("Rejected login because no ACL has been"
" configured yet for initiator %s.\n", ch->sess_name);
/*
* XXX: Hack to retry of ch->i_port_id without leading '0x'
*/
if (p == &ch->sess_name[0]) {
p += 2;
goto try_again;
}
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_CHANNEL_LIMIT_REACHED);
transport_free_session(ch->sess);
goto destroy_ib;
}
ch->sess->se_node_acl = se_acl;
transport_register_session(&sport->port_tpg_1, se_acl, ch->sess, ch);
pr_debug("Establish connection sess=%p name=%s cm_id=%p\n", ch->sess,
ch->sess_name, ch->cm_id);
/* create srp_login_response */
rsp->opcode = SRP_LOGIN_RSP;
rsp->tag = req->tag;
rsp->max_it_iu_len = req->req_it_iu_len;
rsp->max_ti_iu_len = req->req_it_iu_len;
ch->max_ti_iu_len = it_iu_len;
rsp->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
| SRP_BUF_FORMAT_INDIRECT);
rsp->req_lim_delta = cpu_to_be32(ch->rq_size);
atomic_set(&ch->req_lim, ch->rq_size);
atomic_set(&ch->req_lim_delta, 0);
/* create cm reply */
rep_param->qp_num = ch->qp->qp_num;
rep_param->private_data = (void *)rsp;
rep_param->private_data_len = sizeof *rsp;
rep_param->rnr_retry_count = 7;
rep_param->flow_control = 1;
rep_param->failover_accepted = 0;
rep_param->srq = 1;
rep_param->responder_resources = 4;
rep_param->initiator_depth = 4;
ret = ib_send_cm_rep(cm_id, rep_param);
if (ret) {
pr_err("sending SRP_LOGIN_REQ response failed"
" (error code = %d)\n", ret);
goto release_channel;
}
spin_lock_irq(&sdev->spinlock);
list_add_tail(&ch->list, &sdev->rch_list);
spin_unlock_irq(&sdev->spinlock);
goto out;
release_channel:
srpt_set_ch_state(ch, CH_RELEASING);
transport_deregister_session_configfs(ch->sess);
transport_deregister_session(ch->sess);
ch->sess = NULL;
destroy_ib:
srpt_destroy_ch_ib(ch);
free_ring:
srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
ch->sport->sdev, ch->rq_size,
ch->rsp_size, DMA_TO_DEVICE);
free_ch:
kfree(ch);
reject:
rej->opcode = SRP_LOGIN_REJ;
rej->tag = req->tag;
rej->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
| SRP_BUF_FORMAT_INDIRECT);
ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
(void *)rej, sizeof *rej);
out:
kfree(rep_param);
kfree(rsp);
kfree(rej);
return ret;
}
static void srpt_cm_rej_recv(struct ib_cm_id *cm_id)
{
pr_info("Received IB REJ for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
/**
* srpt_cm_rtu_recv() - Process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event.
*
* An IB_CM_RTU_RECEIVED message indicates that the connection is established
* and that the recipient may begin transmitting (RTU = ready to use).
*/
static void srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
{
struct srpt_rdma_ch *ch;
int ret;
ch = srpt_find_channel(cm_id->context, cm_id);
BUG_ON(!ch);
if (srpt_test_and_set_ch_state(ch, CH_CONNECTING, CH_LIVE)) {
struct srpt_recv_ioctx *ioctx, *ioctx_tmp;
ret = srpt_ch_qp_rts(ch, ch->qp);
list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
wait_list) {
list_del(&ioctx->wait_list);
srpt_handle_new_iu(ch, ioctx, NULL);
}
if (ret)
srpt_close_ch(ch);
}
}
static void srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
{
pr_info("Received IB TimeWait exit for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
static void srpt_cm_rep_error(struct ib_cm_id *cm_id)
{
pr_info("Received IB REP error for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
/**
* srpt_cm_dreq_recv() - Process reception of a DREQ message.
*/
static void srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
{
struct srpt_rdma_ch *ch;
unsigned long flags;
bool send_drep = false;
ch = srpt_find_channel(cm_id->context, cm_id);
BUG_ON(!ch);
pr_debug("cm_id= %p ch->state= %d\n", cm_id, srpt_get_ch_state(ch));
spin_lock_irqsave(&ch->spinlock, flags);
switch (ch->state) {
case CH_CONNECTING:
case CH_LIVE:
send_drep = true;
ch->state = CH_DISCONNECTING;
break;
case CH_DISCONNECTING:
case CH_DRAINING:
case CH_RELEASING:
WARN(true, "unexpected channel state %d\n", ch->state);
break;
}
spin_unlock_irqrestore(&ch->spinlock, flags);
if (send_drep) {
if (ib_send_cm_drep(ch->cm_id, NULL, 0) < 0)
pr_err("Sending IB DREP failed.\n");
pr_info("Received DREQ and sent DREP for session %s.\n",
ch->sess_name);
}
}
/**
* srpt_cm_drep_recv() - Process reception of a DREP message.
*/
static void srpt_cm_drep_recv(struct ib_cm_id *cm_id)
{
pr_info("Received InfiniBand DREP message for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
/**
* srpt_cm_handler() - IB connection manager callback function.
*
* A non-zero return value will cause the caller destroy the CM ID.
*
* Note: srpt_cm_handler() must only return a non-zero value when transferring
* ownership of the cm_id to a channel by srpt_cm_req_recv() failed. Returning
* a non-zero value in any other case will trigger a race with the
* ib_destroy_cm_id() call in srpt_release_channel().
*/
static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
{
int ret;
ret = 0;
switch (event->event) {
case IB_CM_REQ_RECEIVED:
ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
event->private_data);
break;
case IB_CM_REJ_RECEIVED:
srpt_cm_rej_recv(cm_id);
break;
case IB_CM_RTU_RECEIVED:
case IB_CM_USER_ESTABLISHED:
srpt_cm_rtu_recv(cm_id);
break;
case IB_CM_DREQ_RECEIVED:
srpt_cm_dreq_recv(cm_id);
break;
case IB_CM_DREP_RECEIVED:
srpt_cm_drep_recv(cm_id);
break;
case IB_CM_TIMEWAIT_EXIT:
srpt_cm_timewait_exit(cm_id);
break;
case IB_CM_REP_ERROR:
srpt_cm_rep_error(cm_id);
break;
case IB_CM_DREQ_ERROR:
pr_info("Received IB DREQ ERROR event.\n");
break;
case IB_CM_MRA_RECEIVED:
pr_info("Received IB MRA event\n");
break;
default:
pr_err("received unrecognized IB CM event %d\n", event->event);
break;
}
return ret;
}
/**
* srpt_perform_rdmas() - Perform IB RDMA.
*
* Returns zero upon success or a negative number upon failure.
*/
static int srpt_perform_rdmas(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
struct ib_send_wr *bad_wr;
int sq_wr_avail, ret, i;
enum dma_data_direction dir;
const int n_rdma = ioctx->n_rdma;
dir = ioctx->cmd.data_direction;
if (dir == DMA_TO_DEVICE) {
/* write */
ret = -ENOMEM;
sq_wr_avail = atomic_sub_return(n_rdma, &ch->sq_wr_avail);
if (sq_wr_avail < 0) {
pr_warn("IB send queue full (needed %d)\n",
n_rdma);
goto out;
}
}
for (i = 0; i < n_rdma; i++) {
struct ib_send_wr *wr = &ioctx->rdma_wrs[i].wr;
wr->opcode = (dir == DMA_FROM_DEVICE) ?
IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
if (i == n_rdma - 1) {
/* only get completion event for the last rdma read */
if (dir == DMA_TO_DEVICE) {
wr->send_flags = IB_SEND_SIGNALED;
ioctx->rdma_cqe.done = srpt_rdma_read_done;
} else {
ioctx->rdma_cqe.done = srpt_rdma_write_done;
}
wr->wr_cqe = &ioctx->rdma_cqe;
wr->next = NULL;
} else {
wr->wr_cqe = NULL;
wr->next = &ioctx->rdma_wrs[i + 1].wr;
}
}
ret = ib_post_send(ch->qp, &ioctx->rdma_wrs->wr, &bad_wr);
if (ret)
pr_err("%s[%d]: ib_post_send() returned %d for %d/%d\n",
__func__, __LINE__, ret, i, n_rdma);
out:
if (unlikely(dir == DMA_TO_DEVICE && ret < 0))
atomic_add(n_rdma, &ch->sq_wr_avail);
return ret;
}
/**
* srpt_xfer_data() - Start data transfer from initiator to target.
*/
static int srpt_xfer_data(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
int ret;
ret = srpt_map_sg_to_ib_sge(ch, ioctx);
if (ret) {
pr_err("%s[%d] ret=%d\n", __func__, __LINE__, ret);
goto out;
}
ret = srpt_perform_rdmas(ch, ioctx);
if (ret) {
if (ret == -EAGAIN || ret == -ENOMEM)
pr_info("%s[%d] queue full -- ret=%d\n",
__func__, __LINE__, ret);
else
pr_err("%s[%d] fatal error -- ret=%d\n",
__func__, __LINE__, ret);
goto out_unmap;
}
out:
return ret;
out_unmap:
srpt_unmap_sg_to_ib_sge(ch, ioctx);
goto out;
}
static int srpt_write_pending_status(struct se_cmd *se_cmd)
{
struct srpt_send_ioctx *ioctx;
ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
return srpt_get_cmd_state(ioctx) == SRPT_STATE_NEED_DATA;
}
/*
* srpt_write_pending() - Start data transfer from initiator to target (write).
*/
static int srpt_write_pending(struct se_cmd *se_cmd)
{
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *ioctx;
enum srpt_command_state new_state;
enum rdma_ch_state ch_state;
int ret;
ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
new_state = srpt_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA);
WARN_ON(new_state == SRPT_STATE_DONE);
ch = ioctx->ch;
BUG_ON(!ch);
ch_state = srpt_get_ch_state(ch);
switch (ch_state) {
case CH_CONNECTING:
WARN(true, "unexpected channel state %d\n", ch_state);
ret = -EINVAL;
goto out;
case CH_LIVE:
break;
case CH_DISCONNECTING:
case CH_DRAINING:
case CH_RELEASING:
pr_debug("cmd with tag %lld: channel disconnecting\n",
ioctx->cmd.tag);
srpt_set_cmd_state(ioctx, SRPT_STATE_DATA_IN);
ret = -EINVAL;
goto out;
}
ret = srpt_xfer_data(ch, ioctx);
out:
return ret;
}
static u8 tcm_to_srp_tsk_mgmt_status(const int tcm_mgmt_status)
{
switch (tcm_mgmt_status) {
case TMR_FUNCTION_COMPLETE:
return SRP_TSK_MGMT_SUCCESS;
case TMR_FUNCTION_REJECTED:
return SRP_TSK_MGMT_FUNC_NOT_SUPP;
}
return SRP_TSK_MGMT_FAILED;
}
/**
* srpt_queue_response() - Transmits the response to a SCSI command.
*
* Callback function called by the TCM core. Must not block since it can be
* invoked on the context of the IB completion handler.
*/
static void srpt_queue_response(struct se_cmd *cmd)
{
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *ioctx;
enum srpt_command_state state;
unsigned long flags;
int ret;
enum dma_data_direction dir;
int resp_len;
u8 srp_tm_status;
ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
ch = ioctx->ch;
BUG_ON(!ch);
spin_lock_irqsave(&ioctx->spinlock, flags);
state = ioctx->state;
switch (state) {
case SRPT_STATE_NEW:
case SRPT_STATE_DATA_IN:
ioctx->state = SRPT_STATE_CMD_RSP_SENT;
break;
case SRPT_STATE_MGMT:
ioctx->state = SRPT_STATE_MGMT_RSP_SENT;
break;
default:
WARN(true, "ch %p; cmd %d: unexpected command state %d\n",
ch, ioctx->ioctx.index, ioctx->state);
break;
}
spin_unlock_irqrestore(&ioctx->spinlock, flags);
if (unlikely(transport_check_aborted_status(&ioctx->cmd, false)
|| WARN_ON_ONCE(state == SRPT_STATE_CMD_RSP_SENT))) {
atomic_inc(&ch->req_lim_delta);
srpt_abort_cmd(ioctx);
return;
}
dir = ioctx->cmd.data_direction;
/* For read commands, transfer the data to the initiator. */
if (dir == DMA_FROM_DEVICE && ioctx->cmd.data_length &&
!ioctx->queue_status_only) {
ret = srpt_xfer_data(ch, ioctx);
if (ret) {
pr_err("xfer_data failed for tag %llu\n",
ioctx->cmd.tag);
return;
}
}
if (state != SRPT_STATE_MGMT)
resp_len = srpt_build_cmd_rsp(ch, ioctx, ioctx->cmd.tag,
cmd->scsi_status);
else {
srp_tm_status
= tcm_to_srp_tsk_mgmt_status(cmd->se_tmr_req->response);
resp_len = srpt_build_tskmgmt_rsp(ch, ioctx, srp_tm_status,
ioctx->cmd.tag);
}
ret = srpt_post_send(ch, ioctx, resp_len);
if (ret) {
pr_err("sending cmd response failed for tag %llu\n",
ioctx->cmd.tag);
srpt_unmap_sg_to_ib_sge(ch, ioctx);
srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
target_put_sess_cmd(&ioctx->cmd);
}
}
static int srpt_queue_data_in(struct se_cmd *cmd)
{
srpt_queue_response(cmd);
return 0;
}
static void srpt_queue_tm_rsp(struct se_cmd *cmd)
{
srpt_queue_response(cmd);
}
static void srpt_aborted_task(struct se_cmd *cmd)
{
struct srpt_send_ioctx *ioctx = container_of(cmd,
struct srpt_send_ioctx, cmd);
srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
}
static int srpt_queue_status(struct se_cmd *cmd)
{
struct srpt_send_ioctx *ioctx;
ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
BUG_ON(ioctx->sense_data != cmd->sense_buffer);
if (cmd->se_cmd_flags &
(SCF_TRANSPORT_TASK_SENSE | SCF_EMULATED_TASK_SENSE))
WARN_ON(cmd->scsi_status != SAM_STAT_CHECK_CONDITION);
ioctx->queue_status_only = true;
srpt_queue_response(cmd);
return 0;
}
static void srpt_refresh_port_work(struct work_struct *work)
{
struct srpt_port *sport = container_of(work, struct srpt_port, work);
srpt_refresh_port(sport);
}
static int srpt_ch_list_empty(struct srpt_device *sdev)
{
int res;
spin_lock_irq(&sdev->spinlock);
res = list_empty(&sdev->rch_list);
spin_unlock_irq(&sdev->spinlock);
return res;
}
/**
* srpt_release_sdev() - Free the channel resources associated with a target.
*/
static int srpt_release_sdev(struct srpt_device *sdev)
{
struct srpt_rdma_ch *ch, *tmp_ch;
int res;
WARN_ON_ONCE(irqs_disabled());
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
__srpt_close_ch(ch);
spin_unlock_irq(&sdev->spinlock);
res = wait_event_interruptible(sdev->ch_releaseQ,
srpt_ch_list_empty(sdev));
if (res)
pr_err("%s: interrupted.\n", __func__);
return 0;
}
static struct srpt_port *__srpt_lookup_port(const char *name)
{
struct ib_device *dev;
struct srpt_device *sdev;
struct srpt_port *sport;
int i;
list_for_each_entry(sdev, &srpt_dev_list, list) {
dev = sdev->device;
if (!dev)
continue;
for (i = 0; i < dev->phys_port_cnt; i++) {
sport = &sdev->port[i];
if (!strcmp(sport->port_guid, name))
return sport;
}
}
return NULL;
}
static struct srpt_port *srpt_lookup_port(const char *name)
{
struct srpt_port *sport;
spin_lock(&srpt_dev_lock);
sport = __srpt_lookup_port(name);
spin_unlock(&srpt_dev_lock);
return sport;
}
/**
* srpt_add_one() - Infiniband device addition callback function.
*/
static void srpt_add_one(struct ib_device *device)
{
struct srpt_device *sdev;
struct srpt_port *sport;
struct ib_srq_init_attr srq_attr;
int i;
pr_debug("device = %p, device->dma_ops = %p\n", device,
device->dma_ops);
sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
if (!sdev)
goto err;
sdev->device = device;
INIT_LIST_HEAD(&sdev->rch_list);
init_waitqueue_head(&sdev->ch_releaseQ);
spin_lock_init(&sdev->spinlock);
sdev->pd = ib_alloc_pd(device);
if (IS_ERR(sdev->pd))
goto free_dev;
sdev->srq_size = min(srpt_srq_size, sdev->device->attrs.max_srq_wr);
srq_attr.event_handler = srpt_srq_event;
srq_attr.srq_context = (void *)sdev;
srq_attr.attr.max_wr = sdev->srq_size;
srq_attr.attr.max_sge = 1;
srq_attr.attr.srq_limit = 0;
srq_attr.srq_type = IB_SRQT_BASIC;
sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
if (IS_ERR(sdev->srq))
goto err_pd;
pr_debug("%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
__func__, sdev->srq_size, sdev->device->attrs.max_srq_wr,
device->name);
if (!srpt_service_guid)
srpt_service_guid = be64_to_cpu(device->node_guid);
sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
if (IS_ERR(sdev->cm_id))
goto err_srq;
/* print out target login information */
pr_debug("Target login info: id_ext=%016llx,ioc_guid=%016llx,"
"pkey=ffff,service_id=%016llx\n", srpt_service_guid,
srpt_service_guid, srpt_service_guid);
/*
* We do not have a consistent service_id (ie. also id_ext of target_id)
* to identify this target. We currently use the guid of the first HCA
* in the system as service_id; therefore, the target_id will change
* if this HCA is gone bad and replaced by different HCA
*/
if (ib_cm_listen(sdev->cm_id, cpu_to_be64(srpt_service_guid), 0))
goto err_cm;
INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
srpt_event_handler);
if (ib_register_event_handler(&sdev->event_handler))
goto err_cm;
sdev->ioctx_ring = (struct srpt_recv_ioctx **)
srpt_alloc_ioctx_ring(sdev, sdev->srq_size,
sizeof(*sdev->ioctx_ring[0]),
srp_max_req_size, DMA_FROM_DEVICE);
if (!sdev->ioctx_ring)
goto err_event;
for (i = 0; i < sdev->srq_size; ++i)
srpt_post_recv(sdev, sdev->ioctx_ring[i]);
WARN_ON(sdev->device->phys_port_cnt > ARRAY_SIZE(sdev->port));
for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
sport = &sdev->port[i - 1];
sport->sdev = sdev;
sport->port = i;
sport->port_attrib.srp_max_rdma_size = DEFAULT_MAX_RDMA_SIZE;
sport->port_attrib.srp_max_rsp_size = DEFAULT_MAX_RSP_SIZE;
sport->port_attrib.srp_sq_size = DEF_SRPT_SQ_SIZE;
INIT_WORK(&sport->work, srpt_refresh_port_work);
if (srpt_refresh_port(sport)) {
pr_err("MAD registration failed for %s-%d.\n",
srpt_sdev_name(sdev), i);
goto err_ring;
}
snprintf(sport->port_guid, sizeof(sport->port_guid),
"0x%016llx%016llx",
be64_to_cpu(sport->gid.global.subnet_prefix),
be64_to_cpu(sport->gid.global.interface_id));
}
spin_lock(&srpt_dev_lock);
list_add_tail(&sdev->list, &srpt_dev_list);
spin_unlock(&srpt_dev_lock);
out:
ib_set_client_data(device, &srpt_client, sdev);
pr_debug("added %s.\n", device->name);
return;
err_ring:
srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
sdev->srq_size, srp_max_req_size,
DMA_FROM_DEVICE);
err_event:
ib_unregister_event_handler(&sdev->event_handler);
err_cm:
ib_destroy_cm_id(sdev->cm_id);
err_srq:
ib_destroy_srq(sdev->srq);
err_pd:
ib_dealloc_pd(sdev->pd);
free_dev:
kfree(sdev);
err:
sdev = NULL;
pr_info("%s(%s) failed.\n", __func__, device->name);
goto out;
}
/**
* srpt_remove_one() - InfiniBand device removal callback function.
*/
static void srpt_remove_one(struct ib_device *device, void *client_data)
{
struct srpt_device *sdev = client_data;
int i;
if (!sdev) {
pr_info("%s(%s): nothing to do.\n", __func__, device->name);
return;
}
srpt_unregister_mad_agent(sdev);
ib_unregister_event_handler(&sdev->event_handler);
/* Cancel any work queued by the just unregistered IB event handler. */
for (i = 0; i < sdev->device->phys_port_cnt; i++)
cancel_work_sync(&sdev->port[i].work);
ib_destroy_cm_id(sdev->cm_id);
/*
* Unregistering a target must happen after destroying sdev->cm_id
* such that no new SRP_LOGIN_REQ information units can arrive while
* destroying the target.
*/
spin_lock(&srpt_dev_lock);
list_del(&sdev->list);
spin_unlock(&srpt_dev_lock);
srpt_release_sdev(sdev);
ib_destroy_srq(sdev->srq);
ib_dealloc_pd(sdev->pd);
srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
sdev->srq_size, srp_max_req_size, DMA_FROM_DEVICE);
sdev->ioctx_ring = NULL;
kfree(sdev);
}
static struct ib_client srpt_client = {
.name = DRV_NAME,
.add = srpt_add_one,
.remove = srpt_remove_one
};
static int srpt_check_true(struct se_portal_group *se_tpg)
{
return 1;
}
static int srpt_check_false(struct se_portal_group *se_tpg)
{
return 0;
}
static char *srpt_get_fabric_name(void)
{
return "srpt";
}
static char *srpt_get_fabric_wwn(struct se_portal_group *tpg)
{
struct srpt_port *sport = container_of(tpg, struct srpt_port, port_tpg_1);
return sport->port_guid;
}
static u16 srpt_get_tag(struct se_portal_group *tpg)
{
return 1;
}
static u32 srpt_tpg_get_inst_index(struct se_portal_group *se_tpg)
{
return 1;
}
static void srpt_release_cmd(struct se_cmd *se_cmd)
{
struct srpt_send_ioctx *ioctx = container_of(se_cmd,
struct srpt_send_ioctx, cmd);
struct srpt_rdma_ch *ch = ioctx->ch;
unsigned long flags;
WARN_ON(ioctx->state != SRPT_STATE_DONE);
WARN_ON(ioctx->mapped_sg_count != 0);
if (ioctx->n_rbuf > 1) {
kfree(ioctx->rbufs);
ioctx->rbufs = NULL;
ioctx->n_rbuf = 0;
}
spin_lock_irqsave(&ch->spinlock, flags);
list_add(&ioctx->free_list, &ch->free_list);
spin_unlock_irqrestore(&ch->spinlock, flags);
}
/**
* srpt_close_session() - Forcibly close a session.
*
* Callback function invoked by the TCM core to clean up sessions associated
* with a node ACL when the user invokes
* rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
*/
static void srpt_close_session(struct se_session *se_sess)
{
DECLARE_COMPLETION_ONSTACK(release_done);
struct srpt_rdma_ch *ch;
struct srpt_device *sdev;
unsigned long res;
ch = se_sess->fabric_sess_ptr;
WARN_ON(ch->sess != se_sess);
pr_debug("ch %p state %d\n", ch, srpt_get_ch_state(ch));
sdev = ch->sport->sdev;
spin_lock_irq(&sdev->spinlock);
BUG_ON(ch->release_done);
ch->release_done = &release_done;
__srpt_close_ch(ch);
spin_unlock_irq(&sdev->spinlock);
res = wait_for_completion_timeout(&release_done, 60 * HZ);
WARN_ON(res == 0);
}
/**
* srpt_sess_get_index() - Return the value of scsiAttIntrPortIndex (SCSI-MIB).
*
* A quote from RFC 4455 (SCSI-MIB) about this MIB object:
* This object represents an arbitrary integer used to uniquely identify a
* particular attached remote initiator port to a particular SCSI target port
* within a particular SCSI target device within a particular SCSI instance.
*/
static u32 srpt_sess_get_index(struct se_session *se_sess)
{
return 0;
}
static void srpt_set_default_node_attrs(struct se_node_acl *nacl)
{
}
/* Note: only used from inside debug printk's by the TCM core. */
static int srpt_get_tcm_cmd_state(struct se_cmd *se_cmd)
{
struct srpt_send_ioctx *ioctx;
ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
return srpt_get_cmd_state(ioctx);
}
/**
* srpt_parse_i_port_id() - Parse an initiator port ID.
* @name: ASCII representation of a 128-bit initiator port ID.
* @i_port_id: Binary 128-bit port ID.
*/
static int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
{
const char *p;
unsigned len, count, leading_zero_bytes;
int ret, rc;
p = name;
if (strncasecmp(p, "0x", 2) == 0)
p += 2;
ret = -EINVAL;
len = strlen(p);
if (len % 2)
goto out;
count = min(len / 2, 16U);
leading_zero_bytes = 16 - count;
memset(i_port_id, 0, leading_zero_bytes);
rc = hex2bin(i_port_id + leading_zero_bytes, p, count);
if (rc < 0)
pr_debug("hex2bin failed for srpt_parse_i_port_id: %d\n", rc);
ret = 0;
out:
return ret;
}
/*
* configfs callback function invoked for
* mkdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
*/
static int srpt_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
{
u8 i_port_id[16];
if (srpt_parse_i_port_id(i_port_id, name) < 0) {
pr_err("invalid initiator port ID %s\n", name);
return -EINVAL;
}
return 0;
}
static ssize_t srpt_tpg_attrib_srp_max_rdma_size_show(struct config_item *item,
char *page)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return sprintf(page, "%u\n", sport->port_attrib.srp_max_rdma_size);
}
static ssize_t srpt_tpg_attrib_srp_max_rdma_size_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long val;
int ret;
ret = kstrtoul(page, 0, &val);
if (ret < 0) {
pr_err("kstrtoul() failed with ret: %d\n", ret);
return -EINVAL;
}
if (val > MAX_SRPT_RDMA_SIZE) {
pr_err("val: %lu exceeds MAX_SRPT_RDMA_SIZE: %d\n", val,
MAX_SRPT_RDMA_SIZE);
return -EINVAL;
}
if (val < DEFAULT_MAX_RDMA_SIZE) {
pr_err("val: %lu smaller than DEFAULT_MAX_RDMA_SIZE: %d\n",
val, DEFAULT_MAX_RDMA_SIZE);
return -EINVAL;
}
sport->port_attrib.srp_max_rdma_size = val;
return count;
}
static ssize_t srpt_tpg_attrib_srp_max_rsp_size_show(struct config_item *item,
char *page)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return sprintf(page, "%u\n", sport->port_attrib.srp_max_rsp_size);
}
static ssize_t srpt_tpg_attrib_srp_max_rsp_size_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long val;
int ret;
ret = kstrtoul(page, 0, &val);
if (ret < 0) {
pr_err("kstrtoul() failed with ret: %d\n", ret);
return -EINVAL;
}
if (val > MAX_SRPT_RSP_SIZE) {
pr_err("val: %lu exceeds MAX_SRPT_RSP_SIZE: %d\n", val,
MAX_SRPT_RSP_SIZE);
return -EINVAL;
}
if (val < MIN_MAX_RSP_SIZE) {
pr_err("val: %lu smaller than MIN_MAX_RSP_SIZE: %d\n", val,
MIN_MAX_RSP_SIZE);
return -EINVAL;
}
sport->port_attrib.srp_max_rsp_size = val;
return count;
}
static ssize_t srpt_tpg_attrib_srp_sq_size_show(struct config_item *item,
char *page)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return sprintf(page, "%u\n", sport->port_attrib.srp_sq_size);
}
static ssize_t srpt_tpg_attrib_srp_sq_size_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long val;
int ret;
ret = kstrtoul(page, 0, &val);
if (ret < 0) {
pr_err("kstrtoul() failed with ret: %d\n", ret);
return -EINVAL;
}
if (val > MAX_SRPT_SRQ_SIZE) {
pr_err("val: %lu exceeds MAX_SRPT_SRQ_SIZE: %d\n", val,
MAX_SRPT_SRQ_SIZE);
return -EINVAL;
}
if (val < MIN_SRPT_SRQ_SIZE) {
pr_err("val: %lu smaller than MIN_SRPT_SRQ_SIZE: %d\n", val,
MIN_SRPT_SRQ_SIZE);
return -EINVAL;
}
sport->port_attrib.srp_sq_size = val;
return count;
}
CONFIGFS_ATTR(srpt_tpg_attrib_, srp_max_rdma_size);
CONFIGFS_ATTR(srpt_tpg_attrib_, srp_max_rsp_size);
CONFIGFS_ATTR(srpt_tpg_attrib_, srp_sq_size);
static struct configfs_attribute *srpt_tpg_attrib_attrs[] = {
&srpt_tpg_attrib_attr_srp_max_rdma_size,
&srpt_tpg_attrib_attr_srp_max_rsp_size,
&srpt_tpg_attrib_attr_srp_sq_size,
NULL,
};
static ssize_t srpt_tpg_enable_show(struct config_item *item, char *page)
{
struct se_portal_group *se_tpg = to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return snprintf(page, PAGE_SIZE, "%d\n", (sport->enabled) ? 1: 0);
}
static ssize_t srpt_tpg_enable_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long tmp;
int ret;
ret = kstrtoul(page, 0, &tmp);
if (ret < 0) {
pr_err("Unable to extract srpt_tpg_store_enable\n");
return -EINVAL;
}
if ((tmp != 0) && (tmp != 1)) {
pr_err("Illegal value for srpt_tpg_store_enable: %lu\n", tmp);
return -EINVAL;
}
if (tmp == 1)
sport->enabled = true;
else
sport->enabled = false;
return count;
}
CONFIGFS_ATTR(srpt_tpg_, enable);
static struct configfs_attribute *srpt_tpg_attrs[] = {
&srpt_tpg_attr_enable,
NULL,
};
/**
* configfs callback invoked for
* mkdir /sys/kernel/config/target/$driver/$port/$tpg
*/
static struct se_portal_group *srpt_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
int res;
/* Initialize sport->port_wwn and sport->port_tpg_1 */
res = core_tpg_register(&sport->port_wwn, &sport->port_tpg_1, SCSI_PROTOCOL_SRP);
if (res)
return ERR_PTR(res);
return &sport->port_tpg_1;
}
/**
* configfs callback invoked for
* rmdir /sys/kernel/config/target/$driver/$port/$tpg
*/
static void srpt_drop_tpg(struct se_portal_group *tpg)
{
struct srpt_port *sport = container_of(tpg,
struct srpt_port, port_tpg_1);
sport->enabled = false;
core_tpg_deregister(&sport->port_tpg_1);
}
/**
* configfs callback invoked for
* mkdir /sys/kernel/config/target/$driver/$port
*/
static struct se_wwn *srpt_make_tport(struct target_fabric_configfs *tf,
struct config_group *group,
const char *name)
{
struct srpt_port *sport;
int ret;
sport = srpt_lookup_port(name);
pr_debug("make_tport(%s)\n", name);
ret = -EINVAL;
if (!sport)
goto err;
return &sport->port_wwn;
err:
return ERR_PTR(ret);
}
/**
* configfs callback invoked for
* rmdir /sys/kernel/config/target/$driver/$port
*/
static void srpt_drop_tport(struct se_wwn *wwn)
{
struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
pr_debug("drop_tport(%s\n", config_item_name(&sport->port_wwn.wwn_group.cg_item));
}
static ssize_t srpt_wwn_version_show(struct config_item *item, char *buf)
{
return scnprintf(buf, PAGE_SIZE, "%s\n", DRV_VERSION);
}
CONFIGFS_ATTR_RO(srpt_wwn_, version);
static struct configfs_attribute *srpt_wwn_attrs[] = {
&srpt_wwn_attr_version,
NULL,
};
static const struct target_core_fabric_ops srpt_template = {
.module = THIS_MODULE,
.name = "srpt",
.node_acl_size = sizeof(struct srpt_node_acl),
.get_fabric_name = srpt_get_fabric_name,
.tpg_get_wwn = srpt_get_fabric_wwn,
.tpg_get_tag = srpt_get_tag,
.tpg_check_demo_mode = srpt_check_false,
.tpg_check_demo_mode_cache = srpt_check_true,
.tpg_check_demo_mode_write_protect = srpt_check_true,
.tpg_check_prod_mode_write_protect = srpt_check_false,
.tpg_get_inst_index = srpt_tpg_get_inst_index,
.release_cmd = srpt_release_cmd,
.check_stop_free = srpt_check_stop_free,
.shutdown_session = srpt_shutdown_session,
.close_session = srpt_close_session,
.sess_get_index = srpt_sess_get_index,
.sess_get_initiator_sid = NULL,
.write_pending = srpt_write_pending,
.write_pending_status = srpt_write_pending_status,
.set_default_node_attributes = srpt_set_default_node_attrs,
.get_cmd_state = srpt_get_tcm_cmd_state,
.queue_data_in = srpt_queue_data_in,
.queue_status = srpt_queue_status,
.queue_tm_rsp = srpt_queue_tm_rsp,
.aborted_task = srpt_aborted_task,
/*
* Setup function pointers for generic logic in
* target_core_fabric_configfs.c
*/
.fabric_make_wwn = srpt_make_tport,
.fabric_drop_wwn = srpt_drop_tport,
.fabric_make_tpg = srpt_make_tpg,
.fabric_drop_tpg = srpt_drop_tpg,
.fabric_init_nodeacl = srpt_init_nodeacl,
.tfc_wwn_attrs = srpt_wwn_attrs,
.tfc_tpg_base_attrs = srpt_tpg_attrs,
.tfc_tpg_attrib_attrs = srpt_tpg_attrib_attrs,
};
/**
* srpt_init_module() - Kernel module initialization.
*
* Note: Since ib_register_client() registers callback functions, and since at
* least one of these callback functions (srpt_add_one()) calls target core
* functions, this driver must be registered with the target core before
* ib_register_client() is called.
*/
static int __init srpt_init_module(void)
{
int ret;
ret = -EINVAL;
if (srp_max_req_size < MIN_MAX_REQ_SIZE) {
pr_err("invalid value %d for kernel module parameter"
" srp_max_req_size -- must be at least %d.\n",
srp_max_req_size, MIN_MAX_REQ_SIZE);
goto out;
}
if (srpt_srq_size < MIN_SRPT_SRQ_SIZE
|| srpt_srq_size > MAX_SRPT_SRQ_SIZE) {
pr_err("invalid value %d for kernel module parameter"
" srpt_srq_size -- must be in the range [%d..%d].\n",
srpt_srq_size, MIN_SRPT_SRQ_SIZE, MAX_SRPT_SRQ_SIZE);
goto out;
}
ret = target_register_template(&srpt_template);
if (ret)
goto out;
ret = ib_register_client(&srpt_client);
if (ret) {
pr_err("couldn't register IB client\n");
goto out_unregister_target;
}
return 0;
out_unregister_target:
target_unregister_template(&srpt_template);
out:
return ret;
}
static void __exit srpt_cleanup_module(void)
{
ib_unregister_client(&srpt_client);
target_unregister_template(&srpt_template);
}
module_init(srpt_init_module);
module_exit(srpt_cleanup_module);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5209_0 |
crossvul-cpp_data_good_5514_4 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_WDDX
#include "ext/xml/expat_compat.h"
#include "php_wddx.h"
#include "php_wddx_api.h"
#define PHP_XML_INTERNAL
#include "ext/xml/php_xml.h"
#include "ext/standard/php_incomplete_class.h"
#include "ext/standard/base64.h"
#include "ext/standard/info.h"
#include "ext/standard/php_smart_str.h"
#include "ext/standard/html.h"
#include "ext/standard/php_string.h"
#include "ext/date/php_date.h"
#include "zend_globals.h"
#define WDDX_BUF_LEN 256
#define PHP_CLASS_NAME_VAR "php_class_name"
#define EL_ARRAY "array"
#define EL_BINARY "binary"
#define EL_BOOLEAN "boolean"
#define EL_CHAR "char"
#define EL_CHAR_CODE "code"
#define EL_NULL "null"
#define EL_NUMBER "number"
#define EL_PACKET "wddxPacket"
#define EL_STRING "string"
#define EL_STRUCT "struct"
#define EL_VALUE "value"
#define EL_VAR "var"
#define EL_NAME "name"
#define EL_VERSION "version"
#define EL_RECORDSET "recordset"
#define EL_FIELD "field"
#define EL_DATETIME "dateTime"
#define php_wddx_deserialize(a,b) \
php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b))
#define SET_STACK_VARNAME \
if (stack->varname) { \
ent.varname = estrdup(stack->varname); \
efree(stack->varname); \
stack->varname = NULL; \
} else \
ent.varname = NULL; \
static int le_wddx;
typedef struct {
zval *data;
enum {
ST_ARRAY,
ST_BOOLEAN,
ST_NULL,
ST_NUMBER,
ST_STRING,
ST_BINARY,
ST_STRUCT,
ST_RECORDSET,
ST_FIELD,
ST_DATETIME
} type;
char *varname;
} st_entry;
typedef struct {
int top, max;
char *varname;
zend_bool done;
void **elements;
} wddx_stack;
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len);
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1)
ZEND_ARG_INFO(0, var)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1)
ZEND_ARG_INFO(0, packet_id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2)
ZEND_ARG_INFO(0, packet_id)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1)
ZEND_ARG_INFO(0, packet)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ wddx_functions[]
*/
const zend_function_entry wddx_functions[] = {
PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value)
PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars)
PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start)
PHP_FE(wddx_packet_end, arginfo_wddx_packet_end)
PHP_FE(wddx_add_vars, arginfo_wddx_add_vars)
PHP_FE(wddx_deserialize, arginfo_wddx_deserialize)
PHP_FE_END
};
/* }}} */
PHP_MINIT_FUNCTION(wddx);
PHP_MINFO_FUNCTION(wddx);
/* {{{ dynamically loadable module stuff */
#ifdef COMPILE_DL_WDDX
ZEND_GET_MODULE(wddx)
#endif /* COMPILE_DL_WDDX */
/* }}} */
/* {{{ wddx_module_entry
*/
zend_module_entry wddx_module_entry = {
STANDARD_MODULE_HEADER,
"wddx",
wddx_functions,
PHP_MINIT(wddx),
NULL,
NULL,
NULL,
PHP_MINFO(wddx),
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
/* {{{ wddx_stack_init
*/
static int wddx_stack_init(wddx_stack *stack)
{
stack->top = 0;
stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0);
stack->max = STACK_BLOCK_SIZE;
stack->varname = NULL;
stack->done = 0;
return SUCCESS;
}
/* }}} */
/* {{{ wddx_stack_push
*/
static int wddx_stack_push(wddx_stack *stack, void *element, int size)
{
if (stack->top >= stack->max) { /* we need to allocate more memory */
stack->elements = (void **) erealloc(stack->elements,
(sizeof(void **) * (stack->max += STACK_BLOCK_SIZE)));
}
stack->elements[stack->top] = (void *) emalloc(size);
memcpy(stack->elements[stack->top], element, size);
return stack->top++;
}
/* }}} */
/* {{{ wddx_stack_top
*/
static int wddx_stack_top(wddx_stack *stack, void **element)
{
if (stack->top > 0) {
*element = stack->elements[stack->top - 1];
return SUCCESS;
} else {
*element = NULL;
return FAILURE;
}
}
/* }}} */
/* {{{ wddx_stack_is_empty
*/
static int wddx_stack_is_empty(wddx_stack *stack)
{
if (stack->top == 0) {
return 1;
} else {
return 0;
}
}
/* }}} */
/* {{{ wddx_stack_destroy
*/
static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data
&& ((st_entry *)stack->elements[i])->type != ST_FIELD) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
/* }}} */
/* {{{ release_wddx_packet_rsrc
*/
static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
smart_str *str = (smart_str *)rsrc->ptr;
smart_str_free(str);
efree(str);
}
/* }}} */
#include "ext/session/php_session.h"
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
/* {{{ PS_SERIALIZER_ENCODE_FUNC
*/
PS_SERIALIZER_ENCODE_FUNC(wddx)
{
wddx_packet *packet;
PS_ENCODE_VARS;
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
PS_ENCODE_LOOP(
php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC);
);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
*newstr = php_wddx_gather(packet);
php_wddx_destructor(packet);
if (newlen) {
*newlen = strlen(*newstr);
}
return SUCCESS;
}
/* }}} */
/* {{{ PS_SERIALIZER_DECODE_FUNC
*/
PS_SERIALIZER_DECODE_FUNC(wddx)
{
zval *retval;
zval **ent;
char *key;
uint key_length;
char tmp[128];
ulong idx;
int hash_type;
int ret;
if (vallen == 0) {
return SUCCESS;
}
MAKE_STD_ZVAL(retval);
if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) {
if (Z_TYPE_P(retval) != IS_ARRAY) {
zval_ptr_dtor(&retval);
return FAILURE;
}
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval));
zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS;
zend_hash_move_forward(Z_ARRVAL_P(retval))) {
hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL);
switch (hash_type) {
case HASH_KEY_IS_LONG:
key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1;
key = tmp;
/* fallthru */
case HASH_KEY_IS_STRING:
php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC);
PS_ADD_VAR(key);
}
}
}
zval_ptr_dtor(&retval);
return ret;
}
/* }}} */
#endif
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(wddx)
{
le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number);
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_session_register_serializer("wddx",
PS_SERIALIZER_ENCODE_NAME(wddx),
PS_SERIALIZER_DECODE_NAME(wddx));
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(wddx)
{
php_info_print_table_start();
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_info_print_table_header(2, "WDDX Support", "enabled" );
php_info_print_table_row(2, "WDDX Session Serializer", "enabled" );
#else
php_info_print_table_row(2, "WDDX Support", "enabled" );
#endif
php_info_print_table_end();
}
/* }}} */
/* {{{ php_wddx_packet_start
*/
void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len)
{
php_wddx_add_chunk_static(packet, WDDX_PACKET_S);
if (comment) {
char *escaped;
size_t escaped_len;
TSRMLS_FETCH();
escaped = php_escape_html_entities(
comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_static(packet, WDDX_HEADER_S);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_S);
php_wddx_add_chunk_ex(packet, escaped, escaped_len);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_E);
php_wddx_add_chunk_static(packet, WDDX_HEADER_E);
str_efree(escaped);
} else {
php_wddx_add_chunk_static(packet, WDDX_HEADER);
}
php_wddx_add_chunk_static(packet, WDDX_DATA_S);
}
/* }}} */
/* {{{ php_wddx_packet_end
*/
void php_wddx_packet_end(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_DATA_E);
php_wddx_add_chunk_static(packet, WDDX_PACKET_E);
}
/* }}} */
#define FLUSH_BUF() \
if (l > 0) { \
php_wddx_add_chunk_ex(packet, buf, l); \
l = 0; \
}
/* {{{ php_wddx_serialize_string
*/
static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC)
{
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
if (Z_STRLEN_P(var) > 0) {
char *buf;
size_t buf_len;
buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_ex(packet, buf, buf_len);
str_efree(buf);
}
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
}
/* }}} */
/* {{{ php_wddx_serialize_number
*/
static void php_wddx_serialize_number(wddx_packet *packet, zval *var)
{
char tmp_buf[WDDX_BUF_LEN];
zval tmp;
tmp = *var;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp));
zval_dtor(&tmp);
php_wddx_add_chunk(packet, tmp_buf);
}
/* }}} */
/* {{{ php_wddx_serialize_boolean
*/
static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var)
{
php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE);
}
/* }}} */
/* {{{ php_wddx_serialize_unset
*/
static void php_wddx_serialize_unset(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_NULL);
}
/* }}} */
/* {{{ php_wddx_serialize_object
*/
static void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
zend_class_entry *ce;
PHP_CLASS_ATTRIBUTES;
TSRMLS_FETCH();
PHP_SET_CLASS_ATTRIBUTES(obj);
ce = Z_OBJCE_P(obj);
if (!ce || ce->serialize || ce->unserialize) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be serialized", class_name);
PHP_CLEANUP_CLASS_ATTRIBUTES();
return;
}
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
PHP_CLEANUP_CLASS_ATTRIBUTES();
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
/* }}} */
/* {{{ php_wddx_serialize_array
*/
static void php_wddx_serialize_array(wddx_packet *packet, zval *arr)
{
zval **ent;
char *key;
uint key_len;
int is_struct = 0, ent_type;
ulong idx;
HashTable *target_hash;
char tmp_buf[WDDX_BUF_LEN];
ulong ind = 0;
int type;
TSRMLS_FETCH();
target_hash = HASH_OF(arr);
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
type = zend_hash_get_current_key(target_hash, &key, &idx, 0);
if (type == HASH_KEY_IS_STRING) {
is_struct = 1;
break;
}
if (idx != ind) {
is_struct = 1;
break;
}
ind++;
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
} else {
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash));
php_wddx_add_chunk(packet, tmp_buf);
}
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
if (*ent == arr) {
continue;
}
if (is_struct) {
ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL);
if (ent_type == HASH_KEY_IS_STRING) {
php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
} else {
php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC);
}
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
} else {
php_wddx_add_chunk_static(packet, WDDX_ARRAY_E);
}
}
/* }}} */
/* {{{ php_wddx_serialize_var
*/
void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC)
{
HashTable *ht;
if (name) {
size_t name_esc_len;
char *tmp_buf, *name_esc;
name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S));
snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc);
php_wddx_add_chunk(packet, tmp_buf);
efree(tmp_buf);
str_efree(name_esc);
}
switch(Z_TYPE_P(var)) {
case IS_STRING:
php_wddx_serialize_string(packet, var TSRMLS_CC);
break;
case IS_LONG:
case IS_DOUBLE:
php_wddx_serialize_number(packet, var);
break;
case IS_BOOL:
php_wddx_serialize_boolean(packet, var);
break;
case IS_NULL:
php_wddx_serialize_unset(packet);
break;
case IS_ARRAY:
ht = Z_ARRVAL_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_array(packet, var);
ht->nApplyCount--;
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_object(packet, var);
ht->nApplyCount--;
break;
}
if (name) {
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
}
}
/* }}} */
/* {{{ php_wddx_add_var
*/
static void php_wddx_add_var(wddx_packet *packet, zval *name_var)
{
zval **val;
HashTable *target_hash;
TSRMLS_FETCH();
if (Z_TYPE_P(name_var) == IS_STRING) {
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var),
Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) {
php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC);
}
} else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) {
int is_array = Z_TYPE_P(name_var) == IS_ARRAY;
target_hash = HASH_OF(name_var);
if (is_array && target_hash->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected");
return;
}
zend_hash_internal_pointer_reset(target_hash);
while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) {
if (is_array) {
target_hash->nApplyCount++;
}
php_wddx_add_var(packet, *val);
if (is_array) {
target_hash->nApplyCount--;
}
zend_hash_move_forward(target_hash);
}
}
}
/* }}} */
/* {{{ php_wddx_push_element
*/
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
/* }}} */
/* {{{ php_wddx_pop_element
*/
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
if (pce != &PHP_IC_ENTRY && ((*pce)->serialize || (*pce)->unserialize)) {
ent2->data = NULL;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be unserialized", Z_STRVAL_P(ent1->data));
} else {
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
}
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
/* }}} */
/* {{{ php_wddx_process_data
*/
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if(!ent->data) {
break;
}
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
ent->varname = NULL;
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
if (Z_TYPE_P(ent->data) == IS_STRING) {
tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1);
memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data));
memcpy(tmp + Z_STRLEN_P(ent->data), s, len);
len += Z_STRLEN_P(ent->data);
efree(Z_STRVAL_P(ent->data));
Z_TYPE_P(ent->data) = IS_LONG;
} else {
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
}
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
ZVAL_STRINGL(ent->data, tmp, len, 0);
} else {
efree(tmp);
}
}
break;
default:
break;
}
}
}
/* }}} */
/* {{{ php_wddx_deserialize_ex
*/
int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
if(ent->data == NULL) {
retval = FAILURE;
} else {
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
}
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
/* }}} */
/* {{{ proto string wddx_serialize_value(mixed var [, string comment])
Creates a new packet and serializes the given value */
PHP_FUNCTION(wddx_serialize_value)
{
zval *var;
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...])
Creates a new packet and serializes given variables into a struct */
PHP_FUNCTION(wddx_serialize_vars)
{
int num_args, i;
wddx_packet *packet;
zval ***args = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, *args[i]);
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
efree(args);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ php_wddx_constructor
*/
wddx_packet *php_wddx_constructor(void)
{
smart_str *packet;
packet = (smart_str *)emalloc(sizeof(smart_str));
packet->c = NULL;
return packet;
}
/* }}} */
/* {{{ php_wddx_destructor
*/
void php_wddx_destructor(wddx_packet *packet)
{
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto resource wddx_packet_start([string comment])
Starts a WDDX packet with optional comment and returns the packet id */
PHP_FUNCTION(wddx_packet_start)
{
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
comment = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx);
}
/* }}} */
/* {{{ proto string wddx_packet_end(resource packet_id)
Ends specified WDDX packet and returns the string containing the packet */
PHP_FUNCTION(wddx_packet_end)
{
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
zend_list_delete(Z_LVAL_P(packet_id));
}
/* }}} */
/* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...])
Serializes given variables and adds them to packet given by packet_id */
PHP_FUNCTION(wddx_add_vars)
{
int num_args, i;
zval ***args = NULL;
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) {
return;
}
if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) {
efree(args);
RETURN_FALSE;
}
if (!packet) {
efree(args);
RETURN_FALSE;
}
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, (*args[i]));
}
efree(args);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed wddx_deserialize(mixed packet)
Deserializes given packet and returns a PHP value */
PHP_FUNCTION(wddx_deserialize)
{
zval *packet;
char *payload;
int payload_len;
php_stream *stream = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) {
return;
}
if (Z_TYPE_P(packet) == IS_STRING) {
payload = Z_STRVAL_P(packet);
payload_len = Z_STRLEN_P(packet);
} else if (Z_TYPE_P(packet) == IS_RESOURCE) {
php_stream_from_zval(stream, &packet);
if (stream) {
payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream");
return;
}
if (payload_len == 0) {
return;
}
php_wddx_deserialize_ex(payload, payload_len, return_value);
if (stream) {
pefree(payload, 0);
}
}
/* }}} */
#endif /* HAVE_LIBEXPAT */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5514_4 |
crossvul-cpp_data_bad_1317_0 | // SPDX-License-Identifier: GPL-2.0
/*
* fs/f2fs/data.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include <linux/blkdev.h>
#include <linux/bio.h>
#include <linux/prefetch.h>
#include <linux/uio.h>
#include <linux/cleancache.h>
#include <linux/sched/signal.h>
#include "f2fs.h"
#include "node.h"
#include "segment.h"
#include "trace.h"
#include <trace/events/f2fs.h>
#define NUM_PREALLOC_POST_READ_CTXS 128
static struct kmem_cache *bio_post_read_ctx_cache;
static mempool_t *bio_post_read_ctx_pool;
static bool __is_cp_guaranteed(struct page *page)
{
struct address_space *mapping = page->mapping;
struct inode *inode;
struct f2fs_sb_info *sbi;
if (!mapping)
return false;
inode = mapping->host;
sbi = F2FS_I_SB(inode);
if (inode->i_ino == F2FS_META_INO(sbi) ||
inode->i_ino == F2FS_NODE_INO(sbi) ||
S_ISDIR(inode->i_mode) ||
(S_ISREG(inode->i_mode) &&
(f2fs_is_atomic_file(inode) || IS_NOQUOTA(inode))) ||
is_cold_data(page))
return true;
return false;
}
static enum count_type __read_io_type(struct page *page)
{
struct address_space *mapping = page->mapping;
if (mapping) {
struct inode *inode = mapping->host;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
if (inode->i_ino == F2FS_META_INO(sbi))
return F2FS_RD_META;
if (inode->i_ino == F2FS_NODE_INO(sbi))
return F2FS_RD_NODE;
}
return F2FS_RD_DATA;
}
/* postprocessing steps for read bios */
enum bio_post_read_step {
STEP_INITIAL = 0,
STEP_DECRYPT,
};
struct bio_post_read_ctx {
struct bio *bio;
struct work_struct work;
unsigned int cur_step;
unsigned int enabled_steps;
};
static void __read_end_io(struct bio *bio)
{
struct page *page;
struct bio_vec *bv;
struct bvec_iter_all iter_all;
bio_for_each_segment_all(bv, bio, iter_all) {
page = bv->bv_page;
/* PG_error was set if any post_read step failed */
if (bio->bi_status || PageError(page)) {
ClearPageUptodate(page);
/* will re-read again later */
ClearPageError(page);
} else {
SetPageUptodate(page);
}
dec_page_count(F2FS_P_SB(page), __read_io_type(page));
unlock_page(page);
}
if (bio->bi_private)
mempool_free(bio->bi_private, bio_post_read_ctx_pool);
bio_put(bio);
}
static void bio_post_read_processing(struct bio_post_read_ctx *ctx);
static void decrypt_work(struct work_struct *work)
{
struct bio_post_read_ctx *ctx =
container_of(work, struct bio_post_read_ctx, work);
fscrypt_decrypt_bio(ctx->bio);
bio_post_read_processing(ctx);
}
static void bio_post_read_processing(struct bio_post_read_ctx *ctx)
{
switch (++ctx->cur_step) {
case STEP_DECRYPT:
if (ctx->enabled_steps & (1 << STEP_DECRYPT)) {
INIT_WORK(&ctx->work, decrypt_work);
fscrypt_enqueue_decrypt_work(&ctx->work);
return;
}
ctx->cur_step++;
/* fall-through */
default:
__read_end_io(ctx->bio);
}
}
static bool f2fs_bio_post_read_required(struct bio *bio)
{
return bio->bi_private && !bio->bi_status;
}
static void f2fs_read_end_io(struct bio *bio)
{
if (time_to_inject(F2FS_P_SB(bio_first_page_all(bio)),
FAULT_READ_IO)) {
f2fs_show_injection_info(FAULT_READ_IO);
bio->bi_status = BLK_STS_IOERR;
}
if (f2fs_bio_post_read_required(bio)) {
struct bio_post_read_ctx *ctx = bio->bi_private;
ctx->cur_step = STEP_INITIAL;
bio_post_read_processing(ctx);
return;
}
__read_end_io(bio);
}
static void f2fs_write_end_io(struct bio *bio)
{
struct f2fs_sb_info *sbi = bio->bi_private;
struct bio_vec *bvec;
struct bvec_iter_all iter_all;
if (time_to_inject(sbi, FAULT_WRITE_IO)) {
f2fs_show_injection_info(FAULT_WRITE_IO);
bio->bi_status = BLK_STS_IOERR;
}
bio_for_each_segment_all(bvec, bio, iter_all) {
struct page *page = bvec->bv_page;
enum count_type type = WB_DATA_TYPE(page);
if (IS_DUMMY_WRITTEN_PAGE(page)) {
set_page_private(page, (unsigned long)NULL);
ClearPagePrivate(page);
unlock_page(page);
mempool_free(page, sbi->write_io_dummy);
if (unlikely(bio->bi_status))
f2fs_stop_checkpoint(sbi, true);
continue;
}
fscrypt_pullback_bio_page(&page, true);
if (unlikely(bio->bi_status)) {
mapping_set_error(page->mapping, -EIO);
if (type == F2FS_WB_CP_DATA)
f2fs_stop_checkpoint(sbi, true);
}
f2fs_bug_on(sbi, page->mapping == NODE_MAPPING(sbi) &&
page->index != nid_of_node(page));
dec_page_count(sbi, type);
if (f2fs_in_warm_node_list(sbi, page))
f2fs_del_fsync_node_entry(sbi, page);
clear_cold_data(page);
end_page_writeback(page);
}
if (!get_pages(sbi, F2FS_WB_CP_DATA) &&
wq_has_sleeper(&sbi->cp_wait))
wake_up(&sbi->cp_wait);
bio_put(bio);
}
/*
* Return true, if pre_bio's bdev is same as its target device.
*/
struct block_device *f2fs_target_device(struct f2fs_sb_info *sbi,
block_t blk_addr, struct bio *bio)
{
struct block_device *bdev = sbi->sb->s_bdev;
int i;
if (f2fs_is_multi_device(sbi)) {
for (i = 0; i < sbi->s_ndevs; i++) {
if (FDEV(i).start_blk <= blk_addr &&
FDEV(i).end_blk >= blk_addr) {
blk_addr -= FDEV(i).start_blk;
bdev = FDEV(i).bdev;
break;
}
}
}
if (bio) {
bio_set_dev(bio, bdev);
bio->bi_iter.bi_sector = SECTOR_FROM_BLOCK(blk_addr);
}
return bdev;
}
int f2fs_target_device_index(struct f2fs_sb_info *sbi, block_t blkaddr)
{
int i;
if (!f2fs_is_multi_device(sbi))
return 0;
for (i = 0; i < sbi->s_ndevs; i++)
if (FDEV(i).start_blk <= blkaddr && FDEV(i).end_blk >= blkaddr)
return i;
return 0;
}
static bool __same_bdev(struct f2fs_sb_info *sbi,
block_t blk_addr, struct bio *bio)
{
struct block_device *b = f2fs_target_device(sbi, blk_addr, NULL);
return bio->bi_disk == b->bd_disk && bio->bi_partno == b->bd_partno;
}
/*
* Low-level block read/write IO operations.
*/
static struct bio *__bio_alloc(struct f2fs_sb_info *sbi, block_t blk_addr,
struct writeback_control *wbc,
int npages, bool is_read,
enum page_type type, enum temp_type temp)
{
struct bio *bio;
bio = f2fs_bio_alloc(sbi, npages, true);
f2fs_target_device(sbi, blk_addr, bio);
if (is_read) {
bio->bi_end_io = f2fs_read_end_io;
bio->bi_private = NULL;
} else {
bio->bi_end_io = f2fs_write_end_io;
bio->bi_private = sbi;
bio->bi_write_hint = f2fs_io_type_to_rw_hint(sbi, type, temp);
}
if (wbc)
wbc_init_bio(wbc, bio);
return bio;
}
static inline void __submit_bio(struct f2fs_sb_info *sbi,
struct bio *bio, enum page_type type)
{
if (!is_read_io(bio_op(bio))) {
unsigned int start;
if (type != DATA && type != NODE)
goto submit_io;
if (test_opt(sbi, LFS) && current->plug)
blk_finish_plug(current->plug);
start = bio->bi_iter.bi_size >> F2FS_BLKSIZE_BITS;
start %= F2FS_IO_SIZE(sbi);
if (start == 0)
goto submit_io;
/* fill dummy pages */
for (; start < F2FS_IO_SIZE(sbi); start++) {
struct page *page =
mempool_alloc(sbi->write_io_dummy,
GFP_NOIO | __GFP_NOFAIL);
f2fs_bug_on(sbi, !page);
zero_user_segment(page, 0, PAGE_SIZE);
SetPagePrivate(page);
set_page_private(page, (unsigned long)DUMMY_WRITTEN_PAGE);
lock_page(page);
if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE)
f2fs_bug_on(sbi, 1);
}
/*
* In the NODE case, we lose next block address chain. So, we
* need to do checkpoint in f2fs_sync_file.
*/
if (type == NODE)
set_sbi_flag(sbi, SBI_NEED_CP);
}
submit_io:
if (is_read_io(bio_op(bio)))
trace_f2fs_submit_read_bio(sbi->sb, type, bio);
else
trace_f2fs_submit_write_bio(sbi->sb, type, bio);
submit_bio(bio);
}
static void __submit_merged_bio(struct f2fs_bio_info *io)
{
struct f2fs_io_info *fio = &io->fio;
if (!io->bio)
return;
bio_set_op_attrs(io->bio, fio->op, fio->op_flags);
if (is_read_io(fio->op))
trace_f2fs_prepare_read_bio(io->sbi->sb, fio->type, io->bio);
else
trace_f2fs_prepare_write_bio(io->sbi->sb, fio->type, io->bio);
__submit_bio(io->sbi, io->bio, fio->type);
io->bio = NULL;
}
static bool __has_merged_page(struct bio *bio, struct inode *inode,
struct page *page, nid_t ino)
{
struct bio_vec *bvec;
struct page *target;
struct bvec_iter_all iter_all;
if (!bio)
return false;
if (!inode && !page && !ino)
return true;
bio_for_each_segment_all(bvec, bio, iter_all) {
if (bvec->bv_page->mapping)
target = bvec->bv_page;
else
target = fscrypt_control_page(bvec->bv_page);
if (inode && inode == target->mapping->host)
return true;
if (page && page == target)
return true;
if (ino && ino == ino_of_node(target))
return true;
}
return false;
}
static void __f2fs_submit_merged_write(struct f2fs_sb_info *sbi,
enum page_type type, enum temp_type temp)
{
enum page_type btype = PAGE_TYPE_OF_BIO(type);
struct f2fs_bio_info *io = sbi->write_io[btype] + temp;
down_write(&io->io_rwsem);
/* change META to META_FLUSH in the checkpoint procedure */
if (type >= META_FLUSH) {
io->fio.type = META_FLUSH;
io->fio.op = REQ_OP_WRITE;
io->fio.op_flags = REQ_META | REQ_PRIO | REQ_SYNC;
if (!test_opt(sbi, NOBARRIER))
io->fio.op_flags |= REQ_PREFLUSH | REQ_FUA;
}
__submit_merged_bio(io);
up_write(&io->io_rwsem);
}
static void __submit_merged_write_cond(struct f2fs_sb_info *sbi,
struct inode *inode, struct page *page,
nid_t ino, enum page_type type, bool force)
{
enum temp_type temp;
bool ret = true;
for (temp = HOT; temp < NR_TEMP_TYPE; temp++) {
if (!force) {
enum page_type btype = PAGE_TYPE_OF_BIO(type);
struct f2fs_bio_info *io = sbi->write_io[btype] + temp;
down_read(&io->io_rwsem);
ret = __has_merged_page(io->bio, inode, page, ino);
up_read(&io->io_rwsem);
}
if (ret)
__f2fs_submit_merged_write(sbi, type, temp);
/* TODO: use HOT temp only for meta pages now. */
if (type >= META)
break;
}
}
void f2fs_submit_merged_write(struct f2fs_sb_info *sbi, enum page_type type)
{
__submit_merged_write_cond(sbi, NULL, NULL, 0, type, true);
}
void f2fs_submit_merged_write_cond(struct f2fs_sb_info *sbi,
struct inode *inode, struct page *page,
nid_t ino, enum page_type type)
{
__submit_merged_write_cond(sbi, inode, page, ino, type, false);
}
void f2fs_flush_merged_writes(struct f2fs_sb_info *sbi)
{
f2fs_submit_merged_write(sbi, DATA);
f2fs_submit_merged_write(sbi, NODE);
f2fs_submit_merged_write(sbi, META);
}
/*
* Fill the locked page with data located in the block address.
* A caller needs to unlock the page on failure.
*/
int f2fs_submit_page_bio(struct f2fs_io_info *fio)
{
struct bio *bio;
struct page *page = fio->encrypted_page ?
fio->encrypted_page : fio->page;
if (!f2fs_is_valid_blkaddr(fio->sbi, fio->new_blkaddr,
fio->is_por ? META_POR : (__is_meta_io(fio) ?
META_GENERIC : DATA_GENERIC_ENHANCE)))
return -EFSCORRUPTED;
trace_f2fs_submit_page_bio(page, fio);
f2fs_trace_ios(fio, 0);
/* Allocate a new bio */
bio = __bio_alloc(fio->sbi, fio->new_blkaddr, fio->io_wbc,
1, is_read_io(fio->op), fio->type, fio->temp);
if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
bio_put(bio);
return -EFAULT;
}
if (fio->io_wbc && !is_read_io(fio->op))
wbc_account_io(fio->io_wbc, page, PAGE_SIZE);
bio_set_op_attrs(bio, fio->op, fio->op_flags);
inc_page_count(fio->sbi, is_read_io(fio->op) ?
__read_io_type(page): WB_DATA_TYPE(fio->page));
__submit_bio(fio->sbi, bio, fio->type);
return 0;
}
int f2fs_merge_page_bio(struct f2fs_io_info *fio)
{
struct bio *bio = *fio->bio;
struct page *page = fio->encrypted_page ?
fio->encrypted_page : fio->page;
if (!f2fs_is_valid_blkaddr(fio->sbi, fio->new_blkaddr,
__is_meta_io(fio) ? META_GENERIC : DATA_GENERIC))
return -EFSCORRUPTED;
trace_f2fs_submit_page_bio(page, fio);
f2fs_trace_ios(fio, 0);
if (bio && (*fio->last_block + 1 != fio->new_blkaddr ||
!__same_bdev(fio->sbi, fio->new_blkaddr, bio))) {
__submit_bio(fio->sbi, bio, fio->type);
bio = NULL;
}
alloc_new:
if (!bio) {
bio = __bio_alloc(fio->sbi, fio->new_blkaddr, fio->io_wbc,
BIO_MAX_PAGES, false, fio->type, fio->temp);
bio_set_op_attrs(bio, fio->op, fio->op_flags);
}
if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
__submit_bio(fio->sbi, bio, fio->type);
bio = NULL;
goto alloc_new;
}
if (fio->io_wbc)
wbc_account_io(fio->io_wbc, page, PAGE_SIZE);
inc_page_count(fio->sbi, WB_DATA_TYPE(page));
*fio->last_block = fio->new_blkaddr;
*fio->bio = bio;
return 0;
}
static void f2fs_submit_ipu_bio(struct f2fs_sb_info *sbi, struct bio **bio,
struct page *page)
{
if (!bio)
return;
if (!__has_merged_page(*bio, NULL, page, 0))
return;
__submit_bio(sbi, *bio, DATA);
*bio = NULL;
}
void f2fs_submit_page_write(struct f2fs_io_info *fio)
{
struct f2fs_sb_info *sbi = fio->sbi;
enum page_type btype = PAGE_TYPE_OF_BIO(fio->type);
struct f2fs_bio_info *io = sbi->write_io[btype] + fio->temp;
struct page *bio_page;
f2fs_bug_on(sbi, is_read_io(fio->op));
down_write(&io->io_rwsem);
next:
if (fio->in_list) {
spin_lock(&io->io_lock);
if (list_empty(&io->io_list)) {
spin_unlock(&io->io_lock);
goto out;
}
fio = list_first_entry(&io->io_list,
struct f2fs_io_info, list);
list_del(&fio->list);
spin_unlock(&io->io_lock);
}
verify_fio_blkaddr(fio);
bio_page = fio->encrypted_page ? fio->encrypted_page : fio->page;
/* set submitted = true as a return value */
fio->submitted = true;
inc_page_count(sbi, WB_DATA_TYPE(bio_page));
if (io->bio && (io->last_block_in_bio != fio->new_blkaddr - 1 ||
(io->fio.op != fio->op || io->fio.op_flags != fio->op_flags) ||
!__same_bdev(sbi, fio->new_blkaddr, io->bio)))
__submit_merged_bio(io);
alloc_new:
if (io->bio == NULL) {
if ((fio->type == DATA || fio->type == NODE) &&
fio->new_blkaddr & F2FS_IO_SIZE_MASK(sbi)) {
dec_page_count(sbi, WB_DATA_TYPE(bio_page));
fio->retry = true;
goto skip;
}
io->bio = __bio_alloc(sbi, fio->new_blkaddr, fio->io_wbc,
BIO_MAX_PAGES, false,
fio->type, fio->temp);
io->fio = *fio;
}
if (bio_add_page(io->bio, bio_page, PAGE_SIZE, 0) < PAGE_SIZE) {
__submit_merged_bio(io);
goto alloc_new;
}
if (fio->io_wbc)
wbc_account_io(fio->io_wbc, bio_page, PAGE_SIZE);
io->last_block_in_bio = fio->new_blkaddr;
f2fs_trace_ios(fio, 0);
trace_f2fs_submit_page_write(fio->page, fio);
skip:
if (fio->in_list)
goto next;
out:
if (is_sbi_flag_set(sbi, SBI_IS_SHUTDOWN) ||
f2fs_is_checkpoint_ready(sbi))
__submit_merged_bio(io);
up_write(&io->io_rwsem);
}
static struct bio *f2fs_grab_read_bio(struct inode *inode, block_t blkaddr,
unsigned nr_pages, unsigned op_flag)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct bio *bio;
struct bio_post_read_ctx *ctx;
unsigned int post_read_steps = 0;
bio = f2fs_bio_alloc(sbi, min_t(int, nr_pages, BIO_MAX_PAGES), false);
if (!bio)
return ERR_PTR(-ENOMEM);
f2fs_target_device(sbi, blkaddr, bio);
bio->bi_end_io = f2fs_read_end_io;
bio_set_op_attrs(bio, REQ_OP_READ, op_flag);
if (f2fs_encrypted_file(inode))
post_read_steps |= 1 << STEP_DECRYPT;
if (post_read_steps) {
ctx = mempool_alloc(bio_post_read_ctx_pool, GFP_NOFS);
if (!ctx) {
bio_put(bio);
return ERR_PTR(-ENOMEM);
}
ctx->bio = bio;
ctx->enabled_steps = post_read_steps;
bio->bi_private = ctx;
}
return bio;
}
/* This can handle encryption stuffs */
static int f2fs_submit_page_read(struct inode *inode, struct page *page,
block_t blkaddr)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct bio *bio;
bio = f2fs_grab_read_bio(inode, blkaddr, 1, 0);
if (IS_ERR(bio))
return PTR_ERR(bio);
/* wait for GCed page writeback via META_MAPPING */
f2fs_wait_on_block_writeback(inode, blkaddr);
if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
bio_put(bio);
return -EFAULT;
}
ClearPageError(page);
inc_page_count(sbi, F2FS_RD_DATA);
__submit_bio(sbi, bio, DATA);
return 0;
}
static void __set_data_blkaddr(struct dnode_of_data *dn)
{
struct f2fs_node *rn = F2FS_NODE(dn->node_page);
__le32 *addr_array;
int base = 0;
if (IS_INODE(dn->node_page) && f2fs_has_extra_attr(dn->inode))
base = get_extra_isize(dn->inode);
/* Get physical address of data block */
addr_array = blkaddr_in_node(rn);
addr_array[base + dn->ofs_in_node] = cpu_to_le32(dn->data_blkaddr);
}
/*
* Lock ordering for the change of data block address:
* ->data_page
* ->node_page
* update block addresses in the node page
*/
void f2fs_set_data_blkaddr(struct dnode_of_data *dn)
{
f2fs_wait_on_page_writeback(dn->node_page, NODE, true, true);
__set_data_blkaddr(dn);
if (set_page_dirty(dn->node_page))
dn->node_changed = true;
}
void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr)
{
dn->data_blkaddr = blkaddr;
f2fs_set_data_blkaddr(dn);
f2fs_update_extent_cache(dn);
}
/* dn->ofs_in_node will be returned with up-to-date last block pointer */
int f2fs_reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
int err;
if (!count)
return 0;
if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
return -EPERM;
if (unlikely((err = inc_valid_block_count(sbi, dn->inode, &count))))
return err;
trace_f2fs_reserve_new_blocks(dn->inode, dn->nid,
dn->ofs_in_node, count);
f2fs_wait_on_page_writeback(dn->node_page, NODE, true, true);
for (; count > 0; dn->ofs_in_node++) {
block_t blkaddr = datablock_addr(dn->inode,
dn->node_page, dn->ofs_in_node);
if (blkaddr == NULL_ADDR) {
dn->data_blkaddr = NEW_ADDR;
__set_data_blkaddr(dn);
count--;
}
}
if (set_page_dirty(dn->node_page))
dn->node_changed = true;
return 0;
}
/* Should keep dn->ofs_in_node unchanged */
int f2fs_reserve_new_block(struct dnode_of_data *dn)
{
unsigned int ofs_in_node = dn->ofs_in_node;
int ret;
ret = f2fs_reserve_new_blocks(dn, 1);
dn->ofs_in_node = ofs_in_node;
return ret;
}
int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index)
{
bool need_put = dn->inode_page ? false : true;
int err;
err = f2fs_get_dnode_of_data(dn, index, ALLOC_NODE);
if (err)
return err;
if (dn->data_blkaddr == NULL_ADDR)
err = f2fs_reserve_new_block(dn);
if (err || need_put)
f2fs_put_dnode(dn);
return err;
}
int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index)
{
struct extent_info ei = {0,0,0};
struct inode *inode = dn->inode;
if (f2fs_lookup_extent_cache(inode, index, &ei)) {
dn->data_blkaddr = ei.blk + index - ei.fofs;
return 0;
}
return f2fs_reserve_block(dn, index);
}
struct page *f2fs_get_read_data_page(struct inode *inode, pgoff_t index,
int op_flags, bool for_write)
{
struct address_space *mapping = inode->i_mapping;
struct dnode_of_data dn;
struct page *page;
struct extent_info ei = {0,0,0};
int err;
page = f2fs_grab_cache_page(mapping, index, for_write);
if (!page)
return ERR_PTR(-ENOMEM);
if (f2fs_lookup_extent_cache(inode, index, &ei)) {
dn.data_blkaddr = ei.blk + index - ei.fofs;
if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), dn.data_blkaddr,
DATA_GENERIC_ENHANCE_READ)) {
err = -EFSCORRUPTED;
goto put_err;
}
goto got_it;
}
set_new_dnode(&dn, inode, NULL, NULL, 0);
err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
if (err)
goto put_err;
f2fs_put_dnode(&dn);
if (unlikely(dn.data_blkaddr == NULL_ADDR)) {
err = -ENOENT;
goto put_err;
}
if (dn.data_blkaddr != NEW_ADDR &&
!f2fs_is_valid_blkaddr(F2FS_I_SB(inode),
dn.data_blkaddr,
DATA_GENERIC_ENHANCE)) {
err = -EFSCORRUPTED;
goto put_err;
}
got_it:
if (PageUptodate(page)) {
unlock_page(page);
return page;
}
/*
* A new dentry page is allocated but not able to be written, since its
* new inode page couldn't be allocated due to -ENOSPC.
* In such the case, its blkaddr can be remained as NEW_ADDR.
* see, f2fs_add_link -> f2fs_get_new_data_page ->
* f2fs_init_inode_metadata.
*/
if (dn.data_blkaddr == NEW_ADDR) {
zero_user_segment(page, 0, PAGE_SIZE);
if (!PageUptodate(page))
SetPageUptodate(page);
unlock_page(page);
return page;
}
err = f2fs_submit_page_read(inode, page, dn.data_blkaddr);
if (err)
goto put_err;
return page;
put_err:
f2fs_put_page(page, 1);
return ERR_PTR(err);
}
struct page *f2fs_find_data_page(struct inode *inode, pgoff_t index)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
page = find_get_page(mapping, index);
if (page && PageUptodate(page))
return page;
f2fs_put_page(page, 0);
page = f2fs_get_read_data_page(inode, index, 0, false);
if (IS_ERR(page))
return page;
if (PageUptodate(page))
return page;
wait_on_page_locked(page);
if (unlikely(!PageUptodate(page))) {
f2fs_put_page(page, 0);
return ERR_PTR(-EIO);
}
return page;
}
/*
* If it tries to access a hole, return an error.
* Because, the callers, functions in dir.c and GC, should be able to know
* whether this page exists or not.
*/
struct page *f2fs_get_lock_data_page(struct inode *inode, pgoff_t index,
bool for_write)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
repeat:
page = f2fs_get_read_data_page(inode, index, 0, for_write);
if (IS_ERR(page))
return page;
/* wait for read completion */
lock_page(page);
if (unlikely(page->mapping != mapping)) {
f2fs_put_page(page, 1);
goto repeat;
}
if (unlikely(!PageUptodate(page))) {
f2fs_put_page(page, 1);
return ERR_PTR(-EIO);
}
return page;
}
/*
* Caller ensures that this data page is never allocated.
* A new zero-filled data page is allocated in the page cache.
*
* Also, caller should grab and release a rwsem by calling f2fs_lock_op() and
* f2fs_unlock_op().
* Note that, ipage is set only by make_empty_dir, and if any error occur,
* ipage should be released by this function.
*/
struct page *f2fs_get_new_data_page(struct inode *inode,
struct page *ipage, pgoff_t index, bool new_i_size)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
struct dnode_of_data dn;
int err;
page = f2fs_grab_cache_page(mapping, index, true);
if (!page) {
/*
* before exiting, we should make sure ipage will be released
* if any error occur.
*/
f2fs_put_page(ipage, 1);
return ERR_PTR(-ENOMEM);
}
set_new_dnode(&dn, inode, ipage, NULL, 0);
err = f2fs_reserve_block(&dn, index);
if (err) {
f2fs_put_page(page, 1);
return ERR_PTR(err);
}
if (!ipage)
f2fs_put_dnode(&dn);
if (PageUptodate(page))
goto got_it;
if (dn.data_blkaddr == NEW_ADDR) {
zero_user_segment(page, 0, PAGE_SIZE);
if (!PageUptodate(page))
SetPageUptodate(page);
} else {
f2fs_put_page(page, 1);
/* if ipage exists, blkaddr should be NEW_ADDR */
f2fs_bug_on(F2FS_I_SB(inode), ipage);
page = f2fs_get_lock_data_page(inode, index, true);
if (IS_ERR(page))
return page;
}
got_it:
if (new_i_size && i_size_read(inode) <
((loff_t)(index + 1) << PAGE_SHIFT))
f2fs_i_size_write(inode, ((loff_t)(index + 1) << PAGE_SHIFT));
return page;
}
static int __allocate_data_block(struct dnode_of_data *dn, int seg_type)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
struct f2fs_summary sum;
struct node_info ni;
block_t old_blkaddr;
blkcnt_t count = 1;
int err;
if (unlikely(is_inode_flag_set(dn->inode, FI_NO_ALLOC)))
return -EPERM;
err = f2fs_get_node_info(sbi, dn->nid, &ni);
if (err)
return err;
dn->data_blkaddr = datablock_addr(dn->inode,
dn->node_page, dn->ofs_in_node);
if (dn->data_blkaddr != NULL_ADDR)
goto alloc;
if (unlikely((err = inc_valid_block_count(sbi, dn->inode, &count))))
return err;
alloc:
set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
old_blkaddr = dn->data_blkaddr;
f2fs_allocate_data_block(sbi, NULL, old_blkaddr, &dn->data_blkaddr,
&sum, seg_type, NULL, false);
if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
invalidate_mapping_pages(META_MAPPING(sbi),
old_blkaddr, old_blkaddr);
f2fs_set_data_blkaddr(dn);
/*
* i_size will be updated by direct_IO. Otherwise, we'll get stale
* data from unwritten block via dio_read.
*/
return 0;
}
int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *from)
{
struct inode *inode = file_inode(iocb->ki_filp);
struct f2fs_map_blocks map;
int flag;
int err = 0;
bool direct_io = iocb->ki_flags & IOCB_DIRECT;
/* convert inline data for Direct I/O*/
if (direct_io) {
err = f2fs_convert_inline_inode(inode);
if (err)
return err;
}
if (direct_io && allow_outplace_dio(inode, iocb, from))
return 0;
if (is_inode_flag_set(inode, FI_NO_PREALLOC))
return 0;
map.m_lblk = F2FS_BLK_ALIGN(iocb->ki_pos);
map.m_len = F2FS_BYTES_TO_BLK(iocb->ki_pos + iov_iter_count(from));
if (map.m_len > map.m_lblk)
map.m_len -= map.m_lblk;
else
map.m_len = 0;
map.m_next_pgofs = NULL;
map.m_next_extent = NULL;
map.m_seg_type = NO_CHECK_TYPE;
map.m_may_create = true;
if (direct_io) {
map.m_seg_type = f2fs_rw_hint_to_seg_type(iocb->ki_hint);
flag = f2fs_force_buffered_io(inode, iocb, from) ?
F2FS_GET_BLOCK_PRE_AIO :
F2FS_GET_BLOCK_PRE_DIO;
goto map_blocks;
}
if (iocb->ki_pos + iov_iter_count(from) > MAX_INLINE_DATA(inode)) {
err = f2fs_convert_inline_inode(inode);
if (err)
return err;
}
if (f2fs_has_inline_data(inode))
return err;
flag = F2FS_GET_BLOCK_PRE_AIO;
map_blocks:
err = f2fs_map_blocks(inode, &map, 1, flag);
if (map.m_len > 0 && err == -ENOSPC) {
if (!direct_io)
set_inode_flag(inode, FI_NO_PREALLOC);
err = 0;
}
return err;
}
void __do_map_lock(struct f2fs_sb_info *sbi, int flag, bool lock)
{
if (flag == F2FS_GET_BLOCK_PRE_AIO) {
if (lock)
down_read(&sbi->node_change);
else
up_read(&sbi->node_change);
} else {
if (lock)
f2fs_lock_op(sbi);
else
f2fs_unlock_op(sbi);
}
}
/*
* f2fs_map_blocks() now supported readahead/bmap/rw direct_IO with
* f2fs_map_blocks structure.
* If original data blocks are allocated, then give them to blockdev.
* Otherwise,
* a. preallocate requested block addresses
* b. do not use extent cache for better performance
* c. give the block addresses to blockdev
*/
int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map,
int create, int flag)
{
unsigned int maxblocks = map->m_len;
struct dnode_of_data dn;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
int mode = map->m_may_create ? ALLOC_NODE : LOOKUP_NODE;
pgoff_t pgofs, end_offset, end;
int err = 0, ofs = 1;
unsigned int ofs_in_node, last_ofs_in_node;
blkcnt_t prealloc;
struct extent_info ei = {0,0,0};
block_t blkaddr;
unsigned int start_pgofs;
if (!maxblocks)
return 0;
map->m_len = 0;
map->m_flags = 0;
/* it only supports block size == page size */
pgofs = (pgoff_t)map->m_lblk;
end = pgofs + maxblocks;
if (!create && f2fs_lookup_extent_cache(inode, pgofs, &ei)) {
if (test_opt(sbi, LFS) && flag == F2FS_GET_BLOCK_DIO &&
map->m_may_create)
goto next_dnode;
map->m_pblk = ei.blk + pgofs - ei.fofs;
map->m_len = min((pgoff_t)maxblocks, ei.fofs + ei.len - pgofs);
map->m_flags = F2FS_MAP_MAPPED;
if (map->m_next_extent)
*map->m_next_extent = pgofs + map->m_len;
/* for hardware encryption, but to avoid potential issue in future */
if (flag == F2FS_GET_BLOCK_DIO)
f2fs_wait_on_block_writeback_range(inode,
map->m_pblk, map->m_len);
goto out;
}
next_dnode:
if (map->m_may_create)
__do_map_lock(sbi, flag, true);
/* When reading holes, we need its node page */
set_new_dnode(&dn, inode, NULL, NULL, 0);
err = f2fs_get_dnode_of_data(&dn, pgofs, mode);
if (err) {
if (flag == F2FS_GET_BLOCK_BMAP)
map->m_pblk = 0;
if (err == -ENOENT) {
err = 0;
if (map->m_next_pgofs)
*map->m_next_pgofs =
f2fs_get_next_page_offset(&dn, pgofs);
if (map->m_next_extent)
*map->m_next_extent =
f2fs_get_next_page_offset(&dn, pgofs);
}
goto unlock_out;
}
start_pgofs = pgofs;
prealloc = 0;
last_ofs_in_node = ofs_in_node = dn.ofs_in_node;
end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
next_block:
blkaddr = datablock_addr(dn.inode, dn.node_page, dn.ofs_in_node);
if (__is_valid_data_blkaddr(blkaddr) &&
!f2fs_is_valid_blkaddr(sbi, blkaddr, DATA_GENERIC_ENHANCE)) {
err = -EFSCORRUPTED;
goto sync_out;
}
if (__is_valid_data_blkaddr(blkaddr)) {
/* use out-place-update for driect IO under LFS mode */
if (test_opt(sbi, LFS) && flag == F2FS_GET_BLOCK_DIO &&
map->m_may_create) {
err = __allocate_data_block(&dn, map->m_seg_type);
if (!err) {
blkaddr = dn.data_blkaddr;
set_inode_flag(inode, FI_APPEND_WRITE);
}
}
} else {
if (create) {
if (unlikely(f2fs_cp_error(sbi))) {
err = -EIO;
goto sync_out;
}
if (flag == F2FS_GET_BLOCK_PRE_AIO) {
if (blkaddr == NULL_ADDR) {
prealloc++;
last_ofs_in_node = dn.ofs_in_node;
}
} else {
WARN_ON(flag != F2FS_GET_BLOCK_PRE_DIO &&
flag != F2FS_GET_BLOCK_DIO);
err = __allocate_data_block(&dn,
map->m_seg_type);
if (!err)
set_inode_flag(inode, FI_APPEND_WRITE);
}
if (err)
goto sync_out;
map->m_flags |= F2FS_MAP_NEW;
blkaddr = dn.data_blkaddr;
} else {
if (flag == F2FS_GET_BLOCK_BMAP) {
map->m_pblk = 0;
goto sync_out;
}
if (flag == F2FS_GET_BLOCK_PRECACHE)
goto sync_out;
if (flag == F2FS_GET_BLOCK_FIEMAP &&
blkaddr == NULL_ADDR) {
if (map->m_next_pgofs)
*map->m_next_pgofs = pgofs + 1;
goto sync_out;
}
if (flag != F2FS_GET_BLOCK_FIEMAP) {
/* for defragment case */
if (map->m_next_pgofs)
*map->m_next_pgofs = pgofs + 1;
goto sync_out;
}
}
}
if (flag == F2FS_GET_BLOCK_PRE_AIO)
goto skip;
if (map->m_len == 0) {
/* preallocated unwritten block should be mapped for fiemap. */
if (blkaddr == NEW_ADDR)
map->m_flags |= F2FS_MAP_UNWRITTEN;
map->m_flags |= F2FS_MAP_MAPPED;
map->m_pblk = blkaddr;
map->m_len = 1;
} else if ((map->m_pblk != NEW_ADDR &&
blkaddr == (map->m_pblk + ofs)) ||
(map->m_pblk == NEW_ADDR && blkaddr == NEW_ADDR) ||
flag == F2FS_GET_BLOCK_PRE_DIO) {
ofs++;
map->m_len++;
} else {
goto sync_out;
}
skip:
dn.ofs_in_node++;
pgofs++;
/* preallocate blocks in batch for one dnode page */
if (flag == F2FS_GET_BLOCK_PRE_AIO &&
(pgofs == end || dn.ofs_in_node == end_offset)) {
dn.ofs_in_node = ofs_in_node;
err = f2fs_reserve_new_blocks(&dn, prealloc);
if (err)
goto sync_out;
map->m_len += dn.ofs_in_node - ofs_in_node;
if (prealloc && dn.ofs_in_node != last_ofs_in_node + 1) {
err = -ENOSPC;
goto sync_out;
}
dn.ofs_in_node = end_offset;
}
if (pgofs >= end)
goto sync_out;
else if (dn.ofs_in_node < end_offset)
goto next_block;
if (flag == F2FS_GET_BLOCK_PRECACHE) {
if (map->m_flags & F2FS_MAP_MAPPED) {
unsigned int ofs = start_pgofs - map->m_lblk;
f2fs_update_extent_cache_range(&dn,
start_pgofs, map->m_pblk + ofs,
map->m_len - ofs);
}
}
f2fs_put_dnode(&dn);
if (map->m_may_create) {
__do_map_lock(sbi, flag, false);
f2fs_balance_fs(sbi, dn.node_changed);
}
goto next_dnode;
sync_out:
/* for hardware encryption, but to avoid potential issue in future */
if (flag == F2FS_GET_BLOCK_DIO && map->m_flags & F2FS_MAP_MAPPED)
f2fs_wait_on_block_writeback_range(inode,
map->m_pblk, map->m_len);
if (flag == F2FS_GET_BLOCK_PRECACHE) {
if (map->m_flags & F2FS_MAP_MAPPED) {
unsigned int ofs = start_pgofs - map->m_lblk;
f2fs_update_extent_cache_range(&dn,
start_pgofs, map->m_pblk + ofs,
map->m_len - ofs);
}
if (map->m_next_extent)
*map->m_next_extent = pgofs + 1;
}
f2fs_put_dnode(&dn);
unlock_out:
if (map->m_may_create) {
__do_map_lock(sbi, flag, false);
f2fs_balance_fs(sbi, dn.node_changed);
}
out:
trace_f2fs_map_blocks(inode, map, err);
return err;
}
bool f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len)
{
struct f2fs_map_blocks map;
block_t last_lblk;
int err;
if (pos + len > i_size_read(inode))
return false;
map.m_lblk = F2FS_BYTES_TO_BLK(pos);
map.m_next_pgofs = NULL;
map.m_next_extent = NULL;
map.m_seg_type = NO_CHECK_TYPE;
map.m_may_create = false;
last_lblk = F2FS_BLK_ALIGN(pos + len);
while (map.m_lblk < last_lblk) {
map.m_len = last_lblk - map.m_lblk;
err = f2fs_map_blocks(inode, &map, 0, F2FS_GET_BLOCK_DEFAULT);
if (err || map.m_len == 0)
return false;
map.m_lblk += map.m_len;
}
return true;
}
static int __get_data_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh, int create, int flag,
pgoff_t *next_pgofs, int seg_type, bool may_write)
{
struct f2fs_map_blocks map;
int err;
map.m_lblk = iblock;
map.m_len = bh->b_size >> inode->i_blkbits;
map.m_next_pgofs = next_pgofs;
map.m_next_extent = NULL;
map.m_seg_type = seg_type;
map.m_may_create = may_write;
err = f2fs_map_blocks(inode, &map, create, flag);
if (!err) {
map_bh(bh, inode->i_sb, map.m_pblk);
bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;
bh->b_size = (u64)map.m_len << inode->i_blkbits;
}
return err;
}
static int get_data_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create, int flag,
pgoff_t *next_pgofs)
{
return __get_data_block(inode, iblock, bh_result, create,
flag, next_pgofs,
NO_CHECK_TYPE, create);
}
static int get_data_block_dio_write(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
return __get_data_block(inode, iblock, bh_result, create,
F2FS_GET_BLOCK_DIO, NULL,
f2fs_rw_hint_to_seg_type(inode->i_write_hint),
true);
}
static int get_data_block_dio(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
return __get_data_block(inode, iblock, bh_result, create,
F2FS_GET_BLOCK_DIO, NULL,
f2fs_rw_hint_to_seg_type(inode->i_write_hint),
false);
}
static int get_data_block_bmap(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
/* Block number less than F2FS MAX BLOCKS */
if (unlikely(iblock >= F2FS_I_SB(inode)->max_file_blocks))
return -EFBIG;
return __get_data_block(inode, iblock, bh_result, create,
F2FS_GET_BLOCK_BMAP, NULL,
NO_CHECK_TYPE, create);
}
static inline sector_t logical_to_blk(struct inode *inode, loff_t offset)
{
return (offset >> inode->i_blkbits);
}
static inline loff_t blk_to_logical(struct inode *inode, sector_t blk)
{
return (blk << inode->i_blkbits);
}
static int f2fs_xattr_fiemap(struct inode *inode,
struct fiemap_extent_info *fieinfo)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct page *page;
struct node_info ni;
__u64 phys = 0, len;
__u32 flags;
nid_t xnid = F2FS_I(inode)->i_xattr_nid;
int err = 0;
if (f2fs_has_inline_xattr(inode)) {
int offset;
page = f2fs_grab_cache_page(NODE_MAPPING(sbi),
inode->i_ino, false);
if (!page)
return -ENOMEM;
err = f2fs_get_node_info(sbi, inode->i_ino, &ni);
if (err) {
f2fs_put_page(page, 1);
return err;
}
phys = (__u64)blk_to_logical(inode, ni.blk_addr);
offset = offsetof(struct f2fs_inode, i_addr) +
sizeof(__le32) * (DEF_ADDRS_PER_INODE -
get_inline_xattr_addrs(inode));
phys += offset;
len = inline_xattr_size(inode);
f2fs_put_page(page, 1);
flags = FIEMAP_EXTENT_DATA_INLINE | FIEMAP_EXTENT_NOT_ALIGNED;
if (!xnid)
flags |= FIEMAP_EXTENT_LAST;
err = fiemap_fill_next_extent(fieinfo, 0, phys, len, flags);
if (err || err == 1)
return err;
}
if (xnid) {
page = f2fs_grab_cache_page(NODE_MAPPING(sbi), xnid, false);
if (!page)
return -ENOMEM;
err = f2fs_get_node_info(sbi, xnid, &ni);
if (err) {
f2fs_put_page(page, 1);
return err;
}
phys = (__u64)blk_to_logical(inode, ni.blk_addr);
len = inode->i_sb->s_blocksize;
f2fs_put_page(page, 1);
flags = FIEMAP_EXTENT_LAST;
}
if (phys)
err = fiemap_fill_next_extent(fieinfo, 0, phys, len, flags);
return (err < 0 ? err : 0);
}
int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
struct buffer_head map_bh;
sector_t start_blk, last_blk;
pgoff_t next_pgofs;
u64 logical = 0, phys = 0, size = 0;
u32 flags = 0;
int ret = 0;
if (fieinfo->fi_flags & FIEMAP_FLAG_CACHE) {
ret = f2fs_precache_extents(inode);
if (ret)
return ret;
}
ret = fiemap_check_flags(fieinfo, FIEMAP_FLAG_SYNC | FIEMAP_FLAG_XATTR);
if (ret)
return ret;
inode_lock(inode);
if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {
ret = f2fs_xattr_fiemap(inode, fieinfo);
goto out;
}
if (f2fs_has_inline_data(inode)) {
ret = f2fs_inline_data_fiemap(inode, fieinfo, start, len);
if (ret != -EAGAIN)
goto out;
}
if (logical_to_blk(inode, len) == 0)
len = blk_to_logical(inode, 1);
start_blk = logical_to_blk(inode, start);
last_blk = logical_to_blk(inode, start + len - 1);
next:
memset(&map_bh, 0, sizeof(struct buffer_head));
map_bh.b_size = len;
ret = get_data_block(inode, start_blk, &map_bh, 0,
F2FS_GET_BLOCK_FIEMAP, &next_pgofs);
if (ret)
goto out;
/* HOLE */
if (!buffer_mapped(&map_bh)) {
start_blk = next_pgofs;
if (blk_to_logical(inode, start_blk) < blk_to_logical(inode,
F2FS_I_SB(inode)->max_file_blocks))
goto prep_next;
flags |= FIEMAP_EXTENT_LAST;
}
if (size) {
if (IS_ENCRYPTED(inode))
flags |= FIEMAP_EXTENT_DATA_ENCRYPTED;
ret = fiemap_fill_next_extent(fieinfo, logical,
phys, size, flags);
}
if (start_blk > last_blk || ret)
goto out;
logical = blk_to_logical(inode, start_blk);
phys = blk_to_logical(inode, map_bh.b_blocknr);
size = map_bh.b_size;
flags = 0;
if (buffer_unwritten(&map_bh))
flags = FIEMAP_EXTENT_UNWRITTEN;
start_blk += logical_to_blk(inode, size);
prep_next:
cond_resched();
if (fatal_signal_pending(current))
ret = -EINTR;
else
goto next;
out:
if (ret == 1)
ret = 0;
inode_unlock(inode);
return ret;
}
static int f2fs_read_single_page(struct inode *inode, struct page *page,
unsigned nr_pages,
struct f2fs_map_blocks *map,
struct bio **bio_ret,
sector_t *last_block_in_bio,
bool is_readahead)
{
struct bio *bio = *bio_ret;
const unsigned blkbits = inode->i_blkbits;
const unsigned blocksize = 1 << blkbits;
sector_t block_in_file;
sector_t last_block;
sector_t last_block_in_file;
sector_t block_nr;
int ret = 0;
block_in_file = (sector_t)page->index;
last_block = block_in_file + nr_pages;
last_block_in_file = (i_size_read(inode) + blocksize - 1) >>
blkbits;
if (last_block > last_block_in_file)
last_block = last_block_in_file;
/* just zeroing out page which is beyond EOF */
if (block_in_file >= last_block)
goto zero_out;
/*
* Map blocks using the previous result first.
*/
if ((map->m_flags & F2FS_MAP_MAPPED) &&
block_in_file > map->m_lblk &&
block_in_file < (map->m_lblk + map->m_len))
goto got_it;
/*
* Then do more f2fs_map_blocks() calls until we are
* done with this page.
*/
map->m_lblk = block_in_file;
map->m_len = last_block - block_in_file;
ret = f2fs_map_blocks(inode, map, 0, F2FS_GET_BLOCK_DEFAULT);
if (ret)
goto out;
got_it:
if ((map->m_flags & F2FS_MAP_MAPPED)) {
block_nr = map->m_pblk + block_in_file - map->m_lblk;
SetPageMappedToDisk(page);
if (!PageUptodate(page) && !cleancache_get_page(page)) {
SetPageUptodate(page);
goto confused;
}
if (!f2fs_is_valid_blkaddr(F2FS_I_SB(inode), block_nr,
DATA_GENERIC_ENHANCE_READ)) {
ret = -EFSCORRUPTED;
goto out;
}
} else {
zero_out:
zero_user_segment(page, 0, PAGE_SIZE);
if (!PageUptodate(page))
SetPageUptodate(page);
unlock_page(page);
goto out;
}
/*
* This page will go to BIO. Do we need to send this
* BIO off first?
*/
if (bio && (*last_block_in_bio != block_nr - 1 ||
!__same_bdev(F2FS_I_SB(inode), block_nr, bio))) {
submit_and_realloc:
__submit_bio(F2FS_I_SB(inode), bio, DATA);
bio = NULL;
}
if (bio == NULL) {
bio = f2fs_grab_read_bio(inode, block_nr, nr_pages,
is_readahead ? REQ_RAHEAD : 0);
if (IS_ERR(bio)) {
ret = PTR_ERR(bio);
bio = NULL;
goto out;
}
}
/*
* If the page is under writeback, we need to wait for
* its completion to see the correct decrypted data.
*/
f2fs_wait_on_block_writeback(inode, block_nr);
if (bio_add_page(bio, page, blocksize, 0) < blocksize)
goto submit_and_realloc;
inc_page_count(F2FS_I_SB(inode), F2FS_RD_DATA);
ClearPageError(page);
*last_block_in_bio = block_nr;
goto out;
confused:
if (bio) {
__submit_bio(F2FS_I_SB(inode), bio, DATA);
bio = NULL;
}
unlock_page(page);
out:
*bio_ret = bio;
return ret;
}
/*
* This function was originally taken from fs/mpage.c, and customized for f2fs.
* Major change was from block_size == page_size in f2fs by default.
*
* Note that the aops->readpages() function is ONLY used for read-ahead. If
* this function ever deviates from doing just read-ahead, it should either
* use ->readpage() or do the necessary surgery to decouple ->readpages()
* from read-ahead.
*/
static int f2fs_mpage_readpages(struct address_space *mapping,
struct list_head *pages, struct page *page,
unsigned nr_pages, bool is_readahead)
{
struct bio *bio = NULL;
sector_t last_block_in_bio = 0;
struct inode *inode = mapping->host;
struct f2fs_map_blocks map;
int ret = 0;
map.m_pblk = 0;
map.m_lblk = 0;
map.m_len = 0;
map.m_flags = 0;
map.m_next_pgofs = NULL;
map.m_next_extent = NULL;
map.m_seg_type = NO_CHECK_TYPE;
map.m_may_create = false;
for (; nr_pages; nr_pages--) {
if (pages) {
page = list_last_entry(pages, struct page, lru);
prefetchw(&page->flags);
list_del(&page->lru);
if (add_to_page_cache_lru(page, mapping,
page->index,
readahead_gfp_mask(mapping)))
goto next_page;
}
ret = f2fs_read_single_page(inode, page, nr_pages, &map, &bio,
&last_block_in_bio, is_readahead);
if (ret) {
SetPageError(page);
zero_user_segment(page, 0, PAGE_SIZE);
unlock_page(page);
}
next_page:
if (pages)
put_page(page);
}
BUG_ON(pages && !list_empty(pages));
if (bio)
__submit_bio(F2FS_I_SB(inode), bio, DATA);
return pages ? 0 : ret;
}
static int f2fs_read_data_page(struct file *file, struct page *page)
{
struct inode *inode = page->mapping->host;
int ret = -EAGAIN;
trace_f2fs_readpage(page, DATA);
/* If the file has inline data, try to read it directly */
if (f2fs_has_inline_data(inode))
ret = f2fs_read_inline_data(inode, page);
if (ret == -EAGAIN)
ret = f2fs_mpage_readpages(page->mapping, NULL, page, 1, false);
return ret;
}
static int f2fs_read_data_pages(struct file *file,
struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct inode *inode = mapping->host;
struct page *page = list_last_entry(pages, struct page, lru);
trace_f2fs_readpages(inode, page, nr_pages);
/* If the file has inline data, skip readpages */
if (f2fs_has_inline_data(inode))
return 0;
return f2fs_mpage_readpages(mapping, pages, NULL, nr_pages, true);
}
static int encrypt_one_page(struct f2fs_io_info *fio)
{
struct inode *inode = fio->page->mapping->host;
struct page *mpage;
gfp_t gfp_flags = GFP_NOFS;
if (!f2fs_encrypted_file(inode))
return 0;
/* wait for GCed page writeback via META_MAPPING */
f2fs_wait_on_block_writeback(inode, fio->old_blkaddr);
retry_encrypt:
fio->encrypted_page = fscrypt_encrypt_page(inode, fio->page,
PAGE_SIZE, 0, fio->page->index, gfp_flags);
if (IS_ERR(fio->encrypted_page)) {
/* flush pending IOs and wait for a while in the ENOMEM case */
if (PTR_ERR(fio->encrypted_page) == -ENOMEM) {
f2fs_flush_merged_writes(fio->sbi);
congestion_wait(BLK_RW_ASYNC, HZ/50);
gfp_flags |= __GFP_NOFAIL;
goto retry_encrypt;
}
return PTR_ERR(fio->encrypted_page);
}
mpage = find_lock_page(META_MAPPING(fio->sbi), fio->old_blkaddr);
if (mpage) {
if (PageUptodate(mpage))
memcpy(page_address(mpage),
page_address(fio->encrypted_page), PAGE_SIZE);
f2fs_put_page(mpage, 1);
}
return 0;
}
static inline bool check_inplace_update_policy(struct inode *inode,
struct f2fs_io_info *fio)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
unsigned int policy = SM_I(sbi)->ipu_policy;
if (policy & (0x1 << F2FS_IPU_FORCE))
return true;
if (policy & (0x1 << F2FS_IPU_SSR) && f2fs_need_SSR(sbi))
return true;
if (policy & (0x1 << F2FS_IPU_UTIL) &&
utilization(sbi) > SM_I(sbi)->min_ipu_util)
return true;
if (policy & (0x1 << F2FS_IPU_SSR_UTIL) && f2fs_need_SSR(sbi) &&
utilization(sbi) > SM_I(sbi)->min_ipu_util)
return true;
/*
* IPU for rewrite async pages
*/
if (policy & (0x1 << F2FS_IPU_ASYNC) &&
fio && fio->op == REQ_OP_WRITE &&
!(fio->op_flags & REQ_SYNC) &&
!IS_ENCRYPTED(inode))
return true;
/* this is only set during fdatasync */
if (policy & (0x1 << F2FS_IPU_FSYNC) &&
is_inode_flag_set(inode, FI_NEED_IPU))
return true;
if (unlikely(fio && is_sbi_flag_set(sbi, SBI_CP_DISABLED) &&
!f2fs_is_checkpointed_data(sbi, fio->old_blkaddr)))
return true;
return false;
}
bool f2fs_should_update_inplace(struct inode *inode, struct f2fs_io_info *fio)
{
if (f2fs_is_pinned_file(inode))
return true;
/* if this is cold file, we should overwrite to avoid fragmentation */
if (file_is_cold(inode))
return true;
return check_inplace_update_policy(inode, fio);
}
bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
if (test_opt(sbi, LFS))
return true;
if (S_ISDIR(inode->i_mode))
return true;
if (IS_NOQUOTA(inode))
return true;
if (f2fs_is_atomic_file(inode))
return true;
if (fio) {
if (is_cold_data(fio->page))
return true;
if (IS_ATOMIC_WRITTEN_PAGE(fio->page))
return true;
if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED) &&
f2fs_is_checkpointed_data(sbi, fio->old_blkaddr)))
return true;
}
return false;
}
static inline bool need_inplace_update(struct f2fs_io_info *fio)
{
struct inode *inode = fio->page->mapping->host;
if (f2fs_should_update_outplace(inode, fio))
return false;
return f2fs_should_update_inplace(inode, fio);
}
int f2fs_do_write_data_page(struct f2fs_io_info *fio)
{
struct page *page = fio->page;
struct inode *inode = page->mapping->host;
struct dnode_of_data dn;
struct extent_info ei = {0,0,0};
struct node_info ni;
bool ipu_force = false;
int err = 0;
set_new_dnode(&dn, inode, NULL, NULL, 0);
if (need_inplace_update(fio) &&
f2fs_lookup_extent_cache(inode, page->index, &ei)) {
fio->old_blkaddr = ei.blk + page->index - ei.fofs;
if (!f2fs_is_valid_blkaddr(fio->sbi, fio->old_blkaddr,
DATA_GENERIC_ENHANCE))
return -EFSCORRUPTED;
ipu_force = true;
fio->need_lock = LOCK_DONE;
goto got_it;
}
/* Deadlock due to between page->lock and f2fs_lock_op */
if (fio->need_lock == LOCK_REQ && !f2fs_trylock_op(fio->sbi))
return -EAGAIN;
err = f2fs_get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
if (err)
goto out;
fio->old_blkaddr = dn.data_blkaddr;
/* This page is already truncated */
if (fio->old_blkaddr == NULL_ADDR) {
ClearPageUptodate(page);
clear_cold_data(page);
goto out_writepage;
}
got_it:
if (__is_valid_data_blkaddr(fio->old_blkaddr) &&
!f2fs_is_valid_blkaddr(fio->sbi, fio->old_blkaddr,
DATA_GENERIC_ENHANCE)) {
err = -EFSCORRUPTED;
goto out_writepage;
}
/*
* If current allocation needs SSR,
* it had better in-place writes for updated data.
*/
if (ipu_force ||
(__is_valid_data_blkaddr(fio->old_blkaddr) &&
need_inplace_update(fio))) {
err = encrypt_one_page(fio);
if (err)
goto out_writepage;
set_page_writeback(page);
ClearPageError(page);
f2fs_put_dnode(&dn);
if (fio->need_lock == LOCK_REQ)
f2fs_unlock_op(fio->sbi);
err = f2fs_inplace_write_data(fio);
if (err) {
if (f2fs_encrypted_file(inode))
fscrypt_pullback_bio_page(&fio->encrypted_page,
true);
if (PageWriteback(page))
end_page_writeback(page);
} else {
set_inode_flag(inode, FI_UPDATE_WRITE);
}
trace_f2fs_do_write_data_page(fio->page, IPU);
return err;
}
if (fio->need_lock == LOCK_RETRY) {
if (!f2fs_trylock_op(fio->sbi)) {
err = -EAGAIN;
goto out_writepage;
}
fio->need_lock = LOCK_REQ;
}
err = f2fs_get_node_info(fio->sbi, dn.nid, &ni);
if (err)
goto out_writepage;
fio->version = ni.version;
err = encrypt_one_page(fio);
if (err)
goto out_writepage;
set_page_writeback(page);
ClearPageError(page);
/* LFS mode write path */
f2fs_outplace_write_data(&dn, fio);
trace_f2fs_do_write_data_page(page, OPU);
set_inode_flag(inode, FI_APPEND_WRITE);
if (page->index == 0)
set_inode_flag(inode, FI_FIRST_BLOCK_WRITTEN);
out_writepage:
f2fs_put_dnode(&dn);
out:
if (fio->need_lock == LOCK_REQ)
f2fs_unlock_op(fio->sbi);
return err;
}
static int __write_data_page(struct page *page, bool *submitted,
struct bio **bio,
sector_t *last_block,
struct writeback_control *wbc,
enum iostat_type io_type)
{
struct inode *inode = page->mapping->host;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
loff_t i_size = i_size_read(inode);
const pgoff_t end_index = ((unsigned long long) i_size)
>> PAGE_SHIFT;
loff_t psize = (page->index + 1) << PAGE_SHIFT;
unsigned offset = 0;
bool need_balance_fs = false;
int err = 0;
struct f2fs_io_info fio = {
.sbi = sbi,
.ino = inode->i_ino,
.type = DATA,
.op = REQ_OP_WRITE,
.op_flags = wbc_to_write_flags(wbc),
.old_blkaddr = NULL_ADDR,
.page = page,
.encrypted_page = NULL,
.submitted = false,
.need_lock = LOCK_RETRY,
.io_type = io_type,
.io_wbc = wbc,
.bio = bio,
.last_block = last_block,
};
trace_f2fs_writepage(page, DATA);
/* we should bypass data pages to proceed the kworkder jobs */
if (unlikely(f2fs_cp_error(sbi))) {
mapping_set_error(page->mapping, -EIO);
/*
* don't drop any dirty dentry pages for keeping lastest
* directory structure.
*/
if (S_ISDIR(inode->i_mode))
goto redirty_out;
goto out;
}
if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
goto redirty_out;
if (page->index < end_index)
goto write;
/*
* If the offset is out-of-range of file size,
* this page does not have to be written to disk.
*/
offset = i_size & (PAGE_SIZE - 1);
if ((page->index >= end_index + 1) || !offset)
goto out;
zero_user_segment(page, offset, PAGE_SIZE);
write:
if (f2fs_is_drop_cache(inode))
goto out;
/* we should not write 0'th page having journal header */
if (f2fs_is_volatile_file(inode) && (!page->index ||
(!wbc->for_reclaim &&
f2fs_available_free_memory(sbi, BASE_CHECK))))
goto redirty_out;
/* Dentry blocks are controlled by checkpoint */
if (S_ISDIR(inode->i_mode)) {
fio.need_lock = LOCK_DONE;
err = f2fs_do_write_data_page(&fio);
goto done;
}
if (!wbc->for_reclaim)
need_balance_fs = true;
else if (has_not_enough_free_secs(sbi, 0, 0))
goto redirty_out;
else
set_inode_flag(inode, FI_HOT_DATA);
err = -EAGAIN;
if (f2fs_has_inline_data(inode)) {
err = f2fs_write_inline_data(inode, page);
if (!err)
goto out;
}
if (err == -EAGAIN) {
err = f2fs_do_write_data_page(&fio);
if (err == -EAGAIN) {
fio.need_lock = LOCK_REQ;
err = f2fs_do_write_data_page(&fio);
}
}
if (err) {
file_set_keep_isize(inode);
} else {
down_write(&F2FS_I(inode)->i_sem);
if (F2FS_I(inode)->last_disk_size < psize)
F2FS_I(inode)->last_disk_size = psize;
up_write(&F2FS_I(inode)->i_sem);
}
done:
if (err && err != -ENOENT)
goto redirty_out;
out:
inode_dec_dirty_pages(inode);
if (err) {
ClearPageUptodate(page);
clear_cold_data(page);
}
if (wbc->for_reclaim) {
f2fs_submit_merged_write_cond(sbi, NULL, page, 0, DATA);
clear_inode_flag(inode, FI_HOT_DATA);
f2fs_remove_dirty_inode(inode);
submitted = NULL;
}
unlock_page(page);
if (!S_ISDIR(inode->i_mode) && !IS_NOQUOTA(inode) &&
!F2FS_I(inode)->cp_task) {
f2fs_submit_ipu_bio(sbi, bio, page);
f2fs_balance_fs(sbi, need_balance_fs);
}
if (unlikely(f2fs_cp_error(sbi))) {
f2fs_submit_ipu_bio(sbi, bio, page);
f2fs_submit_merged_write(sbi, DATA);
submitted = NULL;
}
if (submitted)
*submitted = fio.submitted;
return 0;
redirty_out:
redirty_page_for_writepage(wbc, page);
/*
* pageout() in MM traslates EAGAIN, so calls handle_write_error()
* -> mapping_set_error() -> set_bit(AS_EIO, ...).
* file_write_and_wait_range() will see EIO error, which is critical
* to return value of fsync() followed by atomic_write failure to user.
*/
if (!err || wbc->for_reclaim)
return AOP_WRITEPAGE_ACTIVATE;
unlock_page(page);
return err;
}
static int f2fs_write_data_page(struct page *page,
struct writeback_control *wbc)
{
return __write_data_page(page, NULL, NULL, NULL, wbc, FS_DATA_IO);
}
/*
* This function was copied from write_cche_pages from mm/page-writeback.c.
* The major change is making write step of cold data page separately from
* warm/hot data page.
*/
static int f2fs_write_cache_pages(struct address_space *mapping,
struct writeback_control *wbc,
enum iostat_type io_type)
{
int ret = 0;
int done = 0;
struct pagevec pvec;
struct f2fs_sb_info *sbi = F2FS_M_SB(mapping);
struct bio *bio = NULL;
sector_t last_block;
int nr_pages;
pgoff_t uninitialized_var(writeback_index);
pgoff_t index;
pgoff_t end; /* Inclusive */
pgoff_t done_index;
int cycled;
int range_whole = 0;
xa_mark_t tag;
int nwritten = 0;
pagevec_init(&pvec);
if (get_dirty_pages(mapping->host) <=
SM_I(F2FS_M_SB(mapping))->min_hot_blocks)
set_inode_flag(mapping->host, FI_HOT_DATA);
else
clear_inode_flag(mapping->host, FI_HOT_DATA);
if (wbc->range_cyclic) {
writeback_index = mapping->writeback_index; /* prev offset */
index = writeback_index;
if (index == 0)
cycled = 1;
else
cycled = 0;
end = -1;
} else {
index = wbc->range_start >> PAGE_SHIFT;
end = wbc->range_end >> PAGE_SHIFT;
if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
range_whole = 1;
cycled = 1; /* ignore range_cyclic tests */
}
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag = PAGECACHE_TAG_TOWRITE;
else
tag = PAGECACHE_TAG_DIRTY;
retry:
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag_pages_for_writeback(mapping, index, end);
done_index = index;
while (!done && (index <= end)) {
int i;
nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
tag);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
bool submitted = false;
/* give a priority to WB_SYNC threads */
if (atomic_read(&sbi->wb_sync_req[DATA]) &&
wbc->sync_mode == WB_SYNC_NONE) {
done = 1;
break;
}
done_index = page->index;
retry_write:
lock_page(page);
if (unlikely(page->mapping != mapping)) {
continue_unlock:
unlock_page(page);
continue;
}
if (!PageDirty(page)) {
/* someone wrote it for us */
goto continue_unlock;
}
if (PageWriteback(page)) {
if (wbc->sync_mode != WB_SYNC_NONE) {
f2fs_wait_on_page_writeback(page,
DATA, true, true);
f2fs_submit_ipu_bio(sbi, &bio, page);
} else {
goto continue_unlock;
}
}
if (!clear_page_dirty_for_io(page))
goto continue_unlock;
ret = __write_data_page(page, &submitted, &bio,
&last_block, wbc, io_type);
if (unlikely(ret)) {
/*
* keep nr_to_write, since vfs uses this to
* get # of written pages.
*/
if (ret == AOP_WRITEPAGE_ACTIVATE) {
unlock_page(page);
ret = 0;
continue;
} else if (ret == -EAGAIN) {
ret = 0;
if (wbc->sync_mode == WB_SYNC_ALL) {
cond_resched();
congestion_wait(BLK_RW_ASYNC,
HZ/50);
goto retry_write;
}
continue;
}
done_index = page->index + 1;
done = 1;
break;
} else if (submitted) {
nwritten++;
}
if (--wbc->nr_to_write <= 0 &&
wbc->sync_mode == WB_SYNC_NONE) {
done = 1;
break;
}
}
pagevec_release(&pvec);
cond_resched();
}
if (!cycled && !done) {
cycled = 1;
index = 0;
end = writeback_index - 1;
goto retry;
}
if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
mapping->writeback_index = done_index;
if (nwritten)
f2fs_submit_merged_write_cond(F2FS_M_SB(mapping), mapping->host,
NULL, 0, DATA);
/* submit cached bio of IPU write */
if (bio)
__submit_bio(sbi, bio, DATA);
return ret;
}
static inline bool __should_serialize_io(struct inode *inode,
struct writeback_control *wbc)
{
if (!S_ISREG(inode->i_mode))
return false;
if (IS_NOQUOTA(inode))
return false;
/* to avoid deadlock in path of data flush */
if (F2FS_I(inode)->cp_task)
return false;
if (wbc->sync_mode != WB_SYNC_ALL)
return true;
if (get_dirty_pages(inode) >= SM_I(F2FS_I_SB(inode))->min_seq_blocks)
return true;
return false;
}
static int __f2fs_write_data_pages(struct address_space *mapping,
struct writeback_control *wbc,
enum iostat_type io_type)
{
struct inode *inode = mapping->host;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct blk_plug plug;
int ret;
bool locked = false;
/* deal with chardevs and other special file */
if (!mapping->a_ops->writepage)
return 0;
/* skip writing if there is no dirty page in this inode */
if (!get_dirty_pages(inode) && wbc->sync_mode == WB_SYNC_NONE)
return 0;
/* during POR, we don't need to trigger writepage at all. */
if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
goto skip_write;
if ((S_ISDIR(inode->i_mode) || IS_NOQUOTA(inode)) &&
wbc->sync_mode == WB_SYNC_NONE &&
get_dirty_pages(inode) < nr_pages_to_skip(sbi, DATA) &&
f2fs_available_free_memory(sbi, DIRTY_DENTS))
goto skip_write;
/* skip writing during file defragment */
if (is_inode_flag_set(inode, FI_DO_DEFRAG))
goto skip_write;
trace_f2fs_writepages(mapping->host, wbc, DATA);
/* to avoid spliting IOs due to mixed WB_SYNC_ALL and WB_SYNC_NONE */
if (wbc->sync_mode == WB_SYNC_ALL)
atomic_inc(&sbi->wb_sync_req[DATA]);
else if (atomic_read(&sbi->wb_sync_req[DATA]))
goto skip_write;
if (__should_serialize_io(inode, wbc)) {
mutex_lock(&sbi->writepages);
locked = true;
}
blk_start_plug(&plug);
ret = f2fs_write_cache_pages(mapping, wbc, io_type);
blk_finish_plug(&plug);
if (locked)
mutex_unlock(&sbi->writepages);
if (wbc->sync_mode == WB_SYNC_ALL)
atomic_dec(&sbi->wb_sync_req[DATA]);
/*
* if some pages were truncated, we cannot guarantee its mapping->host
* to detect pending bios.
*/
f2fs_remove_dirty_inode(inode);
return ret;
skip_write:
wbc->pages_skipped += get_dirty_pages(inode);
trace_f2fs_writepages(mapping->host, wbc, DATA);
return 0;
}
static int f2fs_write_data_pages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct inode *inode = mapping->host;
return __f2fs_write_data_pages(mapping, wbc,
F2FS_I(inode)->cp_task == current ?
FS_CP_DATA_IO : FS_DATA_IO);
}
static void f2fs_write_failed(struct address_space *mapping, loff_t to)
{
struct inode *inode = mapping->host;
loff_t i_size = i_size_read(inode);
if (to > i_size) {
down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
down_write(&F2FS_I(inode)->i_mmap_sem);
truncate_pagecache(inode, i_size);
if (!IS_NOQUOTA(inode))
f2fs_truncate_blocks(inode, i_size, true);
up_write(&F2FS_I(inode)->i_mmap_sem);
up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
}
}
static int prepare_write_begin(struct f2fs_sb_info *sbi,
struct page *page, loff_t pos, unsigned len,
block_t *blk_addr, bool *node_changed)
{
struct inode *inode = page->mapping->host;
pgoff_t index = page->index;
struct dnode_of_data dn;
struct page *ipage;
bool locked = false;
struct extent_info ei = {0,0,0};
int err = 0;
int flag;
/*
* we already allocated all the blocks, so we don't need to get
* the block addresses when there is no need to fill the page.
*/
if (!f2fs_has_inline_data(inode) && len == PAGE_SIZE &&
!is_inode_flag_set(inode, FI_NO_PREALLOC))
return 0;
/* f2fs_lock_op avoids race between write CP and convert_inline_page */
if (f2fs_has_inline_data(inode) && pos + len > MAX_INLINE_DATA(inode))
flag = F2FS_GET_BLOCK_DEFAULT;
else
flag = F2FS_GET_BLOCK_PRE_AIO;
if (f2fs_has_inline_data(inode) ||
(pos & PAGE_MASK) >= i_size_read(inode)) {
__do_map_lock(sbi, flag, true);
locked = true;
}
restart:
/* check inline_data */
ipage = f2fs_get_node_page(sbi, inode->i_ino);
if (IS_ERR(ipage)) {
err = PTR_ERR(ipage);
goto unlock_out;
}
set_new_dnode(&dn, inode, ipage, ipage, 0);
if (f2fs_has_inline_data(inode)) {
if (pos + len <= MAX_INLINE_DATA(inode)) {
f2fs_do_read_inline_data(page, ipage);
set_inode_flag(inode, FI_DATA_EXIST);
if (inode->i_nlink)
set_inline_node(ipage);
} else {
err = f2fs_convert_inline_page(&dn, page);
if (err)
goto out;
if (dn.data_blkaddr == NULL_ADDR)
err = f2fs_get_block(&dn, index);
}
} else if (locked) {
err = f2fs_get_block(&dn, index);
} else {
if (f2fs_lookup_extent_cache(inode, index, &ei)) {
dn.data_blkaddr = ei.blk + index - ei.fofs;
} else {
/* hole case */
err = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
if (err || dn.data_blkaddr == NULL_ADDR) {
f2fs_put_dnode(&dn);
__do_map_lock(sbi, F2FS_GET_BLOCK_PRE_AIO,
true);
WARN_ON(flag != F2FS_GET_BLOCK_PRE_AIO);
locked = true;
goto restart;
}
}
}
/* convert_inline_page can make node_changed */
*blk_addr = dn.data_blkaddr;
*node_changed = dn.node_changed;
out:
f2fs_put_dnode(&dn);
unlock_out:
if (locked)
__do_map_lock(sbi, flag, false);
return err;
}
static int f2fs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct page *page = NULL;
pgoff_t index = ((unsigned long long) pos) >> PAGE_SHIFT;
bool need_balance = false, drop_atomic = false;
block_t blkaddr = NULL_ADDR;
int err = 0;
trace_f2fs_write_begin(inode, pos, len, flags);
err = f2fs_is_checkpoint_ready(sbi);
if (err)
goto fail;
if ((f2fs_is_atomic_file(inode) &&
!f2fs_available_free_memory(sbi, INMEM_PAGES)) ||
is_inode_flag_set(inode, FI_ATOMIC_REVOKE_REQUEST)) {
err = -ENOMEM;
drop_atomic = true;
goto fail;
}
/*
* We should check this at this moment to avoid deadlock on inode page
* and #0 page. The locking rule for inline_data conversion should be:
* lock_page(page #0) -> lock_page(inode_page)
*/
if (index != 0) {
err = f2fs_convert_inline_inode(inode);
if (err)
goto fail;
}
repeat:
/*
* Do not use grab_cache_page_write_begin() to avoid deadlock due to
* wait_for_stable_page. Will wait that below with our IO control.
*/
page = f2fs_pagecache_get_page(mapping, index,
FGP_LOCK | FGP_WRITE | FGP_CREAT, GFP_NOFS);
if (!page) {
err = -ENOMEM;
goto fail;
}
*pagep = page;
err = prepare_write_begin(sbi, page, pos, len,
&blkaddr, &need_balance);
if (err)
goto fail;
if (need_balance && !IS_NOQUOTA(inode) &&
has_not_enough_free_secs(sbi, 0, 0)) {
unlock_page(page);
f2fs_balance_fs(sbi, true);
lock_page(page);
if (page->mapping != mapping) {
/* The page got truncated from under us */
f2fs_put_page(page, 1);
goto repeat;
}
}
f2fs_wait_on_page_writeback(page, DATA, false, true);
if (len == PAGE_SIZE || PageUptodate(page))
return 0;
if (!(pos & (PAGE_SIZE - 1)) && (pos + len) >= i_size_read(inode)) {
zero_user_segment(page, len, PAGE_SIZE);
return 0;
}
if (blkaddr == NEW_ADDR) {
zero_user_segment(page, 0, PAGE_SIZE);
SetPageUptodate(page);
} else {
if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
DATA_GENERIC_ENHANCE_READ)) {
err = -EFSCORRUPTED;
goto fail;
}
err = f2fs_submit_page_read(inode, page, blkaddr);
if (err)
goto fail;
lock_page(page);
if (unlikely(page->mapping != mapping)) {
f2fs_put_page(page, 1);
goto repeat;
}
if (unlikely(!PageUptodate(page))) {
err = -EIO;
goto fail;
}
}
return 0;
fail:
f2fs_put_page(page, 1);
f2fs_write_failed(mapping, pos + len);
if (drop_atomic)
f2fs_drop_inmem_pages_all(sbi, false);
return err;
}
static int f2fs_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = page->mapping->host;
trace_f2fs_write_end(inode, pos, len, copied);
/*
* This should be come from len == PAGE_SIZE, and we expect copied
* should be PAGE_SIZE. Otherwise, we treat it with zero copied and
* let generic_perform_write() try to copy data again through copied=0.
*/
if (!PageUptodate(page)) {
if (unlikely(copied != len))
copied = 0;
else
SetPageUptodate(page);
}
if (!copied)
goto unlock_out;
set_page_dirty(page);
if (pos + copied > i_size_read(inode))
f2fs_i_size_write(inode, pos + copied);
unlock_out:
f2fs_put_page(page, 1);
f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
return copied;
}
static int check_direct_IO(struct inode *inode, struct iov_iter *iter,
loff_t offset)
{
unsigned i_blkbits = READ_ONCE(inode->i_blkbits);
unsigned blkbits = i_blkbits;
unsigned blocksize_mask = (1 << blkbits) - 1;
unsigned long align = offset | iov_iter_alignment(iter);
struct block_device *bdev = inode->i_sb->s_bdev;
if (align & blocksize_mask) {
if (bdev)
blkbits = blksize_bits(bdev_logical_block_size(bdev));
blocksize_mask = (1 << blkbits) - 1;
if (align & blocksize_mask)
return -EINVAL;
return 1;
}
return 0;
}
static void f2fs_dio_end_io(struct bio *bio)
{
struct f2fs_private_dio *dio = bio->bi_private;
dec_page_count(F2FS_I_SB(dio->inode),
dio->write ? F2FS_DIO_WRITE : F2FS_DIO_READ);
bio->bi_private = dio->orig_private;
bio->bi_end_io = dio->orig_end_io;
kvfree(dio);
bio_endio(bio);
}
static void f2fs_dio_submit_bio(struct bio *bio, struct inode *inode,
loff_t file_offset)
{
struct f2fs_private_dio *dio;
bool write = (bio_op(bio) == REQ_OP_WRITE);
dio = f2fs_kzalloc(F2FS_I_SB(inode),
sizeof(struct f2fs_private_dio), GFP_NOFS);
if (!dio)
goto out;
dio->inode = inode;
dio->orig_end_io = bio->bi_end_io;
dio->orig_private = bio->bi_private;
dio->write = write;
bio->bi_end_io = f2fs_dio_end_io;
bio->bi_private = dio;
inc_page_count(F2FS_I_SB(inode),
write ? F2FS_DIO_WRITE : F2FS_DIO_READ);
submit_bio(bio);
return;
out:
bio->bi_status = BLK_STS_IOERR;
bio_endio(bio);
}
static ssize_t f2fs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
{
struct address_space *mapping = iocb->ki_filp->f_mapping;
struct inode *inode = mapping->host;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct f2fs_inode_info *fi = F2FS_I(inode);
size_t count = iov_iter_count(iter);
loff_t offset = iocb->ki_pos;
int rw = iov_iter_rw(iter);
int err;
enum rw_hint hint = iocb->ki_hint;
int whint_mode = F2FS_OPTION(sbi).whint_mode;
bool do_opu;
err = check_direct_IO(inode, iter, offset);
if (err)
return err < 0 ? err : 0;
if (f2fs_force_buffered_io(inode, iocb, iter))
return 0;
do_opu = allow_outplace_dio(inode, iocb, iter);
trace_f2fs_direct_IO_enter(inode, offset, count, rw);
if (rw == WRITE && whint_mode == WHINT_MODE_OFF)
iocb->ki_hint = WRITE_LIFE_NOT_SET;
if (iocb->ki_flags & IOCB_NOWAIT) {
if (!down_read_trylock(&fi->i_gc_rwsem[rw])) {
iocb->ki_hint = hint;
err = -EAGAIN;
goto out;
}
if (do_opu && !down_read_trylock(&fi->i_gc_rwsem[READ])) {
up_read(&fi->i_gc_rwsem[rw]);
iocb->ki_hint = hint;
err = -EAGAIN;
goto out;
}
} else {
down_read(&fi->i_gc_rwsem[rw]);
if (do_opu)
down_read(&fi->i_gc_rwsem[READ]);
}
err = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
iter, rw == WRITE ? get_data_block_dio_write :
get_data_block_dio, NULL, f2fs_dio_submit_bio,
DIO_LOCKING | DIO_SKIP_HOLES);
if (do_opu)
up_read(&fi->i_gc_rwsem[READ]);
up_read(&fi->i_gc_rwsem[rw]);
if (rw == WRITE) {
if (whint_mode == WHINT_MODE_OFF)
iocb->ki_hint = hint;
if (err > 0) {
f2fs_update_iostat(F2FS_I_SB(inode), APP_DIRECT_IO,
err);
if (!do_opu)
set_inode_flag(inode, FI_UPDATE_WRITE);
} else if (err < 0) {
f2fs_write_failed(mapping, offset + count);
}
}
out:
trace_f2fs_direct_IO_exit(inode, offset, count, rw, err);
return err;
}
void f2fs_invalidate_page(struct page *page, unsigned int offset,
unsigned int length)
{
struct inode *inode = page->mapping->host;
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
if (inode->i_ino >= F2FS_ROOT_INO(sbi) &&
(offset % PAGE_SIZE || length != PAGE_SIZE))
return;
if (PageDirty(page)) {
if (inode->i_ino == F2FS_META_INO(sbi)) {
dec_page_count(sbi, F2FS_DIRTY_META);
} else if (inode->i_ino == F2FS_NODE_INO(sbi)) {
dec_page_count(sbi, F2FS_DIRTY_NODES);
} else {
inode_dec_dirty_pages(inode);
f2fs_remove_dirty_inode(inode);
}
}
clear_cold_data(page);
if (IS_ATOMIC_WRITTEN_PAGE(page))
return f2fs_drop_inmem_page(inode, page);
f2fs_clear_page_private(page);
}
int f2fs_release_page(struct page *page, gfp_t wait)
{
/* If this is dirty page, keep PagePrivate */
if (PageDirty(page))
return 0;
/* This is atomic written page, keep Private */
if (IS_ATOMIC_WRITTEN_PAGE(page))
return 0;
clear_cold_data(page);
f2fs_clear_page_private(page);
return 1;
}
static int f2fs_set_data_page_dirty(struct page *page)
{
struct address_space *mapping = page->mapping;
struct inode *inode = mapping->host;
trace_f2fs_set_page_dirty(page, DATA);
if (!PageUptodate(page))
SetPageUptodate(page);
if (f2fs_is_atomic_file(inode) && !f2fs_is_commit_atomic_write(inode)) {
if (!IS_ATOMIC_WRITTEN_PAGE(page)) {
f2fs_register_inmem_page(inode, page);
return 1;
}
/*
* Previously, this page has been registered, we just
* return here.
*/
return 0;
}
if (!PageDirty(page)) {
__set_page_dirty_nobuffers(page);
f2fs_update_dirty_page(inode, page);
return 1;
}
return 0;
}
static sector_t f2fs_bmap(struct address_space *mapping, sector_t block)
{
struct inode *inode = mapping->host;
if (f2fs_has_inline_data(inode))
return 0;
/* make sure allocating whole blocks */
if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
filemap_write_and_wait(mapping);
return generic_block_bmap(mapping, block, get_data_block_bmap);
}
#ifdef CONFIG_MIGRATION
#include <linux/migrate.h>
int f2fs_migrate_page(struct address_space *mapping,
struct page *newpage, struct page *page, enum migrate_mode mode)
{
int rc, extra_count;
struct f2fs_inode_info *fi = F2FS_I(mapping->host);
bool atomic_written = IS_ATOMIC_WRITTEN_PAGE(page);
BUG_ON(PageWriteback(page));
/* migrating an atomic written page is safe with the inmem_lock hold */
if (atomic_written) {
if (mode != MIGRATE_SYNC)
return -EBUSY;
if (!mutex_trylock(&fi->inmem_lock))
return -EAGAIN;
}
/* one extra reference was held for atomic_write page */
extra_count = atomic_written ? 1 : 0;
rc = migrate_page_move_mapping(mapping, newpage,
page, mode, extra_count);
if (rc != MIGRATEPAGE_SUCCESS) {
if (atomic_written)
mutex_unlock(&fi->inmem_lock);
return rc;
}
if (atomic_written) {
struct inmem_pages *cur;
list_for_each_entry(cur, &fi->inmem_pages, list)
if (cur->page == page) {
cur->page = newpage;
break;
}
mutex_unlock(&fi->inmem_lock);
put_page(page);
get_page(newpage);
}
if (PagePrivate(page)) {
f2fs_set_page_private(newpage, page_private(page));
f2fs_clear_page_private(page);
}
if (mode != MIGRATE_SYNC_NO_COPY)
migrate_page_copy(newpage, page);
else
migrate_page_states(newpage, page);
return MIGRATEPAGE_SUCCESS;
}
#endif
const struct address_space_operations f2fs_dblock_aops = {
.readpage = f2fs_read_data_page,
.readpages = f2fs_read_data_pages,
.writepage = f2fs_write_data_page,
.writepages = f2fs_write_data_pages,
.write_begin = f2fs_write_begin,
.write_end = f2fs_write_end,
.set_page_dirty = f2fs_set_data_page_dirty,
.invalidatepage = f2fs_invalidate_page,
.releasepage = f2fs_release_page,
.direct_IO = f2fs_direct_IO,
.bmap = f2fs_bmap,
#ifdef CONFIG_MIGRATION
.migratepage = f2fs_migrate_page,
#endif
};
void f2fs_clear_page_cache_dirty_tag(struct page *page)
{
struct address_space *mapping = page_mapping(page);
unsigned long flags;
xa_lock_irqsave(&mapping->i_pages, flags);
__xa_clear_mark(&mapping->i_pages, page_index(page),
PAGECACHE_TAG_DIRTY);
xa_unlock_irqrestore(&mapping->i_pages, flags);
}
int __init f2fs_init_post_read_processing(void)
{
bio_post_read_ctx_cache = KMEM_CACHE(bio_post_read_ctx, 0);
if (!bio_post_read_ctx_cache)
goto fail;
bio_post_read_ctx_pool =
mempool_create_slab_pool(NUM_PREALLOC_POST_READ_CTXS,
bio_post_read_ctx_cache);
if (!bio_post_read_ctx_pool)
goto fail_free_cache;
return 0;
fail_free_cache:
kmem_cache_destroy(bio_post_read_ctx_cache);
fail:
return -ENOMEM;
}
void __exit f2fs_destroy_post_read_processing(void)
{
mempool_destroy(bio_post_read_ctx_pool);
kmem_cache_destroy(bio_post_read_ctx_cache);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_1317_0 |
crossvul-cpp_data_bad_887_1 | /*
* Copyright (C) 2011 Intel Corporation. All rights reserved.
* Copyright (C) 2014 Marvell International Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#define pr_fmt(fmt) "llcp: %s: " fmt, __func__
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/nfc.h>
#include "nfc.h"
#include "llcp.h"
static u8 llcp_magic[3] = {0x46, 0x66, 0x6d};
static LIST_HEAD(llcp_devices);
static void nfc_llcp_rx_skb(struct nfc_llcp_local *local, struct sk_buff *skb);
void nfc_llcp_sock_link(struct llcp_sock_list *l, struct sock *sk)
{
write_lock(&l->lock);
sk_add_node(sk, &l->head);
write_unlock(&l->lock);
}
void nfc_llcp_sock_unlink(struct llcp_sock_list *l, struct sock *sk)
{
write_lock(&l->lock);
sk_del_node_init(sk);
write_unlock(&l->lock);
}
void nfc_llcp_socket_remote_param_init(struct nfc_llcp_sock *sock)
{
sock->remote_rw = LLCP_DEFAULT_RW;
sock->remote_miu = LLCP_MAX_MIU + 1;
}
static void nfc_llcp_socket_purge(struct nfc_llcp_sock *sock)
{
struct nfc_llcp_local *local = sock->local;
struct sk_buff *s, *tmp;
pr_debug("%p\n", &sock->sk);
skb_queue_purge(&sock->tx_queue);
skb_queue_purge(&sock->tx_pending_queue);
if (local == NULL)
return;
/* Search for local pending SKBs that are related to this socket */
skb_queue_walk_safe(&local->tx_queue, s, tmp) {
if (s->sk != &sock->sk)
continue;
skb_unlink(s, &local->tx_queue);
kfree_skb(s);
}
}
static void nfc_llcp_socket_release(struct nfc_llcp_local *local, bool device,
int err)
{
struct sock *sk;
struct hlist_node *tmp;
struct nfc_llcp_sock *llcp_sock;
skb_queue_purge(&local->tx_queue);
write_lock(&local->sockets.lock);
sk_for_each_safe(sk, tmp, &local->sockets.head) {
llcp_sock = nfc_llcp_sock(sk);
bh_lock_sock(sk);
nfc_llcp_socket_purge(llcp_sock);
if (sk->sk_state == LLCP_CONNECTED)
nfc_put_device(llcp_sock->dev);
if (sk->sk_state == LLCP_LISTEN) {
struct nfc_llcp_sock *lsk, *n;
struct sock *accept_sk;
list_for_each_entry_safe(lsk, n,
&llcp_sock->accept_queue,
accept_queue) {
accept_sk = &lsk->sk;
bh_lock_sock(accept_sk);
nfc_llcp_accept_unlink(accept_sk);
if (err)
accept_sk->sk_err = err;
accept_sk->sk_state = LLCP_CLOSED;
accept_sk->sk_state_change(sk);
bh_unlock_sock(accept_sk);
}
}
if (err)
sk->sk_err = err;
sk->sk_state = LLCP_CLOSED;
sk->sk_state_change(sk);
bh_unlock_sock(sk);
sk_del_node_init(sk);
}
write_unlock(&local->sockets.lock);
/* If we still have a device, we keep the RAW sockets alive */
if (device == true)
return;
write_lock(&local->raw_sockets.lock);
sk_for_each_safe(sk, tmp, &local->raw_sockets.head) {
llcp_sock = nfc_llcp_sock(sk);
bh_lock_sock(sk);
nfc_llcp_socket_purge(llcp_sock);
if (err)
sk->sk_err = err;
sk->sk_state = LLCP_CLOSED;
sk->sk_state_change(sk);
bh_unlock_sock(sk);
sk_del_node_init(sk);
}
write_unlock(&local->raw_sockets.lock);
}
struct nfc_llcp_local *nfc_llcp_local_get(struct nfc_llcp_local *local)
{
kref_get(&local->ref);
return local;
}
static void local_cleanup(struct nfc_llcp_local *local)
{
nfc_llcp_socket_release(local, false, ENXIO);
del_timer_sync(&local->link_timer);
skb_queue_purge(&local->tx_queue);
cancel_work_sync(&local->tx_work);
cancel_work_sync(&local->rx_work);
cancel_work_sync(&local->timeout_work);
kfree_skb(local->rx_pending);
del_timer_sync(&local->sdreq_timer);
cancel_work_sync(&local->sdreq_timeout_work);
nfc_llcp_free_sdp_tlv_list(&local->pending_sdreqs);
}
static void local_release(struct kref *ref)
{
struct nfc_llcp_local *local;
local = container_of(ref, struct nfc_llcp_local, ref);
list_del(&local->list);
local_cleanup(local);
kfree(local);
}
int nfc_llcp_local_put(struct nfc_llcp_local *local)
{
if (local == NULL)
return 0;
return kref_put(&local->ref, local_release);
}
static struct nfc_llcp_sock *nfc_llcp_sock_get(struct nfc_llcp_local *local,
u8 ssap, u8 dsap)
{
struct sock *sk;
struct nfc_llcp_sock *llcp_sock, *tmp_sock;
pr_debug("ssap dsap %d %d\n", ssap, dsap);
if (ssap == 0 && dsap == 0)
return NULL;
read_lock(&local->sockets.lock);
llcp_sock = NULL;
sk_for_each(sk, &local->sockets.head) {
tmp_sock = nfc_llcp_sock(sk);
if (tmp_sock->ssap == ssap && tmp_sock->dsap == dsap) {
llcp_sock = tmp_sock;
break;
}
}
read_unlock(&local->sockets.lock);
if (llcp_sock == NULL)
return NULL;
sock_hold(&llcp_sock->sk);
return llcp_sock;
}
static void nfc_llcp_sock_put(struct nfc_llcp_sock *sock)
{
sock_put(&sock->sk);
}
static void nfc_llcp_timeout_work(struct work_struct *work)
{
struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local,
timeout_work);
nfc_dep_link_down(local->dev);
}
static void nfc_llcp_symm_timer(struct timer_list *t)
{
struct nfc_llcp_local *local = from_timer(local, t, link_timer);
pr_err("SYMM timeout\n");
schedule_work(&local->timeout_work);
}
static void nfc_llcp_sdreq_timeout_work(struct work_struct *work)
{
unsigned long time;
HLIST_HEAD(nl_sdres_list);
struct hlist_node *n;
struct nfc_llcp_sdp_tlv *sdp;
struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local,
sdreq_timeout_work);
mutex_lock(&local->sdreq_lock);
time = jiffies - msecs_to_jiffies(3 * local->remote_lto);
hlist_for_each_entry_safe(sdp, n, &local->pending_sdreqs, node) {
if (time_after(sdp->time, time))
continue;
sdp->sap = LLCP_SDP_UNBOUND;
hlist_del(&sdp->node);
hlist_add_head(&sdp->node, &nl_sdres_list);
}
if (!hlist_empty(&local->pending_sdreqs))
mod_timer(&local->sdreq_timer,
jiffies + msecs_to_jiffies(3 * local->remote_lto));
mutex_unlock(&local->sdreq_lock);
if (!hlist_empty(&nl_sdres_list))
nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list);
}
static void nfc_llcp_sdreq_timer(struct timer_list *t)
{
struct nfc_llcp_local *local = from_timer(local, t, sdreq_timer);
schedule_work(&local->sdreq_timeout_work);
}
struct nfc_llcp_local *nfc_llcp_find_local(struct nfc_dev *dev)
{
struct nfc_llcp_local *local;
list_for_each_entry(local, &llcp_devices, list)
if (local->dev == dev)
return local;
pr_debug("No device found\n");
return NULL;
}
static char *wks[] = {
NULL,
NULL, /* SDP */
"urn:nfc:sn:ip",
"urn:nfc:sn:obex",
"urn:nfc:sn:snep",
};
static int nfc_llcp_wks_sap(char *service_name, size_t service_name_len)
{
int sap, num_wks;
pr_debug("%s\n", service_name);
if (service_name == NULL)
return -EINVAL;
num_wks = ARRAY_SIZE(wks);
for (sap = 0; sap < num_wks; sap++) {
if (wks[sap] == NULL)
continue;
if (strncmp(wks[sap], service_name, service_name_len) == 0)
return sap;
}
return -EINVAL;
}
static
struct nfc_llcp_sock *nfc_llcp_sock_from_sn(struct nfc_llcp_local *local,
u8 *sn, size_t sn_len)
{
struct sock *sk;
struct nfc_llcp_sock *llcp_sock, *tmp_sock;
pr_debug("sn %zd %p\n", sn_len, sn);
if (sn == NULL || sn_len == 0)
return NULL;
read_lock(&local->sockets.lock);
llcp_sock = NULL;
sk_for_each(sk, &local->sockets.head) {
tmp_sock = nfc_llcp_sock(sk);
pr_debug("llcp sock %p\n", tmp_sock);
if (tmp_sock->sk.sk_type == SOCK_STREAM &&
tmp_sock->sk.sk_state != LLCP_LISTEN)
continue;
if (tmp_sock->sk.sk_type == SOCK_DGRAM &&
tmp_sock->sk.sk_state != LLCP_BOUND)
continue;
if (tmp_sock->service_name == NULL ||
tmp_sock->service_name_len == 0)
continue;
if (tmp_sock->service_name_len != sn_len)
continue;
if (memcmp(sn, tmp_sock->service_name, sn_len) == 0) {
llcp_sock = tmp_sock;
break;
}
}
read_unlock(&local->sockets.lock);
pr_debug("Found llcp sock %p\n", llcp_sock);
return llcp_sock;
}
u8 nfc_llcp_get_sdp_ssap(struct nfc_llcp_local *local,
struct nfc_llcp_sock *sock)
{
mutex_lock(&local->sdp_lock);
if (sock->service_name != NULL && sock->service_name_len > 0) {
int ssap = nfc_llcp_wks_sap(sock->service_name,
sock->service_name_len);
if (ssap > 0) {
pr_debug("WKS %d\n", ssap);
/* This is a WKS, let's check if it's free */
if (local->local_wks & BIT(ssap)) {
mutex_unlock(&local->sdp_lock);
return LLCP_SAP_MAX;
}
set_bit(ssap, &local->local_wks);
mutex_unlock(&local->sdp_lock);
return ssap;
}
/*
* Check if there already is a non WKS socket bound
* to this service name.
*/
if (nfc_llcp_sock_from_sn(local, sock->service_name,
sock->service_name_len) != NULL) {
mutex_unlock(&local->sdp_lock);
return LLCP_SAP_MAX;
}
mutex_unlock(&local->sdp_lock);
return LLCP_SDP_UNBOUND;
} else if (sock->ssap != 0 && sock->ssap < LLCP_WKS_NUM_SAP) {
if (!test_bit(sock->ssap, &local->local_wks)) {
set_bit(sock->ssap, &local->local_wks);
mutex_unlock(&local->sdp_lock);
return sock->ssap;
}
}
mutex_unlock(&local->sdp_lock);
return LLCP_SAP_MAX;
}
u8 nfc_llcp_get_local_ssap(struct nfc_llcp_local *local)
{
u8 local_ssap;
mutex_lock(&local->sdp_lock);
local_ssap = find_first_zero_bit(&local->local_sap, LLCP_LOCAL_NUM_SAP);
if (local_ssap == LLCP_LOCAL_NUM_SAP) {
mutex_unlock(&local->sdp_lock);
return LLCP_SAP_MAX;
}
set_bit(local_ssap, &local->local_sap);
mutex_unlock(&local->sdp_lock);
return local_ssap + LLCP_LOCAL_SAP_OFFSET;
}
void nfc_llcp_put_ssap(struct nfc_llcp_local *local, u8 ssap)
{
u8 local_ssap;
unsigned long *sdp;
if (ssap < LLCP_WKS_NUM_SAP) {
local_ssap = ssap;
sdp = &local->local_wks;
} else if (ssap < LLCP_LOCAL_NUM_SAP) {
atomic_t *client_cnt;
local_ssap = ssap - LLCP_WKS_NUM_SAP;
sdp = &local->local_sdp;
client_cnt = &local->local_sdp_cnt[local_ssap];
pr_debug("%d clients\n", atomic_read(client_cnt));
mutex_lock(&local->sdp_lock);
if (atomic_dec_and_test(client_cnt)) {
struct nfc_llcp_sock *l_sock;
pr_debug("No more clients for SAP %d\n", ssap);
clear_bit(local_ssap, sdp);
/* Find the listening sock and set it back to UNBOUND */
l_sock = nfc_llcp_sock_get(local, ssap, LLCP_SAP_SDP);
if (l_sock) {
l_sock->ssap = LLCP_SDP_UNBOUND;
nfc_llcp_sock_put(l_sock);
}
}
mutex_unlock(&local->sdp_lock);
return;
} else if (ssap < LLCP_MAX_SAP) {
local_ssap = ssap - LLCP_LOCAL_NUM_SAP;
sdp = &local->local_sap;
} else {
return;
}
mutex_lock(&local->sdp_lock);
clear_bit(local_ssap, sdp);
mutex_unlock(&local->sdp_lock);
}
static u8 nfc_llcp_reserve_sdp_ssap(struct nfc_llcp_local *local)
{
u8 ssap;
mutex_lock(&local->sdp_lock);
ssap = find_first_zero_bit(&local->local_sdp, LLCP_SDP_NUM_SAP);
if (ssap == LLCP_SDP_NUM_SAP) {
mutex_unlock(&local->sdp_lock);
return LLCP_SAP_MAX;
}
pr_debug("SDP ssap %d\n", LLCP_WKS_NUM_SAP + ssap);
set_bit(ssap, &local->local_sdp);
mutex_unlock(&local->sdp_lock);
return LLCP_WKS_NUM_SAP + ssap;
}
static int nfc_llcp_build_gb(struct nfc_llcp_local *local)
{
u8 *gb_cur, *version_tlv, version, version_length;
u8 *lto_tlv, lto_length;
u8 *wks_tlv, wks_length;
u8 *miux_tlv, miux_length;
__be16 wks = cpu_to_be16(local->local_wks);
u8 gb_len = 0;
int ret = 0;
version = LLCP_VERSION_11;
version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version,
1, &version_length);
gb_len += version_length;
lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, <o_length);
gb_len += lto_length;
pr_debug("Local wks 0x%lx\n", local->local_wks);
wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length);
gb_len += wks_length;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0,
&miux_length);
gb_len += miux_length;
gb_len += ARRAY_SIZE(llcp_magic);
if (gb_len > NFC_MAX_GT_LEN) {
ret = -EINVAL;
goto out;
}
gb_cur = local->gb;
memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic));
gb_cur += ARRAY_SIZE(llcp_magic);
memcpy(gb_cur, version_tlv, version_length);
gb_cur += version_length;
memcpy(gb_cur, lto_tlv, lto_length);
gb_cur += lto_length;
memcpy(gb_cur, wks_tlv, wks_length);
gb_cur += wks_length;
memcpy(gb_cur, miux_tlv, miux_length);
gb_cur += miux_length;
local->gb_len = gb_len;
out:
kfree(version_tlv);
kfree(lto_tlv);
kfree(wks_tlv);
kfree(miux_tlv);
return ret;
}
u8 *nfc_llcp_general_bytes(struct nfc_dev *dev, size_t *general_bytes_len)
{
struct nfc_llcp_local *local;
local = nfc_llcp_find_local(dev);
if (local == NULL) {
*general_bytes_len = 0;
return NULL;
}
nfc_llcp_build_gb(local);
*general_bytes_len = local->gb_len;
return local->gb;
}
int nfc_llcp_set_remote_gb(struct nfc_dev *dev, u8 *gb, u8 gb_len)
{
struct nfc_llcp_local *local;
if (gb_len < 3 || gb_len > NFC_MAX_GT_LEN)
return -EINVAL;
local = nfc_llcp_find_local(dev);
if (local == NULL) {
pr_err("No LLCP device\n");
return -ENODEV;
}
memset(local->remote_gb, 0, NFC_MAX_GT_LEN);
memcpy(local->remote_gb, gb, gb_len);
local->remote_gb_len = gb_len;
if (memcmp(local->remote_gb, llcp_magic, 3)) {
pr_err("MAC does not support LLCP\n");
return -EINVAL;
}
return nfc_llcp_parse_gb_tlv(local,
&local->remote_gb[3],
local->remote_gb_len - 3);
}
static u8 nfc_llcp_dsap(struct sk_buff *pdu)
{
return (pdu->data[0] & 0xfc) >> 2;
}
static u8 nfc_llcp_ptype(struct sk_buff *pdu)
{
return ((pdu->data[0] & 0x03) << 2) | ((pdu->data[1] & 0xc0) >> 6);
}
static u8 nfc_llcp_ssap(struct sk_buff *pdu)
{
return pdu->data[1] & 0x3f;
}
static u8 nfc_llcp_ns(struct sk_buff *pdu)
{
return pdu->data[2] >> 4;
}
static u8 nfc_llcp_nr(struct sk_buff *pdu)
{
return pdu->data[2] & 0xf;
}
static void nfc_llcp_set_nrns(struct nfc_llcp_sock *sock, struct sk_buff *pdu)
{
pdu->data[2] = (sock->send_n << 4) | (sock->recv_n);
sock->send_n = (sock->send_n + 1) % 16;
sock->recv_ack_n = (sock->recv_n - 1) % 16;
}
void nfc_llcp_send_to_raw_sock(struct nfc_llcp_local *local,
struct sk_buff *skb, u8 direction)
{
struct sk_buff *skb_copy = NULL, *nskb;
struct sock *sk;
u8 *data;
read_lock(&local->raw_sockets.lock);
sk_for_each(sk, &local->raw_sockets.head) {
if (sk->sk_state != LLCP_BOUND)
continue;
if (skb_copy == NULL) {
skb_copy = __pskb_copy_fclone(skb, NFC_RAW_HEADER_SIZE,
GFP_ATOMIC, true);
if (skb_copy == NULL)
continue;
data = skb_push(skb_copy, NFC_RAW_HEADER_SIZE);
data[0] = local->dev ? local->dev->idx : 0xFF;
data[1] = direction & 0x01;
data[1] |= (RAW_PAYLOAD_LLCP << 1);
}
nskb = skb_clone(skb_copy, GFP_ATOMIC);
if (!nskb)
continue;
if (sock_queue_rcv_skb(sk, nskb))
kfree_skb(nskb);
}
read_unlock(&local->raw_sockets.lock);
kfree_skb(skb_copy);
}
static void nfc_llcp_tx_work(struct work_struct *work)
{
struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local,
tx_work);
struct sk_buff *skb;
struct sock *sk;
struct nfc_llcp_sock *llcp_sock;
skb = skb_dequeue(&local->tx_queue);
if (skb != NULL) {
sk = skb->sk;
llcp_sock = nfc_llcp_sock(sk);
if (llcp_sock == NULL && nfc_llcp_ptype(skb) == LLCP_PDU_I) {
kfree_skb(skb);
nfc_llcp_send_symm(local->dev);
} else if (llcp_sock && !llcp_sock->remote_ready) {
skb_queue_head(&local->tx_queue, skb);
nfc_llcp_send_symm(local->dev);
} else {
struct sk_buff *copy_skb = NULL;
u8 ptype = nfc_llcp_ptype(skb);
int ret;
pr_debug("Sending pending skb\n");
print_hex_dump_debug("LLCP Tx: ", DUMP_PREFIX_OFFSET,
16, 1, skb->data, skb->len, true);
if (ptype == LLCP_PDU_DISC && sk != NULL &&
sk->sk_state == LLCP_DISCONNECTING) {
nfc_llcp_sock_unlink(&local->sockets, sk);
sock_orphan(sk);
sock_put(sk);
}
if (ptype == LLCP_PDU_I)
copy_skb = skb_copy(skb, GFP_ATOMIC);
__net_timestamp(skb);
nfc_llcp_send_to_raw_sock(local, skb,
NFC_DIRECTION_TX);
ret = nfc_data_exchange(local->dev, local->target_idx,
skb, nfc_llcp_recv, local);
if (ret) {
kfree_skb(copy_skb);
goto out;
}
if (ptype == LLCP_PDU_I && copy_skb)
skb_queue_tail(&llcp_sock->tx_pending_queue,
copy_skb);
}
} else {
nfc_llcp_send_symm(local->dev);
}
out:
mod_timer(&local->link_timer,
jiffies + msecs_to_jiffies(2 * local->remote_lto));
}
static struct nfc_llcp_sock *nfc_llcp_connecting_sock_get(struct nfc_llcp_local *local,
u8 ssap)
{
struct sock *sk;
struct nfc_llcp_sock *llcp_sock;
read_lock(&local->connecting_sockets.lock);
sk_for_each(sk, &local->connecting_sockets.head) {
llcp_sock = nfc_llcp_sock(sk);
if (llcp_sock->ssap == ssap) {
sock_hold(&llcp_sock->sk);
goto out;
}
}
llcp_sock = NULL;
out:
read_unlock(&local->connecting_sockets.lock);
return llcp_sock;
}
static struct nfc_llcp_sock *nfc_llcp_sock_get_sn(struct nfc_llcp_local *local,
u8 *sn, size_t sn_len)
{
struct nfc_llcp_sock *llcp_sock;
llcp_sock = nfc_llcp_sock_from_sn(local, sn, sn_len);
if (llcp_sock == NULL)
return NULL;
sock_hold(&llcp_sock->sk);
return llcp_sock;
}
static u8 *nfc_llcp_connect_sn(struct sk_buff *skb, size_t *sn_len)
{
u8 *tlv = &skb->data[2], type, length;
size_t tlv_array_len = skb->len - LLCP_HEADER_SIZE, offset = 0;
while (offset < tlv_array_len) {
type = tlv[0];
length = tlv[1];
pr_debug("type 0x%x length %d\n", type, length);
if (type == LLCP_TLV_SN) {
*sn_len = length;
return &tlv[2];
}
offset += length + 2;
tlv += length + 2;
}
return NULL;
}
static void nfc_llcp_recv_ui(struct nfc_llcp_local *local,
struct sk_buff *skb)
{
struct nfc_llcp_sock *llcp_sock;
struct nfc_llcp_ui_cb *ui_cb;
u8 dsap, ssap;
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
ui_cb = nfc_llcp_ui_skb_cb(skb);
ui_cb->dsap = dsap;
ui_cb->ssap = ssap;
pr_debug("%d %d\n", dsap, ssap);
/* We're looking for a bound socket, not a client one */
llcp_sock = nfc_llcp_sock_get(local, dsap, LLCP_SAP_SDP);
if (llcp_sock == NULL || llcp_sock->sk.sk_type != SOCK_DGRAM)
return;
/* There is no sequence with UI frames */
skb_pull(skb, LLCP_HEADER_SIZE);
if (!sock_queue_rcv_skb(&llcp_sock->sk, skb)) {
/*
* UI frames will be freed from the socket layer, so we
* need to keep them alive until someone receives them.
*/
skb_get(skb);
} else {
pr_err("Receive queue is full\n");
}
nfc_llcp_sock_put(llcp_sock);
}
static void nfc_llcp_recv_connect(struct nfc_llcp_local *local,
struct sk_buff *skb)
{
struct sock *new_sk, *parent;
struct nfc_llcp_sock *sock, *new_sock;
u8 dsap, ssap, reason;
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
pr_debug("%d %d\n", dsap, ssap);
if (dsap != LLCP_SAP_SDP) {
sock = nfc_llcp_sock_get(local, dsap, LLCP_SAP_SDP);
if (sock == NULL || sock->sk.sk_state != LLCP_LISTEN) {
reason = LLCP_DM_NOBOUND;
goto fail;
}
} else {
u8 *sn;
size_t sn_len;
sn = nfc_llcp_connect_sn(skb, &sn_len);
if (sn == NULL) {
reason = LLCP_DM_NOBOUND;
goto fail;
}
pr_debug("Service name length %zu\n", sn_len);
sock = nfc_llcp_sock_get_sn(local, sn, sn_len);
if (sock == NULL) {
reason = LLCP_DM_NOBOUND;
goto fail;
}
}
lock_sock(&sock->sk);
parent = &sock->sk;
if (sk_acceptq_is_full(parent)) {
reason = LLCP_DM_REJ;
release_sock(&sock->sk);
sock_put(&sock->sk);
goto fail;
}
if (sock->ssap == LLCP_SDP_UNBOUND) {
u8 ssap = nfc_llcp_reserve_sdp_ssap(local);
pr_debug("First client, reserving %d\n", ssap);
if (ssap == LLCP_SAP_MAX) {
reason = LLCP_DM_REJ;
release_sock(&sock->sk);
sock_put(&sock->sk);
goto fail;
}
sock->ssap = ssap;
}
new_sk = nfc_llcp_sock_alloc(NULL, parent->sk_type, GFP_ATOMIC, 0);
if (new_sk == NULL) {
reason = LLCP_DM_REJ;
release_sock(&sock->sk);
sock_put(&sock->sk);
goto fail;
}
new_sock = nfc_llcp_sock(new_sk);
new_sock->dev = local->dev;
new_sock->local = nfc_llcp_local_get(local);
new_sock->rw = sock->rw;
new_sock->miux = sock->miux;
new_sock->nfc_protocol = sock->nfc_protocol;
new_sock->dsap = ssap;
new_sock->target_idx = local->target_idx;
new_sock->parent = parent;
new_sock->ssap = sock->ssap;
if (sock->ssap < LLCP_LOCAL_NUM_SAP && sock->ssap >= LLCP_WKS_NUM_SAP) {
atomic_t *client_count;
pr_debug("reserved_ssap %d for %p\n", sock->ssap, new_sock);
client_count =
&local->local_sdp_cnt[sock->ssap - LLCP_WKS_NUM_SAP];
atomic_inc(client_count);
new_sock->reserved_ssap = sock->ssap;
}
nfc_llcp_parse_connection_tlv(new_sock, &skb->data[LLCP_HEADER_SIZE],
skb->len - LLCP_HEADER_SIZE);
pr_debug("new sock %p sk %p\n", new_sock, &new_sock->sk);
nfc_llcp_sock_link(&local->sockets, new_sk);
nfc_llcp_accept_enqueue(&sock->sk, new_sk);
nfc_get_device(local->dev->idx);
new_sk->sk_state = LLCP_CONNECTED;
/* Wake the listening processes */
parent->sk_data_ready(parent);
/* Send CC */
nfc_llcp_send_cc(new_sock);
release_sock(&sock->sk);
sock_put(&sock->sk);
return;
fail:
/* Send DM */
nfc_llcp_send_dm(local, dsap, ssap, reason);
}
int nfc_llcp_queue_i_frames(struct nfc_llcp_sock *sock)
{
int nr_frames = 0;
struct nfc_llcp_local *local = sock->local;
pr_debug("Remote ready %d tx queue len %d remote rw %d",
sock->remote_ready, skb_queue_len(&sock->tx_pending_queue),
sock->remote_rw);
/* Try to queue some I frames for transmission */
while (sock->remote_ready &&
skb_queue_len(&sock->tx_pending_queue) < sock->remote_rw) {
struct sk_buff *pdu;
pdu = skb_dequeue(&sock->tx_queue);
if (pdu == NULL)
break;
/* Update N(S)/N(R) */
nfc_llcp_set_nrns(sock, pdu);
skb_queue_tail(&local->tx_queue, pdu);
nr_frames++;
}
return nr_frames;
}
static void nfc_llcp_recv_hdlc(struct nfc_llcp_local *local,
struct sk_buff *skb)
{
struct nfc_llcp_sock *llcp_sock;
struct sock *sk;
u8 dsap, ssap, ptype, ns, nr;
ptype = nfc_llcp_ptype(skb);
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
ns = nfc_llcp_ns(skb);
nr = nfc_llcp_nr(skb);
pr_debug("%d %d R %d S %d\n", dsap, ssap, nr, ns);
llcp_sock = nfc_llcp_sock_get(local, dsap, ssap);
if (llcp_sock == NULL) {
nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN);
return;
}
sk = &llcp_sock->sk;
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED) {
release_sock(sk);
nfc_llcp_sock_put(llcp_sock);
}
/* Pass the payload upstream */
if (ptype == LLCP_PDU_I) {
pr_debug("I frame, queueing on %p\n", &llcp_sock->sk);
if (ns == llcp_sock->recv_n)
llcp_sock->recv_n = (llcp_sock->recv_n + 1) % 16;
else
pr_err("Received out of sequence I PDU\n");
skb_pull(skb, LLCP_HEADER_SIZE + LLCP_SEQUENCE_SIZE);
if (!sock_queue_rcv_skb(&llcp_sock->sk, skb)) {
/*
* I frames will be freed from the socket layer, so we
* need to keep them alive until someone receives them.
*/
skb_get(skb);
} else {
pr_err("Receive queue is full\n");
}
}
/* Remove skbs from the pending queue */
if (llcp_sock->send_ack_n != nr) {
struct sk_buff *s, *tmp;
u8 n;
llcp_sock->send_ack_n = nr;
/* Remove and free all skbs until ns == nr */
skb_queue_walk_safe(&llcp_sock->tx_pending_queue, s, tmp) {
n = nfc_llcp_ns(s);
skb_unlink(s, &llcp_sock->tx_pending_queue);
kfree_skb(s);
if (n == nr)
break;
}
/* Re-queue the remaining skbs for transmission */
skb_queue_reverse_walk_safe(&llcp_sock->tx_pending_queue,
s, tmp) {
skb_unlink(s, &llcp_sock->tx_pending_queue);
skb_queue_head(&local->tx_queue, s);
}
}
if (ptype == LLCP_PDU_RR)
llcp_sock->remote_ready = true;
else if (ptype == LLCP_PDU_RNR)
llcp_sock->remote_ready = false;
if (nfc_llcp_queue_i_frames(llcp_sock) == 0 && ptype == LLCP_PDU_I)
nfc_llcp_send_rr(llcp_sock);
release_sock(sk);
nfc_llcp_sock_put(llcp_sock);
}
static void nfc_llcp_recv_disc(struct nfc_llcp_local *local,
struct sk_buff *skb)
{
struct nfc_llcp_sock *llcp_sock;
struct sock *sk;
u8 dsap, ssap;
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
if ((dsap == 0) && (ssap == 0)) {
pr_debug("Connection termination");
nfc_dep_link_down(local->dev);
return;
}
llcp_sock = nfc_llcp_sock_get(local, dsap, ssap);
if (llcp_sock == NULL) {
nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN);
return;
}
sk = &llcp_sock->sk;
lock_sock(sk);
nfc_llcp_socket_purge(llcp_sock);
if (sk->sk_state == LLCP_CLOSED) {
release_sock(sk);
nfc_llcp_sock_put(llcp_sock);
}
if (sk->sk_state == LLCP_CONNECTED) {
nfc_put_device(local->dev);
sk->sk_state = LLCP_CLOSED;
sk->sk_state_change(sk);
}
nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_DISC);
release_sock(sk);
nfc_llcp_sock_put(llcp_sock);
}
static void nfc_llcp_recv_cc(struct nfc_llcp_local *local, struct sk_buff *skb)
{
struct nfc_llcp_sock *llcp_sock;
struct sock *sk;
u8 dsap, ssap;
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
llcp_sock = nfc_llcp_connecting_sock_get(local, dsap);
if (llcp_sock == NULL) {
pr_err("Invalid CC\n");
nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN);
return;
}
sk = &llcp_sock->sk;
/* Unlink from connecting and link to the client array */
nfc_llcp_sock_unlink(&local->connecting_sockets, sk);
nfc_llcp_sock_link(&local->sockets, sk);
llcp_sock->dsap = ssap;
nfc_llcp_parse_connection_tlv(llcp_sock, &skb->data[LLCP_HEADER_SIZE],
skb->len - LLCP_HEADER_SIZE);
sk->sk_state = LLCP_CONNECTED;
sk->sk_state_change(sk);
nfc_llcp_sock_put(llcp_sock);
}
static void nfc_llcp_recv_dm(struct nfc_llcp_local *local, struct sk_buff *skb)
{
struct nfc_llcp_sock *llcp_sock;
struct sock *sk;
u8 dsap, ssap, reason;
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
reason = skb->data[2];
pr_debug("%d %d reason %d\n", ssap, dsap, reason);
switch (reason) {
case LLCP_DM_NOBOUND:
case LLCP_DM_REJ:
llcp_sock = nfc_llcp_connecting_sock_get(local, dsap);
break;
default:
llcp_sock = nfc_llcp_sock_get(local, dsap, ssap);
break;
}
if (llcp_sock == NULL) {
pr_debug("Already closed\n");
return;
}
sk = &llcp_sock->sk;
sk->sk_err = ENXIO;
sk->sk_state = LLCP_CLOSED;
sk->sk_state_change(sk);
nfc_llcp_sock_put(llcp_sock);
}
static void nfc_llcp_recv_snl(struct nfc_llcp_local *local,
struct sk_buff *skb)
{
struct nfc_llcp_sock *llcp_sock;
u8 dsap, ssap, *tlv, type, length, tid, sap;
u16 tlv_len, offset;
char *service_name;
size_t service_name_len;
struct nfc_llcp_sdp_tlv *sdp;
HLIST_HEAD(llc_sdres_list);
size_t sdres_tlvs_len;
HLIST_HEAD(nl_sdres_list);
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
pr_debug("%d %d\n", dsap, ssap);
if (dsap != LLCP_SAP_SDP || ssap != LLCP_SAP_SDP) {
pr_err("Wrong SNL SAP\n");
return;
}
tlv = &skb->data[LLCP_HEADER_SIZE];
tlv_len = skb->len - LLCP_HEADER_SIZE;
offset = 0;
sdres_tlvs_len = 0;
while (offset < tlv_len) {
type = tlv[0];
length = tlv[1];
switch (type) {
case LLCP_TLV_SDREQ:
tid = tlv[2];
service_name = (char *) &tlv[3];
service_name_len = length - 1;
pr_debug("Looking for %.16s\n", service_name);
if (service_name_len == strlen("urn:nfc:sn:sdp") &&
!strncmp(service_name, "urn:nfc:sn:sdp",
service_name_len)) {
sap = 1;
goto add_snl;
}
llcp_sock = nfc_llcp_sock_from_sn(local, service_name,
service_name_len);
if (!llcp_sock) {
sap = 0;
goto add_snl;
}
/*
* We found a socket but its ssap has not been reserved
* yet. We need to assign it for good and send a reply.
* The ssap will be freed when the socket is closed.
*/
if (llcp_sock->ssap == LLCP_SDP_UNBOUND) {
atomic_t *client_count;
sap = nfc_llcp_reserve_sdp_ssap(local);
pr_debug("Reserving %d\n", sap);
if (sap == LLCP_SAP_MAX) {
sap = 0;
goto add_snl;
}
client_count =
&local->local_sdp_cnt[sap -
LLCP_WKS_NUM_SAP];
atomic_inc(client_count);
llcp_sock->ssap = sap;
llcp_sock->reserved_ssap = sap;
} else {
sap = llcp_sock->ssap;
}
pr_debug("%p %d\n", llcp_sock, sap);
add_snl:
sdp = nfc_llcp_build_sdres_tlv(tid, sap);
if (sdp == NULL)
goto exit;
sdres_tlvs_len += sdp->tlv_len;
hlist_add_head(&sdp->node, &llc_sdres_list);
break;
case LLCP_TLV_SDRES:
mutex_lock(&local->sdreq_lock);
pr_debug("LLCP_TLV_SDRES: searching tid %d\n", tlv[2]);
hlist_for_each_entry(sdp, &local->pending_sdreqs, node) {
if (sdp->tid != tlv[2])
continue;
sdp->sap = tlv[3];
pr_debug("Found: uri=%s, sap=%d\n",
sdp->uri, sdp->sap);
hlist_del(&sdp->node);
hlist_add_head(&sdp->node, &nl_sdres_list);
break;
}
mutex_unlock(&local->sdreq_lock);
break;
default:
pr_err("Invalid SNL tlv value 0x%x\n", type);
break;
}
offset += length + 2;
tlv += length + 2;
}
exit:
if (!hlist_empty(&nl_sdres_list))
nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list);
if (!hlist_empty(&llc_sdres_list))
nfc_llcp_send_snl_sdres(local, &llc_sdres_list, sdres_tlvs_len);
}
static void nfc_llcp_recv_agf(struct nfc_llcp_local *local, struct sk_buff *skb)
{
u8 ptype;
u16 pdu_len;
struct sk_buff *new_skb;
if (skb->len <= LLCP_HEADER_SIZE) {
pr_err("Malformed AGF PDU\n");
return;
}
skb_pull(skb, LLCP_HEADER_SIZE);
while (skb->len > LLCP_AGF_PDU_HEADER_SIZE) {
pdu_len = skb->data[0] << 8 | skb->data[1];
skb_pull(skb, LLCP_AGF_PDU_HEADER_SIZE);
if (pdu_len < LLCP_HEADER_SIZE || pdu_len > skb->len) {
pr_err("Malformed AGF PDU\n");
return;
}
ptype = nfc_llcp_ptype(skb);
if (ptype == LLCP_PDU_SYMM || ptype == LLCP_PDU_AGF)
goto next;
new_skb = nfc_alloc_recv_skb(pdu_len, GFP_KERNEL);
if (new_skb == NULL) {
pr_err("Could not allocate PDU\n");
return;
}
skb_put_data(new_skb, skb->data, pdu_len);
nfc_llcp_rx_skb(local, new_skb);
kfree_skb(new_skb);
next:
skb_pull(skb, pdu_len);
}
}
static void nfc_llcp_rx_skb(struct nfc_llcp_local *local, struct sk_buff *skb)
{
u8 dsap, ssap, ptype;
ptype = nfc_llcp_ptype(skb);
dsap = nfc_llcp_dsap(skb);
ssap = nfc_llcp_ssap(skb);
pr_debug("ptype 0x%x dsap 0x%x ssap 0x%x\n", ptype, dsap, ssap);
if (ptype != LLCP_PDU_SYMM)
print_hex_dump_debug("LLCP Rx: ", DUMP_PREFIX_OFFSET, 16, 1,
skb->data, skb->len, true);
switch (ptype) {
case LLCP_PDU_SYMM:
pr_debug("SYMM\n");
break;
case LLCP_PDU_UI:
pr_debug("UI\n");
nfc_llcp_recv_ui(local, skb);
break;
case LLCP_PDU_CONNECT:
pr_debug("CONNECT\n");
nfc_llcp_recv_connect(local, skb);
break;
case LLCP_PDU_DISC:
pr_debug("DISC\n");
nfc_llcp_recv_disc(local, skb);
break;
case LLCP_PDU_CC:
pr_debug("CC\n");
nfc_llcp_recv_cc(local, skb);
break;
case LLCP_PDU_DM:
pr_debug("DM\n");
nfc_llcp_recv_dm(local, skb);
break;
case LLCP_PDU_SNL:
pr_debug("SNL\n");
nfc_llcp_recv_snl(local, skb);
break;
case LLCP_PDU_I:
case LLCP_PDU_RR:
case LLCP_PDU_RNR:
pr_debug("I frame\n");
nfc_llcp_recv_hdlc(local, skb);
break;
case LLCP_PDU_AGF:
pr_debug("AGF frame\n");
nfc_llcp_recv_agf(local, skb);
break;
}
}
static void nfc_llcp_rx_work(struct work_struct *work)
{
struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local,
rx_work);
struct sk_buff *skb;
skb = local->rx_pending;
if (skb == NULL) {
pr_debug("No pending SKB\n");
return;
}
__net_timestamp(skb);
nfc_llcp_send_to_raw_sock(local, skb, NFC_DIRECTION_RX);
nfc_llcp_rx_skb(local, skb);
schedule_work(&local->tx_work);
kfree_skb(local->rx_pending);
local->rx_pending = NULL;
}
static void __nfc_llcp_recv(struct nfc_llcp_local *local, struct sk_buff *skb)
{
local->rx_pending = skb;
del_timer(&local->link_timer);
schedule_work(&local->rx_work);
}
void nfc_llcp_recv(void *data, struct sk_buff *skb, int err)
{
struct nfc_llcp_local *local = (struct nfc_llcp_local *) data;
pr_debug("Received an LLCP PDU\n");
if (err < 0) {
pr_err("err %d\n", err);
return;
}
__nfc_llcp_recv(local, skb);
}
int nfc_llcp_data_received(struct nfc_dev *dev, struct sk_buff *skb)
{
struct nfc_llcp_local *local;
local = nfc_llcp_find_local(dev);
if (local == NULL) {
kfree_skb(skb);
return -ENODEV;
}
__nfc_llcp_recv(local, skb);
return 0;
}
void nfc_llcp_mac_is_down(struct nfc_dev *dev)
{
struct nfc_llcp_local *local;
local = nfc_llcp_find_local(dev);
if (local == NULL)
return;
local->remote_miu = LLCP_DEFAULT_MIU;
local->remote_lto = LLCP_DEFAULT_LTO;
/* Close and purge all existing sockets */
nfc_llcp_socket_release(local, true, 0);
}
void nfc_llcp_mac_is_up(struct nfc_dev *dev, u32 target_idx,
u8 comm_mode, u8 rf_mode)
{
struct nfc_llcp_local *local;
pr_debug("rf mode %d\n", rf_mode);
local = nfc_llcp_find_local(dev);
if (local == NULL)
return;
local->target_idx = target_idx;
local->comm_mode = comm_mode;
local->rf_mode = rf_mode;
if (rf_mode == NFC_RF_INITIATOR) {
pr_debug("Queueing Tx work\n");
schedule_work(&local->tx_work);
} else {
mod_timer(&local->link_timer,
jiffies + msecs_to_jiffies(local->remote_lto));
}
}
int nfc_llcp_register_device(struct nfc_dev *ndev)
{
struct nfc_llcp_local *local;
local = kzalloc(sizeof(struct nfc_llcp_local), GFP_KERNEL);
if (local == NULL)
return -ENOMEM;
local->dev = ndev;
INIT_LIST_HEAD(&local->list);
kref_init(&local->ref);
mutex_init(&local->sdp_lock);
timer_setup(&local->link_timer, nfc_llcp_symm_timer, 0);
skb_queue_head_init(&local->tx_queue);
INIT_WORK(&local->tx_work, nfc_llcp_tx_work);
local->rx_pending = NULL;
INIT_WORK(&local->rx_work, nfc_llcp_rx_work);
INIT_WORK(&local->timeout_work, nfc_llcp_timeout_work);
rwlock_init(&local->sockets.lock);
rwlock_init(&local->connecting_sockets.lock);
rwlock_init(&local->raw_sockets.lock);
local->lto = 150; /* 1500 ms */
local->rw = LLCP_MAX_RW;
local->miux = cpu_to_be16(LLCP_MAX_MIUX);
local->local_wks = 0x1; /* LLC Link Management */
nfc_llcp_build_gb(local);
local->remote_miu = LLCP_DEFAULT_MIU;
local->remote_lto = LLCP_DEFAULT_LTO;
mutex_init(&local->sdreq_lock);
INIT_HLIST_HEAD(&local->pending_sdreqs);
timer_setup(&local->sdreq_timer, nfc_llcp_sdreq_timer, 0);
INIT_WORK(&local->sdreq_timeout_work, nfc_llcp_sdreq_timeout_work);
list_add(&local->list, &llcp_devices);
return 0;
}
void nfc_llcp_unregister_device(struct nfc_dev *dev)
{
struct nfc_llcp_local *local = nfc_llcp_find_local(dev);
if (local == NULL) {
pr_debug("No such device\n");
return;
}
local_cleanup(local);
nfc_llcp_local_put(local);
}
int __init nfc_llcp_init(void)
{
return nfc_llcp_sock_init();
}
void nfc_llcp_exit(void)
{
nfc_llcp_sock_exit();
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_887_1 |
crossvul-cpp_data_good_212_0 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_sb.h"
#include "xfs_mount.h"
#include "xfs_inode.h"
#include "xfs_error.h"
#include "xfs_trans.h"
#include "xfs_trans_priv.h"
#include "xfs_inode_item.h"
#include "xfs_quota.h"
#include "xfs_trace.h"
#include "xfs_icache.h"
#include "xfs_bmap_util.h"
#include "xfs_dquot_item.h"
#include "xfs_dquot.h"
#include "xfs_reflink.h"
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/iversion.h>
/*
* Allocate and initialise an xfs_inode.
*/
struct xfs_inode *
xfs_inode_alloc(
struct xfs_mount *mp,
xfs_ino_t ino)
{
struct xfs_inode *ip;
/*
* if this didn't occur in transactions, we could use
* KM_MAYFAIL and return NULL here on ENOMEM. Set the
* code up to do this anyway.
*/
ip = kmem_zone_alloc(xfs_inode_zone, KM_SLEEP);
if (!ip)
return NULL;
if (inode_init_always(mp->m_super, VFS_I(ip))) {
kmem_zone_free(xfs_inode_zone, ip);
return NULL;
}
/* VFS doesn't initialise i_mode! */
VFS_I(ip)->i_mode = 0;
XFS_STATS_INC(mp, vn_active);
ASSERT(atomic_read(&ip->i_pincount) == 0);
ASSERT(!xfs_isiflocked(ip));
ASSERT(ip->i_ino == 0);
/* initialise the xfs inode */
ip->i_ino = ino;
ip->i_mount = mp;
memset(&ip->i_imap, 0, sizeof(struct xfs_imap));
ip->i_afp = NULL;
ip->i_cowfp = NULL;
ip->i_cnextents = 0;
ip->i_cformat = XFS_DINODE_FMT_EXTENTS;
memset(&ip->i_df, 0, sizeof(xfs_ifork_t));
ip->i_flags = 0;
ip->i_delayed_blks = 0;
memset(&ip->i_d, 0, sizeof(ip->i_d));
return ip;
}
STATIC void
xfs_inode_free_callback(
struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
struct xfs_inode *ip = XFS_I(inode);
switch (VFS_I(ip)->i_mode & S_IFMT) {
case S_IFREG:
case S_IFDIR:
case S_IFLNK:
xfs_idestroy_fork(ip, XFS_DATA_FORK);
break;
}
if (ip->i_afp)
xfs_idestroy_fork(ip, XFS_ATTR_FORK);
if (ip->i_cowfp)
xfs_idestroy_fork(ip, XFS_COW_FORK);
if (ip->i_itemp) {
ASSERT(!(ip->i_itemp->ili_item.li_flags & XFS_LI_IN_AIL));
xfs_inode_item_destroy(ip);
ip->i_itemp = NULL;
}
kmem_zone_free(xfs_inode_zone, ip);
}
static void
__xfs_inode_free(
struct xfs_inode *ip)
{
/* asserts to verify all state is correct here */
ASSERT(atomic_read(&ip->i_pincount) == 0);
XFS_STATS_DEC(ip->i_mount, vn_active);
call_rcu(&VFS_I(ip)->i_rcu, xfs_inode_free_callback);
}
void
xfs_inode_free(
struct xfs_inode *ip)
{
ASSERT(!xfs_isiflocked(ip));
/*
* Because we use RCU freeing we need to ensure the inode always
* appears to be reclaimed with an invalid inode number when in the
* free state. The ip->i_flags_lock provides the barrier against lookup
* races.
*/
spin_lock(&ip->i_flags_lock);
ip->i_flags = XFS_IRECLAIM;
ip->i_ino = 0;
spin_unlock(&ip->i_flags_lock);
__xfs_inode_free(ip);
}
/*
* Queue a new inode reclaim pass if there are reclaimable inodes and there
* isn't a reclaim pass already in progress. By default it runs every 5s based
* on the xfs periodic sync default of 30s. Perhaps this should have it's own
* tunable, but that can be done if this method proves to be ineffective or too
* aggressive.
*/
static void
xfs_reclaim_work_queue(
struct xfs_mount *mp)
{
rcu_read_lock();
if (radix_tree_tagged(&mp->m_perag_tree, XFS_ICI_RECLAIM_TAG)) {
queue_delayed_work(mp->m_reclaim_workqueue, &mp->m_reclaim_work,
msecs_to_jiffies(xfs_syncd_centisecs / 6 * 10));
}
rcu_read_unlock();
}
/*
* This is a fast pass over the inode cache to try to get reclaim moving on as
* many inodes as possible in a short period of time. It kicks itself every few
* seconds, as well as being kicked by the inode cache shrinker when memory
* goes low. It scans as quickly as possible avoiding locked inodes or those
* already being flushed, and once done schedules a future pass.
*/
void
xfs_reclaim_worker(
struct work_struct *work)
{
struct xfs_mount *mp = container_of(to_delayed_work(work),
struct xfs_mount, m_reclaim_work);
xfs_reclaim_inodes(mp, SYNC_TRYLOCK);
xfs_reclaim_work_queue(mp);
}
static void
xfs_perag_set_reclaim_tag(
struct xfs_perag *pag)
{
struct xfs_mount *mp = pag->pag_mount;
lockdep_assert_held(&pag->pag_ici_lock);
if (pag->pag_ici_reclaimable++)
return;
/* propagate the reclaim tag up into the perag radix tree */
spin_lock(&mp->m_perag_lock);
radix_tree_tag_set(&mp->m_perag_tree, pag->pag_agno,
XFS_ICI_RECLAIM_TAG);
spin_unlock(&mp->m_perag_lock);
/* schedule periodic background inode reclaim */
xfs_reclaim_work_queue(mp);
trace_xfs_perag_set_reclaim(mp, pag->pag_agno, -1, _RET_IP_);
}
static void
xfs_perag_clear_reclaim_tag(
struct xfs_perag *pag)
{
struct xfs_mount *mp = pag->pag_mount;
lockdep_assert_held(&pag->pag_ici_lock);
if (--pag->pag_ici_reclaimable)
return;
/* clear the reclaim tag from the perag radix tree */
spin_lock(&mp->m_perag_lock);
radix_tree_tag_clear(&mp->m_perag_tree, pag->pag_agno,
XFS_ICI_RECLAIM_TAG);
spin_unlock(&mp->m_perag_lock);
trace_xfs_perag_clear_reclaim(mp, pag->pag_agno, -1, _RET_IP_);
}
/*
* We set the inode flag atomically with the radix tree tag.
* Once we get tag lookups on the radix tree, this inode flag
* can go away.
*/
void
xfs_inode_set_reclaim_tag(
struct xfs_inode *ip)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_perag *pag;
pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
spin_lock(&pag->pag_ici_lock);
spin_lock(&ip->i_flags_lock);
radix_tree_tag_set(&pag->pag_ici_root, XFS_INO_TO_AGINO(mp, ip->i_ino),
XFS_ICI_RECLAIM_TAG);
xfs_perag_set_reclaim_tag(pag);
__xfs_iflags_set(ip, XFS_IRECLAIMABLE);
spin_unlock(&ip->i_flags_lock);
spin_unlock(&pag->pag_ici_lock);
xfs_perag_put(pag);
}
STATIC void
xfs_inode_clear_reclaim_tag(
struct xfs_perag *pag,
xfs_ino_t ino)
{
radix_tree_tag_clear(&pag->pag_ici_root,
XFS_INO_TO_AGINO(pag->pag_mount, ino),
XFS_ICI_RECLAIM_TAG);
xfs_perag_clear_reclaim_tag(pag);
}
static void
xfs_inew_wait(
struct xfs_inode *ip)
{
wait_queue_head_t *wq = bit_waitqueue(&ip->i_flags, __XFS_INEW_BIT);
DEFINE_WAIT_BIT(wait, &ip->i_flags, __XFS_INEW_BIT);
do {
prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
if (!xfs_iflags_test(ip, XFS_INEW))
break;
schedule();
} while (true);
finish_wait(wq, &wait.wq_entry);
}
/*
* When we recycle a reclaimable inode, we need to re-initialise the VFS inode
* part of the structure. This is made more complex by the fact we store
* information about the on-disk values in the VFS inode and so we can't just
* overwrite the values unconditionally. Hence we save the parameters we
* need to retain across reinitialisation, and rewrite them into the VFS inode
* after reinitialisation even if it fails.
*/
static int
xfs_reinit_inode(
struct xfs_mount *mp,
struct inode *inode)
{
int error;
uint32_t nlink = inode->i_nlink;
uint32_t generation = inode->i_generation;
uint64_t version = inode_peek_iversion(inode);
umode_t mode = inode->i_mode;
dev_t dev = inode->i_rdev;
error = inode_init_always(mp->m_super, inode);
set_nlink(inode, nlink);
inode->i_generation = generation;
inode_set_iversion_queried(inode, version);
inode->i_mode = mode;
inode->i_rdev = dev;
return error;
}
/*
* If we are allocating a new inode, then check what was returned is
* actually a free, empty inode. If we are not allocating an inode,
* then check we didn't find a free inode.
*
* Returns:
* 0 if the inode free state matches the lookup context
* -ENOENT if the inode is free and we are not allocating
* -EFSCORRUPTED if there is any state mismatch at all
*/
static int
xfs_iget_check_free_state(
struct xfs_inode *ip,
int flags)
{
if (flags & XFS_IGET_CREATE) {
/* should be a free inode */
if (VFS_I(ip)->i_mode != 0) {
xfs_warn(ip->i_mount,
"Corruption detected! Free inode 0x%llx not marked free! (mode 0x%x)",
ip->i_ino, VFS_I(ip)->i_mode);
return -EFSCORRUPTED;
}
if (ip->i_d.di_nblocks != 0) {
xfs_warn(ip->i_mount,
"Corruption detected! Free inode 0x%llx has blocks allocated!",
ip->i_ino);
return -EFSCORRUPTED;
}
return 0;
}
/* should be an allocated inode */
if (VFS_I(ip)->i_mode == 0)
return -ENOENT;
return 0;
}
/*
* Check the validity of the inode we just found it the cache
*/
static int
xfs_iget_cache_hit(
struct xfs_perag *pag,
struct xfs_inode *ip,
xfs_ino_t ino,
int flags,
int lock_flags) __releases(RCU)
{
struct inode *inode = VFS_I(ip);
struct xfs_mount *mp = ip->i_mount;
int error;
/*
* check for re-use of an inode within an RCU grace period due to the
* radix tree nodes not being updated yet. We monitor for this by
* setting the inode number to zero before freeing the inode structure.
* If the inode has been reallocated and set up, then the inode number
* will not match, so check for that, too.
*/
spin_lock(&ip->i_flags_lock);
if (ip->i_ino != ino) {
trace_xfs_iget_skip(ip);
XFS_STATS_INC(mp, xs_ig_frecycle);
error = -EAGAIN;
goto out_error;
}
/*
* If we are racing with another cache hit that is currently
* instantiating this inode or currently recycling it out of
* reclaimabe state, wait for the initialisation to complete
* before continuing.
*
* XXX(hch): eventually we should do something equivalent to
* wait_on_inode to wait for these flags to be cleared
* instead of polling for it.
*/
if (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) {
trace_xfs_iget_skip(ip);
XFS_STATS_INC(mp, xs_ig_frecycle);
error = -EAGAIN;
goto out_error;
}
/*
* Check the inode free state is valid. This also detects lookup
* racing with unlinks.
*/
error = xfs_iget_check_free_state(ip, flags);
if (error)
goto out_error;
/*
* If IRECLAIMABLE is set, we've torn down the VFS inode already.
* Need to carefully get it back into useable state.
*/
if (ip->i_flags & XFS_IRECLAIMABLE) {
trace_xfs_iget_reclaim(ip);
if (flags & XFS_IGET_INCORE) {
error = -EAGAIN;
goto out_error;
}
/*
* We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode
* from stomping over us while we recycle the inode. We can't
* clear the radix tree reclaimable tag yet as it requires
* pag_ici_lock to be held exclusive.
*/
ip->i_flags |= XFS_IRECLAIM;
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
error = xfs_reinit_inode(mp, inode);
if (error) {
bool wake;
/*
* Re-initializing the inode failed, and we are in deep
* trouble. Try to re-add it to the reclaim list.
*/
rcu_read_lock();
spin_lock(&ip->i_flags_lock);
wake = !!__xfs_iflags_test(ip, XFS_INEW);
ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM);
if (wake)
wake_up_bit(&ip->i_flags, __XFS_INEW_BIT);
ASSERT(ip->i_flags & XFS_IRECLAIMABLE);
trace_xfs_iget_reclaim_fail(ip);
goto out_error;
}
spin_lock(&pag->pag_ici_lock);
spin_lock(&ip->i_flags_lock);
/*
* Clear the per-lifetime state in the inode as we are now
* effectively a new inode and need to return to the initial
* state before reuse occurs.
*/
ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS;
ip->i_flags |= XFS_INEW;
xfs_inode_clear_reclaim_tag(pag, ip->i_ino);
inode->i_state = I_NEW;
ASSERT(!rwsem_is_locked(&inode->i_rwsem));
init_rwsem(&inode->i_rwsem);
spin_unlock(&ip->i_flags_lock);
spin_unlock(&pag->pag_ici_lock);
} else {
/* If the VFS inode is being torn down, pause and try again. */
if (!igrab(inode)) {
trace_xfs_iget_skip(ip);
error = -EAGAIN;
goto out_error;
}
/* We've got a live one. */
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
trace_xfs_iget_hit(ip);
}
if (lock_flags != 0)
xfs_ilock(ip, lock_flags);
if (!(flags & XFS_IGET_INCORE))
xfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE);
XFS_STATS_INC(mp, xs_ig_found);
return 0;
out_error:
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
return error;
}
static int
xfs_iget_cache_miss(
struct xfs_mount *mp,
struct xfs_perag *pag,
xfs_trans_t *tp,
xfs_ino_t ino,
struct xfs_inode **ipp,
int flags,
int lock_flags)
{
struct xfs_inode *ip;
int error;
xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino);
int iflags;
ip = xfs_inode_alloc(mp, ino);
if (!ip)
return -ENOMEM;
error = xfs_iread(mp, tp, ip, flags);
if (error)
goto out_destroy;
if (!xfs_inode_verify_forks(ip)) {
error = -EFSCORRUPTED;
goto out_destroy;
}
trace_xfs_iget_miss(ip);
/*
* Check the inode free state is valid. This also detects lookup
* racing with unlinks.
*/
error = xfs_iget_check_free_state(ip, flags);
if (error)
goto out_destroy;
/*
* Preload the radix tree so we can insert safely under the
* write spinlock. Note that we cannot sleep inside the preload
* region. Since we can be called from transaction context, don't
* recurse into the file system.
*/
if (radix_tree_preload(GFP_NOFS)) {
error = -EAGAIN;
goto out_destroy;
}
/*
* Because the inode hasn't been added to the radix-tree yet it can't
* be found by another thread, so we can do the non-sleeping lock here.
*/
if (lock_flags) {
if (!xfs_ilock_nowait(ip, lock_flags))
BUG();
}
/*
* These values must be set before inserting the inode into the radix
* tree as the moment it is inserted a concurrent lookup (allowed by the
* RCU locking mechanism) can find it and that lookup must see that this
* is an inode currently under construction (i.e. that XFS_INEW is set).
* The ip->i_flags_lock that protects the XFS_INEW flag forms the
* memory barrier that ensures this detection works correctly at lookup
* time.
*/
iflags = XFS_INEW;
if (flags & XFS_IGET_DONTCACHE)
iflags |= XFS_IDONTCACHE;
ip->i_udquot = NULL;
ip->i_gdquot = NULL;
ip->i_pdquot = NULL;
xfs_iflags_set(ip, iflags);
/* insert the new inode */
spin_lock(&pag->pag_ici_lock);
error = radix_tree_insert(&pag->pag_ici_root, agino, ip);
if (unlikely(error)) {
WARN_ON(error != -EEXIST);
XFS_STATS_INC(mp, xs_ig_dup);
error = -EAGAIN;
goto out_preload_end;
}
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
*ipp = ip;
return 0;
out_preload_end:
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
if (lock_flags)
xfs_iunlock(ip, lock_flags);
out_destroy:
__destroy_inode(VFS_I(ip));
xfs_inode_free(ip);
return error;
}
/*
* Look up an inode by number in the given file system.
* The inode is looked up in the cache held in each AG.
* If the inode is found in the cache, initialise the vfs inode
* if necessary.
*
* If it is not in core, read it in from the file system's device,
* add it to the cache and initialise the vfs inode.
*
* The inode is locked according to the value of the lock_flags parameter.
* This flag parameter indicates how and if the inode's IO lock and inode lock
* should be taken.
*
* mp -- the mount point structure for the current file system. It points
* to the inode hash table.
* tp -- a pointer to the current transaction if there is one. This is
* simply passed through to the xfs_iread() call.
* ino -- the number of the inode desired. This is the unique identifier
* within the file system for the inode being requested.
* lock_flags -- flags indicating how to lock the inode. See the comment
* for xfs_ilock() for a list of valid values.
*/
int
xfs_iget(
xfs_mount_t *mp,
xfs_trans_t *tp,
xfs_ino_t ino,
uint flags,
uint lock_flags,
xfs_inode_t **ipp)
{
xfs_inode_t *ip;
int error;
xfs_perag_t *pag;
xfs_agino_t agino;
/*
* xfs_reclaim_inode() uses the ILOCK to ensure an inode
* doesn't get freed while it's being referenced during a
* radix tree traversal here. It assumes this function
* aqcuires only the ILOCK (and therefore it has no need to
* involve the IOLOCK in this synchronization).
*/
ASSERT((lock_flags & (XFS_IOLOCK_EXCL | XFS_IOLOCK_SHARED)) == 0);
/* reject inode numbers outside existing AGs */
if (!ino || XFS_INO_TO_AGNO(mp, ino) >= mp->m_sb.sb_agcount)
return -EINVAL;
XFS_STATS_INC(mp, xs_ig_attempts);
/* get the perag structure and ensure that it's inode capable */
pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ino));
agino = XFS_INO_TO_AGINO(mp, ino);
again:
error = 0;
rcu_read_lock();
ip = radix_tree_lookup(&pag->pag_ici_root, agino);
if (ip) {
error = xfs_iget_cache_hit(pag, ip, ino, flags, lock_flags);
if (error)
goto out_error_or_again;
} else {
rcu_read_unlock();
if (flags & XFS_IGET_INCORE) {
error = -ENODATA;
goto out_error_or_again;
}
XFS_STATS_INC(mp, xs_ig_missed);
error = xfs_iget_cache_miss(mp, pag, tp, ino, &ip,
flags, lock_flags);
if (error)
goto out_error_or_again;
}
xfs_perag_put(pag);
*ipp = ip;
/*
* If we have a real type for an on-disk inode, we can setup the inode
* now. If it's a new inode being created, xfs_ialloc will handle it.
*/
if (xfs_iflags_test(ip, XFS_INEW) && VFS_I(ip)->i_mode != 0)
xfs_setup_existing_inode(ip);
return 0;
out_error_or_again:
if (!(flags & XFS_IGET_INCORE) && error == -EAGAIN) {
delay(1);
goto again;
}
xfs_perag_put(pag);
return error;
}
/*
* "Is this a cached inode that's also allocated?"
*
* Look up an inode by number in the given file system. If the inode is
* in cache and isn't in purgatory, return 1 if the inode is allocated
* and 0 if it is not. For all other cases (not in cache, being torn
* down, etc.), return a negative error code.
*
* The caller has to prevent inode allocation and freeing activity,
* presumably by locking the AGI buffer. This is to ensure that an
* inode cannot transition from allocated to freed until the caller is
* ready to allow that. If the inode is in an intermediate state (new,
* reclaimable, or being reclaimed), -EAGAIN will be returned; if the
* inode is not in the cache, -ENOENT will be returned. The caller must
* deal with these scenarios appropriately.
*
* This is a specialized use case for the online scrubber; if you're
* reading this, you probably want xfs_iget.
*/
int
xfs_icache_inode_is_allocated(
struct xfs_mount *mp,
struct xfs_trans *tp,
xfs_ino_t ino,
bool *inuse)
{
struct xfs_inode *ip;
int error;
error = xfs_iget(mp, tp, ino, XFS_IGET_INCORE, 0, &ip);
if (error)
return error;
*inuse = !!(VFS_I(ip)->i_mode);
IRELE(ip);
return 0;
}
/*
* The inode lookup is done in batches to keep the amount of lock traffic and
* radix tree lookups to a minimum. The batch size is a trade off between
* lookup reduction and stack usage. This is in the reclaim path, so we can't
* be too greedy.
*/
#define XFS_LOOKUP_BATCH 32
STATIC int
xfs_inode_ag_walk_grab(
struct xfs_inode *ip,
int flags)
{
struct inode *inode = VFS_I(ip);
bool newinos = !!(flags & XFS_AGITER_INEW_WAIT);
ASSERT(rcu_read_lock_held());
/*
* check for stale RCU freed inode
*
* If the inode has been reallocated, it doesn't matter if it's not in
* the AG we are walking - we are walking for writeback, so if it
* passes all the "valid inode" checks and is dirty, then we'll write
* it back anyway. If it has been reallocated and still being
* initialised, the XFS_INEW check below will catch it.
*/
spin_lock(&ip->i_flags_lock);
if (!ip->i_ino)
goto out_unlock_noent;
/* avoid new or reclaimable inodes. Leave for reclaim code to flush */
if ((!newinos && __xfs_iflags_test(ip, XFS_INEW)) ||
__xfs_iflags_test(ip, XFS_IRECLAIMABLE | XFS_IRECLAIM))
goto out_unlock_noent;
spin_unlock(&ip->i_flags_lock);
/* nothing to sync during shutdown */
if (XFS_FORCED_SHUTDOWN(ip->i_mount))
return -EFSCORRUPTED;
/* If we can't grab the inode, it must on it's way to reclaim. */
if (!igrab(inode))
return -ENOENT;
/* inode is valid */
return 0;
out_unlock_noent:
spin_unlock(&ip->i_flags_lock);
return -ENOENT;
}
STATIC int
xfs_inode_ag_walk(
struct xfs_mount *mp,
struct xfs_perag *pag,
int (*execute)(struct xfs_inode *ip, int flags,
void *args),
int flags,
void *args,
int tag,
int iter_flags)
{
uint32_t first_index;
int last_error = 0;
int skipped;
int done;
int nr_found;
restart:
done = 0;
skipped = 0;
first_index = 0;
nr_found = 0;
do {
struct xfs_inode *batch[XFS_LOOKUP_BATCH];
int error = 0;
int i;
rcu_read_lock();
if (tag == -1)
nr_found = radix_tree_gang_lookup(&pag->pag_ici_root,
(void **)batch, first_index,
XFS_LOOKUP_BATCH);
else
nr_found = radix_tree_gang_lookup_tag(
&pag->pag_ici_root,
(void **) batch, first_index,
XFS_LOOKUP_BATCH, tag);
if (!nr_found) {
rcu_read_unlock();
break;
}
/*
* Grab the inodes before we drop the lock. if we found
* nothing, nr == 0 and the loop will be skipped.
*/
for (i = 0; i < nr_found; i++) {
struct xfs_inode *ip = batch[i];
if (done || xfs_inode_ag_walk_grab(ip, iter_flags))
batch[i] = NULL;
/*
* Update the index for the next lookup. Catch
* overflows into the next AG range which can occur if
* we have inodes in the last block of the AG and we
* are currently pointing to the last inode.
*
* Because we may see inodes that are from the wrong AG
* due to RCU freeing and reallocation, only update the
* index if it lies in this AG. It was a race that lead
* us to see this inode, so another lookup from the
* same index will not find it again.
*/
if (XFS_INO_TO_AGNO(mp, ip->i_ino) != pag->pag_agno)
continue;
first_index = XFS_INO_TO_AGINO(mp, ip->i_ino + 1);
if (first_index < XFS_INO_TO_AGINO(mp, ip->i_ino))
done = 1;
}
/* unlock now we've grabbed the inodes. */
rcu_read_unlock();
for (i = 0; i < nr_found; i++) {
if (!batch[i])
continue;
if ((iter_flags & XFS_AGITER_INEW_WAIT) &&
xfs_iflags_test(batch[i], XFS_INEW))
xfs_inew_wait(batch[i]);
error = execute(batch[i], flags, args);
IRELE(batch[i]);
if (error == -EAGAIN) {
skipped++;
continue;
}
if (error && last_error != -EFSCORRUPTED)
last_error = error;
}
/* bail out if the filesystem is corrupted. */
if (error == -EFSCORRUPTED)
break;
cond_resched();
} while (nr_found && !done);
if (skipped) {
delay(1);
goto restart;
}
return last_error;
}
/*
* Background scanning to trim post-EOF preallocated space. This is queued
* based on the 'speculative_prealloc_lifetime' tunable (5m by default).
*/
void
xfs_queue_eofblocks(
struct xfs_mount *mp)
{
rcu_read_lock();
if (radix_tree_tagged(&mp->m_perag_tree, XFS_ICI_EOFBLOCKS_TAG))
queue_delayed_work(mp->m_eofblocks_workqueue,
&mp->m_eofblocks_work,
msecs_to_jiffies(xfs_eofb_secs * 1000));
rcu_read_unlock();
}
void
xfs_eofblocks_worker(
struct work_struct *work)
{
struct xfs_mount *mp = container_of(to_delayed_work(work),
struct xfs_mount, m_eofblocks_work);
xfs_icache_free_eofblocks(mp, NULL);
xfs_queue_eofblocks(mp);
}
/*
* Background scanning to trim preallocated CoW space. This is queued
* based on the 'speculative_cow_prealloc_lifetime' tunable (5m by default).
* (We'll just piggyback on the post-EOF prealloc space workqueue.)
*/
void
xfs_queue_cowblocks(
struct xfs_mount *mp)
{
rcu_read_lock();
if (radix_tree_tagged(&mp->m_perag_tree, XFS_ICI_COWBLOCKS_TAG))
queue_delayed_work(mp->m_eofblocks_workqueue,
&mp->m_cowblocks_work,
msecs_to_jiffies(xfs_cowb_secs * 1000));
rcu_read_unlock();
}
void
xfs_cowblocks_worker(
struct work_struct *work)
{
struct xfs_mount *mp = container_of(to_delayed_work(work),
struct xfs_mount, m_cowblocks_work);
xfs_icache_free_cowblocks(mp, NULL);
xfs_queue_cowblocks(mp);
}
int
xfs_inode_ag_iterator_flags(
struct xfs_mount *mp,
int (*execute)(struct xfs_inode *ip, int flags,
void *args),
int flags,
void *args,
int iter_flags)
{
struct xfs_perag *pag;
int error = 0;
int last_error = 0;
xfs_agnumber_t ag;
ag = 0;
while ((pag = xfs_perag_get(mp, ag))) {
ag = pag->pag_agno + 1;
error = xfs_inode_ag_walk(mp, pag, execute, flags, args, -1,
iter_flags);
xfs_perag_put(pag);
if (error) {
last_error = error;
if (error == -EFSCORRUPTED)
break;
}
}
return last_error;
}
int
xfs_inode_ag_iterator(
struct xfs_mount *mp,
int (*execute)(struct xfs_inode *ip, int flags,
void *args),
int flags,
void *args)
{
return xfs_inode_ag_iterator_flags(mp, execute, flags, args, 0);
}
int
xfs_inode_ag_iterator_tag(
struct xfs_mount *mp,
int (*execute)(struct xfs_inode *ip, int flags,
void *args),
int flags,
void *args,
int tag)
{
struct xfs_perag *pag;
int error = 0;
int last_error = 0;
xfs_agnumber_t ag;
ag = 0;
while ((pag = xfs_perag_get_tag(mp, ag, tag))) {
ag = pag->pag_agno + 1;
error = xfs_inode_ag_walk(mp, pag, execute, flags, args, tag,
0);
xfs_perag_put(pag);
if (error) {
last_error = error;
if (error == -EFSCORRUPTED)
break;
}
}
return last_error;
}
/*
* Grab the inode for reclaim exclusively.
* Return 0 if we grabbed it, non-zero otherwise.
*/
STATIC int
xfs_reclaim_inode_grab(
struct xfs_inode *ip,
int flags)
{
ASSERT(rcu_read_lock_held());
/* quick check for stale RCU freed inode */
if (!ip->i_ino)
return 1;
/*
* If we are asked for non-blocking operation, do unlocked checks to
* see if the inode already is being flushed or in reclaim to avoid
* lock traffic.
*/
if ((flags & SYNC_TRYLOCK) &&
__xfs_iflags_test(ip, XFS_IFLOCK | XFS_IRECLAIM))
return 1;
/*
* The radix tree lock here protects a thread in xfs_iget from racing
* with us starting reclaim on the inode. Once we have the
* XFS_IRECLAIM flag set it will not touch us.
*
* Due to RCU lookup, we may find inodes that have been freed and only
* have XFS_IRECLAIM set. Indeed, we may see reallocated inodes that
* aren't candidates for reclaim at all, so we must check the
* XFS_IRECLAIMABLE is set first before proceeding to reclaim.
*/
spin_lock(&ip->i_flags_lock);
if (!__xfs_iflags_test(ip, XFS_IRECLAIMABLE) ||
__xfs_iflags_test(ip, XFS_IRECLAIM)) {
/* not a reclaim candidate. */
spin_unlock(&ip->i_flags_lock);
return 1;
}
__xfs_iflags_set(ip, XFS_IRECLAIM);
spin_unlock(&ip->i_flags_lock);
return 0;
}
/*
* Inodes in different states need to be treated differently. The following
* table lists the inode states and the reclaim actions necessary:
*
* inode state iflush ret required action
* --------------- ---------- ---------------
* bad - reclaim
* shutdown EIO unpin and reclaim
* clean, unpinned 0 reclaim
* stale, unpinned 0 reclaim
* clean, pinned(*) 0 requeue
* stale, pinned EAGAIN requeue
* dirty, async - requeue
* dirty, sync 0 reclaim
*
* (*) dgc: I don't think the clean, pinned state is possible but it gets
* handled anyway given the order of checks implemented.
*
* Also, because we get the flush lock first, we know that any inode that has
* been flushed delwri has had the flush completed by the time we check that
* the inode is clean.
*
* Note that because the inode is flushed delayed write by AIL pushing, the
* flush lock may already be held here and waiting on it can result in very
* long latencies. Hence for sync reclaims, where we wait on the flush lock,
* the caller should push the AIL first before trying to reclaim inodes to
* minimise the amount of time spent waiting. For background relaim, we only
* bother to reclaim clean inodes anyway.
*
* Hence the order of actions after gaining the locks should be:
* bad => reclaim
* shutdown => unpin and reclaim
* pinned, async => requeue
* pinned, sync => unpin
* stale => reclaim
* clean => reclaim
* dirty, async => requeue
* dirty, sync => flush, wait and reclaim
*/
STATIC int
xfs_reclaim_inode(
struct xfs_inode *ip,
struct xfs_perag *pag,
int sync_mode)
{
struct xfs_buf *bp = NULL;
xfs_ino_t ino = ip->i_ino; /* for radix_tree_delete */
int error;
restart:
error = 0;
xfs_ilock(ip, XFS_ILOCK_EXCL);
if (!xfs_iflock_nowait(ip)) {
if (!(sync_mode & SYNC_WAIT))
goto out;
xfs_iflock(ip);
}
if (XFS_FORCED_SHUTDOWN(ip->i_mount)) {
xfs_iunpin_wait(ip);
/* xfs_iflush_abort() drops the flush lock */
xfs_iflush_abort(ip, false);
goto reclaim;
}
if (xfs_ipincount(ip)) {
if (!(sync_mode & SYNC_WAIT))
goto out_ifunlock;
xfs_iunpin_wait(ip);
}
if (xfs_iflags_test(ip, XFS_ISTALE) || xfs_inode_clean(ip)) {
xfs_ifunlock(ip);
goto reclaim;
}
/*
* Never flush out dirty data during non-blocking reclaim, as it would
* just contend with AIL pushing trying to do the same job.
*/
if (!(sync_mode & SYNC_WAIT))
goto out_ifunlock;
/*
* Now we have an inode that needs flushing.
*
* Note that xfs_iflush will never block on the inode buffer lock, as
* xfs_ifree_cluster() can lock the inode buffer before it locks the
* ip->i_lock, and we are doing the exact opposite here. As a result,
* doing a blocking xfs_imap_to_bp() to get the cluster buffer would
* result in an ABBA deadlock with xfs_ifree_cluster().
*
* As xfs_ifree_cluser() must gather all inodes that are active in the
* cache to mark them stale, if we hit this case we don't actually want
* to do IO here - we want the inode marked stale so we can simply
* reclaim it. Hence if we get an EAGAIN error here, just unlock the
* inode, back off and try again. Hopefully the next pass through will
* see the stale flag set on the inode.
*/
error = xfs_iflush(ip, &bp);
if (error == -EAGAIN) {
xfs_iunlock(ip, XFS_ILOCK_EXCL);
/* backoff longer than in xfs_ifree_cluster */
delay(2);
goto restart;
}
if (!error) {
error = xfs_bwrite(bp);
xfs_buf_relse(bp);
}
reclaim:
ASSERT(!xfs_isiflocked(ip));
/*
* Because we use RCU freeing we need to ensure the inode always appears
* to be reclaimed with an invalid inode number when in the free state.
* We do this as early as possible under the ILOCK so that
* xfs_iflush_cluster() and xfs_ifree_cluster() can be guaranteed to
* detect races with us here. By doing this, we guarantee that once
* xfs_iflush_cluster() or xfs_ifree_cluster() has locked XFS_ILOCK that
* it will see either a valid inode that will serialise correctly, or it
* will see an invalid inode that it can skip.
*/
spin_lock(&ip->i_flags_lock);
ip->i_flags = XFS_IRECLAIM;
ip->i_ino = 0;
spin_unlock(&ip->i_flags_lock);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
XFS_STATS_INC(ip->i_mount, xs_ig_reclaims);
/*
* Remove the inode from the per-AG radix tree.
*
* Because radix_tree_delete won't complain even if the item was never
* added to the tree assert that it's been there before to catch
* problems with the inode life time early on.
*/
spin_lock(&pag->pag_ici_lock);
if (!radix_tree_delete(&pag->pag_ici_root,
XFS_INO_TO_AGINO(ip->i_mount, ino)))
ASSERT(0);
xfs_perag_clear_reclaim_tag(pag);
spin_unlock(&pag->pag_ici_lock);
/*
* Here we do an (almost) spurious inode lock in order to coordinate
* with inode cache radix tree lookups. This is because the lookup
* can reference the inodes in the cache without taking references.
*
* We make that OK here by ensuring that we wait until the inode is
* unlocked after the lookup before we go ahead and free it.
*/
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_qm_dqdetach(ip);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
__xfs_inode_free(ip);
return error;
out_ifunlock:
xfs_ifunlock(ip);
out:
xfs_iflags_clear(ip, XFS_IRECLAIM);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
/*
* We could return -EAGAIN here to make reclaim rescan the inode tree in
* a short while. However, this just burns CPU time scanning the tree
* waiting for IO to complete and the reclaim work never goes back to
* the idle state. Instead, return 0 to let the next scheduled
* background reclaim attempt to reclaim the inode again.
*/
return 0;
}
/*
* Walk the AGs and reclaim the inodes in them. Even if the filesystem is
* corrupted, we still want to try to reclaim all the inodes. If we don't,
* then a shut down during filesystem unmount reclaim walk leak all the
* unreclaimed inodes.
*/
STATIC int
xfs_reclaim_inodes_ag(
struct xfs_mount *mp,
int flags,
int *nr_to_scan)
{
struct xfs_perag *pag;
int error = 0;
int last_error = 0;
xfs_agnumber_t ag;
int trylock = flags & SYNC_TRYLOCK;
int skipped;
restart:
ag = 0;
skipped = 0;
while ((pag = xfs_perag_get_tag(mp, ag, XFS_ICI_RECLAIM_TAG))) {
unsigned long first_index = 0;
int done = 0;
int nr_found = 0;
ag = pag->pag_agno + 1;
if (trylock) {
if (!mutex_trylock(&pag->pag_ici_reclaim_lock)) {
skipped++;
xfs_perag_put(pag);
continue;
}
first_index = pag->pag_ici_reclaim_cursor;
} else
mutex_lock(&pag->pag_ici_reclaim_lock);
do {
struct xfs_inode *batch[XFS_LOOKUP_BATCH];
int i;
rcu_read_lock();
nr_found = radix_tree_gang_lookup_tag(
&pag->pag_ici_root,
(void **)batch, first_index,
XFS_LOOKUP_BATCH,
XFS_ICI_RECLAIM_TAG);
if (!nr_found) {
done = 1;
rcu_read_unlock();
break;
}
/*
* Grab the inodes before we drop the lock. if we found
* nothing, nr == 0 and the loop will be skipped.
*/
for (i = 0; i < nr_found; i++) {
struct xfs_inode *ip = batch[i];
if (done || xfs_reclaim_inode_grab(ip, flags))
batch[i] = NULL;
/*
* Update the index for the next lookup. Catch
* overflows into the next AG range which can
* occur if we have inodes in the last block of
* the AG and we are currently pointing to the
* last inode.
*
* Because we may see inodes that are from the
* wrong AG due to RCU freeing and
* reallocation, only update the index if it
* lies in this AG. It was a race that lead us
* to see this inode, so another lookup from
* the same index will not find it again.
*/
if (XFS_INO_TO_AGNO(mp, ip->i_ino) !=
pag->pag_agno)
continue;
first_index = XFS_INO_TO_AGINO(mp, ip->i_ino + 1);
if (first_index < XFS_INO_TO_AGINO(mp, ip->i_ino))
done = 1;
}
/* unlock now we've grabbed the inodes. */
rcu_read_unlock();
for (i = 0; i < nr_found; i++) {
if (!batch[i])
continue;
error = xfs_reclaim_inode(batch[i], pag, flags);
if (error && last_error != -EFSCORRUPTED)
last_error = error;
}
*nr_to_scan -= XFS_LOOKUP_BATCH;
cond_resched();
} while (nr_found && !done && *nr_to_scan > 0);
if (trylock && !done)
pag->pag_ici_reclaim_cursor = first_index;
else
pag->pag_ici_reclaim_cursor = 0;
mutex_unlock(&pag->pag_ici_reclaim_lock);
xfs_perag_put(pag);
}
/*
* if we skipped any AG, and we still have scan count remaining, do
* another pass this time using blocking reclaim semantics (i.e
* waiting on the reclaim locks and ignoring the reclaim cursors). This
* ensure that when we get more reclaimers than AGs we block rather
* than spin trying to execute reclaim.
*/
if (skipped && (flags & SYNC_WAIT) && *nr_to_scan > 0) {
trylock = 0;
goto restart;
}
return last_error;
}
int
xfs_reclaim_inodes(
xfs_mount_t *mp,
int mode)
{
int nr_to_scan = INT_MAX;
return xfs_reclaim_inodes_ag(mp, mode, &nr_to_scan);
}
/*
* Scan a certain number of inodes for reclaim.
*
* When called we make sure that there is a background (fast) inode reclaim in
* progress, while we will throttle the speed of reclaim via doing synchronous
* reclaim of inodes. That means if we come across dirty inodes, we wait for
* them to be cleaned, which we hope will not be very long due to the
* background walker having already kicked the IO off on those dirty inodes.
*/
long
xfs_reclaim_inodes_nr(
struct xfs_mount *mp,
int nr_to_scan)
{
/* kick background reclaimer and push the AIL */
xfs_reclaim_work_queue(mp);
xfs_ail_push_all(mp->m_ail);
return xfs_reclaim_inodes_ag(mp, SYNC_TRYLOCK | SYNC_WAIT, &nr_to_scan);
}
/*
* Return the number of reclaimable inodes in the filesystem for
* the shrinker to determine how much to reclaim.
*/
int
xfs_reclaim_inodes_count(
struct xfs_mount *mp)
{
struct xfs_perag *pag;
xfs_agnumber_t ag = 0;
int reclaimable = 0;
while ((pag = xfs_perag_get_tag(mp, ag, XFS_ICI_RECLAIM_TAG))) {
ag = pag->pag_agno + 1;
reclaimable += pag->pag_ici_reclaimable;
xfs_perag_put(pag);
}
return reclaimable;
}
STATIC int
xfs_inode_match_id(
struct xfs_inode *ip,
struct xfs_eofblocks *eofb)
{
if ((eofb->eof_flags & XFS_EOF_FLAGS_UID) &&
!uid_eq(VFS_I(ip)->i_uid, eofb->eof_uid))
return 0;
if ((eofb->eof_flags & XFS_EOF_FLAGS_GID) &&
!gid_eq(VFS_I(ip)->i_gid, eofb->eof_gid))
return 0;
if ((eofb->eof_flags & XFS_EOF_FLAGS_PRID) &&
xfs_get_projid(ip) != eofb->eof_prid)
return 0;
return 1;
}
/*
* A union-based inode filtering algorithm. Process the inode if any of the
* criteria match. This is for global/internal scans only.
*/
STATIC int
xfs_inode_match_id_union(
struct xfs_inode *ip,
struct xfs_eofblocks *eofb)
{
if ((eofb->eof_flags & XFS_EOF_FLAGS_UID) &&
uid_eq(VFS_I(ip)->i_uid, eofb->eof_uid))
return 1;
if ((eofb->eof_flags & XFS_EOF_FLAGS_GID) &&
gid_eq(VFS_I(ip)->i_gid, eofb->eof_gid))
return 1;
if ((eofb->eof_flags & XFS_EOF_FLAGS_PRID) &&
xfs_get_projid(ip) == eofb->eof_prid)
return 1;
return 0;
}
STATIC int
xfs_inode_free_eofblocks(
struct xfs_inode *ip,
int flags,
void *args)
{
int ret = 0;
struct xfs_eofblocks *eofb = args;
int match;
if (!xfs_can_free_eofblocks(ip, false)) {
/* inode could be preallocated or append-only */
trace_xfs_inode_free_eofblocks_invalid(ip);
xfs_inode_clear_eofblocks_tag(ip);
return 0;
}
/*
* If the mapping is dirty the operation can block and wait for some
* time. Unless we are waiting, skip it.
*/
if (!(flags & SYNC_WAIT) &&
mapping_tagged(VFS_I(ip)->i_mapping, PAGECACHE_TAG_DIRTY))
return 0;
if (eofb) {
if (eofb->eof_flags & XFS_EOF_FLAGS_UNION)
match = xfs_inode_match_id_union(ip, eofb);
else
match = xfs_inode_match_id(ip, eofb);
if (!match)
return 0;
/* skip the inode if the file size is too small */
if (eofb->eof_flags & XFS_EOF_FLAGS_MINFILESIZE &&
XFS_ISIZE(ip) < eofb->eof_min_file_size)
return 0;
}
/*
* If the caller is waiting, return -EAGAIN to keep the background
* scanner moving and revisit the inode in a subsequent pass.
*/
if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
if (flags & SYNC_WAIT)
ret = -EAGAIN;
return ret;
}
ret = xfs_free_eofblocks(ip);
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return ret;
}
static int
__xfs_icache_free_eofblocks(
struct xfs_mount *mp,
struct xfs_eofblocks *eofb,
int (*execute)(struct xfs_inode *ip, int flags,
void *args),
int tag)
{
int flags = SYNC_TRYLOCK;
if (eofb && (eofb->eof_flags & XFS_EOF_FLAGS_SYNC))
flags = SYNC_WAIT;
return xfs_inode_ag_iterator_tag(mp, execute, flags,
eofb, tag);
}
int
xfs_icache_free_eofblocks(
struct xfs_mount *mp,
struct xfs_eofblocks *eofb)
{
return __xfs_icache_free_eofblocks(mp, eofb, xfs_inode_free_eofblocks,
XFS_ICI_EOFBLOCKS_TAG);
}
/*
* Run eofblocks scans on the quotas applicable to the inode. For inodes with
* multiple quotas, we don't know exactly which quota caused an allocation
* failure. We make a best effort by including each quota under low free space
* conditions (less than 1% free space) in the scan.
*/
static int
__xfs_inode_free_quota_eofblocks(
struct xfs_inode *ip,
int (*execute)(struct xfs_mount *mp,
struct xfs_eofblocks *eofb))
{
int scan = 0;
struct xfs_eofblocks eofb = {0};
struct xfs_dquot *dq;
/*
* Run a sync scan to increase effectiveness and use the union filter to
* cover all applicable quotas in a single scan.
*/
eofb.eof_flags = XFS_EOF_FLAGS_UNION|XFS_EOF_FLAGS_SYNC;
if (XFS_IS_UQUOTA_ENFORCED(ip->i_mount)) {
dq = xfs_inode_dquot(ip, XFS_DQ_USER);
if (dq && xfs_dquot_lowsp(dq)) {
eofb.eof_uid = VFS_I(ip)->i_uid;
eofb.eof_flags |= XFS_EOF_FLAGS_UID;
scan = 1;
}
}
if (XFS_IS_GQUOTA_ENFORCED(ip->i_mount)) {
dq = xfs_inode_dquot(ip, XFS_DQ_GROUP);
if (dq && xfs_dquot_lowsp(dq)) {
eofb.eof_gid = VFS_I(ip)->i_gid;
eofb.eof_flags |= XFS_EOF_FLAGS_GID;
scan = 1;
}
}
if (scan)
execute(ip->i_mount, &eofb);
return scan;
}
int
xfs_inode_free_quota_eofblocks(
struct xfs_inode *ip)
{
return __xfs_inode_free_quota_eofblocks(ip, xfs_icache_free_eofblocks);
}
static inline unsigned long
xfs_iflag_for_tag(
int tag)
{
switch (tag) {
case XFS_ICI_EOFBLOCKS_TAG:
return XFS_IEOFBLOCKS;
case XFS_ICI_COWBLOCKS_TAG:
return XFS_ICOWBLOCKS;
default:
ASSERT(0);
return 0;
}
}
static void
__xfs_inode_set_blocks_tag(
xfs_inode_t *ip,
void (*execute)(struct xfs_mount *mp),
void (*set_tp)(struct xfs_mount *mp, xfs_agnumber_t agno,
int error, unsigned long caller_ip),
int tag)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_perag *pag;
int tagged;
/*
* Don't bother locking the AG and looking up in the radix trees
* if we already know that we have the tag set.
*/
if (ip->i_flags & xfs_iflag_for_tag(tag))
return;
spin_lock(&ip->i_flags_lock);
ip->i_flags |= xfs_iflag_for_tag(tag);
spin_unlock(&ip->i_flags_lock);
pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
spin_lock(&pag->pag_ici_lock);
tagged = radix_tree_tagged(&pag->pag_ici_root, tag);
radix_tree_tag_set(&pag->pag_ici_root,
XFS_INO_TO_AGINO(ip->i_mount, ip->i_ino), tag);
if (!tagged) {
/* propagate the eofblocks tag up into the perag radix tree */
spin_lock(&ip->i_mount->m_perag_lock);
radix_tree_tag_set(&ip->i_mount->m_perag_tree,
XFS_INO_TO_AGNO(ip->i_mount, ip->i_ino),
tag);
spin_unlock(&ip->i_mount->m_perag_lock);
/* kick off background trimming */
execute(ip->i_mount);
set_tp(ip->i_mount, pag->pag_agno, -1, _RET_IP_);
}
spin_unlock(&pag->pag_ici_lock);
xfs_perag_put(pag);
}
void
xfs_inode_set_eofblocks_tag(
xfs_inode_t *ip)
{
trace_xfs_inode_set_eofblocks_tag(ip);
return __xfs_inode_set_blocks_tag(ip, xfs_queue_eofblocks,
trace_xfs_perag_set_eofblocks,
XFS_ICI_EOFBLOCKS_TAG);
}
static void
__xfs_inode_clear_blocks_tag(
xfs_inode_t *ip,
void (*clear_tp)(struct xfs_mount *mp, xfs_agnumber_t agno,
int error, unsigned long caller_ip),
int tag)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_perag *pag;
spin_lock(&ip->i_flags_lock);
ip->i_flags &= ~xfs_iflag_for_tag(tag);
spin_unlock(&ip->i_flags_lock);
pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, ip->i_ino));
spin_lock(&pag->pag_ici_lock);
radix_tree_tag_clear(&pag->pag_ici_root,
XFS_INO_TO_AGINO(ip->i_mount, ip->i_ino), tag);
if (!radix_tree_tagged(&pag->pag_ici_root, tag)) {
/* clear the eofblocks tag from the perag radix tree */
spin_lock(&ip->i_mount->m_perag_lock);
radix_tree_tag_clear(&ip->i_mount->m_perag_tree,
XFS_INO_TO_AGNO(ip->i_mount, ip->i_ino),
tag);
spin_unlock(&ip->i_mount->m_perag_lock);
clear_tp(ip->i_mount, pag->pag_agno, -1, _RET_IP_);
}
spin_unlock(&pag->pag_ici_lock);
xfs_perag_put(pag);
}
void
xfs_inode_clear_eofblocks_tag(
xfs_inode_t *ip)
{
trace_xfs_inode_clear_eofblocks_tag(ip);
return __xfs_inode_clear_blocks_tag(ip,
trace_xfs_perag_clear_eofblocks, XFS_ICI_EOFBLOCKS_TAG);
}
/*
* Set ourselves up to free CoW blocks from this file. If it's already clean
* then we can bail out quickly, but otherwise we must back off if the file
* is undergoing some kind of write.
*/
static bool
xfs_prep_free_cowblocks(
struct xfs_inode *ip,
struct xfs_ifork *ifp)
{
/*
* Just clear the tag if we have an empty cow fork or none at all. It's
* possible the inode was fully unshared since it was originally tagged.
*/
if (!xfs_is_reflink_inode(ip) || !ifp->if_bytes) {
trace_xfs_inode_free_cowblocks_invalid(ip);
xfs_inode_clear_cowblocks_tag(ip);
return false;
}
/*
* If the mapping is dirty or under writeback we cannot touch the
* CoW fork. Leave it alone if we're in the midst of a directio.
*/
if ((VFS_I(ip)->i_state & I_DIRTY_PAGES) ||
mapping_tagged(VFS_I(ip)->i_mapping, PAGECACHE_TAG_DIRTY) ||
mapping_tagged(VFS_I(ip)->i_mapping, PAGECACHE_TAG_WRITEBACK) ||
atomic_read(&VFS_I(ip)->i_dio_count))
return false;
return true;
}
/*
* Automatic CoW Reservation Freeing
*
* These functions automatically garbage collect leftover CoW reservations
* that were made on behalf of a cowextsize hint when we start to run out
* of quota or when the reservations sit around for too long. If the file
* has dirty pages or is undergoing writeback, its CoW reservations will
* be retained.
*
* The actual garbage collection piggybacks off the same code that runs
* the speculative EOF preallocation garbage collector.
*/
STATIC int
xfs_inode_free_cowblocks(
struct xfs_inode *ip,
int flags,
void *args)
{
struct xfs_eofblocks *eofb = args;
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_COW_FORK);
int match;
int ret = 0;
if (!xfs_prep_free_cowblocks(ip, ifp))
return 0;
if (eofb) {
if (eofb->eof_flags & XFS_EOF_FLAGS_UNION)
match = xfs_inode_match_id_union(ip, eofb);
else
match = xfs_inode_match_id(ip, eofb);
if (!match)
return 0;
/* skip the inode if the file size is too small */
if (eofb->eof_flags & XFS_EOF_FLAGS_MINFILESIZE &&
XFS_ISIZE(ip) < eofb->eof_min_file_size)
return 0;
}
/* Free the CoW blocks */
xfs_ilock(ip, XFS_IOLOCK_EXCL);
xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
/*
* Check again, nobody else should be able to dirty blocks or change
* the reflink iflag now that we have the first two locks held.
*/
if (xfs_prep_free_cowblocks(ip, ifp))
ret = xfs_reflink_cancel_cow_range(ip, 0, NULLFILEOFF, false);
xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
xfs_iunlock(ip, XFS_IOLOCK_EXCL);
return ret;
}
int
xfs_icache_free_cowblocks(
struct xfs_mount *mp,
struct xfs_eofblocks *eofb)
{
return __xfs_icache_free_eofblocks(mp, eofb, xfs_inode_free_cowblocks,
XFS_ICI_COWBLOCKS_TAG);
}
int
xfs_inode_free_quota_cowblocks(
struct xfs_inode *ip)
{
return __xfs_inode_free_quota_eofblocks(ip, xfs_icache_free_cowblocks);
}
void
xfs_inode_set_cowblocks_tag(
xfs_inode_t *ip)
{
trace_xfs_inode_set_cowblocks_tag(ip);
return __xfs_inode_set_blocks_tag(ip, xfs_queue_cowblocks,
trace_xfs_perag_set_cowblocks,
XFS_ICI_COWBLOCKS_TAG);
}
void
xfs_inode_clear_cowblocks_tag(
xfs_inode_t *ip)
{
trace_xfs_inode_clear_cowblocks_tag(ip);
return __xfs_inode_clear_blocks_tag(ip,
trace_xfs_perag_clear_cowblocks, XFS_ICI_COWBLOCKS_TAG);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_212_0 |
crossvul-cpp_data_good_2512_0 | /*
* Copyright 2014, Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* A daemon that supports a simplified interface for writing TCMU
* handlers.
*/
#define _GNU_SOURCE
#define _BITS_UIO_H
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <assert.h>
#include <dlfcn.h>
#include <pthread.h>
#include <signal.h>
#include <glib.h>
#include <glib-unix.h>
#include <gio/gio.h>
#include <getopt.h>
#include <poll.h>
#include <scsi/scsi.h>
#include <libkmod.h>
#include <sys/utsname.h>
#include "target_core_user_local.h"
#include "darray.h"
#include "tcmu-runner.h"
#include "tcmur_aio.h"
#include "tcmur_device.h"
#include "tcmur_cmd_handler.h"
#include "libtcmu.h"
#include "tcmuhandler-generated.h"
#include "version.h"
#include "libtcmu_config.h"
#include "libtcmu_log.h"
static char *handler_path = DEFAULT_HANDLER_PATH;
/* tcmu log dir path */
extern char *tcmu_log_dir;
static struct tcmu_config *tcmu_cfg;
darray(struct tcmur_handler *) g_runner_handlers = darray_new();
static struct tcmur_handler *find_handler_by_subtype(gchar *subtype)
{
struct tcmur_handler **handler;
darray_foreach(handler, g_runner_handlers) {
if (strcmp((*handler)->subtype, subtype) == 0)
return *handler;
}
return NULL;
}
int tcmur_register_handler(struct tcmur_handler *handler)
{
struct tcmur_handler *h;
int i;
for (i = 0; i < darray_size(g_runner_handlers); i++) {
h = darray_item(g_runner_handlers, i);
if (!strcmp(h->subtype, handler->subtype)) {
tcmu_err("Handler %s has already been registered\n",
handler->subtype);
return -1;
}
}
darray_append(g_runner_handlers, handler);
return 0;
}
static int tcmur_register_dbus_handler(struct tcmur_handler *handler)
{
assert(handler->_is_dbus_handler == true);
return tcmur_register_handler(handler);
}
bool tcmur_unregister_handler(struct tcmur_handler *handler)
{
int i;
for (i = 0; i < darray_size(g_runner_handlers); i++) {
if (darray_item(g_runner_handlers, i) == handler) {
darray_remove(g_runner_handlers, i);
return true;
}
}
return false;
}
static bool tcmur_unregister_dbus_handler(struct tcmur_handler *handler)
{
bool ret = false;
assert(handler->_is_dbus_handler == true);
ret = tcmur_unregister_handler(handler);
return ret;
}
static int is_handler(const struct dirent *dirent)
{
if (strncmp(dirent->d_name, "handler_", 8))
return 0;
return 1;
}
static int open_handlers(void)
{
struct dirent **dirent_list;
int num_handlers;
int num_good = 0;
int i;
num_handlers = scandir(handler_path, &dirent_list, is_handler, alphasort);
if (num_handlers == -1)
return -1;
for (i = 0; i < num_handlers; i++) {
char *path;
void *handle;
int (*handler_init)(void);
int ret;
ret = asprintf(&path, "%s/%s", handler_path, dirent_list[i]->d_name);
if (ret == -1) {
tcmu_err("ENOMEM\n");
continue;
}
handle = dlopen(path, RTLD_NOW|RTLD_LOCAL);
if (!handle) {
tcmu_err("Could not open handler at %s: %s\n", path, dlerror());
free(path);
continue;
}
handler_init = dlsym(handle, "handler_init");
if (!handler_init) {
tcmu_err("dlsym failure on %s\n", path);
free(path);
continue;
}
ret = handler_init();
free(path);
if (ret == 0)
num_good++;
}
for (i = 0; i < num_handlers; i++)
free(dirent_list[i]);
free(dirent_list);
return num_good;
}
static gboolean sighandler(gpointer user_data)
{
tcmulib_cleanup_all_cmdproc_threads();
tcmu_cancel_log_thread();
tcmu_cancel_config_thread(tcmu_cfg);
g_main_loop_quit((GMainLoop*)user_data);
return G_SOURCE_CONTINUE;
}
gboolean tcmulib_callback(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
struct tcmulib_context *ctx = data;
tcmulib_master_fd_ready(ctx);
return TRUE;
}
static GDBusObjectManagerServer *manager = NULL;
static gboolean
on_check_config(TCMUService1 *interface,
GDBusMethodInvocation *invocation,
gchar *cfgstring,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
char *reason = NULL;
bool str_ok = true;
if (handler->check_config)
str_ok = handler->check_config(cfgstring, &reason);
if (str_ok)
reason = "success";
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", str_ok, reason ? : "unknown"));
if (!str_ok)
free(reason);
return TRUE;
}
static void
dbus_export_handler(struct tcmur_handler *handler, GCallback check_config)
{
GDBusObjectSkeleton *object;
char obj_name[128];
TCMUService1 *interface;
snprintf(obj_name, sizeof(obj_name), "/org/kernel/TCMUService1/%s",
handler->subtype);
object = g_dbus_object_skeleton_new(obj_name);
interface = tcmuservice1_skeleton_new();
g_dbus_object_skeleton_add_interface(object, G_DBUS_INTERFACE_SKELETON(interface));
g_signal_connect(interface,
"handle-check-config",
check_config,
handler); /* user_data */
tcmuservice1_set_config_desc(interface, handler->cfg_desc);
g_dbus_object_manager_server_export(manager, G_DBUS_OBJECT_SKELETON(object));
g_object_unref(object);
}
static bool
dbus_unexport_handler(struct tcmur_handler *handler)
{
char obj_name[128];
snprintf(obj_name, sizeof(obj_name), "/org/kernel/TCMUService1/%s",
handler->subtype);
return g_dbus_object_manager_server_unexport(manager, obj_name) == TRUE;
}
struct dbus_info {
guint watcher_id;
/* The RegisterHandler invocation on
* org.kernel.TCMUService1.HandlerManager1 interface. */
GDBusMethodInvocation *register_invocation;
/* Connection to the handler's bus_name. */
GDBusConnection *connection;
};
static int dbus_handler_open(struct tcmu_device *dev)
{
return -1;
}
static void dbus_handler_close(struct tcmu_device *dev)
{
/* nop */
}
static int dbus_handler_handle_cmd(struct tcmu_device *dev,
struct tcmulib_cmd *cmd)
{
abort();
}
static gboolean
on_dbus_check_config(TCMUService1 *interface,
GDBusMethodInvocation *invocation,
gchar *cfgstring,
gpointer user_data)
{
char *bus_name, *obj_name;
struct tcmur_handler *handler = user_data;
GDBusConnection *connection;
GError *error = NULL;
GVariant *result;
bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
obj_name = g_strdup_printf("/org/kernel/TCMUService1/HandlerManager1/%s",
handler->subtype);
connection = g_dbus_method_invocation_get_connection(invocation);
result = g_dbus_connection_call_sync(connection,
bus_name,
obj_name,
"org.kernel.TCMUService1",
"CheckConfig",
g_variant_new("(s)", cfgstring),
NULL, G_DBUS_CALL_FLAGS_NONE, -1,
NULL, &error);
if (result)
g_dbus_method_invocation_return_value(invocation, result);
else
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE, error->message));
g_free(bus_name);
g_free(obj_name);
return TRUE;
}
static void
on_handler_appeared(GDBusConnection *connection,
const gchar *name,
const gchar *name_owner,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
info->connection = connection;
tcmur_register_dbus_handler(handler);
dbus_export_handler(handler, G_CALLBACK(on_dbus_check_config));
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
info->register_invocation = NULL;
}
}
static void
on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_dbus_handler(handler);
dbus_unexport_handler(handler);
}
static gboolean
on_register_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gchar *cfg_desc,
gpointer user_data)
{
struct tcmur_handler *handler;
struct dbus_info *info;
char *bus_name;
bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s",
subtype);
handler = g_new0(struct tcmur_handler, 1);
handler->subtype = g_strdup(subtype);
handler->cfg_desc = g_strdup(cfg_desc);
handler->open = dbus_handler_open;
handler->close = dbus_handler_close;
handler->handle_cmd = dbus_handler_handle_cmd;
info = g_new0(struct dbus_info, 1);
handler->opaque = info;
handler->_is_dbus_handler = 1;
info->register_invocation = invocation;
info->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM,
bus_name,
G_BUS_NAME_WATCHER_FLAGS_NONE,
on_handler_appeared,
on_handler_vanished,
handler,
NULL);
g_free(bus_name);
handler->opaque = info;
return TRUE;
}
static gboolean
on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
else if (handler->_is_dbus_handler != 1) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"cannot unregister internal handler"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_dbus_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
void dbus_handler_manager1_init(GDBusConnection *connection)
{
GError *error = NULL;
TCMUService1HandlerManager1 *interface;
gboolean ret;
interface = tcmuservice1_handler_manager1_skeleton_new();
ret = g_dbus_interface_skeleton_export(
G_DBUS_INTERFACE_SKELETON(interface),
connection,
"/org/kernel/TCMUService1/HandlerManager1",
&error);
g_signal_connect(interface,
"handle-register-handler",
G_CALLBACK (on_register_handler),
NULL);
g_signal_connect(interface,
"handle-unregister-handler",
G_CALLBACK (on_unregister_handler),
NULL);
if (!ret)
tcmu_err("Handler manager export failed: %s\n",
error ? error->message : "unknown error");
if (error)
g_error_free(error);
}
static void dbus_bus_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler **handler;
tcmu_dbg("bus %s acquired\n", name);
manager = g_dbus_object_manager_server_new("/org/kernel/TCMUService1");
darray_foreach(handler, g_runner_handlers) {
dbus_export_handler(*handler, G_CALLBACK(on_check_config));
}
dbus_handler_manager1_init(connection);
g_dbus_object_manager_server_set_connection(manager, connection);
}
static void dbus_name_acquired(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
tcmu_dbg("name %s acquired\n", name);
}
static void dbus_name_lost(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
tcmu_dbg("name lost\n");
}
static int load_our_module(void)
{
struct kmod_list *list = NULL, *itr;
struct kmod_ctx *ctx;
struct stat sb;
struct utsname u;
int ret;
ctx = kmod_new(NULL, NULL);
if (!ctx) {
tcmu_err("kmod_new() failed: %m\n");
return -1;
}
ret = kmod_module_new_from_lookup(ctx, "target_core_user", &list);
if (ret < 0) {
/* In some environments like containers, /lib/modules/`uname -r`
* will not exist, in such cases the load module job be taken
* care by admin, either by manual load or makesure it's builtin
*/
if (ENOENT == errno) {
if (uname(&u) < 0) {
tcmu_err("uname() failed: %m\n");
} else {
tcmu_info("no modules directory '/lib/modules/%s', checking module target_core_user entry in '/sys/modules/'\n",
u.release);
ret = stat("/sys/module/target_core_user", &sb);
if (!ret) {
tcmu_dbg("Module target_core_user already loaded\n");
} else {
tcmu_err("stat() on '/sys/module/target_core_user' failed: %m\n");
}
}
} else {
tcmu_err("kmod_module_new_from_lookup() failed to lookup alias target_core_use %m\n");
}
kmod_unref(ctx);
return ret;
}
if (!list) {
tcmu_err("kmod_module_new_from_lookup() failed to find module target_core_user\n");
kmod_unref(ctx);
return -ENOENT;
}
kmod_list_foreach(itr, list) {
int state, err;
struct kmod_module *mod = kmod_module_get_module(itr);
state = kmod_module_get_initstate(mod);
switch (state) {
case KMOD_MODULE_BUILTIN:
tcmu_info("Module '%s' is builtin\n",
kmod_module_get_name(mod));
break;
case KMOD_MODULE_LIVE:
tcmu_dbg("Module '%s' is already loaded\n",
kmod_module_get_name(mod));
break;
default:
err = kmod_module_probe_insert_module(mod,
KMOD_PROBE_APPLY_BLACKLIST,
NULL, NULL, NULL, NULL);
if (err == 0) {
tcmu_info("Inserted module '%s'\n",
kmod_module_get_name(mod));
} else if (err == KMOD_PROBE_APPLY_BLACKLIST) {
tcmu_err("Module '%s' is blacklisted\n",
kmod_module_get_name(mod));
} else {
tcmu_err("Failed to insert '%s'\n",
kmod_module_get_name(mod));
}
ret = err;
}
kmod_module_unref(mod);
}
kmod_module_unref_list(list);
kmod_unref(ctx);
return ret;
}
static void cmdproc_thread_cleanup(void *arg)
{
struct tcmu_device *dev = arg;
struct tcmur_handler *rhandler = tcmu_get_runner_handler(dev);
rhandler->close(dev);
}
static void *tcmur_cmdproc_thread(void *arg)
{
struct tcmu_device *dev = arg;
struct tcmur_handler *rhandler = tcmu_get_runner_handler(dev);
struct pollfd pfd;
int ret;
pthread_cleanup_push(cmdproc_thread_cleanup, dev);
while (1) {
int completed = 0;
struct tcmulib_cmd *cmd;
tcmulib_processing_start(dev);
while ((cmd = tcmulib_get_next_command(dev)) != NULL) {
if (tcmu_get_log_level() == TCMU_LOG_DEBUG_SCSI_CMD)
tcmu_cdb_debug_info(cmd);
if (tcmur_handler_is_passthrough_only(rhandler))
ret = tcmur_cmd_passthrough_handler(dev, cmd);
else
ret = tcmur_generic_handle_cmd(dev, cmd);
if (ret == TCMU_NOT_HANDLED)
tcmu_warn("Command 0x%x not supported\n", cmd->cdb[0]);
/*
* command (processing) completion is called in the following
* scenarios:
* - handle_cmd: synchronous handlers
* - generic_handle_cmd: non tcmur handler calls (see generic_cmd())
* and on errors when calling tcmur handler.
*/
if (ret != TCMU_ASYNC_HANDLED) {
completed = 1;
tcmur_command_complete(dev, cmd, ret);
}
}
if (completed)
tcmulib_processing_complete(dev);
pfd.fd = tcmu_get_dev_fd(dev);
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, -1);
if (pfd.revents != POLLIN) {
tcmu_err("poll received unexpected revent: 0x%x\n", pfd.revents);
break;
}
}
tcmu_err("thread terminating, should never happen\n");
pthread_cleanup_pop(1);
return NULL;
}
static int dev_added(struct tcmu_device *dev)
{
struct tcmur_handler *rhandler = tcmu_get_runner_handler(dev);
struct tcmur_device *rdev;
int32_t block_size, max_sectors;
int64_t dev_size;
int ret;
rdev = calloc(1, sizeof(*rdev));
if (!rdev)
return -ENOMEM;
tcmu_set_daemon_dev_private(dev, rdev);
ret = -EINVAL;
block_size = tcmu_get_attribute(dev, "hw_block_size");
if (block_size <= 0) {
tcmu_dev_err(dev, "Could not get hw_block_size\n");
goto free_rdev;
}
tcmu_set_dev_block_size(dev, block_size);
dev_size = tcmu_get_device_size(dev);
if (dev_size < 0) {
tcmu_dev_err(dev, "Could not get device size\n");
goto free_rdev;
}
tcmu_set_dev_num_lbas(dev, dev_size / block_size);
max_sectors = tcmu_get_attribute(dev, "hw_max_sectors");
if (max_sectors < 0)
goto free_rdev;
tcmu_set_dev_max_xfer_len(dev, max_sectors);
tcmu_dev_dbg(dev, "Got block_size %ld, size in bytes %lld\n",
block_size, dev_size);
ret = pthread_spin_init(&rdev->lock, 0);
if (ret != 0)
goto free_rdev;
ret = pthread_mutex_init(&rdev->caw_lock, NULL);
if (ret != 0)
goto cleanup_dev_lock;
ret = pthread_mutex_init(&rdev->format_lock, NULL);
if (ret != 0)
goto cleanup_caw_lock;
ret = setup_io_work_queue(dev);
if (ret < 0)
goto cleanup_format_lock;
ret = setup_aio_tracking(rdev);
if (ret < 0)
goto cleanup_io_work_queue;
ret = rhandler->open(dev);
if (ret)
goto cleanup_aio_tracking;
ret = tcmulib_start_cmdproc_thread(dev, tcmur_cmdproc_thread);
if (ret < 0)
goto close_dev;
return 0;
close_dev:
rhandler->close(dev);
cleanup_aio_tracking:
cleanup_aio_tracking(rdev);
cleanup_io_work_queue:
cleanup_io_work_queue(dev, true);
cleanup_format_lock:
pthread_mutex_destroy(&rdev->format_lock);
cleanup_caw_lock:
pthread_mutex_destroy(&rdev->caw_lock);
cleanup_dev_lock:
pthread_spin_destroy(&rdev->lock);
free_rdev:
free(rdev);
return ret;
}
static void dev_removed(struct tcmu_device *dev)
{
struct tcmur_device *rdev = tcmu_get_daemon_dev_private(dev);
int ret;
/*
* The order of cleaning up worker threads and calling ->removed()
* is important: for sync handlers, the worker thread needs to be
* terminated before removing the handler (i.e., calling handlers
* ->close() callout) in order to ensure that no handler callouts
* are getting invoked when shutting down the handler.
*/
cleanup_io_work_queue_threads(dev);
tcmulib_cleanup_cmdproc_thread(dev);
cleanup_io_work_queue(dev, false);
cleanup_aio_tracking(rdev);
ret = pthread_mutex_destroy(&rdev->format_lock);
if (ret != 0)
tcmu_err("could not cleanup format lock %d\n", ret);
ret = pthread_mutex_destroy(&rdev->caw_lock);
if (ret != 0)
tcmu_err("could not cleanup caw lock %d\n", ret);
ret = pthread_spin_destroy(&rdev->lock);
if (ret != 0)
tcmu_err("could not cleanup mailbox lock %d\n", ret);
free(rdev);
}
static bool tcmu_logdir_create(const char *path)
{
DIR* dir = opendir(path);
if (dir) {
closedir(dir);
} else if (errno == ENOENT) {
if (mkdir(path, 0755) == -1) {
tcmu_err("mkdir(%s) failed: %m\n", path);
return FALSE;
}
} else {
tcmu_err("opendir(%s) failed: %m\n", path);
return FALSE;
}
return TRUE;
}
static void usage(void) {
printf("\nusage:\n");
printf("\ttcmu-runner [options]\n");
printf("\noptions:\n");
printf("\t-h, --help: print this message and exit\n");
printf("\t-V, --version: print version and exit\n");
printf("\t-d, --debug: enable debug messages\n");
printf("\t--handler-path: set path to search for handler modules\n");
printf("\t\tdefault is %s\n", DEFAULT_HANDLER_PATH);
printf("\t-l, --tcmu-log-dir: tcmu log dir\n");
printf("\t\tdefault is %s\n", TCMU_LOG_DIR_DEFAULT);
printf("\n");
}
static struct option long_options[] = {
{"debug", no_argument, 0, 'd'},
{"handler-path", required_argument, 0, 0},
{"tcmu-log-dir", required_argument, 0, 'l'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{0, 0, 0, 0},
};
int main(int argc, char **argv)
{
darray(struct tcmulib_handler) handlers = darray_new();
struct tcmulib_context *tcmulib_context;
struct tcmur_handler **tmp_r_handler;
GMainLoop *loop;
GIOChannel *libtcmu_gio;
guint reg_id;
int ret;
tcmu_cfg = tcmu_config_new();
if (!tcmu_cfg)
exit(1);
ret = tcmu_load_config(tcmu_cfg, NULL);
if (ret == -1)
goto err_out;
while (1) {
int option_index = 0;
int c;
c = getopt_long(argc, argv, "dhlV",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
if (option_index == 1)
handler_path = strdup(optarg);
break;
case 'l':
if (strlen(optarg) > PATH_MAX - TCMU_LOG_FILENAME_MAX) {
tcmu_err("--tcmu-log-dir='%s' cannot exceed %d characters\n",
optarg, PATH_MAX - TCMU_LOG_FILENAME_MAX);
}
if (!tcmu_logdir_create(optarg)) {
goto err_out;
}
tcmu_log_dir = strdup(optarg);
break;
case 'd':
tcmu_set_log_level(TCMU_CONF_LOG_DEBUG_SCSI_CMD);
break;
case 'V':
printf("tcmu-runner %s\n", TCMUR_VERSION);
goto err_out;
default:
case 'h':
usage();
goto err_out;
}
}
tcmu_dbg("handler path: %s\n", handler_path);
ret = load_our_module();
if (ret < 0) {
tcmu_err("couldn't load module\n");
goto err_out;
}
ret = open_handlers();
if (ret < 0) {
tcmu_err("couldn't open handlers\n");
goto err_out;
}
tcmu_dbg("%d runner handlers found\n", ret);
/*
* Convert from tcmu-runner's handler struct to libtcmu's
* handler struct, an array of which we pass in, below.
*/
darray_foreach(tmp_r_handler, g_runner_handlers) {
struct tcmulib_handler tmp_handler;
tmp_handler.name = (*tmp_r_handler)->name;
tmp_handler.subtype = (*tmp_r_handler)->subtype;
tmp_handler.cfg_desc = (*tmp_r_handler)->cfg_desc;
tmp_handler.check_config = (*tmp_r_handler)->check_config;
tmp_handler.reconfig = (*tmp_r_handler)->reconfig;
tmp_handler.added = dev_added;
tmp_handler.removed = dev_removed;
/*
* Can hand out a ref to an internal pointer to the
* darray b/c handlers will never be added or removed
* once open_handlers() is done.
*/
tmp_handler.hm_private = *tmp_r_handler;
darray_append(handlers, tmp_handler);
}
tcmulib_context = tcmulib_initialize(handlers.item, handlers.size);
if (!tcmulib_context) {
tcmu_err("tcmulib_initialize failed\n");
goto err_out;
}
loop = g_main_loop_new(NULL, FALSE);
if (g_unix_signal_add(SIGINT, sighandler, loop) <= 0 ||
g_unix_signal_add(SIGTERM, sighandler, loop) <= 0) {
tcmu_err("couldn't setup signal handlers\n");
goto err_tcmulib_close;
}
/* Set up event for libtcmu */
libtcmu_gio = g_io_channel_unix_new(tcmulib_get_master_fd(tcmulib_context));
g_io_add_watch(libtcmu_gio, G_IO_IN, tcmulib_callback, tcmulib_context);
/* Set up DBus name, see callback */
reg_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
"org.kernel.TCMUService1",
G_BUS_NAME_OWNER_FLAGS_NONE,
dbus_bus_acquired,
dbus_name_acquired, // name acquired
dbus_name_lost, // name lost
NULL, // user data
NULL // user date free func
);
g_main_loop_run(loop);
tcmu_dbg("Exiting...\n");
g_bus_unown_name(reg_id);
g_main_loop_unref(loop);
tcmulib_close(tcmulib_context);
tcmu_config_destroy(tcmu_cfg);
return 0;
err_tcmulib_close:
tcmulib_close(tcmulib_context);
err_out:
tcmu_config_destroy(tcmu_cfg);
exit(1);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_2512_0 |
crossvul-cpp_data_good_5488_3 | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2010-2011, Kaori Hagihara
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
* Copyright (c) 2012, CS Systemes d'Information, France
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
/** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */
/*@{*/
/** @name Local static functions */
/*@{*/
/**
* Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_reading (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager);
/**
* The read header procedure.
*/
static OPJ_BOOL opj_j2k_read_header_procedure( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* The default encoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_encoding_validation ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* The default decoding validation procedure without any extension.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_decoding_validation ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_encoding_validation (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_validation (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager);
/**
* Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
* are valid. Developpers wanting to extend the library can add their own validation procedures.
*/
static OPJ_BOOL opj_j2k_setup_end_compress (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager);
/**
* The mct encoding validation procedure.
*
* @param p_j2k the jpeg2000 codec to validate.
* @param p_stream the input stream to validate.
* @param p_manager the user event manager.
*
* @return true if the parameters are correct.
*/
static OPJ_BOOL opj_j2k_mct_validation (opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Builds the tcd decoder to use to decode tile.
*/
static OPJ_BOOL opj_j2k_build_decoder ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Builds the tcd encoder to use to encode tile.
*/
static OPJ_BOOL opj_j2k_build_encoder ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Excutes the given procedures on the given codec.
*
* @param p_procedure_list the list of procedures to execute
* @param p_j2k the jpeg2000 codec to execute the procedures on.
* @param p_stream the stream to execute the procedures on.
* @param p_manager the user manager.
*
* @return true if all the procedures were successfully executed.
*/
static OPJ_BOOL opj_j2k_exec ( opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
/**
* Updates the rates of the tcp.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_update_rates( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Copies the decoding tile parameters onto all the tile parameters.
* Creates also the tile decoder.
*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads the lookup table containing all the marker, status and action, and returns the handler associated
* with the marker value.
* @param p_id Marker value to look up
*
* @return the handler associated with the id.
*/
static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler (OPJ_UINT32 p_id);
/**
* Destroys a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter to destroy.
*/
static void opj_j2k_tcp_destroy (opj_tcp_t *p_tcp);
/**
* Destroys the data inside a tile coding parameter structure.
*
* @param p_tcp the tile coding parameter which contain data to destroy.
*/
static void opj_j2k_tcp_data_destroy (opj_tcp_t *p_tcp);
/**
* Destroys a coding parameter structure.
*
* @param p_cp the coding parameter to destroy.
*/
static void opj_j2k_cp_destroy (opj_cp_t *p_cp);
/**
* Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no Tile number
* @param p_first_comp_no The 1st component number to compare.
* @param p_second_comp_no The 1st component number to compare.
*
* @return OPJ_TRUE if SPCdod are equals.
*/
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
*
* @param p_j2k J2K codec.
* @param p_tile_no FIXME DOC
* @param p_comp_no the component number to output.
* @param p_data FIXME DOC
* @param p_header_size FIXME DOC
* @param p_manager the user event manager.
*
* @return FIXME DOC
*/
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager );
/**
* Gets the size taken by writing a SPCod or SPCoc for the given tile and component.
*
* @param p_j2k the J2K codec.
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size (opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no );
/**
* Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile.
* @param p_j2k the jpeg2000 codec.
* @param compno FIXME DOC
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc( opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager );
/**
* Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile index.
* @param p_comp_no the component being outputted.
* @param p_j2k the J2K codec.
*
* @return the number of bytes taken by the SPCod element.
*/
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size ( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no );
/**
* Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param p_tile_no the tile to output.
* @param p_first_comp_no the first component number to compare.
* @param p_second_comp_no the second component number to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_tile_no the tile to output.
* @param p_comp_no the component number to output.
* @param p_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager);
/**
* Updates the Tile Length Marker.
*/
static void opj_j2k_update_tlm ( opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size);
/**
* Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC.
*
* @param p_j2k J2K codec.
* @param compno the component number to output.
* @param p_header_data the data buffer.
* @param p_header_size pointer to the size of the data buffer, it is changed by the function.
* @param p_manager the user event manager.
*
*/
static OPJ_BOOL opj_j2k_read_SQcd_SQcc( opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager );
/**
* Copies the tile component parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_component_parameters( opj_j2k_t *p_j2k );
/**
* Copies the tile quantization parameters of all the component from the first tile component.
*
* @param p_j2k the J2k codec.
*/
static void opj_j2k_copy_tile_quantization_parameters( opj_j2k_t *p_j2k );
/**
* Reads the tiles.
*/
static OPJ_BOOL opj_j2k_decode_tiles ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_pre_write_tile ( opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
static OPJ_BOOL opj_j2k_update_image_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image);
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset);
static void opj_j2k_get_tile_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data);
static OPJ_BOOL opj_j2k_post_write_tile (opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Sets up the procedures to do on writing header.
* Developers wanting to extend the library can add their own writing procedures.
*/
static OPJ_BOOL opj_j2k_setup_header_writing (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager);
static OPJ_BOOL opj_j2k_write_first_tile_part( opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager );
static OPJ_BOOL opj_j2k_write_all_tile_parts( opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager );
/**
* Gets the offset of the header.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_end_header( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k);
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
/**
* Writes the SOC marker (Start Of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_soc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream XXX needs data
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes the SIZ marker (image and tile size)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_siz( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the COM marker (comment)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_com( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Writes the COD marker (Coding style default)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cod( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Compares 2 COC markers (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals
*/
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_coc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes the COC marker (Coding style component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_manager the user event manager.
*/
static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager );
/**
* Gets the maximum size taken by a coc.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k);
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Writes the QCD marker (quantization default)
*
* @param p_j2k J2K codec.
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcd( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Compare QCC markers (quantization component)
*
* @param p_j2k J2K codec.
* @param p_first_comp_no the index of the first component to compare.
* @param p_second_comp_no the index of the second component to compare.
*
* @return OPJ_TRUE if equals.
*/
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no);
/**
* Writes the QCC marker (quantization component)
*
* @param p_comp_no the index of the component to output.
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_qcc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes the QCC marker (quantization component)
*
* @param p_j2k J2K codec.
* @param p_comp_no the index of the component to output.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager );
/**
* Gets the maximum size taken by a qcc.
*/
static OPJ_UINT32 opj_j2k_get_max_qcc_size (opj_j2k_t *p_j2k);
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_poc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes the POC marker (Progression Order Change)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written the stream to write data to.
* @param p_manager the user event manager.
*/
static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager );
/**
* Gets the maximum size taken by the writing of a POC.
*/
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k);
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Gets the maximum size taken by the toc headers of all the tile parts of any given tile.
*/
static OPJ_UINT32 opj_j2k_get_max_toc_size (opj_j2k_t *p_j2k);
/**
* Gets the maximum size taken by the headers of the SOT.
*
* @param p_j2k the jpeg2000 codec to use.
*/
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k);
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes the updated tlm.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_updated_tlm( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Reads a PPM marker (Packed headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm (
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm ( opj_cp_t *p_cp, opj_event_mgr_t * p_manager );
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Merges all PPT markers read (Packed headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt ( opj_tcp_t *p_tcp,
opj_event_mgr_t * p_manager );
/**
* Writes the TLM marker (Tile Length Marker)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_tlm( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes the SOT marker (Start of tile-part)
*
* @param p_j2k J2K codec.
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot( opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads values from a SOT marker (Start of tile-part)
*
* the j2k decoder state is not affected. No side effects, no checks except for p_header_size.
*
* @param p_header_data the data contained in the SOT marker.
* @param p_header_size the size of the data contained in the SOT marker.
* @param p_tile_no Isot.
* @param p_tot_len Psot.
* @param p_current_part TPsot.
* @param p_num_parts TNsot.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager );
/**
* Reads a SOT marker (Start of tile-part)
*
* @param p_header_data the data contained in the SOT marker.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sot ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Writes the SOD marker (Start of data)
*
* @param p_j2k J2K codec.
* @param p_tile_coder FIXME DOC
* @param p_data FIXME DOC
* @param p_data_written FIXME DOC
* @param p_total_data_size FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod( opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a SOD marker (Start Of Data)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_sod( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
static void opj_j2k_update_tlm (opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size )
{
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,p_j2k->m_current_tile_number,1); /* PSOT */
++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current;
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current,p_tile_part_size,4); /* PSOT */
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4;
}
/**
* Writes the RGN marker (Region Of Interest)
*
* @param p_tile_no the tile to output
* @param p_comp_no the component to output
* @param nb_comps the number of components
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_rgn( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn (opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Writes the EOC marker (End of Codestream)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_eoc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
#if 0
/**
* Reads a EOC marker (End Of Codestream)
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_eoc ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
#endif
/**
* Writes the CBD-MCT-MCC-MCO markers (Multi components transform)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_data_group( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Inits the Info
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_init_info( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
Add main header marker information
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ;
/**
Add tile header marker information
@param tileno tile index number
@param cstr_index Codestream information structure
@param type marker type
@param pos byte offset of marker segment
@param len length of marker segment
*/
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno, opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len);
/**
* Reads an unknown marker
*
* @param p_j2k the jpeg2000 codec.
* @param p_stream the stream object to read from.
* @param output_marker FIXME DOC
* @param p_manager the user event manager.
*
* @return true if the marker could be deduced.
*/
static OPJ_BOOL opj_j2k_read_unk( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager );
/**
* Writes the MCT marker (Multiple Component Transform)
*
* @param p_j2k J2K codec.
* @param p_mct_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mct_record( opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Writes the MCC marker (Multiple Component Collection)
*
* @param p_j2k J2K codec.
* @param p_mcc_record FIXME DOC
* @param p_stream the stream to write data to.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mcc_record( opj_j2k_t *p_j2k,
opj_simple_mcc_decorrelation_data_t * p_mcc_record,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a MCC marker (Multiple Component Collection)
*
* @param p_header_data the data contained in the MCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mcc ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
/**
* Writes the MCO marker (Multiple component transformation ordering)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image, OPJ_UINT32 p_index);
static void opj_j2k_read_int16_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int16_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_int32_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float32_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_read_float64_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int16 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static void opj_j2k_write_float_to_float64 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
/**
* Ends the encoding, i.e. frees memory.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_end_encoding( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes the CBD marker (Component bit depth definition)
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_cbd( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager);
/**
* Writes COC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_coc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes QCC marker for each component.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_all_qcc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes regions of interests.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_regions( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Writes EPC ????
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_write_epc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager );
/**
* Checks the progression order changes values. Tells of the poc given as input are valid.
* A nice message is outputted at errors.
*
* @param p_pocs the progression order changes.
* @param p_nb_pocs the number of progression order changes.
* @param p_nb_resolutions the number of resolutions.
* @param numcomps the number of components
* @param numlayers the number of layers.
* @param p_manager the user event manager.
*
* @return true if the pocs are valid.
*/
static OPJ_BOOL opj_j2k_check_poc_val( const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 numcomps,
OPJ_UINT32 numlayers,
opj_event_mgr_t * p_manager);
/**
* Gets the number of tile parts used for the given change of progression (if any) and the given tile.
*
* @param cp the coding parameters.
* @param pino the offset of the given poc (i.e. its position in the coding parameter).
* @param tileno the given tile.
*
* @return the number of tile parts.
*/
static OPJ_UINT32 opj_j2k_get_num_tp( opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno);
/**
* Calculates the total number of tile parts needed by the encoder to
* encode such an image. If not enough memory is available, then the function return false.
*
* @param p_nb_tiles pointer that will hold the number of tile parts.
* @param cp the coding parameters for the image.
* @param image the image to encode.
* @param p_j2k the p_j2k encoder.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_calculate_tp( opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager);
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream);
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream);
static opj_codestream_index_t* opj_j2k_create_cstr_index(void);
static OPJ_FLOAT32 opj_j2k_get_tp_stride (opj_tcp_t * p_tcp);
static OPJ_FLOAT32 opj_j2k_get_default_stride (opj_tcp_t * p_tcp);
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager);
/**
* Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
*
* @param p_stream the stream to read data from.
* @param tile_no tile number we're looking for.
* @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction.
* @param p_manager the user event manager.
*
* @return true if the function was successful, false else.
*/
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t *p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed, opj_event_mgr_t * p_manager );
/*@}*/
/*@}*/
/* ----------------------------------------------------------------------- */
typedef struct j2k_prog_order{
OPJ_PROG_ORDER enum_prog;
char str_prog[5];
}j2k_prog_order_t;
static j2k_prog_order_t j2k_prog_order_list[] = {
{OPJ_CPRL, "CPRL"},
{OPJ_LRCP, "LRCP"},
{OPJ_PCRL, "PCRL"},
{OPJ_RLCP, "RLCP"},
{OPJ_RPCL, "RPCL"},
{(OPJ_PROG_ORDER)-1, ""}
};
/**
* FIXME DOC
*/
static const OPJ_UINT32 MCT_ELEMENT_SIZE [] =
{
2,
4,
4,
8
};
typedef void (* opj_j2k_mct_function) (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem);
static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] =
{
opj_j2k_read_int16_to_float,
opj_j2k_read_int32_to_float,
opj_j2k_read_float32_to_float,
opj_j2k_read_float64_to_float
};
static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] =
{
opj_j2k_read_int16_to_int32,
opj_j2k_read_int32_to_int32,
opj_j2k_read_float32_to_int32,
opj_j2k_read_float64_to_int32
};
static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] =
{
opj_j2k_write_float_to_int16,
opj_j2k_write_float_to_int32,
opj_j2k_write_float_to_float,
opj_j2k_write_float_to_float64
};
typedef struct opj_dec_memory_marker_handler
{
/** marker value */
OPJ_UINT32 id;
/** value of the state when the marker can appear */
OPJ_UINT32 states;
/** action linked to the marker */
OPJ_BOOL (*handler) ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager );
}
opj_dec_memory_marker_handler_t;
static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] =
{
{J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot},
{J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod},
{J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc},
{J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn},
{J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd},
{J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc},
{J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc},
{J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz},
{J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm},
{J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm},
{J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt},
{J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm},
{J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt},
{J2K_MS_SOP, 0, 0},
{J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg},
{J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com},
{J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct},
{J2K_MS_CBD, J2K_STATE_MH , opj_j2k_read_cbd},
{J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc},
{J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco},
#ifdef USE_JPWL
#ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */
{J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc},
{J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb},
{J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd},
{J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red},
#endif
#endif /* USE_JPWL */
#ifdef USE_JPSEC
{J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec},
{J2K_MS_INSEC, 0, j2k_read_insec}
#endif /* USE_JPSEC */
{J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/
};
static void opj_j2k_read_int16_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_bytes(l_src_data,&l_temp,2);
l_src_data+=sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int32_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_bytes(l_src_data,&l_temp,4);
l_src_data+=sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_float32_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_float(l_src_data,&l_temp);
l_src_data+=sizeof(OPJ_FLOAT32);
*(l_dest_data++) = l_temp;
}
}
static void opj_j2k_read_float64_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_double(l_src_data,&l_temp);
l_src_data+=sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_FLOAT32) l_temp;
}
}
static void opj_j2k_read_int16_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_bytes(l_src_data,&l_temp,2);
l_src_data+=sizeof(OPJ_INT16);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_int32_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_bytes(l_src_data,&l_temp,4);
l_src_data+=sizeof(OPJ_INT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float32_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_float(l_src_data,&l_temp);
l_src_data+=sizeof(OPJ_FLOAT32);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_read_float64_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data;
OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i=0;i<p_nb_elem;++i) {
opj_read_double(l_src_data,&l_temp);
l_src_data+=sizeof(OPJ_FLOAT64);
*(l_dest_data++) = (OPJ_INT32) l_temp;
}
}
static void opj_j2k_write_float_to_int16 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
l_temp = (OPJ_UINT32) *(l_src_data++);
opj_write_bytes(l_dest_data,l_temp,sizeof(OPJ_INT16));
l_dest_data+=sizeof(OPJ_INT16);
}
}
static void opj_j2k_write_float_to_int32 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_UINT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
l_temp = (OPJ_UINT32) *(l_src_data++);
opj_write_bytes(l_dest_data,l_temp,sizeof(OPJ_INT32));
l_dest_data+=sizeof(OPJ_INT32);
}
}
static void opj_j2k_write_float_to_float (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT32 l_temp;
for (i=0;i<p_nb_elem;++i) {
l_temp = (OPJ_FLOAT32) *(l_src_data++);
opj_write_float(l_dest_data,l_temp);
l_dest_data+=sizeof(OPJ_FLOAT32);
}
}
static void opj_j2k_write_float_to_float64 (const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem)
{
OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data;
OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data;
OPJ_UINT32 i;
OPJ_FLOAT64 l_temp;
for (i=0;i<p_nb_elem;++i) {
l_temp = (OPJ_FLOAT64) *(l_src_data++);
opj_write_double(l_dest_data,l_temp);
l_dest_data+=sizeof(OPJ_FLOAT64);
}
}
char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order){
j2k_prog_order_t *po;
for(po = j2k_prog_order_list; po->enum_prog != -1; po++ ){
if(po->enum_prog == prg_order){
return po->str_prog;
}
}
return po->str_prog;
}
static OPJ_BOOL opj_j2k_check_poc_val( const opj_poc_t *p_pocs,
OPJ_UINT32 p_nb_pocs,
OPJ_UINT32 p_nb_resolutions,
OPJ_UINT32 p_num_comps,
OPJ_UINT32 p_num_layers,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32* packet_array;
OPJ_UINT32 index , resno, compno, layno;
OPJ_UINT32 i;
OPJ_UINT32 step_c = 1;
OPJ_UINT32 step_r = p_num_comps * step_c;
OPJ_UINT32 step_l = p_nb_resolutions * step_r;
OPJ_BOOL loss = OPJ_FALSE;
OPJ_UINT32 layno0 = 0;
packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers, sizeof(OPJ_UINT32));
if (packet_array == 00) {
opj_event_msg(p_manager , EVT_ERROR, "Not enough memory for checking the poc values.\n");
return OPJ_FALSE;
}
if (p_nb_pocs == 0) {
opj_free(packet_array);
return OPJ_TRUE;
}
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno)
{
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
/* iterate through all the pocs */
for (i = 1; i < p_nb_pocs ; ++i) {
OPJ_UINT32 l_last_layno1 = (p_pocs-1)->layno1 ;
layno0 = (p_pocs->layno1 > l_last_layno1)? l_last_layno1 : 0;
index = step_r * p_pocs->resno0;
/* take each resolution for each poc */
for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;
/* take each comp of each resolution for each poc */
for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
OPJ_UINT32 comp_index = res_index + layno0 * step_l;
/* and finally take each layer of each res of ... */
for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
/*index = step_r * resno + step_c * compno + step_l * layno;*/
packet_array[comp_index] = 1;
comp_index += step_l;
}
res_index += step_c;
}
index += step_r;
}
++p_pocs;
}
index = 0;
for (layno = 0; layno < p_num_layers ; ++layno) {
for (resno = 0; resno < p_nb_resolutions; ++resno) {
for (compno = 0; compno < p_num_comps; ++compno) {
loss |= (packet_array[index]!=1);
/*index = step_r * resno + step_c * compno + step_l * layno;*/
index += step_c;
}
}
}
if (loss) {
opj_event_msg(p_manager , EVT_ERROR, "Missing packets possible loss of data\n");
}
opj_free(packet_array);
return !loss;
}
/* ----------------------------------------------------------------------- */
static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno)
{
const OPJ_CHAR *prog = 00;
OPJ_INT32 i;
OPJ_UINT32 tpnum = 1;
opj_tcp_t *tcp = 00;
opj_poc_t * l_current_poc = 00;
/* preconditions */
assert(tileno < (cp->tw * cp->th));
assert(pino < (cp->tcps[tileno].numpocs + 1));
/* get the given tile coding parameter */
tcp = &cp->tcps[tileno];
assert(tcp != 00);
l_current_poc = &(tcp->pocs[pino]);
assert(l_current_poc != 0);
/* get the progression order as a character string */
prog = opj_j2k_convert_progression_order(tcp->prg);
assert(strlen(prog) > 0);
if (cp->m_specific_param.m_enc.m_tp_on == 1) {
for (i=0;i<4;++i) {
switch (prog[i])
{
/* component wise */
case 'C':
tpnum *= l_current_poc->compE;
break;
/* resolution wise */
case 'R':
tpnum *= l_current_poc->resE;
break;
/* precinct wise */
case 'P':
tpnum *= l_current_poc->prcE;
break;
/* layer wise */
case 'L':
tpnum *= l_current_poc->layE;
break;
}
/* whould we split here ? */
if ( cp->m_specific_param.m_enc.m_tp_flag == prog[i] ) {
cp->m_specific_param.m_enc.m_tp_pos=i;
break;
}
}
}
else {
tpnum=1;
}
return tpnum;
}
static OPJ_BOOL opj_j2k_calculate_tp( opj_j2k_t *p_j2k,
opj_cp_t *cp,
OPJ_UINT32 * p_nb_tiles,
opj_image_t *image,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 pino,tileno;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t *tcp;
/* preconditions */
assert(p_nb_tiles != 00);
assert(cp != 00);
assert(image != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_nb_tiles = cp->tw * cp->th;
* p_nb_tiles = 0;
tcp = cp->tcps;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*if (p_j2k->cstr_info) {
opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile;
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image,cp,tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino)
{
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t));
if (l_info_tile_ptr->tp == 00) {
return OPJ_FALSE;
}
memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t));
l_info_tile_ptr->num_tps = cur_totnum_tp;
++l_info_tile_ptr;
++tcp;
}
}
else */{
for (tileno = 0; tileno < l_nb_tiles; ++tileno) {
OPJ_UINT32 cur_totnum_tp = 0;
opj_pi_update_encoding_parameters(image,cp,tileno);
for (pino = 0; pino <= tcp->numpocs; ++pino) {
OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno);
*p_nb_tiles = *p_nb_tiles + tp_num;
cur_totnum_tp += tp_num;
}
tcp->m_nb_tile_parts = cur_totnum_tp;
++tcp;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_soc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
/* 2 bytes will be written */
OPJ_BYTE * l_start_stream = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_start_stream,J2K_MS_SOC,2);
if (opj_stream_write_data(p_stream,l_start_stream,2,p_manager) != 2) {
return OPJ_FALSE;
}
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2);
*/
assert( 0 && "TODO" );
#endif /* USE_JPWL */
/* <<UniPG */
return OPJ_TRUE;
}
/**
* Reads a SOC marker (Start of Codestream)
* @param p_j2k the jpeg2000 file codec.
* @param p_stream FIXME DOC
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_soc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE l_data [2];
OPJ_UINT32 l_marker;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (opj_stream_read_data(p_stream,l_data,2,p_manager) != 2) {
return OPJ_FALSE;
}
opj_read_bytes(l_data,&l_marker,2);
if (l_marker != J2K_MS_SOC) {
return OPJ_FALSE;
}
/* Next marker should be a SIZ marker in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ;
/* FIXME move it in a index structure included in p_j2k*/
p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2;
opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n", p_j2k->cstr_index->main_head_start);
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC, p_j2k->cstr_index->main_head_start, 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_siz( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 i;
OPJ_UINT32 l_size_len;
OPJ_BYTE * l_current_ptr;
opj_image_t * l_image = 00;
opj_cp_t *cp = 00;
opj_image_comp_t * l_img_comp = 00;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
cp = &(p_j2k->m_cp);
l_size_len = 40 + 3 * l_image->numcomps;
l_img_comp = l_image->comps;
if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* write SOC identifier */
opj_write_bytes(l_current_ptr,J2K_MS_SIZ,2); /* SIZ */
l_current_ptr+=2;
opj_write_bytes(l_current_ptr,l_size_len-2,2); /* L_SIZ */
l_current_ptr+=2;
opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */
l_current_ptr+=2;
opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */
l_current_ptr+=4;
opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */
l_current_ptr+=2;
for (i = 0; i < l_image->numcomps; ++i) {
/* TODO here with MCT ? */
opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7), 1); /* Ssiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */
++l_current_ptr;
opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */
++l_current_ptr;
++l_img_comp;
}
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_size_len,p_manager) != l_size_len) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a SIZ marker (image and tile size)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the SIZ box.
* @param p_header_size the size of the data contained in the SIZ marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_comp_remain;
OPJ_UINT32 l_remaining_size;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_tmp, l_tx1, l_ty1;
opj_image_t *l_image = 00;
opj_cp_t *l_cp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcp_t * l_current_tile_param = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* minimum size == 39 - 3 (= minimum component parameter) */
if (p_header_size < 36) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
l_remaining_size = p_header_size - 36;
l_nb_comp = l_remaining_size / 3;
l_nb_comp_remain = l_remaining_size % 3;
if (l_nb_comp_remain != 0){
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_tmp ,2); /* Rsiz (capabilities) */
p_header_data+=2;
l_cp->rsiz = (OPJ_UINT16) l_tmp;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx, 4); /* XTsiz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy, 4); /* YTsiz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0, 4); /* XT0siz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0, 4); /* YT0siz */
p_header_data+=4;
opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp, 2); /* Csiz */
p_header_data+=2;
if (l_tmp < 16385)
l_image->numcomps = (OPJ_UINT16) l_tmp;
else {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is illegal -> %d\n", l_tmp);
return OPJ_FALSE;
}
if (l_image->numcomps != l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n", l_image->numcomps, l_nb_comp);
return OPJ_FALSE;
}
/* testcase 4035.pdf.SIGSEGV.d8b.3375 */
/* testcase issue427-null-image-size.jp2 */
if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64 ")\n", (OPJ_INT64)l_image->x1 - l_image->x0, (OPJ_INT64)l_image->y1 - l_image->y0);
return OPJ_FALSE;
}
/* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */
if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx, l_cp->tdy);
return OPJ_FALSE;
}
/* testcase 1610.pdf.SIGSEGV.59c.681 */
if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) {
opj_event_msg(p_manager, EVT_ERROR, "Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1);
return OPJ_FALSE;
}
/* testcase issue427-illegal-tile-offset.jp2 */
l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */
l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */
if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) || (l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0) ) {
opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: illegal tile offset\n");
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if (!(l_image->x1 * l_image->y1)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad image size (%d x %d)\n",
l_image->x1, l_image->y1);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
/* FIXME check previously in the function so why keep this piece of code ? Need by the norm ?
if (l_image->numcomps != ((len - 38) / 3)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n",
l_image->numcomps, ((len - 38) / 3));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
*/ /* we try to correct */
/* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n");
if (l_image->numcomps < ((len - 38) / 3)) {
len = 38 + 3 * l_image->numcomps;
opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n",
len);
} else {
l_image->numcomps = ((len - 38) / 3);
opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n",
l_image->numcomps);
}
}
*/
/* update components number in the jpwl_exp_comps filed */
l_cp->exp_comps = l_image->numcomps;
}
#endif /* USE_JPWL */
/* Allocate the resulting image components */
l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps, sizeof(opj_image_comp_t));
if (l_image->comps == 00){
l_image->numcomps = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
l_img_comp = l_image->comps;
/* Read the component information */
for (i = 0; i < l_image->numcomps; ++i){
OPJ_UINT32 tmp;
opj_read_bytes(p_header_data,&tmp,1); /* Ssiz_i */
++p_header_data;
l_img_comp->prec = (tmp & 0x7f) + 1;
l_img_comp->sgnd = tmp >> 7;
opj_read_bytes(p_header_data,&tmp,1); /* XRsiz_i */
++p_header_data;
l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
opj_read_bytes(p_header_data,&tmp,1); /* YRsiz_i */
++p_header_data;
l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */
if( l_img_comp->dx < 1 || l_img_comp->dx > 255 ||
l_img_comp->dy < 1 || l_img_comp->dy > 255 ) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n",
i, l_img_comp->dx, l_img_comp->dy);
return OPJ_FALSE;
}
if( l_img_comp->prec < 1 || l_img_comp->prec > 38) { /* TODO openjpeg won't handle more than ? */
opj_event_msg(p_manager, EVT_ERROR,
"Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm)\n",
i, l_img_comp->prec);
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters, again */
if (!(l_image->comps[i].dx * l_image->comps[i].dy)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n",
i, i, l_image->comps[i].dx, l_image->comps[i].dy);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (!l_image->comps[i].dx) {
l_image->comps[i].dx = 1;
opj_event_msg(p_manager, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dx);
}
if (!l_image->comps[i].dy) {
l_image->comps[i].dy = 1;
opj_event_msg(p_manager, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n",
i, l_image->comps[i].dy);
}
}
}
#endif /* USE_JPWL */
l_img_comp->resno_decoded = 0; /* number of resolution decoded */
l_img_comp->factor = l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */
++l_img_comp;
}
/* Compute the number of tiles */
l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0), (OPJ_INT32)l_cp->tdx);
l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0), (OPJ_INT32)l_cp->tdy);
/* Check that the number of tiles is valid */
if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) {
opj_event_msg( p_manager, EVT_ERROR,
"Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n",
l_cp->tw, l_cp->th);
return OPJ_FALSE;
}
l_nb_tiles = l_cp->tw * l_cp->th;
/* Define the tiles which will be decoded */
if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = (p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = (p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0), (OPJ_INT32)l_cp->tdx);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0), (OPJ_INT32)l_cp->tdy);
}
else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether TX errors have damaged
too much the SIZ parameters */
if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) || (l_cp->th > l_cp->max_tiles)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of tiles (%d x %d)\n",
l_cp->tw, l_cp->th);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n");
if (l_cp->tw < 1) {
l_cp->tw= 1;
opj_event_msg(p_manager, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->tw);
}
if (l_cp->tw > l_cp->max_tiles) {
l_cp->tw= 1;
opj_event_msg(p_manager, EVT_WARNING, "- too large x, increase expectance of %d\n"
"- setting %d tiles in x => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->tw);
}
if (l_cp->th < 1) {
l_cp->th= 1;
opj_event_msg(p_manager, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->th);
}
if (l_cp->th > l_cp->max_tiles) {
l_cp->th= 1;
opj_event_msg(p_manager, EVT_WARNING, "- too large y, increase expectance of %d to continue\n",
"- setting %d tiles in y => HYPOTHESIS!!!\n",
l_cp->max_tiles, l_cp->th);
}
}
}
#endif /* USE_JPWL */
/* memory allocations */
l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t));
if (l_cp->tcps == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
#ifdef USE_JPWL
if (l_cp->correct) {
if (!l_cp->tcps) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: could not alloc tcps field of cp\n");
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
}
#endif /* USE_JPWL */
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps =
(opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
if(p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records =
(opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS ,sizeof(opj_mct_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records = OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records =
(opj_simple_mcc_decorrelation_data_t*)
opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS, sizeof(opj_simple_mcc_decorrelation_data_t));
if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records = OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
/* set up default dc level shift */
for (i=0;i<l_image->numcomps;++i) {
if (! l_image->comps[i].sgnd) {
p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1 << (l_image->comps[i].prec - 1);
}
}
l_current_tile_param = l_cp->tcps;
for (i = 0; i < l_nb_tiles; ++i) {
l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t));
if (l_current_tile_param->tccps == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n");
return OPJ_FALSE;
}
++l_current_tile_param;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH; /* FIXME J2K_DEC_STATE_MH; */
opj_image_comp_header_update(l_image,l_cp);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_com( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_comment_size;
OPJ_UINT32 l_total_com_size;
const OPJ_CHAR *l_comment;
OPJ_BYTE * l_current_ptr = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_comment = p_j2k->m_cp.comment;
l_comment_size = (OPJ_UINT32)strlen(l_comment);
l_total_com_size = l_comment_size + 6;
if (l_total_com_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write the COM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size;
}
l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_ptr,J2K_MS_COM , 2); /* COM */
l_current_ptr+=2;
opj_write_bytes(l_current_ptr,l_total_com_size - 2 , 2); /* L_COM */
l_current_ptr+=2;
opj_write_bytes(l_current_ptr,1 , 2); /* General use (IS 8859-15:1999 (Latin) values) */
l_current_ptr+=2;
memcpy( l_current_ptr,l_comment,l_comment_size);
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_total_com_size,p_manager) != l_total_com_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COM marker (comments)
* @param p_j2k the jpeg2000 file codec.
* @param p_header_data the data contained in the COM box.
* @param p_header_size the size of the data contained in the COM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_com ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
(void)p_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cod( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_code_size,l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k,p_j2k->m_current_tile_number,0);
l_remaining_size = l_code_size;
if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_COD,2); /* COD */
l_current_data += 2;
opj_write_bytes(l_current_data,l_code_size-2,2); /* L_COD */
l_current_data += 2;
opj_write_bytes(l_current_data,l_tcp->csty,1); /* Scod */
++l_current_data;
opj_write_bytes(l_current_data,(OPJ_UINT32)l_tcp->prg,1); /* SGcod (A) */
++l_current_data;
opj_write_bytes(l_current_data,l_tcp->numlayers,2); /* SGcod (B) */
l_current_data+=2;
opj_write_bytes(l_current_data,l_tcp->mct,1); /* SGcod (C) */
++l_current_data;
l_remaining_size -= 9;
if (! opj_j2k_write_SPCod_SPCoc(p_j2k,p_j2k->m_current_tile_number,0,l_current_data,&l_remaining_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_code_size,p_manager) != l_code_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a COD marker (Coding Styke defaults)
* @param p_header_data the data contained in the COD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cod ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop */
OPJ_UINT32 i;
OPJ_UINT32 l_tmp;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_image_t *l_image = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_cp = &(p_j2k->m_cp);
/* If we are in the first tile-part header of the current tile */
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* Only one COD per tile */
if (l_tcp->cod) {
opj_event_msg(p_manager, EVT_ERROR, "COD marker already read. No more than one COD marker per tile.\n");
return OPJ_FALSE;
}
l_tcp->cod = 1;
/* Make sure room is sufficient */
if (p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_tcp->csty,1); /* Scod */
++p_header_data;
/* Make sure we know how to decode this */
if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP | J2K_CP_CSTY_EPH)) != 0U) {
opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_tmp,1); /* SGcod (A) */
++p_header_data;
l_tcp->prg = (OPJ_PROG_ORDER) l_tmp;
/* Make sure progression order is valid */
if (l_tcp->prg > OPJ_CPRL ) {
opj_event_msg(p_manager, EVT_ERROR, "Unknown progression order in COD marker\n");
l_tcp->prg = OPJ_PROG_UNKNOWN;
}
opj_read_bytes(p_header_data,&l_tcp->numlayers,2); /* SGcod (B) */
p_header_data+=2;
if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid number of layers in COD marker : %d not in range [1-65535]\n", l_tcp->numlayers);
return OPJ_FALSE;
}
/* If user didn't set a number layer to decode take the max specify in the codestream. */
if (l_cp->m_specific_param.m_dec.m_layer) {
l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
}
else {
l_tcp->num_layers_to_decode = l_tcp->numlayers;
}
opj_read_bytes(p_header_data,&l_tcp->mct,1); /* SGcod (C) */
++p_header_data;
p_header_size -= 5;
for (i = 0; i < l_image->numcomps; ++i) {
l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
}
if (! opj_j2k_read_SPCod_SPCoc(p_j2k,0,p_header_data,&p_header_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n");
return OPJ_FALSE;
}
/* Apply the coding style to other components of the current tile or the m_default_tcp*/
opj_j2k_copy_tile_component_parameters(p_j2k);
/* Index */
#ifdef WIP_REMOVE_MSD
if (p_j2k->cstr_info) {
/*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/
p_j2k->cstr_info->prog = l_tcp->prg;
p_j2k->cstr_info->numlayers = l_tcp->numlayers;
p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(l_image->numcomps * sizeof(OPJ_UINT32));
if(!p_j2k->cstr_info->numdecompos){
return OPJ_FALSE;
}
for (i = 0; i < l_image->numcomps; ++i) {
p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1;
}
}
#endif
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_coc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 l_coc_size,l_remaining_size;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,p_j2k->m_current_tile_number,p_comp_no);
if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data;
/*p_j2k->m_specific_param.m_encoder.m_header_tile_data
= (OPJ_BYTE*)opj_realloc(
p_j2k->m_specific_param.m_encoder.m_header_tile_data,
l_coc_size);*/
new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size;
}
opj_j2k_write_coc_in_memory(p_j2k,p_comp_no,p_j2k->m_specific_param.m_encoder.m_header_tile_data,&l_remaining_size,p_manager);
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_coc_size,p_manager) != l_coc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) {
return OPJ_FALSE;
}
return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_coc_in_memory( opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_coc_size,l_remaining_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_image = p_j2k->m_private_image;
l_comp_room = (l_image->numcomps <= 256) ? 1 : 2;
l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k,p_j2k->m_current_tile_number,p_comp_no);
l_remaining_size = l_coc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data,J2K_MS_COC,2); /* COC */
l_current_data += 2;
opj_write_bytes(l_current_data,l_coc_size-2,2); /* L_COC */
l_current_data += 2;
opj_write_bytes(l_current_data,p_comp_no, l_comp_room); /* Ccoc */
l_current_data+=l_comp_room;
opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty, 1); /* Scoc */
++l_current_data;
l_remaining_size -= (5 + l_comp_room);
opj_j2k_write_SPCod_SPCoc(p_j2k,p_j2k->m_current_tile_number,0,l_current_data,&l_remaining_size,p_manager);
* p_data_written = l_coc_size;
}
static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k)
{
OPJ_UINT32 i,j;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
/* preconditions */
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
l_nb_comp = p_j2k->m_private_image->numcomps;
for (i=0;i<l_nb_tiles;++i) {
for (j=0;j<l_nb_comp;++j) {
l_max = opj_uint_max(l_max,opj_j2k_get_SPCod_SPCoc_size(p_j2k,i,j));
}
}
return 6 + l_max;
}
/**
* Reads a COC marker (Coding Style Component)
* @param p_header_data the data contained in the COC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the COC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_coc ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_image_t *l_image = NULL;
OPJ_UINT32 l_comp_room;
OPJ_UINT32 l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ) ? /*FIXME J2K_DEC_STATE_TPH*/
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_image = p_j2k->m_private_image;
l_comp_room = l_image->numcomps <= 256 ? 1 : 2;
/* make sure room is sufficient*/
if (p_header_size < l_comp_room + 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
p_header_size -= l_comp_room + 1;
opj_read_bytes(p_header_data,&l_comp_no,l_comp_room); /* Ccoc */
p_header_data += l_comp_room;
if (l_comp_no >= l_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker (bad number of components)\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_tcp->tccps[l_comp_no].csty,1); /* Scoc */
++p_header_data ;
if (! opj_j2k_read_SPCod_SPCoc(p_j2k,l_comp_no,p_header_data,&p_header_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcd( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcd_size,l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k,p_j2k->m_current_tile_number,0);
l_remaining_size = l_qcd_size;
if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_QCD,2); /* QCD */
l_current_data += 2;
opj_write_bytes(l_current_data,l_qcd_size-2,2); /* L_QCD */
l_current_data += 2;
l_remaining_size -= 4;
if (! opj_j2k_write_SQcd_SQcc(p_j2k,p_j2k->m_current_tile_number,0,l_current_data,&l_remaining_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (l_remaining_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n");
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_qcd_size,p_manager) != l_qcd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a QCD marker (Quantization defaults)
* @param p_header_data the data contained in the QCD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcd ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_read_SQcd_SQcc(p_j2k,0,p_header_data,&p_header_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n");
return OPJ_FALSE;
}
/* Apply the quantization parameters to other components of the current tile or the m_default_tcp */
opj_j2k_copy_tile_quantization_parameters(p_j2k);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_qcc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size,l_remaining_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k,p_j2k->m_current_tile_number,p_comp_no);
l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0:1;
l_remaining_size = l_qcc_size;
if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size;
}
opj_j2k_write_qcc_in_memory(p_j2k,p_comp_no,p_j2k->m_specific_param.m_encoder.m_header_tile_data,&l_remaining_size,p_manager);
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_qcc_size,p_manager) != l_qcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
return opj_j2k_compare_SQcd_SQcc(p_j2k,p_j2k->m_current_tile_number,p_first_comp_no, p_second_comp_no);
}
static void opj_j2k_write_qcc_in_memory( opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_qcc_size,l_remaining_size;
OPJ_BYTE * l_current_data = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k,p_j2k->m_current_tile_number,p_comp_no);
l_remaining_size = l_qcc_size;
l_current_data = p_data;
opj_write_bytes(l_current_data,J2K_MS_QCC,2); /* QCC */
l_current_data += 2;
if (p_j2k->m_private_image->numcomps <= 256) {
--l_qcc_size;
opj_write_bytes(l_current_data,l_qcc_size-2,2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */
++l_current_data;
/* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */
l_remaining_size -= 6;
}
else {
opj_write_bytes(l_current_data,l_qcc_size-2,2); /* L_QCC */
l_current_data += 2;
opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */
l_current_data+=2;
l_remaining_size -= 6;
}
opj_j2k_write_SQcd_SQcc(p_j2k,p_j2k->m_current_tile_number,p_comp_no,l_current_data,&l_remaining_size,p_manager);
*p_data_written = l_qcc_size;
}
static OPJ_UINT32 opj_j2k_get_max_qcc_size (opj_j2k_t *p_j2k)
{
return opj_j2k_get_max_coc_size(p_j2k);
}
/**
* Reads a QCC marker (Quantization component)
* @param p_header_data the data contained in the QCC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the QCC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_qcc( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_num_comp,l_comp_no;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (l_num_comp <= 256) {
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_comp_no,1);
++p_header_data;
--p_header_size;
}
else {
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_comp_no,2);
p_header_data+=2;
p_header_size-=2;
}
#ifdef USE_JPWL
if (p_j2k->m_cp.correct) {
static OPJ_UINT32 backup_compno = 0;
/* compno is negative or larger than the number of components!!! */
if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in QCC (%d out of a maximum of %d)\n",
l_comp_no, l_num_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_comp_no = backup_compno % l_num_comp;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting component number to %d\n",
l_comp_no);
}
/* keep your private count of tiles */
backup_compno++;
};
#endif /* USE_JPWL */
if (l_comp_no >= p_j2k->m_private_image->numcomps) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid component number: %d, regarding the number of components %d\n",
l_comp_no, p_j2k->m_private_image->numcomps);
return OPJ_FALSE;
}
if (! opj_j2k_read_SQcd_SQcc(p_j2k,l_comp_no,p_header_data,&p_header_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_poc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
OPJ_UINT32 l_written_size = 0;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_nb_comp = p_j2k->m_private_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
}
else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size;
}
opj_j2k_write_poc_in_memory(p_j2k,p_j2k->m_specific_param.m_encoder.m_header_tile_data,&l_written_size,p_manager);
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_poc_size,p_manager) != l_poc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_j2k_write_poc_in_memory( opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_comp;
OPJ_UINT32 l_nb_poc;
OPJ_UINT32 l_poc_size;
opj_image_t *l_image = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
opj_poc_t *l_current_poc = 00;
OPJ_UINT32 l_poc_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number];
l_tccp = &l_tcp->tccps[0];
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
l_nb_poc = 1 + l_tcp->numpocs;
if (l_nb_comp <= 256) {
l_poc_room = 1;
}
else {
l_poc_room = 2;
}
l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc;
l_current_data = p_data;
opj_write_bytes(l_current_data,J2K_MS_POC,2); /* POC */
l_current_data += 2;
opj_write_bytes(l_current_data,l_poc_size-2,2); /* Lpoc */
l_current_data += 2;
l_current_poc = l_tcp->pocs;
for (i = 0; i < l_nb_poc; ++i) {
opj_write_bytes(l_current_data,l_current_poc->resno0,1); /* RSpoc_i */
++l_current_data;
opj_write_bytes(l_current_data,l_current_poc->compno0,l_poc_room); /* CSpoc_i */
l_current_data+=l_poc_room;
opj_write_bytes(l_current_data,l_current_poc->layno1,2); /* LYEpoc_i */
l_current_data+=2;
opj_write_bytes(l_current_data,l_current_poc->resno1,1); /* REpoc_i */
++l_current_data;
opj_write_bytes(l_current_data,l_current_poc->compno1,l_poc_room); /* CEpoc_i */
l_current_data+=l_poc_room;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg,1); /* Ppoc_i */
++l_current_data;
/* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/
l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers);
l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions);
l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32)l_current_poc->compno1, (OPJ_INT32)l_nb_comp);
++l_current_poc;
}
*p_data_written = l_poc_size;
}
static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k)
{
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 l_nb_tiles = 0;
OPJ_UINT32 l_max_poc = 0;
OPJ_UINT32 i;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
for (i=0;i<l_nb_tiles;++i) {
l_max_poc = opj_uint_max(l_max_poc,l_tcp->numpocs);
++l_tcp;
}
++l_max_poc;
return 4 + 9 * l_max_poc;
}
static OPJ_UINT32 opj_j2k_get_max_toc_size (opj_j2k_t *p_j2k)
{
OPJ_UINT32 i;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max = 0;
opj_tcp_t * l_tcp = 00;
l_tcp = p_j2k->m_cp.tcps;
l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ;
for (i=0;i<l_nb_tiles;++i) {
l_max = opj_uint_max(l_max,l_tcp->m_nb_tile_parts);
++l_tcp;
}
return 12 * l_max;
}
static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k)
{
OPJ_UINT32 l_nb_bytes = 0;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_coc_bytes,l_qcc_bytes;
l_nb_comps = p_j2k->m_private_image->numcomps - 1;
l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k);
if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) {
l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_coc_bytes;
l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
l_nb_bytes += l_nb_comps * l_qcc_bytes;
}
l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);
/*** DEVELOPER CORNER, Add room for your headers ***/
return l_nb_bytes;
}
/**
* Reads a POC marker (Progression Order Change)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_poc ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i, l_nb_comp, l_tmp;
opj_image_t * l_image = 00;
OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining;
OPJ_UINT32 l_chunk_size, l_comp_room;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_poc_t *l_current_poc = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1;
}
else {
l_comp_room = 2;
}
l_chunk_size = 5 + 2 * l_comp_room;
l_current_poc_nb = p_header_size / l_chunk_size;
l_current_poc_remaining = p_header_size % l_chunk_size;
if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0;
l_current_poc_nb += l_old_poc_nb;
if(l_current_poc_nb >= 32)
{
opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb);
return OPJ_FALSE;
}
assert(l_current_poc_nb < 32);
/* now poc is in use.*/
l_tcp->POC = 1;
l_current_poc = &l_tcp->pocs[l_old_poc_nb];
for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) {
opj_read_bytes(p_header_data,&(l_current_poc->resno0),1); /* RSpoc_i */
++p_header_data;
opj_read_bytes(p_header_data,&(l_current_poc->compno0),l_comp_room); /* CSpoc_i */
p_header_data+=l_comp_room;
opj_read_bytes(p_header_data,&(l_current_poc->layno1),2); /* LYEpoc_i */
/* make sure layer end is in acceptable bounds */
l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers);
p_header_data+=2;
opj_read_bytes(p_header_data,&(l_current_poc->resno1),1); /* REpoc_i */
++p_header_data;
opj_read_bytes(p_header_data,&(l_current_poc->compno1),l_comp_room); /* CEpoc_i */
p_header_data+=l_comp_room;
opj_read_bytes(p_header_data,&l_tmp,1); /* Ppoc_i */
++p_header_data;
l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp;
/* make sure comp is in acceptable bounds */
l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp);
++l_current_poc;
}
l_tcp->numpocs = l_current_poc_nb - 1;
return OPJ_TRUE;
}
/**
* Reads a CRG marker (Component registration)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_crg ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_nb_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != l_nb_comp *4) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_nb_comp; ++i)
{
opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i
p_header_data+=2;
opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i
p_header_data+=2;
}
*/
return OPJ_TRUE;
}
/**
* Reads a TLM marker (Tile Length Marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_tlm ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient, l_Ptlm_size;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
p_header_size -= 2;
opj_read_bytes(p_header_data,&l_Ztlm,1); /* Ztlm */
++p_header_data;
opj_read_bytes(p_header_data,&l_Stlm,1); /* Stlm */
++p_header_data;
l_ST = ((l_Stlm >> 4) & 0x3);
l_SP = (l_Stlm >> 6) & 0x1;
l_Ptlm_size = (l_SP + 1) * 2;
l_quotient = l_Ptlm_size + l_ST;
l_tot_num_tp_remaining = p_header_size % l_quotient;
if (l_tot_num_tp_remaining != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n");
return OPJ_FALSE;
}
/* FIXME Do not care of this at the moment since only local variables are set here */
/*
for
(i = 0; i < l_tot_num_tp; ++i)
{
opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i
p_header_data += l_ST;
opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i
p_header_data += l_Ptlm_size;
}*/
return OPJ_TRUE;
}
/**
* Reads a PLM marker (Packet length, main header marker)
*
* @param p_header_data the data contained in the TLM box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the TLM marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plm ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return OPJ_FALSE;
}
/* Do not care of this at the moment since only local variables are set here */
/*
opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm
++p_header_data;
--p_header_size;
while
(p_header_size > 0)
{
opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm
++p_header_data;
p_header_size -= (1+l_Nplm);
if
(p_header_size < 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
for
(i = 0; i < l_Nplm; ++i)
{
opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij
++p_header_data;
// take only the last seven bytes
l_packet_len |= (l_tmp & 0x7f);
if
(l_tmp & 0x80)
{
l_packet_len <<= 7;
}
else
{
// store packet length and proceed to next packet
l_packet_len = 0;
}
}
if
(l_packet_len != 0)
{
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n");
return false;
}
}
*/
return OPJ_TRUE;
}
/**
* Reads a PLT marker (Packet length, tile-part header)
*
* @param p_header_data the data contained in the PLT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PLT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_plt ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_Zplt,1); /* Zplt */
++p_header_data;
--p_header_size;
for (i = 0; i < p_header_size; ++i) {
opj_read_bytes(p_header_data,&l_tmp,1); /* Iplt_ij */
++p_header_data;
/* take only the last seven bytes */
l_packet_len |= (l_tmp & 0x7f);
if (l_tmp & 0x80) {
l_packet_len <<= 7;
}
else {
/* store packet length and proceed to next packet */
l_packet_len = 0;
}
}
if (l_packet_len != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a PPM marker (Packed packet headers, main header)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppm (
opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager )
{
opj_cp_t *l_cp = 00;
OPJ_UINT32 l_Z_ppm;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_cp->ppm = 1;
opj_read_bytes(p_header_data,&l_Z_ppm,1); /* Z_ppm */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_cp->ppm_markers == NULL) { /* first PPM marker */
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
assert(l_cp->ppm_markers_count == 0U);
l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_cp->ppm_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers_count = l_newCount;
} else if (l_cp->ppm_markers_count <= l_Z_ppm) {
OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */
opj_ppx *new_ppm_markers;
new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers, l_newCount * sizeof(opj_ppx));
if (new_ppm_markers == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers = new_ppm_markers;
memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0, (l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx));
l_cp->ppm_markers_count = l_newCount;
}
if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm);
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size;
memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPM markers read (Packed headers, main header)
*
* @param p_cp main coding parameters.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppm ( opj_cp_t *p_cp, opj_event_mgr_t * p_manager )
{
OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining;
/* preconditions */
assert(p_cp != 00);
assert(p_manager != 00);
assert(p_cp->ppm_buffer == NULL);
if (p_cp->ppm == 0U) {
return OPJ_TRUE;
}
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do
{
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data+=4;
l_data_size-=4;
l_ppm_data_size += l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */
if (l_data_size >= l_N_ppm) {
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
}
}
if (l_N_ppm_remaining != 0U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n");
return OPJ_FALSE;
}
p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size);
if (p_cp->ppm_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n");
return OPJ_FALSE;
}
p_cp->ppm_len = l_ppm_data_size;
l_ppm_data_size = 0U;
l_N_ppm_remaining = 0U;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppm */
OPJ_UINT32 l_N_ppm;
OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size;
const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data;
if (l_N_ppm_remaining >= l_data_size) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining -= l_data_size;
l_data_size = 0U;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining);
l_ppm_data_size += l_N_ppm_remaining;
l_data += l_N_ppm_remaining;
l_data_size -= l_N_ppm_remaining;
l_N_ppm_remaining = 0U;
}
if (l_data_size > 0U) {
do
{
/* read Nppm */
if (l_data_size < 4U) {
/* clean up to be done on l_cp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data, &l_N_ppm, 4);
l_data+=4;
l_data_size-=4;
if (l_data_size >= l_N_ppm) {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm);
l_ppm_data_size += l_N_ppm;
l_data_size -= l_N_ppm;
l_data += l_N_ppm;
} else {
memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size);
l_ppm_data_size += l_data_size;
l_N_ppm_remaining = l_N_ppm - l_data_size;
l_data_size = 0U;
}
} while (l_data_size > 0U);
}
opj_free(p_cp->ppm_markers[i].m_data);
p_cp->ppm_markers[i].m_data = NULL;
p_cp->ppm_markers[i].m_data_size = 0U;
}
}
p_cp->ppm_data = p_cp->ppm_buffer;
p_cp->ppm_data_size = p_cp->ppm_len;
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
return OPJ_TRUE;
}
/**
* Reads a PPT marker (Packed packet headers, tile-part header)
*
* @param p_header_data the data contained in the PPT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the PPT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_ppt ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_Z_ppt;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We need to have the Z_ppt element + 1 byte of Ippt at minimum */
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
if (l_cp->ppm){
opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n");
return OPJ_FALSE;
}
l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]);
l_tcp->ppt = 1;
opj_read_bytes(p_header_data,&l_Z_ppt,1); /* Z_ppt */
++p_header_data;
--p_header_size;
/* check allocation needed */
if (l_tcp->ppt_markers == NULL) { /* first PPT marker */
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
assert(l_tcp->ppt_markers_count == 0U);
l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx));
if (l_tcp->ppt_markers == NULL) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers_count = l_newCount;
} else if (l_tcp->ppt_markers_count <= l_Z_ppt) {
OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */
opj_ppx *new_ppt_markers;
new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers, l_newCount * sizeof(opj_ppx));
if (new_ppt_markers == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers = new_ppt_markers;
memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0, (l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx));
l_tcp->ppt_markers_count = l_newCount;
}
if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt);
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size);
if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) {
/* clean up to be done on l_tcp destruction */
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size;
memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size);
return OPJ_TRUE;
}
/**
* Merges all PPT markers read (Packed packet headers, tile-part header)
*
* @param p_tcp the tile.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_ppt_data_size;
/* preconditions */
assert(p_tcp != 00);
assert(p_manager != 00);
assert(p_tcp->ppt_buffer == NULL);
if (p_tcp->ppt == 0U) {
return OPJ_TRUE;
}
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
l_ppt_data_size += p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
}
p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size);
if (p_tcp->ppt_buffer == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n");
return OPJ_FALSE;
}
p_tcp->ppt_len = l_ppt_data_size;
l_ppt_data_size = 0U;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppt */
memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data, p_tcp->ppt_markers[i].m_data_size);
l_ppt_data_size += p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */
opj_free(p_tcp->ppt_markers[i].m_data);
p_tcp->ppt_markers[i].m_data = NULL;
p_tcp->ppt_markers[i].m_data_size = 0U;
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
p_tcp->ppt_data = p_tcp->ppt_buffer;
p_tcp->ppt_data_size = p_tcp->ppt_len;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_tlm( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tlm_size;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 6 + (5*p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
/* change the way data is written to avoid seeking if possible */
/* TODO */
p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream);
opj_write_bytes(l_current_data,J2K_MS_TLM,2); /* TLM */
l_current_data += 2;
opj_write_bytes(l_current_data,l_tlm_size-2,2); /* Lpoc */
l_current_data += 2;
opj_write_bytes(l_current_data,0,1); /* Ztlm=0*/
++l_current_data;
opj_write_bytes(l_current_data,0x50,1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */
++l_current_data;
/* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_tlm_size,p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sot( opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_data,J2K_MS_SOT,2); /* SOT */
p_data += 2;
opj_write_bytes(p_data,10,2); /* Lsot */
p_data += 2;
opj_write_bytes(p_data, p_j2k->m_current_tile_number,2); /* Isot */
p_data += 2;
/* Psot */
p_data += 4;
opj_write_bytes(p_data, p_j2k->m_specific_param.m_encoder.m_current_tile_part_number,1); /* TPsot */
++p_data;
opj_write_bytes(p_data, p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts,1); /* TNsot */
++p_data;
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2);
*/
assert( 0 && "TODO" );
#endif /* USE_JPWL */
* p_data_written = 12;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
OPJ_UINT32* p_tile_no,
OPJ_UINT32* p_tot_len,
OPJ_UINT32* p_current_part,
OPJ_UINT32* p_num_parts,
opj_event_mgr_t * p_manager )
{
/* preconditions */
assert(p_header_data != 00);
assert(p_manager != 00);
/* Size of this marker is fixed = 12 (we have already read marker and its size)*/
if (p_header_size != 8) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,p_tile_no,2); /* Isot */
p_header_data+=2;
opj_read_bytes(p_header_data,p_tot_len,4); /* Psot */
p_header_data+=4;
opj_read_bytes(p_header_data,p_current_part,1); /* TPsot */
++p_header_data;
opj_read_bytes(p_header_data,p_num_parts ,1); /* TNsot */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sot ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager )
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tot_len, l_num_parts = 0;
OPJ_UINT32 l_current_part;
OPJ_UINT32 l_tile_x,l_tile_y;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_j2k_get_sot_values(p_header_data, p_header_size, &(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
/* testcase 2.pdf.SIGFPE.706.1112 */
if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n", p_j2k->m_current_tile_number);
return OPJ_FALSE;
}
l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number];
l_tile_x = p_j2k->m_current_tile_number % l_cp->tw;
l_tile_y = p_j2k->m_current_tile_number / l_cp->tw;
#ifdef USE_JPWL
if (l_cp->correct) {
OPJ_UINT32 tileno = p_j2k->m_current_tile_number;
static OPJ_UINT32 backup_tileno = 0;
/* tileno is negative or larger than the number of tiles!!! */
if (tileno > (l_cp->tw * l_cp->th)) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile number (%d out of a maximum of %d)\n",
tileno, (l_cp->tw * l_cp->th));
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
tileno = backup_tileno;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting tile number to %d\n",
tileno);
}
/* keep your private count of tiles */
backup_tileno++;
};
#endif /* USE_JPWL */
/* look for the tile in the list of already processed tile (in parts). */
/* Optimization possible here with a more complex data structure and with the removing of tiles */
/* since the time taken by this function can only grow at the time */
/* PSot should be equal to zero or >=14 or <= 2^32-1 */
if ((l_tot_len !=0 ) && (l_tot_len < 14) )
{
if (l_tot_len == 12 ) /* MSD: Special case for the PHR data which are read by kakadu*/
{
opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n", l_tot_len);
}
else
{
opj_event_msg(p_manager, EVT_ERROR, "Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len);
return OPJ_FALSE;
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (/*(l_tot_len < 0) ||*/ (l_tot_len > p_header_size ) ) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad tile byte size (%d bytes against %d bytes left)\n",
l_tot_len, p_header_size ); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_tot_len = 0;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"
"- setting Psot to %d => assuming it is the last tile\n",
l_tot_len);
}
};
#endif /* USE_JPWL */
/* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/
if (!l_tot_len) {
opj_event_msg(p_manager, EVT_INFO, "Psot value of the current tile-part is equal to zero, "
"we assuming it is the last tile-part of the codestream.\n");
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
}
if (l_num_parts != 0) { /* Number of tile-part header is provided by this tile-part header */
l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction;
/* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of
* tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */
if (l_tcp->m_nb_tile_parts) {
if (l_current_part >= l_tcp->m_nb_tile_parts){
opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts );
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
}
if( l_current_part >= l_num_parts ) {
/* testcase 451.pdf.SIGSEGV.ce9.3723 */
opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current "
"number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts );
p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1;
return OPJ_FALSE;
}
l_tcp->m_nb_tile_parts = l_num_parts;
}
/* If know the number of tile part header we will check if we didn't read the last*/
if (l_tcp->m_nb_tile_parts) {
if (l_tcp->m_nb_tile_parts == (l_current_part+1)) {
p_j2k->m_specific_param.m_decoder.m_can_decode = 1; /* Process the last tile-part header*/
}
}
if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part){
/* Keep the size of data to skip after this marker */
p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len - 12; /* SOT_marker_size = 12 */
}
else {
/* FIXME: need to be computed from the number of bytes remaining in the codestream */
p_j2k->m_specific_param.m_decoder.m_sot_length = 0;
}
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH;
/* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/
if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) {
p_j2k->m_specific_param.m_decoder.m_skip_data =
(l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x)
|| (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x)
|| (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y)
|| (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y);
}
else {
assert( p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0 );
p_j2k->m_specific_param.m_decoder.m_skip_data =
(p_j2k->m_current_tile_number != (OPJ_UINT32)p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec);
}
/* Index */
if (p_j2k->cstr_index)
{
assert(p_j2k->cstr_index->tile_index != 00);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno = l_current_part;
if (l_num_parts != 0){
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps = l_num_parts;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = l_num_parts;
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
}
else {
opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index, l_num_parts* sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index;
}
}
else{
/*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ {
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index =
(opj_tp_index_t*)opj_calloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps,
sizeof(opj_tp_index_t));
if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) {
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
}
if ( l_current_part >= p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps ){
opj_tp_index_t *new_tp_index;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = l_current_part + 1;
new_tp_index = (opj_tp_index_t *) opj_realloc(
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index,
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps * sizeof(opj_tp_index_t));
if (! new_tp_index) {
opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index);
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL;
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n");
return OPJ_FALSE;
}
p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index;
}
}
}
}
/* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */
/* if (p_j2k->cstr_info) {
if (l_tcp->first) {
if (tileno == 0) {
p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13;
}
p_j2k->cstr_info->tile[tileno].tileno = tileno;
p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1;
p_j2k->cstr_info->tile[tileno].num_tps = numparts;
if (numparts) {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t));
}
else {
p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10)
}
}
else {
p_j2k->cstr_info->tile[tileno].end_pos += totlen;
}
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
}*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_sod( opj_j2k_t *p_j2k,
opj_tcd_t * p_tile_coder,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
const opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_codestream_info_t *l_cstr_info = 00;
OPJ_UINT32 l_remaining_data;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_data,J2K_MS_SOD,2); /* SOD */
p_data += 2;
/* make room for the EOF marker */
l_remaining_data = p_total_data_size - 4;
/* update tile coder */
p_tile_coder->tp_num = p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
p_tile_coder->cur_tp_num = p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
/* INDEX >> */
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) {
//TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1;
l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number;
}
else {*/
/*
TODO
if
(cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream))
{
cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream);
}*/
/*}*/
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2);
*/
assert( 0 && "TODO" );
#endif /* USE_JPWL */
/* <<UniPG */
/*}*/
/* << INDEX */
if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) {
p_tile_coder->tcd_image->tiles->packno = 0;
if (l_cstr_info) {
l_cstr_info->packno = 0;
}
}
*p_data_written = 0;
if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data, p_data_written, l_remaining_data , l_cstr_info)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");
return OPJ_FALSE;
}
*p_data_written += 2;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_sod (opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_SIZE_T l_current_read_size;
opj_codestream_index_t * l_cstr_index = 00;
OPJ_BYTE ** l_current_data = 00;
opj_tcp_t * l_tcp = 00;
OPJ_UINT32 * l_tile_len = 00;
OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) {
/* opj_stream_get_number_byte_left returns OPJ_OFF_T
// but we are in the last tile part,
// so its result will fit on OPJ_UINT32 unless we find
// a file with a single tile part of more than 4 GB...*/
p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)(opj_stream_get_number_byte_left(p_stream) - 2);
}
else {
/* Check to avoid pass the limit of OPJ_UINT32 */
if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2 )
p_j2k->m_specific_param.m_decoder.m_sot_length -= 2;
else {
/* MSD: case commented to support empty SOT marker (PHR data) */
}
}
l_current_data = &(l_tcp->m_data);
l_tile_len = &l_tcp->m_data_size;
/* Patch to support new PHR data */
if (p_j2k->m_specific_param.m_decoder.m_sot_length) {
/* If we are here, we'll try to read the data after allocation */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length > opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR, "Tile part length size inconsistent with stream length\n");
return OPJ_FALSE;
}
if (! *l_current_data) {
/* LH: oddly enough, in this path, l_tile_len!=0.
* TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...).
*/
*l_current_data = (OPJ_BYTE*) opj_malloc(p_j2k->m_specific_param.m_decoder.m_sot_length);
}
else {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data, *l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length);
if (! l_new_current_data) {
opj_free(*l_current_data);
/*nothing more is done as l_current_data will be set to null, and just
afterward we enter in the error path
and the actual tile_len is updated (committed) at the end of the
function. */
}
*l_current_data = l_new_current_data;
}
if (*l_current_data == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n");
return OPJ_FALSE;
}
}
else {
l_sot_length_pb_detected = OPJ_TRUE;
}
/* Index */
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2;
OPJ_UINT32 l_current_tile_part = l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header =
l_current_pos;
l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos =
l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2;
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
l_cstr_index,
J2K_MS_SOD,
l_current_pos,
p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/*l_cstr_index->packno = 0;*/
}
/* Patch to support new PHR data */
if (!l_sot_length_pb_detected) {
l_current_read_size = opj_stream_read_data(
p_stream,
*l_current_data + *l_tile_len,
p_j2k->m_specific_param.m_decoder.m_sot_length,
p_manager);
}
else
{
l_current_read_size = 0;
}
if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
}
else {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
*l_tile_len += (OPJ_UINT32)l_current_read_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_UINT32 nb_comps,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_rgn_size;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_UINT32 l_comp_room;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
if (nb_comps <= 256) {
l_comp_room = 1;
}
else {
l_comp_room = 2;
}
l_rgn_size = 6 + l_comp_room;
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_RGN,2); /* RGN */
l_current_data += 2;
opj_write_bytes(l_current_data,l_rgn_size-2,2); /* Lrgn */
l_current_data += 2;
opj_write_bytes(l_current_data,p_comp_no,l_comp_room); /* Crgn */
l_current_data+=l_comp_room;
opj_write_bytes(l_current_data, 0,1); /* Srgn */
++l_current_data;
opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift,1); /* SPrgn */
++l_current_data;
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_rgn_size,p_manager) != l_rgn_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_eoc( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data,J2K_MS_EOC,2); /* EOC */
/* UniPG>> */
#ifdef USE_JPWL
/* update markers struct */
/*
OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2);
*/
#endif /* USE_JPWL */
if ( opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,2,p_manager) != 2) {
return OPJ_FALSE;
}
if ( ! opj_stream_flush(p_stream,p_manager) ) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a RGN marker (Region Of Interest)
*
* @param p_header_data the data contained in the POC box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the POC marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_rgn (opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp;
opj_image_t * l_image = 00;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty;
/* preconditions*/
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_comp = l_image->numcomps;
if (l_nb_comp <= 256) {
l_comp_room = 1; }
else {
l_comp_room = 2; }
if (p_header_size != 2 + l_comp_room) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n");
return OPJ_FALSE;
}
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
opj_read_bytes(p_header_data,&l_comp_no,l_comp_room); /* Crgn */
p_header_data+=l_comp_room;
opj_read_bytes(p_header_data,&l_roi_sty,1); /* Srgn */
++p_header_data;
#ifdef USE_JPWL
if (l_cp->correct) {
/* totlen is negative or larger than the bytes left!!! */
if (l_comp_room >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"JPWL: bad component number in RGN (%d when there are only %d)\n",
l_comp_room, l_nb_comp);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
}
};
#endif /* USE_JPWL */
/* testcase 3635.pdf.asan.77.2930 */
if (l_comp_no >= l_nb_comp) {
opj_event_msg(p_manager, EVT_ERROR,
"bad component number in RGN (%d when there are only %d)\n",
l_comp_no, l_nb_comp);
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,(OPJ_UINT32 *) (&(l_tcp->tccps[l_comp_no].roishift)),1); /* SPrgn */
++p_header_data;
return OPJ_TRUE;
}
static OPJ_FLOAT32 opj_j2k_get_tp_stride (opj_tcp_t * p_tcp)
{
return (OPJ_FLOAT32) ((p_tcp->m_nb_tile_parts - 1) * 14);
}
static OPJ_FLOAT32 opj_j2k_get_default_stride (opj_tcp_t * p_tcp)
{
(void)p_tcp;
return 0;
}
static OPJ_BOOL opj_j2k_update_rates( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
opj_cp_t * l_cp = 00;
opj_image_t * l_image = 00;
opj_tcp_t * l_tcp = 00;
opj_image_comp_t * l_img_comp = 00;
OPJ_UINT32 i,j,k;
OPJ_INT32 l_x0,l_y0,l_x1,l_y1;
OPJ_FLOAT32 * l_rates = 0;
OPJ_FLOAT32 l_sot_remove;
OPJ_UINT32 l_bits_empty, l_size_pixel;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_last_res;
OPJ_FLOAT32 (* l_tp_stride_func)(opj_tcp_t *) = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cp = &(p_j2k->m_cp);
l_image = p_j2k->m_private_image;
l_tcp = l_cp->tcps;
l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy;
l_size_pixel = l_image->numcomps * l_image->comps->prec;
l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)(l_cp->th * l_cp->tw);
if (l_cp->m_specific_param.m_enc.m_tp_on) {
l_tp_stride_func = opj_j2k_get_tp_stride;
}
else {
l_tp_stride_func = opj_j2k_get_default_stride;
}
for (i=0;i<l_cp->th;++i) {
for (j=0;j<l_cp->tw;++j) {
OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) / (OPJ_FLOAT32)l_tcp->numlayers;
/* 4 borders of the tile rescale on the image if necessary */
l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx), (OPJ_INT32)l_image->x0);
l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy), (OPJ_INT32)l_image->y0);
l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx), (OPJ_INT32)l_image->x1);
l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy), (OPJ_INT32)l_image->y1);
l_rates = l_tcp->rates;
/* Modification of the RATE >> */
if (*l_rates > 0.0f) {
*l_rates = (( (OPJ_FLOAT32) (l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) * (OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
for (k = 1; k < l_tcp->numlayers; ++k) {
if (*l_rates > 0.0f) {
*l_rates = (( (OPJ_FLOAT32) (l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) * (OPJ_UINT32)(l_y1 - l_y0)))
/
((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
)
-
l_offset;
}
++l_rates;
}
++l_tcp;
}
}
l_tcp = l_cp->tcps;
for (i=0;i<l_cp->th;++i) {
for (j=0;j<l_cp->tw;++j) {
l_rates = l_tcp->rates;
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < 30.0f) {
*l_rates = 30.0f;
}
}
++l_rates;
l_last_res = l_tcp->numlayers - 1;
for (k = 1; k < l_last_res; ++k) {
if (*l_rates > 0.0f) {
*l_rates -= l_sot_remove;
if (*l_rates < *(l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_rates;
}
if (*l_rates > 0.0f) {
*l_rates -= (l_sot_remove + 2.f);
if (*l_rates < *(l_rates - 1) + 10.0f) {
*l_rates = (*(l_rates - 1)) + 20.0f;
}
}
++l_tcp;
}
}
l_img_comp = l_image->comps;
l_tile_size = 0;
for (i=0;i<l_image->numcomps;++i) {
l_tile_size += ( opj_uint_ceildiv(l_cp->tdx,l_img_comp->dx)
*
opj_uint_ceildiv(l_cp->tdy,l_img_comp->dy)
*
l_img_comp->prec
);
++l_img_comp;
}
l_tile_size = (OPJ_UINT32) (l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */
l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size;
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
(OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
(OPJ_BYTE *) opj_malloc(5*p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current =
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer;
}
return OPJ_TRUE;
}
#if 0
static OPJ_BOOL opj_j2k_read_eoc ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 i;
opj_tcd_t * l_tcd = 00;
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_tcp = 00;
OPJ_BOOL l_success;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tcd = opj_tcd_create(OPJ_TRUE);
if (l_tcd == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
for (i = 0; i < l_nb_tiles; ++i) {
if (l_tcp->m_data) {
if (! opj_tcd_init_decode_tile(l_tcd, i)) {
opj_tcd_destroy(l_tcd);
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i, p_j2k->cstr_index);
/* cleanup */
if (! l_success) {
p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR;
break;
}
}
opj_j2k_tcp_destroy(l_tcp);
++l_tcp;
}
opj_tcd_destroy(l_tcd);
return OPJ_TRUE;
}
#endif
static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream);
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_data_group( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_record;
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if (! opj_j2k_write_cbd(p_j2k,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mct_record = l_tcp->m_mct_records;
for (i=0;i<l_tcp->m_nb_mct_records;++i) {
if (! opj_j2k_write_mct_record(p_j2k,l_mct_record,p_stream,p_manager)) {
return OPJ_FALSE;
}
++l_mct_record;
}
l_mcc_record = l_tcp->m_mcc_records;
for (i=0;i<l_tcp->m_nb_mcc_records;++i) {
if (! opj_j2k_write_mcc_record(p_j2k,l_mcc_record,p_stream,p_manager)) {
return OPJ_FALSE;
}
++l_mcc_record;
}
if (! opj_j2k_write_mco(p_j2k,p_stream,p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_coc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno)
{
/* cod is first component of first tile */
if (! opj_j2k_compare_coc(p_j2k, 0, compno)) {
if (! opj_j2k_write_coc(p_j2k,compno,p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_qcc(
opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 compno;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno)
{
/* qcd is first component of first tile */
if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) {
if (! opj_j2k_write_qcc(p_j2k,compno,p_stream, p_manager)) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_regions( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 compno;
const opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tccp = p_j2k->m_cp.tcps->tccps;
for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) {
if (l_tccp->roishift) {
if (! opj_j2k_write_rgn(p_j2k,0,compno,p_j2k->m_private_image->numcomps,p_stream,p_manager)) {
return OPJ_FALSE;
}
}
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_epc( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
opj_codestream_index_t * l_cstr_index = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_cstr_index = p_j2k->cstr_index;
if (l_cstr_index) {
l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream);
/* UniPG>> */
/* The following adjustment is done to adjust the codestream size */
/* if SOD is not at 0 in the buffer. Useful in case of JP2, where */
/* the first bunch of bytes is not in the codestream */
l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start;
/* <<UniPG */
}
#ifdef USE_JPWL
/* preparation of JPWL marker segments */
#if 0
if(cp->epc_on) {
/* encode according to JPWL */
jpwl_encode(p_j2k, p_stream, image);
}
#endif
assert( 0 && "TODO" );
#endif /* USE_JPWL */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_unk ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
OPJ_UINT32 *output_marker,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_unknown_marker;
const opj_dec_memory_marker_handler_t * l_marker_handler;
OPJ_UINT32 l_size_unk = 2;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n");
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID*/
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_unknown_marker,2);
if (!(l_unknown_marker < 0xff00)) {
/* Get the marker handler from the marker ID*/
l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker);
if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) {
opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n");
return OPJ_FALSE;
}
else {
if (l_marker_handler->id != J2K_MS_UNK) {
/* Add the marker to the codestream index*/
if (l_marker_handler->id != J2K_MS_SOT)
{
OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk,
l_size_unk);
if (res == OPJ_FALSE) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
}
break; /* next marker is known and well located */
}
else
l_size_unk += 2;
}
}
}
*output_marker = l_marker_handler->id ;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mct_record( opj_j2k_t *p_j2k,
opj_mct_data_t * p_mct_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 l_mct_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tmp;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_mct_size = 10 + p_mct_record->m_data_size;
if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_MCT,2); /* MCT */
l_current_data += 2;
opj_write_bytes(l_current_data,l_mct_size-2,2); /* Lmct */
l_current_data += 2;
opj_write_bytes(l_current_data,0,2); /* Zmct */
l_current_data += 2;
/* only one marker atm */
l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) | (p_mct_record->m_element_type << 10);
opj_write_bytes(l_current_data,l_tmp,2);
l_current_data += 2;
opj_write_bytes(l_current_data,0,2); /* Ymct */
l_current_data+=2;
memcpy(l_current_data,p_mct_record->m_data,p_mct_record->m_data_size);
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mct_size,p_manager) != l_mct_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCT marker (Multiple Component Transform)
*
* @param p_header_data the data contained in the MCT box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCT marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mct ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 i;
opj_tcp_t *l_tcp = 00;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_mct_data_t * l_mct_data;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data,&l_tmp,2); /* Zmct */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge mct data within multiple MCT records\n");
return OPJ_TRUE;
}
if(p_header_size <= 6) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
/* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/
opj_read_bytes(p_header_data,&l_tmp,2); /* Imct */
p_header_data += 2;
l_indix = l_tmp & 0xff;
l_mct_data = l_tcp->m_mct_records;
for (i=0;i<l_tcp->m_nb_mct_records;++i) {
if (l_mct_data->m_index == l_indix) {
break;
}
++l_mct_data;
}
/* NOT FOUND */
if (i == l_tcp->m_nb_mct_records) {
if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records, l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(l_tcp->m_mct_records);
l_tcp->m_mct_records = NULL;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_nb_mct_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n");
return OPJ_FALSE;
}
l_tcp->m_mct_records = new_mct_records;
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
memset(l_mct_data ,0,(l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) * sizeof(opj_mct_data_t));
}
l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records;
++l_tcp->m_nb_mct_records;
}
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
}
l_mct_data->m_index = l_indix;
l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3);
l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3);
opj_read_bytes(p_header_data,&l_tmp,2); /* Ymct */
p_header_data+=2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple MCT markers\n");
return OPJ_TRUE;
}
p_header_size -= 6;
l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size);
if (! l_mct_data->m_data) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n");
return OPJ_FALSE;
}
memcpy(l_mct_data->m_data,p_header_data,p_header_size);
l_mct_data->m_data_size = p_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mcc_record( opj_j2k_t *p_j2k,
struct opj_simple_mcc_decorrelation_data * p_mcc_record,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 i;
OPJ_UINT32 l_mcc_size;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_nb_bytes_for_comp;
OPJ_UINT32 l_mask;
OPJ_UINT32 l_tmcc;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
if (p_mcc_record->m_nb_comps > 255 ) {
l_nb_bytes_for_comp = 2;
l_mask = 0x8000;
}
else {
l_nb_bytes_for_comp = 1;
l_mask = 0;
}
l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19;
if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size)
{
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_MCC,2); /* MCC */
l_current_data += 2;
opj_write_bytes(l_current_data,l_mcc_size-2,2); /* Lmcc */
l_current_data += 2;
/* first marker */
opj_write_bytes(l_current_data,0,2); /* Zmcc */
l_current_data += 2;
opj_write_bytes(l_current_data,p_mcc_record->m_index,1); /* Imcc -> no need for other values, take the first */
++l_current_data;
/* only one marker atm */
opj_write_bytes(l_current_data,0,2); /* Ymcc */
l_current_data+=2;
opj_write_bytes(l_current_data,1,2); /* Qmcc -> number of collections -> 1 */
l_current_data+=2;
opj_write_bytes(l_current_data,0x1,1); /* Xmcci type of component transformation -> array based decorrelation */
++l_current_data;
opj_write_bytes(l_current_data,p_mcc_record->m_nb_comps | l_mask,2); /* Nmcci number of input components involved and size for each component offset = 8 bits */
l_current_data+=2;
for (i=0;i<p_mcc_record->m_nb_comps;++i) {
opj_write_bytes(l_current_data,i,l_nb_bytes_for_comp); /* Cmccij Component offset*/
l_current_data+=l_nb_bytes_for_comp;
}
opj_write_bytes(l_current_data,p_mcc_record->m_nb_comps|l_mask,2); /* Mmcci number of output components involved and size for each component offset = 8 bits */
l_current_data+=2;
for (i=0;i<p_mcc_record->m_nb_comps;++i)
{
opj_write_bytes(l_current_data,i,l_nb_bytes_for_comp); /* Wmccij Component offset*/
l_current_data+=l_nb_bytes_for_comp;
}
l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16;
if (p_mcc_record->m_decorrelation_array) {
l_tmcc |= p_mcc_record->m_decorrelation_array->m_index;
}
if (p_mcc_record->m_offset_array) {
l_tmcc |= ((p_mcc_record->m_offset_array->m_index)<<8);
}
opj_write_bytes(l_current_data,l_tmcc,3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */
l_current_data+=3;
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mcc_size,p_manager) != l_mcc_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_mcc ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 i,j;
OPJ_UINT32 l_tmp;
OPJ_UINT32 l_indix;
opj_tcp_t * l_tcp;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_mct_data;
OPJ_UINT32 l_nb_collections;
OPJ_UINT32 l_nb_comps;
OPJ_UINT32 l_nb_bytes_by_comp;
OPJ_BOOL l_new_mcc = OPJ_FALSE;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
/* first marker */
opj_read_bytes(p_header_data,&l_tmp,2); /* Zmcc */
p_header_data += 2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
if (p_header_size < 7) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_indix,1); /* Imcc -> no need for other values, take the first */
++p_header_data;
l_mcc_record = l_tcp->m_mcc_records;
for(i=0;i<l_tcp->m_nb_mcc_records;++i) {
if (l_mcc_record->m_index == l_indix) {
break;
}
++l_mcc_record;
}
/** NOT FOUND */
if (i == l_tcp->m_nb_mcc_records) {
if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof(opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(l_tcp->m_mcc_records);
l_tcp->m_mcc_records = NULL;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_nb_mcc_records = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n");
return OPJ_FALSE;
}
l_tcp->m_mcc_records = new_mcc_records;
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
memset(l_mcc_record,0,(l_tcp->m_nb_max_mcc_records-l_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records;
l_new_mcc = OPJ_TRUE;
}
l_mcc_record->m_index = l_indix;
/* only one marker atm */
opj_read_bytes(p_header_data,&l_tmp,2); /* Ymcc */
p_header_data+=2;
if (l_tmp != 0) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data,&l_nb_collections,2); /* Qmcc -> number of collections -> 1 */
p_header_data+=2;
if (l_nb_collections > 1) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple collections\n");
return OPJ_TRUE;
}
p_header_size -= 7;
for (i=0;i<l_nb_collections;++i) {
if (p_header_size < 3) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_tmp,1); /* Xmcci type of component transformation -> array based decorrelation */
++p_header_data;
if (l_tmp != 1) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections other than array decorrelation\n");
return OPJ_TRUE;
}
opj_read_bytes(p_header_data,&l_nb_comps,2);
p_header_data+=2;
p_header_size-=3;
l_nb_bytes_by_comp = 1 + (l_nb_comps>>15);
l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff;
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2);
for (j=0;j<l_mcc_record->m_nb_comps;++j) {
opj_read_bytes(p_header_data,&l_tmp,l_nb_bytes_by_comp); /* Cmccij Component offset*/
p_header_data+=l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data,&l_nb_comps,2);
p_header_data+=2;
l_nb_bytes_by_comp = 1 + (l_nb_comps>>15);
l_nb_comps &= 0x7fff;
if (l_nb_comps != l_mcc_record->m_nb_comps) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections without same number of indixes\n");
return OPJ_TRUE;
}
if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3);
for (j=0;j<l_mcc_record->m_nb_comps;++j) {
opj_read_bytes(p_header_data,&l_tmp,l_nb_bytes_by_comp); /* Wmccij Component offset*/
p_header_data+=l_nb_bytes_by_comp;
if (l_tmp != j) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n");
return OPJ_TRUE;
}
}
opj_read_bytes(p_header_data,&l_tmp,3); /* Wmccij Component offset*/
p_header_data += 3;
l_mcc_record->m_is_irreversible = ! ((l_tmp>>16) & 1);
l_mcc_record->m_decorrelation_array = 00;
l_mcc_record->m_offset_array = 00;
l_indix = l_tmp & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j=0;j<l_tcp->m_nb_mct_records;++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_decorrelation_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_decorrelation_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
l_indix = (l_tmp >> 8) & 0xff;
if (l_indix != 0) {
l_mct_data = l_tcp->m_mct_records;
for (j=0;j<l_tcp->m_nb_mct_records;++j) {
if (l_mct_data->m_index == l_indix) {
l_mcc_record->m_offset_array = l_mct_data;
break;
}
++l_mct_data;
}
if (l_mcc_record->m_offset_array == 00) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
}
}
if (p_header_size != 0) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n");
return OPJ_FALSE;
}
if (l_new_mcc) {
++l_tcp->m_nb_mcc_records;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_mco_size;
opj_tcp_t * l_tcp = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
OPJ_UINT32 i;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tcp =&(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);
l_mco_size = 5 + l_tcp->m_nb_mcc_records;
if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_MCO,2); /* MCO */
l_current_data += 2;
opj_write_bytes(l_current_data,l_mco_size-2,2); /* Lmco */
l_current_data += 2;
opj_write_bytes(l_current_data,l_tcp->m_nb_mcc_records,1); /* Nmco : only one transform stage*/
++l_current_data;
l_mcc_record = l_tcp->m_mcc_records;
for (i=0;i<l_tcp->m_nb_mcc_records;++i) {
opj_write_bytes(l_current_data,l_mcc_record->m_index,1);/* Imco -> use the mcc indicated by 1*/
++l_current_data;
++l_mcc_record;
}
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mco_size,p_manager) != l_mco_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a MCO marker (Multiple Component Transform Ordering)
*
* @param p_header_data the data contained in the MCO box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the MCO marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_mco ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_tmp, i;
OPJ_UINT32 l_nb_stages;
opj_tcp_t * l_tcp;
opj_tccp_t * l_tccp;
opj_image_t * l_image;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
if (p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_nb_stages,1); /* Nmco : only one transform stage*/
++p_header_data;
if (l_nb_stages > 1) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple transformation stages.\n");
return OPJ_TRUE;
}
if (p_header_size != l_nb_stages + 1) {
opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n");
return OPJ_FALSE;
}
l_tccp = l_tcp->tccps;
for (i=0;i<l_image->numcomps;++i) {
l_tccp->m_dc_level_shift = 0;
++l_tccp;
}
if (l_tcp->m_mct_decoding_matrix) {
opj_free(l_tcp->m_mct_decoding_matrix);
l_tcp->m_mct_decoding_matrix = 00;
}
for (i=0;i<l_nb_stages;++i) {
opj_read_bytes(p_header_data,&l_tmp,1);
++p_header_data;
if (! opj_j2k_add_mct(l_tcp,p_j2k->m_private_image,l_tmp)) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image, OPJ_UINT32 p_index)
{
OPJ_UINT32 i;
opj_simple_mcc_decorrelation_data_t * l_mcc_record;
opj_mct_data_t * l_deco_array, * l_offset_array;
OPJ_UINT32 l_data_size,l_mct_size, l_offset_size;
OPJ_UINT32 l_nb_elem;
OPJ_UINT32 * l_offset_data, * l_current_offset_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
l_mcc_record = p_tcp->m_mcc_records;
for (i=0;i<p_tcp->m_nb_mcc_records;++i) {
if (l_mcc_record->m_index == p_index) {
break;
}
}
if (i==p_tcp->m_nb_mcc_records) {
/** element discarded **/
return OPJ_TRUE;
}
if (l_mcc_record->m_nb_comps != p_image->numcomps) {
/** do not support number of comps != image */
return OPJ_TRUE;
}
l_deco_array = l_mcc_record->m_decorrelation_array;
if (l_deco_array) {
l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps * p_image->numcomps;
if (l_deco_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! p_tcp->m_mct_decoding_matrix ) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_float[l_deco_array->m_element_type](l_deco_array->m_data,p_tcp->m_mct_decoding_matrix,l_nb_elem);
}
l_offset_array = l_mcc_record->m_offset_array;
if (l_offset_array) {
l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] * p_image->numcomps;
if (l_offset_array->m_data_size != l_data_size) {
return OPJ_FALSE;
}
l_nb_elem = p_image->numcomps;
l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size);
if (! l_offset_data ) {
return OPJ_FALSE;
}
j2k_mct_read_functions_to_int32[l_offset_array->m_element_type](l_offset_array->m_data,l_offset_data,l_nb_elem);
l_tccp = p_tcp->tccps;
l_current_offset_data = l_offset_data;
for (i=0;i<p_image->numcomps;++i) {
l_tccp->m_dc_level_shift = (OPJ_INT32)*(l_current_offset_data++);
++l_tccp;
}
opj_free(l_offset_data);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_cbd( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 i;
OPJ_UINT32 l_cbd_size;
OPJ_BYTE * l_current_data = 00;
opj_image_t *l_image = 00;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_image = p_j2k->m_private_image;
l_cbd_size = 6 + p_j2k->m_private_image->numcomps;
if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {
OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size);
if (! new_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size;
}
l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;
opj_write_bytes(l_current_data,J2K_MS_CBD,2); /* CBD */
l_current_data += 2;
opj_write_bytes(l_current_data,l_cbd_size-2,2); /* L_CBD */
l_current_data += 2;
opj_write_bytes(l_current_data,l_image->numcomps, 2); /* Ncbd */
l_current_data+=2;
l_comp = l_image->comps;
for (i=0;i<l_image->numcomps;++i) {
opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1), 1); /* Component bit depth */
++l_current_data;
++l_comp;
}
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_cbd_size,p_manager) != l_cbd_size) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/**
* Reads a CBD marker (Component bit depth definition)
* @param p_header_data the data contained in the CBD box.
* @param p_j2k the jpeg2000 codec.
* @param p_header_size the size of the data contained in the CBD marker.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_read_cbd ( opj_j2k_t *p_j2k,
OPJ_BYTE * p_header_data,
OPJ_UINT32 p_header_size,
opj_event_mgr_t * p_manager
)
{
OPJ_UINT32 l_nb_comp,l_num_comp;
OPJ_UINT32 l_comp_def;
OPJ_UINT32 i;
opj_image_comp_t * l_comp = 00;
/* preconditions */
assert(p_header_data != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
l_num_comp = p_j2k->m_private_image->numcomps;
if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
opj_read_bytes(p_header_data,&l_nb_comp,2); /* Ncbd */
p_header_data+=2;
if (l_nb_comp != l_num_comp) {
opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n");
return OPJ_FALSE;
}
l_comp = p_j2k->m_private_image->comps;
for (i=0;i<l_num_comp;++i) {
opj_read_bytes(p_header_data,&l_comp_def,1); /* Component bit depth */
++p_header_data;
l_comp->sgnd = (l_comp_def>>7) & 1;
l_comp->prec = (l_comp_def&0x7f) + 1;
++l_comp;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
/* J2K / JPT decoder interface */
/* ----------------------------------------------------------------------- */
void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters)
{
if(j2k && parameters) {
j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer;
j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce;
#ifdef USE_JPWL
j2k->m_cp.correct = parameters->jpwl_correct;
j2k->m_cp.exp_comps = parameters->jpwl_exp_comps;
j2k->m_cp.max_tiles = parameters->jpwl_max_tiles;
#endif /* USE_JPWL */
}
}
OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads)
{
if( opj_has_thread_support() )
{
opj_thread_pool_destroy(j2k->m_tp);
j2k->m_tp = NULL;
if (num_threads <= (OPJ_UINT32)INT_MAX ) {
j2k->m_tp = opj_thread_pool_create((int)num_threads);
}
if( j2k->m_tp == NULL )
{
j2k->m_tp = opj_thread_pool_create(0);
return OPJ_FALSE;
}
return OPJ_TRUE;
}
return OPJ_FALSE;
}
static int opj_j2k_get_default_thread_count()
{
const char* num_threads = getenv("OPJ_NUM_THREADS");
if( num_threads == NULL || !opj_has_thread_support() )
return 0;
if( strcmp(num_threads, "ALL_CPUS") == 0 )
return opj_get_num_cpus();
return atoi(num_threads);
}
/* ----------------------------------------------------------------------- */
/* J2K encoder interface */
/* ----------------------------------------------------------------------- */
opj_j2k_t* opj_j2k_create_compress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1,sizeof(opj_j2k_t));
if (!l_j2k) {
return NULL;
}
l_j2k->m_is_decoder = 0;
l_j2k->m_cp.m_is_decoder = 0;
l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc(OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_specific_param.m_encoder.m_header_tile_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE;
/* validation list creation*/
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
/* execution list creation*/
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return NULL;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if( !l_j2k->m_tp )
{
l_j2k->m_tp = opj_thread_pool_create(0);
}
if( !l_j2k->m_tp )
{
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres){
POC[0].tile = 1;
POC[0].resno0 = 0;
POC[0].compno0 = 0;
POC[0].layno1 = 1;
POC[0].resno1 = (OPJ_UINT32)(numres-1);
POC[0].compno1 = 3;
POC[0].prg1 = OPJ_CPRL;
POC[1].tile = 1;
POC[1].resno0 = (OPJ_UINT32)(numres-1);
POC[1].compno0 = 0;
POC[1].layno1 = 1;
POC[1].resno1 = (OPJ_UINT32)numres;
POC[1].compno1 = 3;
POC[1].prg1 = OPJ_CPRL;
return 2;
}
static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx=1;
parameters->cp_tdy=1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers-1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers-1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz){
case OPJ_PROFILE_CINEMA_2K:
if(parameters->numresolution > 6){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution+1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if(parameters->numresolution < 2){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution+1);
parameters->numresolution = 1;
}else if(parameters->numresolution > 7){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution+1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
parameters->res_spec = parameters->numresolution-1;
for (i = 0; i<parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy);
}
static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager)
{
OPJ_UINT32 i;
/* Number of components */
if (image->numcomps != 3){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"3 components"
"-> Number of components of input image (%d) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->numcomps);
return OPJ_FALSE;
}
/* Bitdepth */
for (i = 0; i < image->numcomps; i++) {
if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)){
char signed_str[] = "signed";
char unsigned_str[] = "unsigned";
char *tmp_str = image->comps[i].sgnd?signed_str:unsigned_str;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Precision of each component shall be 12 bits unsigned"
"-> At least component %d of input image (%d bits, %s) is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
i,image->comps[i].bpp, tmp_str);
return OPJ_FALSE;
}
}
/* Image size */
switch (rsiz){
case OPJ_PROFILE_CINEMA_2K:
if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"width <= 2048 and height <= 1080\n"
"-> Input image size %d x %d is not compliant\n"
"-> Non-profile-3 codestream will be generated\n",
image->comps[0].w,image->comps[0].h);
return OPJ_FALSE;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"width <= 4096 and height <= 2160\n"
"-> Image size %d x %d is not compliant\n"
"-> Non-profile-4 codestream will be generated\n",
image->comps[0].w,image->comps[0].h);
return OPJ_FALSE;
}
break;
default :
break;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_setup_encoder( opj_j2k_t *p_j2k,
opj_cparameters_t *parameters,
opj_image_t *image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, j, tileno, numpocs_tile;
opj_cp_t *cp = 00;
if(!p_j2k || !parameters || ! image) {
return OPJ_FALSE;
}
if ((parameters->numresolution <= 0) || (parameters->numresolution > OPJ_J2K_MAXRLVLS)) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid number of resolutions : %d not in range [1,%d]\n", parameters->numresolution, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
/* keep a link to cp so that we can destroy it later in j2k_destroy_compress */
cp = &(p_j2k->m_cp);
/* set default values for cp */
cp->tw = 1;
cp->th = 1;
/* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */
if (parameters->rsiz == OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */
OPJ_BOOL deprecated_used = OPJ_FALSE;
switch (parameters->cp_cinema){
case OPJ_CINEMA2K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA2K_48:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
parameters->max_cs_size = OPJ_CINEMA_48_CS;
parameters->max_comp_size = OPJ_CINEMA_48_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K_24:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
parameters->max_cs_size = OPJ_CINEMA_24_CS;
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
deprecated_used = OPJ_TRUE;
break;
case OPJ_OFF:
default:
break;
}
switch (parameters->cp_rsiz){
case OPJ_CINEMA2K:
parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_CINEMA4K:
parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
deprecated_used = OPJ_TRUE;
break;
case OPJ_MCT:
parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT;
deprecated_used = OPJ_TRUE;
case OPJ_STD_RSIZ:
default:
break;
}
if (deprecated_used) {
opj_event_msg(p_manager, EVT_WARNING,
"Deprecated fields cp_cinema or cp_rsiz are used\n"
"Please consider using only the rsiz field\n"
"See openjpeg.h documentation for more details\n");
}
}
/* see if max_codestream_size does limit input rate */
if (parameters->max_cs_size <= 0) {
if (parameters->tcp_rates[parameters->tcp_numlayers-1] > 0) {
OPJ_FLOAT32 temp_size;
temp_size =(OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
(parameters->tcp_rates[parameters->tcp_numlayers-1] * 8 * (OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy);
parameters->max_cs_size = (int) floor(temp_size);
} else {
parameters->max_cs_size = 0;
}
} else {
OPJ_FLOAT32 temp_rate;
OPJ_BOOL cap = OPJ_FALSE;
temp_rate = (OPJ_FLOAT32) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)/
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy);
for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
if (parameters->tcp_rates[i] < temp_rate) {
parameters->tcp_rates[i] = temp_rate;
cap = OPJ_TRUE;
}
}
if (cap) {
opj_event_msg(p_manager, EVT_WARNING,
"The desired maximum codestream size has limited\n"
"at least one of the desired quality layers\n");
}
}
/* Manage profiles and applications and set RSIZ */
/* set cinema parameters if required */
if (OPJ_IS_CINEMA(parameters->rsiz)){
if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K)
|| (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)){
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Scalable Digital Cinema profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else {
opj_j2k_set_cinema_parameters(parameters,image,p_manager);
if (!opj_j2k_is_cinema_compliant(image,parameters->rsiz,p_manager)) {
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
} else if (OPJ_IS_STORAGE(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Long Term Storage profile not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Broadcast profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_IMF(parameters->rsiz)) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 IMF profiles not yet supported\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (OPJ_IS_PART2(parameters->rsiz)) {
if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Part-2 profile defined\n"
"but no Part-2 extension enabled.\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
} else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) {
opj_event_msg(p_manager, EVT_WARNING,
"Unsupported Part-2 extension enabled\n"
"Profile set to NONE.\n");
parameters->rsiz = OPJ_PROFILE_NONE;
}
}
/*
copy user encoding parameters
*/
cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32)parameters->max_comp_size;
cp->rsiz = parameters->rsiz;
cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32)parameters->cp_disto_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32)parameters->cp_fixed_alloc & 1u;
cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32)parameters->cp_fixed_quality & 1u;
/* mod fixed_quality */
if (parameters->cp_fixed_alloc && parameters->cp_matrice) {
size_t array_size = (size_t)parameters->tcp_numlayers * (size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32);
cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size);
if (!cp->m_specific_param.m_enc.m_matrice) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of user encoding parameters matrix \n");
return OPJ_FALSE;
}
memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice, array_size);
}
/* tiles */
cp->tdx = (OPJ_UINT32)parameters->cp_tdx;
cp->tdy = (OPJ_UINT32)parameters->cp_tdy;
/* tile offset */
cp->tx0 = (OPJ_UINT32)parameters->cp_tx0;
cp->ty0 = (OPJ_UINT32)parameters->cp_ty0;
/* comment string */
if(parameters->cp_comment) {
cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U);
if(!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of comment string\n");
return OPJ_FALSE;
}
strcpy(cp->comment, parameters->cp_comment);
} else {
/* Create default comment for codestream */
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
/* UniPG>> */
#ifdef USE_JPWL
cp->comment = (char*)opj_malloc(clen+strlen(version)+11);
if(!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment,"%s%s with JPWL", comment, version);
#else
cp->comment = (char*)opj_malloc(clen+strlen(version)+1);
if(!cp->comment) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n");
return OPJ_FALSE;
}
sprintf(cp->comment,"%s%s", comment, version);
#endif
/* <<UniPG */
}
/*
calculate other encoding parameters
*/
if (parameters->tile_size_on) {
cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0), (OPJ_INT32)cp->tdx);
cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0), (OPJ_INT32)cp->tdy);
} else {
cp->tdx = image->x1 - cp->tx0;
cp->tdy = image->y1 - cp->ty0;
}
if (parameters->tp_on) {
cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag;
cp->m_specific_param.m_enc.m_tp_on = 1;
}
#ifdef USE_JPWL
/*
calculate JPWL encoding parameters
*/
if (parameters->jpwl_epc_on) {
OPJ_INT32 i;
/* set JPWL on */
cp->epc_on = OPJ_TRUE;
cp->info_on = OPJ_FALSE; /* no informative technique */
/* set EPB on */
if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) {
cp->epb_on = OPJ_TRUE;
cp->hprot_MH = parameters->jpwl_hprot_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i];
cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i];
}
/* if tile specs are not specified, copy MH specs */
if (cp->hprot_TPH[0] == -1) {
cp->hprot_TPH_tileno[0] = 0;
cp->hprot_TPH[0] = parameters->jpwl_hprot_MH;
}
for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) {
cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i];
cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i];
cp->pprot[i] = parameters->jpwl_pprot[i];
}
}
/* set ESD writing */
if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) {
cp->esd_on = OPJ_TRUE;
cp->sens_size = parameters->jpwl_sens_size;
cp->sens_addr = parameters->jpwl_sens_addr;
cp->sens_range = parameters->jpwl_sens_range;
cp->sens_MH = parameters->jpwl_sens_MH;
for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) {
cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i];
cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i];
}
}
/* always set RED writing to false: we are at the encoder */
cp->red_on = OPJ_FALSE;
} else {
cp->epc_on = OPJ_FALSE;
}
#endif /* USE_JPWL */
/* initialize the mutiple tiles */
/* ---------------------------- */
cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
if (!cp->tcps) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile coding parameters\n");
return OPJ_FALSE;
}
if (parameters->numpocs) {
/* initialisation of POC */
opj_j2k_check_poc_val(parameters->POC,parameters->numpocs, (OPJ_UINT32)parameters->numresolution, image->numcomps, (OPJ_UINT32)parameters->tcp_numlayers, p_manager);
/* TODO MSD use the return value*/
}
for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
opj_tcp_t *tcp = &cp->tcps[tileno];
tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;
for (j = 0; j < tcp->numlayers; j++) {
if(OPJ_IS_CINEMA(cp->rsiz)){
if (cp->m_specific_param.m_enc.m_fixed_quality) {
tcp->distoratio[j] = parameters->tcp_distoratio[j];
}
tcp->rates[j] = parameters->tcp_rates[j];
}else{
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */
tcp->distoratio[j] = parameters->tcp_distoratio[j];
} else {
tcp->rates[j] = parameters->tcp_rates[j];
}
}
}
tcp->csty = (OPJ_UINT32)parameters->csty;
tcp->prg = parameters->prog_order;
tcp->mct = (OPJ_UINT32)parameters->tcp_mct;
numpocs_tile = 0;
tcp->POC = 0;
if (parameters->numpocs) {
/* initialisation of POC */
tcp->POC = 1;
for (i = 0; i < parameters->numpocs; i++) {
if (tileno + 1 == parameters->POC[i].tile ) {
opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];
tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0;
tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0;
tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1;
tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1;
tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1;
tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1;
tcp_poc->tile = parameters->POC[numpocs_tile].tile;
numpocs_tile++;
}
}
tcp->numpocs = numpocs_tile -1 ;
}else{
tcp->numpocs = 0;
}
tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
if (!tcp->tccps) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile component coding parameters\n");
return OPJ_FALSE;
}
if (parameters->mct_data) {
OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize);
OPJ_INT32 * l_dc_shift = (OPJ_INT32 *) ((OPJ_BYTE *) parameters->mct_data + lMctSize);
if (!lTmpBuf) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate temp buffer\n");
return OPJ_FALSE;
}
tcp->mct = 2;
tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_coding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT coding matrix \n");
return OPJ_FALSE;
}
memcpy(tcp->m_mct_coding_matrix,parameters->mct_data,lMctSize);
memcpy(lTmpBuf,parameters->mct_data,lMctSize);
tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize);
if (! tcp->m_mct_decoding_matrix) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
if(opj_matrix_inversion_f(lTmpBuf,(tcp->m_mct_decoding_matrix),image->numcomps) == OPJ_FALSE) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Failed to inverse encoder MCT decoding matrix \n");
return OPJ_FALSE;
}
tcp->mct_norms = (OPJ_FLOAT64*)
opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64));
if (! tcp->mct_norms) {
opj_free(lTmpBuf);
lTmpBuf = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT norms \n");
return OPJ_FALSE;
}
opj_calculate_norms(tcp->mct_norms,image->numcomps,tcp->m_mct_decoding_matrix);
opj_free(lTmpBuf);
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->m_dc_level_shift = l_dc_shift[i];
}
if (opj_j2k_setup_mct_encoding(tcp,image) == OPJ_FALSE) {
/* free will be handled by opj_j2k_destroy */
opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n");
return OPJ_FALSE;
}
}
else {
if(tcp->mct==1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */
if ((image->comps[0].dx != image->comps[1].dx) ||
(image->comps[0].dx != image->comps[2].dx) ||
(image->comps[0].dy != image->comps[1].dy) ||
(image->comps[0].dy != image->comps[2].dy)) {
opj_event_msg(p_manager, EVT_WARNING, "Cannot perform MCT on components with different sizes. Disabling MCT.\n");
tcp->mct = 0;
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
opj_image_comp_t * l_comp = &(image->comps[i]);
if (! l_comp->sgnd) {
tccp->m_dc_level_shift = 1 << (l_comp->prec - 1);
}
}
}
for (i = 0; i < image->numcomps; i++) {
opj_tccp_t *tccp = &tcp->tccps[i];
tccp->csty = parameters->csty & 0x01; /* 0 => one precinct || 1 => custom precinct */
tccp->numresolutions = (OPJ_UINT32)parameters->numresolution;
tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init);
tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init);
tccp->cblksty = (OPJ_UINT32)parameters->mode;
tccp->qmfbid = parameters->irreversible ? 0 : 1;
tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT;
tccp->numgbits = 2;
if ((OPJ_INT32)i == parameters->roi_compno) {
tccp->roishift = parameters->roi_shift;
} else {
tccp->roishift = 0;
}
if (parameters->csty & J2K_CCP_CSTY_PRT) {
OPJ_INT32 p = 0, it_res;
assert( tccp->numresolutions > 0 );
for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) {
if (p < parameters->res_spec) {
if (parameters->prcw_init[p] < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]);
}
if (parameters->prch_init[p] < 1) {
tccp->prch[it_res] = 1;
}else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]);
}
} else {
OPJ_INT32 res_spec = parameters->res_spec;
OPJ_INT32 size_prcw = 0;
OPJ_INT32 size_prch = 0;
assert(res_spec>0); /* issue 189 */
size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1));
size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1));
if (size_prcw < 1) {
tccp->prcw[it_res] = 1;
} else {
tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw);
}
if (size_prch < 1) {
tccp->prch[it_res] = 1;
} else {
tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch);
}
}
p++;
/*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */
} /*end for*/
} else {
for (j = 0; j < tccp->numresolutions; j++) {
tccp->prcw[j] = 15;
tccp->prch[j] = 15;
}
}
opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec);
}
}
if (parameters->mct_data) {
opj_free(parameters->mct_data);
parameters->mct_data = 00;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
{
assert(cstr_index != 00);
/* expand the list? */
if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32) cstr_index->maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker, cstr_index->maxmarknum *sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->marker);
cstr_index->marker = NULL;
cstr_index->maxmarknum = 0;
cstr_index->marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */
return OPJ_FALSE;
}
cstr_index->marker = new_marker;
}
/* add the marker */
cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type;
cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos;
cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len;
cstr_index->marknum++;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno, opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len)
{
assert(cstr_index != 00);
assert(cstr_index->tile_index != 00);
/* expand the list? */
if ((cstr_index->tile_index[tileno].marknum + 1) > cstr_index->tile_index[tileno].maxmarknum) {
opj_marker_info_t *new_marker;
cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum);
new_marker = (opj_marker_info_t *) opj_realloc(
cstr_index->tile_index[tileno].marker,
cstr_index->tile_index[tileno].maxmarknum *sizeof(opj_marker_info_t));
if (! new_marker) {
opj_free(cstr_index->tile_index[tileno].marker);
cstr_index->tile_index[tileno].marker = NULL;
cstr_index->tile_index[tileno].maxmarknum = 0;
cstr_index->tile_index[tileno].marknum = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */
return OPJ_FALSE;
}
cstr_index->tile_index[tileno].marker = new_marker;
}
/* add the marker */
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type = (OPJ_UINT16)type;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos = (OPJ_INT32)pos;
cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len = (OPJ_INT32)len;
cstr_index->tile_index[tileno].marknum++;
if (type == J2K_MS_SOT) {
OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno;
if (cstr_index->tile_index[tileno].tp_index)
cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos;
}
return OPJ_TRUE;
}
/*
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
* -----------------------------------------------------------------------
*/
OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_header( opj_stream_private_t *p_stream,
opj_j2k_t* p_j2k,
opj_image_t** p_image,
opj_event_mgr_t* p_manager )
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* create an empty image header */
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
return OPJ_FALSE;
}
/* customization of the validation */
if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream,p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* read header */
if (! opj_j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
*p_image = opj_image_create0();
if (! (*p_image)) {
return OPJ_FALSE;
}
/* Copy codestream image information to the output image */
opj_copy_image_header(p_j2k->m_private_image, *p_image);
/*Allocate and initialize some elements of codestrem index*/
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)){
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_reading (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_read_header_procedure, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_decoding_validation (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,(opj_procedure)opj_j2k_build_decoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list,(opj_procedure)opj_j2k_decoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_mct_validation ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
OPJ_UINT32 i,j;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
for (i=0;i<l_nb_tiles;++i) {
if (l_tcp->mct == 2) {
opj_tccp_t * l_tccp = l_tcp->tccps;
l_is_valid &= (l_tcp->m_mct_coding_matrix != 00);
for (j=0;j<p_j2k->m_private_image->numcomps;++j) {
l_is_valid &= ! (l_tccp->qmfbid & 1);
++l_tccp;
}
}
++l_tcp;
}
}
return l_is_valid;
}
OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image)
{
OPJ_UINT32 i;
OPJ_UINT32 l_indix = 1;
opj_mct_data_t * l_mct_deco_data = 00,* l_mct_offset_data = 00;
opj_simple_mcc_decorrelation_data_t * l_mcc_data;
OPJ_UINT32 l_mct_size,l_nb_elem;
OPJ_FLOAT32 * l_data, * l_current_data;
opj_tccp_t * l_tccp;
/* preconditions */
assert(p_tcp != 00);
if (p_tcp->mct != 2) {
return OPJ_TRUE;
}
if (p_tcp->m_mct_decoding_matrix) {
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records, p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_deco_data ,0,(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(opj_mct_data_t));
}
l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_deco_data->m_data) {
opj_free(l_mct_deco_data->m_data);
l_mct_deco_data->m_data = 00;
}
l_mct_deco_data->m_index = l_indix++;
l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION;
l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps * p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type];
l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size );
if (! l_mct_deco_data->m_data) {
return OPJ_FALSE;
}
j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type](p_tcp->m_mct_decoding_matrix,l_mct_deco_data->m_data,l_nb_elem);
l_mct_deco_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
}
if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) {
opj_mct_data_t *new_mct_records;
p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records, p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t));
if (! new_mct_records) {
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = NULL;
p_tcp->m_nb_max_mct_records = 0;
p_tcp->m_nb_mct_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mct_records = new_mct_records;
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
memset(l_mct_offset_data ,0,(p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof(opj_mct_data_t));
if (l_mct_deco_data) {
l_mct_deco_data = l_mct_offset_data - 1;
}
}
l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records;
if (l_mct_offset_data->m_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
}
l_mct_offset_data->m_index = l_indix++;
l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET;
l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT;
l_nb_elem = p_image->numcomps;
l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type];
l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size );
if (! l_mct_offset_data->m_data) {
return OPJ_FALSE;
}
l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32));
if (! l_data) {
opj_free(l_mct_offset_data->m_data);
l_mct_offset_data->m_data = 00;
return OPJ_FALSE;
}
l_tccp = p_tcp->tccps;
l_current_data = l_data;
for (i=0;i<l_nb_elem;++i) {
*(l_current_data++) = (OPJ_FLOAT32) (l_tccp->m_dc_level_shift);
++l_tccp;
}
j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data,l_mct_offset_data->m_data,l_nb_elem);
opj_free(l_data);
l_mct_offset_data->m_data_size = l_mct_size;
++p_tcp->m_nb_mct_records;
if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) {
opj_simple_mcc_decorrelation_data_t *new_mcc_records;
p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS;
new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc(
p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof(opj_simple_mcc_decorrelation_data_t));
if (! new_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = NULL;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
/* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */
return OPJ_FALSE;
}
p_tcp->m_mcc_records = new_mcc_records;
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
memset(l_mcc_data ,0,(p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t));
}
l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records;
l_mcc_data->m_decorrelation_array = l_mct_deco_data;
l_mcc_data->m_is_irreversible = 1;
l_mcc_data->m_nb_comps = p_image->numcomps;
l_mcc_data->m_index = l_indix++;
l_mcc_data->m_offset_array = l_mct_offset_data;
++p_tcp->m_nb_mcc_records;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_decoder (opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
/* add here initialization of cp
copy paste of setup_decoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_build_encoder (opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
/* add here initialization of cp
copy paste of setup_encoder */
(void)p_j2k;
(void)p_stream;
(void)p_manager;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_encoding_validation ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* STATE checking */
/* make sure the state is at 0 */
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE);
/* POINTER validation */
/* make sure a p_j2k codec is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */
/* 33 (32) would always fail the check below (if a cast to 64bits was done) */
/* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */
if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) || (p_j2k->m_cp.tcps->tccps->numresolutions > 32)) {
opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdx) < (OPJ_UINT32) (1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
if ((p_j2k->m_cp.tdy) < (OPJ_UINT32) (1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) {
opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n");
return OPJ_FALSE;
}
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_decoding_validation ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
OPJ_BOOL l_is_valid = OPJ_TRUE;
/* preconditions*/
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
/* STATE checking */
/* make sure the state is at 0 */
#ifdef TODO_MSD
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE);
#endif
l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000);
/* POINTER validation */
/* make sure a p_j2k codec is present */
/* make sure a procedure list is present */
l_is_valid &= (p_j2k->m_procedure_list != 00);
/* make sure a validation list is present */
l_is_valid &= (p_j2k->m_validation_list != 00);
/* PARAMETER VALIDATION */
return l_is_valid;
}
static OPJ_BOOL opj_j2k_read_header_procedure( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
OPJ_BOOL l_has_siz = 0;
OPJ_BOOL l_has_cod = 0;
OPJ_BOOL l_has_qcd = 0;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* We enter in the main header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC;
/* Try to read the SOC marker, the codestream must begin with SOC marker */
if (! opj_j2k_read_soc(p_j2k,p_stream,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
/* Try to read until the SOT is detected */
while (l_current_marker != J2K_MS_SOT) {
/* Check if the current marker ID is valid */
if (l_current_marker < 0xff00) {
opj_event_msg(p_manager, EVT_ERROR, "A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker);
return OPJ_FALSE;
}
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Manage case where marker is unknown */
if (l_marker_handler->id == J2K_MS_UNK) {
if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)){
opj_event_msg(p_manager, EVT_ERROR, "Unknow marker have been detected and generated error.\n");
return OPJ_FALSE;
}
if (l_current_marker == J2K_MS_SOT)
break; /* SOT marker is detected main header is completely read */
else /* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
}
if (l_marker_handler->id == J2K_MS_SIZ) {
/* Mark required SIZ marker as found */
l_has_siz = 1;
}
if (l_marker_handler->id == J2K_MS_COD) {
/* Mark required COD marker as found */
l_has_cod = 1;
}
if (l_marker_handler->id == J2K_MS_QCD) {
/* Mark required QCD marker as found */
l_has_qcd = 1;
}
/* Check if the marker is known and if it is the right place to find it */
if (! (p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states) ) {
opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_marker_size,2);
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (! (*(l_marker_handler->handler))(p_j2k,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Marker handler function failed to read the marker segment\n");
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_mhmarker(
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4 )) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n");
return OPJ_FALSE;
}
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* read 2 bytes as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
}
if (l_has_siz == 0) {
opj_event_msg(p_manager, EVT_ERROR, "required SIZ marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_cod == 0) {
opj_event_msg(p_manager, EVT_ERROR, "required COD marker not found in main header\n");
return OPJ_FALSE;
}
if (l_has_qcd == 0) {
opj_event_msg(p_manager, EVT_ERROR, "required QCD marker not found in main header\n");
return OPJ_FALSE;
}
if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n");
/* Position of the last element if the main header */
p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2;
/* Next step: read a tile-part header */
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_exec ( opj_j2k_t * p_j2k,
opj_procedure_list_t * p_procedure_list,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_BOOL (** l_procedure) (opj_j2k_t * ,opj_stream_private_t *,opj_event_mgr_t *) = 00;
OPJ_BOOL l_result = OPJ_TRUE;
OPJ_UINT32 l_nb_proc, i;
/* preconditions*/
assert(p_procedure_list != 00);
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
l_procedure = (OPJ_BOOL (**) (opj_j2k_t * ,opj_stream_private_t *,opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
for (i=0;i<l_nb_proc;++i) {
l_result = l_result && ((*l_procedure) (p_j2k,p_stream,p_manager));
++l_procedure;
}
/* and clear the procedure list at the end.*/
opj_procedure_list_clear(p_procedure_list);
return l_result;
}
/* FIXME DOC*/
static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
opj_tcp_t * l_tcp = 00;
opj_tcp_t * l_default_tcp = 00;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 i,j;
opj_tccp_t *l_current_tccp = 00;
OPJ_UINT32 l_tccp_size;
OPJ_UINT32 l_mct_size;
opj_image_t * l_image;
OPJ_UINT32 l_mcc_records_size,l_mct_records_size;
opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec;
opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec;
OPJ_UINT32 l_offset;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
l_image = p_j2k->m_private_image;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps;
l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t);
l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof(OPJ_FLOAT32);
/* For each tile */
for (i=0; i<l_nb_tiles; ++i) {
/* keep the tile-compo coding parameters pointer of the current tile coding parameters*/
l_current_tccp = l_tcp->tccps;
/*Copy default coding parameters into the current tile coding parameters*/
memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t));
/* Initialize some values of the current tile coding parameters*/
l_tcp->cod = 0;
l_tcp->ppt = 0;
l_tcp->ppt_data = 00;
/* Remove memory not owned by this tile in case of early error return. */
l_tcp->m_mct_decoding_matrix = 00;
l_tcp->m_nb_max_mct_records = 0;
l_tcp->m_mct_records = 00;
l_tcp->m_nb_max_mcc_records = 0;
l_tcp->m_mcc_records = 00;
/* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/
l_tcp->tccps = l_current_tccp;
/* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/
if (l_default_tcp->m_mct_decoding_matrix) {
l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size);
if (! l_tcp->m_mct_decoding_matrix ) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_decoding_matrix,l_default_tcp->m_mct_decoding_matrix,l_mct_size);
}
/* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof(opj_mct_data_t);
l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size);
if (! l_tcp->m_mct_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records,l_mct_records_size);
/* Copy the mct record data from dflt_tile_cp to the current tile*/
l_src_mct_rec = l_default_tcp->m_mct_records;
l_dest_mct_rec = l_tcp->m_mct_records;
for (j=0;j<l_default_tcp->m_nb_mct_records;++j) {
if (l_src_mct_rec->m_data) {
l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size);
if(! l_dest_mct_rec->m_data) {
return OPJ_FALSE;
}
memcpy(l_dest_mct_rec->m_data,l_src_mct_rec->m_data,l_src_mct_rec->m_data_size);
}
++l_src_mct_rec;
++l_dest_mct_rec;
/* Update with each pass to free exactly what has been allocated on early return. */
l_tcp->m_nb_max_mct_records += 1;
}
/* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/
l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof(opj_simple_mcc_decorrelation_data_t);
l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc(l_mcc_records_size);
if (! l_tcp->m_mcc_records) {
return OPJ_FALSE;
}
memcpy(l_tcp->m_mcc_records,l_default_tcp->m_mcc_records,l_mcc_records_size);
l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records;
/* Copy the mcc record data from dflt_tile_cp to the current tile*/
l_src_mcc_rec = l_default_tcp->m_mcc_records;
l_dest_mcc_rec = l_tcp->m_mcc_records;
for (j=0;j<l_default_tcp->m_nb_max_mcc_records;++j) {
if (l_src_mcc_rec->m_decorrelation_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array - l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset;
}
if (l_src_mcc_rec->m_offset_array) {
l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array - l_default_tcp->m_mct_records);
l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset;
}
++l_src_mcc_rec;
++l_dest_mcc_rec;
}
/* Copy all the dflt_tile_compo_cp to the current tile cp */
memcpy(l_current_tccp,l_default_tcp->tccps,l_tccp_size);
/* Move to next tile cp*/
++l_tcp;
}
/* Create the current tile decoder*/
p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */
if (! p_j2k->m_tcd ) {
return OPJ_FALSE;
}
if ( !opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp) ) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler (OPJ_UINT32 p_id)
{
const opj_dec_memory_marker_handler_t *e;
for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) {
if (e->id == p_id) {
break; /* we find a handler corresponding to the marker ID*/
}
}
return e;
}
void opj_j2k_destroy (opj_j2k_t *p_j2k)
{
if (p_j2k == 00) {
return;
}
if (p_j2k->m_is_decoder) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) {
opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp);
opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp);
p_j2k->m_specific_param.m_decoder.m_default_tcp = 00;
}
if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = 00;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
}
}
else {
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00;
}
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00;
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
}
}
opj_tcd_destroy(p_j2k->m_tcd);
opj_j2k_cp_destroy(&(p_j2k->m_cp));
memset(&(p_j2k->m_cp),0,sizeof(opj_cp_t));
opj_procedure_list_destroy(p_j2k->m_procedure_list);
p_j2k->m_procedure_list = 00;
opj_procedure_list_destroy(p_j2k->m_validation_list);
p_j2k->m_procedure_list = 00;
j2k_destroy_cstr_index(p_j2k->cstr_index);
p_j2k->cstr_index = NULL;
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
opj_image_destroy(p_j2k->m_output_image);
p_j2k->m_output_image = NULL;
opj_thread_pool_destroy(p_j2k->m_tp);
p_j2k->m_tp = NULL;
opj_free(p_j2k);
}
void j2k_destroy_cstr_index (opj_codestream_index_t *p_cstr_ind)
{
if (p_cstr_ind) {
if (p_cstr_ind->marker) {
opj_free(p_cstr_ind->marker);
p_cstr_ind->marker = NULL;
}
if (p_cstr_ind->tile_index) {
OPJ_UINT32 it_tile = 0;
for (it_tile=0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) {
if(p_cstr_ind->tile_index[it_tile].packet_index) {
opj_free(p_cstr_ind->tile_index[it_tile].packet_index);
p_cstr_ind->tile_index[it_tile].packet_index = NULL;
}
if(p_cstr_ind->tile_index[it_tile].tp_index){
opj_free(p_cstr_ind->tile_index[it_tile].tp_index);
p_cstr_ind->tile_index[it_tile].tp_index = NULL;
}
if(p_cstr_ind->tile_index[it_tile].marker){
opj_free(p_cstr_ind->tile_index[it_tile].marker);
p_cstr_ind->tile_index[it_tile].marker = NULL;
}
}
opj_free( p_cstr_ind->tile_index);
p_cstr_ind->tile_index = NULL;
}
opj_free(p_cstr_ind);
}
}
static void opj_j2k_tcp_destroy (opj_tcp_t *p_tcp)
{
if (p_tcp == 00) {
return;
}
if (p_tcp->ppt_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_tcp->ppt_markers_count; ++i) {
if (p_tcp->ppt_markers[i].m_data != NULL) {
opj_free(p_tcp->ppt_markers[i].m_data);
}
}
p_tcp->ppt_markers_count = 0U;
opj_free(p_tcp->ppt_markers);
p_tcp->ppt_markers = NULL;
}
if (p_tcp->ppt_buffer != 00) {
opj_free(p_tcp->ppt_buffer);
p_tcp->ppt_buffer = 00;
}
if (p_tcp->tccps != 00) {
opj_free(p_tcp->tccps);
p_tcp->tccps = 00;
}
if (p_tcp->m_mct_coding_matrix != 00) {
opj_free(p_tcp->m_mct_coding_matrix);
p_tcp->m_mct_coding_matrix = 00;
}
if (p_tcp->m_mct_decoding_matrix != 00) {
opj_free(p_tcp->m_mct_decoding_matrix);
p_tcp->m_mct_decoding_matrix = 00;
}
if (p_tcp->m_mcc_records) {
opj_free(p_tcp->m_mcc_records);
p_tcp->m_mcc_records = 00;
p_tcp->m_nb_max_mcc_records = 0;
p_tcp->m_nb_mcc_records = 0;
}
if (p_tcp->m_mct_records) {
opj_mct_data_t * l_mct_data = p_tcp->m_mct_records;
OPJ_UINT32 i;
for (i=0;i<p_tcp->m_nb_mct_records;++i) {
if (l_mct_data->m_data) {
opj_free(l_mct_data->m_data);
l_mct_data->m_data = 00;
}
++l_mct_data;
}
opj_free(p_tcp->m_mct_records);
p_tcp->m_mct_records = 00;
}
if (p_tcp->mct_norms != 00) {
opj_free(p_tcp->mct_norms);
p_tcp->mct_norms = 00;
}
opj_j2k_tcp_data_destroy(p_tcp);
}
static void opj_j2k_tcp_data_destroy (opj_tcp_t *p_tcp)
{
if (p_tcp->m_data) {
opj_free(p_tcp->m_data);
p_tcp->m_data = NULL;
p_tcp->m_data_size = 0;
}
}
static void opj_j2k_cp_destroy (opj_cp_t *p_cp)
{
OPJ_UINT32 l_nb_tiles;
opj_tcp_t * l_current_tile = 00;
if (p_cp == 00)
{
return;
}
if (p_cp->tcps != 00)
{
OPJ_UINT32 i;
l_current_tile = p_cp->tcps;
l_nb_tiles = p_cp->th * p_cp->tw;
for (i = 0U; i < l_nb_tiles; ++i)
{
opj_j2k_tcp_destroy(l_current_tile);
++l_current_tile;
}
opj_free(p_cp->tcps);
p_cp->tcps = 00;
}
if (p_cp->ppm_markers != 00) {
OPJ_UINT32 i;
for (i = 0U; i < p_cp->ppm_markers_count; ++i) {
if (p_cp->ppm_markers[i].m_data != NULL) {
opj_free(p_cp->ppm_markers[i].m_data);
}
}
p_cp->ppm_markers_count = 0U;
opj_free(p_cp->ppm_markers);
p_cp->ppm_markers = NULL;
}
opj_free(p_cp->ppm_buffer);
p_cp->ppm_buffer = 00;
p_cp->ppm_data = NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */
opj_free(p_cp->comment);
p_cp->comment = 00;
if (! p_cp->m_is_decoder)
{
opj_free(p_cp->m_specific_param.m_enc.m_matrice);
p_cp->m_specific_param.m_enc.m_matrice = 00;
}
}
static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t *p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed, opj_event_mgr_t * p_manager )
{
OPJ_BYTE l_header_data[10];
OPJ_OFF_T l_stream_pos_backup;
OPJ_UINT32 l_current_marker;
OPJ_UINT32 l_marker_size;
OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts;
/* initialize to no correction needed */
*p_correction_needed = OPJ_FALSE;
if (!opj_stream_has_seek(p_stream)) {
/* We can't do much in this case, seek is needed */
return OPJ_TRUE;
}
l_stream_pos_backup = opj_stream_tell(p_stream);
if (l_stream_pos_backup == -1) {
/* let's do nothing */
return OPJ_TRUE;
}
for (;;) {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,l_header_data, 2, p_manager) != 2) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(l_header_data, &l_current_marker, 2);
if (l_current_marker != J2K_MS_SOT) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(l_header_data, &l_marker_size, 2);
/* Check marker size for SOT Marker */
if (l_marker_size != 10) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
l_marker_size -= 2;
if (opj_stream_read_data(p_stream, l_header_data, l_marker_size, p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no, &l_tot_len, &l_current_part, &l_num_parts, p_manager)) {
return OPJ_FALSE;
}
if (l_tile_no == tile_no) {
/* we found what we were looking for */
break;
}
if ((l_tot_len == 0U) || (l_tot_len < 14U)) {
/* last SOT until EOC or invalid Psot value */
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
l_tot_len -= 12U;
/* look for next SOT marker */
if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len), p_manager) != (OPJ_OFF_T)(l_tot_len)) {
/* assume all is OK */
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
}
/* check for correction */
if (l_current_part == l_num_parts) {
*p_correction_needed = OPJ_TRUE;
}
if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_read_tile_header( opj_j2k_t * p_j2k,
OPJ_UINT32 * p_tile_index,
OPJ_UINT32 * p_data_size,
OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
OPJ_UINT32 * p_nb_comps,
OPJ_BOOL * p_go_on,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 l_current_marker = J2K_MS_SOT;
OPJ_UINT32 l_marker_size;
const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
opj_tcp_t * l_tcp = NULL;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
/* Reach the End Of Codestream ?*/
if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC){
l_current_marker = J2K_MS_EOC;
}
/* We need to encounter a SOT marker (a new tile-part header) */
else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT){
return OPJ_FALSE;
}
/* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */
while ( (!p_j2k->m_specific_param.m_decoder.m_can_decode) && (l_current_marker != J2K_MS_EOC) ) {
/* Try to read until the Start Of Data is detected */
while (l_current_marker != J2K_MS_SOD) {
if(opj_stream_get_number_byte_left(p_stream) == 0)
{
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the marker size */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_marker_size,2);
/* Check marker size (does not include marker ID but includes marker size) */
if (l_marker_size < 2) {
opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n");
return OPJ_FALSE;
}
/* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */
if (l_current_marker == 0x8080 && opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
break;
}
/* Why this condition? FIXME */
if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH){
p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2);
}
l_marker_size -= 2; /* Subtract the size of the marker ID already read */
/* Get the marker handler from the marker ID */
l_marker_handler = opj_j2k_get_marker_handler(l_current_marker);
/* Check if the marker is known and if it is the right place to find it */
if (! (p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states) ) {
opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n");
return OPJ_FALSE;
}
/* FIXME manage case of unknown marker as in the main header ? */
/* Check if the marker size is compatible with the header data size */
if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) {
OPJ_BYTE *new_header_data = NULL;
/* If we are here, this means we consider this marker as known & we will read it */
/* Check enough bytes left in stream before allocation */
if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) {
opj_event_msg(p_manager, EVT_ERROR, "Marker size inconsistent with stream length\n");
return OPJ_FALSE;
}
new_header_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size);
if (! new_header_data) {
opj_free(p_j2k->m_specific_param.m_decoder.m_header_data);
p_j2k->m_specific_param.m_decoder.m_header_data = NULL;
p_j2k->m_specific_param.m_decoder.m_header_data_size = 0;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n");
return OPJ_FALSE;
}
p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data;
p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size;
}
/* Try to read the rest of the marker segment from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager) != l_marker_size) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
if (!l_marker_handler->handler) {
/* See issue #175 */
opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n");
return OPJ_FALSE;
}
/* Read the marker segment with the correct marker handler */
if (! (*(l_marker_handler->handler))(p_j2k,p_j2k->m_specific_param.m_decoder.m_header_data,l_marker_size,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Fail to read the current marker segment (%#x)\n", l_current_marker);
return OPJ_FALSE;
}
/* Add the marker to the codestream index*/
if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number,
p_j2k->cstr_index,
l_marker_handler->id,
(OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4,
l_marker_size + 4 )) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n");
return OPJ_FALSE;
}
/* Keep the position of the last SOT marker read */
if ( l_marker_handler->id == J2K_MS_SOT ) {
OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4 ;
if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos)
{
p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos;
}
}
if (p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Skip the rest of the tile part header*/
if (opj_stream_skip(p_stream,p_j2k->m_specific_param.m_decoder.m_sot_length,p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */
}
else {
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from the buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
}
}
if(opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC)
break;
/* If we didn't skip data before, we need to read the SOD marker*/
if (! p_j2k->m_specific_param.m_decoder.m_skip_data) {
/* Try to read the SOD marker and skip data ? FIXME */
if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_specific_param.m_decoder.m_can_decode && !p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) {
/* Issue 254 */
OPJ_BOOL l_correction_needed;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
if(!opj_j2k_need_nb_tile_parts_correction(p_stream, p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "opj_j2k_apply_nb_tile_parts_correction error\n");
return OPJ_FALSE;
}
if (l_correction_needed) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
OPJ_UINT32 l_tile_no;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
/* correct tiles */
for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts+=1;
}
}
opj_event_msg(p_manager, EVT_WARNING, "Non conformant codestream TPsot==TNsot.\n");
}
}
if (! p_j2k->m_specific_param.m_decoder.m_can_decode){
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
}
}
else {
/* Indicate we will try to read a new tile-part header*/
p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
/* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
if (opj_stream_read_data(p_stream,p_j2k->m_specific_param.m_decoder.m_header_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
/* Read 2 bytes from buffer as the new marker ID */
opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,&l_current_marker,2);
}
}
/* Current marker is the EOC marker ?*/
if (l_current_marker == J2K_MS_EOC) {
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC ){
p_j2k->m_current_tile_number = 0;
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
}
}
/* FIXME DOC ???*/
if ( ! p_j2k->m_specific_param.m_decoder.m_can_decode) {
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;
while( (p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00) ) {
++p_j2k->m_current_tile_number;
++l_tcp;
}
if (p_j2k->m_current_tile_number == l_nb_tiles) {
*p_go_on = OPJ_FALSE;
return OPJ_TRUE;
}
}
if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n");
return OPJ_FALSE;
}
/*FIXME ???*/
if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number, p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n");
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n",
p_j2k->m_current_tile_number+1, (p_j2k->m_cp.th * p_j2k->m_cp.tw));
*p_tile_index = p_j2k->m_current_tile_number;
*p_go_on = OPJ_TRUE;
*p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd);
*p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0;
*p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0;
*p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1;
*p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1;
*p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps;
p_j2k->m_specific_param.m_decoder.m_state |= 0x0080;/* FIXME J2K_DEC_STATE_DATA;*/
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode_tile ( opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 l_current_marker;
OPJ_BYTE l_data [2];
opj_tcp_t * l_tcp;
/* preconditions */
assert(p_stream != 00);
assert(p_j2k != 00);
assert(p_manager != 00);
if ( !(p_j2k->m_specific_param.m_decoder.m_state & 0x0080/*FIXME J2K_DEC_STATE_DATA*/)
|| (p_tile_index != p_j2k->m_current_tile_number) ) {
return OPJ_FALSE;
}
l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]);
if (! l_tcp->m_data) {
opj_j2k_tcp_destroy(l_tcp);
return OPJ_FALSE;
}
if (! opj_tcd_decode_tile( p_j2k->m_tcd,
l_tcp->m_data,
l_tcp->m_data_size,
p_tile_index,
p_j2k->cstr_index, p_manager) ) {
opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;/*FIXME J2K_DEC_STATE_ERR;*/
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n");
return OPJ_FALSE;
}
if (! opj_tcd_update_tile_data(p_j2k->m_tcd,p_data,p_data_size)) {
return OPJ_FALSE;
}
/* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access)
* we destroy just the data which will be re-read in read_tile_header*/
/*opj_j2k_tcp_destroy(l_tcp);
p_j2k->m_tcd->tcp = 0;*/
opj_j2k_tcp_data_destroy(l_tcp);
p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
p_j2k->m_specific_param.m_decoder.m_state &= (~ (0x0080u));/* FIXME J2K_DEC_STATE_DATA);*/
if(opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC){
return OPJ_TRUE;
}
if (p_j2k->m_specific_param.m_decoder.m_state != 0x0100){ /*FIXME J2K_DEC_STATE_EOC)*/
if (opj_stream_read_data(p_stream,l_data,2,p_manager) != 2) {
opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
return OPJ_FALSE;
}
opj_read_bytes(l_data,&l_current_marker,2);
if (l_current_marker == J2K_MS_EOC) {
p_j2k->m_current_tile_number = 0;
p_j2k->m_specific_param.m_decoder.m_state = 0x0100;/*FIXME J2K_DEC_STATE_EOC;*/
}
else if (l_current_marker != J2K_MS_SOT)
{
if(opj_stream_get_number_byte_left(p_stream) == 0) {
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC;
opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n");
return OPJ_TRUE;
}
opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n");
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_update_image_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image)
{
OPJ_UINT32 i,j,k = 0;
OPJ_UINT32 l_width_src,l_height_src;
OPJ_UINT32 l_width_dest,l_height_dest;
OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src;
OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ;
OPJ_UINT32 l_start_x_dest , l_start_y_dest;
OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest;
OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest;
opj_image_comp_t * l_img_comp_src = 00;
opj_image_comp_t * l_img_comp_dest = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_image_t * l_image_src = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_INT32 * l_dest_ptr;
opj_tcd_resolution_t* l_res= 00;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_image_src = p_tcd->image;
l_img_comp_src = l_image_src->comps;
l_img_comp_dest = p_output_image->comps;
for (i=0; i<l_image_src->numcomps; i++) {
/* Allocate output component buffer if necessary */
if (!l_img_comp_dest->data) {
OPJ_SIZE_T l_width = l_img_comp_dest->w;
OPJ_SIZE_T l_height = l_img_comp_dest->h;
if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height))) {
/* would overflow */
return OPJ_FALSE;
}
l_img_comp_dest->data = (OPJ_INT32*) opj_calloc(l_width * l_height, sizeof(OPJ_INT32));
if (! l_img_comp_dest->data) {
return OPJ_FALSE;
}
}
/* Copy info from decoded comp image to output image */
l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded;
/*-----*/
/* Compute the precision of the output buffer */
l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp_src->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
/*-----*/
/* Current tile component size*/
/*if (i == 0) {
fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n",
l_res->x0, l_res->x1, l_res->y0, l_res->y1);
}*/
l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0);
/* Border of the current output component*/
l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor);
l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor);
l_x1_dest = l_x0_dest + l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */
l_y1_dest = l_y0_dest + l_img_comp_dest->h;
/*if (i == 0) {
fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n",
l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor );
}*/
/*-----*/
/* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src)
* of the input buffer (decoded tile component) which will be move
* in the output buffer. Compute the area of the output buffer (l_start_x_dest,
* l_start_y_dest, l_width_dest, l_height_dest) which will be modified
* by this input area.
* */
assert( l_res->x0 >= 0);
assert( l_res->x1 >= 0);
if ( l_x0_dest < (OPJ_UINT32)l_res->x0 ) {
l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest;
l_offset_x0_src = 0;
if ( l_x1_dest >= (OPJ_UINT32)l_res->x1 ) {
l_width_dest = l_width_src;
l_offset_x1_src = 0;
}
else {
l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ;
l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest);
}
}
else {
l_start_x_dest = 0U;
l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0;
if ( l_x1_dest >= (OPJ_UINT32)l_res->x1 ) {
l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src;
l_offset_x1_src = 0;
}
else {
l_width_dest = l_img_comp_dest->w ;
l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest;
}
}
if ( l_y0_dest < (OPJ_UINT32)l_res->y0 ) {
l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest;
l_offset_y0_src = 0;
if ( l_y1_dest >= (OPJ_UINT32)l_res->y1 ) {
l_height_dest = l_height_src;
l_offset_y1_src = 0;
}
else {
l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ;
l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest);
}
}
else {
l_start_y_dest = 0U;
l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0;
if ( l_y1_dest >= (OPJ_UINT32)l_res->y1 ) {
l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src;
l_offset_y1_src = 0;
}
else {
l_height_dest = l_img_comp_dest->h ;
l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest;
}
}
if( (l_offset_x0_src < 0 ) || (l_offset_y0_src < 0 ) || (l_offset_x1_src < 0 ) || (l_offset_y1_src < 0 ) ){
return OPJ_FALSE;
}
/* testcase 2977.pdf.asan.67.2198 */
if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) {
return OPJ_FALSE;
}
/*-----*/
/* Compute the input buffer offset */
l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src * (OPJ_SIZE_T)l_width_src;
l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src;
l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src - (OPJ_SIZE_T)l_offset_x0_src;
/* Compute the output buffer offset */
l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest * (OPJ_SIZE_T)l_img_comp_dest->w;
l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest;
/* Move the output buffer to the first place where we will write*/
l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest;
/*if (i == 0) {
fprintf(stdout, "COMPO[%d]:\n",i);
fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n"
"\t tile offset:%d, %d, %d, %d\n"
"\t buffer offset: %d; %d, %d\n",
l_res->x0, l_res->y0, l_width_src, l_height_src,
l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src,
l_start_offset_src, l_line_offset_src, l_end_offset_src);
fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n"
"\t start offset: %d, line offset= %d\n",
l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest);
}*/
switch (l_size_comp) {
case 1:
{
OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data;
l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/
if (l_img_comp_src->sgnd) {
for (j = 0 ; j < l_height_dest ; ++j) {
for ( k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); /* Copy only the data needed for the output image */
}
l_dest_ptr+= l_line_offset_dest; /* Move to the next place where we will write */
l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */
}
}
else {
for ( j = 0 ; j < l_height_dest ; ++j ) {
for ( k = 0 ; k < l_width_dest ; ++k) {
*(l_dest_ptr++) = (OPJ_INT32) ((*(l_src_ptr++))&0xff);
}
l_dest_ptr+= l_line_offset_dest;
l_src_ptr += l_line_offset_src;
}
}
l_src_ptr += l_end_offset_src; /* Move to the end of this component-part of the input buffer */
p_data = (OPJ_BYTE*) l_src_ptr; /* Keep the current position for the next component-part */
}
break;
case 2:
{
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data;
l_src_ptr += l_start_offset_src;
if (l_img_comp_src->sgnd) {
for (j=0;j<l_height_dest;++j) {
for (k=0;k<l_width_dest;++k) {
*(l_dest_ptr++) = *(l_src_ptr++);
}
l_dest_ptr+= l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
}
else {
for (j=0;j<l_height_dest;++j) {
for (k=0;k<l_width_dest;++k) {
*(l_dest_ptr++) = (*(l_src_ptr++))&0xffff;
}
l_dest_ptr+= l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4:
{
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data;
l_src_ptr += l_start_offset_src;
for (j=0;j<l_height_dest;++j) {
for (k=0;k<l_width_dest;++k) {
*(l_dest_ptr++) = (*(l_src_ptr++));
}
l_dest_ptr+= l_line_offset_dest;
l_src_ptr += l_line_offset_src ;
}
l_src_ptr += l_end_offset_src;
p_data = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp_dest;
++l_img_comp_src;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decode_area( opj_j2k_t *p_j2k,
opj_image_t* p_image,
OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
opj_event_mgr_t * p_manager )
{
opj_cp_t * l_cp = &(p_j2k->m_cp);
opj_image_t * l_image = p_j2k->m_private_image;
OPJ_UINT32 it_comp;
OPJ_INT32 l_comp_x1, l_comp_y1;
opj_image_comp_t* l_img_comp = NULL;
/* Check if we are read the main header */
if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) { /* FIXME J2K_DEC_STATE_TPHSOT)*/
opj_event_msg(p_manager, EVT_ERROR, "Need to decode the main header before begin to decode the remaining codestream");
return OPJ_FALSE;
}
if ( !p_start_x && !p_start_y && !p_end_x && !p_end_y){
opj_event_msg(p_manager, EVT_INFO, "No decoded area parameters, set the decoded area to the whole image\n");
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
return OPJ_TRUE;
}
/* ----- */
/* Check if the positions provided by the user are correct */
/* Left */
assert(p_start_x >= 0 );
assert(p_start_y >= 0 );
if ((OPJ_UINT32)p_start_x > l_image->x1 ) {
opj_event_msg(p_manager, EVT_ERROR,
"Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n",
p_start_x, l_image->x1);
return OPJ_FALSE;
}
else if ((OPJ_UINT32)p_start_x < l_image->x0){
opj_event_msg(p_manager, EVT_WARNING,
"Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n",
p_start_x, l_image->x0);
p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0;
p_image->x0 = l_image->x0;
}
else {
p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x - l_cp->tx0) / l_cp->tdx;
p_image->x0 = (OPJ_UINT32)p_start_x;
}
/* Up */
if ((OPJ_UINT32)p_start_y > l_image->y1){
opj_event_msg(p_manager, EVT_ERROR,
"Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n",
p_start_y, l_image->y1);
return OPJ_FALSE;
}
else if ((OPJ_UINT32)p_start_y < l_image->y0){
opj_event_msg(p_manager, EVT_WARNING,
"Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n",
p_start_y, l_image->y0);
p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0;
p_image->y0 = l_image->y0;
}
else {
p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y - l_cp->ty0) / l_cp->tdy;
p_image->y0 = (OPJ_UINT32)p_start_y;
}
/* Right */
assert((OPJ_UINT32)p_end_x > 0);
assert((OPJ_UINT32)p_end_y > 0);
if ((OPJ_UINT32)p_end_x < l_image->x0) {
opj_event_msg(p_manager, EVT_ERROR,
"Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n",
p_end_x, l_image->x0);
return OPJ_FALSE;
}
else if ((OPJ_UINT32)p_end_x > l_image->x1) {
opj_event_msg(p_manager, EVT_WARNING,
"Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n",
p_end_x, l_image->x1);
p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw;
p_image->x1 = l_image->x1;
}
else {
p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx);
p_image->x1 = (OPJ_UINT32)p_end_x;
}
/* Bottom */
if ((OPJ_UINT32)p_end_y < l_image->y0) {
opj_event_msg(p_manager, EVT_ERROR,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n",
p_end_y, l_image->y0);
return OPJ_FALSE;
}
if ((OPJ_UINT32)p_end_y > l_image->y1){
opj_event_msg(p_manager, EVT_WARNING,
"Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n",
p_end_y, l_image->y1);
p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th;
p_image->y1 = l_image->y1;
}
else{
p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy);
p_image->y1 = (OPJ_UINT32)p_end_y;
}
/* ----- */
p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1;
l_img_comp = p_image->comps;
for (it_comp=0; it_comp < p_image->numcomps; ++it_comp)
{
OPJ_INT32 l_h,l_w;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor);
if (l_w < 0){
opj_event_msg(p_manager, EVT_ERROR,
"Size x of the decoded component image is incorrect (comp[%d].w=%d).\n",
it_comp, l_w);
return OPJ_FALSE;
}
l_img_comp->w = (OPJ_UINT32)l_w;
l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor)
- opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor);
if (l_h < 0){
opj_event_msg(p_manager, EVT_ERROR,
"Size y of the decoded component image is incorrect (comp[%d].h=%d).\n",
it_comp, l_h);
return OPJ_FALSE;
}
l_img_comp->h = (OPJ_UINT32)l_h;
l_img_comp++;
}
opj_event_msg( p_manager, EVT_INFO,"Setting decoding area to %d,%d,%d,%d\n",
p_image->x0, p_image->y0, p_image->x1, p_image->y1);
return OPJ_TRUE;
}
opj_j2k_t* opj_j2k_create_decompress(void)
{
opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1,sizeof(opj_j2k_t));
if (!l_j2k) {
return 00;
}
l_j2k->m_is_decoder = 1;
l_j2k->m_cp.m_is_decoder = 1;
#ifdef OPJ_DISABLE_TPSOT_FIX
l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1;
#endif
l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1,sizeof(opj_tcp_t));
if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1,OPJ_J2K_DEFAULT_HEADER_SIZE);
if (! l_j2k->m_specific_param.m_decoder.m_header_data) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_specific_param.m_decoder.m_header_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE;
l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ;
l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ;
/* codestream index creation */
l_j2k->cstr_index = opj_j2k_create_cstr_index();
if (!l_j2k->cstr_index){
opj_j2k_destroy(l_j2k);
return 00;
}
/* validation list creation */
l_j2k->m_validation_list = opj_procedure_list_create();
if (! l_j2k->m_validation_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
/* execution list creation */
l_j2k->m_procedure_list = opj_procedure_list_create();
if (! l_j2k->m_procedure_list) {
opj_j2k_destroy(l_j2k);
return 00;
}
l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count());
if( !l_j2k->m_tp )
{
l_j2k->m_tp = opj_thread_pool_create(0);
}
if( !l_j2k->m_tp )
{
opj_j2k_destroy(l_j2k);
return NULL;
}
return l_j2k;
}
static opj_codestream_index_t* opj_j2k_create_cstr_index(void)
{
opj_codestream_index_t* cstr_index = (opj_codestream_index_t*)
opj_calloc(1,sizeof(opj_codestream_index_t));
if (!cstr_index)
return NULL;
cstr_index->maxmarknum = 100;
cstr_index->marknum = 0;
cstr_index->marker = (opj_marker_info_t*)
opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t));
if (!cstr_index-> marker) {
opj_free(cstr_index);
return NULL;
}
cstr_index->tile_index = NULL;
return cstr_index;
}
static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size ( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no )
{
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no < p_j2k->m_private_image->numcomps);
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
return 5 + l_tccp->numresolutions;
}
else {
return 5;
}
}
static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->numresolutions != l_tccp1->numresolutions) {
return OPJ_FALSE;
}
if (l_tccp0->cblkw != l_tccp1->cblkw) {
return OPJ_FALSE;
}
if (l_tccp0->cblkh != l_tccp1->cblkh) {
return OPJ_FALSE;
}
if (l_tccp0->cblksty != l_tccp1->cblksty) {
return OPJ_FALSE;
}
if (l_tccp0->qmfbid != l_tccp1->qmfbid) {
return OPJ_FALSE;
}
if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) {
return OPJ_FALSE;
}
for (i = 0U; i < l_tccp0->numresolutions; ++i) {
if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) {
return OPJ_FALSE;
}
if (l_tccp0->prch[i] != l_tccp1->prch[i]) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SPCod_SPCoc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 i;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < (l_cp->tw * l_cp->th));
assert(p_comp_no <(p_j2k->m_private_image->numcomps));
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data,l_tccp->numresolutions - 1, 1); /* SPcoc (D) */
++p_data;
opj_write_bytes(p_data,l_tccp->cblkw - 2, 1); /* SPcoc (E) */
++p_data;
opj_write_bytes(p_data,l_tccp->cblkh - 2, 1); /* SPcoc (F) */
++p_data;
opj_write_bytes(p_data,l_tccp->cblksty, 1); /* SPcoc (G) */
++p_data;
opj_write_bytes(p_data,l_tccp->qmfbid, 1); /* SPcoc (H) */
++p_data;
*p_header_size = *p_header_size - 5;
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_write_bytes(p_data,l_tccp->prcw[i] + (l_tccp->prch[i] << 4), 1); /* SPcoc (I_i) */
++p_data;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SPCod_SPCoc( opj_j2k_t *p_j2k,
OPJ_UINT32 compno,
OPJ_BYTE * p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 i, l_tmp;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp = NULL;
OPJ_BYTE * l_current_ptr = NULL;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again */
assert(compno < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[compno];
l_current_ptr = p_header_data;
/* make sure room is sufficient */
if (*p_header_size < 5) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr, &l_tccp->numresolutions ,1); /* SPcox (D) */
++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */
if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
opj_event_msg(p_manager, EVT_ERROR,
"Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
return OPJ_FALSE;
}
++l_current_ptr;
/* If user wants to remove more resolutions than the codestream contains, return error */
if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number "
"of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno);
p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr,&l_tccp->cblkw ,1); /* SPcoc (E) */
++l_current_ptr;
l_tccp->cblkw += 2;
opj_read_bytes(l_current_ptr,&l_tccp->cblkh ,1); /* SPcoc (F) */
++l_current_ptr;
l_tccp->cblkh += 2;
if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) || ((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr,&l_tccp->cblksty ,1); /* SPcoc (G) */
++l_current_ptr;
if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid code-block style found\n");
return OPJ_FALSE;
}
opj_read_bytes(l_current_ptr,&l_tccp->qmfbid ,1); /* SPcoc (H) */
++l_current_ptr;
*p_header_size = *p_header_size - 5;
/* use custom precinct size ? */
if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
if (*p_header_size < l_tccp->numresolutions) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
return OPJ_FALSE;
}
for (i = 0; i < l_tccp->numresolutions; ++i) {
opj_read_bytes(l_current_ptr,&l_tmp ,1); /* SPcoc (I_i) */
++l_current_ptr;
/* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
return OPJ_FALSE;
}
l_tccp->prcw[i] = l_tmp & 0xf;
l_tccp->prch[i] = l_tmp >> 4;
}
*p_header_size = *p_header_size - l_tccp->numresolutions;
}
else {
/* set default size for the precinct width and height */
for (i = 0; i < l_tccp->numresolutions; ++i) {
l_tccp->prcw[i] = 15;
l_tccp->prch[i] = 15;
}
}
#ifdef WIP_REMOVE_MSD
/* INDEX >> */
if (p_j2k->cstr_info && compno == 0) {
OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32);
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh = l_tccp->cblkh;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw = l_tccp->cblkw;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions = l_tccp->numresolutions;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty = l_tccp->cblksty;
p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid = l_tccp->qmfbid;
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx,l_tccp->prcw, l_data_size);
memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy,l_tccp->prch, l_data_size);
}
/* << INDEX */
#endif
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_component_parameters( opj_j2k_t *p_j2k )
{
/* loop */
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL;
OPJ_UINT32 l_prc_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? /* FIXME J2K_DEC_STATE_TPH*/
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32);
for (i=1; i<p_j2k->m_private_image->numcomps; ++i) {
l_copied_tccp->numresolutions = l_ref_tccp->numresolutions;
l_copied_tccp->cblkw = l_ref_tccp->cblkw;
l_copied_tccp->cblkh = l_ref_tccp->cblkh;
l_copied_tccp->cblksty = l_ref_tccp->cblksty;
l_copied_tccp->qmfbid = l_ref_tccp->qmfbid;
memcpy(l_copied_tccp->prcw,l_ref_tccp->prcw,l_prc_size);
memcpy(l_copied_tccp->prch,l_ref_tccp->prch,l_prc_size);
++l_copied_tccp;
}
}
static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size ( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no )
{
OPJ_UINT32 l_num_bands;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
return 1 + l_num_bands;
}
else {
return 1 + 2*l_num_bands;
}
}
static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no)
{
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_tccp0 = NULL;
opj_tccp_t *l_tccp1 = NULL;
OPJ_UINT32 l_band_no, l_num_bands;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp0 = &l_tcp->tccps[p_first_comp_no];
l_tccp1 = &l_tcp->tccps[p_second_comp_no];
if (l_tccp0->qntsty != l_tccp1->qntsty ) {
return OPJ_FALSE;
}
if (l_tccp0->numgbits != l_tccp1->numgbits ) {
return OPJ_FALSE;
}
if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_bands = 1U;
} else {
l_num_bands = l_tccp0->numresolutions * 3U - 2U;
if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) {
return OPJ_FALSE;
}
}
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn ) {
return OPJ_FALSE;
}
}
if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT)
{
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant ) {
return OPJ_FALSE;
}
}
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_SQcd_SQcc( opj_j2k_t *p_j2k,
OPJ_UINT32 p_tile_no,
OPJ_UINT32 p_comp_no,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_header_size,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 l_header_size;
OPJ_UINT32 l_band_no, l_num_bands;
OPJ_UINT32 l_expn,l_mant;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_header_size != 00);
assert(p_manager != 00);
assert(p_data != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = &l_cp->tcps[p_tile_no];
l_tccp = &l_tcp->tccps[p_comp_no];
/* preconditions again */
assert(p_tile_no < l_cp->tw * l_cp->th);
assert(p_comp_no <p_j2k->m_private_image->numcomps);
l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2);
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
l_header_size = 1 + l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data,l_tccp->qntsty + (l_tccp->numgbits << 5), 1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */
++p_data;
}
}
else {
l_header_size = 1 + 2*l_num_bands;
if (*p_header_size < l_header_size) {
opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n");
return OPJ_FALSE;
}
opj_write_bytes(p_data,l_tccp->qntsty + (l_tccp->numgbits << 5), 1); /* Sqcx */
++p_data;
for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) {
l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn;
l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant;
opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */
p_data += 2;
}
}
*p_header_size = *p_header_size - l_header_size;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k,
OPJ_UINT32 p_comp_no,
OPJ_BYTE* p_header_data,
OPJ_UINT32 * p_header_size,
opj_event_mgr_t * p_manager
)
{
/* loop*/
OPJ_UINT32 l_band_no;
opj_cp_t *l_cp = 00;
opj_tcp_t *l_tcp = 00;
opj_tccp_t *l_tccp = 00;
OPJ_BYTE * l_current_ptr = 00;
OPJ_UINT32 l_tmp, l_num_band;
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_header_data != 00);
l_cp = &(p_j2k->m_cp);
/* come from tile part header or main header ?*/
l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? /*FIXME J2K_DEC_STATE_TPH*/
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
/* precondition again*/
assert(p_comp_no < p_j2k->m_private_image->numcomps);
l_tccp = &l_tcp->tccps[p_comp_no];
l_current_ptr = p_header_data;
if (*p_header_size < 1) {
opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n");
return OPJ_FALSE;
}
*p_header_size -= 1;
opj_read_bytes(l_current_ptr, &l_tmp ,1); /* Sqcx */
++l_current_ptr;
l_tccp->qntsty = l_tmp & 0x1f;
l_tccp->numgbits = l_tmp >> 5;
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
l_num_band = 1;
}
else {
l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ?
(*p_header_size) :
(*p_header_size) / 2;
if( l_num_band > OPJ_J2K_MAXBANDS ) {
opj_event_msg(p_manager, EVT_WARNING, "While reading CCP_QNTSTY element inside QCD or QCC marker segment, "
"number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to "
"OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS, OPJ_J2K_MAXBANDS);
/*return OPJ_FALSE;*/
}
}
#ifdef USE_JPWL
if (l_cp->correct) {
/* if JPWL is on, we check whether there are too many subbands */
if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) {
opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR,
"JPWL: bad number of subbands in Sqcx (%d)\n",
l_num_band);
if (!JPWL_ASSUME) {
opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n");
return OPJ_FALSE;
}
/* we try to correct */
l_num_band = 1;
opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"
"- setting number of bands to %d => HYPOTHESIS!!!\n",
l_num_band);
};
};
#endif /* USE_JPWL */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp ,1); /* SPqcx_i */
++l_current_ptr;
if (l_band_no < OPJ_J2K_MAXBANDS){
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3);
l_tccp->stepsizes[l_band_no].mant = 0;
}
}
*p_header_size = *p_header_size - l_num_band;
}
else {
for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) {
opj_read_bytes(l_current_ptr, &l_tmp ,2); /* SPqcx_i */
l_current_ptr+=2;
if (l_band_no < OPJ_J2K_MAXBANDS){
l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11);
l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff;
}
}
*p_header_size = *p_header_size - 2*l_num_band;
}
/* Add Antonin : if scalar_derived -> compute other stepsizes */
if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) {
for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) {
l_tccp->stepsizes[l_band_no].expn =
((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0) ?
(OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0;
l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant;
}
}
return OPJ_TRUE;
}
static void opj_j2k_copy_tile_quantization_parameters( opj_j2k_t *p_j2k )
{
OPJ_UINT32 i;
opj_cp_t *l_cp = NULL;
opj_tcp_t *l_tcp = NULL;
opj_tccp_t *l_ref_tccp = NULL;
opj_tccp_t *l_copied_tccp = NULL;
OPJ_UINT32 l_size;
/* preconditions */
assert(p_j2k != 00);
l_cp = &(p_j2k->m_cp);
l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ?
&l_cp->tcps[p_j2k->m_current_tile_number] :
p_j2k->m_specific_param.m_decoder.m_default_tcp;
l_ref_tccp = &l_tcp->tccps[0];
l_copied_tccp = l_ref_tccp + 1;
l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t);
for (i=1;i<p_j2k->m_private_image->numcomps;++i) {
l_copied_tccp->qntsty = l_ref_tccp->qntsty;
l_copied_tccp->numgbits = l_ref_tccp->numgbits;
memcpy(l_copied_tccp->stepsizes,l_ref_tccp->stepsizes,l_size);
++l_copied_tccp;
}
}
static void opj_j2k_dump_tile_info( opj_tcp_t * l_default_tile,OPJ_INT32 numcomps,FILE* out_stream)
{
if (l_default_tile)
{
OPJ_INT32 compno;
fprintf(out_stream, "\t default tile {\n");
fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty);
fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg);
fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers);
fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct);
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
OPJ_UINT32 resno;
OPJ_INT32 bandno, numbands;
/* coding style*/
fprintf(out_stream, "\t\t comp %d {\n", compno);
fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty);
fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions);
fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw);
fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh);
fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty);
fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid);
fprintf(out_stream, "\t\t\t preccintsize (w,h)=");
for (resno = 0; resno < l_tccp->numresolutions; resno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]);
}
fprintf(out_stream, "\n");
/* quantization style*/
fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty);
fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits);
fprintf(out_stream, "\t\t\t stepsizes (m,e)=");
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (OPJ_INT32)l_tccp->numresolutions * 3 - 2;
for (bandno = 0; bandno < numbands; bandno++) {
fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant,
l_tccp->stepsizes[bandno].expn);
}
fprintf(out_stream, "\n");
/* RGN value*/
fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift);
fprintf(out_stream, "\t\t }\n");
} /*end of component of default tile*/
fprintf(out_stream, "\t }\n"); /*end of default tile*/
}
}
void j2k_dump (opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream)
{
/* Check if the flag is compatible with j2k file*/
if ( (flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)){
fprintf(out_stream, "Wrong flag\n");
return;
}
/* Dump the image_header */
if (flag & OPJ_IMG_INFO){
if (p_j2k->m_private_image)
j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream);
}
/* Dump the codestream info from main header */
if (flag & OPJ_J2K_MH_INFO){
if (p_j2k->m_private_image)
opj_j2k_dump_MH_info(p_j2k, out_stream);
}
/* Dump all tile/codestream info */
if (flag & OPJ_J2K_TCH_INFO){
OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
OPJ_UINT32 i;
opj_tcp_t * l_tcp = p_j2k->m_cp.tcps;
if (p_j2k->m_private_image) {
for (i=0;i<l_nb_tiles;++i) {
opj_j2k_dump_tile_info( l_tcp,(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
++l_tcp;
}
}
}
/* Dump the codestream info of the current tile */
if (flag & OPJ_J2K_TH_INFO){
}
/* Dump the codestream index from main header */
if (flag & OPJ_J2K_MH_IND){
opj_j2k_dump_MH_index(p_j2k, out_stream);
}
/* Dump the codestream index of the current tile */
if (flag & OPJ_J2K_TH_IND){
}
}
static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream)
{
opj_codestream_index_t* cstr_index = p_j2k->cstr_index;
OPJ_UINT32 it_marker, it_tile, it_tile_part;
fprintf(out_stream, "Codestream index from main header: {\n");
fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n"
"\t Main header end position=%" PRIi64 "\n",
cstr_index->main_head_start, cstr_index->main_head_end);
fprintf(out_stream, "\t Marker list: {\n");
if (cstr_index->marker){
for (it_marker=0; it_marker < cstr_index->marknum ; it_marker++){
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->marker[it_marker].type,
cstr_index->marker[it_marker].pos,
cstr_index->marker[it_marker].len );
}
}
fprintf(out_stream, "\t }\n");
if (cstr_index->tile_index){
/* Simple test to avoid to write empty information*/
OPJ_UINT32 l_acc_nb_of_tile_part = 0;
for (it_tile=0; it_tile < cstr_index->nb_of_tiles ; it_tile++){
l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps;
}
if (l_acc_nb_of_tile_part)
{
fprintf(out_stream, "\t Tile index: {\n");
for (it_tile=0; it_tile < cstr_index->nb_of_tiles ; it_tile++){
OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps;
fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile, nb_of_tile_part);
if (cstr_index->tile_index[it_tile].tp_index){
for (it_tile_part =0; it_tile_part < nb_of_tile_part; it_tile_part++){
fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%" PRIi64 ", end_pos=%" PRIi64 ".\n",
it_tile_part,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header,
cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos);
}
}
if (cstr_index->tile_index[it_tile].marker){
for (it_marker=0; it_marker < cstr_index->tile_index[it_tile].marknum ; it_marker++){
fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n",
cstr_index->tile_index[it_tile].marker[it_marker].type,
cstr_index->tile_index[it_tile].marker[it_marker].pos,
cstr_index->tile_index[it_tile].marker[it_marker].len );
}
}
}
fprintf(out_stream,"\t }\n");
}
}
fprintf(out_stream,"}\n");
}
static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream)
{
fprintf(out_stream, "Codestream info from main header: {\n");
fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0);
fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy);
fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th);
opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp,(OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream);
fprintf(out_stream, "}\n");
}
void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag, FILE* out_stream)
{
char tab[2];
if (dev_dump_flag){
fprintf(stdout, "[DEV] Dump an image_header struct {\n");
tab[0] = '\0';
}
else {
fprintf(out_stream, "Image info {\n");
tab[0] = '\t';tab[1] = '\0';
}
fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0);
fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1, img_header->y1);
fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps);
if (img_header->comps){
OPJ_UINT32 compno;
for (compno = 0; compno < img_header->numcomps; compno++) {
fprintf(out_stream, "%s\t component %d {\n", tab, compno);
j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag, out_stream);
fprintf(out_stream,"%s}\n",tab);
}
}
fprintf(out_stream, "}\n");
}
void j2k_dump_image_comp_header(opj_image_comp_t* comp_header, OPJ_BOOL dev_dump_flag, FILE* out_stream)
{
char tab[3];
if (dev_dump_flag){
fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n");
tab[0] = '\0';
} else {
tab[0] = '\t';tab[1] = '\t';tab[2] = '\0';
}
fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy);
fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec);
fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd);
if (dev_dump_flag)
fprintf(out_stream, "}\n");
}
opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k)
{
OPJ_UINT32 compno;
OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps;
opj_tcp_t *l_default_tile;
opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1,sizeof(opj_codestream_info_v2_t));
if (!cstr_info)
return NULL;
cstr_info->nbcomps = p_j2k->m_private_image->numcomps;
cstr_info->tx0 = p_j2k->m_cp.tx0;
cstr_info->ty0 = p_j2k->m_cp.ty0;
cstr_info->tdx = p_j2k->m_cp.tdx;
cstr_info->tdy = p_j2k->m_cp.tdy;
cstr_info->tw = p_j2k->m_cp.tw;
cstr_info->th = p_j2k->m_cp.th;
cstr_info->tile_info = NULL; /* Not fill from the main header*/
l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp;
cstr_info->m_default_tile_info.csty = l_default_tile->csty;
cstr_info->m_default_tile_info.prg = l_default_tile->prg;
cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers;
cstr_info->m_default_tile_info.mct = l_default_tile->mct;
cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc(cstr_info->nbcomps, sizeof(opj_tccp_info_t));
if (!cstr_info->m_default_tile_info.tccp_info)
{
opj_destroy_cstr_info(&cstr_info);
return NULL;
}
for (compno = 0; compno < numcomps; compno++) {
opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]);
opj_tccp_info_t *l_tccp_info = &(cstr_info->m_default_tile_info.tccp_info[compno]);
OPJ_INT32 bandno, numbands;
/* coding style*/
l_tccp_info->csty = l_tccp->csty;
l_tccp_info->numresolutions = l_tccp->numresolutions;
l_tccp_info->cblkw = l_tccp->cblkw;
l_tccp_info->cblkh = l_tccp->cblkh;
l_tccp_info->cblksty = l_tccp->cblksty;
l_tccp_info->qmfbid = l_tccp->qmfbid;
if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS)
{
memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions);
memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions);
}
/* quantization style*/
l_tccp_info->qntsty = l_tccp->qntsty;
l_tccp_info->numgbits = l_tccp->numgbits;
numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (OPJ_INT32)l_tccp->numresolutions * 3 - 2;
if (numbands < OPJ_J2K_MAXBANDS) {
for (bandno = 0; bandno < numbands; bandno++) {
l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32)l_tccp->stepsizes[bandno].mant;
l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32)l_tccp->stepsizes[bandno].expn;
}
}
/* RGN value*/
l_tccp_info->roishift = l_tccp->roishift;
}
return cstr_info;
}
opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k)
{
opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*)
opj_calloc(1,sizeof(opj_codestream_index_t));
if (!l_cstr_index)
return NULL;
l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start;
l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end;
l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size;
l_cstr_index->marknum = p_j2k->cstr_index->marknum;
l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum*sizeof(opj_marker_info_t));
if (!l_cstr_index->marker){
opj_free( l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->marker)
memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker, l_cstr_index->marknum * sizeof(opj_marker_info_t) );
else{
opj_free(l_cstr_index->marker);
l_cstr_index->marker = NULL;
}
l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles;
l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t) );
if (!l_cstr_index->tile_index){
opj_free( l_cstr_index->marker);
opj_free( l_cstr_index);
return NULL;
}
if (!p_j2k->cstr_index->tile_index){
opj_free(l_cstr_index->tile_index);
l_cstr_index->tile_index = NULL;
}
else {
OPJ_UINT32 it_tile = 0;
for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++ ){
/* Tile Marker*/
l_cstr_index->tile_index[it_tile].marknum = p_j2k->cstr_index->tile_index[it_tile].marknum;
l_cstr_index->tile_index[it_tile].marker =
(opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum*sizeof(opj_marker_info_t));
if (!l_cstr_index->tile_index[it_tile].marker) {
OPJ_UINT32 it_tile_free;
for (it_tile_free=0; it_tile_free < it_tile; it_tile_free++){
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
}
opj_free( l_cstr_index->tile_index);
opj_free( l_cstr_index->marker);
opj_free( l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].marker)
memcpy( l_cstr_index->tile_index[it_tile].marker,
p_j2k->cstr_index->tile_index[it_tile].marker,
l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t) );
else{
opj_free(l_cstr_index->tile_index[it_tile].marker);
l_cstr_index->tile_index[it_tile].marker = NULL;
}
/* Tile part index*/
l_cstr_index->tile_index[it_tile].nb_tps = p_j2k->cstr_index->tile_index[it_tile].nb_tps;
l_cstr_index->tile_index[it_tile].tp_index =
(opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps*sizeof(opj_tp_index_t));
if(!l_cstr_index->tile_index[it_tile].tp_index){
OPJ_UINT32 it_tile_free;
for (it_tile_free=0; it_tile_free < it_tile; it_tile_free++){
opj_free(l_cstr_index->tile_index[it_tile_free].marker);
opj_free(l_cstr_index->tile_index[it_tile_free].tp_index);
}
opj_free( l_cstr_index->tile_index);
opj_free( l_cstr_index->marker);
opj_free( l_cstr_index);
return NULL;
}
if (p_j2k->cstr_index->tile_index[it_tile].tp_index){
memcpy( l_cstr_index->tile_index[it_tile].tp_index,
p_j2k->cstr_index->tile_index[it_tile].tp_index,
l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t) );
}
else{
opj_free(l_cstr_index->tile_index[it_tile].tp_index);
l_cstr_index->tile_index[it_tile].tp_index = NULL;
}
/* Packet index (NOT USED)*/
l_cstr_index->tile_index[it_tile].nb_packet = 0;
l_cstr_index->tile_index[it_tile].packet_index = NULL;
}
}
return l_cstr_index;
}
static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k)
{
OPJ_UINT32 it_tile=0;
p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc(p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t));
if (!p_j2k->cstr_index->tile_index)
return OPJ_FALSE;
for (it_tile=0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++){
p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100;
p_j2k->cstr_index->tile_index[it_tile].marknum = 0;
p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)
opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum, sizeof(opj_marker_info_t));
if (!p_j2k->cstr_index->tile_index[it_tile].marker)
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_decode_tiles ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_data_size,l_max_data_size;
OPJ_INT32 l_tile_x0,l_tile_y0,l_tile_x1,l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
OPJ_UINT32 nr_tiles = 0;
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
for (;;) {
if (! opj_j2k_read_tile_header( p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n", l_current_tile_no +1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k,l_current_tile_no,l_current_data,l_data_size,p_stream,p_manager)) {
opj_free(l_current_data);
opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n", l_current_tile_no +1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n", l_current_tile_no +1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd,l_current_data, p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no + 1);
if(opj_stream_get_number_byte_left(p_stream) == 0
&& p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC)
break;
if(++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw)
break;
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_decode_tiles, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
/*
* Read and decode one tile.
*/
static OPJ_BOOL opj_j2k_decode_one_tile ( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_current_tile_no;
OPJ_UINT32 l_tile_no_to_dec;
OPJ_UINT32 l_data_size,l_max_data_size;
OPJ_INT32 l_tile_x0,l_tile_y0,l_tile_x1,l_tile_y1;
OPJ_UINT32 l_nb_comps;
OPJ_BYTE * l_current_data;
l_current_data = (OPJ_BYTE*)opj_malloc(1000);
if (! l_current_data) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n");
return OPJ_FALSE;
}
l_max_data_size = 1000;
/*Allocate and initialize some elements of codestrem index if not already done*/
if( !p_j2k->cstr_index->tile_index)
{
if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)){
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Move into the codestream to the first SOT used to decode the desired tile */
l_tile_no_to_dec = (OPJ_UINT32)p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec;
if (p_j2k->cstr_index->tile_index)
if(p_j2k->cstr_index->tile_index->tp_index)
{
if ( ! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) {
/* the index for this tile has not been built,
* so move to the last SOT read */
if ( !(opj_stream_read_seek(p_stream, p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos+2, p_manager)) ){
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
else{
if ( !(opj_stream_read_seek(p_stream, p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos+2, p_manager)) ) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
}
/* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */
if(p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC)
p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
}
for (;;) {
if (! opj_j2k_read_tile_header( p_j2k,
&l_current_tile_no,
&l_data_size,
&l_tile_x0, &l_tile_y0,
&l_tile_x1, &l_tile_y1,
&l_nb_comps,
&l_go_on,
p_stream,
p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
if (! l_go_on) {
break;
}
if (l_data_size > l_max_data_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_data_size);
if (! l_new_current_data) {
opj_free(l_current_data);
l_current_data = NULL;
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n", l_current_tile_no+1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_data_size = l_data_size;
}
if (! opj_j2k_decode_tile(p_j2k,l_current_tile_no,l_current_data,l_data_size,p_stream,p_manager)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n", l_current_tile_no+1, p_j2k->m_cp.th * p_j2k->m_cp.tw);
if (! opj_j2k_update_image_data(p_j2k->m_tcd,l_current_data, p_j2k->m_output_image)) {
opj_free(l_current_data);
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no+1);
if(l_current_tile_no == l_tile_no_to_dec)
{
/* move into the codestream to the first SOT (FIXME or not move?)*/
if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2, p_manager) ) ) {
opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n");
opj_free(l_current_data);
return OPJ_FALSE;
}
break;
}
else {
opj_event_msg(p_manager, EVT_WARNING, "Tile read, decoded and updated is not the desired one (%d vs %d).\n", l_current_tile_no+1, l_tile_no_to_dec+1);
}
}
opj_free(l_current_data);
return OPJ_TRUE;
}
/**
* Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
*/
static OPJ_BOOL opj_j2k_setup_decoding_tile (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions*/
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_decode_one_tile, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom procedures */
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k,
opj_stream_private_t * p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 compno;
if (!p_image)
return OPJ_FALSE;
p_j2k->m_output_image = opj_image_create0();
if (! (p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
/* customization of the decoding */
opj_j2k_setup_decoding(p_j2k, p_manager);
/* Decode the codestream */
if (! opj_j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded;
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
if(p_image->comps[compno].data == NULL) return OPJ_FALSE;
p_j2k->m_output_image->comps[compno].data = NULL;
#if 0
char fn[256];
sprintf( fn, "/tmp/%d.raw", compno );
FILE *debug = fopen( fn, "wb" );
fwrite( p_image->comps[compno].data, sizeof(OPJ_INT32), p_image->comps[compno].w * p_image->comps[compno].h, debug );
fclose( debug );
#endif
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_get_tile( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t* p_image,
opj_event_mgr_t * p_manager,
OPJ_UINT32 tile_index )
{
OPJ_UINT32 compno;
OPJ_UINT32 l_tile_x, l_tile_y;
opj_image_comp_t* l_img_comp;
if (!p_image) {
opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n");
return OPJ_FALSE;
}
if ( /*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th) ){
opj_event_msg(p_manager, EVT_ERROR, "Tile index provided by the user is incorrect %d (max = %d) \n", tile_index, (p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1);
return OPJ_FALSE;
}
/* Compute the dimension of the desired tile*/
l_tile_x = tile_index % p_j2k->m_cp.tw;
l_tile_y = tile_index / p_j2k->m_cp.tw;
p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x0 < p_j2k->m_private_image->x0)
p_image->x0 = p_j2k->m_private_image->x0;
p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0;
if (p_image->x1 > p_j2k->m_private_image->x1)
p_image->x1 = p_j2k->m_private_image->x1;
p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y0 < p_j2k->m_private_image->y0)
p_image->y0 = p_j2k->m_private_image->y0;
p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0;
if (p_image->y1 > p_j2k->m_private_image->y1)
p_image->y1 = p_j2k->m_private_image->y1;
l_img_comp = p_image->comps;
for (compno=0; compno < p_image->numcomps; ++compno)
{
OPJ_INT32 l_comp_x1, l_comp_y1;
l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor;
l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx);
l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy);
l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor));
l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor));
l_img_comp++;
}
/* Destroy the previous output image*/
if (p_j2k->m_output_image)
opj_image_destroy(p_j2k->m_output_image);
/* Create the ouput image from the information previously computed*/
p_j2k->m_output_image = opj_image_create0();
if (! (p_j2k->m_output_image)) {
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_output_image);
p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index;
/* customization of the decoding */
opj_j2k_setup_decoding_tile(p_j2k, p_manager);
/* Decode the codestream */
if (! opj_j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
opj_image_destroy(p_j2k->m_private_image);
p_j2k->m_private_image = NULL;
return OPJ_FALSE;
}
/* Move data and copy one information from codec to output image*/
for (compno = 0; compno < p_image->numcomps; compno++) {
p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded;
if (p_image->comps[compno].data)
opj_free(p_image->comps[compno].data);
p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data;
if (p_image->comps[compno].data == NULL) return OPJ_FALSE;
p_j2k->m_output_image->comps[compno].data = NULL;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
OPJ_UINT32 res_factor,
opj_event_mgr_t * p_manager)
{
OPJ_UINT32 it_comp;
p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor;
if (p_j2k->m_private_image) {
if (p_j2k->m_private_image->comps) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp) {
if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) {
for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) {
OPJ_UINT32 max_res = p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions;
if ( res_factor >= max_res){
opj_event_msg(p_manager, EVT_ERROR, "Resolution factor is greater than the maximum resolution in the component.\n");
return OPJ_FALSE;
}
p_j2k->m_private_image->comps[it_comp].factor = res_factor;
}
return OPJ_TRUE;
}
}
}
}
return OPJ_FALSE;
}
OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 i, j;
OPJ_UINT32 l_nb_tiles;
OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size;
OPJ_BYTE * l_current_data = 00;
OPJ_BOOL l_reuse_data = OPJ_FALSE;
opj_tcd_t* p_tcd = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_tcd = p_j2k->m_tcd;
l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
if (l_nb_tiles == 1) {
l_reuse_data = OPJ_TRUE;
#ifdef __SSE__
for (j=0;j<p_j2k->m_tcd->image->numcomps;++j) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
if (((size_t)l_img_comp->data & 0xFU) != 0U) { /* tile data shall be aligned on 16 bytes */
l_reuse_data = OPJ_FALSE;
}
}
#endif
}
for (i=0;i<l_nb_tiles;++i) {
if (! opj_j2k_pre_write_tile(p_j2k,i,p_stream,p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
/* if we only have one tile, then simply set tile component data equal to image component data */
/* otherwise, allocate the data */
for (j=0;j<p_j2k->m_tcd->image->numcomps;++j) {
opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j;
if (l_reuse_data) {
opj_image_comp_t * l_img_comp = p_tcd->image->comps + j;
l_tilec->data = l_img_comp->data;
l_tilec->ownsData = OPJ_FALSE;
} else {
if(! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data." );
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
}
l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd);
if (!l_reuse_data) {
if (l_current_tile_size > l_max_tile_size) {
OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_current_tile_size);
if (! l_new_current_data) {
if (l_current_data) {
opj_free(l_current_data);
}
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n");
return OPJ_FALSE;
}
l_current_data = l_new_current_data;
l_max_tile_size = l_current_tile_size;
}
/* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */
/* 32 bit components @ 8 bit precision get converted to 8 bit */
/* 32 bit components @ 16 bit precision get converted to 16 bit */
opj_j2k_get_tile_data(p_j2k->m_tcd,l_current_data);
/* now copy this data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd,l_current_data,l_current_tile_size)) {
opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data." );
opj_free(l_current_data);
return OPJ_FALSE;
}
}
if (! opj_j2k_post_write_tile (p_j2k,p_stream,p_manager)) {
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_FALSE;
}
}
if (l_current_data) {
opj_free(l_current_data);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_end_compress( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager)
{
/* customization of the encoding */
if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) {
return OPJ_FALSE;
}
if (! opj_j2k_exec (p_j2k, p_j2k->m_procedure_list, p_stream, p_manager))
{
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_image_t * p_image,
opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
p_j2k->m_private_image = opj_image_create0();
if (! p_j2k->m_private_image) {
opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header." );
return OPJ_FALSE;
}
opj_copy_image_header(p_image, p_j2k->m_private_image);
/* TODO_MSD: Find a better way */
if (p_image->comps) {
OPJ_UINT32 it_comp;
for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) {
if (p_image->comps[it_comp].data) {
p_j2k->m_private_image->comps[it_comp].data =p_image->comps[it_comp].data;
p_image->comps[it_comp].data = NULL;
}
}
}
/* customization of the validation */
if (! opj_j2k_setup_encoding_validation (p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* validation of the parameters codec */
if (! opj_j2k_exec(p_j2k,p_j2k->m_validation_list,p_stream,p_manager)) {
return OPJ_FALSE;
}
/* customization of the encoding */
if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) {
return OPJ_FALSE;
}
/* write header */
if (! opj_j2k_exec (p_j2k,p_j2k->m_procedure_list,p_stream,p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_pre_write_tile ( opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
(void)p_stream;
if (p_tile_index != p_j2k->m_current_tile_number) {
opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match." );
return OPJ_FALSE;
}
opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n", p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th);
p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0;
p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts;
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* initialisation before tile encoding */
if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static void opj_get_tile_dimensions(opj_image_t * l_image,
opj_tcd_tilecomp_t * l_tilec,
opj_image_comp_t * l_img_comp,
OPJ_UINT32* l_size_comp,
OPJ_UINT32* l_width,
OPJ_UINT32* l_height,
OPJ_UINT32* l_offset_x,
OPJ_UINT32* l_offset_y,
OPJ_UINT32* l_image_width,
OPJ_UINT32* l_stride,
OPJ_UINT32* l_tile_offset) {
OPJ_UINT32 l_remaining;
*l_size_comp = l_img_comp->prec >> 3; /* (/8) */
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
*l_size_comp += 1;
}
if (*l_size_comp == 3) {
*l_size_comp = 4;
}
*l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
*l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
*l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx);
*l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0, (OPJ_INT32)l_img_comp->dy);
*l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 - (OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx);
*l_stride = *l_image_width - *l_width;
*l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + ((OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width;
}
static void opj_j2k_get_tile_data (opj_tcd_t * p_tcd, OPJ_BYTE * p_data)
{
OPJ_UINT32 i,j,k = 0;
for (i=0;i<p_tcd->image->numcomps;++i) {
opj_image_t * l_image = p_tcd->image;
OPJ_INT32 * l_src_ptr;
opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i;
opj_image_comp_t * l_img_comp = l_image->comps + i;
OPJ_UINT32 l_size_comp,l_width,l_height,l_offset_x,l_offset_y, l_image_width,l_stride,l_tile_offset;
opj_get_tile_dimensions(l_image,
l_tilec,
l_img_comp,
&l_size_comp,
&l_width,
&l_height,
&l_offset_x,
&l_offset_y,
&l_image_width,
&l_stride,
&l_tile_offset);
l_src_ptr = l_img_comp->data + l_tile_offset;
switch (l_size_comp) {
case 1:
{
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_data;
if (l_img_comp->sgnd) {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr) = (OPJ_CHAR) (*l_src_ptr);
++l_dest_ptr;
++l_src_ptr;
}
l_src_ptr += l_stride;
}
}
else {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr) = (OPJ_CHAR)((*l_src_ptr)&0xff);
++l_dest_ptr;
++l_src_ptr;
}
l_src_ptr += l_stride;
}
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 2:
{
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data;
if (l_img_comp->sgnd) {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (OPJ_INT16) (*(l_src_ptr++));
}
l_src_ptr += l_stride;
}
}
else {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff);
}
l_src_ptr += l_stride;
}
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4:
{
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_data;
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = *(l_src_ptr++);
}
l_src_ptr += l_stride;
}
p_data = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
}
}
static OPJ_BOOL opj_j2k_post_write_tile ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
OPJ_UINT32 l_nb_bytes_written;
OPJ_BYTE * l_current_data = 00;
OPJ_UINT32 l_tile_size = 0;
OPJ_UINT32 l_available_data;
/* preconditions */
assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size;
l_available_data = l_tile_size;
l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data;
l_nb_bytes_written = 0;
if (! opj_j2k_write_first_tile_part(p_j2k,l_current_data,&l_nb_bytes_written,l_available_data,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_current_data += l_nb_bytes_written;
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = 0;
if (! opj_j2k_write_all_tile_parts(p_j2k,l_current_data,&l_nb_bytes_written,l_available_data,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_available_data -= l_nb_bytes_written;
l_nb_bytes_written = l_tile_size - l_available_data;
if ( opj_stream_write_data( p_stream,
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data,
l_nb_bytes_written,p_manager) != l_nb_bytes_written) {
return OPJ_FALSE;
}
++p_j2k->m_current_tile_number;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_end_compress (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
/* DEVELOPER CORNER, insert your custom procedures */
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_eoc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_epc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_end_encoding, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_destroy_header_memory, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_encoding_validation (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_build_encoder, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_encoding_validation, p_manager)) {
return OPJ_FALSE;
}
/* DEVELOPER CORNER, add your custom validation procedure */
if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_mct_validation, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_setup_header_writing (opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_init_info, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_soc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_siz, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_cod, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_qcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_all_coc, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
return OPJ_FALSE;
}
if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_tlm, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_poc, p_manager)) {
return OPJ_FALSE;
}
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_regions, p_manager)) {
return OPJ_FALSE;
}
if (p_j2k->m_cp.comment != 00) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_com, p_manager)) {
return OPJ_FALSE;
}
}
/* DEVELOPER CORNER, insert your custom procedures */
if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
return OPJ_FALSE;
}
}
/* End of Developer Corner */
if (p_j2k->cstr_index) {
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_get_end_header, p_manager)) {
return OPJ_FALSE;
}
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_create_tcd, p_manager)) {
return OPJ_FALSE;
}
if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,(opj_procedure)opj_j2k_update_rates, p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_first_tile_part (opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_BYTE * l_begin_data = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcd->cur_pino = 0;
/*Get number of tile parts*/
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;
/* INDEX >> */
/* << INDEX */
l_current_nb_bytes_written = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k,p_data,&l_current_nb_bytes_written,p_stream,p_manager))
{
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
l_current_nb_bytes_written = 0;
opj_j2k_write_coc_in_memory(p_j2k,compno,p_data,&l_current_nb_bytes_written,p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
opj_j2k_write_qcc_in_memory(p_j2k,compno,p_data,&l_current_nb_bytes_written,p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
#endif
if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
l_current_nb_bytes_written = 0;
opj_j2k_write_poc_in_memory(p_j2k,p_data,&l_current_nb_bytes_written,p_manager);
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
}
}
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k,l_tcd,p_data,&l_current_nb_bytes_written,p_total_data_size,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
* p_data_written = l_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6,l_nb_bytes_written,4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)){
opj_j2k_update_tlm(p_j2k,l_nb_bytes_written);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_all_tile_parts( opj_j2k_t *p_j2k,
OPJ_BYTE * p_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_total_data_size,
opj_stream_private_t *p_stream,
struct opj_event_mgr * p_manager
)
{
OPJ_UINT32 tilepartno=0;
OPJ_UINT32 l_nb_bytes_written = 0;
OPJ_UINT32 l_current_nb_bytes_written;
OPJ_UINT32 l_part_tile_size;
OPJ_UINT32 tot_num_tp;
OPJ_UINT32 pino;
OPJ_BYTE * l_begin_data;
opj_tcp_t *l_tcp = 00;
opj_tcd_t * l_tcd = 00;
opj_cp_t * l_cp = 00;
l_tcd = p_j2k->m_tcd;
l_cp = &(p_j2k->m_cp);
l_tcp = l_cp->tcps + p_j2k->m_current_tile_number;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp,0,p_j2k->m_current_tile_number);
/* start writing remaining tile parts */
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k,p_data,&l_current_nb_bytes_written,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k,l_tcd,p_data,&l_current_nb_bytes_written,p_total_data_size,p_stream,p_manager)) {
return OPJ_FALSE;
}
p_data += l_current_nb_bytes_written;
l_nb_bytes_written += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6,l_part_tile_size,4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k,l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
l_tcd->cur_pino = pino;
/*Get number of tile parts*/
tot_num_tp = opj_j2k_get_num_tp(l_cp,pino,p_j2k->m_current_tile_number);
for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
l_current_nb_bytes_written = 0;
l_part_tile_size = 0;
l_begin_data = p_data;
if (! opj_j2k_write_sot(p_j2k,p_data,&l_current_nb_bytes_written,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
l_current_nb_bytes_written = 0;
if (! opj_j2k_write_sod(p_j2k,l_tcd,p_data,&l_current_nb_bytes_written,p_total_data_size,p_stream,p_manager)) {
return OPJ_FALSE;
}
l_nb_bytes_written += l_current_nb_bytes_written;
p_data += l_current_nb_bytes_written;
p_total_data_size -= l_current_nb_bytes_written;
l_part_tile_size += l_current_nb_bytes_written;
/* Writing Psot in SOT marker */
opj_write_bytes(l_begin_data + 6,l_part_tile_size,4); /* PSOT */
if (OPJ_IS_CINEMA(l_cp->rsiz)) {
opj_j2k_update_tlm(p_j2k,l_part_tile_size);
}
++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
}
}
*p_data_written = l_nb_bytes_written;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_write_updated_tlm( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
OPJ_UINT32 l_tlm_size;
OPJ_OFF_T l_tlm_position, l_current_position;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts;
l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start;
l_current_position = opj_stream_tell(p_stream);
if (! opj_stream_seek(p_stream,l_tlm_position,p_manager)) {
return OPJ_FALSE;
}
if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer,l_tlm_size,p_manager) != l_tlm_size) {
return OPJ_FALSE;
}
if (! opj_stream_seek(p_stream,l_current_position,p_manager)) {
return OPJ_FALSE;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_end_encoding( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer);
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0;
p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0;
}
if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data);
p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0;
return OPJ_TRUE;
}
/**
* Destroys the memory associated with the decoding of headers.
*/
static OPJ_BOOL opj_j2k_destroy_header_memory ( opj_j2k_t * p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_stream != 00);
assert(p_manager != 00);
if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) {
opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);
p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0;
}
p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;
return OPJ_TRUE;
}
static OPJ_BOOL opj_j2k_init_info( opj_j2k_t *p_j2k,
struct opj_stream_private *p_stream,
struct opj_event_mgr * p_manager )
{
opj_codestream_info_t * l_cstr_info = 00;
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
(void)l_cstr_info;
/* TODO mergeV2: check this part which use cstr_info */
/*l_cstr_info = p_j2k->cstr_info;
if (l_cstr_info) {
OPJ_UINT32 compno;
l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t));
l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0;
l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0;
l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg;
l_cstr_info->tw = p_j2k->m_cp.tw;
l_cstr_info->th = p_j2k->m_cp.th;
l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */
/*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */
/*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */
/*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */
/*l_cstr_info->numcomps = p_j2k->m_image->numcomps;
l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers;
l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32));
for (compno=0; compno < p_j2k->m_image->numcomps; compno++) {
l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1;
}
l_cstr_info->D_max = 0.0; */ /* ADD Marcela */
/*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */
/*l_cstr_info->maxmarknum = 100;
l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t));
l_cstr_info->marknum = 0;
}*/
return opj_j2k_calculate_tp(p_j2k,&(p_j2k->m_cp),&p_j2k->m_specific_param.m_encoder.m_total_tile_parts,p_j2k->m_private_image,p_manager);
}
/**
* Creates a tile-coder decoder.
*
* @param p_stream the stream to write data to.
* @param p_j2k J2K codec.
* @param p_manager the user event manager.
*/
static OPJ_BOOL opj_j2k_create_tcd( opj_j2k_t *p_j2k,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager
)
{
/* preconditions */
assert(p_j2k != 00);
assert(p_manager != 00);
assert(p_stream != 00);
p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE);
if (! p_j2k->m_tcd) {
opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n");
return OPJ_FALSE;
}
if (!opj_tcd_init(p_j2k->m_tcd,p_j2k->m_private_image,&p_j2k->m_cp, p_j2k->m_tp)) {
opj_tcd_destroy(p_j2k->m_tcd);
p_j2k->m_tcd = 00;
return OPJ_FALSE;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_j2k_write_tile (opj_j2k_t * p_j2k,
OPJ_UINT32 p_tile_index,
OPJ_BYTE * p_data,
OPJ_UINT32 p_data_size,
opj_stream_private_t *p_stream,
opj_event_mgr_t * p_manager )
{
if (! opj_j2k_pre_write_tile(p_j2k,p_tile_index,p_stream,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
}
else {
OPJ_UINT32 j;
/* Allocate data */
for (j=0;j<p_j2k->m_tcd->image->numcomps;++j) {
opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j;
if(! opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data." );
return OPJ_FALSE;
}
}
/* now copy data into the tile component */
if (! opj_tcd_copy_tile_data(p_j2k->m_tcd,p_data,p_data_size)) {
opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data." );
return OPJ_FALSE;
}
if (! opj_j2k_post_write_tile(p_j2k,p_stream,p_manager)) {
opj_event_msg(p_manager, EVT_ERROR, "Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index);
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5488_3 |
crossvul-cpp_data_bad_5509_2 | /*
* gsf-infile-tar.c :
*
* Copyright (C) 2008 Morten Welinder (terra@gnome.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*
* TODO:
* symlinks
* hardlinks
* weird headers
*/
#include <gsf-config.h>
#include <gsf/gsf-infile-tar.h>
#include <gsf/gsf.h>
#include <glib/gi18n-lib.h>
#include <string.h>
#undef G_LOG_DOMAIN
#define G_LOG_DOMAIN "libgsf:tar"
static void gsf_infile_tar_set_source (GsfInfileTar *tar, GsfInput *src);
enum {
PROP_0,
PROP_SOURCE
};
static GObjectClass *parent_class;
typedef struct {
char *name;
GDateTime *modtime;
/* The location of data. */
gsf_off_t offset;
gsf_off_t length;
/* The directory object, or NULL for a data file. */
GsfInfileTar *dir;
} TarChild;
/* tar header from POSIX 1003.1-1990. */
typedef struct {
char name[100]; /* 0 */
char mode[8]; /* 100 (octal) */
char uid[8]; /* 108 (octal) */
char gid[8]; /* 116 (octal) */
char size[12]; /* 124 (octal) */
char mtime[12]; /* 136 (octal) */
char chksum[8]; /* 148 (octal) */
char typeflag; /* 156 */
char linkname[100]; /* 157 */
char magic[6]; /* 257 */
char version[2]; /* 263 */
char uname[32]; /* 265 */
char gname[32]; /* 297 */
char devmajor[8]; /* 329 (octal) */
char devminor[8]; /* 337 (octal) */
char prefix[155]; /* 345 */
char filler[12]; /* 500 */
} TarHeader;
#define HEADER_SIZE (sizeof (TarHeader))
#define BLOCK_SIZE 512
#define MAGIC_LONGNAME "././@LongLink"
struct _GsfInfileTar {
GsfInfile parent;
GsfInput *source;
GArray *children; /* of TarChild */
GError *err;
};
typedef struct {
GsfInfileClass parent_class;
} GsfInfileTarClass;
#define GSF_INFILE_TAR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GSF_INFILE_TAR_TYPE, GsfInfileTarClass))
#define GSF_IS_INFILE_TAR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GSF_INFILE_TAR_TYPE))
static gint64
unpack_octal (GsfInfileTar *tar, const char *s, size_t len)
{
guint64 res = 0;
/*
* Different specifications differ on what terminating characters
* are allowed. It doesn't hurt for us to allow both space and
* NUL.
*/
if (len == 0 || (s[len - 1] != 0 && s[len - 1] != ' '))
goto invalid;
len--;
while (len--) {
unsigned char c = *s++;
if (c < '0' || c > '7')
goto invalid;
res = (res << 3) | (c - '0');
}
return (gint64)res;
invalid:
tar->err = g_error_new (gsf_input_error_id (), 0,
_("Invalid tar header"));
return 0;
}
static GsfInfileTar *
tar_create_dir (GsfInfileTar *dir, const char *name)
{
TarChild c;
c.offset = 0;
c.length = 0;
c.name = g_strdup (name);
c.modtime = NULL;
c.dir = g_object_new (GSF_INFILE_TAR_TYPE, NULL);
/*
* We set the source here, so gsf_infile_tar_constructor doesn't
* start reading the tarfile recursively.
*/
gsf_infile_tar_set_source (c.dir, dir->source);
gsf_input_set_name (GSF_INPUT (c.dir), name);
g_array_append_val (dir->children, c);
return c.dir;
}
static GsfInfileTar *
tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)
{
const char *s = name;
while (1) {
const char *s0 = s;
char *dirname;
/* Find a directory component, if any. */
while (1) {
if (*s == 0) {
if (last && s != s0)
break;
else
return dir;
}
/* This is deliberately slash-only. */
if (*s == '/')
break;
s++;
}
dirname = g_strndup (s0, s - s0);
while (*s == '/')
s++;
if (strcmp (dirname, ".") != 0) {
GsfInput *subdir =
gsf_infile_child_by_name (GSF_INFILE (dir),
dirname);
if (subdir) {
/* Undo the ref. */
g_object_unref (subdir);
dir = GSF_INFILE_TAR (subdir);
} else
dir = tar_create_dir (dir, dirname);
}
g_free (dirname);
}
}
/*****************************************************************************/
/**
* tar_init_info :
* @tar : #GsfInfileTar
*
* Read tar headers and do some sanity checking
* along the way.
**/
static void
tar_init_info (GsfInfileTar *tar)
{
TarHeader end;
const TarHeader *header;
gsf_off_t pos0 = gsf_input_tell (tar->source);
char *pending_longname = NULL;
memset (&end, 0, sizeof (end));
while (tar->err == NULL &&
(header = (const TarHeader *)gsf_input_read (tar->source,
HEADER_SIZE,
NULL))) {
char *name;
gsf_off_t length;
gsf_off_t offset;
gint64 mtime;
if (memcmp (header->filler, end.filler, sizeof (end.filler))) {
tar->err = g_error_new (gsf_input_error_id (), 0,
_("Invalid tar header"));
break;
}
if (memcmp (header, &end, HEADER_SIZE) == 0)
break;
if (pending_longname) {
name = pending_longname;
pending_longname = NULL;
} else
name = g_strndup (header->name, sizeof (header->name));
length = unpack_octal (tar, header->size, sizeof (header->size));
offset = gsf_input_tell (tar->source);
mtime = unpack_octal (tar, header->mtime, sizeof (header->mtime));
switch (header->typeflag) {
case '0': case 0: {
/* Regular file. */
GsfInfileTar *dir;
const char *n = name, *s;
TarChild c;
/* This is deliberately slash-only. */
while ((s = strchr (n, '/')))
n = s + 1;
c.name = g_strdup (n);
c.modtime = mtime > 0
? g_date_time_new_from_unix_utc (mtime)
: NULL;
c.offset = offset;
c.length = length;
c.dir = NULL;
dir = tar_directory_for_file (tar, name, FALSE);
g_array_append_val (dir->children, c);
break;
}
case '5': {
/* Directory */
(void)tar_directory_for_file (tar, name, TRUE);
break;
}
case 'L': {
const char *n;
if (pending_longname ||
strcmp (name, MAGIC_LONGNAME) != 0) {
tar->err = g_error_new (gsf_input_error_id (), 0,
_("Invalid longname header"));
break;
}
n = gsf_input_read (tar->source, length, NULL);
if (!n) {
tar->err = g_error_new (gsf_input_error_id (), 0,
_("Failed to read longname"));
break;
}
pending_longname = g_strndup (n, length);
break;
}
default:
/* Other -- ignore */
break;
}
g_free (name);
/* Round up to block size */
length = (length + (BLOCK_SIZE - 1)) / BLOCK_SIZE * BLOCK_SIZE;
if (!tar->err &&
gsf_input_seek (tar->source, offset + length, G_SEEK_SET)) {
tar->err = g_error_new (gsf_input_error_id (), 0,
_("Seek failed"));
break;
}
}
if (pending_longname) {
if (!tar->err)
tar->err = g_error_new (gsf_input_error_id (), 0,
_("Truncated archive"));
g_free (pending_longname);
}
if (tar->err)
gsf_input_seek (tar->source, pos0, G_SEEK_SET);
}
/* GsfInput class functions */
static GsfInput *
gsf_infile_tar_dup (GsfInput *src_input, GError **err)
{
GsfInfileTar *res, *src;
unsigned ui;
src = GSF_INFILE_TAR (src_input);
if (src->err) {
if (err)
*err = g_error_copy (src->err);
return NULL;
}
res = (GsfInfileTar *)g_object_new (GSF_INFILE_TAR_TYPE, NULL);
gsf_infile_tar_set_source (res, src->source);
for (ui = 0; ui < src->children->len; ui++) {
/* This copies the structure. */
TarChild c = g_array_index (src->children, TarChild, ui);
c.name = g_strdup (c.name);
if (c.modtime) g_date_time_ref (c.modtime);
if (c.dir) g_object_ref (c.dir);
g_array_append_val (res->children, c);
}
return NULL;
}
static guint8 const *
gsf_infile_tar_read (GsfInput *input, size_t num_bytes, guint8 *buffer)
{
(void)input;
(void)num_bytes;
(void)buffer;
return NULL;
}
static gboolean
gsf_infile_tar_seek (GsfInput *input, gsf_off_t offset, GSeekType whence)
{
(void)input;
(void)offset;
(void)whence;
return FALSE;
}
/* GsfInfile class functions */
/*****************************************************************************/
static GsfInput *
gsf_infile_tar_child_by_index (GsfInfile *infile, int target, GError **err)
{
GsfInfileTar *tar = GSF_INFILE_TAR (infile);
const TarChild *c;
if (err)
*err = NULL;
if (target < 0 || (unsigned)target >= tar->children->len)
return NULL;
c = &g_array_index (tar->children, TarChild, target);
if (c->dir)
return g_object_ref (c->dir);
else {
GsfInput *input = gsf_input_proxy_new_section (tar->source,
c->offset,
c->length);
gsf_input_set_modtime (input, c->modtime);
gsf_input_set_name (input, c->name);
return input;
}
}
static char const *
gsf_infile_tar_name_by_index (GsfInfile *infile, int target)
{
GsfInfileTar *tar = GSF_INFILE_TAR (infile);
if (target < 0 || (unsigned)target >= tar->children->len)
return NULL;
return g_array_index (tar->children, TarChild, target).name;
}
static GsfInput *
gsf_infile_tar_child_by_name (GsfInfile *infile, char const *name, GError **err)
{
GsfInfileTar *tar = GSF_INFILE_TAR (infile);
unsigned ui;
for (ui = 0; ui < tar->children->len; ui++) {
const TarChild *c = &g_array_index (tar->children,
TarChild,
ui);
if (strcmp (name, c->name) == 0)
return gsf_infile_tar_child_by_index (infile, ui, err);
}
return NULL;
}
static int
gsf_infile_tar_num_children (GsfInfile *infile)
{
GsfInfileTar *tar = GSF_INFILE_TAR (infile);
return tar->children->len;
}
static void
gsf_infile_tar_finalize (GObject *obj)
{
GsfInfileTar *tar = GSF_INFILE_TAR (obj);
g_array_free (tar->children, TRUE);
parent_class->finalize (obj);
}
static void
gsf_infile_tar_dispose (GObject *obj)
{
GsfInfileTar *tar = GSF_INFILE_TAR (obj);
unsigned ui;
gsf_infile_tar_set_source (tar, NULL);
g_clear_error (&tar->err);
for (ui = 0; ui < tar->children->len; ui++) {
TarChild *c = &g_array_index (tar->children, TarChild, ui);
g_free (c->name);
if (c->modtime)
g_date_time_unref (c->modtime);
if (c->dir)
g_object_unref (c->dir);
}
g_array_set_size (tar->children, 0);
parent_class->dispose (obj);
}
static GObject*
gsf_infile_tar_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GsfInfileTar *tar = (GsfInfileTar *)
(parent_class->constructor (type,
n_construct_properties,
construct_params));
if (tar->source)
tar_init_info (tar);
return (GObject *)tar;
}
static void
gsf_infile_tar_init (GObject *obj)
{
GsfInfileTar *tar = (GsfInfileTar *)obj;
tar->source = NULL;
tar->children = g_array_new (FALSE, FALSE, sizeof (TarChild));
tar->err = NULL;
}
static void
gsf_infile_tar_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
GsfInfileTar *tar = (GsfInfileTar *)object;
switch (property_id) {
case PROP_SOURCE:
g_value_set_object (value, tar->source);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gsf_infile_tar_set_source (GsfInfileTar *tar, GsfInput *src)
{
if (src)
src = gsf_input_proxy_new (src);
if (tar->source)
g_object_unref (tar->source);
tar->source = src;
}
static void
gsf_infile_tar_set_property (GObject *object,
guint property_id,
GValue const *value,
GParamSpec *pspec)
{
GsfInfileTar *tar = (GsfInfileTar *)object;
switch (property_id) {
case PROP_SOURCE:
gsf_infile_tar_set_source (tar, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gsf_infile_tar_class_init (GObjectClass *gobject_class)
{
GsfInputClass *input_class = GSF_INPUT_CLASS (gobject_class);
GsfInfileClass *infile_class = GSF_INFILE_CLASS (gobject_class);
gobject_class->constructor = gsf_infile_tar_constructor;
gobject_class->finalize = gsf_infile_tar_finalize;
gobject_class->dispose = gsf_infile_tar_dispose;
gobject_class->get_property = gsf_infile_tar_get_property;
gobject_class->set_property = gsf_infile_tar_set_property;
input_class->Dup = gsf_infile_tar_dup;
input_class->Read = gsf_infile_tar_read;
input_class->Seek = gsf_infile_tar_seek;
infile_class->num_children = gsf_infile_tar_num_children;
infile_class->name_by_index = gsf_infile_tar_name_by_index;
infile_class->child_by_index = gsf_infile_tar_child_by_index;
infile_class->child_by_name = gsf_infile_tar_child_by_name;
parent_class = g_type_class_peek_parent (gobject_class);
g_object_class_install_property
(gobject_class,
PROP_SOURCE,
g_param_spec_object ("source",
_("Source"),
_("The archive being interpreted"),
GSF_INPUT_TYPE,
GSF_PARAM_STATIC |
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY));
}
GSF_CLASS (GsfInfileTar, gsf_infile_tar,
gsf_infile_tar_class_init, gsf_infile_tar_init,
GSF_INFILE_TYPE)
/**
* gsf_infile_tar_new:
* @source: A base #GsfInput
* @err: A #GError, optionally %NULL
*
* Opens the root directory of a Tar file.
* <note>This adds a reference to @source.</note>
*
* Returns: the new tar file handler
**/
GsfInfile *
gsf_infile_tar_new (GsfInput *source, GError **err)
{
GsfInfileTar *tar;
g_return_val_if_fail (GSF_IS_INPUT (source), NULL);
tar = g_object_new (GSF_INFILE_TAR_TYPE,
"source", source,
NULL);
if (tar->err) {
if (err)
*err = g_error_copy (tar->err);
g_object_unref (tar);
return NULL;
}
return GSF_INFILE (tar);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_5509_2 |
crossvul-cpp_data_bad_99_0 | /*
* Packet matching code for ARP packets.
*
* Based heavily, if not almost entirely, upon ip_tables.c framework.
*
* Some ARP specific bits are:
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
* Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/capability.h>
#include <linux/if_arp.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <net/compat.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_arp/arp_tables.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David S. Miller <davem@redhat.com>");
MODULE_DESCRIPTION("arptables core");
void *arpt_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(arpt, ARPT);
}
EXPORT_SYMBOL_GPL(arpt_alloc_initial_table);
static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap,
const char *hdr_addr, int len)
{
int i, ret;
if (len > ARPT_DEV_ADDR_LEN_MAX)
len = ARPT_DEV_ADDR_LEN_MAX;
ret = 0;
for (i = 0; i < len; i++)
ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i];
return ret != 0;
}
/*
* Unfortunately, _b and _mask are not aligned to an int (or long int)
* Some arches dont care, unrolling the loop is a win on them.
* For other arches, we only have a 16bit alignement.
*/
static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask)
{
#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
unsigned long ret = ifname_compare_aligned(_a, _b, _mask);
#else
unsigned long ret = 0;
const u16 *a = (const u16 *)_a;
const u16 *b = (const u16 *)_b;
const u16 *mask = (const u16 *)_mask;
int i;
for (i = 0; i < IFNAMSIZ/sizeof(u16); i++)
ret |= (a[i] ^ b[i]) & mask[i];
#endif
return ret;
}
/* Returns whether packet matches rule or not. */
static inline int arp_packet_match(const struct arphdr *arphdr,
struct net_device *dev,
const char *indev,
const char *outdev,
const struct arpt_arp *arpinfo)
{
const char *arpptr = (char *)(arphdr + 1);
const char *src_devaddr, *tgt_devaddr;
__be32 src_ipaddr, tgt_ipaddr;
long ret;
if (NF_INVF(arpinfo, ARPT_INV_ARPOP,
(arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop))
return 0;
if (NF_INVF(arpinfo, ARPT_INV_ARPHRD,
(arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd))
return 0;
if (NF_INVF(arpinfo, ARPT_INV_ARPPRO,
(arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro))
return 0;
if (NF_INVF(arpinfo, ARPT_INV_ARPHLN,
(arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln))
return 0;
src_devaddr = arpptr;
arpptr += dev->addr_len;
memcpy(&src_ipaddr, arpptr, sizeof(u32));
arpptr += sizeof(u32);
tgt_devaddr = arpptr;
arpptr += dev->addr_len;
memcpy(&tgt_ipaddr, arpptr, sizeof(u32));
if (NF_INVF(arpinfo, ARPT_INV_SRCDEVADDR,
arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr,
dev->addr_len)) ||
NF_INVF(arpinfo, ARPT_INV_TGTDEVADDR,
arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr,
dev->addr_len)))
return 0;
if (NF_INVF(arpinfo, ARPT_INV_SRCIP,
(src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr) ||
NF_INVF(arpinfo, ARPT_INV_TGTIP,
(tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr))
return 0;
/* Look for ifname matches. */
ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask);
if (NF_INVF(arpinfo, ARPT_INV_VIA_IN, ret != 0))
return 0;
ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask);
if (NF_INVF(arpinfo, ARPT_INV_VIA_OUT, ret != 0))
return 0;
return 1;
}
static inline int arp_checkentry(const struct arpt_arp *arp)
{
if (arp->flags & ~ARPT_F_MASK)
return 0;
if (arp->invflags & ~ARPT_INV_MASK)
return 0;
return 1;
}
static unsigned int
arpt_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_err_ratelimited("arp_tables: error: '%s'\n",
(const char *)par->targinfo);
return NF_DROP;
}
static inline const struct xt_entry_target *
arpt_get_target_c(const struct arpt_entry *e)
{
return arpt_get_target((struct arpt_entry *)e);
}
static inline struct arpt_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct arpt_entry *)(base + offset);
}
static inline
struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
unsigned int arpt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
unsigned int verdict = NF_DROP;
const struct arphdr *arp;
struct arpt_entry *e, **jumpstack;
const char *indev, *outdev;
const void *table_base;
unsigned int cpu, stackidx = 0;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
if (!pskb_may_pull(skb, arp_hdr_len(skb->dev)))
return NF_DROP;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct arpt_entry **)private->jumpstack[cpu];
/* No TEE support for arptables, so no need to switch to alternate
* stack. All targets that reenter must return absolute verdicts.
*/
e = get_entry(table_base, private->hook_entry[hook]);
acpar.state = state;
acpar.hotdrop = false;
arp = arp_hdr(skb);
do {
const struct xt_entry_target *t;
struct xt_counters *counter;
if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) {
e = arpt_next_entry(e);
continue;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1);
t = arpt_get_target_c(e);
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
} else {
e = jumpstack[--stackidx];
e = arpt_next_entry(e);
}
continue;
}
if (table_base + v
!= arpt_next_entry(e)) {
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE) {
/* Target might have changed stuff. */
arp = arp_hdr(skb);
e = arpt_next_entry(e);
} else {
/* Verdict */
break;
}
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else
return verdict;
}
/* All zeroes == unconditional rule. */
static inline bool unconditional(const struct arpt_entry *e)
{
static const struct arpt_arp uncond;
return e->target_offset == sizeof(struct arpt_entry) &&
memcmp(&e->arp, &uncond, sizeof(uncond)) == 0;
}
/* Figures out from what hook each rule can be called: returns 0 if
* there are loops. Puts hook bitmask in comefrom.
*/
static int mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0,
unsigned int *offsets)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
* to 0 as we leave), and comefrom to save source hook bitmask.
*/
for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct arpt_entry *e = entry0 + pos;
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)arpt_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_ARP_NUMHOOKS))
return 0;
e->comefrom
|= ((1 << hook) | (1 << NF_ARP_NUMHOOKS));
/* Unconditional return/END. */
if ((unconditional(e) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0) || visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1)
return 0;
/* Return: backtrack through the last
* big jump.
*/
do {
e->comefrom ^= (1<<NF_ARP_NUMHOOKS);
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = entry0 + pos;
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = entry0 + pos + size;
if (pos + size >= newinfo->size)
return 0;
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
/* This a jump; chase it. */
if (!xt_find_jump_offset(offsets, newpos,
newinfo->number))
return 0;
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
if (newpos >= newinfo->size)
return 0;
}
e = entry0 + newpos;
e->counters.pcnt = pos;
pos = newpos;
}
}
next: ;
}
return 1;
}
static inline int check_target(struct arpt_entry *e, const char *name)
{
struct xt_entry_target *t = arpt_get_target(e);
struct xt_tgchk_param par = {
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_ARP,
};
return xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false);
}
static inline int
find_check_entry(struct arpt_entry *e, const char *name, unsigned int size,
struct xt_percpu_counter_alloc_state *alloc_state)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
if (!xt_percpu_counter_alloc(alloc_state, &e->counters))
return -ENOMEM;
t = arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
ret = check_target(e, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
out:
xt_percpu_counter_free(&e->counters);
return ret;
}
static bool check_underflow(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(e))
return false;
t = arpt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
static inline int check_entry_size_and_hooks(struct arpt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit)
return -EINVAL;
if (e->next_offset
< sizeof(struct arpt_entry) + sizeof(struct xt_entry_target))
return -EINVAL;
if (!arp_checkentry(&e->arp))
return -EINVAL;
err = xt_check_entry_offsets(e, e->elems, e->target_offset,
e->next_offset);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e))
return -EINVAL;
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
static inline void cleanup_entry(struct arpt_entry *e)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
t = arpt_get_target(e);
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_ARP;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
xt_percpu_counter_free(&e->counters);
}
/* Checks and translates the user-supplied table segment (held in
* newinfo).
*/
static int translate_table(struct xt_table_info *newinfo, void *entry0,
const struct arpt_replace *repl)
{
struct xt_percpu_counter_alloc_state alloc_state = { 0 };
struct arpt_entry *iter;
unsigned int *offsets;
unsigned int i;
int ret = 0;
newinfo->size = repl->size;
newinfo->number = repl->num_entries;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
newinfo->hook_entry[i] = 0xFFFFFFFF;
newinfo->underflow[i] = 0xFFFFFFFF;
}
offsets = xt_alloc_entry_offsets(newinfo->number);
if (!offsets)
return -ENOMEM;
i = 0;
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = check_entry_size_and_hooks(iter, newinfo, entry0,
entry0 + repl->size,
repl->hook_entry,
repl->underflow,
repl->valid_hooks);
if (ret != 0)
goto out_free;
if (i < repl->num_entries)
offsets[i] = (void *)iter - entry0;
++i;
if (strcmp(arpt_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
ret = -EINVAL;
if (i != repl->num_entries)
goto out_free;
/* Check hooks all assigned */
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(repl->valid_hooks & (1 << i)))
continue;
if (newinfo->hook_entry[i] == 0xFFFFFFFF)
goto out_free;
if (newinfo->underflow[i] == 0xFFFFFFFF)
goto out_free;
}
if (!mark_source_chains(newinfo, repl->valid_hooks, entry0, offsets)) {
ret = -ELOOP;
goto out_free;
}
kvfree(offsets);
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, repl->name, repl->size,
&alloc_state);
if (ret != 0)
break;
++i;
}
if (ret != 0) {
xt_entry_foreach(iter, entry0, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter);
}
return ret;
}
return ret;
out_free:
kvfree(offsets);
return ret;
}
static void get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct arpt_entry *iter;
unsigned int cpu;
unsigned int i;
for_each_possible_cpu(cpu) {
seqcount_t *s = &per_cpu(xt_recseq, cpu);
i = 0;
xt_entry_foreach(iter, t->entries, t->size) {
struct xt_counters *tmp;
u64 bcnt, pcnt;
unsigned int start;
tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
do {
start = read_seqcount_begin(s);
bcnt = tmp->bcnt;
pcnt = tmp->pcnt;
} while (read_seqcount_retry(s, start));
ADD_COUNTER(counters[i], bcnt, pcnt);
++i;
cond_resched();
}
}
}
static void get_old_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct arpt_entry *iter;
unsigned int cpu, i;
for_each_possible_cpu(cpu) {
i = 0;
xt_entry_foreach(iter, t->entries, t->size) {
struct xt_counters *tmp;
tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
ADD_COUNTER(counters[i], tmp->bcnt, tmp->pcnt);
++i;
}
cond_resched();
}
}
static struct xt_counters *alloc_counters(const struct xt_table *table)
{
unsigned int countersize;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
/* We need atomic snapshot of counters: rest doesn't change
* (other than comefrom, which userspace doesn't care
* about).
*/
countersize = sizeof(struct xt_counters) * private->number;
counters = vzalloc(countersize);
if (counters == NULL)
return ERR_PTR(-ENOMEM);
get_counters(private, counters);
return counters;
}
static int copy_entries_to_user(unsigned int total_size,
const struct xt_table *table,
void __user *userptr)
{
unsigned int off, num;
const struct arpt_entry *e;
struct xt_counters *counters;
struct xt_table_info *private = table->private;
int ret = 0;
void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
loc_cpu_entry = private->entries;
/* FIXME: use iterator macros --RR */
/* ... then go back and fix counters and names */
for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
const struct xt_entry_target *t;
e = loc_cpu_entry + off;
if (copy_to_user(userptr + off, e, sizeof(*e))) {
ret = -EFAULT;
goto free_counters;
}
if (copy_to_user(userptr + off
+ offsetof(struct arpt_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
t = arpt_get_target_c(e);
if (xt_target_to_user(t, userptr + off + e->target_offset)) {
ret = -EFAULT;
goto free_counters;
}
}
free_counters:
vfree(counters);
return ret;
}
#ifdef CONFIG_COMPAT
static void compat_standard_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v > 0)
v += xt_compat_calc_jump(NFPROTO_ARP, v);
memcpy(dst, &v, sizeof(v));
}
static int compat_standard_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv > 0)
cv -= xt_compat_calc_jump(NFPROTO_ARP, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct arpt_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - base;
t = arpt_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct arpt_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct arpt_entry *)(base + info->underflow[i])))
newinfo->underflow[i] -= off;
}
return 0;
}
static int compat_table_info(const struct xt_table_info *info,
struct xt_table_info *newinfo)
{
struct arpt_entry *iter;
const void *loc_cpu_entry;
int ret;
if (!newinfo || !info)
return -EINVAL;
/* we dont care about newinfo->entries */
memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
newinfo->initial_entries = 0;
loc_cpu_entry = info->entries;
xt_compat_init_offsets(NFPROTO_ARP, info->number);
xt_entry_foreach(iter, loc_cpu_entry, info->size) {
ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
if (ret != 0)
return ret;
}
return 0;
}
#endif
static int get_info(struct net *net, void __user *user,
const int *len, int compat)
{
char name[XT_TABLE_MAXNAMELEN];
struct xt_table *t;
int ret;
if (*len != sizeof(struct arpt_getinfo))
return -EINVAL;
if (copy_from_user(name, user, sizeof(name)) != 0)
return -EFAULT;
name[XT_TABLE_MAXNAMELEN-1] = '\0';
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_lock(NFPROTO_ARP);
#endif
t = xt_request_find_table_lock(net, NFPROTO_ARP, name);
if (!IS_ERR(t)) {
struct arpt_getinfo info;
const struct xt_table_info *private = t->private;
#ifdef CONFIG_COMPAT
struct xt_table_info tmp;
if (compat) {
ret = compat_table_info(private, &tmp);
xt_compat_flush_offsets(NFPROTO_ARP);
private = &tmp;
}
#endif
memset(&info, 0, sizeof(info));
info.valid_hooks = t->valid_hooks;
memcpy(info.hook_entry, private->hook_entry,
sizeof(info.hook_entry));
memcpy(info.underflow, private->underflow,
sizeof(info.underflow));
info.num_entries = private->number;
info.size = private->size;
strcpy(info.name, name);
if (copy_to_user(user, &info, *len) != 0)
ret = -EFAULT;
else
ret = 0;
xt_table_unlock(t);
module_put(t->me);
} else
ret = PTR_ERR(t);
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_unlock(NFPROTO_ARP);
#endif
return ret;
}
static int get_entries(struct net *net, struct arpt_get_entries __user *uptr,
const int *len)
{
int ret;
struct arpt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get))
return -EINVAL;
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct arpt_get_entries) + get.size)
return -EINVAL;
get.name[sizeof(get.name) - 1] = '\0';
t = xt_find_table_lock(net, NFPROTO_ARP, get.name);
if (!IS_ERR(t)) {
const struct xt_table_info *private = t->private;
if (get.size == private->size)
ret = copy_entries_to_user(private->size,
t, uptr->entrytable);
else
ret = -EAGAIN;
module_put(t->me);
xt_table_unlock(t);
} else
ret = PTR_ERR(t);
return ret;
}
static int __do_replace(struct net *net, const char *name,
unsigned int valid_hooks,
struct xt_table_info *newinfo,
unsigned int num_counters,
void __user *counters_ptr)
{
int ret;
struct xt_table *t;
struct xt_table_info *oldinfo;
struct xt_counters *counters;
void *loc_cpu_old_entry;
struct arpt_entry *iter;
ret = 0;
counters = vzalloc(num_counters * sizeof(struct xt_counters));
if (!counters) {
ret = -ENOMEM;
goto out;
}
t = xt_request_find_table_lock(net, NFPROTO_ARP, name);
if (IS_ERR(t)) {
ret = PTR_ERR(t);
goto free_newinfo_counters_untrans;
}
/* You lied! */
if (valid_hooks != t->valid_hooks) {
ret = -EINVAL;
goto put_module;
}
oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
if (!oldinfo)
goto put_module;
/* Update module usage count based on number of rules */
if ((oldinfo->number > oldinfo->initial_entries) ||
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
if ((oldinfo->number > oldinfo->initial_entries) &&
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
get_old_counters(oldinfo, counters);
/* Decrease module usage counts and free resource */
loc_cpu_old_entry = oldinfo->entries;
xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size)
cleanup_entry(iter);
xt_free_table_info(oldinfo);
if (copy_to_user(counters_ptr, counters,
sizeof(struct xt_counters) * num_counters) != 0) {
/* Silent error, can't fail, new table is already in place */
net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n");
}
vfree(counters);
xt_table_unlock(t);
return ret;
put_module:
module_put(t->me);
xt_table_unlock(t);
free_newinfo_counters_untrans:
vfree(counters);
out:
return ret;
}
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret;
struct arpt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct arpt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_table(newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, tmp.counters);
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int do_add_counters(struct net *net, const void __user *user,
unsigned int len, int compat)
{
unsigned int i;
struct xt_counters_info tmp;
struct xt_counters *paddc;
struct xt_table *t;
const struct xt_table_info *private;
int ret = 0;
struct arpt_entry *iter;
unsigned int addend;
paddc = xt_copy_counters_from_user(user, len, &tmp, compat);
if (IS_ERR(paddc))
return PTR_ERR(paddc);
t = xt_find_table_lock(net, NFPROTO_ARP, tmp.name);
if (IS_ERR(t)) {
ret = PTR_ERR(t);
goto free;
}
local_bh_disable();
private = t->private;
if (private->number != tmp.num_counters) {
ret = -EINVAL;
goto unlock_up_free;
}
i = 0;
addend = xt_write_recseq_begin();
xt_entry_foreach(iter, private->entries, private->size) {
struct xt_counters *tmp;
tmp = xt_get_this_cpu_counter(&iter->counters);
ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);
++i;
}
xt_write_recseq_end(addend);
unlock_up_free:
local_bh_enable();
xt_table_unlock(t);
module_put(t->me);
free:
vfree(paddc);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_arpt_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_ARP_NUMHOOKS];
u32 underflow[NF_ARP_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters;
struct compat_arpt_entry entries[0];
};
static inline void compat_release_entry(struct compat_arpt_entry *e)
{
struct xt_entry_target *t;
t = compat_arpt_get_target(e);
module_put(t->u.kernel.target->me);
}
static int
check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off;
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit)
return -EINVAL;
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target))
return -EINVAL;
if (!arp_checkentry(&e->arp))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->elems, e->target_offset,
e->next_offset);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
static void
compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr,
unsigned int *size,
struct xt_table_info *newinfo, unsigned char *base)
{
struct xt_entry_target *t;
struct arpt_entry *de;
unsigned int origsize;
int h;
origsize = *size;
de = *dstptr;
memcpy(de, e, sizeof(struct arpt_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct arpt_entry);
*size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
de->target_offset = e->target_offset - (origsize - *size);
t = compat_arpt_get_target(e);
xt_compat_target_from_user(t, dstptr, size);
de->next_offset = e->next_offset - (origsize - *size);
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)de - base < newinfo->hook_entry[h])
newinfo->hook_entry[h] -= origsize - *size;
if ((unsigned char *)de - base < newinfo->underflow[h])
newinfo->underflow[h] -= origsize - *size;
}
}
static int translate_compat_table(struct xt_table_info **pinfo,
void **pentry0,
const struct compat_arpt_replace *compatr)
{
unsigned int i, j;
struct xt_table_info *newinfo, *info;
void *pos, *entry0, *entry1;
struct compat_arpt_entry *iter0;
struct arpt_replace repl;
unsigned int size;
int ret = 0;
info = *pinfo;
entry0 = *pentry0;
size = compatr->size;
info->number = compatr->num_entries;
j = 0;
xt_compat_lock(NFPROTO_ARP);
xt_compat_init_offsets(NFPROTO_ARP, compatr->num_entries);
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter0, entry0, compatr->size) {
ret = check_compat_entry_size_and_hooks(iter0, info, &size,
entry0,
entry0 + compatr->size);
if (ret != 0)
goto out_unlock;
++j;
}
ret = -EINVAL;
if (j != compatr->num_entries)
goto out_unlock;
ret = -ENOMEM;
newinfo = xt_alloc_table_info(size);
if (!newinfo)
goto out_unlock;
newinfo->number = compatr->num_entries;
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
newinfo->hook_entry[i] = compatr->hook_entry[i];
newinfo->underflow[i] = compatr->underflow[i];
}
entry1 = newinfo->entries;
pos = entry1;
size = compatr->size;
xt_entry_foreach(iter0, entry0, compatr->size)
compat_copy_entry_from_user(iter0, &pos, &size,
newinfo, entry1);
/* all module references in entry0 are now gone */
xt_compat_flush_offsets(NFPROTO_ARP);
xt_compat_unlock(NFPROTO_ARP);
memcpy(&repl, compatr, sizeof(*compatr));
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
repl.hook_entry[i] = newinfo->hook_entry[i];
repl.underflow[i] = newinfo->underflow[i];
}
repl.num_counters = 0;
repl.counters = NULL;
repl.size = newinfo->size;
ret = translate_table(newinfo, entry1, &repl);
if (ret)
goto free_newinfo;
*pinfo = newinfo;
*pentry0 = entry1;
xt_free_table_info(info);
return 0;
free_newinfo:
xt_free_table_info(newinfo);
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_ARP);
xt_compat_unlock(NFPROTO_ARP);
xt_entry_foreach(iter0, entry0, compatr->size) {
if (j-- == 0)
break;
compat_release_entry(iter0);
}
return ret;
}
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret;
struct compat_arpt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct arpt_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(&newinfo, &loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case ARPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr,
compat_uint_t *size,
struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_arpt_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
int ret;
origsize = *size;
ce = *dstptr;
if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_arpt_entry);
*size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
target_offset = e->target_offset - (origsize - *size);
t = arpt_get_target(e);
ret = xt_compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(target_offset, &ce->target_offset) != 0 ||
put_user(next_offset, &ce->next_offset) != 0)
return -EFAULT;
return 0;
}
static int compat_copy_entries_to_user(unsigned int total_size,
struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
unsigned int i = 0;
struct arpt_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
pos = userptr;
size = total_size;
xt_entry_foreach(iter, private->entries, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
struct compat_arpt_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_arpt_entry entrytable[0];
};
static int compat_get_entries(struct net *net,
struct compat_arpt_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_arpt_get_entries get;
struct xt_table *t;
if (*len < sizeof(get))
return -EINVAL;
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct compat_arpt_get_entries) + get.size)
return -EINVAL;
get.name[sizeof(get.name) - 1] = '\0';
xt_compat_lock(NFPROTO_ARP);
t = xt_find_table_lock(net, NFPROTO_ARP, get.name);
if (!IS_ERR(t)) {
const struct xt_table_info *private = t->private;
struct xt_table_info info;
ret = compat_table_info(private, &info);
if (!ret && get.size == info.size) {
ret = compat_copy_entries_to_user(private->size,
t, uptr->entrytable);
} else if (!ret)
ret = -EAGAIN;
xt_compat_flush_offsets(NFPROTO_ARP);
module_put(t->me);
xt_table_unlock(t);
} else
ret = PTR_ERR(t);
xt_compat_unlock(NFPROTO_ARP);
return ret;
}
static int do_arpt_get_ctl(struct sock *, int, void __user *, int *);
static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user,
int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case ARPT_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_arpt_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case ARPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case ARPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case ARPT_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case ARPT_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
if (*len != sizeof(rev)) {
ret = -EINVAL;
break;
}
if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
ret = -EFAULT;
break;
}
rev.name[sizeof(rev.name)-1] = 0;
try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name,
rev.revision, 1, &ret),
"arpt_%s", rev.name);
break;
}
default:
ret = -EINVAL;
}
return ret;
}
static void __arpt_unregister_table(struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct arpt_entry *iter;
private = xt_unregister_table(table);
/* Decrease module usage counts and free resources */
loc_cpu_entry = private->entries;
xt_entry_foreach(iter, loc_cpu_entry, private->size)
cleanup_entry(iter);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
int arpt_register_table(struct net *net,
const struct xt_table *table,
const struct arpt_replace *repl,
const struct nf_hook_ops *ops,
struct xt_table **res)
{
int ret;
struct xt_table_info *newinfo;
struct xt_table_info bootstrap = {0};
void *loc_cpu_entry;
struct xt_table *new_table;
newinfo = xt_alloc_table_info(repl->size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
memcpy(loc_cpu_entry, repl->entries, repl->size);
ret = translate_table(newinfo, loc_cpu_entry, repl);
if (ret != 0)
goto out_free;
new_table = xt_register_table(net, table, &bootstrap, newinfo);
if (IS_ERR(new_table)) {
ret = PTR_ERR(new_table);
goto out_free;
}
/* set res now, will see skbs right after nf_register_net_hooks */
WRITE_ONCE(*res, new_table);
ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks));
if (ret != 0) {
__arpt_unregister_table(new_table);
*res = NULL;
}
return ret;
out_free:
xt_free_table_info(newinfo);
return ret;
}
void arpt_unregister_table(struct net *net, struct xt_table *table,
const struct nf_hook_ops *ops)
{
nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks));
__arpt_unregister_table(table);
}
/* The built-in targets: standard (NULL) and error. */
static struct xt_target arpt_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_ARP,
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = compat_standard_from_user,
.compat_to_user = compat_standard_to_user,
#endif
},
{
.name = XT_ERROR_TARGET,
.target = arpt_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_ARP,
},
};
static struct nf_sockopt_ops arpt_sockopts = {
.pf = PF_INET,
.set_optmin = ARPT_BASE_CTL,
.set_optmax = ARPT_SO_SET_MAX+1,
.set = do_arpt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_arpt_set_ctl,
#endif
.get_optmin = ARPT_BASE_CTL,
.get_optmax = ARPT_SO_GET_MAX+1,
.get = do_arpt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_arpt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __net_init arp_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_ARP);
}
static void __net_exit arp_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_ARP);
}
static struct pernet_operations arp_tables_net_ops = {
.init = arp_tables_net_init,
.exit = arp_tables_net_exit,
};
static int __init arp_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&arp_tables_net_ops);
if (ret < 0)
goto err1;
/* No one else will be downing sem now, so we won't sleep */
ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
if (ret < 0)
goto err2;
/* Register setsockopt */
ret = nf_register_sockopt(&arpt_sockopts);
if (ret < 0)
goto err4;
return 0;
err4:
xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
err2:
unregister_pernet_subsys(&arp_tables_net_ops);
err1:
return ret;
}
static void __exit arp_tables_fini(void)
{
nf_unregister_sockopt(&arpt_sockopts);
xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
unregister_pernet_subsys(&arp_tables_net_ops);
}
EXPORT_SYMBOL(arpt_register_table);
EXPORT_SYMBOL(arpt_unregister_table);
EXPORT_SYMBOL(arpt_do_table);
module_init(arp_tables_init);
module_exit(arp_tables_fini);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_99_0 |
crossvul-cpp_data_good_5209_0 | /*
* Copyright (c) 2006 - 2009 Mellanox Technology Inc. All rights reserved.
* Copyright (C) 2008 - 2011 Bart Van Assche <bvanassche@acm.org>.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/kthread.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <scsi/scsi_proto.h>
#include <scsi/scsi_tcq.h>
#include <target/target_core_base.h>
#include <target/target_core_fabric.h>
#include "ib_srpt.h"
/* Name of this kernel module. */
#define DRV_NAME "ib_srpt"
#define DRV_VERSION "2.0.0"
#define DRV_RELDATE "2011-02-14"
#define SRPT_ID_STRING "Linux SRP target"
#undef pr_fmt
#define pr_fmt(fmt) DRV_NAME " " fmt
MODULE_AUTHOR("Vu Pham and Bart Van Assche");
MODULE_DESCRIPTION("InfiniBand SCSI RDMA Protocol target "
"v" DRV_VERSION " (" DRV_RELDATE ")");
MODULE_LICENSE("Dual BSD/GPL");
/*
* Global Variables
*/
static u64 srpt_service_guid;
static DEFINE_SPINLOCK(srpt_dev_lock); /* Protects srpt_dev_list. */
static LIST_HEAD(srpt_dev_list); /* List of srpt_device structures. */
static unsigned srp_max_req_size = DEFAULT_MAX_REQ_SIZE;
module_param(srp_max_req_size, int, 0444);
MODULE_PARM_DESC(srp_max_req_size,
"Maximum size of SRP request messages in bytes.");
static int srpt_srq_size = DEFAULT_SRPT_SRQ_SIZE;
module_param(srpt_srq_size, int, 0444);
MODULE_PARM_DESC(srpt_srq_size,
"Shared receive queue (SRQ) size.");
static int srpt_get_u64_x(char *buffer, struct kernel_param *kp)
{
return sprintf(buffer, "0x%016llx", *(u64 *)kp->arg);
}
module_param_call(srpt_service_guid, NULL, srpt_get_u64_x, &srpt_service_guid,
0444);
MODULE_PARM_DESC(srpt_service_guid,
"Using this value for ioc_guid, id_ext, and cm_listen_id"
" instead of using the node_guid of the first HCA.");
static struct ib_client srpt_client;
static void srpt_release_channel(struct srpt_rdma_ch *ch);
static int srpt_queue_status(struct se_cmd *cmd);
static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc);
static void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc);
/**
* opposite_dma_dir() - Swap DMA_TO_DEVICE and DMA_FROM_DEVICE.
*/
static inline
enum dma_data_direction opposite_dma_dir(enum dma_data_direction dir)
{
switch (dir) {
case DMA_TO_DEVICE: return DMA_FROM_DEVICE;
case DMA_FROM_DEVICE: return DMA_TO_DEVICE;
default: return dir;
}
}
/**
* srpt_sdev_name() - Return the name associated with the HCA.
*
* Examples are ib0, ib1, ...
*/
static inline const char *srpt_sdev_name(struct srpt_device *sdev)
{
return sdev->device->name;
}
static enum rdma_ch_state srpt_get_ch_state(struct srpt_rdma_ch *ch)
{
unsigned long flags;
enum rdma_ch_state state;
spin_lock_irqsave(&ch->spinlock, flags);
state = ch->state;
spin_unlock_irqrestore(&ch->spinlock, flags);
return state;
}
static enum rdma_ch_state
srpt_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state new_state)
{
unsigned long flags;
enum rdma_ch_state prev;
spin_lock_irqsave(&ch->spinlock, flags);
prev = ch->state;
ch->state = new_state;
spin_unlock_irqrestore(&ch->spinlock, flags);
return prev;
}
/**
* srpt_test_and_set_ch_state() - Test and set the channel state.
*
* Returns true if and only if the channel state has been set to the new state.
*/
static bool
srpt_test_and_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state old,
enum rdma_ch_state new)
{
unsigned long flags;
enum rdma_ch_state prev;
spin_lock_irqsave(&ch->spinlock, flags);
prev = ch->state;
if (prev == old)
ch->state = new;
spin_unlock_irqrestore(&ch->spinlock, flags);
return prev == old;
}
/**
* srpt_event_handler() - Asynchronous IB event callback function.
*
* Callback function called by the InfiniBand core when an asynchronous IB
* event occurs. This callback may occur in interrupt context. See also
* section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
* Architecture Specification.
*/
static void srpt_event_handler(struct ib_event_handler *handler,
struct ib_event *event)
{
struct srpt_device *sdev;
struct srpt_port *sport;
sdev = ib_get_client_data(event->device, &srpt_client);
if (!sdev || sdev->device != event->device)
return;
pr_debug("ASYNC event= %d on device= %s\n", event->event,
srpt_sdev_name(sdev));
switch (event->event) {
case IB_EVENT_PORT_ERR:
if (event->element.port_num <= sdev->device->phys_port_cnt) {
sport = &sdev->port[event->element.port_num - 1];
sport->lid = 0;
sport->sm_lid = 0;
}
break;
case IB_EVENT_PORT_ACTIVE:
case IB_EVENT_LID_CHANGE:
case IB_EVENT_PKEY_CHANGE:
case IB_EVENT_SM_CHANGE:
case IB_EVENT_CLIENT_REREGISTER:
case IB_EVENT_GID_CHANGE:
/* Refresh port data asynchronously. */
if (event->element.port_num <= sdev->device->phys_port_cnt) {
sport = &sdev->port[event->element.port_num - 1];
if (!sport->lid && !sport->sm_lid)
schedule_work(&sport->work);
}
break;
default:
pr_err("received unrecognized IB event %d\n",
event->event);
break;
}
}
/**
* srpt_srq_event() - SRQ event callback function.
*/
static void srpt_srq_event(struct ib_event *event, void *ctx)
{
pr_info("SRQ event %d\n", event->event);
}
/**
* srpt_qp_event() - QP event callback function.
*/
static void srpt_qp_event(struct ib_event *event, struct srpt_rdma_ch *ch)
{
pr_debug("QP event %d on cm_id=%p sess_name=%s state=%d\n",
event->event, ch->cm_id, ch->sess_name, srpt_get_ch_state(ch));
switch (event->event) {
case IB_EVENT_COMM_EST:
ib_cm_notify(ch->cm_id, event->event);
break;
case IB_EVENT_QP_LAST_WQE_REACHED:
if (srpt_test_and_set_ch_state(ch, CH_DRAINING,
CH_RELEASING))
srpt_release_channel(ch);
else
pr_debug("%s: state %d - ignored LAST_WQE.\n",
ch->sess_name, srpt_get_ch_state(ch));
break;
default:
pr_err("received unrecognized IB QP event %d\n", event->event);
break;
}
}
/**
* srpt_set_ioc() - Helper function for initializing an IOUnitInfo structure.
*
* @slot: one-based slot number.
* @value: four-bit value.
*
* Copies the lowest four bits of value in element slot of the array of four
* bit elements called c_list (controller list). The index slot is one-based.
*/
static void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
{
u16 id;
u8 tmp;
id = (slot - 1) / 2;
if (slot & 0x1) {
tmp = c_list[id] & 0xf;
c_list[id] = (value << 4) | tmp;
} else {
tmp = c_list[id] & 0xf0;
c_list[id] = (value & 0xf) | tmp;
}
}
/**
* srpt_get_class_port_info() - Copy ClassPortInfo to a management datagram.
*
* See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
* Specification.
*/
static void srpt_get_class_port_info(struct ib_dm_mad *mad)
{
struct ib_class_port_info *cif;
cif = (struct ib_class_port_info *)mad->data;
memset(cif, 0, sizeof *cif);
cif->base_version = 1;
cif->class_version = 1;
cif->resp_time_value = 20;
mad->mad_hdr.status = 0;
}
/**
* srpt_get_iou() - Write IOUnitInfo to a management datagram.
*
* See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
* Specification. See also section B.7, table B.6 in the SRP r16a document.
*/
static void srpt_get_iou(struct ib_dm_mad *mad)
{
struct ib_dm_iou_info *ioui;
u8 slot;
int i;
ioui = (struct ib_dm_iou_info *)mad->data;
ioui->change_id = cpu_to_be16(1);
ioui->max_controllers = 16;
/* set present for slot 1 and empty for the rest */
srpt_set_ioc(ioui->controller_list, 1, 1);
for (i = 1, slot = 2; i < 16; i++, slot++)
srpt_set_ioc(ioui->controller_list, slot, 0);
mad->mad_hdr.status = 0;
}
/**
* srpt_get_ioc() - Write IOControllerprofile to a management datagram.
*
* See also section 16.3.3.4 IOControllerProfile in the InfiniBand
* Architecture Specification. See also section B.7, table B.7 in the SRP
* r16a document.
*/
static void srpt_get_ioc(struct srpt_port *sport, u32 slot,
struct ib_dm_mad *mad)
{
struct srpt_device *sdev = sport->sdev;
struct ib_dm_ioc_profile *iocp;
iocp = (struct ib_dm_ioc_profile *)mad->data;
if (!slot || slot > 16) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
return;
}
if (slot > 2) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_NO_IOC);
return;
}
memset(iocp, 0, sizeof *iocp);
strcpy(iocp->id_string, SRPT_ID_STRING);
iocp->guid = cpu_to_be64(srpt_service_guid);
iocp->vendor_id = cpu_to_be32(sdev->device->attrs.vendor_id);
iocp->device_id = cpu_to_be32(sdev->device->attrs.vendor_part_id);
iocp->device_version = cpu_to_be16(sdev->device->attrs.hw_ver);
iocp->subsys_vendor_id = cpu_to_be32(sdev->device->attrs.vendor_id);
iocp->subsys_device_id = 0x0;
iocp->io_class = cpu_to_be16(SRP_REV16A_IB_IO_CLASS);
iocp->io_subclass = cpu_to_be16(SRP_IO_SUBCLASS);
iocp->protocol = cpu_to_be16(SRP_PROTOCOL);
iocp->protocol_version = cpu_to_be16(SRP_PROTOCOL_VERSION);
iocp->send_queue_depth = cpu_to_be16(sdev->srq_size);
iocp->rdma_read_depth = 4;
iocp->send_size = cpu_to_be32(srp_max_req_size);
iocp->rdma_size = cpu_to_be32(min(sport->port_attrib.srp_max_rdma_size,
1U << 24));
iocp->num_svc_entries = 1;
iocp->op_cap_mask = SRP_SEND_TO_IOC | SRP_SEND_FROM_IOC |
SRP_RDMA_READ_FROM_IOC | SRP_RDMA_WRITE_FROM_IOC;
mad->mad_hdr.status = 0;
}
/**
* srpt_get_svc_entries() - Write ServiceEntries to a management datagram.
*
* See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
* Specification. See also section B.7, table B.8 in the SRP r16a document.
*/
static void srpt_get_svc_entries(u64 ioc_guid,
u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
{
struct ib_dm_svc_entries *svc_entries;
WARN_ON(!ioc_guid);
if (!slot || slot > 16) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
return;
}
if (slot > 2 || lo > hi || hi > 1) {
mad->mad_hdr.status
= cpu_to_be16(DM_MAD_STATUS_NO_IOC);
return;
}
svc_entries = (struct ib_dm_svc_entries *)mad->data;
memset(svc_entries, 0, sizeof *svc_entries);
svc_entries->service_entries[0].id = cpu_to_be64(ioc_guid);
snprintf(svc_entries->service_entries[0].name,
sizeof(svc_entries->service_entries[0].name),
"%s%016llx",
SRP_SERVICE_NAME_PREFIX,
ioc_guid);
mad->mad_hdr.status = 0;
}
/**
* srpt_mgmt_method_get() - Process a received management datagram.
* @sp: source port through which the MAD has been received.
* @rq_mad: received MAD.
* @rsp_mad: response MAD.
*/
static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
struct ib_dm_mad *rsp_mad)
{
u16 attr_id;
u32 slot;
u8 hi, lo;
attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
switch (attr_id) {
case DM_ATTR_CLASS_PORT_INFO:
srpt_get_class_port_info(rsp_mad);
break;
case DM_ATTR_IOU_INFO:
srpt_get_iou(rsp_mad);
break;
case DM_ATTR_IOC_PROFILE:
slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
srpt_get_ioc(sp, slot, rsp_mad);
break;
case DM_ATTR_SVC_ENTRIES:
slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
hi = (u8) ((slot >> 8) & 0xff);
lo = (u8) (slot & 0xff);
slot = (u16) ((slot >> 16) & 0xffff);
srpt_get_svc_entries(srpt_service_guid,
slot, hi, lo, rsp_mad);
break;
default:
rsp_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
break;
}
}
/**
* srpt_mad_send_handler() - Post MAD-send callback function.
*/
static void srpt_mad_send_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_send_wc *mad_wc)
{
ib_destroy_ah(mad_wc->send_buf->ah);
ib_free_send_mad(mad_wc->send_buf);
}
/**
* srpt_mad_recv_handler() - MAD reception callback function.
*/
static void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent,
struct ib_mad_send_buf *send_buf,
struct ib_mad_recv_wc *mad_wc)
{
struct srpt_port *sport = (struct srpt_port *)mad_agent->context;
struct ib_ah *ah;
struct ib_mad_send_buf *rsp;
struct ib_dm_mad *dm_mad;
if (!mad_wc || !mad_wc->recv_buf.mad)
return;
ah = ib_create_ah_from_wc(mad_agent->qp->pd, mad_wc->wc,
mad_wc->recv_buf.grh, mad_agent->port_num);
if (IS_ERR(ah))
goto err;
BUILD_BUG_ON(offsetof(struct ib_dm_mad, data) != IB_MGMT_DEVICE_HDR);
rsp = ib_create_send_mad(mad_agent, mad_wc->wc->src_qp,
mad_wc->wc->pkey_index, 0,
IB_MGMT_DEVICE_HDR, IB_MGMT_DEVICE_DATA,
GFP_KERNEL,
IB_MGMT_BASE_VERSION);
if (IS_ERR(rsp))
goto err_rsp;
rsp->ah = ah;
dm_mad = rsp->mad;
memcpy(dm_mad, mad_wc->recv_buf.mad, sizeof *dm_mad);
dm_mad->mad_hdr.method = IB_MGMT_METHOD_GET_RESP;
dm_mad->mad_hdr.status = 0;
switch (mad_wc->recv_buf.mad->mad_hdr.method) {
case IB_MGMT_METHOD_GET:
srpt_mgmt_method_get(sport, mad_wc->recv_buf.mad, dm_mad);
break;
case IB_MGMT_METHOD_SET:
dm_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
break;
default:
dm_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD);
break;
}
if (!ib_post_send_mad(rsp, NULL)) {
ib_free_recv_mad(mad_wc);
/* will destroy_ah & free_send_mad in send completion */
return;
}
ib_free_send_mad(rsp);
err_rsp:
ib_destroy_ah(ah);
err:
ib_free_recv_mad(mad_wc);
}
/**
* srpt_refresh_port() - Configure a HCA port.
*
* Enable InfiniBand management datagram processing, update the cached sm_lid,
* lid and gid values, and register a callback function for processing MADs
* on the specified port.
*
* Note: It is safe to call this function more than once for the same port.
*/
static int srpt_refresh_port(struct srpt_port *sport)
{
struct ib_mad_reg_req reg_req;
struct ib_port_modify port_modify;
struct ib_port_attr port_attr;
int ret;
memset(&port_modify, 0, sizeof port_modify);
port_modify.set_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
port_modify.clr_port_cap_mask = 0;
ret = ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
if (ret)
goto err_mod_port;
ret = ib_query_port(sport->sdev->device, sport->port, &port_attr);
if (ret)
goto err_query_port;
sport->sm_lid = port_attr.sm_lid;
sport->lid = port_attr.lid;
ret = ib_query_gid(sport->sdev->device, sport->port, 0, &sport->gid,
NULL);
if (ret)
goto err_query_port;
if (!sport->mad_agent) {
memset(®_req, 0, sizeof reg_req);
reg_req.mgmt_class = IB_MGMT_CLASS_DEVICE_MGMT;
reg_req.mgmt_class_version = IB_MGMT_BASE_VERSION;
set_bit(IB_MGMT_METHOD_GET, reg_req.method_mask);
set_bit(IB_MGMT_METHOD_SET, reg_req.method_mask);
sport->mad_agent = ib_register_mad_agent(sport->sdev->device,
sport->port,
IB_QPT_GSI,
®_req, 0,
srpt_mad_send_handler,
srpt_mad_recv_handler,
sport, 0);
if (IS_ERR(sport->mad_agent)) {
ret = PTR_ERR(sport->mad_agent);
sport->mad_agent = NULL;
goto err_query_port;
}
}
return 0;
err_query_port:
port_modify.set_port_cap_mask = 0;
port_modify.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
err_mod_port:
return ret;
}
/**
* srpt_unregister_mad_agent() - Unregister MAD callback functions.
*
* Note: It is safe to call this function more than once for the same device.
*/
static void srpt_unregister_mad_agent(struct srpt_device *sdev)
{
struct ib_port_modify port_modify = {
.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP,
};
struct srpt_port *sport;
int i;
for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
sport = &sdev->port[i - 1];
WARN_ON(sport->port != i);
if (ib_modify_port(sdev->device, i, 0, &port_modify) < 0)
pr_err("disabling MAD processing failed.\n");
if (sport->mad_agent) {
ib_unregister_mad_agent(sport->mad_agent);
sport->mad_agent = NULL;
}
}
}
/**
* srpt_alloc_ioctx() - Allocate an SRPT I/O context structure.
*/
static struct srpt_ioctx *srpt_alloc_ioctx(struct srpt_device *sdev,
int ioctx_size, int dma_size,
enum dma_data_direction dir)
{
struct srpt_ioctx *ioctx;
ioctx = kmalloc(ioctx_size, GFP_KERNEL);
if (!ioctx)
goto err;
ioctx->buf = kmalloc(dma_size, GFP_KERNEL);
if (!ioctx->buf)
goto err_free_ioctx;
ioctx->dma = ib_dma_map_single(sdev->device, ioctx->buf, dma_size, dir);
if (ib_dma_mapping_error(sdev->device, ioctx->dma))
goto err_free_buf;
return ioctx;
err_free_buf:
kfree(ioctx->buf);
err_free_ioctx:
kfree(ioctx);
err:
return NULL;
}
/**
* srpt_free_ioctx() - Free an SRPT I/O context structure.
*/
static void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx,
int dma_size, enum dma_data_direction dir)
{
if (!ioctx)
return;
ib_dma_unmap_single(sdev->device, ioctx->dma, dma_size, dir);
kfree(ioctx->buf);
kfree(ioctx);
}
/**
* srpt_alloc_ioctx_ring() - Allocate a ring of SRPT I/O context structures.
* @sdev: Device to allocate the I/O context ring for.
* @ring_size: Number of elements in the I/O context ring.
* @ioctx_size: I/O context size.
* @dma_size: DMA buffer size.
* @dir: DMA data direction.
*/
static struct srpt_ioctx **srpt_alloc_ioctx_ring(struct srpt_device *sdev,
int ring_size, int ioctx_size,
int dma_size, enum dma_data_direction dir)
{
struct srpt_ioctx **ring;
int i;
WARN_ON(ioctx_size != sizeof(struct srpt_recv_ioctx)
&& ioctx_size != sizeof(struct srpt_send_ioctx));
ring = kmalloc(ring_size * sizeof(ring[0]), GFP_KERNEL);
if (!ring)
goto out;
for (i = 0; i < ring_size; ++i) {
ring[i] = srpt_alloc_ioctx(sdev, ioctx_size, dma_size, dir);
if (!ring[i])
goto err;
ring[i]->index = i;
}
goto out;
err:
while (--i >= 0)
srpt_free_ioctx(sdev, ring[i], dma_size, dir);
kfree(ring);
ring = NULL;
out:
return ring;
}
/**
* srpt_free_ioctx_ring() - Free the ring of SRPT I/O context structures.
*/
static void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring,
struct srpt_device *sdev, int ring_size,
int dma_size, enum dma_data_direction dir)
{
int i;
for (i = 0; i < ring_size; ++i)
srpt_free_ioctx(sdev, ioctx_ring[i], dma_size, dir);
kfree(ioctx_ring);
}
/**
* srpt_get_cmd_state() - Get the state of a SCSI command.
*/
static enum srpt_command_state srpt_get_cmd_state(struct srpt_send_ioctx *ioctx)
{
enum srpt_command_state state;
unsigned long flags;
BUG_ON(!ioctx);
spin_lock_irqsave(&ioctx->spinlock, flags);
state = ioctx->state;
spin_unlock_irqrestore(&ioctx->spinlock, flags);
return state;
}
/**
* srpt_set_cmd_state() - Set the state of a SCSI command.
*
* Does not modify the state of aborted commands. Returns the previous command
* state.
*/
static enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx,
enum srpt_command_state new)
{
enum srpt_command_state previous;
unsigned long flags;
BUG_ON(!ioctx);
spin_lock_irqsave(&ioctx->spinlock, flags);
previous = ioctx->state;
if (previous != SRPT_STATE_DONE)
ioctx->state = new;
spin_unlock_irqrestore(&ioctx->spinlock, flags);
return previous;
}
/**
* srpt_test_and_set_cmd_state() - Test and set the state of a command.
*
* Returns true if and only if the previous command state was equal to 'old'.
*/
static bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx,
enum srpt_command_state old,
enum srpt_command_state new)
{
enum srpt_command_state previous;
unsigned long flags;
WARN_ON(!ioctx);
WARN_ON(old == SRPT_STATE_DONE);
WARN_ON(new == SRPT_STATE_NEW);
spin_lock_irqsave(&ioctx->spinlock, flags);
previous = ioctx->state;
if (previous == old)
ioctx->state = new;
spin_unlock_irqrestore(&ioctx->spinlock, flags);
return previous == old;
}
/**
* srpt_post_recv() - Post an IB receive request.
*/
static int srpt_post_recv(struct srpt_device *sdev,
struct srpt_recv_ioctx *ioctx)
{
struct ib_sge list;
struct ib_recv_wr wr, *bad_wr;
BUG_ON(!sdev);
list.addr = ioctx->ioctx.dma;
list.length = srp_max_req_size;
list.lkey = sdev->pd->local_dma_lkey;
ioctx->ioctx.cqe.done = srpt_recv_done;
wr.wr_cqe = &ioctx->ioctx.cqe;
wr.next = NULL;
wr.sg_list = &list;
wr.num_sge = 1;
return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
}
/**
* srpt_post_send() - Post an IB send request.
*
* Returns zero upon success and a non-zero value upon failure.
*/
static int srpt_post_send(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx, int len)
{
struct ib_sge list;
struct ib_send_wr wr, *bad_wr;
struct srpt_device *sdev = ch->sport->sdev;
int ret;
atomic_inc(&ch->req_lim);
ret = -ENOMEM;
if (unlikely(atomic_dec_return(&ch->sq_wr_avail) < 0)) {
pr_warn("IB send queue full (needed 1)\n");
goto out;
}
ib_dma_sync_single_for_device(sdev->device, ioctx->ioctx.dma, len,
DMA_TO_DEVICE);
list.addr = ioctx->ioctx.dma;
list.length = len;
list.lkey = sdev->pd->local_dma_lkey;
ioctx->ioctx.cqe.done = srpt_send_done;
wr.next = NULL;
wr.wr_cqe = &ioctx->ioctx.cqe;
wr.sg_list = &list;
wr.num_sge = 1;
wr.opcode = IB_WR_SEND;
wr.send_flags = IB_SEND_SIGNALED;
ret = ib_post_send(ch->qp, &wr, &bad_wr);
out:
if (ret < 0) {
atomic_inc(&ch->sq_wr_avail);
atomic_dec(&ch->req_lim);
}
return ret;
}
/**
* srpt_get_desc_tbl() - Parse the data descriptors of an SRP_CMD request.
* @ioctx: Pointer to the I/O context associated with the request.
* @srp_cmd: Pointer to the SRP_CMD request data.
* @dir: Pointer to the variable to which the transfer direction will be
* written.
* @data_len: Pointer to the variable to which the total data length of all
* descriptors in the SRP_CMD request will be written.
*
* This function initializes ioctx->nrbuf and ioctx->r_bufs.
*
* Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
* -ENOMEM when memory allocation fails and zero upon success.
*/
static int srpt_get_desc_tbl(struct srpt_send_ioctx *ioctx,
struct srp_cmd *srp_cmd,
enum dma_data_direction *dir, u64 *data_len)
{
struct srp_indirect_buf *idb;
struct srp_direct_buf *db;
unsigned add_cdb_offset;
int ret;
/*
* The pointer computations below will only be compiled correctly
* if srp_cmd::add_data is declared as s8*, u8*, s8[] or u8[], so check
* whether srp_cmd::add_data has been declared as a byte pointer.
*/
BUILD_BUG_ON(!__same_type(srp_cmd->add_data[0], (s8)0)
&& !__same_type(srp_cmd->add_data[0], (u8)0));
BUG_ON(!dir);
BUG_ON(!data_len);
ret = 0;
*data_len = 0;
/*
* The lower four bits of the buffer format field contain the DATA-IN
* buffer descriptor format, and the highest four bits contain the
* DATA-OUT buffer descriptor format.
*/
*dir = DMA_NONE;
if (srp_cmd->buf_fmt & 0xf)
/* DATA-IN: transfer data from target to initiator (read). */
*dir = DMA_FROM_DEVICE;
else if (srp_cmd->buf_fmt >> 4)
/* DATA-OUT: transfer data from initiator to target (write). */
*dir = DMA_TO_DEVICE;
/*
* According to the SRP spec, the lower two bits of the 'ADDITIONAL
* CDB LENGTH' field are reserved and the size in bytes of this field
* is four times the value specified in bits 3..7. Hence the "& ~3".
*/
add_cdb_offset = srp_cmd->add_cdb_len & ~3;
if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
ioctx->n_rbuf = 1;
ioctx->rbufs = &ioctx->single_rbuf;
db = (struct srp_direct_buf *)(srp_cmd->add_data
+ add_cdb_offset);
memcpy(ioctx->rbufs, db, sizeof *db);
*data_len = be32_to_cpu(db->len);
} else if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_INDIRECT) ||
((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_INDIRECT)) {
idb = (struct srp_indirect_buf *)(srp_cmd->add_data
+ add_cdb_offset);
ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof *db;
if (ioctx->n_rbuf >
(srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
pr_err("received unsupported SRP_CMD request"
" type (%u out + %u in != %u / %zu)\n",
srp_cmd->data_out_desc_cnt,
srp_cmd->data_in_desc_cnt,
be32_to_cpu(idb->table_desc.len),
sizeof(*db));
ioctx->n_rbuf = 0;
ret = -EINVAL;
goto out;
}
if (ioctx->n_rbuf == 1)
ioctx->rbufs = &ioctx->single_rbuf;
else {
ioctx->rbufs =
kmalloc(ioctx->n_rbuf * sizeof *db, GFP_ATOMIC);
if (!ioctx->rbufs) {
ioctx->n_rbuf = 0;
ret = -ENOMEM;
goto out;
}
}
db = idb->desc_list;
memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof *db);
*data_len = be32_to_cpu(idb->len);
}
out:
return ret;
}
/**
* srpt_init_ch_qp() - Initialize queue pair attributes.
*
* Initialized the attributes of queue pair 'qp' by allowing local write,
* remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.
*/
static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
struct ib_qp_attr *attr;
int ret;
attr = kzalloc(sizeof *attr, GFP_KERNEL);
if (!attr)
return -ENOMEM;
attr->qp_state = IB_QPS_INIT;
attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ |
IB_ACCESS_REMOTE_WRITE;
attr->port_num = ch->sport->port;
attr->pkey_index = 0;
ret = ib_modify_qp(qp, attr,
IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
IB_QP_PKEY_INDEX);
kfree(attr);
return ret;
}
/**
* srpt_ch_qp_rtr() - Change the state of a channel to 'ready to receive' (RTR).
* @ch: channel of the queue pair.
* @qp: queue pair to change the state of.
*
* Returns zero upon success and a negative value upon failure.
*
* Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
* If this structure ever becomes larger, it might be necessary to allocate
* it dynamically instead of on the stack.
*/
static int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
struct ib_qp_attr qp_attr;
int attr_mask;
int ret;
qp_attr.qp_state = IB_QPS_RTR;
ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
if (ret)
goto out;
qp_attr.max_dest_rd_atomic = 4;
ret = ib_modify_qp(qp, &qp_attr, attr_mask);
out:
return ret;
}
/**
* srpt_ch_qp_rts() - Change the state of a channel to 'ready to send' (RTS).
* @ch: channel of the queue pair.
* @qp: queue pair to change the state of.
*
* Returns zero upon success and a negative value upon failure.
*
* Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
* If this structure ever becomes larger, it might be necessary to allocate
* it dynamically instead of on the stack.
*/
static int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
{
struct ib_qp_attr qp_attr;
int attr_mask;
int ret;
qp_attr.qp_state = IB_QPS_RTS;
ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
if (ret)
goto out;
qp_attr.max_rd_atomic = 4;
ret = ib_modify_qp(qp, &qp_attr, attr_mask);
out:
return ret;
}
/**
* srpt_ch_qp_err() - Set the channel queue pair state to 'error'.
*/
static int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
{
struct ib_qp_attr qp_attr;
qp_attr.qp_state = IB_QPS_ERR;
return ib_modify_qp(ch->qp, &qp_attr, IB_QP_STATE);
}
/**
* srpt_unmap_sg_to_ib_sge() - Unmap an IB SGE list.
*/
static void srpt_unmap_sg_to_ib_sge(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
struct scatterlist *sg;
enum dma_data_direction dir;
BUG_ON(!ch);
BUG_ON(!ioctx);
BUG_ON(ioctx->n_rdma && !ioctx->rdma_wrs);
while (ioctx->n_rdma)
kfree(ioctx->rdma_wrs[--ioctx->n_rdma].wr.sg_list);
kfree(ioctx->rdma_wrs);
ioctx->rdma_wrs = NULL;
if (ioctx->mapped_sg_count) {
sg = ioctx->sg;
WARN_ON(!sg);
dir = ioctx->cmd.data_direction;
BUG_ON(dir == DMA_NONE);
ib_dma_unmap_sg(ch->sport->sdev->device, sg, ioctx->sg_cnt,
opposite_dma_dir(dir));
ioctx->mapped_sg_count = 0;
}
}
/**
* srpt_map_sg_to_ib_sge() - Map an SG list to an IB SGE list.
*/
static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
struct ib_device *dev = ch->sport->sdev->device;
struct se_cmd *cmd;
struct scatterlist *sg, *sg_orig;
int sg_cnt;
enum dma_data_direction dir;
struct ib_rdma_wr *riu;
struct srp_direct_buf *db;
dma_addr_t dma_addr;
struct ib_sge *sge;
u64 raddr;
u32 rsize;
u32 tsize;
u32 dma_len;
int count, nrdma;
int i, j, k;
BUG_ON(!ch);
BUG_ON(!ioctx);
cmd = &ioctx->cmd;
dir = cmd->data_direction;
BUG_ON(dir == DMA_NONE);
ioctx->sg = sg = sg_orig = cmd->t_data_sg;
ioctx->sg_cnt = sg_cnt = cmd->t_data_nents;
count = ib_dma_map_sg(ch->sport->sdev->device, sg, sg_cnt,
opposite_dma_dir(dir));
if (unlikely(!count))
return -EAGAIN;
ioctx->mapped_sg_count = count;
if (ioctx->rdma_wrs && ioctx->n_rdma_wrs)
nrdma = ioctx->n_rdma_wrs;
else {
nrdma = (count + SRPT_DEF_SG_PER_WQE - 1) / SRPT_DEF_SG_PER_WQE
+ ioctx->n_rbuf;
ioctx->rdma_wrs = kcalloc(nrdma, sizeof(*ioctx->rdma_wrs),
GFP_KERNEL);
if (!ioctx->rdma_wrs)
goto free_mem;
ioctx->n_rdma_wrs = nrdma;
}
db = ioctx->rbufs;
tsize = cmd->data_length;
dma_len = ib_sg_dma_len(dev, &sg[0]);
riu = ioctx->rdma_wrs;
/*
* For each remote desc - calculate the #ib_sge.
* If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
* each remote desc rdma_iu is required a rdma wr;
* else
* we need to allocate extra rdma_iu to carry extra #ib_sge in
* another rdma wr
*/
for (i = 0, j = 0;
j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
rsize = be32_to_cpu(db->len);
raddr = be64_to_cpu(db->va);
riu->remote_addr = raddr;
riu->rkey = be32_to_cpu(db->key);
riu->wr.num_sge = 0;
/* calculate how many sge required for this remote_buf */
while (rsize > 0 && tsize > 0) {
if (rsize >= dma_len) {
tsize -= dma_len;
rsize -= dma_len;
raddr += dma_len;
if (tsize > 0) {
++j;
if (j < count) {
sg = sg_next(sg);
dma_len = ib_sg_dma_len(
dev, sg);
}
}
} else {
tsize -= rsize;
dma_len -= rsize;
rsize = 0;
}
++riu->wr.num_sge;
if (rsize > 0 &&
riu->wr.num_sge == SRPT_DEF_SG_PER_WQE) {
++ioctx->n_rdma;
riu->wr.sg_list = kmalloc_array(riu->wr.num_sge,
sizeof(*riu->wr.sg_list),
GFP_KERNEL);
if (!riu->wr.sg_list)
goto free_mem;
++riu;
riu->wr.num_sge = 0;
riu->remote_addr = raddr;
riu->rkey = be32_to_cpu(db->key);
}
}
++ioctx->n_rdma;
riu->wr.sg_list = kmalloc_array(riu->wr.num_sge,
sizeof(*riu->wr.sg_list),
GFP_KERNEL);
if (!riu->wr.sg_list)
goto free_mem;
}
db = ioctx->rbufs;
tsize = cmd->data_length;
riu = ioctx->rdma_wrs;
sg = sg_orig;
dma_len = ib_sg_dma_len(dev, &sg[0]);
dma_addr = ib_sg_dma_address(dev, &sg[0]);
/* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
for (i = 0, j = 0;
j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
rsize = be32_to_cpu(db->len);
sge = riu->wr.sg_list;
k = 0;
while (rsize > 0 && tsize > 0) {
sge->addr = dma_addr;
sge->lkey = ch->sport->sdev->pd->local_dma_lkey;
if (rsize >= dma_len) {
sge->length =
(tsize < dma_len) ? tsize : dma_len;
tsize -= dma_len;
rsize -= dma_len;
if (tsize > 0) {
++j;
if (j < count) {
sg = sg_next(sg);
dma_len = ib_sg_dma_len(
dev, sg);
dma_addr = ib_sg_dma_address(
dev, sg);
}
}
} else {
sge->length = (tsize < rsize) ? tsize : rsize;
tsize -= rsize;
dma_len -= rsize;
dma_addr += rsize;
rsize = 0;
}
++k;
if (k == riu->wr.num_sge && rsize > 0 && tsize > 0) {
++riu;
sge = riu->wr.sg_list;
k = 0;
} else if (rsize > 0 && tsize > 0)
++sge;
}
}
return 0;
free_mem:
srpt_unmap_sg_to_ib_sge(ch, ioctx);
return -ENOMEM;
}
/**
* srpt_get_send_ioctx() - Obtain an I/O context for sending to the initiator.
*/
static struct srpt_send_ioctx *srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
{
struct srpt_send_ioctx *ioctx;
unsigned long flags;
BUG_ON(!ch);
ioctx = NULL;
spin_lock_irqsave(&ch->spinlock, flags);
if (!list_empty(&ch->free_list)) {
ioctx = list_first_entry(&ch->free_list,
struct srpt_send_ioctx, free_list);
list_del(&ioctx->free_list);
}
spin_unlock_irqrestore(&ch->spinlock, flags);
if (!ioctx)
return ioctx;
BUG_ON(ioctx->ch != ch);
spin_lock_init(&ioctx->spinlock);
ioctx->state = SRPT_STATE_NEW;
ioctx->n_rbuf = 0;
ioctx->rbufs = NULL;
ioctx->n_rdma = 0;
ioctx->n_rdma_wrs = 0;
ioctx->rdma_wrs = NULL;
ioctx->mapped_sg_count = 0;
init_completion(&ioctx->tx_done);
ioctx->queue_status_only = false;
/*
* transport_init_se_cmd() does not initialize all fields, so do it
* here.
*/
memset(&ioctx->cmd, 0, sizeof(ioctx->cmd));
memset(&ioctx->sense_data, 0, sizeof(ioctx->sense_data));
return ioctx;
}
/**
* srpt_abort_cmd() - Abort a SCSI command.
* @ioctx: I/O context associated with the SCSI command.
* @context: Preferred execution context.
*/
static int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
{
enum srpt_command_state state;
unsigned long flags;
BUG_ON(!ioctx);
/*
* If the command is in a state where the target core is waiting for
* the ib_srpt driver, change the state to the next state. Changing
* the state of the command from SRPT_STATE_NEED_DATA to
* SRPT_STATE_DATA_IN ensures that srpt_xmit_response() will call this
* function a second time.
*/
spin_lock_irqsave(&ioctx->spinlock, flags);
state = ioctx->state;
switch (state) {
case SRPT_STATE_NEED_DATA:
ioctx->state = SRPT_STATE_DATA_IN;
break;
case SRPT_STATE_DATA_IN:
case SRPT_STATE_CMD_RSP_SENT:
case SRPT_STATE_MGMT_RSP_SENT:
ioctx->state = SRPT_STATE_DONE;
break;
default:
break;
}
spin_unlock_irqrestore(&ioctx->spinlock, flags);
if (state == SRPT_STATE_DONE) {
struct srpt_rdma_ch *ch = ioctx->ch;
BUG_ON(ch->sess == NULL);
target_put_sess_cmd(&ioctx->cmd);
goto out;
}
pr_debug("Aborting cmd with state %d and tag %lld\n", state,
ioctx->cmd.tag);
switch (state) {
case SRPT_STATE_NEW:
case SRPT_STATE_DATA_IN:
case SRPT_STATE_MGMT:
/*
* Do nothing - defer abort processing until
* srpt_queue_response() is invoked.
*/
WARN_ON(!transport_check_aborted_status(&ioctx->cmd, false));
break;
case SRPT_STATE_NEED_DATA:
/* DMA_TO_DEVICE (write) - RDMA read error. */
/* XXX(hch): this is a horrible layering violation.. */
spin_lock_irqsave(&ioctx->cmd.t_state_lock, flags);
ioctx->cmd.transport_state &= ~CMD_T_ACTIVE;
spin_unlock_irqrestore(&ioctx->cmd.t_state_lock, flags);
break;
case SRPT_STATE_CMD_RSP_SENT:
/*
* SRP_RSP sending failed or the SRP_RSP send completion has
* not been received in time.
*/
srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
target_put_sess_cmd(&ioctx->cmd);
break;
case SRPT_STATE_MGMT_RSP_SENT:
srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
target_put_sess_cmd(&ioctx->cmd);
break;
default:
WARN(1, "Unexpected command state (%d)", state);
break;
}
out:
return state;
}
/**
* XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
* the data that has been transferred via IB RDMA had to be postponed until the
* check_stop_free() callback. None of this is necessary anymore and needs to
* be cleaned up.
*/
static void srpt_rdma_read_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_send_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe);
WARN_ON(ioctx->n_rdma <= 0);
atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
if (unlikely(wc->status != IB_WC_SUCCESS)) {
pr_info("RDMA_READ for ioctx 0x%p failed with status %d\n",
ioctx, wc->status);
srpt_abort_cmd(ioctx);
return;
}
if (srpt_test_and_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA,
SRPT_STATE_DATA_IN))
target_execute_cmd(&ioctx->cmd);
else
pr_err("%s[%d]: wrong state = %d\n", __func__,
__LINE__, srpt_get_cmd_state(ioctx));
}
static void srpt_rdma_write_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_send_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe);
if (unlikely(wc->status != IB_WC_SUCCESS)) {
pr_info("RDMA_WRITE for ioctx 0x%p failed with status %d\n",
ioctx, wc->status);
srpt_abort_cmd(ioctx);
}
}
/**
* srpt_build_cmd_rsp() - Build an SRP_RSP response.
* @ch: RDMA channel through which the request has been received.
* @ioctx: I/O context associated with the SRP_CMD request. The response will
* be built in the buffer ioctx->buf points at and hence this function will
* overwrite the request data.
* @tag: tag of the request for which this response is being generated.
* @status: value for the STATUS field of the SRP_RSP information unit.
*
* Returns the size in bytes of the SRP_RSP response.
*
* An SRP_RSP response contains a SCSI status or service response. See also
* section 6.9 in the SRP r16a document for the format of an SRP_RSP
* response. See also SPC-2 for more information about sense data.
*/
static int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx, u64 tag,
int status)
{
struct srp_rsp *srp_rsp;
const u8 *sense_data;
int sense_data_len, max_sense_len;
/*
* The lowest bit of all SAM-3 status codes is zero (see also
* paragraph 5.3 in SAM-3).
*/
WARN_ON(status & 1);
srp_rsp = ioctx->ioctx.buf;
BUG_ON(!srp_rsp);
sense_data = ioctx->sense_data;
sense_data_len = ioctx->cmd.scsi_sense_length;
WARN_ON(sense_data_len > sizeof(ioctx->sense_data));
memset(srp_rsp, 0, sizeof *srp_rsp);
srp_rsp->opcode = SRP_RSP;
srp_rsp->req_lim_delta =
cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
srp_rsp->tag = tag;
srp_rsp->status = status;
if (sense_data_len) {
BUILD_BUG_ON(MIN_MAX_RSP_SIZE <= sizeof(*srp_rsp));
max_sense_len = ch->max_ti_iu_len - sizeof(*srp_rsp);
if (sense_data_len > max_sense_len) {
pr_warn("truncated sense data from %d to %d"
" bytes\n", sense_data_len, max_sense_len);
sense_data_len = max_sense_len;
}
srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
srp_rsp->sense_data_len = cpu_to_be32(sense_data_len);
memcpy(srp_rsp + 1, sense_data, sense_data_len);
}
return sizeof(*srp_rsp) + sense_data_len;
}
/**
* srpt_build_tskmgmt_rsp() - Build a task management response.
* @ch: RDMA channel through which the request has been received.
* @ioctx: I/O context in which the SRP_RSP response will be built.
* @rsp_code: RSP_CODE that will be stored in the response.
* @tag: Tag of the request for which this response is being generated.
*
* Returns the size in bytes of the SRP_RSP response.
*
* An SRP_RSP response contains a SCSI status or service response. See also
* section 6.9 in the SRP r16a document for the format of an SRP_RSP
* response.
*/
static int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx,
u8 rsp_code, u64 tag)
{
struct srp_rsp *srp_rsp;
int resp_data_len;
int resp_len;
resp_data_len = 4;
resp_len = sizeof(*srp_rsp) + resp_data_len;
srp_rsp = ioctx->ioctx.buf;
BUG_ON(!srp_rsp);
memset(srp_rsp, 0, sizeof *srp_rsp);
srp_rsp->opcode = SRP_RSP;
srp_rsp->req_lim_delta =
cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
srp_rsp->tag = tag;
srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
srp_rsp->resp_data_len = cpu_to_be32(resp_data_len);
srp_rsp->data[3] = rsp_code;
return resp_len;
}
#define NO_SUCH_LUN ((uint64_t)-1LL)
/*
* SCSI LUN addressing method. See also SAM-2 and the section about
* eight byte LUNs.
*/
enum scsi_lun_addr_method {
SCSI_LUN_ADDR_METHOD_PERIPHERAL = 0,
SCSI_LUN_ADDR_METHOD_FLAT = 1,
SCSI_LUN_ADDR_METHOD_LUN = 2,
SCSI_LUN_ADDR_METHOD_EXTENDED_LUN = 3,
};
/*
* srpt_unpack_lun() - Convert from network LUN to linear LUN.
*
* Convert an 2-byte, 4-byte, 6-byte or 8-byte LUN structure in network byte
* order (big endian) to a linear LUN. Supports three LUN addressing methods:
* peripheral, flat and logical unit. See also SAM-2, section 4.9.4 (page 40).
*/
static uint64_t srpt_unpack_lun(const uint8_t *lun, int len)
{
uint64_t res = NO_SUCH_LUN;
int addressing_method;
if (unlikely(len < 2)) {
pr_err("Illegal LUN length %d, expected 2 bytes or more\n",
len);
goto out;
}
switch (len) {
case 8:
if ((*((__be64 *)lun) &
cpu_to_be64(0x0000FFFFFFFFFFFFLL)) != 0)
goto out_err;
break;
case 4:
if (*((__be16 *)&lun[2]) != 0)
goto out_err;
break;
case 6:
if (*((__be32 *)&lun[2]) != 0)
goto out_err;
break;
case 2:
break;
default:
goto out_err;
}
addressing_method = (*lun) >> 6; /* highest two bits of byte 0 */
switch (addressing_method) {
case SCSI_LUN_ADDR_METHOD_PERIPHERAL:
case SCSI_LUN_ADDR_METHOD_FLAT:
case SCSI_LUN_ADDR_METHOD_LUN:
res = *(lun + 1) | (((*lun) & 0x3f) << 8);
break;
case SCSI_LUN_ADDR_METHOD_EXTENDED_LUN:
default:
pr_err("Unimplemented LUN addressing method %u\n",
addressing_method);
break;
}
out:
return res;
out_err:
pr_err("Support for multi-level LUNs has not yet been implemented\n");
goto out;
}
static int srpt_check_stop_free(struct se_cmd *cmd)
{
struct srpt_send_ioctx *ioctx = container_of(cmd,
struct srpt_send_ioctx, cmd);
return target_put_sess_cmd(&ioctx->cmd);
}
/**
* srpt_handle_cmd() - Process SRP_CMD.
*/
static int srpt_handle_cmd(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct se_cmd *cmd;
struct srp_cmd *srp_cmd;
uint64_t unpacked_lun;
u64 data_len;
enum dma_data_direction dir;
sense_reason_t ret;
int rc;
BUG_ON(!send_ioctx);
srp_cmd = recv_ioctx->ioctx.buf;
cmd = &send_ioctx->cmd;
cmd->tag = srp_cmd->tag;
switch (srp_cmd->task_attr) {
case SRP_CMD_SIMPLE_Q:
cmd->sam_task_attr = TCM_SIMPLE_TAG;
break;
case SRP_CMD_ORDERED_Q:
default:
cmd->sam_task_attr = TCM_ORDERED_TAG;
break;
case SRP_CMD_HEAD_OF_Q:
cmd->sam_task_attr = TCM_HEAD_TAG;
break;
case SRP_CMD_ACA:
cmd->sam_task_attr = TCM_ACA_TAG;
break;
}
if (srpt_get_desc_tbl(send_ioctx, srp_cmd, &dir, &data_len)) {
pr_err("0x%llx: parsing SRP descriptor table failed.\n",
srp_cmd->tag);
ret = TCM_INVALID_CDB_FIELD;
goto send_sense;
}
unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_cmd->lun,
sizeof(srp_cmd->lun));
rc = target_submit_cmd(cmd, ch->sess, srp_cmd->cdb,
&send_ioctx->sense_data[0], unpacked_lun, data_len,
TCM_SIMPLE_TAG, dir, TARGET_SCF_ACK_KREF);
if (rc != 0) {
ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
goto send_sense;
}
return 0;
send_sense:
transport_send_check_condition_and_sense(cmd, ret, 0);
return -1;
}
static int srp_tmr_to_tcm(int fn)
{
switch (fn) {
case SRP_TSK_ABORT_TASK:
return TMR_ABORT_TASK;
case SRP_TSK_ABORT_TASK_SET:
return TMR_ABORT_TASK_SET;
case SRP_TSK_CLEAR_TASK_SET:
return TMR_CLEAR_TASK_SET;
case SRP_TSK_LUN_RESET:
return TMR_LUN_RESET;
case SRP_TSK_CLEAR_ACA:
return TMR_CLEAR_ACA;
default:
return -1;
}
}
/**
* srpt_handle_tsk_mgmt() - Process an SRP_TSK_MGMT information unit.
*
* Returns 0 if and only if the request will be processed by the target core.
*
* For more information about SRP_TSK_MGMT information units, see also section
* 6.7 in the SRP r16a document.
*/
static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct srp_tsk_mgmt *srp_tsk;
struct se_cmd *cmd;
struct se_session *sess = ch->sess;
uint64_t unpacked_lun;
int tcm_tmr;
int rc;
BUG_ON(!send_ioctx);
srp_tsk = recv_ioctx->ioctx.buf;
cmd = &send_ioctx->cmd;
pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
" cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
send_ioctx->cmd.tag = srp_tsk->tag;
tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,
sizeof(srp_tsk->lun));
rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,
srp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag,
TARGET_SCF_ACK_KREF);
if (rc != 0) {
send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
goto fail;
}
return;
fail:
transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
}
/**
* srpt_handle_new_iu() - Process a newly received information unit.
* @ch: RDMA channel through which the information unit has been received.
* @ioctx: SRPT I/O context associated with the information unit.
*/
static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct srp_cmd *srp_cmd;
enum rdma_ch_state ch_state;
BUG_ON(!ch);
BUG_ON(!recv_ioctx);
ib_dma_sync_single_for_cpu(ch->sport->sdev->device,
recv_ioctx->ioctx.dma, srp_max_req_size,
DMA_FROM_DEVICE);
ch_state = srpt_get_ch_state(ch);
if (unlikely(ch_state == CH_CONNECTING)) {
list_add_tail(&recv_ioctx->wait_list, &ch->cmd_wait_list);
goto out;
}
if (unlikely(ch_state != CH_LIVE))
goto out;
srp_cmd = recv_ioctx->ioctx.buf;
if (srp_cmd->opcode == SRP_CMD || srp_cmd->opcode == SRP_TSK_MGMT) {
if (!send_ioctx)
send_ioctx = srpt_get_send_ioctx(ch);
if (unlikely(!send_ioctx)) {
list_add_tail(&recv_ioctx->wait_list,
&ch->cmd_wait_list);
goto out;
}
}
switch (srp_cmd->opcode) {
case SRP_CMD:
srpt_handle_cmd(ch, recv_ioctx, send_ioctx);
break;
case SRP_TSK_MGMT:
srpt_handle_tsk_mgmt(ch, recv_ioctx, send_ioctx);
break;
case SRP_I_LOGOUT:
pr_err("Not yet implemented: SRP_I_LOGOUT\n");
break;
case SRP_CRED_RSP:
pr_debug("received SRP_CRED_RSP\n");
break;
case SRP_AER_RSP:
pr_debug("received SRP_AER_RSP\n");
break;
case SRP_RSP:
pr_err("Received SRP_RSP\n");
break;
default:
pr_err("received IU with unknown opcode 0x%x\n",
srp_cmd->opcode);
break;
}
srpt_post_recv(ch->sport->sdev, recv_ioctx);
out:
return;
}
static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_recv_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_recv_ioctx, ioctx.cqe);
if (wc->status == IB_WC_SUCCESS) {
int req_lim;
req_lim = atomic_dec_return(&ch->req_lim);
if (unlikely(req_lim < 0))
pr_err("req_lim = %d < 0\n", req_lim);
srpt_handle_new_iu(ch, ioctx, NULL);
} else {
pr_info("receiving failed for ioctx %p with status %d\n",
ioctx, wc->status);
}
}
/**
* Note: Although this has not yet been observed during tests, at least in
* theory it is possible that the srpt_get_send_ioctx() call invoked by
* srpt_handle_new_iu() fails. This is possible because the req_lim_delta
* value in each response is set to one, and it is possible that this response
* makes the initiator send a new request before the send completion for that
* response has been processed. This could e.g. happen if the call to
* srpt_put_send_iotcx() is delayed because of a higher priority interrupt or
* if IB retransmission causes generation of the send completion to be
* delayed. Incoming information units for which srpt_get_send_ioctx() fails
* are queued on cmd_wait_list. The code below processes these delayed
* requests one at a time.
*/
static void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_send_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_send_ioctx, ioctx.cqe);
enum srpt_command_state state;
state = srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
WARN_ON(state != SRPT_STATE_CMD_RSP_SENT &&
state != SRPT_STATE_MGMT_RSP_SENT);
atomic_inc(&ch->sq_wr_avail);
if (wc->status != IB_WC_SUCCESS) {
pr_info("sending response for ioctx 0x%p failed"
" with status %d\n", ioctx, wc->status);
atomic_dec(&ch->req_lim);
srpt_abort_cmd(ioctx);
goto out;
}
if (state != SRPT_STATE_DONE) {
srpt_unmap_sg_to_ib_sge(ch, ioctx);
transport_generic_free_cmd(&ioctx->cmd, 0);
} else {
pr_err("IB completion has been received too late for"
" wr_id = %u.\n", ioctx->ioctx.index);
}
out:
while (!list_empty(&ch->cmd_wait_list) &&
srpt_get_ch_state(ch) == CH_LIVE &&
(ioctx = srpt_get_send_ioctx(ch)) != NULL) {
struct srpt_recv_ioctx *recv_ioctx;
recv_ioctx = list_first_entry(&ch->cmd_wait_list,
struct srpt_recv_ioctx,
wait_list);
list_del(&recv_ioctx->wait_list);
srpt_handle_new_iu(ch, recv_ioctx, ioctx);
}
}
/**
* srpt_create_ch_ib() - Create receive and send completion queues.
*/
static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
{
struct ib_qp_init_attr *qp_init;
struct srpt_port *sport = ch->sport;
struct srpt_device *sdev = sport->sdev;
u32 srp_sq_size = sport->port_attrib.srp_sq_size;
int ret;
WARN_ON(ch->rq_size < 1);
ret = -ENOMEM;
qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
if (!qp_init)
goto out;
retry:
ch->cq = ib_alloc_cq(sdev->device, ch, ch->rq_size + srp_sq_size,
0 /* XXX: spread CQs */, IB_POLL_WORKQUEUE);
if (IS_ERR(ch->cq)) {
ret = PTR_ERR(ch->cq);
pr_err("failed to create CQ cqe= %d ret= %d\n",
ch->rq_size + srp_sq_size, ret);
goto out;
}
qp_init->qp_context = (void *)ch;
qp_init->event_handler
= (void(*)(struct ib_event *, void*))srpt_qp_event;
qp_init->send_cq = ch->cq;
qp_init->recv_cq = ch->cq;
qp_init->srq = sdev->srq;
qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
qp_init->qp_type = IB_QPT_RC;
qp_init->cap.max_send_wr = srp_sq_size;
qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
ch->qp = ib_create_qp(sdev->pd, qp_init);
if (IS_ERR(ch->qp)) {
ret = PTR_ERR(ch->qp);
if (ret == -ENOMEM) {
srp_sq_size /= 2;
if (srp_sq_size >= MIN_SRPT_SQ_SIZE) {
ib_destroy_cq(ch->cq);
goto retry;
}
}
pr_err("failed to create_qp ret= %d\n", ret);
goto err_destroy_cq;
}
atomic_set(&ch->sq_wr_avail, qp_init->cap.max_send_wr);
pr_debug("%s: max_cqe= %d max_sge= %d sq_size = %d cm_id= %p\n",
__func__, ch->cq->cqe, qp_init->cap.max_send_sge,
qp_init->cap.max_send_wr, ch->cm_id);
ret = srpt_init_ch_qp(ch, ch->qp);
if (ret)
goto err_destroy_qp;
out:
kfree(qp_init);
return ret;
err_destroy_qp:
ib_destroy_qp(ch->qp);
err_destroy_cq:
ib_free_cq(ch->cq);
goto out;
}
static void srpt_destroy_ch_ib(struct srpt_rdma_ch *ch)
{
ib_destroy_qp(ch->qp);
ib_free_cq(ch->cq);
}
/**
* __srpt_close_ch() - Close an RDMA channel by setting the QP error state.
*
* Reset the QP and make sure all resources associated with the channel will
* be deallocated at an appropriate time.
*
* Note: The caller must hold ch->sport->sdev->spinlock.
*/
static void __srpt_close_ch(struct srpt_rdma_ch *ch)
{
enum rdma_ch_state prev_state;
unsigned long flags;
spin_lock_irqsave(&ch->spinlock, flags);
prev_state = ch->state;
switch (prev_state) {
case CH_CONNECTING:
case CH_LIVE:
ch->state = CH_DISCONNECTING;
break;
default:
break;
}
spin_unlock_irqrestore(&ch->spinlock, flags);
switch (prev_state) {
case CH_CONNECTING:
ib_send_cm_rej(ch->cm_id, IB_CM_REJ_NO_RESOURCES, NULL, 0,
NULL, 0);
/* fall through */
case CH_LIVE:
if (ib_send_cm_dreq(ch->cm_id, NULL, 0) < 0)
pr_err("sending CM DREQ failed.\n");
break;
case CH_DISCONNECTING:
break;
case CH_DRAINING:
case CH_RELEASING:
break;
}
}
/**
* srpt_close_ch() - Close an RDMA channel.
*/
static void srpt_close_ch(struct srpt_rdma_ch *ch)
{
struct srpt_device *sdev;
sdev = ch->sport->sdev;
spin_lock_irq(&sdev->spinlock);
__srpt_close_ch(ch);
spin_unlock_irq(&sdev->spinlock);
}
/**
* srpt_shutdown_session() - Whether or not a session may be shut down.
*/
static int srpt_shutdown_session(struct se_session *se_sess)
{
struct srpt_rdma_ch *ch = se_sess->fabric_sess_ptr;
unsigned long flags;
spin_lock_irqsave(&ch->spinlock, flags);
if (ch->in_shutdown) {
spin_unlock_irqrestore(&ch->spinlock, flags);
return true;
}
ch->in_shutdown = true;
target_sess_cmd_list_set_waiting(se_sess);
spin_unlock_irqrestore(&ch->spinlock, flags);
return true;
}
/**
* srpt_drain_channel() - Drain a channel by resetting the IB queue pair.
* @cm_id: Pointer to the CM ID of the channel to be drained.
*
* Note: Must be called from inside srpt_cm_handler to avoid a race between
* accessing sdev->spinlock and the call to kfree(sdev) in srpt_remove_one()
* (the caller of srpt_cm_handler holds the cm_id spinlock; srpt_remove_one()
* waits until all target sessions for the associated IB device have been
* unregistered and target session registration involves a call to
* ib_destroy_cm_id(), which locks the cm_id spinlock and hence waits until
* this function has finished).
*/
static void srpt_drain_channel(struct ib_cm_id *cm_id)
{
struct srpt_device *sdev;
struct srpt_rdma_ch *ch;
int ret;
bool do_reset = false;
WARN_ON_ONCE(irqs_disabled());
sdev = cm_id->context;
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
list_for_each_entry(ch, &sdev->rch_list, list) {
if (ch->cm_id == cm_id) {
do_reset = srpt_test_and_set_ch_state(ch,
CH_CONNECTING, CH_DRAINING) ||
srpt_test_and_set_ch_state(ch,
CH_LIVE, CH_DRAINING) ||
srpt_test_and_set_ch_state(ch,
CH_DISCONNECTING, CH_DRAINING);
break;
}
}
spin_unlock_irq(&sdev->spinlock);
if (do_reset) {
if (ch->sess)
srpt_shutdown_session(ch->sess);
ret = srpt_ch_qp_err(ch);
if (ret < 0)
pr_err("Setting queue pair in error state"
" failed: %d\n", ret);
}
}
/**
* srpt_find_channel() - Look up an RDMA channel.
* @cm_id: Pointer to the CM ID of the channel to be looked up.
*
* Return NULL if no matching RDMA channel has been found.
*/
static struct srpt_rdma_ch *srpt_find_channel(struct srpt_device *sdev,
struct ib_cm_id *cm_id)
{
struct srpt_rdma_ch *ch;
bool found;
WARN_ON_ONCE(irqs_disabled());
BUG_ON(!sdev);
found = false;
spin_lock_irq(&sdev->spinlock);
list_for_each_entry(ch, &sdev->rch_list, list) {
if (ch->cm_id == cm_id) {
found = true;
break;
}
}
spin_unlock_irq(&sdev->spinlock);
return found ? ch : NULL;
}
/**
* srpt_release_channel() - Release channel resources.
*
* Schedules the actual release because:
* - Calling the ib_destroy_cm_id() call from inside an IB CM callback would
* trigger a deadlock.
* - It is not safe to call TCM transport_* functions from interrupt context.
*/
static void srpt_release_channel(struct srpt_rdma_ch *ch)
{
schedule_work(&ch->release_work);
}
static void srpt_release_channel_work(struct work_struct *w)
{
struct srpt_rdma_ch *ch;
struct srpt_device *sdev;
struct se_session *se_sess;
ch = container_of(w, struct srpt_rdma_ch, release_work);
pr_debug("ch = %p; ch->sess = %p; release_done = %p\n", ch, ch->sess,
ch->release_done);
sdev = ch->sport->sdev;
BUG_ON(!sdev);
se_sess = ch->sess;
BUG_ON(!se_sess);
target_wait_for_sess_cmds(se_sess);
transport_deregister_session_configfs(se_sess);
transport_deregister_session(se_sess);
ch->sess = NULL;
ib_destroy_cm_id(ch->cm_id);
srpt_destroy_ch_ib(ch);
srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
ch->sport->sdev, ch->rq_size,
ch->rsp_size, DMA_TO_DEVICE);
spin_lock_irq(&sdev->spinlock);
list_del(&ch->list);
spin_unlock_irq(&sdev->spinlock);
if (ch->release_done)
complete(ch->release_done);
wake_up(&sdev->ch_releaseQ);
kfree(ch);
}
/**
* srpt_cm_req_recv() - Process the event IB_CM_REQ_RECEIVED.
*
* Ownership of the cm_id is transferred to the target session if this
* functions returns zero. Otherwise the caller remains the owner of cm_id.
*/
static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
struct ib_cm_req_event_param *param,
void *private_data)
{
struct srpt_device *sdev = cm_id->context;
struct srpt_port *sport = &sdev->port[param->port - 1];
struct srp_login_req *req;
struct srp_login_rsp *rsp;
struct srp_login_rej *rej;
struct ib_cm_rep_param *rep_param;
struct srpt_rdma_ch *ch, *tmp_ch;
struct se_node_acl *se_acl;
u32 it_iu_len;
int i, ret = 0;
unsigned char *p;
WARN_ON_ONCE(irqs_disabled());
if (WARN_ON(!sdev || !private_data))
return -EINVAL;
req = (struct srp_login_req *)private_data;
it_iu_len = be32_to_cpu(req->req_it_iu_len);
pr_info("Received SRP_LOGIN_REQ with i_port_id 0x%llx:0x%llx,"
" t_port_id 0x%llx:0x%llx and it_iu_len %d on port %d"
" (guid=0x%llx:0x%llx)\n",
be64_to_cpu(*(__be64 *)&req->initiator_port_id[0]),
be64_to_cpu(*(__be64 *)&req->initiator_port_id[8]),
be64_to_cpu(*(__be64 *)&req->target_port_id[0]),
be64_to_cpu(*(__be64 *)&req->target_port_id[8]),
it_iu_len,
param->port,
be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[0]),
be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[8]));
rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
rej = kzalloc(sizeof *rej, GFP_KERNEL);
rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
if (!rsp || !rej || !rep_param) {
ret = -ENOMEM;
goto out;
}
if (it_iu_len > srp_max_req_size || it_iu_len < 64) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
ret = -EINVAL;
pr_err("rejected SRP_LOGIN_REQ because its"
" length (%d bytes) is out of range (%d .. %d)\n",
it_iu_len, 64, srp_max_req_size);
goto reject;
}
if (!sport->enabled) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
ret = -EINVAL;
pr_err("rejected SRP_LOGIN_REQ because the target port"
" has not yet been enabled\n");
goto reject;
}
if ((req->req_flags & SRP_MTCH_ACTION) == SRP_MULTICHAN_SINGLE) {
rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
spin_lock_irq(&sdev->spinlock);
list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
&& !memcmp(ch->t_port_id, req->target_port_id, 16)
&& param->port == ch->sport->port
&& param->listen_id == ch->sport->sdev->cm_id
&& ch->cm_id) {
enum rdma_ch_state ch_state;
ch_state = srpt_get_ch_state(ch);
if (ch_state != CH_CONNECTING
&& ch_state != CH_LIVE)
continue;
/* found an existing channel */
pr_debug("Found existing channel %s"
" cm_id= %p state= %d\n",
ch->sess_name, ch->cm_id, ch_state);
__srpt_close_ch(ch);
rsp->rsp_flags =
SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
}
}
spin_unlock_irq(&sdev->spinlock);
} else
rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
if (*(__be64 *)req->target_port_id != cpu_to_be64(srpt_service_guid)
|| *(__be64 *)(req->target_port_id + 8) !=
cpu_to_be64(srpt_service_guid)) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
ret = -ENOMEM;
pr_err("rejected SRP_LOGIN_REQ because it"
" has an invalid target port identifier.\n");
goto reject;
}
ch = kzalloc(sizeof *ch, GFP_KERNEL);
if (!ch) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_err("rejected SRP_LOGIN_REQ because no memory.\n");
ret = -ENOMEM;
goto reject;
}
INIT_WORK(&ch->release_work, srpt_release_channel_work);
memcpy(ch->i_port_id, req->initiator_port_id, 16);
memcpy(ch->t_port_id, req->target_port_id, 16);
ch->sport = &sdev->port[param->port - 1];
ch->cm_id = cm_id;
/*
* Avoid QUEUE_FULL conditions by limiting the number of buffers used
* for the SRP protocol to the command queue size.
*/
ch->rq_size = SRPT_RQ_SIZE;
spin_lock_init(&ch->spinlock);
ch->state = CH_CONNECTING;
INIT_LIST_HEAD(&ch->cmd_wait_list);
ch->rsp_size = ch->sport->port_attrib.srp_max_rsp_size;
ch->ioctx_ring = (struct srpt_send_ioctx **)
srpt_alloc_ioctx_ring(ch->sport->sdev, ch->rq_size,
sizeof(*ch->ioctx_ring[0]),
ch->rsp_size, DMA_TO_DEVICE);
if (!ch->ioctx_ring)
goto free_ch;
INIT_LIST_HEAD(&ch->free_list);
for (i = 0; i < ch->rq_size; i++) {
ch->ioctx_ring[i]->ch = ch;
list_add_tail(&ch->ioctx_ring[i]->free_list, &ch->free_list);
}
ret = srpt_create_ch_ib(ch);
if (ret) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_err("rejected SRP_LOGIN_REQ because creating"
" a new RDMA channel failed.\n");
goto free_ring;
}
ret = srpt_ch_qp_rtr(ch, ch->qp);
if (ret) {
rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_err("rejected SRP_LOGIN_REQ because enabling"
" RTR failed (error code = %d)\n", ret);
goto destroy_ib;
}
/*
* Use the initator port identifier as the session name, when
* checking against se_node_acl->initiatorname[] this can be
* with or without preceeding '0x'.
*/
snprintf(ch->sess_name, sizeof(ch->sess_name), "0x%016llx%016llx",
be64_to_cpu(*(__be64 *)ch->i_port_id),
be64_to_cpu(*(__be64 *)(ch->i_port_id + 8)));
pr_debug("registering session %s\n", ch->sess_name);
p = &ch->sess_name[0];
ch->sess = transport_init_session(TARGET_PROT_NORMAL);
if (IS_ERR(ch->sess)) {
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
pr_debug("Failed to create session\n");
goto destroy_ib;
}
try_again:
se_acl = core_tpg_get_initiator_node_acl(&sport->port_tpg_1, p);
if (!se_acl) {
pr_info("Rejected login because no ACL has been"
" configured yet for initiator %s.\n", ch->sess_name);
/*
* XXX: Hack to retry of ch->i_port_id without leading '0x'
*/
if (p == &ch->sess_name[0]) {
p += 2;
goto try_again;
}
rej->reason = cpu_to_be32(
SRP_LOGIN_REJ_CHANNEL_LIMIT_REACHED);
transport_free_session(ch->sess);
goto destroy_ib;
}
ch->sess->se_node_acl = se_acl;
transport_register_session(&sport->port_tpg_1, se_acl, ch->sess, ch);
pr_debug("Establish connection sess=%p name=%s cm_id=%p\n", ch->sess,
ch->sess_name, ch->cm_id);
/* create srp_login_response */
rsp->opcode = SRP_LOGIN_RSP;
rsp->tag = req->tag;
rsp->max_it_iu_len = req->req_it_iu_len;
rsp->max_ti_iu_len = req->req_it_iu_len;
ch->max_ti_iu_len = it_iu_len;
rsp->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
| SRP_BUF_FORMAT_INDIRECT);
rsp->req_lim_delta = cpu_to_be32(ch->rq_size);
atomic_set(&ch->req_lim, ch->rq_size);
atomic_set(&ch->req_lim_delta, 0);
/* create cm reply */
rep_param->qp_num = ch->qp->qp_num;
rep_param->private_data = (void *)rsp;
rep_param->private_data_len = sizeof *rsp;
rep_param->rnr_retry_count = 7;
rep_param->flow_control = 1;
rep_param->failover_accepted = 0;
rep_param->srq = 1;
rep_param->responder_resources = 4;
rep_param->initiator_depth = 4;
ret = ib_send_cm_rep(cm_id, rep_param);
if (ret) {
pr_err("sending SRP_LOGIN_REQ response failed"
" (error code = %d)\n", ret);
goto release_channel;
}
spin_lock_irq(&sdev->spinlock);
list_add_tail(&ch->list, &sdev->rch_list);
spin_unlock_irq(&sdev->spinlock);
goto out;
release_channel:
srpt_set_ch_state(ch, CH_RELEASING);
transport_deregister_session_configfs(ch->sess);
transport_deregister_session(ch->sess);
ch->sess = NULL;
destroy_ib:
srpt_destroy_ch_ib(ch);
free_ring:
srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
ch->sport->sdev, ch->rq_size,
ch->rsp_size, DMA_TO_DEVICE);
free_ch:
kfree(ch);
reject:
rej->opcode = SRP_LOGIN_REJ;
rej->tag = req->tag;
rej->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
| SRP_BUF_FORMAT_INDIRECT);
ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
(void *)rej, sizeof *rej);
out:
kfree(rep_param);
kfree(rsp);
kfree(rej);
return ret;
}
static void srpt_cm_rej_recv(struct ib_cm_id *cm_id)
{
pr_info("Received IB REJ for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
/**
* srpt_cm_rtu_recv() - Process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event.
*
* An IB_CM_RTU_RECEIVED message indicates that the connection is established
* and that the recipient may begin transmitting (RTU = ready to use).
*/
static void srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
{
struct srpt_rdma_ch *ch;
int ret;
ch = srpt_find_channel(cm_id->context, cm_id);
BUG_ON(!ch);
if (srpt_test_and_set_ch_state(ch, CH_CONNECTING, CH_LIVE)) {
struct srpt_recv_ioctx *ioctx, *ioctx_tmp;
ret = srpt_ch_qp_rts(ch, ch->qp);
list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
wait_list) {
list_del(&ioctx->wait_list);
srpt_handle_new_iu(ch, ioctx, NULL);
}
if (ret)
srpt_close_ch(ch);
}
}
static void srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
{
pr_info("Received IB TimeWait exit for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
static void srpt_cm_rep_error(struct ib_cm_id *cm_id)
{
pr_info("Received IB REP error for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
/**
* srpt_cm_dreq_recv() - Process reception of a DREQ message.
*/
static void srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
{
struct srpt_rdma_ch *ch;
unsigned long flags;
bool send_drep = false;
ch = srpt_find_channel(cm_id->context, cm_id);
BUG_ON(!ch);
pr_debug("cm_id= %p ch->state= %d\n", cm_id, srpt_get_ch_state(ch));
spin_lock_irqsave(&ch->spinlock, flags);
switch (ch->state) {
case CH_CONNECTING:
case CH_LIVE:
send_drep = true;
ch->state = CH_DISCONNECTING;
break;
case CH_DISCONNECTING:
case CH_DRAINING:
case CH_RELEASING:
WARN(true, "unexpected channel state %d\n", ch->state);
break;
}
spin_unlock_irqrestore(&ch->spinlock, flags);
if (send_drep) {
if (ib_send_cm_drep(ch->cm_id, NULL, 0) < 0)
pr_err("Sending IB DREP failed.\n");
pr_info("Received DREQ and sent DREP for session %s.\n",
ch->sess_name);
}
}
/**
* srpt_cm_drep_recv() - Process reception of a DREP message.
*/
static void srpt_cm_drep_recv(struct ib_cm_id *cm_id)
{
pr_info("Received InfiniBand DREP message for cm_id %p.\n", cm_id);
srpt_drain_channel(cm_id);
}
/**
* srpt_cm_handler() - IB connection manager callback function.
*
* A non-zero return value will cause the caller destroy the CM ID.
*
* Note: srpt_cm_handler() must only return a non-zero value when transferring
* ownership of the cm_id to a channel by srpt_cm_req_recv() failed. Returning
* a non-zero value in any other case will trigger a race with the
* ib_destroy_cm_id() call in srpt_release_channel().
*/
static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
{
int ret;
ret = 0;
switch (event->event) {
case IB_CM_REQ_RECEIVED:
ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
event->private_data);
break;
case IB_CM_REJ_RECEIVED:
srpt_cm_rej_recv(cm_id);
break;
case IB_CM_RTU_RECEIVED:
case IB_CM_USER_ESTABLISHED:
srpt_cm_rtu_recv(cm_id);
break;
case IB_CM_DREQ_RECEIVED:
srpt_cm_dreq_recv(cm_id);
break;
case IB_CM_DREP_RECEIVED:
srpt_cm_drep_recv(cm_id);
break;
case IB_CM_TIMEWAIT_EXIT:
srpt_cm_timewait_exit(cm_id);
break;
case IB_CM_REP_ERROR:
srpt_cm_rep_error(cm_id);
break;
case IB_CM_DREQ_ERROR:
pr_info("Received IB DREQ ERROR event.\n");
break;
case IB_CM_MRA_RECEIVED:
pr_info("Received IB MRA event\n");
break;
default:
pr_err("received unrecognized IB CM event %d\n", event->event);
break;
}
return ret;
}
/**
* srpt_perform_rdmas() - Perform IB RDMA.
*
* Returns zero upon success or a negative number upon failure.
*/
static int srpt_perform_rdmas(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
struct ib_send_wr *bad_wr;
int sq_wr_avail, ret, i;
enum dma_data_direction dir;
const int n_rdma = ioctx->n_rdma;
dir = ioctx->cmd.data_direction;
if (dir == DMA_TO_DEVICE) {
/* write */
ret = -ENOMEM;
sq_wr_avail = atomic_sub_return(n_rdma, &ch->sq_wr_avail);
if (sq_wr_avail < 0) {
pr_warn("IB send queue full (needed %d)\n",
n_rdma);
goto out;
}
}
for (i = 0; i < n_rdma; i++) {
struct ib_send_wr *wr = &ioctx->rdma_wrs[i].wr;
wr->opcode = (dir == DMA_FROM_DEVICE) ?
IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
if (i == n_rdma - 1) {
/* only get completion event for the last rdma read */
if (dir == DMA_TO_DEVICE) {
wr->send_flags = IB_SEND_SIGNALED;
ioctx->rdma_cqe.done = srpt_rdma_read_done;
} else {
ioctx->rdma_cqe.done = srpt_rdma_write_done;
}
wr->wr_cqe = &ioctx->rdma_cqe;
wr->next = NULL;
} else {
wr->wr_cqe = NULL;
wr->next = &ioctx->rdma_wrs[i + 1].wr;
}
}
ret = ib_post_send(ch->qp, &ioctx->rdma_wrs->wr, &bad_wr);
if (ret)
pr_err("%s[%d]: ib_post_send() returned %d for %d/%d\n",
__func__, __LINE__, ret, i, n_rdma);
out:
if (unlikely(dir == DMA_TO_DEVICE && ret < 0))
atomic_add(n_rdma, &ch->sq_wr_avail);
return ret;
}
/**
* srpt_xfer_data() - Start data transfer from initiator to target.
*/
static int srpt_xfer_data(struct srpt_rdma_ch *ch,
struct srpt_send_ioctx *ioctx)
{
int ret;
ret = srpt_map_sg_to_ib_sge(ch, ioctx);
if (ret) {
pr_err("%s[%d] ret=%d\n", __func__, __LINE__, ret);
goto out;
}
ret = srpt_perform_rdmas(ch, ioctx);
if (ret) {
if (ret == -EAGAIN || ret == -ENOMEM)
pr_info("%s[%d] queue full -- ret=%d\n",
__func__, __LINE__, ret);
else
pr_err("%s[%d] fatal error -- ret=%d\n",
__func__, __LINE__, ret);
goto out_unmap;
}
out:
return ret;
out_unmap:
srpt_unmap_sg_to_ib_sge(ch, ioctx);
goto out;
}
static int srpt_write_pending_status(struct se_cmd *se_cmd)
{
struct srpt_send_ioctx *ioctx;
ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
return srpt_get_cmd_state(ioctx) == SRPT_STATE_NEED_DATA;
}
/*
* srpt_write_pending() - Start data transfer from initiator to target (write).
*/
static int srpt_write_pending(struct se_cmd *se_cmd)
{
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *ioctx;
enum srpt_command_state new_state;
enum rdma_ch_state ch_state;
int ret;
ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
new_state = srpt_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA);
WARN_ON(new_state == SRPT_STATE_DONE);
ch = ioctx->ch;
BUG_ON(!ch);
ch_state = srpt_get_ch_state(ch);
switch (ch_state) {
case CH_CONNECTING:
WARN(true, "unexpected channel state %d\n", ch_state);
ret = -EINVAL;
goto out;
case CH_LIVE:
break;
case CH_DISCONNECTING:
case CH_DRAINING:
case CH_RELEASING:
pr_debug("cmd with tag %lld: channel disconnecting\n",
ioctx->cmd.tag);
srpt_set_cmd_state(ioctx, SRPT_STATE_DATA_IN);
ret = -EINVAL;
goto out;
}
ret = srpt_xfer_data(ch, ioctx);
out:
return ret;
}
static u8 tcm_to_srp_tsk_mgmt_status(const int tcm_mgmt_status)
{
switch (tcm_mgmt_status) {
case TMR_FUNCTION_COMPLETE:
return SRP_TSK_MGMT_SUCCESS;
case TMR_FUNCTION_REJECTED:
return SRP_TSK_MGMT_FUNC_NOT_SUPP;
}
return SRP_TSK_MGMT_FAILED;
}
/**
* srpt_queue_response() - Transmits the response to a SCSI command.
*
* Callback function called by the TCM core. Must not block since it can be
* invoked on the context of the IB completion handler.
*/
static void srpt_queue_response(struct se_cmd *cmd)
{
struct srpt_rdma_ch *ch;
struct srpt_send_ioctx *ioctx;
enum srpt_command_state state;
unsigned long flags;
int ret;
enum dma_data_direction dir;
int resp_len;
u8 srp_tm_status;
ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
ch = ioctx->ch;
BUG_ON(!ch);
spin_lock_irqsave(&ioctx->spinlock, flags);
state = ioctx->state;
switch (state) {
case SRPT_STATE_NEW:
case SRPT_STATE_DATA_IN:
ioctx->state = SRPT_STATE_CMD_RSP_SENT;
break;
case SRPT_STATE_MGMT:
ioctx->state = SRPT_STATE_MGMT_RSP_SENT;
break;
default:
WARN(true, "ch %p; cmd %d: unexpected command state %d\n",
ch, ioctx->ioctx.index, ioctx->state);
break;
}
spin_unlock_irqrestore(&ioctx->spinlock, flags);
if (unlikely(transport_check_aborted_status(&ioctx->cmd, false)
|| WARN_ON_ONCE(state == SRPT_STATE_CMD_RSP_SENT))) {
atomic_inc(&ch->req_lim_delta);
srpt_abort_cmd(ioctx);
return;
}
dir = ioctx->cmd.data_direction;
/* For read commands, transfer the data to the initiator. */
if (dir == DMA_FROM_DEVICE && ioctx->cmd.data_length &&
!ioctx->queue_status_only) {
ret = srpt_xfer_data(ch, ioctx);
if (ret) {
pr_err("xfer_data failed for tag %llu\n",
ioctx->cmd.tag);
return;
}
}
if (state != SRPT_STATE_MGMT)
resp_len = srpt_build_cmd_rsp(ch, ioctx, ioctx->cmd.tag,
cmd->scsi_status);
else {
srp_tm_status
= tcm_to_srp_tsk_mgmt_status(cmd->se_tmr_req->response);
resp_len = srpt_build_tskmgmt_rsp(ch, ioctx, srp_tm_status,
ioctx->cmd.tag);
}
ret = srpt_post_send(ch, ioctx, resp_len);
if (ret) {
pr_err("sending cmd response failed for tag %llu\n",
ioctx->cmd.tag);
srpt_unmap_sg_to_ib_sge(ch, ioctx);
srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
target_put_sess_cmd(&ioctx->cmd);
}
}
static int srpt_queue_data_in(struct se_cmd *cmd)
{
srpt_queue_response(cmd);
return 0;
}
static void srpt_queue_tm_rsp(struct se_cmd *cmd)
{
srpt_queue_response(cmd);
}
static void srpt_aborted_task(struct se_cmd *cmd)
{
struct srpt_send_ioctx *ioctx = container_of(cmd,
struct srpt_send_ioctx, cmd);
srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
}
static int srpt_queue_status(struct se_cmd *cmd)
{
struct srpt_send_ioctx *ioctx;
ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
BUG_ON(ioctx->sense_data != cmd->sense_buffer);
if (cmd->se_cmd_flags &
(SCF_TRANSPORT_TASK_SENSE | SCF_EMULATED_TASK_SENSE))
WARN_ON(cmd->scsi_status != SAM_STAT_CHECK_CONDITION);
ioctx->queue_status_only = true;
srpt_queue_response(cmd);
return 0;
}
static void srpt_refresh_port_work(struct work_struct *work)
{
struct srpt_port *sport = container_of(work, struct srpt_port, work);
srpt_refresh_port(sport);
}
static int srpt_ch_list_empty(struct srpt_device *sdev)
{
int res;
spin_lock_irq(&sdev->spinlock);
res = list_empty(&sdev->rch_list);
spin_unlock_irq(&sdev->spinlock);
return res;
}
/**
* srpt_release_sdev() - Free the channel resources associated with a target.
*/
static int srpt_release_sdev(struct srpt_device *sdev)
{
struct srpt_rdma_ch *ch, *tmp_ch;
int res;
WARN_ON_ONCE(irqs_disabled());
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
__srpt_close_ch(ch);
spin_unlock_irq(&sdev->spinlock);
res = wait_event_interruptible(sdev->ch_releaseQ,
srpt_ch_list_empty(sdev));
if (res)
pr_err("%s: interrupted.\n", __func__);
return 0;
}
static struct srpt_port *__srpt_lookup_port(const char *name)
{
struct ib_device *dev;
struct srpt_device *sdev;
struct srpt_port *sport;
int i;
list_for_each_entry(sdev, &srpt_dev_list, list) {
dev = sdev->device;
if (!dev)
continue;
for (i = 0; i < dev->phys_port_cnt; i++) {
sport = &sdev->port[i];
if (!strcmp(sport->port_guid, name))
return sport;
}
}
return NULL;
}
static struct srpt_port *srpt_lookup_port(const char *name)
{
struct srpt_port *sport;
spin_lock(&srpt_dev_lock);
sport = __srpt_lookup_port(name);
spin_unlock(&srpt_dev_lock);
return sport;
}
/**
* srpt_add_one() - Infiniband device addition callback function.
*/
static void srpt_add_one(struct ib_device *device)
{
struct srpt_device *sdev;
struct srpt_port *sport;
struct ib_srq_init_attr srq_attr;
int i;
pr_debug("device = %p, device->dma_ops = %p\n", device,
device->dma_ops);
sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
if (!sdev)
goto err;
sdev->device = device;
INIT_LIST_HEAD(&sdev->rch_list);
init_waitqueue_head(&sdev->ch_releaseQ);
spin_lock_init(&sdev->spinlock);
sdev->pd = ib_alloc_pd(device);
if (IS_ERR(sdev->pd))
goto free_dev;
sdev->srq_size = min(srpt_srq_size, sdev->device->attrs.max_srq_wr);
srq_attr.event_handler = srpt_srq_event;
srq_attr.srq_context = (void *)sdev;
srq_attr.attr.max_wr = sdev->srq_size;
srq_attr.attr.max_sge = 1;
srq_attr.attr.srq_limit = 0;
srq_attr.srq_type = IB_SRQT_BASIC;
sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
if (IS_ERR(sdev->srq))
goto err_pd;
pr_debug("%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
__func__, sdev->srq_size, sdev->device->attrs.max_srq_wr,
device->name);
if (!srpt_service_guid)
srpt_service_guid = be64_to_cpu(device->node_guid);
sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
if (IS_ERR(sdev->cm_id))
goto err_srq;
/* print out target login information */
pr_debug("Target login info: id_ext=%016llx,ioc_guid=%016llx,"
"pkey=ffff,service_id=%016llx\n", srpt_service_guid,
srpt_service_guid, srpt_service_guid);
/*
* We do not have a consistent service_id (ie. also id_ext of target_id)
* to identify this target. We currently use the guid of the first HCA
* in the system as service_id; therefore, the target_id will change
* if this HCA is gone bad and replaced by different HCA
*/
if (ib_cm_listen(sdev->cm_id, cpu_to_be64(srpt_service_guid), 0))
goto err_cm;
INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
srpt_event_handler);
if (ib_register_event_handler(&sdev->event_handler))
goto err_cm;
sdev->ioctx_ring = (struct srpt_recv_ioctx **)
srpt_alloc_ioctx_ring(sdev, sdev->srq_size,
sizeof(*sdev->ioctx_ring[0]),
srp_max_req_size, DMA_FROM_DEVICE);
if (!sdev->ioctx_ring)
goto err_event;
for (i = 0; i < sdev->srq_size; ++i)
srpt_post_recv(sdev, sdev->ioctx_ring[i]);
WARN_ON(sdev->device->phys_port_cnt > ARRAY_SIZE(sdev->port));
for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
sport = &sdev->port[i - 1];
sport->sdev = sdev;
sport->port = i;
sport->port_attrib.srp_max_rdma_size = DEFAULT_MAX_RDMA_SIZE;
sport->port_attrib.srp_max_rsp_size = DEFAULT_MAX_RSP_SIZE;
sport->port_attrib.srp_sq_size = DEF_SRPT_SQ_SIZE;
INIT_WORK(&sport->work, srpt_refresh_port_work);
if (srpt_refresh_port(sport)) {
pr_err("MAD registration failed for %s-%d.\n",
srpt_sdev_name(sdev), i);
goto err_ring;
}
snprintf(sport->port_guid, sizeof(sport->port_guid),
"0x%016llx%016llx",
be64_to_cpu(sport->gid.global.subnet_prefix),
be64_to_cpu(sport->gid.global.interface_id));
}
spin_lock(&srpt_dev_lock);
list_add_tail(&sdev->list, &srpt_dev_list);
spin_unlock(&srpt_dev_lock);
out:
ib_set_client_data(device, &srpt_client, sdev);
pr_debug("added %s.\n", device->name);
return;
err_ring:
srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
sdev->srq_size, srp_max_req_size,
DMA_FROM_DEVICE);
err_event:
ib_unregister_event_handler(&sdev->event_handler);
err_cm:
ib_destroy_cm_id(sdev->cm_id);
err_srq:
ib_destroy_srq(sdev->srq);
err_pd:
ib_dealloc_pd(sdev->pd);
free_dev:
kfree(sdev);
err:
sdev = NULL;
pr_info("%s(%s) failed.\n", __func__, device->name);
goto out;
}
/**
* srpt_remove_one() - InfiniBand device removal callback function.
*/
static void srpt_remove_one(struct ib_device *device, void *client_data)
{
struct srpt_device *sdev = client_data;
int i;
if (!sdev) {
pr_info("%s(%s): nothing to do.\n", __func__, device->name);
return;
}
srpt_unregister_mad_agent(sdev);
ib_unregister_event_handler(&sdev->event_handler);
/* Cancel any work queued by the just unregistered IB event handler. */
for (i = 0; i < sdev->device->phys_port_cnt; i++)
cancel_work_sync(&sdev->port[i].work);
ib_destroy_cm_id(sdev->cm_id);
/*
* Unregistering a target must happen after destroying sdev->cm_id
* such that no new SRP_LOGIN_REQ information units can arrive while
* destroying the target.
*/
spin_lock(&srpt_dev_lock);
list_del(&sdev->list);
spin_unlock(&srpt_dev_lock);
srpt_release_sdev(sdev);
ib_destroy_srq(sdev->srq);
ib_dealloc_pd(sdev->pd);
srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
sdev->srq_size, srp_max_req_size, DMA_FROM_DEVICE);
sdev->ioctx_ring = NULL;
kfree(sdev);
}
static struct ib_client srpt_client = {
.name = DRV_NAME,
.add = srpt_add_one,
.remove = srpt_remove_one
};
static int srpt_check_true(struct se_portal_group *se_tpg)
{
return 1;
}
static int srpt_check_false(struct se_portal_group *se_tpg)
{
return 0;
}
static char *srpt_get_fabric_name(void)
{
return "srpt";
}
static char *srpt_get_fabric_wwn(struct se_portal_group *tpg)
{
struct srpt_port *sport = container_of(tpg, struct srpt_port, port_tpg_1);
return sport->port_guid;
}
static u16 srpt_get_tag(struct se_portal_group *tpg)
{
return 1;
}
static u32 srpt_tpg_get_inst_index(struct se_portal_group *se_tpg)
{
return 1;
}
static void srpt_release_cmd(struct se_cmd *se_cmd)
{
struct srpt_send_ioctx *ioctx = container_of(se_cmd,
struct srpt_send_ioctx, cmd);
struct srpt_rdma_ch *ch = ioctx->ch;
unsigned long flags;
WARN_ON(ioctx->state != SRPT_STATE_DONE);
WARN_ON(ioctx->mapped_sg_count != 0);
if (ioctx->n_rbuf > 1) {
kfree(ioctx->rbufs);
ioctx->rbufs = NULL;
ioctx->n_rbuf = 0;
}
spin_lock_irqsave(&ch->spinlock, flags);
list_add(&ioctx->free_list, &ch->free_list);
spin_unlock_irqrestore(&ch->spinlock, flags);
}
/**
* srpt_close_session() - Forcibly close a session.
*
* Callback function invoked by the TCM core to clean up sessions associated
* with a node ACL when the user invokes
* rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
*/
static void srpt_close_session(struct se_session *se_sess)
{
DECLARE_COMPLETION_ONSTACK(release_done);
struct srpt_rdma_ch *ch;
struct srpt_device *sdev;
unsigned long res;
ch = se_sess->fabric_sess_ptr;
WARN_ON(ch->sess != se_sess);
pr_debug("ch %p state %d\n", ch, srpt_get_ch_state(ch));
sdev = ch->sport->sdev;
spin_lock_irq(&sdev->spinlock);
BUG_ON(ch->release_done);
ch->release_done = &release_done;
__srpt_close_ch(ch);
spin_unlock_irq(&sdev->spinlock);
res = wait_for_completion_timeout(&release_done, 60 * HZ);
WARN_ON(res == 0);
}
/**
* srpt_sess_get_index() - Return the value of scsiAttIntrPortIndex (SCSI-MIB).
*
* A quote from RFC 4455 (SCSI-MIB) about this MIB object:
* This object represents an arbitrary integer used to uniquely identify a
* particular attached remote initiator port to a particular SCSI target port
* within a particular SCSI target device within a particular SCSI instance.
*/
static u32 srpt_sess_get_index(struct se_session *se_sess)
{
return 0;
}
static void srpt_set_default_node_attrs(struct se_node_acl *nacl)
{
}
/* Note: only used from inside debug printk's by the TCM core. */
static int srpt_get_tcm_cmd_state(struct se_cmd *se_cmd)
{
struct srpt_send_ioctx *ioctx;
ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
return srpt_get_cmd_state(ioctx);
}
/**
* srpt_parse_i_port_id() - Parse an initiator port ID.
* @name: ASCII representation of a 128-bit initiator port ID.
* @i_port_id: Binary 128-bit port ID.
*/
static int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
{
const char *p;
unsigned len, count, leading_zero_bytes;
int ret, rc;
p = name;
if (strncasecmp(p, "0x", 2) == 0)
p += 2;
ret = -EINVAL;
len = strlen(p);
if (len % 2)
goto out;
count = min(len / 2, 16U);
leading_zero_bytes = 16 - count;
memset(i_port_id, 0, leading_zero_bytes);
rc = hex2bin(i_port_id + leading_zero_bytes, p, count);
if (rc < 0)
pr_debug("hex2bin failed for srpt_parse_i_port_id: %d\n", rc);
ret = 0;
out:
return ret;
}
/*
* configfs callback function invoked for
* mkdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
*/
static int srpt_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
{
u8 i_port_id[16];
if (srpt_parse_i_port_id(i_port_id, name) < 0) {
pr_err("invalid initiator port ID %s\n", name);
return -EINVAL;
}
return 0;
}
static ssize_t srpt_tpg_attrib_srp_max_rdma_size_show(struct config_item *item,
char *page)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return sprintf(page, "%u\n", sport->port_attrib.srp_max_rdma_size);
}
static ssize_t srpt_tpg_attrib_srp_max_rdma_size_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long val;
int ret;
ret = kstrtoul(page, 0, &val);
if (ret < 0) {
pr_err("kstrtoul() failed with ret: %d\n", ret);
return -EINVAL;
}
if (val > MAX_SRPT_RDMA_SIZE) {
pr_err("val: %lu exceeds MAX_SRPT_RDMA_SIZE: %d\n", val,
MAX_SRPT_RDMA_SIZE);
return -EINVAL;
}
if (val < DEFAULT_MAX_RDMA_SIZE) {
pr_err("val: %lu smaller than DEFAULT_MAX_RDMA_SIZE: %d\n",
val, DEFAULT_MAX_RDMA_SIZE);
return -EINVAL;
}
sport->port_attrib.srp_max_rdma_size = val;
return count;
}
static ssize_t srpt_tpg_attrib_srp_max_rsp_size_show(struct config_item *item,
char *page)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return sprintf(page, "%u\n", sport->port_attrib.srp_max_rsp_size);
}
static ssize_t srpt_tpg_attrib_srp_max_rsp_size_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long val;
int ret;
ret = kstrtoul(page, 0, &val);
if (ret < 0) {
pr_err("kstrtoul() failed with ret: %d\n", ret);
return -EINVAL;
}
if (val > MAX_SRPT_RSP_SIZE) {
pr_err("val: %lu exceeds MAX_SRPT_RSP_SIZE: %d\n", val,
MAX_SRPT_RSP_SIZE);
return -EINVAL;
}
if (val < MIN_MAX_RSP_SIZE) {
pr_err("val: %lu smaller than MIN_MAX_RSP_SIZE: %d\n", val,
MIN_MAX_RSP_SIZE);
return -EINVAL;
}
sport->port_attrib.srp_max_rsp_size = val;
return count;
}
static ssize_t srpt_tpg_attrib_srp_sq_size_show(struct config_item *item,
char *page)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return sprintf(page, "%u\n", sport->port_attrib.srp_sq_size);
}
static ssize_t srpt_tpg_attrib_srp_sq_size_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = attrib_to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long val;
int ret;
ret = kstrtoul(page, 0, &val);
if (ret < 0) {
pr_err("kstrtoul() failed with ret: %d\n", ret);
return -EINVAL;
}
if (val > MAX_SRPT_SRQ_SIZE) {
pr_err("val: %lu exceeds MAX_SRPT_SRQ_SIZE: %d\n", val,
MAX_SRPT_SRQ_SIZE);
return -EINVAL;
}
if (val < MIN_SRPT_SRQ_SIZE) {
pr_err("val: %lu smaller than MIN_SRPT_SRQ_SIZE: %d\n", val,
MIN_SRPT_SRQ_SIZE);
return -EINVAL;
}
sport->port_attrib.srp_sq_size = val;
return count;
}
CONFIGFS_ATTR(srpt_tpg_attrib_, srp_max_rdma_size);
CONFIGFS_ATTR(srpt_tpg_attrib_, srp_max_rsp_size);
CONFIGFS_ATTR(srpt_tpg_attrib_, srp_sq_size);
static struct configfs_attribute *srpt_tpg_attrib_attrs[] = {
&srpt_tpg_attrib_attr_srp_max_rdma_size,
&srpt_tpg_attrib_attr_srp_max_rsp_size,
&srpt_tpg_attrib_attr_srp_sq_size,
NULL,
};
static ssize_t srpt_tpg_enable_show(struct config_item *item, char *page)
{
struct se_portal_group *se_tpg = to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
return snprintf(page, PAGE_SIZE, "%d\n", (sport->enabled) ? 1: 0);
}
static ssize_t srpt_tpg_enable_store(struct config_item *item,
const char *page, size_t count)
{
struct se_portal_group *se_tpg = to_tpg(item);
struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
unsigned long tmp;
int ret;
ret = kstrtoul(page, 0, &tmp);
if (ret < 0) {
pr_err("Unable to extract srpt_tpg_store_enable\n");
return -EINVAL;
}
if ((tmp != 0) && (tmp != 1)) {
pr_err("Illegal value for srpt_tpg_store_enable: %lu\n", tmp);
return -EINVAL;
}
if (tmp == 1)
sport->enabled = true;
else
sport->enabled = false;
return count;
}
CONFIGFS_ATTR(srpt_tpg_, enable);
static struct configfs_attribute *srpt_tpg_attrs[] = {
&srpt_tpg_attr_enable,
NULL,
};
/**
* configfs callback invoked for
* mkdir /sys/kernel/config/target/$driver/$port/$tpg
*/
static struct se_portal_group *srpt_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
int res;
/* Initialize sport->port_wwn and sport->port_tpg_1 */
res = core_tpg_register(&sport->port_wwn, &sport->port_tpg_1, SCSI_PROTOCOL_SRP);
if (res)
return ERR_PTR(res);
return &sport->port_tpg_1;
}
/**
* configfs callback invoked for
* rmdir /sys/kernel/config/target/$driver/$port/$tpg
*/
static void srpt_drop_tpg(struct se_portal_group *tpg)
{
struct srpt_port *sport = container_of(tpg,
struct srpt_port, port_tpg_1);
sport->enabled = false;
core_tpg_deregister(&sport->port_tpg_1);
}
/**
* configfs callback invoked for
* mkdir /sys/kernel/config/target/$driver/$port
*/
static struct se_wwn *srpt_make_tport(struct target_fabric_configfs *tf,
struct config_group *group,
const char *name)
{
struct srpt_port *sport;
int ret;
sport = srpt_lookup_port(name);
pr_debug("make_tport(%s)\n", name);
ret = -EINVAL;
if (!sport)
goto err;
return &sport->port_wwn;
err:
return ERR_PTR(ret);
}
/**
* configfs callback invoked for
* rmdir /sys/kernel/config/target/$driver/$port
*/
static void srpt_drop_tport(struct se_wwn *wwn)
{
struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
pr_debug("drop_tport(%s\n", config_item_name(&sport->port_wwn.wwn_group.cg_item));
}
static ssize_t srpt_wwn_version_show(struct config_item *item, char *buf)
{
return scnprintf(buf, PAGE_SIZE, "%s\n", DRV_VERSION);
}
CONFIGFS_ATTR_RO(srpt_wwn_, version);
static struct configfs_attribute *srpt_wwn_attrs[] = {
&srpt_wwn_attr_version,
NULL,
};
static const struct target_core_fabric_ops srpt_template = {
.module = THIS_MODULE,
.name = "srpt",
.node_acl_size = sizeof(struct srpt_node_acl),
.get_fabric_name = srpt_get_fabric_name,
.tpg_get_wwn = srpt_get_fabric_wwn,
.tpg_get_tag = srpt_get_tag,
.tpg_check_demo_mode = srpt_check_false,
.tpg_check_demo_mode_cache = srpt_check_true,
.tpg_check_demo_mode_write_protect = srpt_check_true,
.tpg_check_prod_mode_write_protect = srpt_check_false,
.tpg_get_inst_index = srpt_tpg_get_inst_index,
.release_cmd = srpt_release_cmd,
.check_stop_free = srpt_check_stop_free,
.shutdown_session = srpt_shutdown_session,
.close_session = srpt_close_session,
.sess_get_index = srpt_sess_get_index,
.sess_get_initiator_sid = NULL,
.write_pending = srpt_write_pending,
.write_pending_status = srpt_write_pending_status,
.set_default_node_attributes = srpt_set_default_node_attrs,
.get_cmd_state = srpt_get_tcm_cmd_state,
.queue_data_in = srpt_queue_data_in,
.queue_status = srpt_queue_status,
.queue_tm_rsp = srpt_queue_tm_rsp,
.aborted_task = srpt_aborted_task,
/*
* Setup function pointers for generic logic in
* target_core_fabric_configfs.c
*/
.fabric_make_wwn = srpt_make_tport,
.fabric_drop_wwn = srpt_drop_tport,
.fabric_make_tpg = srpt_make_tpg,
.fabric_drop_tpg = srpt_drop_tpg,
.fabric_init_nodeacl = srpt_init_nodeacl,
.tfc_wwn_attrs = srpt_wwn_attrs,
.tfc_tpg_base_attrs = srpt_tpg_attrs,
.tfc_tpg_attrib_attrs = srpt_tpg_attrib_attrs,
};
/**
* srpt_init_module() - Kernel module initialization.
*
* Note: Since ib_register_client() registers callback functions, and since at
* least one of these callback functions (srpt_add_one()) calls target core
* functions, this driver must be registered with the target core before
* ib_register_client() is called.
*/
static int __init srpt_init_module(void)
{
int ret;
ret = -EINVAL;
if (srp_max_req_size < MIN_MAX_REQ_SIZE) {
pr_err("invalid value %d for kernel module parameter"
" srp_max_req_size -- must be at least %d.\n",
srp_max_req_size, MIN_MAX_REQ_SIZE);
goto out;
}
if (srpt_srq_size < MIN_SRPT_SRQ_SIZE
|| srpt_srq_size > MAX_SRPT_SRQ_SIZE) {
pr_err("invalid value %d for kernel module parameter"
" srpt_srq_size -- must be in the range [%d..%d].\n",
srpt_srq_size, MIN_SRPT_SRQ_SIZE, MAX_SRPT_SRQ_SIZE);
goto out;
}
ret = target_register_template(&srpt_template);
if (ret)
goto out;
ret = ib_register_client(&srpt_client);
if (ret) {
pr_err("couldn't register IB client\n");
goto out_unregister_target;
}
return 0;
out_unregister_target:
target_unregister_template(&srpt_template);
out:
return ret;
}
static void __exit srpt_cleanup_module(void)
{
ib_unregister_client(&srpt_client);
target_unregister_template(&srpt_template);
}
module_init(srpt_init_module);
module_exit(srpt_cleanup_module);
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_5209_0 |
crossvul-cpp_data_bad_3198_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X X CCCC FFFFF %
% X X C F %
% X C FFF %
% X X C F %
% X X CCCC F %
% %
% %
% Read GIMP XCF Image Format %
% %
% Software Design %
% Leonard Rosenthol %
% November 2001 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/composite.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Typedef declarations.
*/
typedef enum
{
GIMP_RGB,
GIMP_GRAY,
GIMP_INDEXED
} GimpImageBaseType;
typedef enum
{
PROP_END = 0,
PROP_COLORMAP = 1,
PROP_ACTIVE_LAYER = 2,
PROP_ACTIVE_CHANNEL = 3,
PROP_SELECTION = 4,
PROP_FLOATING_SELECTION = 5,
PROP_OPACITY = 6,
PROP_MODE = 7,
PROP_VISIBLE = 8,
PROP_LINKED = 9,
PROP_PRESERVE_TRANSPARENCY = 10,
PROP_APPLY_MASK = 11,
PROP_EDIT_MASK = 12,
PROP_SHOW_MASK = 13,
PROP_SHOW_MASKED = 14,
PROP_OFFSETS = 15,
PROP_COLOR = 16,
PROP_COMPRESSION = 17,
PROP_GUIDES = 18,
PROP_RESOLUTION = 19,
PROP_TATTOO = 20,
PROP_PARASITES = 21,
PROP_UNIT = 22,
PROP_PATHS = 23,
PROP_USER_UNIT = 24
} PropType;
typedef enum
{
COMPRESS_NONE = 0,
COMPRESS_RLE = 1,
COMPRESS_ZLIB = 2, /* unused */
COMPRESS_FRACTAL = 3 /* unused */
} XcfCompressionType;
typedef struct
{
size_t
width,
height,
image_type,
bytes_per_pixel;
int
compression;
size_t
file_size;
size_t
number_layers;
ExceptionInfo
*exception;
} XCFDocInfo;
typedef struct
{
char
name[1024];
unsigned int
active;
size_t
width,
height,
type,
alpha,
visible,
linked,
preserve_trans,
apply_mask,
show_mask,
edit_mask,
floating_offset;
ssize_t
offset_x,
offset_y;
size_t
mode,
tattoo;
Image
*image;
} XCFLayerInfo;
#define TILE_WIDTH 64
#define TILE_HEIGHT 64
typedef struct
{
unsigned char
red,
green,
blue,
alpha;
} XCFPixelPacket;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s X C F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsXCF() returns MagickTrue if the image format type, identified by the
% magick string, is XCF (GIMP native format).
%
% The format of the IsXCF method is:
%
% MagickBooleanType IsXCF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsXCF(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"gimp xcf",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
typedef enum
{
GIMP_NORMAL_MODE,
GIMP_DISSOLVE_MODE,
GIMP_BEHIND_MODE,
GIMP_MULTIPLY_MODE,
GIMP_SCREEN_MODE,
GIMP_OVERLAY_MODE,
GIMP_DIFFERENCE_MODE,
GIMP_ADDITION_MODE,
GIMP_SUBTRACT_MODE,
GIMP_DARKEN_ONLY_MODE,
GIMP_LIGHTEN_ONLY_MODE,
GIMP_HUE_MODE,
GIMP_SATURATION_MODE,
GIMP_COLOR_MODE,
GIMP_VALUE_MODE,
GIMP_DIVIDE_MODE,
GIMP_DODGE_MODE,
GIMP_BURN_MODE,
GIMP_HARDLIGHT_MODE
} GimpLayerModeEffects;
/*
Simple utility routine to convert between PSD blending modes and
ImageMagick compositing operators
*/
static CompositeOperator GIMPBlendModeToCompositeOperator(
size_t blendMode)
{
switch ( blendMode )
{
case GIMP_NORMAL_MODE: return(OverCompositeOp);
case GIMP_DISSOLVE_MODE: return(DissolveCompositeOp);
case GIMP_MULTIPLY_MODE: return(MultiplyCompositeOp);
case GIMP_SCREEN_MODE: return(ScreenCompositeOp);
case GIMP_OVERLAY_MODE: return(OverlayCompositeOp);
case GIMP_DIFFERENCE_MODE: return(DifferenceCompositeOp);
case GIMP_ADDITION_MODE: return(AddCompositeOp);
case GIMP_SUBTRACT_MODE: return(SubtractCompositeOp);
case GIMP_DARKEN_ONLY_MODE: return(DarkenCompositeOp);
case GIMP_LIGHTEN_ONLY_MODE: return(LightenCompositeOp);
case GIMP_HUE_MODE: return(HueCompositeOp);
case GIMP_SATURATION_MODE: return(SaturateCompositeOp);
case GIMP_COLOR_MODE: return(ColorizeCompositeOp);
case GIMP_DODGE_MODE: return(ColorDodgeCompositeOp);
case GIMP_BURN_MODE: return(ColorBurnCompositeOp);
case GIMP_HARDLIGHT_MODE: return(HardLightCompositeOp);
case GIMP_DIVIDE_MODE: return(DivideCompositeOp);
/* these are the ones we don't support...yet */
case GIMP_BEHIND_MODE: return(OverCompositeOp);
case GIMP_VALUE_MODE: return(OverCompositeOp);
default: return(OverCompositeOp);
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d B l o b S t r i n g W i t h L o n g S i z e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadBlobStringWithLongSize reads characters from a blob or file
% starting with a ssize_t length byte and then characters to that length
%
% The format of the ReadBlobStringWithLongSize method is:
%
% char *ReadBlobStringWithLongSize(Image *image,char *string)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o string: the address of a character buffer.
%
*/
static char *ReadBlobStringWithLongSize(Image *image,char *string,size_t max)
{
int
c;
MagickOffsetType
offset;
register ssize_t
i;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
assert(max != 0);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=ReadBlobMSBLong(image);
for (i=0; i < (ssize_t) MagickMin(length,max-1); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
return((char *) NULL);
string[i]=(char) c;
}
string[i]='\0';
offset=SeekBlob(image,(MagickOffsetType) (length-i),SEEK_CUR);
if (offset < 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"ImproperImageHeader","`%s'",image->filename);
return(string);
}
static MagickBooleanType load_tile(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length)
{
ExceptionInfo
*exception;
ssize_t
y;
register ssize_t
x;
register PixelPacket
*q;
size_t
extent;
ssize_t
count;
unsigned char
*graydata;
XCFPixelPacket
*xcfdata,
*xcfodata;
extent=0;
if (inDocInfo->image_type == GIMP_GRAY)
extent=tile_image->columns*tile_image->rows*sizeof(*graydata);
else
if (inDocInfo->image_type == GIMP_RGB)
extent=tile_image->columns*tile_image->rows*sizeof(*xcfdata);
if (extent > data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
xcfdata=(XCFPixelPacket *) AcquireQuantumMemory(MagickMax(data_length,
tile_image->columns*tile_image->rows),sizeof(*xcfdata));
if (xcfdata == (XCFPixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
graydata=(unsigned char *) xcfdata; /* used by gray and indexed */
count=ReadBlob(image,data_length,(unsigned char *) xcfdata);
if (count != (ssize_t) data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
exception=(&image->exception);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (inDocInfo->image_type == GIMP_GRAY)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*graydata));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
inLayerInfo->alpha));
graydata++;
q++;
}
}
else
if (inDocInfo->image_type == GIMP_RGB)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(xcfdata->red));
SetPixelGreen(q,ScaleCharToQuantum(xcfdata->green));
SetPixelBlue(q,ScaleCharToQuantum(xcfdata->blue));
SetPixelAlpha(q,xcfdata->alpha == 255U ? TransparentOpacity :
ScaleCharToQuantum((unsigned char) inLayerInfo->alpha));
xcfdata++;
q++;
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(XCFPixelPacket *) RelinquishMagickMemory(xcfodata);
return MagickTrue;
}
static MagickBooleanType load_tile_rle(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length)
{
ExceptionInfo
*exception;
MagickOffsetType
size;
Quantum
alpha;
register PixelPacket
*q;
size_t
length;
ssize_t
bytes_per_pixel,
count,
i,
j;
unsigned char
data,
pixel,
*xcfdata,
*xcfodata,
*xcfdatalimit;
bytes_per_pixel=(ssize_t) inDocInfo->bytes_per_pixel;
xcfdata=(unsigned char *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));
if (xcfdata == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
count=ReadBlob(image, (size_t) data_length, xcfdata);
xcfdatalimit = xcfodata+count-1;
exception=(&image->exception);
alpha=ScaleCharToQuantum((unsigned char) inLayerInfo->alpha);
for (i=0; i < (ssize_t) bytes_per_pixel; i++)
{
q=GetAuthenticPixels(tile_image,0,0,tile_image->columns,tile_image->rows,
exception);
if (q == (PixelPacket *) NULL)
continue;
size=(MagickOffsetType) tile_image->rows*tile_image->columns;
while (size > 0)
{
if (xcfdata > xcfdatalimit)
goto bogus_rle;
pixel=(*xcfdata++);
length=(size_t) pixel;
if (length >= 128)
{
length=255-(length-1);
if (length == 128)
{
if (xcfdata >= xcfdatalimit)
goto bogus_rle;
length=(size_t) ((*xcfdata << 8) + xcfdata[1]);
xcfdata+=2;
}
size-=length;
if (size < 0)
goto bogus_rle;
if (&xcfdata[length-1] > xcfdatalimit)
goto bogus_rle;
while (length-- > 0)
{
data=(*xcfdata++);
switch (i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum(data));
if (inDocInfo->image_type == GIMP_GRAY)
{
SetPixelGreen(q,ScaleCharToQuantum(data));
SetPixelBlue(q,ScaleCharToQuantum(data));
}
else
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
SetPixelAlpha(q,alpha);
break;
}
case 1:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelAlpha(q,ScaleCharToQuantum(data));
else
SetPixelGreen(q,ScaleCharToQuantum(data));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum(data));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum(data));
break;
}
}
q++;
}
}
else
{
length+=1;
if (length == 128)
{
if (xcfdata >= xcfdatalimit)
goto bogus_rle;
length=(size_t) ((*xcfdata << 8) + xcfdata[1]);
xcfdata+=2;
}
size-=length;
if (size < 0)
goto bogus_rle;
if (xcfdata > xcfdatalimit)
goto bogus_rle;
pixel=(*xcfdata++);
for (j=0; j < (ssize_t) length; j++)
{
data=pixel;
switch (i)
{
case 0:
{
SetPixelRed(q,ScaleCharToQuantum(data));
if (inDocInfo->image_type == GIMP_GRAY)
{
SetPixelGreen(q,ScaleCharToQuantum(data));
SetPixelBlue(q,ScaleCharToQuantum(data));
}
else
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
SetPixelAlpha(q,alpha);
break;
}
case 1:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelAlpha(q,ScaleCharToQuantum(data));
else
SetPixelGreen(q,ScaleCharToQuantum(data));
break;
}
case 2:
{
SetPixelBlue(q,ScaleCharToQuantum(data));
break;
}
case 3:
{
SetPixelAlpha(q,ScaleCharToQuantum(data));
break;
}
}
q++;
}
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(unsigned char *) RelinquishMagickMemory(xcfodata);
return(MagickTrue);
bogus_rle:
if (xcfodata != (unsigned char *) NULL)
xcfodata=(unsigned char *) RelinquishMagickMemory(xcfodata);
return(MagickFalse);
}
static MagickBooleanType load_level(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayerInfo)
{
ExceptionInfo
*exception;
int
destLeft = 0,
destTop = 0;
Image*
tile_image;
MagickBooleanType
status;
MagickOffsetType
saved_pos,
offset,
offset2;
register ssize_t
i;
size_t
width,
height,
ntiles,
ntile_rows,
ntile_cols,
tile_image_width,
tile_image_height;
/* start reading the data */
exception=inDocInfo->exception;
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
/*
Read in the first tile offset. If it is '0', then this tile level is empty
and we can simply return.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image);
if (offset == 0)
return(MagickTrue);
/*
Initialize the reference for the in-memory tile-compression.
*/
ntile_rows=(height+TILE_HEIGHT-1)/TILE_HEIGHT;
ntile_cols=(width+TILE_WIDTH-1)/TILE_WIDTH;
ntiles=ntile_rows*ntile_cols;
for (i = 0; i < (ssize_t) ntiles; i++)
{
status=MagickFalse;
if (offset == 0)
ThrowBinaryException(CorruptImageError,"NotEnoughTiles",image->filename);
/* save the current position as it is where the
* next tile offset is stored.
*/
saved_pos=TellBlob(image);
/* read in the offset of the next tile so we can calculate the amount
of data needed for this tile*/
offset2=(MagickOffsetType)ReadBlobMSBLong(image);
/* if the offset is 0 then we need to read in the maximum possible
allowing for negative compression */
if (offset2 == 0)
offset2=(MagickOffsetType) (offset + TILE_WIDTH * TILE_WIDTH * 4* 1.5);
/* seek to the tile offset */
if (SeekBlob(image, offset, SEEK_SET) != offset)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/* allocate the image for the tile
NOTE: the last tile in a row or column may not be a full tile!
*/
tile_image_width=(size_t) (destLeft == (int) ntile_cols-1 ?
(int) width % TILE_WIDTH : TILE_WIDTH);
if (tile_image_width == 0)
tile_image_width=TILE_WIDTH;
tile_image_height = (size_t) (destTop == (int) ntile_rows-1 ?
(int) height % TILE_HEIGHT : TILE_HEIGHT);
if (tile_image_height == 0)
tile_image_height=TILE_HEIGHT;
tile_image=CloneImage(inLayerInfo->image,tile_image_width,
tile_image_height,MagickTrue,exception);
/* read in the tile */
switch (inDocInfo->compression)
{
case COMPRESS_NONE:
if (load_tile(image,tile_image,inDocInfo,inLayerInfo,(size_t) (offset2-offset)) == 0)
status=MagickTrue;
break;
case COMPRESS_RLE:
if (load_tile_rle (image,tile_image,inDocInfo,inLayerInfo,
(int) (offset2-offset)) == 0)
status=MagickTrue;
break;
case COMPRESS_ZLIB:
ThrowBinaryException(CoderError,"ZipCompressNotSupported",
image->filename)
case COMPRESS_FRACTAL:
ThrowBinaryException(CoderError,"FractalCompressNotSupported",
image->filename)
}
/* composite the tile onto the layer's image, and then destroy it */
(void) CompositeImage(inLayerInfo->image,CopyCompositeOp,tile_image,
destLeft * TILE_WIDTH,destTop*TILE_HEIGHT);
tile_image=DestroyImage(tile_image);
/* adjust tile position */
destLeft++;
if (destLeft >= (int) ntile_cols)
{
destLeft = 0;
destTop++;
}
if (status != MagickFalse)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
/* read in the offset of the next tile */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
}
if (offset != 0)
ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename)
return(MagickTrue);
}
static MagickBooleanType load_hierarchy(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayer)
{
MagickOffsetType
saved_pos,
offset,
junk;
size_t
width,
height,
bytes_per_pixel;
width=ReadBlobMSBLong(image);
(void) width;
height=ReadBlobMSBLong(image);
(void) height;
bytes_per_pixel=inDocInfo->bytes_per_pixel=ReadBlobMSBLong(image);
(void) bytes_per_pixel;
/* load in the levels...we make sure that the number of levels
* calculated when the TileManager was created is the same
* as the number of levels found in the file.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image); /* top level */
/* discard offsets for layers below first, if any.
*/
do
{
junk=(MagickOffsetType) ReadBlobMSBLong(image);
}
while (junk != 0);
/* save the current position as it is where the
* next level offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the level offset */
if (SeekBlob(image, offset, SEEK_SET) != offset)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/* read in the level */
if (load_level (image, inDocInfo, inLayer) == 0)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
return(MagickTrue);
}
static void InitXCFImage(XCFLayerInfo *outLayer)
{
outLayer->image->page.x=outLayer->offset_x;
outLayer->image->page.y=outLayer->offset_y;
outLayer->image->page.width=outLayer->width;
outLayer->image->page.height=outLayer->height;
(void) SetImageProperty(outLayer->image,"label",(char *)outLayer->name);
}
static MagickBooleanType ReadOneLayer(const ImageInfo *image_info,Image* image,
XCFDocInfo* inDocInfo,XCFLayerInfo *outLayer,const ssize_t layer)
{
MagickOffsetType
offset;
unsigned int
foundPropEnd = 0;
size_t
hierarchy_offset,
layer_mask_offset;
/* clear the block! */
(void) ResetMagickMemory( outLayer, 0, sizeof( XCFLayerInfo ) );
/* read in the layer width, height, type and name */
outLayer->width = ReadBlobMSBLong(image);
outLayer->height = ReadBlobMSBLong(image);
outLayer->type = ReadBlobMSBLong(image);
(void) ReadBlobStringWithLongSize(image, outLayer->name,
sizeof(outLayer->name));
if (EOFBlob(image) != MagickFalse)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/* read the layer properties! */
foundPropEnd = 0;
while ( (foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse) ) {
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd = 1;
break;
case PROP_ACTIVE_LAYER:
outLayer->active = 1;
break;
case PROP_FLOATING_SELECTION:
outLayer->floating_offset = ReadBlobMSBLong(image);
break;
case PROP_OPACITY:
outLayer->alpha = ReadBlobMSBLong(image);
break;
case PROP_VISIBLE:
outLayer->visible = ReadBlobMSBLong(image);
break;
case PROP_LINKED:
outLayer->linked = ReadBlobMSBLong(image);
break;
case PROP_PRESERVE_TRANSPARENCY:
outLayer->preserve_trans = ReadBlobMSBLong(image);
break;
case PROP_APPLY_MASK:
outLayer->apply_mask = ReadBlobMSBLong(image);
break;
case PROP_EDIT_MASK:
outLayer->edit_mask = ReadBlobMSBLong(image);
break;
case PROP_SHOW_MASK:
outLayer->show_mask = ReadBlobMSBLong(image);
break;
case PROP_OFFSETS:
outLayer->offset_x = ReadBlobMSBSignedLong(image);
outLayer->offset_y = ReadBlobMSBSignedLong(image);
break;
case PROP_MODE:
outLayer->mode = ReadBlobMSBLong(image);
break;
case PROP_TATTOO:
outLayer->preserve_trans = ReadBlobMSBLong(image);
break;
case PROP_PARASITES:
{
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
ssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite(info);
gimp_drawable_parasite_attach(GIMP_DRAWABLE(layer), p);
gimp_parasite_free(p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading a layer's parasites");
*/
}
break;
default:
/* g_message ("unexpected/unknown layer property: %d (skipping)",
prop_type); */
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount = (ssize_t) MagickMin(16, prop_size);
amount = ReadBlob(image, (size_t) amount, (unsigned char *) &buf);
if (!amount)
ThrowBinaryException(CorruptImageError,"CorruptImage",
image->filename);
prop_size -= (size_t) MagickMin(16, (size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
return(MagickFalse);
/* allocate the image for this layer */
if (image_info->number_scenes != 0)
{
ssize_t
scene;
scene=inDocInfo->number_layers-layer-1;
if (scene > (ssize_t) (image_info->scene+image_info->number_scenes-1))
{
outLayer->image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (outLayer->image == (Image *) NULL)
return(MagickFalse);
InitXCFImage(outLayer);
return(MagickTrue);
}
}
/* allocate the image for this layer */
outLayer->image=CloneImage(image,outLayer->width, outLayer->height,MagickTrue,
&image->exception);
if (outLayer->image == (Image *) NULL)
return(MagickFalse);
/* clear the image based on the layer opacity */
outLayer->image->background_color.opacity=
ScaleCharToQuantum((unsigned char) (255-outLayer->alpha));
(void) SetImageBackgroundColor(outLayer->image);
InitXCFImage(outLayer);
/* set the compositing mode */
outLayer->image->compose = GIMPBlendModeToCompositeOperator( outLayer->mode );
if ( outLayer->visible == MagickFalse )
{
/* BOGUS: should really be separate member var! */
outLayer->image->compose = NoCompositeOp;
}
/* read the hierarchy and layer mask offsets */
hierarchy_offset = ReadBlobMSBLong(image);
layer_mask_offset = ReadBlobMSBLong(image);
/* read in the hierarchy */
offset=SeekBlob(image, (MagickOffsetType) hierarchy_offset, SEEK_SET);
if (offset != (MagickOffsetType) hierarchy_offset)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageError,"InvalidImageHeader","`%s'",image->filename);
if (load_hierarchy (image, inDocInfo, outLayer) == 0)
return(MagickFalse);
/* read in the layer mask */
if (layer_mask_offset != 0)
{
offset=SeekBlob(image, (MagickOffsetType) layer_mask_offset, SEEK_SET);
#if 0 /* BOGUS: support layer masks! */
layer_mask = xcf_load_layer_mask (info, gimage);
if (layer_mask == 0)
goto error;
/* set the offsets of the layer_mask */
GIMP_DRAWABLE (layer_mask)->offset_x = GIMP_DRAWABLE (layer)->offset_x;
GIMP_DRAWABLE (layer_mask)->offset_y = GIMP_DRAWABLE (layer)->offset_y;
gimp_layer_add_mask (layer, layer_mask, MagickFalse);
layer->mask->apply_mask = apply_mask;
layer->mask->edit_mask = edit_mask;
layer->mask->show_mask = show_mask;
#endif
}
/* attach the floating selection... */
#if 0 /* BOGUS: we may need to read this, even if we don't support it! */
if (add_floating_sel)
{
GimpLayer *floating_sel;
floating_sel = info->floating_sel;
floating_sel_attach (floating_sel, GIMP_DRAWABLE (layer));
}
#endif
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadXCFImage() reads a GIMP (GNU Image Manipulation Program) image
% file and returns it. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the ReadXCFImage method is:
%
% image=ReadXCFImage(image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[14];
Image
*image;
int
foundPropEnd = 0;
MagickBooleanType
status;
MagickOffsetType
offset;
register ssize_t
i;
size_t
image_type,
length;
ssize_t
count;
XCFDocInfo
doc_info;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
count=ReadBlob(image,14,(unsigned char *) magick);
if ((count != 14) ||
(LocaleNCompare((char *) magick,"gimp xcf",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo));
doc_info.exception=exception;
doc_info.width=ReadBlobMSBLong(image);
doc_info.height=ReadBlobMSBLong(image);
if ((doc_info.width > 262144) || (doc_info.height > 262144))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
doc_info.image_type=ReadBlobMSBLong(image);
/*
Initialize image attributes.
*/
image->columns=doc_info.width;
image->rows=doc_info.height;
image_type=doc_info.image_type;
doc_info.file_size=GetBlobSize(image);
image->compression=NoCompression;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image_type == GIMP_RGB)
;
else
if (image_type == GIMP_GRAY)
image->colorspace=GRAYColorspace;
else
if (image_type == GIMP_INDEXED)
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
(void) SetImageOpacity(image,OpaqueOpacity);
(void) SetImageBackgroundColor(image);
/*
Read properties.
*/
while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse))
{
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd=1;
break;
case PROP_COLORMAP:
{
/* Cannot rely on prop_size here--the value is set incorrectly
by some Gimp versions.
*/
size_t num_colours = ReadBlobMSBLong(image);
if (DiscardBlobBytes(image,3*num_colours) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
if (info->file_version == 0)
{
gint i;
g_message (_("XCF warning: version 0 of XCF file format\n"
"did not save indexed colormaps correctly.\n"
"Substituting grayscale map."));
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
xcf_seek_pos (info, info->cp + gimage->num_cols);
for (i = 0; i<gimage->num_cols; i++)
{
gimage->cmap[i*3+0] = i;
gimage->cmap[i*3+1] = i;
gimage->cmap[i*3+2] = i;
}
}
else
{
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
info->cp +=
xcf_read_int8 (info->fp,
(guint8*) gimage->cmap, gimage->num_cols*3);
}
*/
break;
}
case PROP_COMPRESSION:
{
doc_info.compression = ReadBlobByte(image);
if ((doc_info.compression != COMPRESS_NONE) &&
(doc_info.compression != COMPRESS_RLE) &&
(doc_info.compression != COMPRESS_ZLIB) &&
(doc_info.compression != COMPRESS_FRACTAL))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
break;
case PROP_GUIDES:
{
/* just skip it - we don't care about guides */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
break;
case PROP_RESOLUTION:
{
/* float xres = (float) */ (void) ReadBlobMSBLong(image);
/* float yres = (float) */ (void) ReadBlobMSBLong(image);
/*
if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION ||
yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION)
{
g_message ("Warning, resolution out of range in XCF file");
xres = gimage->gimp->config->default_xresolution;
yres = gimage->gimp->config->default_yresolution;
}
*/
/* BOGUS: we don't write these yet because we aren't
reading them properly yet :(
image->x_resolution = xres;
image->y_resolution = yres;
*/
}
break;
case PROP_TATTOO:
{
/* we need to read it, even if we ignore it */
/*size_t tattoo_state = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PARASITES:
{
/* BOGUS: we may need these for IPTC stuff */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
gssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite (info);
gimp_image_parasite_attach (gimage, p);
gimp_parasite_free (p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading an image's parasites");
*/
}
break;
case PROP_UNIT:
{
/* BOGUS: ignore for now... */
/*size_t unit = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PATHS:
{
/* BOGUS: just skip it for now */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(&image->exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
PathList *paths = xcf_load_bzpaths (gimage, info);
gimp_image_set_paths (gimage, paths);
*/
}
break;
case PROP_USER_UNIT:
{
char unit_string[1000];
/*BOGUS: ignored for now */
/*float factor = (float) */ (void) ReadBlobMSBLong(image);
/* size_t digits = */ (void) ReadBlobMSBLong(image);
for (i=0; i<5; i++)
(void) ReadBlobStringWithLongSize(image, unit_string,
sizeof(unit_string));
}
break;
default:
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount=(ssize_t) MagickMin(16, prop_size);
amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf);
if (!amount)
ThrowReaderException(CorruptImageError,"CorruptImage");
prop_size -= (size_t) MagickMin(16,(size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
{
; /* do nothing, were just pinging! */
}
else
{
int
current_layer = 0,
foundAllLayers = MagickFalse,
number_layers = 0;
MagickOffsetType
oldPos=TellBlob(image);
XCFLayerInfo
*layer_info;
/*
The read pointer.
*/
do
{
ssize_t offset = ReadBlobMSBSignedLong(image);
if (offset == 0)
foundAllLayers=MagickTrue;
else
number_layers++;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
} while (foundAllLayers == MagickFalse);
doc_info.number_layers=number_layers;
offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* allocate our array of layer info blocks */
length=(size_t) number_layers;
layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length,
sizeof(*layer_info));
if (layer_info == (XCFLayerInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo));
for ( ; ; )
{
MagickBooleanType
layer_ok;
MagickOffsetType
offset,
saved_pos;
/* read in the offset of the next layer */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
/* if the offset is 0 then we are at the end
* of the layer list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next layer offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the layer offset */
if (SeekBlob(image,offset,SEEK_SET) != offset)
ThrowReaderException(ResourceLimitError,"NotEnoughPixelData");
/* read in the layer */
layer_ok=ReadOneLayer(image_info,image,&doc_info,
&layer_info[current_layer],current_layer);
if (layer_ok == MagickFalse)
{
int j;
for (j=0; j < current_layer; j++)
layer_info[j].image=DestroyImage(layer_info[j].image);
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
current_layer++;
}
#if 0
{
/* NOTE: XCF layers are REVERSED from composite order! */
signed int j;
for (j=number_layers-1; j>=0; j--) {
/* BOGUS: need to consider layer blending modes!! */
if ( layer_info[j].visible ) { /* only visible ones, please! */
CompositeImage(image, OverCompositeOp, layer_info[j].image,
layer_info[j].offset_x, layer_info[j].offset_y );
layer_info[j].image =DestroyImage( layer_info[j].image );
/* If we do this, we'll get REAL gray images! */
if ( image_type == GIMP_GRAY ) {
QuantizeInfo qi;
GetQuantizeInfo(&qi);
qi.colorspace = GRAYColorspace;
QuantizeImage( &qi, layer_info[j].image );
}
}
}
}
#else
{
/* NOTE: XCF layers are REVERSED from composite order! */
ssize_t j;
/* now reverse the order of the layers as they are put
into subimages
*/
for (j=(long) number_layers-1; j >= 0; j--)
AppendImageToList(&image,layer_info[j].image);
}
#endif
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
#if 0 /* BOGUS: do we need the channels?? */
while (MagickTrue)
{
/* read in the offset of the next channel */
info->cp += xcf_read_int32 (info->fp, &offset, 1);
/* if the offset is 0 then we are at the end
* of the channel list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next channel offset is stored.
*/
saved_pos = info->cp;
/* seek to the channel offset */
xcf_seek_pos (info, offset);
/* read in the layer */
channel = xcf_load_channel (info, gimage);
if (channel == 0)
goto error;
num_successful_elements++;
/* add the channel to the image if its not the selection */
if (channel != gimage->selection_mask)
gimp_image_add_channel (gimage, channel, -1);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
xcf_seek_pos (info, saved_pos);
}
#endif
}
(void) CloseBlob(image);
DestroyImage(RemoveFirstImageFromList(&image));
if (image_type == GIMP_GRAY)
image->type=GrayscaleType;
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterXCFImage() adds attributes for the XCF image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterXCFImage method is:
%
% size_t RegisterXCFImage(void)
%
*/
ModuleExport size_t RegisterXCFImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("XCF");
entry->decoder=(DecodeImageHandler *) ReadXCFImage;
entry->magick=(IsImageFormatHandler *) IsXCF;
entry->description=ConstantString("GIMP image");
entry->module=ConstantString("XCF");
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterXCFImage() removes format registrations made by the
% XCF module from the list of supported formats.
%
% The format of the UnregisterXCFImage method is:
%
% UnregisterXCFImage(void)
%
*/
ModuleExport void UnregisterXCFImage(void)
{
(void) UnregisterMagickInfo("XCF");
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3198_0 |
crossvul-cpp_data_bad_3060_3 | /*
* fs/cifs/cifsacl.c
*
* Copyright (C) International Business Machines Corp., 2007,2008
* Author(s): Steve French (sfrench@us.ibm.com)
*
* Contains the routines for mapping CIFS/NTFS ACLs
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/keyctl.h>
#include <linux/key-type.h>
#include <keys/user-type.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsacl.h"
#include "cifsproto.h"
#include "cifs_debug.h"
/* security id for everyone/world system group */
static const struct cifs_sid sid_everyone = {
1, 1, {0, 0, 0, 0, 0, 1}, {0} };
/* security id for Authenticated Users system group */
static const struct cifs_sid sid_authusers = {
1, 1, {0, 0, 0, 0, 0, 5}, {__constant_cpu_to_le32(11)} };
/* group users */
static const struct cifs_sid sid_user = {1, 2 , {0, 0, 0, 0, 0, 5}, {} };
static const struct cred *root_cred;
static int
cifs_idmap_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
{
char *payload;
/*
* If the payload is less than or equal to the size of a pointer, then
* an allocation here is wasteful. Just copy the data directly to the
* payload.value union member instead.
*
* With this however, you must check the datalen before trying to
* dereference payload.data!
*/
if (prep->datalen <= sizeof(key->payload)) {
key->payload.value = 0;
memcpy(&key->payload.value, prep->data, prep->datalen);
key->datalen = prep->datalen;
return 0;
}
payload = kmemdup(prep->data, prep->datalen, GFP_KERNEL);
if (!payload)
return -ENOMEM;
key->payload.data = payload;
key->datalen = prep->datalen;
return 0;
}
static inline void
cifs_idmap_key_destroy(struct key *key)
{
if (key->datalen > sizeof(key->payload))
kfree(key->payload.data);
}
static struct key_type cifs_idmap_key_type = {
.name = "cifs.idmap",
.instantiate = cifs_idmap_key_instantiate,
.destroy = cifs_idmap_key_destroy,
.describe = user_describe,
.match = user_match,
};
static char *
sid_to_key_str(struct cifs_sid *sidptr, unsigned int type)
{
int i, len;
unsigned int saval;
char *sidstr, *strptr;
unsigned long long id_auth_val;
/* 3 bytes for prefix */
sidstr = kmalloc(3 + SID_STRING_BASE_SIZE +
(SID_STRING_SUBAUTH_SIZE * sidptr->num_subauth),
GFP_KERNEL);
if (!sidstr)
return sidstr;
strptr = sidstr;
len = sprintf(strptr, "%cs:S-%hhu", type == SIDOWNER ? 'o' : 'g',
sidptr->revision);
strptr += len;
/* The authority field is a single 48-bit number */
id_auth_val = (unsigned long long)sidptr->authority[5];
id_auth_val |= (unsigned long long)sidptr->authority[4] << 8;
id_auth_val |= (unsigned long long)sidptr->authority[3] << 16;
id_auth_val |= (unsigned long long)sidptr->authority[2] << 24;
id_auth_val |= (unsigned long long)sidptr->authority[1] << 32;
id_auth_val |= (unsigned long long)sidptr->authority[0] << 48;
/*
* MS-DTYP states that if the authority is >= 2^32, then it should be
* expressed as a hex value.
*/
if (id_auth_val <= UINT_MAX)
len = sprintf(strptr, "-%llu", id_auth_val);
else
len = sprintf(strptr, "-0x%llx", id_auth_val);
strptr += len;
for (i = 0; i < sidptr->num_subauth; ++i) {
saval = le32_to_cpu(sidptr->sub_auth[i]);
len = sprintf(strptr, "-%u", saval);
strptr += len;
}
return sidstr;
}
/*
* if the two SIDs (roughly equivalent to a UUID for a user or group) are
* the same returns zero, if they do not match returns non-zero.
*/
static int
compare_sids(const struct cifs_sid *ctsid, const struct cifs_sid *cwsid)
{
int i;
int num_subauth, num_sat, num_saw;
if ((!ctsid) || (!cwsid))
return 1;
/* compare the revision */
if (ctsid->revision != cwsid->revision) {
if (ctsid->revision > cwsid->revision)
return 1;
else
return -1;
}
/* compare all of the six auth values */
for (i = 0; i < NUM_AUTHS; ++i) {
if (ctsid->authority[i] != cwsid->authority[i]) {
if (ctsid->authority[i] > cwsid->authority[i])
return 1;
else
return -1;
}
}
/* compare all of the subauth values if any */
num_sat = ctsid->num_subauth;
num_saw = cwsid->num_subauth;
num_subauth = num_sat < num_saw ? num_sat : num_saw;
if (num_subauth) {
for (i = 0; i < num_subauth; ++i) {
if (ctsid->sub_auth[i] != cwsid->sub_auth[i]) {
if (le32_to_cpu(ctsid->sub_auth[i]) >
le32_to_cpu(cwsid->sub_auth[i]))
return 1;
else
return -1;
}
}
}
return 0; /* sids compare/match */
}
static void
cifs_copy_sid(struct cifs_sid *dst, const struct cifs_sid *src)
{
int i;
dst->revision = src->revision;
dst->num_subauth = min_t(u8, src->num_subauth, SID_MAX_SUB_AUTHORITIES);
for (i = 0; i < NUM_AUTHS; ++i)
dst->authority[i] = src->authority[i];
for (i = 0; i < dst->num_subauth; ++i)
dst->sub_auth[i] = src->sub_auth[i];
}
static int
id_to_sid(unsigned int cid, uint sidtype, struct cifs_sid *ssid)
{
int rc;
struct key *sidkey;
struct cifs_sid *ksid;
unsigned int ksid_size;
char desc[3 + 10 + 1]; /* 3 byte prefix + 10 bytes for value + NULL */
const struct cred *saved_cred;
rc = snprintf(desc, sizeof(desc), "%ci:%u",
sidtype == SIDOWNER ? 'o' : 'g', cid);
if (rc >= sizeof(desc))
return -EINVAL;
rc = 0;
saved_cred = override_creds(root_cred);
sidkey = request_key(&cifs_idmap_key_type, desc, "");
if (IS_ERR(sidkey)) {
rc = -EINVAL;
cifs_dbg(FYI, "%s: Can't map %cid %u to a SID\n",
__func__, sidtype == SIDOWNER ? 'u' : 'g', cid);
goto out_revert_creds;
} else if (sidkey->datalen < CIFS_SID_BASE_SIZE) {
rc = -EIO;
cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%hu)\n",
__func__, sidkey->datalen);
goto invalidate_key;
}
/*
* A sid is usually too large to be embedded in payload.value, but if
* there are no subauthorities and the host has 8-byte pointers, then
* it could be.
*/
ksid = sidkey->datalen <= sizeof(sidkey->payload) ?
(struct cifs_sid *)&sidkey->payload.value :
(struct cifs_sid *)sidkey->payload.data;
ksid_size = CIFS_SID_BASE_SIZE + (ksid->num_subauth * sizeof(__le32));
if (ksid_size > sidkey->datalen) {
rc = -EIO;
cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%hu, ksid_size=%u)\n",
__func__, sidkey->datalen, ksid_size);
goto invalidate_key;
}
cifs_copy_sid(ssid, ksid);
out_key_put:
key_put(sidkey);
out_revert_creds:
revert_creds(saved_cred);
return rc;
invalidate_key:
key_invalidate(sidkey);
goto out_key_put;
}
static int
sid_to_id(struct cifs_sb_info *cifs_sb, struct cifs_sid *psid,
struct cifs_fattr *fattr, uint sidtype)
{
int rc;
struct key *sidkey;
char *sidstr;
const struct cred *saved_cred;
kuid_t fuid = cifs_sb->mnt_uid;
kgid_t fgid = cifs_sb->mnt_gid;
/*
* If we have too many subauthorities, then something is really wrong.
* Just return an error.
*/
if (unlikely(psid->num_subauth > SID_MAX_SUB_AUTHORITIES)) {
cifs_dbg(FYI, "%s: %u subauthorities is too many!\n",
__func__, psid->num_subauth);
return -EIO;
}
sidstr = sid_to_key_str(psid, sidtype);
if (!sidstr)
return -ENOMEM;
saved_cred = override_creds(root_cred);
sidkey = request_key(&cifs_idmap_key_type, sidstr, "");
if (IS_ERR(sidkey)) {
rc = -EINVAL;
cifs_dbg(FYI, "%s: Can't map SID %s to a %cid\n",
__func__, sidstr, sidtype == SIDOWNER ? 'u' : 'g');
goto out_revert_creds;
}
/*
* FIXME: Here we assume that uid_t and gid_t are same size. It's
* probably a safe assumption but might be better to check based on
* sidtype.
*/
BUILD_BUG_ON(sizeof(uid_t) != sizeof(gid_t));
if (sidkey->datalen != sizeof(uid_t)) {
rc = -EIO;
cifs_dbg(FYI, "%s: Downcall contained malformed key (datalen=%hu)\n",
__func__, sidkey->datalen);
key_invalidate(sidkey);
goto out_key_put;
}
if (sidtype == SIDOWNER) {
kuid_t uid;
uid_t id;
memcpy(&id, &sidkey->payload.value, sizeof(uid_t));
uid = make_kuid(&init_user_ns, id);
if (uid_valid(uid))
fuid = uid;
} else {
kgid_t gid;
gid_t id;
memcpy(&id, &sidkey->payload.value, sizeof(gid_t));
gid = make_kgid(&init_user_ns, id);
if (gid_valid(gid))
fgid = gid;
}
out_key_put:
key_put(sidkey);
out_revert_creds:
revert_creds(saved_cred);
kfree(sidstr);
/*
* Note that we return 0 here unconditionally. If the mapping
* fails then we just fall back to using the mnt_uid/mnt_gid.
*/
if (sidtype == SIDOWNER)
fattr->cf_uid = fuid;
else
fattr->cf_gid = fgid;
return 0;
}
int
init_cifs_idmap(void)
{
struct cred *cred;
struct key *keyring;
int ret;
cifs_dbg(FYI, "Registering the %s key type\n",
cifs_idmap_key_type.name);
/* create an override credential set with a special thread keyring in
* which requests are cached
*
* this is used to prevent malicious redirections from being installed
* with add_key().
*/
cred = prepare_kernel_cred(NULL);
if (!cred)
return -ENOMEM;
keyring = keyring_alloc(".cifs_idmap",
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
(KEY_POS_ALL & ~KEY_POS_SETATTR) |
KEY_USR_VIEW | KEY_USR_READ,
KEY_ALLOC_NOT_IN_QUOTA, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto failed_put_cred;
}
ret = register_key_type(&cifs_idmap_key_type);
if (ret < 0)
goto failed_put_key;
/* instruct request_key() to use this special keyring as a cache for
* the results it looks up */
set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
cred->thread_keyring = keyring;
cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
root_cred = cred;
cifs_dbg(FYI, "cifs idmap keyring: %d\n", key_serial(keyring));
return 0;
failed_put_key:
key_put(keyring);
failed_put_cred:
put_cred(cred);
return ret;
}
void
exit_cifs_idmap(void)
{
key_revoke(root_cred->thread_keyring);
unregister_key_type(&cifs_idmap_key_type);
put_cred(root_cred);
cifs_dbg(FYI, "Unregistered %s key type\n", cifs_idmap_key_type.name);
}
/* copy ntsd, owner sid, and group sid from a security descriptor to another */
static void copy_sec_desc(const struct cifs_ntsd *pntsd,
struct cifs_ntsd *pnntsd, __u32 sidsoffset)
{
struct cifs_sid *owner_sid_ptr, *group_sid_ptr;
struct cifs_sid *nowner_sid_ptr, *ngroup_sid_ptr;
/* copy security descriptor control portion */
pnntsd->revision = pntsd->revision;
pnntsd->type = pntsd->type;
pnntsd->dacloffset = cpu_to_le32(sizeof(struct cifs_ntsd));
pnntsd->sacloffset = 0;
pnntsd->osidoffset = cpu_to_le32(sidsoffset);
pnntsd->gsidoffset = cpu_to_le32(sidsoffset + sizeof(struct cifs_sid));
/* copy owner sid */
owner_sid_ptr = (struct cifs_sid *)((char *)pntsd +
le32_to_cpu(pntsd->osidoffset));
nowner_sid_ptr = (struct cifs_sid *)((char *)pnntsd + sidsoffset);
cifs_copy_sid(nowner_sid_ptr, owner_sid_ptr);
/* copy group sid */
group_sid_ptr = (struct cifs_sid *)((char *)pntsd +
le32_to_cpu(pntsd->gsidoffset));
ngroup_sid_ptr = (struct cifs_sid *)((char *)pnntsd + sidsoffset +
sizeof(struct cifs_sid));
cifs_copy_sid(ngroup_sid_ptr, group_sid_ptr);
return;
}
/*
change posix mode to reflect permissions
pmode is the existing mode (we only want to overwrite part of this
bits to set can be: S_IRWXU, S_IRWXG or S_IRWXO ie 00700 or 00070 or 00007
*/
static void access_flags_to_mode(__le32 ace_flags, int type, umode_t *pmode,
umode_t *pbits_to_set)
{
__u32 flags = le32_to_cpu(ace_flags);
/* the order of ACEs is important. The canonical order is to begin with
DENY entries followed by ALLOW, otherwise an allow entry could be
encountered first, making the subsequent deny entry like "dead code"
which would be superflous since Windows stops when a match is made
for the operation you are trying to perform for your user */
/* For deny ACEs we change the mask so that subsequent allow access
control entries do not turn on the bits we are denying */
if (type == ACCESS_DENIED) {
if (flags & GENERIC_ALL)
*pbits_to_set &= ~S_IRWXUGO;
if ((flags & GENERIC_WRITE) ||
((flags & FILE_WRITE_RIGHTS) == FILE_WRITE_RIGHTS))
*pbits_to_set &= ~S_IWUGO;
if ((flags & GENERIC_READ) ||
((flags & FILE_READ_RIGHTS) == FILE_READ_RIGHTS))
*pbits_to_set &= ~S_IRUGO;
if ((flags & GENERIC_EXECUTE) ||
((flags & FILE_EXEC_RIGHTS) == FILE_EXEC_RIGHTS))
*pbits_to_set &= ~S_IXUGO;
return;
} else if (type != ACCESS_ALLOWED) {
cifs_dbg(VFS, "unknown access control type %d\n", type);
return;
}
/* else ACCESS_ALLOWED type */
if (flags & GENERIC_ALL) {
*pmode |= (S_IRWXUGO & (*pbits_to_set));
cifs_dbg(NOISY, "all perms\n");
return;
}
if ((flags & GENERIC_WRITE) ||
((flags & FILE_WRITE_RIGHTS) == FILE_WRITE_RIGHTS))
*pmode |= (S_IWUGO & (*pbits_to_set));
if ((flags & GENERIC_READ) ||
((flags & FILE_READ_RIGHTS) == FILE_READ_RIGHTS))
*pmode |= (S_IRUGO & (*pbits_to_set));
if ((flags & GENERIC_EXECUTE) ||
((flags & FILE_EXEC_RIGHTS) == FILE_EXEC_RIGHTS))
*pmode |= (S_IXUGO & (*pbits_to_set));
cifs_dbg(NOISY, "access flags 0x%x mode now 0x%x\n", flags, *pmode);
return;
}
/*
Generate access flags to reflect permissions mode is the existing mode.
This function is called for every ACE in the DACL whose SID matches
with either owner or group or everyone.
*/
static void mode_to_access_flags(umode_t mode, umode_t bits_to_use,
__u32 *pace_flags)
{
/* reset access mask */
*pace_flags = 0x0;
/* bits to use are either S_IRWXU or S_IRWXG or S_IRWXO */
mode &= bits_to_use;
/* check for R/W/X UGO since we do not know whose flags
is this but we have cleared all the bits sans RWX for
either user or group or other as per bits_to_use */
if (mode & S_IRUGO)
*pace_flags |= SET_FILE_READ_RIGHTS;
if (mode & S_IWUGO)
*pace_flags |= SET_FILE_WRITE_RIGHTS;
if (mode & S_IXUGO)
*pace_flags |= SET_FILE_EXEC_RIGHTS;
cifs_dbg(NOISY, "mode: 0x%x, access flags now 0x%x\n",
mode, *pace_flags);
return;
}
static __u16 fill_ace_for_sid(struct cifs_ace *pntace,
const struct cifs_sid *psid, __u64 nmode, umode_t bits)
{
int i;
__u16 size = 0;
__u32 access_req = 0;
pntace->type = ACCESS_ALLOWED;
pntace->flags = 0x0;
mode_to_access_flags(nmode, bits, &access_req);
if (!access_req)
access_req = SET_MINIMUM_RIGHTS;
pntace->access_req = cpu_to_le32(access_req);
pntace->sid.revision = psid->revision;
pntace->sid.num_subauth = psid->num_subauth;
for (i = 0; i < NUM_AUTHS; i++)
pntace->sid.authority[i] = psid->authority[i];
for (i = 0; i < psid->num_subauth; i++)
pntace->sid.sub_auth[i] = psid->sub_auth[i];
size = 1 + 1 + 2 + 4 + 1 + 1 + 6 + (psid->num_subauth * 4);
pntace->size = cpu_to_le16(size);
return size;
}
#ifdef CONFIG_CIFS_DEBUG2
static void dump_ace(struct cifs_ace *pace, char *end_of_acl)
{
int num_subauth;
/* validate that we do not go past end of acl */
if (le16_to_cpu(pace->size) < 16) {
cifs_dbg(VFS, "ACE too small %d\n", le16_to_cpu(pace->size));
return;
}
if (end_of_acl < (char *)pace + le16_to_cpu(pace->size)) {
cifs_dbg(VFS, "ACL too small to parse ACE\n");
return;
}
num_subauth = pace->sid.num_subauth;
if (num_subauth) {
int i;
cifs_dbg(FYI, "ACE revision %d num_auth %d type %d flags %d size %d\n",
pace->sid.revision, pace->sid.num_subauth, pace->type,
pace->flags, le16_to_cpu(pace->size));
for (i = 0; i < num_subauth; ++i) {
cifs_dbg(FYI, "ACE sub_auth[%d]: 0x%x\n",
i, le32_to_cpu(pace->sid.sub_auth[i]));
}
/* BB add length check to make sure that we do not have huge
num auths and therefore go off the end */
}
return;
}
#endif
static void parse_dacl(struct cifs_acl *pdacl, char *end_of_acl,
struct cifs_sid *pownersid, struct cifs_sid *pgrpsid,
struct cifs_fattr *fattr)
{
int i;
int num_aces = 0;
int acl_size;
char *acl_base;
struct cifs_ace **ppace;
/* BB need to add parm so we can store the SID BB */
if (!pdacl) {
/* no DACL in the security descriptor, set
all the permissions for user/group/other */
fattr->cf_mode |= S_IRWXUGO;
return;
}
/* validate that we do not go past end of acl */
if (end_of_acl < (char *)pdacl + le16_to_cpu(pdacl->size)) {
cifs_dbg(VFS, "ACL too small to parse DACL\n");
return;
}
cifs_dbg(NOISY, "DACL revision %d size %d num aces %d\n",
le16_to_cpu(pdacl->revision), le16_to_cpu(pdacl->size),
le32_to_cpu(pdacl->num_aces));
/* reset rwx permissions for user/group/other.
Also, if num_aces is 0 i.e. DACL has no ACEs,
user/group/other have no permissions */
fattr->cf_mode &= ~(S_IRWXUGO);
acl_base = (char *)pdacl;
acl_size = sizeof(struct cifs_acl);
num_aces = le32_to_cpu(pdacl->num_aces);
if (num_aces > 0) {
umode_t user_mask = S_IRWXU;
umode_t group_mask = S_IRWXG;
umode_t other_mask = S_IRWXU | S_IRWXG | S_IRWXO;
if (num_aces > ULONG_MAX / sizeof(struct cifs_ace *))
return;
ppace = kmalloc(num_aces * sizeof(struct cifs_ace *),
GFP_KERNEL);
if (!ppace)
return;
for (i = 0; i < num_aces; ++i) {
ppace[i] = (struct cifs_ace *) (acl_base + acl_size);
#ifdef CONFIG_CIFS_DEBUG2
dump_ace(ppace[i], end_of_acl);
#endif
if (compare_sids(&(ppace[i]->sid), pownersid) == 0)
access_flags_to_mode(ppace[i]->access_req,
ppace[i]->type,
&fattr->cf_mode,
&user_mask);
if (compare_sids(&(ppace[i]->sid), pgrpsid) == 0)
access_flags_to_mode(ppace[i]->access_req,
ppace[i]->type,
&fattr->cf_mode,
&group_mask);
if (compare_sids(&(ppace[i]->sid), &sid_everyone) == 0)
access_flags_to_mode(ppace[i]->access_req,
ppace[i]->type,
&fattr->cf_mode,
&other_mask);
if (compare_sids(&(ppace[i]->sid), &sid_authusers) == 0)
access_flags_to_mode(ppace[i]->access_req,
ppace[i]->type,
&fattr->cf_mode,
&other_mask);
/* memcpy((void *)(&(cifscred->aces[i])),
(void *)ppace[i],
sizeof(struct cifs_ace)); */
acl_base = (char *)ppace[i];
acl_size = le16_to_cpu(ppace[i]->size);
}
kfree(ppace);
}
return;
}
static int set_chmod_dacl(struct cifs_acl *pndacl, struct cifs_sid *pownersid,
struct cifs_sid *pgrpsid, __u64 nmode)
{
u16 size = 0;
struct cifs_acl *pnndacl;
pnndacl = (struct cifs_acl *)((char *)pndacl + sizeof(struct cifs_acl));
size += fill_ace_for_sid((struct cifs_ace *) ((char *)pnndacl + size),
pownersid, nmode, S_IRWXU);
size += fill_ace_for_sid((struct cifs_ace *)((char *)pnndacl + size),
pgrpsid, nmode, S_IRWXG);
size += fill_ace_for_sid((struct cifs_ace *)((char *)pnndacl + size),
&sid_everyone, nmode, S_IRWXO);
pndacl->size = cpu_to_le16(size + sizeof(struct cifs_acl));
pndacl->num_aces = cpu_to_le32(3);
return 0;
}
static int parse_sid(struct cifs_sid *psid, char *end_of_acl)
{
/* BB need to add parm so we can store the SID BB */
/* validate that we do not go past end of ACL - sid must be at least 8
bytes long (assuming no sub-auths - e.g. the null SID */
if (end_of_acl < (char *)psid + 8) {
cifs_dbg(VFS, "ACL too small to parse SID %p\n", psid);
return -EINVAL;
}
#ifdef CONFIG_CIFS_DEBUG2
if (psid->num_subauth) {
int i;
cifs_dbg(FYI, "SID revision %d num_auth %d\n",
psid->revision, psid->num_subauth);
for (i = 0; i < psid->num_subauth; i++) {
cifs_dbg(FYI, "SID sub_auth[%d]: 0x%x\n",
i, le32_to_cpu(psid->sub_auth[i]));
}
/* BB add length check to make sure that we do not have huge
num auths and therefore go off the end */
cifs_dbg(FYI, "RID 0x%x\n",
le32_to_cpu(psid->sub_auth[psid->num_subauth-1]));
}
#endif
return 0;
}
/* Convert CIFS ACL to POSIX form */
static int parse_sec_desc(struct cifs_sb_info *cifs_sb,
struct cifs_ntsd *pntsd, int acl_len, struct cifs_fattr *fattr)
{
int rc = 0;
struct cifs_sid *owner_sid_ptr, *group_sid_ptr;
struct cifs_acl *dacl_ptr; /* no need for SACL ptr */
char *end_of_acl = ((char *)pntsd) + acl_len;
__u32 dacloffset;
if (pntsd == NULL)
return -EIO;
owner_sid_ptr = (struct cifs_sid *)((char *)pntsd +
le32_to_cpu(pntsd->osidoffset));
group_sid_ptr = (struct cifs_sid *)((char *)pntsd +
le32_to_cpu(pntsd->gsidoffset));
dacloffset = le32_to_cpu(pntsd->dacloffset);
dacl_ptr = (struct cifs_acl *)((char *)pntsd + dacloffset);
cifs_dbg(NOISY, "revision %d type 0x%x ooffset 0x%x goffset 0x%x sacloffset 0x%x dacloffset 0x%x\n",
pntsd->revision, pntsd->type, le32_to_cpu(pntsd->osidoffset),
le32_to_cpu(pntsd->gsidoffset),
le32_to_cpu(pntsd->sacloffset), dacloffset);
/* cifs_dump_mem("owner_sid: ", owner_sid_ptr, 64); */
rc = parse_sid(owner_sid_ptr, end_of_acl);
if (rc) {
cifs_dbg(FYI, "%s: Error %d parsing Owner SID\n", __func__, rc);
return rc;
}
rc = sid_to_id(cifs_sb, owner_sid_ptr, fattr, SIDOWNER);
if (rc) {
cifs_dbg(FYI, "%s: Error %d mapping Owner SID to uid\n",
__func__, rc);
return rc;
}
rc = parse_sid(group_sid_ptr, end_of_acl);
if (rc) {
cifs_dbg(FYI, "%s: Error %d mapping Owner SID to gid\n",
__func__, rc);
return rc;
}
rc = sid_to_id(cifs_sb, group_sid_ptr, fattr, SIDGROUP);
if (rc) {
cifs_dbg(FYI, "%s: Error %d mapping Group SID to gid\n",
__func__, rc);
return rc;
}
if (dacloffset)
parse_dacl(dacl_ptr, end_of_acl, owner_sid_ptr,
group_sid_ptr, fattr);
else
cifs_dbg(FYI, "no ACL\n"); /* BB grant all or default perms? */
return rc;
}
/* Convert permission bits from mode to equivalent CIFS ACL */
static int build_sec_desc(struct cifs_ntsd *pntsd, struct cifs_ntsd *pnntsd,
__u32 secdesclen, __u64 nmode, kuid_t uid, kgid_t gid, int *aclflag)
{
int rc = 0;
__u32 dacloffset;
__u32 ndacloffset;
__u32 sidsoffset;
struct cifs_sid *owner_sid_ptr, *group_sid_ptr;
struct cifs_sid *nowner_sid_ptr, *ngroup_sid_ptr;
struct cifs_acl *dacl_ptr = NULL; /* no need for SACL ptr */
struct cifs_acl *ndacl_ptr = NULL; /* no need for SACL ptr */
if (nmode != NO_CHANGE_64) { /* chmod */
owner_sid_ptr = (struct cifs_sid *)((char *)pntsd +
le32_to_cpu(pntsd->osidoffset));
group_sid_ptr = (struct cifs_sid *)((char *)pntsd +
le32_to_cpu(pntsd->gsidoffset));
dacloffset = le32_to_cpu(pntsd->dacloffset);
dacl_ptr = (struct cifs_acl *)((char *)pntsd + dacloffset);
ndacloffset = sizeof(struct cifs_ntsd);
ndacl_ptr = (struct cifs_acl *)((char *)pnntsd + ndacloffset);
ndacl_ptr->revision = dacl_ptr->revision;
ndacl_ptr->size = 0;
ndacl_ptr->num_aces = 0;
rc = set_chmod_dacl(ndacl_ptr, owner_sid_ptr, group_sid_ptr,
nmode);
sidsoffset = ndacloffset + le16_to_cpu(ndacl_ptr->size);
/* copy sec desc control portion & owner and group sids */
copy_sec_desc(pntsd, pnntsd, sidsoffset);
*aclflag = CIFS_ACL_DACL;
} else {
memcpy(pnntsd, pntsd, secdesclen);
if (uid_valid(uid)) { /* chown */
uid_t id;
owner_sid_ptr = (struct cifs_sid *)((char *)pnntsd +
le32_to_cpu(pnntsd->osidoffset));
nowner_sid_ptr = kmalloc(sizeof(struct cifs_sid),
GFP_KERNEL);
if (!nowner_sid_ptr)
return -ENOMEM;
id = from_kuid(&init_user_ns, uid);
rc = id_to_sid(id, SIDOWNER, nowner_sid_ptr);
if (rc) {
cifs_dbg(FYI, "%s: Mapping error %d for owner id %d\n",
__func__, rc, id);
kfree(nowner_sid_ptr);
return rc;
}
cifs_copy_sid(owner_sid_ptr, nowner_sid_ptr);
kfree(nowner_sid_ptr);
*aclflag = CIFS_ACL_OWNER;
}
if (gid_valid(gid)) { /* chgrp */
gid_t id;
group_sid_ptr = (struct cifs_sid *)((char *)pnntsd +
le32_to_cpu(pnntsd->gsidoffset));
ngroup_sid_ptr = kmalloc(sizeof(struct cifs_sid),
GFP_KERNEL);
if (!ngroup_sid_ptr)
return -ENOMEM;
id = from_kgid(&init_user_ns, gid);
rc = id_to_sid(id, SIDGROUP, ngroup_sid_ptr);
if (rc) {
cifs_dbg(FYI, "%s: Mapping error %d for group id %d\n",
__func__, rc, id);
kfree(ngroup_sid_ptr);
return rc;
}
cifs_copy_sid(group_sid_ptr, ngroup_sid_ptr);
kfree(ngroup_sid_ptr);
*aclflag = CIFS_ACL_GROUP;
}
}
return rc;
}
struct cifs_ntsd *get_cifs_acl_by_fid(struct cifs_sb_info *cifs_sb,
const struct cifs_fid *cifsfid, u32 *pacllen)
{
struct cifs_ntsd *pntsd = NULL;
unsigned int xid;
int rc;
struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
if (IS_ERR(tlink))
return ERR_CAST(tlink);
xid = get_xid();
rc = CIFSSMBGetCIFSACL(xid, tlink_tcon(tlink), cifsfid->netfid, &pntsd,
pacllen);
free_xid(xid);
cifs_put_tlink(tlink);
cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
if (rc)
return ERR_PTR(rc);
return pntsd;
}
static struct cifs_ntsd *get_cifs_acl_by_path(struct cifs_sb_info *cifs_sb,
const char *path, u32 *pacllen)
{
struct cifs_ntsd *pntsd = NULL;
int oplock = 0;
unsigned int xid;
int rc, create_options = 0;
struct cifs_tcon *tcon;
struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
struct cifs_fid fid;
struct cifs_open_parms oparms;
if (IS_ERR(tlink))
return ERR_CAST(tlink);
tcon = tlink_tcon(tlink);
xid = get_xid();
if (backup_cred(cifs_sb))
create_options |= CREATE_OPEN_BACKUP_INTENT;
oparms.tcon = tcon;
oparms.cifs_sb = cifs_sb;
oparms.desired_access = READ_CONTROL;
oparms.create_options = create_options;
oparms.disposition = FILE_OPEN;
oparms.path = path;
oparms.fid = &fid;
oparms.reconnect = false;
rc = CIFS_open(xid, &oparms, &oplock, NULL);
if (!rc) {
rc = CIFSSMBGetCIFSACL(xid, tcon, fid.netfid, &pntsd, pacllen);
CIFSSMBClose(xid, tcon, fid.netfid);
}
cifs_put_tlink(tlink);
free_xid(xid);
cifs_dbg(FYI, "%s: rc = %d ACL len %d\n", __func__, rc, *pacllen);
if (rc)
return ERR_PTR(rc);
return pntsd;
}
/* Retrieve an ACL from the server */
struct cifs_ntsd *get_cifs_acl(struct cifs_sb_info *cifs_sb,
struct inode *inode, const char *path,
u32 *pacllen)
{
struct cifs_ntsd *pntsd = NULL;
struct cifsFileInfo *open_file = NULL;
if (inode)
open_file = find_readable_file(CIFS_I(inode), true);
if (!open_file)
return get_cifs_acl_by_path(cifs_sb, path, pacllen);
pntsd = get_cifs_acl_by_fid(cifs_sb, &open_file->fid, pacllen);
cifsFileInfo_put(open_file);
return pntsd;
}
/* Set an ACL on the server */
int set_cifs_acl(struct cifs_ntsd *pnntsd, __u32 acllen,
struct inode *inode, const char *path, int aclflag)
{
int oplock = 0;
unsigned int xid;
int rc, access_flags, create_options = 0;
struct cifs_tcon *tcon;
struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
struct cifs_fid fid;
struct cifs_open_parms oparms;
if (IS_ERR(tlink))
return PTR_ERR(tlink);
tcon = tlink_tcon(tlink);
xid = get_xid();
if (backup_cred(cifs_sb))
create_options |= CREATE_OPEN_BACKUP_INTENT;
if (aclflag == CIFS_ACL_OWNER || aclflag == CIFS_ACL_GROUP)
access_flags = WRITE_OWNER;
else
access_flags = WRITE_DAC;
oparms.tcon = tcon;
oparms.cifs_sb = cifs_sb;
oparms.desired_access = access_flags;
oparms.create_options = create_options;
oparms.disposition = FILE_OPEN;
oparms.path = path;
oparms.fid = &fid;
oparms.reconnect = false;
rc = CIFS_open(xid, &oparms, &oplock, NULL);
if (rc) {
cifs_dbg(VFS, "Unable to open file to set ACL\n");
goto out;
}
rc = CIFSSMBSetCIFSACL(xid, tcon, fid.netfid, pnntsd, acllen, aclflag);
cifs_dbg(NOISY, "SetCIFSACL rc = %d\n", rc);
CIFSSMBClose(xid, tcon, fid.netfid);
out:
free_xid(xid);
cifs_put_tlink(tlink);
return rc;
}
/* Translate the CIFS ACL (simlar to NTFS ACL) for a file into mode bits */
int
cifs_acl_to_fattr(struct cifs_sb_info *cifs_sb, struct cifs_fattr *fattr,
struct inode *inode, const char *path,
const struct cifs_fid *pfid)
{
struct cifs_ntsd *pntsd = NULL;
u32 acllen = 0;
int rc = 0;
struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
struct cifs_tcon *tcon;
cifs_dbg(NOISY, "converting ACL to mode for %s\n", path);
if (IS_ERR(tlink))
return PTR_ERR(tlink);
tcon = tlink_tcon(tlink);
if (pfid && (tcon->ses->server->ops->get_acl_by_fid))
pntsd = tcon->ses->server->ops->get_acl_by_fid(cifs_sb, pfid,
&acllen);
else if (tcon->ses->server->ops->get_acl)
pntsd = tcon->ses->server->ops->get_acl(cifs_sb, inode, path,
&acllen);
else {
cifs_put_tlink(tlink);
return -EOPNOTSUPP;
}
/* if we can retrieve the ACL, now parse Access Control Entries, ACEs */
if (IS_ERR(pntsd)) {
rc = PTR_ERR(pntsd);
cifs_dbg(VFS, "%s: error %d getting sec desc\n", __func__, rc);
} else {
rc = parse_sec_desc(cifs_sb, pntsd, acllen, fattr);
kfree(pntsd);
if (rc)
cifs_dbg(VFS, "parse sec desc failed rc = %d\n", rc);
}
cifs_put_tlink(tlink);
return rc;
}
/* Convert mode bits to an ACL so we can update the ACL on the server */
int
id_mode_to_cifs_acl(struct inode *inode, const char *path, __u64 nmode,
kuid_t uid, kgid_t gid)
{
int rc = 0;
int aclflag = CIFS_ACL_DACL; /* default flag to set */
__u32 secdesclen = 0;
struct cifs_ntsd *pntsd = NULL; /* acl obtained from server */
struct cifs_ntsd *pnntsd = NULL; /* modified acl to be sent to server */
struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
struct tcon_link *tlink = cifs_sb_tlink(cifs_sb);
struct cifs_tcon *tcon;
if (IS_ERR(tlink))
return PTR_ERR(tlink);
tcon = tlink_tcon(tlink);
cifs_dbg(NOISY, "set ACL from mode for %s\n", path);
/* Get the security descriptor */
if (tcon->ses->server->ops->get_acl == NULL) {
cifs_put_tlink(tlink);
return -EOPNOTSUPP;
}
pntsd = tcon->ses->server->ops->get_acl(cifs_sb, inode, path,
&secdesclen);
if (IS_ERR(pntsd)) {
rc = PTR_ERR(pntsd);
cifs_dbg(VFS, "%s: error %d getting sec desc\n", __func__, rc);
cifs_put_tlink(tlink);
return rc;
}
/*
* Add three ACEs for owner, group, everyone getting rid of other ACEs
* as chmod disables ACEs and set the security descriptor. Allocate
* memory for the smb header, set security descriptor request security
* descriptor parameters, and secuirty descriptor itself
*/
secdesclen = max_t(u32, secdesclen, DEFAULT_SEC_DESC_LEN);
pnntsd = kmalloc(secdesclen, GFP_KERNEL);
if (!pnntsd) {
kfree(pntsd);
cifs_put_tlink(tlink);
return -ENOMEM;
}
rc = build_sec_desc(pntsd, pnntsd, secdesclen, nmode, uid, gid,
&aclflag);
cifs_dbg(NOISY, "build_sec_desc rc: %d\n", rc);
if (tcon->ses->server->ops->set_acl == NULL)
rc = -EOPNOTSUPP;
if (!rc) {
/* Set the security descriptor */
rc = tcon->ses->server->ops->set_acl(pnntsd, secdesclen, inode,
path, aclflag);
cifs_dbg(NOISY, "set_cifs_acl rc: %d\n", rc);
}
cifs_put_tlink(tlink);
kfree(pnntsd);
kfree(pntsd);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3060_3 |
crossvul-cpp_data_good_3060_17 | /*
* Copyright (C) 2010 IBM Corporation
*
* Author:
* David Safford <safford@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* See Documentation/security/keys-trusted-encrypted.txt
*/
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/parser.h>
#include <linux/string.h>
#include <linux/err.h>
#include <keys/user-type.h>
#include <keys/trusted-type.h>
#include <linux/key-type.h>
#include <linux/rcupdate.h>
#include <linux/crypto.h>
#include <crypto/hash.h>
#include <crypto/sha.h>
#include <linux/capability.h>
#include <linux/tpm.h>
#include <linux/tpm_command.h>
#include "trusted.h"
static const char hmac_alg[] = "hmac(sha1)";
static const char hash_alg[] = "sha1";
struct sdesc {
struct shash_desc shash;
char ctx[];
};
static struct crypto_shash *hashalg;
static struct crypto_shash *hmacalg;
static struct sdesc *init_sdesc(struct crypto_shash *alg)
{
struct sdesc *sdesc;
int size;
size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
sdesc = kmalloc(size, GFP_KERNEL);
if (!sdesc)
return ERR_PTR(-ENOMEM);
sdesc->shash.tfm = alg;
sdesc->shash.flags = 0x0;
return sdesc;
}
static int TSS_sha1(const unsigned char *data, unsigned int datalen,
unsigned char *digest)
{
struct sdesc *sdesc;
int ret;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
kfree(sdesc);
return ret;
}
static int TSS_rawhmac(unsigned char *digest, const unsigned char *key,
unsigned int keylen, ...)
{
struct sdesc *sdesc;
va_list argp;
unsigned int dlen;
unsigned char *data;
int ret;
sdesc = init_sdesc(hmacalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hmac_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_setkey(hmacalg, key, keylen);
if (ret < 0)
goto out;
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
va_start(argp, keylen);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
data = va_arg(argp, unsigned char *);
if (data == NULL) {
ret = -EINVAL;
break;
}
ret = crypto_shash_update(&sdesc->shash, data, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, digest);
out:
kfree(sdesc);
return ret;
}
/*
* calculate authorization info fields to send to TPM
*/
static int TSS_authhmac(unsigned char *digest, const unsigned char *key,
unsigned int keylen, unsigned char *h1,
unsigned char *h2, unsigned char h3, ...)
{
unsigned char paramdigest[SHA1_DIGEST_SIZE];
struct sdesc *sdesc;
unsigned int dlen;
unsigned char *data;
unsigned char c;
int ret;
va_list argp;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
c = h3;
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
va_start(argp, h3);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
data = va_arg(argp, unsigned char *);
if (!data) {
ret = -EINVAL;
break;
}
ret = crypto_shash_update(&sdesc->shash, data, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, paramdigest);
if (!ret)
ret = TSS_rawhmac(digest, key, keylen, SHA1_DIGEST_SIZE,
paramdigest, TPM_NONCE_SIZE, h1,
TPM_NONCE_SIZE, h2, 1, &c, 0, 0);
out:
kfree(sdesc);
return ret;
}
/*
* verify the AUTH1_COMMAND (Seal) result from TPM
*/
static int TSS_checkhmac1(unsigned char *buffer,
const uint32_t command,
const unsigned char *ononce,
const unsigned char *key,
unsigned int keylen, ...)
{
uint32_t bufsize;
uint16_t tag;
uint32_t ordinal;
uint32_t result;
unsigned char *enonce;
unsigned char *continueflag;
unsigned char *authdata;
unsigned char testhmac[SHA1_DIGEST_SIZE];
unsigned char paramdigest[SHA1_DIGEST_SIZE];
struct sdesc *sdesc;
unsigned int dlen;
unsigned int dpos;
va_list argp;
int ret;
bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
tag = LOAD16(buffer, 0);
ordinal = command;
result = LOAD32N(buffer, TPM_RETURN_OFFSET);
if (tag == TPM_TAG_RSP_COMMAND)
return 0;
if (tag != TPM_TAG_RSP_AUTH1_COMMAND)
return -EINVAL;
authdata = buffer + bufsize - SHA1_DIGEST_SIZE;
continueflag = authdata - 1;
enonce = continueflag - TPM_NONCE_SIZE;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
sizeof result);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
sizeof ordinal);
if (ret < 0)
goto out;
va_start(argp, keylen);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
dpos = va_arg(argp, unsigned int);
ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, paramdigest);
if (ret < 0)
goto out;
ret = TSS_rawhmac(testhmac, key, keylen, SHA1_DIGEST_SIZE, paramdigest,
TPM_NONCE_SIZE, enonce, TPM_NONCE_SIZE, ononce,
1, continueflag, 0, 0);
if (ret < 0)
goto out;
if (memcmp(testhmac, authdata, SHA1_DIGEST_SIZE))
ret = -EINVAL;
out:
kfree(sdesc);
return ret;
}
/*
* verify the AUTH2_COMMAND (unseal) result from TPM
*/
static int TSS_checkhmac2(unsigned char *buffer,
const uint32_t command,
const unsigned char *ononce,
const unsigned char *key1,
unsigned int keylen1,
const unsigned char *key2,
unsigned int keylen2, ...)
{
uint32_t bufsize;
uint16_t tag;
uint32_t ordinal;
uint32_t result;
unsigned char *enonce1;
unsigned char *continueflag1;
unsigned char *authdata1;
unsigned char *enonce2;
unsigned char *continueflag2;
unsigned char *authdata2;
unsigned char testhmac1[SHA1_DIGEST_SIZE];
unsigned char testhmac2[SHA1_DIGEST_SIZE];
unsigned char paramdigest[SHA1_DIGEST_SIZE];
struct sdesc *sdesc;
unsigned int dlen;
unsigned int dpos;
va_list argp;
int ret;
bufsize = LOAD32(buffer, TPM_SIZE_OFFSET);
tag = LOAD16(buffer, 0);
ordinal = command;
result = LOAD32N(buffer, TPM_RETURN_OFFSET);
if (tag == TPM_TAG_RSP_COMMAND)
return 0;
if (tag != TPM_TAG_RSP_AUTH2_COMMAND)
return -EINVAL;
authdata1 = buffer + bufsize - (SHA1_DIGEST_SIZE + 1
+ SHA1_DIGEST_SIZE + SHA1_DIGEST_SIZE);
authdata2 = buffer + bufsize - (SHA1_DIGEST_SIZE);
continueflag1 = authdata1 - 1;
continueflag2 = authdata2 - 1;
enonce1 = continueflag1 - TPM_NONCE_SIZE;
enonce2 = continueflag2 - TPM_NONCE_SIZE;
sdesc = init_sdesc(hashalg);
if (IS_ERR(sdesc)) {
pr_info("trusted_key: can't alloc %s\n", hash_alg);
return PTR_ERR(sdesc);
}
ret = crypto_shash_init(&sdesc->shash);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&result,
sizeof result);
if (ret < 0)
goto out;
ret = crypto_shash_update(&sdesc->shash, (const u8 *)&ordinal,
sizeof ordinal);
if (ret < 0)
goto out;
va_start(argp, keylen2);
for (;;) {
dlen = va_arg(argp, unsigned int);
if (dlen == 0)
break;
dpos = va_arg(argp, unsigned int);
ret = crypto_shash_update(&sdesc->shash, buffer + dpos, dlen);
if (ret < 0)
break;
}
va_end(argp);
if (!ret)
ret = crypto_shash_final(&sdesc->shash, paramdigest);
if (ret < 0)
goto out;
ret = TSS_rawhmac(testhmac1, key1, keylen1, SHA1_DIGEST_SIZE,
paramdigest, TPM_NONCE_SIZE, enonce1,
TPM_NONCE_SIZE, ononce, 1, continueflag1, 0, 0);
if (ret < 0)
goto out;
if (memcmp(testhmac1, authdata1, SHA1_DIGEST_SIZE)) {
ret = -EINVAL;
goto out;
}
ret = TSS_rawhmac(testhmac2, key2, keylen2, SHA1_DIGEST_SIZE,
paramdigest, TPM_NONCE_SIZE, enonce2,
TPM_NONCE_SIZE, ononce, 1, continueflag2, 0, 0);
if (ret < 0)
goto out;
if (memcmp(testhmac2, authdata2, SHA1_DIGEST_SIZE))
ret = -EINVAL;
out:
kfree(sdesc);
return ret;
}
/*
* For key specific tpm requests, we will generate and send our
* own TPM command packets using the drivers send function.
*/
static int trusted_tpm_send(const u32 chip_num, unsigned char *cmd,
size_t buflen)
{
int rc;
dump_tpm_buf(cmd);
rc = tpm_send(chip_num, cmd, buflen);
dump_tpm_buf(cmd);
if (rc > 0)
/* Can't return positive return codes values to keyctl */
rc = -EPERM;
return rc;
}
/*
* Lock a trusted key, by extending a selected PCR.
*
* Prevents a trusted key that is sealed to PCRs from being accessed.
* This uses the tpm driver's extend function.
*/
static int pcrlock(const int pcrnum)
{
unsigned char hash[SHA1_DIGEST_SIZE];
int ret;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
ret = tpm_get_random(TPM_ANY_NUM, hash, SHA1_DIGEST_SIZE);
if (ret != SHA1_DIGEST_SIZE)
return ret;
return tpm_pcr_extend(TPM_ANY_NUM, pcrnum, hash) ? -EINVAL : 0;
}
/*
* Create an object specific authorisation protocol (OSAP) session
*/
static int osap(struct tpm_buf *tb, struct osapsess *s,
const unsigned char *key, uint16_t type, uint32_t handle)
{
unsigned char enonce[TPM_NONCE_SIZE];
unsigned char ononce[TPM_NONCE_SIZE];
int ret;
ret = tpm_get_random(TPM_ANY_NUM, ononce, TPM_NONCE_SIZE);
if (ret != TPM_NONCE_SIZE)
return ret;
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_COMMAND);
store32(tb, TPM_OSAP_SIZE);
store32(tb, TPM_ORD_OSAP);
store16(tb, type);
store32(tb, handle);
storebytes(tb, ononce, TPM_NONCE_SIZE);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0)
return ret;
s->handle = LOAD32(tb->data, TPM_DATA_OFFSET);
memcpy(s->enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)]),
TPM_NONCE_SIZE);
memcpy(enonce, &(tb->data[TPM_DATA_OFFSET + sizeof(uint32_t) +
TPM_NONCE_SIZE]), TPM_NONCE_SIZE);
return TSS_rawhmac(s->secret, key, SHA1_DIGEST_SIZE, TPM_NONCE_SIZE,
enonce, TPM_NONCE_SIZE, ononce, 0, 0);
}
/*
* Create an object independent authorisation protocol (oiap) session
*/
static int oiap(struct tpm_buf *tb, uint32_t *handle, unsigned char *nonce)
{
int ret;
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_COMMAND);
store32(tb, TPM_OIAP_SIZE);
store32(tb, TPM_ORD_OIAP);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0)
return ret;
*handle = LOAD32(tb->data, TPM_DATA_OFFSET);
memcpy(nonce, &tb->data[TPM_DATA_OFFSET + sizeof(uint32_t)],
TPM_NONCE_SIZE);
return 0;
}
struct tpm_digests {
unsigned char encauth[SHA1_DIGEST_SIZE];
unsigned char pubauth[SHA1_DIGEST_SIZE];
unsigned char xorwork[SHA1_DIGEST_SIZE * 2];
unsigned char xorhash[SHA1_DIGEST_SIZE];
unsigned char nonceodd[TPM_NONCE_SIZE];
};
/*
* Have the TPM seal(encrypt) the trusted key, possibly based on
* Platform Configuration Registers (PCRs). AUTH1 for sealing key.
*/
static int tpm_seal(struct tpm_buf *tb, uint16_t keytype,
uint32_t keyhandle, const unsigned char *keyauth,
const unsigned char *data, uint32_t datalen,
unsigned char *blob, uint32_t *bloblen,
const unsigned char *blobauth,
const unsigned char *pcrinfo, uint32_t pcrinfosize)
{
struct osapsess sess;
struct tpm_digests *td;
unsigned char cont;
uint32_t ordinal;
uint32_t pcrsize;
uint32_t datsize;
int sealinfosize;
int encdatasize;
int storedsize;
int ret;
int i;
/* alloc some work space for all the hashes */
td = kmalloc(sizeof *td, GFP_KERNEL);
if (!td)
return -ENOMEM;
/* get session for sealing key */
ret = osap(tb, &sess, keyauth, keytype, keyhandle);
if (ret < 0)
goto out;
dump_sess(&sess);
/* calculate encrypted authorization value */
memcpy(td->xorwork, sess.secret, SHA1_DIGEST_SIZE);
memcpy(td->xorwork + SHA1_DIGEST_SIZE, sess.enonce, SHA1_DIGEST_SIZE);
ret = TSS_sha1(td->xorwork, SHA1_DIGEST_SIZE * 2, td->xorhash);
if (ret < 0)
goto out;
ret = tpm_get_random(TPM_ANY_NUM, td->nonceodd, TPM_NONCE_SIZE);
if (ret != TPM_NONCE_SIZE)
goto out;
ordinal = htonl(TPM_ORD_SEAL);
datsize = htonl(datalen);
pcrsize = htonl(pcrinfosize);
cont = 0;
/* encrypt data authorization key */
for (i = 0; i < SHA1_DIGEST_SIZE; ++i)
td->encauth[i] = td->xorhash[i] ^ blobauth[i];
/* calculate authorization HMAC value */
if (pcrinfosize == 0) {
/* no pcr info specified */
ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
sess.enonce, td->nonceodd, cont,
sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
td->encauth, sizeof(uint32_t), &pcrsize,
sizeof(uint32_t), &datsize, datalen, data, 0,
0);
} else {
/* pcr info specified */
ret = TSS_authhmac(td->pubauth, sess.secret, SHA1_DIGEST_SIZE,
sess.enonce, td->nonceodd, cont,
sizeof(uint32_t), &ordinal, SHA1_DIGEST_SIZE,
td->encauth, sizeof(uint32_t), &pcrsize,
pcrinfosize, pcrinfo, sizeof(uint32_t),
&datsize, datalen, data, 0, 0);
}
if (ret < 0)
goto out;
/* build and send the TPM request packet */
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_AUTH1_COMMAND);
store32(tb, TPM_SEAL_SIZE + pcrinfosize + datalen);
store32(tb, TPM_ORD_SEAL);
store32(tb, keyhandle);
storebytes(tb, td->encauth, SHA1_DIGEST_SIZE);
store32(tb, pcrinfosize);
storebytes(tb, pcrinfo, pcrinfosize);
store32(tb, datalen);
storebytes(tb, data, datalen);
store32(tb, sess.handle);
storebytes(tb, td->nonceodd, TPM_NONCE_SIZE);
store8(tb, cont);
storebytes(tb, td->pubauth, SHA1_DIGEST_SIZE);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0)
goto out;
/* calculate the size of the returned Blob */
sealinfosize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t));
encdatasize = LOAD32(tb->data, TPM_DATA_OFFSET + sizeof(uint32_t) +
sizeof(uint32_t) + sealinfosize);
storedsize = sizeof(uint32_t) + sizeof(uint32_t) + sealinfosize +
sizeof(uint32_t) + encdatasize;
/* check the HMAC in the response */
ret = TSS_checkhmac1(tb->data, ordinal, td->nonceodd, sess.secret,
SHA1_DIGEST_SIZE, storedsize, TPM_DATA_OFFSET, 0,
0);
/* copy the returned blob to caller */
if (!ret) {
memcpy(blob, tb->data + TPM_DATA_OFFSET, storedsize);
*bloblen = storedsize;
}
out:
kfree(td);
return ret;
}
/*
* use the AUTH2_COMMAND form of unseal, to authorize both key and blob
*/
static int tpm_unseal(struct tpm_buf *tb,
uint32_t keyhandle, const unsigned char *keyauth,
const unsigned char *blob, int bloblen,
const unsigned char *blobauth,
unsigned char *data, unsigned int *datalen)
{
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char enonce1[TPM_NONCE_SIZE];
unsigned char enonce2[TPM_NONCE_SIZE];
unsigned char authdata1[SHA1_DIGEST_SIZE];
unsigned char authdata2[SHA1_DIGEST_SIZE];
uint32_t authhandle1 = 0;
uint32_t authhandle2 = 0;
unsigned char cont = 0;
uint32_t ordinal;
uint32_t keyhndl;
int ret;
/* sessions for unsealing key and data */
ret = oiap(tb, &authhandle1, enonce1);
if (ret < 0) {
pr_info("trusted_key: oiap failed (%d)\n", ret);
return ret;
}
ret = oiap(tb, &authhandle2, enonce2);
if (ret < 0) {
pr_info("trusted_key: oiap failed (%d)\n", ret);
return ret;
}
ordinal = htonl(TPM_ORD_UNSEAL);
keyhndl = htonl(SRKHANDLE);
ret = tpm_get_random(TPM_ANY_NUM, nonceodd, TPM_NONCE_SIZE);
if (ret != TPM_NONCE_SIZE) {
pr_info("trusted_key: tpm_get_random failed (%d)\n", ret);
return ret;
}
ret = TSS_authhmac(authdata1, keyauth, TPM_NONCE_SIZE,
enonce1, nonceodd, cont, sizeof(uint32_t),
&ordinal, bloblen, blob, 0, 0);
if (ret < 0)
return ret;
ret = TSS_authhmac(authdata2, blobauth, TPM_NONCE_SIZE,
enonce2, nonceodd, cont, sizeof(uint32_t),
&ordinal, bloblen, blob, 0, 0);
if (ret < 0)
return ret;
/* build and send TPM request packet */
INIT_BUF(tb);
store16(tb, TPM_TAG_RQU_AUTH2_COMMAND);
store32(tb, TPM_UNSEAL_SIZE + bloblen);
store32(tb, TPM_ORD_UNSEAL);
store32(tb, keyhandle);
storebytes(tb, blob, bloblen);
store32(tb, authhandle1);
storebytes(tb, nonceodd, TPM_NONCE_SIZE);
store8(tb, cont);
storebytes(tb, authdata1, SHA1_DIGEST_SIZE);
store32(tb, authhandle2);
storebytes(tb, nonceodd, TPM_NONCE_SIZE);
store8(tb, cont);
storebytes(tb, authdata2, SHA1_DIGEST_SIZE);
ret = trusted_tpm_send(TPM_ANY_NUM, tb->data, MAX_BUF_SIZE);
if (ret < 0) {
pr_info("trusted_key: authhmac failed (%d)\n", ret);
return ret;
}
*datalen = LOAD32(tb->data, TPM_DATA_OFFSET);
ret = TSS_checkhmac2(tb->data, ordinal, nonceodd,
keyauth, SHA1_DIGEST_SIZE,
blobauth, SHA1_DIGEST_SIZE,
sizeof(uint32_t), TPM_DATA_OFFSET,
*datalen, TPM_DATA_OFFSET + sizeof(uint32_t), 0,
0);
if (ret < 0) {
pr_info("trusted_key: TSS_checkhmac2 failed (%d)\n", ret);
return ret;
}
memcpy(data, tb->data + TPM_DATA_OFFSET + sizeof(uint32_t), *datalen);
return 0;
}
/*
* Have the TPM seal(encrypt) the symmetric key
*/
static int key_seal(struct trusted_key_payload *p,
struct trusted_key_options *o)
{
struct tpm_buf *tb;
int ret;
tb = kzalloc(sizeof *tb, GFP_KERNEL);
if (!tb)
return -ENOMEM;
/* include migratable flag at end of sealed key */
p->key[p->key_len] = p->migratable;
ret = tpm_seal(tb, o->keytype, o->keyhandle, o->keyauth,
p->key, p->key_len + 1, p->blob, &p->blob_len,
o->blobauth, o->pcrinfo, o->pcrinfo_len);
if (ret < 0)
pr_info("trusted_key: srkseal failed (%d)\n", ret);
kfree(tb);
return ret;
}
/*
* Have the TPM unseal(decrypt) the symmetric key
*/
static int key_unseal(struct trusted_key_payload *p,
struct trusted_key_options *o)
{
struct tpm_buf *tb;
int ret;
tb = kzalloc(sizeof *tb, GFP_KERNEL);
if (!tb)
return -ENOMEM;
ret = tpm_unseal(tb, o->keyhandle, o->keyauth, p->blob, p->blob_len,
o->blobauth, p->key, &p->key_len);
if (ret < 0)
pr_info("trusted_key: srkunseal failed (%d)\n", ret);
else
/* pull migratable flag out of sealed key */
p->migratable = p->key[--p->key_len];
kfree(tb);
return ret;
}
enum {
Opt_err = -1,
Opt_new, Opt_load, Opt_update,
Opt_keyhandle, Opt_keyauth, Opt_blobauth,
Opt_pcrinfo, Opt_pcrlock, Opt_migratable
};
static const match_table_t key_tokens = {
{Opt_new, "new"},
{Opt_load, "load"},
{Opt_update, "update"},
{Opt_keyhandle, "keyhandle=%s"},
{Opt_keyauth, "keyauth=%s"},
{Opt_blobauth, "blobauth=%s"},
{Opt_pcrinfo, "pcrinfo=%s"},
{Opt_pcrlock, "pcrlock=%s"},
{Opt_migratable, "migratable=%s"},
{Opt_err, NULL}
};
/* can have zero or more token= options */
static int getoptions(char *c, struct trusted_key_payload *pay,
struct trusted_key_options *opt)
{
substring_t args[MAX_OPT_ARGS];
char *p = c;
int token;
int res;
unsigned long handle;
unsigned long lock;
while ((p = strsep(&c, " \t"))) {
if (*p == '\0' || *p == ' ' || *p == '\t')
continue;
token = match_token(p, key_tokens, args);
switch (token) {
case Opt_pcrinfo:
opt->pcrinfo_len = strlen(args[0].from) / 2;
if (opt->pcrinfo_len > MAX_PCRINFO_SIZE)
return -EINVAL;
res = hex2bin(opt->pcrinfo, args[0].from,
opt->pcrinfo_len);
if (res < 0)
return -EINVAL;
break;
case Opt_keyhandle:
res = kstrtoul(args[0].from, 16, &handle);
if (res < 0)
return -EINVAL;
opt->keytype = SEAL_keytype;
opt->keyhandle = handle;
break;
case Opt_keyauth:
if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
return -EINVAL;
res = hex2bin(opt->keyauth, args[0].from,
SHA1_DIGEST_SIZE);
if (res < 0)
return -EINVAL;
break;
case Opt_blobauth:
if (strlen(args[0].from) != 2 * SHA1_DIGEST_SIZE)
return -EINVAL;
res = hex2bin(opt->blobauth, args[0].from,
SHA1_DIGEST_SIZE);
if (res < 0)
return -EINVAL;
break;
case Opt_migratable:
if (*args[0].from == '0')
pay->migratable = 0;
else
return -EINVAL;
break;
case Opt_pcrlock:
res = kstrtoul(args[0].from, 10, &lock);
if (res < 0)
return -EINVAL;
opt->pcrlock = lock;
break;
default:
return -EINVAL;
}
}
return 0;
}
/*
* datablob_parse - parse the keyctl data and fill in the
* payload and options structures
*
* On success returns 0, otherwise -EINVAL.
*/
static int datablob_parse(char *datablob, struct trusted_key_payload *p,
struct trusted_key_options *o)
{
substring_t args[MAX_OPT_ARGS];
long keylen;
int ret = -EINVAL;
int key_cmd;
char *c;
/* main command */
c = strsep(&datablob, " \t");
if (!c)
return -EINVAL;
key_cmd = match_token(c, key_tokens, args);
switch (key_cmd) {
case Opt_new:
/* first argument is key size */
c = strsep(&datablob, " \t");
if (!c)
return -EINVAL;
ret = kstrtol(c, 10, &keylen);
if (ret < 0 || keylen < MIN_KEY_SIZE || keylen > MAX_KEY_SIZE)
return -EINVAL;
p->key_len = keylen;
ret = getoptions(datablob, p, o);
if (ret < 0)
return ret;
ret = Opt_new;
break;
case Opt_load:
/* first argument is sealed blob */
c = strsep(&datablob, " \t");
if (!c)
return -EINVAL;
p->blob_len = strlen(c) / 2;
if (p->blob_len > MAX_BLOB_SIZE)
return -EINVAL;
ret = hex2bin(p->blob, c, p->blob_len);
if (ret < 0)
return -EINVAL;
ret = getoptions(datablob, p, o);
if (ret < 0)
return ret;
ret = Opt_load;
break;
case Opt_update:
/* all arguments are options */
ret = getoptions(datablob, p, o);
if (ret < 0)
return ret;
ret = Opt_update;
break;
case Opt_err:
return -EINVAL;
break;
}
return ret;
}
static struct trusted_key_options *trusted_options_alloc(void)
{
struct trusted_key_options *options;
options = kzalloc(sizeof *options, GFP_KERNEL);
if (options) {
/* set any non-zero defaults */
options->keytype = SRK_keytype;
options->keyhandle = SRKHANDLE;
}
return options;
}
static struct trusted_key_payload *trusted_payload_alloc(struct key *key)
{
struct trusted_key_payload *p = NULL;
int ret;
ret = key_payload_reserve(key, sizeof *p);
if (ret < 0)
return p;
p = kzalloc(sizeof *p, GFP_KERNEL);
if (p)
p->migratable = 1; /* migratable by default */
return p;
}
/*
* trusted_instantiate - create a new trusted key
*
* Unseal an existing trusted blob or, for a new key, get a
* random key, then seal and create a trusted key-type key,
* adding it to the specified keyring.
*
* On success, return 0. Otherwise return errno.
*/
static int trusted_instantiate(struct key *key,
struct key_preparsed_payload *prep)
{
struct trusted_key_payload *payload = NULL;
struct trusted_key_options *options = NULL;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
int key_cmd;
size_t key_len;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
options = trusted_options_alloc();
if (!options) {
ret = -ENOMEM;
goto out;
}
payload = trusted_payload_alloc(key);
if (!payload) {
ret = -ENOMEM;
goto out;
}
key_cmd = datablob_parse(datablob, payload, options);
if (key_cmd < 0) {
ret = key_cmd;
goto out;
}
dump_payload(payload);
dump_options(options);
switch (key_cmd) {
case Opt_load:
ret = key_unseal(payload, options);
dump_payload(payload);
dump_options(options);
if (ret < 0)
pr_info("trusted_key: key_unseal failed (%d)\n", ret);
break;
case Opt_new:
key_len = payload->key_len;
ret = tpm_get_random(TPM_ANY_NUM, payload->key, key_len);
if (ret != key_len) {
pr_info("trusted_key: key_create failed (%d)\n", ret);
goto out;
}
ret = key_seal(payload, options);
if (ret < 0)
pr_info("trusted_key: key_seal failed (%d)\n", ret);
break;
default:
ret = -EINVAL;
goto out;
}
if (!ret && options->pcrlock)
ret = pcrlock(options->pcrlock);
out:
kfree(datablob);
kfree(options);
if (!ret)
rcu_assign_keypointer(key, payload);
else
kfree(payload);
return ret;
}
static void trusted_rcu_free(struct rcu_head *rcu)
{
struct trusted_key_payload *p;
p = container_of(rcu, struct trusted_key_payload, rcu);
memset(p->key, 0, p->key_len);
kfree(p);
}
/*
* trusted_update - reseal an existing key with new PCR values
*/
static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct trusted_key_payload *p = key->payload.data;
struct trusted_key_payload *new_p;
struct trusted_key_options *new_o;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
if (!p->migratable)
return -EPERM;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
new_o = trusted_options_alloc();
if (!new_o) {
ret = -ENOMEM;
goto out;
}
new_p = trusted_payload_alloc(key);
if (!new_p) {
ret = -ENOMEM;
goto out;
}
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
ret = datablob_parse(datablob, new_p, new_o);
if (ret != Opt_update) {
ret = -EINVAL;
kfree(new_p);
goto out;
}
/* copy old key values, and reseal with new pcrs */
new_p->migratable = p->migratable;
new_p->key_len = p->key_len;
memcpy(new_p->key, p->key, p->key_len);
dump_payload(p);
dump_payload(new_p);
ret = key_seal(new_p, new_o);
if (ret < 0) {
pr_info("trusted_key: key_seal failed (%d)\n", ret);
kfree(new_p);
goto out;
}
if (new_o->pcrlock) {
ret = pcrlock(new_o->pcrlock);
if (ret < 0) {
pr_info("trusted_key: pcrlock failed (%d)\n", ret);
kfree(new_p);
goto out;
}
}
rcu_assign_keypointer(key, new_p);
call_rcu(&p->rcu, trusted_rcu_free);
out:
kfree(datablob);
kfree(new_o);
return ret;
}
/*
* trusted_read - copy the sealed blob data to userspace in hex.
* On success, return to userspace the trusted key datablob size.
*/
static long trusted_read(const struct key *key, char __user *buffer,
size_t buflen)
{
struct trusted_key_payload *p;
char *ascii_buf;
char *bufp;
int i;
p = rcu_dereference_key(key);
if (!p)
return -EINVAL;
if (!buffer || buflen <= 0)
return 2 * p->blob_len;
ascii_buf = kmalloc(2 * p->blob_len, GFP_KERNEL);
if (!ascii_buf)
return -ENOMEM;
bufp = ascii_buf;
for (i = 0; i < p->blob_len; i++)
bufp = hex_byte_pack(bufp, p->blob[i]);
if ((copy_to_user(buffer, ascii_buf, 2 * p->blob_len)) != 0) {
kfree(ascii_buf);
return -EFAULT;
}
kfree(ascii_buf);
return 2 * p->blob_len;
}
/*
* trusted_destroy - before freeing the key, clear the decrypted data
*/
static void trusted_destroy(struct key *key)
{
struct trusted_key_payload *p = key->payload.data;
if (!p)
return;
memset(p->key, 0, p->key_len);
kfree(key->payload.data);
}
struct key_type key_type_trusted = {
.name = "trusted",
.instantiate = trusted_instantiate,
.update = trusted_update,
.destroy = trusted_destroy,
.describe = user_describe,
.read = trusted_read,
};
EXPORT_SYMBOL_GPL(key_type_trusted);
static void trusted_shash_release(void)
{
if (hashalg)
crypto_free_shash(hashalg);
if (hmacalg)
crypto_free_shash(hmacalg);
}
static int __init trusted_shash_alloc(void)
{
int ret;
hmacalg = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hmacalg)) {
pr_info("trusted_key: could not allocate crypto %s\n",
hmac_alg);
return PTR_ERR(hmacalg);
}
hashalg = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hashalg)) {
pr_info("trusted_key: could not allocate crypto %s\n",
hash_alg);
ret = PTR_ERR(hashalg);
goto hashalg_fail;
}
return 0;
hashalg_fail:
crypto_free_shash(hmacalg);
return ret;
}
static int __init init_trusted(void)
{
int ret;
ret = trusted_shash_alloc();
if (ret < 0)
return ret;
ret = register_key_type(&key_type_trusted);
if (ret < 0)
trusted_shash_release();
return ret;
}
static void __exit cleanup_trusted(void)
{
trusted_shash_release();
unregister_key_type(&key_type_trusted);
}
late_initcall(init_trusted);
module_exit(cleanup_trusted);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3060_17 |
crossvul-cpp_data_good_1432_0 | /*
* mm/mmap.c
*
* Written by obz.
*
* Address space accounting code <alan@lxorguk.ukuu.org.uk>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/backing-dev.h>
#include <linux/mm.h>
#include <linux/vmacache.h>
#include <linux/shm.h>
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/syscalls.h>
#include <linux/capability.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
#include <linux/shmem_fs.h>
#include <linux/profile.h>
#include <linux/export.h>
#include <linux/mount.h>
#include <linux/mempolicy.h>
#include <linux/rmap.h>
#include <linux/mmu_notifier.h>
#include <linux/mmdebug.h>
#include <linux/perf_event.h>
#include <linux/audit.h>
#include <linux/khugepaged.h>
#include <linux/uprobes.h>
#include <linux/rbtree_augmented.h>
#include <linux/notifier.h>
#include <linux/memory.h>
#include <linux/printk.h>
#include <linux/userfaultfd_k.h>
#include <linux/moduleparam.h>
#include <linux/pkeys.h>
#include <linux/oom.h>
#include <linux/uaccess.h>
#include <asm/cacheflush.h>
#include <asm/tlb.h>
#include <asm/mmu_context.h>
#include "internal.h"
#ifndef arch_mmap_check
#define arch_mmap_check(addr, len, flags) (0)
#endif
#ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
#endif
#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
#endif
static bool ignore_rlimit_data;
core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
static void unmap_region(struct mm_struct *mm,
struct vm_area_struct *vma, struct vm_area_struct *prev,
unsigned long start, unsigned long end);
/* description of effects of mapping type and prot in current implementation.
* this is due to the limited x86 page protection hardware. The expected
* behavior is in parens:
*
* map_type prot
* PROT_NONE PROT_READ PROT_WRITE PROT_EXEC
* MAP_SHARED r: (no) no r: (yes) yes r: (no) yes r: (no) yes
* w: (no) no w: (no) no w: (yes) yes w: (no) no
* x: (no) no x: (no) yes x: (no) yes x: (yes) yes
*
* MAP_PRIVATE r: (no) no r: (yes) yes r: (no) yes r: (no) yes
* w: (no) no w: (no) no w: (copy) copy w: (no) no
* x: (no) no x: (no) yes x: (no) yes x: (yes) yes
*
* On arm64, PROT_EXEC has the following behaviour for both MAP_SHARED and
* MAP_PRIVATE:
* r: (no) no
* w: (no) no
* x: (yes) yes
*/
pgprot_t protection_map[16] __ro_after_init = {
__P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
__S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
};
#ifndef CONFIG_ARCH_HAS_FILTER_PGPROT
static inline pgprot_t arch_filter_pgprot(pgprot_t prot)
{
return prot;
}
#endif
pgprot_t vm_get_page_prot(unsigned long vm_flags)
{
pgprot_t ret = __pgprot(pgprot_val(protection_map[vm_flags &
(VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
pgprot_val(arch_vm_get_page_prot(vm_flags)));
return arch_filter_pgprot(ret);
}
EXPORT_SYMBOL(vm_get_page_prot);
static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
{
return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
}
/* Update vma->vm_page_prot to reflect vma->vm_flags. */
void vma_set_page_prot(struct vm_area_struct *vma)
{
unsigned long vm_flags = vma->vm_flags;
pgprot_t vm_page_prot;
vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
if (vma_wants_writenotify(vma, vm_page_prot)) {
vm_flags &= ~VM_SHARED;
vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
}
/* remove_protection_ptes reads vma->vm_page_prot without mmap_sem */
WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
}
/*
* Requires inode->i_mapping->i_mmap_rwsem
*/
static void __remove_shared_vm_struct(struct vm_area_struct *vma,
struct file *file, struct address_space *mapping)
{
if (vma->vm_flags & VM_DENYWRITE)
atomic_inc(&file_inode(file)->i_writecount);
if (vma->vm_flags & VM_SHARED)
mapping_unmap_writable(mapping);
flush_dcache_mmap_lock(mapping);
vma_interval_tree_remove(vma, &mapping->i_mmap);
flush_dcache_mmap_unlock(mapping);
}
/*
* Unlink a file-based vm structure from its interval tree, to hide
* vma from rmap and vmtruncate before freeing its page tables.
*/
void unlink_file_vma(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
if (file) {
struct address_space *mapping = file->f_mapping;
i_mmap_lock_write(mapping);
__remove_shared_vm_struct(vma, file, mapping);
i_mmap_unlock_write(mapping);
}
}
/*
* Close a vm structure and free it, returning the next.
*/
static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
{
struct vm_area_struct *next = vma->vm_next;
might_sleep();
if (vma->vm_ops && vma->vm_ops->close)
vma->vm_ops->close(vma);
if (vma->vm_file)
fput(vma->vm_file);
mpol_put(vma_policy(vma));
vm_area_free(vma);
return next;
}
static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,
struct list_head *uf);
SYSCALL_DEFINE1(brk, unsigned long, brk)
{
unsigned long retval;
unsigned long newbrk, oldbrk, origbrk;
struct mm_struct *mm = current->mm;
struct vm_area_struct *next;
unsigned long min_brk;
bool populate;
bool downgraded = false;
LIST_HEAD(uf);
if (down_write_killable(&mm->mmap_sem))
return -EINTR;
origbrk = mm->brk;
#ifdef CONFIG_COMPAT_BRK
/*
* CONFIG_COMPAT_BRK can still be overridden by setting
* randomize_va_space to 2, which will still cause mm->start_brk
* to be arbitrarily shifted
*/
if (current->brk_randomized)
min_brk = mm->start_brk;
else
min_brk = mm->end_data;
#else
min_brk = mm->start_brk;
#endif
if (brk < min_brk)
goto out;
/*
* Check against rlimit here. If this check is done later after the test
* of oldbrk with newbrk then it can escape the test and let the data
* segment grow beyond its set limit the in case where the limit is
* not page aligned -Ram Gupta
*/
if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
mm->end_data, mm->start_data))
goto out;
newbrk = PAGE_ALIGN(brk);
oldbrk = PAGE_ALIGN(mm->brk);
if (oldbrk == newbrk) {
mm->brk = brk;
goto success;
}
/*
* Always allow shrinking brk.
* __do_munmap() may downgrade mmap_sem to read.
*/
if (brk <= mm->brk) {
int ret;
/*
* mm->brk must to be protected by write mmap_sem so update it
* before downgrading mmap_sem. When __do_munmap() fails,
* mm->brk will be restored from origbrk.
*/
mm->brk = brk;
ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
if (ret < 0) {
mm->brk = origbrk;
goto out;
} else if (ret == 1) {
downgraded = true;
}
goto success;
}
/* Check against existing mmap mappings. */
next = find_vma(mm, oldbrk);
if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
goto out;
/* Ok, looks good - let it rip. */
if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
goto out;
mm->brk = brk;
success:
populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
if (downgraded)
up_read(&mm->mmap_sem);
else
up_write(&mm->mmap_sem);
userfaultfd_unmap_complete(mm, &uf);
if (populate)
mm_populate(oldbrk, newbrk - oldbrk);
return brk;
out:
retval = origbrk;
up_write(&mm->mmap_sem);
return retval;
}
static long vma_compute_subtree_gap(struct vm_area_struct *vma)
{
unsigned long max, prev_end, subtree_gap;
/*
* Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
* allow two stack_guard_gaps between them here, and when choosing
* an unmapped area; whereas when expanding we only require one.
* That's a little inconsistent, but keeps the code here simpler.
*/
max = vm_start_gap(vma);
if (vma->vm_prev) {
prev_end = vm_end_gap(vma->vm_prev);
if (max > prev_end)
max -= prev_end;
else
max = 0;
}
if (vma->vm_rb.rb_left) {
subtree_gap = rb_entry(vma->vm_rb.rb_left,
struct vm_area_struct, vm_rb)->rb_subtree_gap;
if (subtree_gap > max)
max = subtree_gap;
}
if (vma->vm_rb.rb_right) {
subtree_gap = rb_entry(vma->vm_rb.rb_right,
struct vm_area_struct, vm_rb)->rb_subtree_gap;
if (subtree_gap > max)
max = subtree_gap;
}
return max;
}
#ifdef CONFIG_DEBUG_VM_RB
static int browse_rb(struct mm_struct *mm)
{
struct rb_root *root = &mm->mm_rb;
int i = 0, j, bug = 0;
struct rb_node *nd, *pn = NULL;
unsigned long prev = 0, pend = 0;
for (nd = rb_first(root); nd; nd = rb_next(nd)) {
struct vm_area_struct *vma;
vma = rb_entry(nd, struct vm_area_struct, vm_rb);
if (vma->vm_start < prev) {
pr_emerg("vm_start %lx < prev %lx\n",
vma->vm_start, prev);
bug = 1;
}
if (vma->vm_start < pend) {
pr_emerg("vm_start %lx < pend %lx\n",
vma->vm_start, pend);
bug = 1;
}
if (vma->vm_start > vma->vm_end) {
pr_emerg("vm_start %lx > vm_end %lx\n",
vma->vm_start, vma->vm_end);
bug = 1;
}
spin_lock(&mm->page_table_lock);
if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
pr_emerg("free gap %lx, correct %lx\n",
vma->rb_subtree_gap,
vma_compute_subtree_gap(vma));
bug = 1;
}
spin_unlock(&mm->page_table_lock);
i++;
pn = nd;
prev = vma->vm_start;
pend = vma->vm_end;
}
j = 0;
for (nd = pn; nd; nd = rb_prev(nd))
j++;
if (i != j) {
pr_emerg("backwards %d, forwards %d\n", j, i);
bug = 1;
}
return bug ? -1 : i;
}
static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
{
struct rb_node *nd;
for (nd = rb_first(root); nd; nd = rb_next(nd)) {
struct vm_area_struct *vma;
vma = rb_entry(nd, struct vm_area_struct, vm_rb);
VM_BUG_ON_VMA(vma != ignore &&
vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
vma);
}
}
static void validate_mm(struct mm_struct *mm)
{
int bug = 0;
int i = 0;
unsigned long highest_address = 0;
struct vm_area_struct *vma = mm->mmap;
while (vma) {
struct anon_vma *anon_vma = vma->anon_vma;
struct anon_vma_chain *avc;
if (anon_vma) {
anon_vma_lock_read(anon_vma);
list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
anon_vma_interval_tree_verify(avc);
anon_vma_unlock_read(anon_vma);
}
highest_address = vm_end_gap(vma);
vma = vma->vm_next;
i++;
}
if (i != mm->map_count) {
pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
bug = 1;
}
if (highest_address != mm->highest_vm_end) {
pr_emerg("mm->highest_vm_end %lx, found %lx\n",
mm->highest_vm_end, highest_address);
bug = 1;
}
i = browse_rb(mm);
if (i != mm->map_count) {
if (i != -1)
pr_emerg("map_count %d rb %d\n", mm->map_count, i);
bug = 1;
}
VM_BUG_ON_MM(bug, mm);
}
#else
#define validate_mm_rb(root, ignore) do { } while (0)
#define validate_mm(mm) do { } while (0)
#endif
RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,
unsigned long, rb_subtree_gap, vma_compute_subtree_gap)
/*
* Update augmented rbtree rb_subtree_gap values after vma->vm_start or
* vma->vm_prev->vm_end values changed, without modifying the vma's position
* in the rbtree.
*/
static void vma_gap_update(struct vm_area_struct *vma)
{
/*
* As it turns out, RB_DECLARE_CALLBACKS() already created a callback
* function that does exacltly what we want.
*/
vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
}
static inline void vma_rb_insert(struct vm_area_struct *vma,
struct rb_root *root)
{
/* All rb_subtree_gap values must be consistent prior to insertion */
validate_mm_rb(root, NULL);
rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
}
static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
{
/*
* Note rb_erase_augmented is a fairly large inline function,
* so make sure we instantiate it only once with our desired
* augmented rbtree callbacks.
*/
rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
}
static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
struct rb_root *root,
struct vm_area_struct *ignore)
{
/*
* All rb_subtree_gap values must be consistent prior to erase,
* with the possible exception of the "next" vma being erased if
* next->vm_start was reduced.
*/
validate_mm_rb(root, ignore);
__vma_rb_erase(vma, root);
}
static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
struct rb_root *root)
{
/*
* All rb_subtree_gap values must be consistent prior to erase,
* with the possible exception of the vma being erased.
*/
validate_mm_rb(root, vma);
__vma_rb_erase(vma, root);
}
/*
* vma has some anon_vma assigned, and is already inserted on that
* anon_vma's interval trees.
*
* Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
* vma must be removed from the anon_vma's interval trees using
* anon_vma_interval_tree_pre_update_vma().
*
* After the update, the vma will be reinserted using
* anon_vma_interval_tree_post_update_vma().
*
* The entire update must be protected by exclusive mmap_sem and by
* the root anon_vma's mutex.
*/
static inline void
anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
{
struct anon_vma_chain *avc;
list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
}
static inline void
anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
{
struct anon_vma_chain *avc;
list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
}
static int find_vma_links(struct mm_struct *mm, unsigned long addr,
unsigned long end, struct vm_area_struct **pprev,
struct rb_node ***rb_link, struct rb_node **rb_parent)
{
struct rb_node **__rb_link, *__rb_parent, *rb_prev;
__rb_link = &mm->mm_rb.rb_node;
rb_prev = __rb_parent = NULL;
while (*__rb_link) {
struct vm_area_struct *vma_tmp;
__rb_parent = *__rb_link;
vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
if (vma_tmp->vm_end > addr) {
/* Fail if an existing vma overlaps the area */
if (vma_tmp->vm_start < end)
return -ENOMEM;
__rb_link = &__rb_parent->rb_left;
} else {
rb_prev = __rb_parent;
__rb_link = &__rb_parent->rb_right;
}
}
*pprev = NULL;
if (rb_prev)
*pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
*rb_link = __rb_link;
*rb_parent = __rb_parent;
return 0;
}
static unsigned long count_vma_pages_range(struct mm_struct *mm,
unsigned long addr, unsigned long end)
{
unsigned long nr_pages = 0;
struct vm_area_struct *vma;
/* Find first overlaping mapping */
vma = find_vma_intersection(mm, addr, end);
if (!vma)
return 0;
nr_pages = (min(end, vma->vm_end) -
max(addr, vma->vm_start)) >> PAGE_SHIFT;
/* Iterate over the rest of the overlaps */
for (vma = vma->vm_next; vma; vma = vma->vm_next) {
unsigned long overlap_len;
if (vma->vm_start > end)
break;
overlap_len = min(end, vma->vm_end) - vma->vm_start;
nr_pages += overlap_len >> PAGE_SHIFT;
}
return nr_pages;
}
void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
struct rb_node **rb_link, struct rb_node *rb_parent)
{
/* Update tracking information for the gap following the new vma. */
if (vma->vm_next)
vma_gap_update(vma->vm_next);
else
mm->highest_vm_end = vm_end_gap(vma);
/*
* vma->vm_prev wasn't known when we followed the rbtree to find the
* correct insertion point for that vma. As a result, we could not
* update the vma vm_rb parents rb_subtree_gap values on the way down.
* So, we first insert the vma with a zero rb_subtree_gap value
* (to be consistent with what we did on the way down), and then
* immediately update the gap to the correct value. Finally we
* rebalance the rbtree after all augmented values have been set.
*/
rb_link_node(&vma->vm_rb, rb_parent, rb_link);
vma->rb_subtree_gap = 0;
vma_gap_update(vma);
vma_rb_insert(vma, &mm->mm_rb);
}
static void __vma_link_file(struct vm_area_struct *vma)
{
struct file *file;
file = vma->vm_file;
if (file) {
struct address_space *mapping = file->f_mapping;
if (vma->vm_flags & VM_DENYWRITE)
atomic_dec(&file_inode(file)->i_writecount);
if (vma->vm_flags & VM_SHARED)
atomic_inc(&mapping->i_mmap_writable);
flush_dcache_mmap_lock(mapping);
vma_interval_tree_insert(vma, &mapping->i_mmap);
flush_dcache_mmap_unlock(mapping);
}
}
static void
__vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
struct vm_area_struct *prev, struct rb_node **rb_link,
struct rb_node *rb_parent)
{
__vma_link_list(mm, vma, prev, rb_parent);
__vma_link_rb(mm, vma, rb_link, rb_parent);
}
static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
struct vm_area_struct *prev, struct rb_node **rb_link,
struct rb_node *rb_parent)
{
struct address_space *mapping = NULL;
if (vma->vm_file) {
mapping = vma->vm_file->f_mapping;
i_mmap_lock_write(mapping);
}
__vma_link(mm, vma, prev, rb_link, rb_parent);
__vma_link_file(vma);
if (mapping)
i_mmap_unlock_write(mapping);
mm->map_count++;
validate_mm(mm);
}
/*
* Helper for vma_adjust() in the split_vma insert case: insert a vma into the
* mm's list and rbtree. It has already been inserted into the interval tree.
*/
static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
{
struct vm_area_struct *prev;
struct rb_node **rb_link, *rb_parent;
if (find_vma_links(mm, vma->vm_start, vma->vm_end,
&prev, &rb_link, &rb_parent))
BUG();
__vma_link(mm, vma, prev, rb_link, rb_parent);
mm->map_count++;
}
static __always_inline void __vma_unlink_common(struct mm_struct *mm,
struct vm_area_struct *vma,
struct vm_area_struct *prev,
bool has_prev,
struct vm_area_struct *ignore)
{
struct vm_area_struct *next;
vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
next = vma->vm_next;
if (has_prev)
prev->vm_next = next;
else {
prev = vma->vm_prev;
if (prev)
prev->vm_next = next;
else
mm->mmap = next;
}
if (next)
next->vm_prev = prev;
/* Kill the cache */
vmacache_invalidate(mm);
}
static inline void __vma_unlink_prev(struct mm_struct *mm,
struct vm_area_struct *vma,
struct vm_area_struct *prev)
{
__vma_unlink_common(mm, vma, prev, true, vma);
}
/*
* We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
* is already present in an i_mmap tree without adjusting the tree.
* The following helper function should be used when such adjustments
* are necessary. The "insert" vma (if any) is to be inserted
* before we drop the necessary locks.
*/
int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
struct vm_area_struct *expand)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
struct address_space *mapping = NULL;
struct rb_root_cached *root = NULL;
struct anon_vma *anon_vma = NULL;
struct file *file = vma->vm_file;
bool start_changed = false, end_changed = false;
long adjust_next = 0;
int remove_next = 0;
if (next && !insert) {
struct vm_area_struct *exporter = NULL, *importer = NULL;
if (end >= next->vm_end) {
/*
* vma expands, overlapping all the next, and
* perhaps the one after too (mprotect case 6).
* The only other cases that gets here are
* case 1, case 7 and case 8.
*/
if (next == expand) {
/*
* The only case where we don't expand "vma"
* and we expand "next" instead is case 8.
*/
VM_WARN_ON(end != next->vm_end);
/*
* remove_next == 3 means we're
* removing "vma" and that to do so we
* swapped "vma" and "next".
*/
remove_next = 3;
VM_WARN_ON(file != next->vm_file);
swap(vma, next);
} else {
VM_WARN_ON(expand != vma);
/*
* case 1, 6, 7, remove_next == 2 is case 6,
* remove_next == 1 is case 1 or 7.
*/
remove_next = 1 + (end > next->vm_end);
VM_WARN_ON(remove_next == 2 &&
end != next->vm_next->vm_end);
VM_WARN_ON(remove_next == 1 &&
end != next->vm_end);
/* trim end to next, for case 6 first pass */
end = next->vm_end;
}
exporter = next;
importer = vma;
/*
* If next doesn't have anon_vma, import from vma after
* next, if the vma overlaps with it.
*/
if (remove_next == 2 && !next->anon_vma)
exporter = next->vm_next;
} else if (end > next->vm_start) {
/*
* vma expands, overlapping part of the next:
* mprotect case 5 shifting the boundary up.
*/
adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
exporter = next;
importer = vma;
VM_WARN_ON(expand != importer);
} else if (end < vma->vm_end) {
/*
* vma shrinks, and !insert tells it's not
* split_vma inserting another: so it must be
* mprotect case 4 shifting the boundary down.
*/
adjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);
exporter = vma;
importer = next;
VM_WARN_ON(expand != importer);
}
/*
* Easily overlooked: when mprotect shifts the boundary,
* make sure the expanding vma has anon_vma set if the
* shrinking vma had, to cover any anon pages imported.
*/
if (exporter && exporter->anon_vma && !importer->anon_vma) {
int error;
importer->anon_vma = exporter->anon_vma;
error = anon_vma_clone(importer, exporter);
if (error)
return error;
}
}
again:
vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
if (file) {
mapping = file->f_mapping;
root = &mapping->i_mmap;
uprobe_munmap(vma, vma->vm_start, vma->vm_end);
if (adjust_next)
uprobe_munmap(next, next->vm_start, next->vm_end);
i_mmap_lock_write(mapping);
if (insert) {
/*
* Put into interval tree now, so instantiated pages
* are visible to arm/parisc __flush_dcache_page
* throughout; but we cannot insert into address
* space until vma start or end is updated.
*/
__vma_link_file(insert);
}
}
anon_vma = vma->anon_vma;
if (!anon_vma && adjust_next)
anon_vma = next->anon_vma;
if (anon_vma) {
VM_WARN_ON(adjust_next && next->anon_vma &&
anon_vma != next->anon_vma);
anon_vma_lock_write(anon_vma);
anon_vma_interval_tree_pre_update_vma(vma);
if (adjust_next)
anon_vma_interval_tree_pre_update_vma(next);
}
if (root) {
flush_dcache_mmap_lock(mapping);
vma_interval_tree_remove(vma, root);
if (adjust_next)
vma_interval_tree_remove(next, root);
}
if (start != vma->vm_start) {
vma->vm_start = start;
start_changed = true;
}
if (end != vma->vm_end) {
vma->vm_end = end;
end_changed = true;
}
vma->vm_pgoff = pgoff;
if (adjust_next) {
next->vm_start += adjust_next << PAGE_SHIFT;
next->vm_pgoff += adjust_next;
}
if (root) {
if (adjust_next)
vma_interval_tree_insert(next, root);
vma_interval_tree_insert(vma, root);
flush_dcache_mmap_unlock(mapping);
}
if (remove_next) {
/*
* vma_merge has merged next into vma, and needs
* us to remove next before dropping the locks.
*/
if (remove_next != 3)
__vma_unlink_prev(mm, next, vma);
else
/*
* vma is not before next if they've been
* swapped.
*
* pre-swap() next->vm_start was reduced so
* tell validate_mm_rb to ignore pre-swap()
* "next" (which is stored in post-swap()
* "vma").
*/
__vma_unlink_common(mm, next, NULL, false, vma);
if (file)
__remove_shared_vm_struct(next, file, mapping);
} else if (insert) {
/*
* split_vma has split insert from vma, and needs
* us to insert it before dropping the locks
* (it may either follow vma or precede it).
*/
__insert_vm_struct(mm, insert);
} else {
if (start_changed)
vma_gap_update(vma);
if (end_changed) {
if (!next)
mm->highest_vm_end = vm_end_gap(vma);
else if (!adjust_next)
vma_gap_update(next);
}
}
if (anon_vma) {
anon_vma_interval_tree_post_update_vma(vma);
if (adjust_next)
anon_vma_interval_tree_post_update_vma(next);
anon_vma_unlock_write(anon_vma);
}
if (mapping)
i_mmap_unlock_write(mapping);
if (root) {
uprobe_mmap(vma);
if (adjust_next)
uprobe_mmap(next);
}
if (remove_next) {
if (file) {
uprobe_munmap(next, next->vm_start, next->vm_end);
fput(file);
}
if (next->anon_vma)
anon_vma_merge(vma, next);
mm->map_count--;
mpol_put(vma_policy(next));
vm_area_free(next);
/*
* In mprotect's case 6 (see comments on vma_merge),
* we must remove another next too. It would clutter
* up the code too much to do both in one go.
*/
if (remove_next != 3) {
/*
* If "next" was removed and vma->vm_end was
* expanded (up) over it, in turn
* "next->vm_prev->vm_end" changed and the
* "vma->vm_next" gap must be updated.
*/
next = vma->vm_next;
} else {
/*
* For the scope of the comment "next" and
* "vma" considered pre-swap(): if "vma" was
* removed, next->vm_start was expanded (down)
* over it and the "next" gap must be updated.
* Because of the swap() the post-swap() "vma"
* actually points to pre-swap() "next"
* (post-swap() "next" as opposed is now a
* dangling pointer).
*/
next = vma;
}
if (remove_next == 2) {
remove_next = 1;
end = next->vm_end;
goto again;
}
else if (next)
vma_gap_update(next);
else {
/*
* If remove_next == 2 we obviously can't
* reach this path.
*
* If remove_next == 3 we can't reach this
* path because pre-swap() next is always not
* NULL. pre-swap() "next" is not being
* removed and its next->vm_end is not altered
* (and furthermore "end" already matches
* next->vm_end in remove_next == 3).
*
* We reach this only in the remove_next == 1
* case if the "next" vma that was removed was
* the highest vma of the mm. However in such
* case next->vm_end == "end" and the extended
* "vma" has vma->vm_end == next->vm_end so
* mm->highest_vm_end doesn't need any update
* in remove_next == 1 case.
*/
VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
}
}
if (insert && file)
uprobe_mmap(insert);
validate_mm(mm);
return 0;
}
/*
* If the vma has a ->close operation then the driver probably needs to release
* per-vma resources, so we don't attempt to merge those.
*/
static inline int is_mergeable_vma(struct vm_area_struct *vma,
struct file *file, unsigned long vm_flags,
struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
{
/*
* VM_SOFTDIRTY should not prevent from VMA merging, if we
* match the flags but dirty bit -- the caller should mark
* merged VMA as dirty. If dirty bit won't be excluded from
* comparison, we increase pressue on the memory system forcing
* the kernel to generate new VMAs when old one could be
* extended instead.
*/
if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
return 0;
if (vma->vm_file != file)
return 0;
if (vma->vm_ops && vma->vm_ops->close)
return 0;
if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
return 0;
return 1;
}
static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
struct anon_vma *anon_vma2,
struct vm_area_struct *vma)
{
/*
* The list_is_singular() test is to avoid merging VMA cloned from
* parents. This can improve scalability caused by anon_vma lock.
*/
if ((!anon_vma1 || !anon_vma2) && (!vma ||
list_is_singular(&vma->anon_vma_chain)))
return 1;
return anon_vma1 == anon_vma2;
}
/*
* Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
* in front of (at a lower virtual address and file offset than) the vma.
*
* We cannot merge two vmas if they have differently assigned (non-NULL)
* anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
*
* We don't check here for the merged mmap wrapping around the end of pagecache
* indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
* wrap, nor mmaps which cover the final page at index -1UL.
*/
static int
can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
struct anon_vma *anon_vma, struct file *file,
pgoff_t vm_pgoff,
struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
{
if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
if (vma->vm_pgoff == vm_pgoff)
return 1;
}
return 0;
}
/*
* Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
* beyond (at a higher virtual address and file offset than) the vma.
*
* We cannot merge two vmas if they have differently assigned (non-NULL)
* anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
*/
static int
can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
struct anon_vma *anon_vma, struct file *file,
pgoff_t vm_pgoff,
struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
{
if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
pgoff_t vm_pglen;
vm_pglen = vma_pages(vma);
if (vma->vm_pgoff + vm_pglen == vm_pgoff)
return 1;
}
return 0;
}
/*
* Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
* whether that can be merged with its predecessor or its successor.
* Or both (it neatly fills a hole).
*
* In most cases - when called for mmap, brk or mremap - [addr,end) is
* certain not to be mapped by the time vma_merge is called; but when
* called for mprotect, it is certain to be already mapped (either at
* an offset within prev, or at the start of next), and the flags of
* this area are about to be changed to vm_flags - and the no-change
* case has already been eliminated.
*
* The following mprotect cases have to be considered, where AAAA is
* the area passed down from mprotect_fixup, never extending beyond one
* vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
*
* AAAA AAAA AAAA AAAA
* PPPPPPNNNNNN PPPPPPNNNNNN PPPPPPNNNNNN PPPPNNNNXXXX
* cannot merge might become might become might become
* PPNNNNNNNNNN PPPPPPPPPPNN PPPPPPPPPPPP 6 or
* mmap, brk or case 4 below case 5 below PPPPPPPPXXXX 7 or
* mremap move: PPPPXXXXXXXX 8
* AAAA
* PPPP NNNN PPPPPPPPPPPP PPPPPPPPNNNN PPPPNNNNNNNN
* might become case 1 below case 2 below case 3 below
*
* It is important for case 8 that the the vma NNNN overlapping the
* region AAAA is never going to extended over XXXX. Instead XXXX must
* be extended in region AAAA and NNNN must be removed. This way in
* all cases where vma_merge succeeds, the moment vma_adjust drops the
* rmap_locks, the properties of the merged vma will be already
* correct for the whole merged range. Some of those properties like
* vm_page_prot/vm_flags may be accessed by rmap_walks and they must
* be correct for the whole merged range immediately after the
* rmap_locks are released. Otherwise if XXXX would be removed and
* NNNN would be extended over the XXXX range, remove_migration_ptes
* or other rmap walkers (if working on addresses beyond the "end"
* parameter) may establish ptes with the wrong permissions of NNNN
* instead of the right permissions of XXXX.
*/
struct vm_area_struct *vma_merge(struct mm_struct *mm,
struct vm_area_struct *prev, unsigned long addr,
unsigned long end, unsigned long vm_flags,
struct anon_vma *anon_vma, struct file *file,
pgoff_t pgoff, struct mempolicy *policy,
struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
{
pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
struct vm_area_struct *area, *next;
int err;
/*
* We later require that vma->vm_flags == vm_flags,
* so this tests vma->vm_flags & VM_SPECIAL, too.
*/
if (vm_flags & VM_SPECIAL)
return NULL;
if (prev)
next = prev->vm_next;
else
next = mm->mmap;
area = next;
if (area && area->vm_end == end) /* cases 6, 7, 8 */
next = next->vm_next;
/* verify some invariant that must be enforced by the caller */
VM_WARN_ON(prev && addr <= prev->vm_start);
VM_WARN_ON(area && end > area->vm_end);
VM_WARN_ON(addr >= end);
/*
* Can it merge with the predecessor?
*/
if (prev && prev->vm_end == addr &&
mpol_equal(vma_policy(prev), policy) &&
can_vma_merge_after(prev, vm_flags,
anon_vma, file, pgoff,
vm_userfaultfd_ctx)) {
/*
* OK, it can. Can we now merge in the successor as well?
*/
if (next && end == next->vm_start &&
mpol_equal(policy, vma_policy(next)) &&
can_vma_merge_before(next, vm_flags,
anon_vma, file,
pgoff+pglen,
vm_userfaultfd_ctx) &&
is_mergeable_anon_vma(prev->anon_vma,
next->anon_vma, NULL)) {
/* cases 1, 6 */
err = __vma_adjust(prev, prev->vm_start,
next->vm_end, prev->vm_pgoff, NULL,
prev);
} else /* cases 2, 5, 7 */
err = __vma_adjust(prev, prev->vm_start,
end, prev->vm_pgoff, NULL, prev);
if (err)
return NULL;
khugepaged_enter_vma_merge(prev, vm_flags);
return prev;
}
/*
* Can this new request be merged in front of next?
*/
if (next && end == next->vm_start &&
mpol_equal(policy, vma_policy(next)) &&
can_vma_merge_before(next, vm_flags,
anon_vma, file, pgoff+pglen,
vm_userfaultfd_ctx)) {
if (prev && addr < prev->vm_end) /* case 4 */
err = __vma_adjust(prev, prev->vm_start,
addr, prev->vm_pgoff, NULL, next);
else { /* cases 3, 8 */
err = __vma_adjust(area, addr, next->vm_end,
next->vm_pgoff - pglen, NULL, next);
/*
* In case 3 area is already equal to next and
* this is a noop, but in case 8 "area" has
* been removed and next was expanded over it.
*/
area = next;
}
if (err)
return NULL;
khugepaged_enter_vma_merge(area, vm_flags);
return area;
}
return NULL;
}
/*
* Rough compatbility check to quickly see if it's even worth looking
* at sharing an anon_vma.
*
* They need to have the same vm_file, and the flags can only differ
* in things that mprotect may change.
*
* NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
* we can merge the two vma's. For example, we refuse to merge a vma if
* there is a vm_ops->close() function, because that indicates that the
* driver is doing some kind of reference counting. But that doesn't
* really matter for the anon_vma sharing case.
*/
static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
{
return a->vm_end == b->vm_start &&
mpol_equal(vma_policy(a), vma_policy(b)) &&
a->vm_file == b->vm_file &&
!((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
}
/*
* Do some basic sanity checking to see if we can re-use the anon_vma
* from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
* the same as 'old', the other will be the new one that is trying
* to share the anon_vma.
*
* NOTE! This runs with mm_sem held for reading, so it is possible that
* the anon_vma of 'old' is concurrently in the process of being set up
* by another page fault trying to merge _that_. But that's ok: if it
* is being set up, that automatically means that it will be a singleton
* acceptable for merging, so we can do all of this optimistically. But
* we do that READ_ONCE() to make sure that we never re-load the pointer.
*
* IOW: that the "list_is_singular()" test on the anon_vma_chain only
* matters for the 'stable anon_vma' case (ie the thing we want to avoid
* is to return an anon_vma that is "complex" due to having gone through
* a fork).
*
* We also make sure that the two vma's are compatible (adjacent,
* and with the same memory policies). That's all stable, even with just
* a read lock on the mm_sem.
*/
static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
{
if (anon_vma_compatible(a, b)) {
struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
if (anon_vma && list_is_singular(&old->anon_vma_chain))
return anon_vma;
}
return NULL;
}
/*
* find_mergeable_anon_vma is used by anon_vma_prepare, to check
* neighbouring vmas for a suitable anon_vma, before it goes off
* to allocate a new anon_vma. It checks because a repetitive
* sequence of mprotects and faults may otherwise lead to distinct
* anon_vmas being allocated, preventing vma merge in subsequent
* mprotect.
*/
struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
{
struct anon_vma *anon_vma;
struct vm_area_struct *near;
near = vma->vm_next;
if (!near)
goto try_prev;
anon_vma = reusable_anon_vma(near, vma, near);
if (anon_vma)
return anon_vma;
try_prev:
near = vma->vm_prev;
if (!near)
goto none;
anon_vma = reusable_anon_vma(near, near, vma);
if (anon_vma)
return anon_vma;
none:
/*
* There's no absolute need to look only at touching neighbours:
* we could search further afield for "compatible" anon_vmas.
* But it would probably just be a waste of time searching,
* or lead to too many vmas hanging off the same anon_vma.
* We're trying to allow mprotect remerging later on,
* not trying to minimize memory used for anon_vmas.
*/
return NULL;
}
/*
* If a hint addr is less than mmap_min_addr change hint to be as
* low as possible but still greater than mmap_min_addr
*/
static inline unsigned long round_hint_to_min(unsigned long hint)
{
hint &= PAGE_MASK;
if (((void *)hint != NULL) &&
(hint < mmap_min_addr))
return PAGE_ALIGN(mmap_min_addr);
return hint;
}
static inline int mlock_future_check(struct mm_struct *mm,
unsigned long flags,
unsigned long len)
{
unsigned long locked, lock_limit;
/* mlock MCL_FUTURE? */
if (flags & VM_LOCKED) {
locked = len >> PAGE_SHIFT;
locked += mm->locked_vm;
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
if (locked > lock_limit && !capable(CAP_IPC_LOCK))
return -EAGAIN;
}
return 0;
}
static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
{
if (S_ISREG(inode->i_mode))
return MAX_LFS_FILESIZE;
if (S_ISBLK(inode->i_mode))
return MAX_LFS_FILESIZE;
/* Special "we do even unsigned file positions" case */
if (file->f_mode & FMODE_UNSIGNED_OFFSET)
return 0;
/* Yes, random drivers might want more. But I'm tired of buggy drivers */
return ULONG_MAX;
}
static inline bool file_mmap_ok(struct file *file, struct inode *inode,
unsigned long pgoff, unsigned long len)
{
u64 maxsize = file_mmap_size_max(file, inode);
if (maxsize && len > maxsize)
return false;
maxsize -= len;
if (pgoff > maxsize >> PAGE_SHIFT)
return false;
return true;
}
/*
* The caller must hold down_write(¤t->mm->mmap_sem).
*/
unsigned long do_mmap(struct file *file, unsigned long addr,
unsigned long len, unsigned long prot,
unsigned long flags, vm_flags_t vm_flags,
unsigned long pgoff, unsigned long *populate,
struct list_head *uf)
{
struct mm_struct *mm = current->mm;
int pkey = 0;
*populate = 0;
if (!len)
return -EINVAL;
/*
* Does the application expect PROT_READ to imply PROT_EXEC?
*
* (the exception is when the underlying filesystem is noexec
* mounted, in which case we dont add PROT_EXEC.)
*/
if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
if (!(file && path_noexec(&file->f_path)))
prot |= PROT_EXEC;
/* force arch specific MAP_FIXED handling in get_unmapped_area */
if (flags & MAP_FIXED_NOREPLACE)
flags |= MAP_FIXED;
if (!(flags & MAP_FIXED))
addr = round_hint_to_min(addr);
/* Careful about overflows.. */
len = PAGE_ALIGN(len);
if (!len)
return -ENOMEM;
/* offset overflow? */
if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
return -EOVERFLOW;
/* Too many mappings? */
if (mm->map_count > sysctl_max_map_count)
return -ENOMEM;
/* Obtain the address to map to. we verify (or select) it and ensure
* that it represents a valid section of the address space.
*/
addr = get_unmapped_area(file, addr, len, pgoff, flags);
if (offset_in_page(addr))
return addr;
if (flags & MAP_FIXED_NOREPLACE) {
struct vm_area_struct *vma = find_vma(mm, addr);
if (vma && vma->vm_start < addr + len)
return -EEXIST;
}
if (prot == PROT_EXEC) {
pkey = execute_only_pkey(mm);
if (pkey < 0)
pkey = 0;
}
/* Do simple checking here so the lower-level routines won't have
* to. we assume access permissions have been handled by the open
* of the memory object, so we don't do any here.
*/
vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
if (flags & MAP_LOCKED)
if (!can_do_mlock())
return -EPERM;
if (mlock_future_check(mm, vm_flags, len))
return -EAGAIN;
if (file) {
struct inode *inode = file_inode(file);
unsigned long flags_mask;
if (!file_mmap_ok(file, inode, pgoff, len))
return -EOVERFLOW;
flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
switch (flags & MAP_TYPE) {
case MAP_SHARED:
/*
* Force use of MAP_SHARED_VALIDATE with non-legacy
* flags. E.g. MAP_SYNC is dangerous to use with
* MAP_SHARED as you don't know which consistency model
* you will get. We silently ignore unsupported flags
* with MAP_SHARED to preserve backward compatibility.
*/
flags &= LEGACY_MAP_MASK;
/* fall through */
case MAP_SHARED_VALIDATE:
if (flags & ~flags_mask)
return -EOPNOTSUPP;
if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
return -EACCES;
/*
* Make sure we don't allow writing to an append-only
* file..
*/
if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
return -EACCES;
/*
* Make sure there are no mandatory locks on the file.
*/
if (locks_verify_locked(file))
return -EAGAIN;
vm_flags |= VM_SHARED | VM_MAYSHARE;
if (!(file->f_mode & FMODE_WRITE))
vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
/* fall through */
case MAP_PRIVATE:
if (!(file->f_mode & FMODE_READ))
return -EACCES;
if (path_noexec(&file->f_path)) {
if (vm_flags & VM_EXEC)
return -EPERM;
vm_flags &= ~VM_MAYEXEC;
}
if (!file->f_op->mmap)
return -ENODEV;
if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
return -EINVAL;
break;
default:
return -EINVAL;
}
} else {
switch (flags & MAP_TYPE) {
case MAP_SHARED:
if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
return -EINVAL;
/*
* Ignore pgoff.
*/
pgoff = 0;
vm_flags |= VM_SHARED | VM_MAYSHARE;
break;
case MAP_PRIVATE:
/*
* Set pgoff according to addr for anon_vma.
*/
pgoff = addr >> PAGE_SHIFT;
break;
default:
return -EINVAL;
}
}
/*
* Set 'VM_NORESERVE' if we should not account for the
* memory use of this mapping.
*/
if (flags & MAP_NORESERVE) {
/* We honor MAP_NORESERVE if allowed to overcommit */
if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
vm_flags |= VM_NORESERVE;
/* hugetlb applies strict overcommit unless MAP_NORESERVE */
if (file && is_file_hugepages(file))
vm_flags |= VM_NORESERVE;
}
addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
if (!IS_ERR_VALUE(addr) &&
((vm_flags & VM_LOCKED) ||
(flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
*populate = len;
return addr;
}
unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
{
struct file *file = NULL;
unsigned long retval;
if (!(flags & MAP_ANONYMOUS)) {
audit_mmap_fd(fd, flags);
file = fget(fd);
if (!file)
return -EBADF;
if (is_file_hugepages(file))
len = ALIGN(len, huge_page_size(hstate_file(file)));
retval = -EINVAL;
if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
goto out_fput;
} else if (flags & MAP_HUGETLB) {
struct user_struct *user = NULL;
struct hstate *hs;
hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
if (!hs)
return -EINVAL;
len = ALIGN(len, huge_page_size(hs));
/*
* VM_NORESERVE is used because the reservations will be
* taken when vm_ops->mmap() is called
* A dummy user value is used because we are not locking
* memory so no accounting is necessary
*/
file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
VM_NORESERVE,
&user, HUGETLB_ANONHUGE_INODE,
(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
if (IS_ERR(file))
return PTR_ERR(file);
}
flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
out_fput:
if (file)
fput(file);
return retval;
}
SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
unsigned long, prot, unsigned long, flags,
unsigned long, fd, unsigned long, pgoff)
{
return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
}
#ifdef __ARCH_WANT_SYS_OLD_MMAP
struct mmap_arg_struct {
unsigned long addr;
unsigned long len;
unsigned long prot;
unsigned long flags;
unsigned long fd;
unsigned long offset;
};
SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
{
struct mmap_arg_struct a;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
if (offset_in_page(a.offset))
return -EINVAL;
return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
a.offset >> PAGE_SHIFT);
}
#endif /* __ARCH_WANT_SYS_OLD_MMAP */
/*
* Some shared mappigns will want the pages marked read-only
* to track write events. If so, we'll downgrade vm_page_prot
* to the private version (using protection_map[] without the
* VM_SHARED bit).
*/
int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
{
vm_flags_t vm_flags = vma->vm_flags;
const struct vm_operations_struct *vm_ops = vma->vm_ops;
/* If it was private or non-writable, the write bit is already clear */
if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
return 0;
/* The backer wishes to know when pages are first written to? */
if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
return 1;
/* The open routine did something to the protections that pgprot_modify
* won't preserve? */
if (pgprot_val(vm_page_prot) !=
pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
return 0;
/* Do we need to track softdirty? */
if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
return 1;
/* Specialty mapping? */
if (vm_flags & VM_PFNMAP)
return 0;
/* Can the mapping track the dirty pages? */
return vma->vm_file && vma->vm_file->f_mapping &&
mapping_cap_account_dirty(vma->vm_file->f_mapping);
}
/*
* We account for memory if it's a private writeable mapping,
* not hugepages and VM_NORESERVE wasn't set.
*/
static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
{
/*
* hugetlb has its own accounting separate from the core VM
* VM_HUGETLB may not be set yet so we cannot check for that flag.
*/
if (file && is_file_hugepages(file))
return 0;
return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
}
unsigned long mmap_region(struct file *file, unsigned long addr,
unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
struct list_head *uf)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma, *prev;
int error;
struct rb_node **rb_link, *rb_parent;
unsigned long charged = 0;
/* Check against address space limit. */
if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
unsigned long nr_pages;
/*
* MAP_FIXED may remove pages of mappings that intersects with
* requested mapping. Account for the pages it would unmap.
*/
nr_pages = count_vma_pages_range(mm, addr, addr + len);
if (!may_expand_vm(mm, vm_flags,
(len >> PAGE_SHIFT) - nr_pages))
return -ENOMEM;
}
/* Clear old maps */
while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
&rb_parent)) {
if (do_munmap(mm, addr, len, uf))
return -ENOMEM;
}
/*
* Private writable mapping: check memory availability
*/
if (accountable_mapping(file, vm_flags)) {
charged = len >> PAGE_SHIFT;
if (security_vm_enough_memory_mm(mm, charged))
return -ENOMEM;
vm_flags |= VM_ACCOUNT;
}
/*
* Can we just expand an old mapping?
*/
vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);
if (vma)
goto out;
/*
* Determine the object being mapped and call the appropriate
* specific mapper. the address has already been validated, but
* not unmapped, but the maps are removed from the list.
*/
vma = vm_area_alloc(mm);
if (!vma) {
error = -ENOMEM;
goto unacct_error;
}
vma->vm_start = addr;
vma->vm_end = addr + len;
vma->vm_flags = vm_flags;
vma->vm_page_prot = vm_get_page_prot(vm_flags);
vma->vm_pgoff = pgoff;
if (file) {
if (vm_flags & VM_DENYWRITE) {
error = deny_write_access(file);
if (error)
goto free_vma;
}
if (vm_flags & VM_SHARED) {
error = mapping_map_writable(file->f_mapping);
if (error)
goto allow_write_and_free_vma;
}
/* ->mmap() can change vma->vm_file, but must guarantee that
* vma_link() below can deny write-access if VM_DENYWRITE is set
* and map writably if VM_SHARED is set. This usually means the
* new file must not have been exposed to user-space, yet.
*/
vma->vm_file = get_file(file);
error = call_mmap(file, vma);
if (error)
goto unmap_and_free_vma;
/* Can addr have changed??
*
* Answer: Yes, several device drivers can do it in their
* f_op->mmap method. -DaveM
* Bug: If addr is changed, prev, rb_link, rb_parent should
* be updated for vma_link()
*/
WARN_ON_ONCE(addr != vma->vm_start);
addr = vma->vm_start;
vm_flags = vma->vm_flags;
} else if (vm_flags & VM_SHARED) {
error = shmem_zero_setup(vma);
if (error)
goto free_vma;
} else {
vma_set_anonymous(vma);
}
vma_link(mm, vma, prev, rb_link, rb_parent);
/* Once vma denies write, undo our temporary denial count */
if (file) {
if (vm_flags & VM_SHARED)
mapping_unmap_writable(file->f_mapping);
if (vm_flags & VM_DENYWRITE)
allow_write_access(file);
}
file = vma->vm_file;
out:
perf_event_mmap(vma);
vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
if (vm_flags & VM_LOCKED) {
if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
is_vm_hugetlb_page(vma) ||
vma == get_gate_vma(current->mm))
vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
else
mm->locked_vm += (len >> PAGE_SHIFT);
}
if (file)
uprobe_mmap(vma);
/*
* New (or expanded) vma always get soft dirty status.
* Otherwise user-space soft-dirty page tracker won't
* be able to distinguish situation when vma area unmapped,
* then new mapped in-place (which must be aimed as
* a completely new data area).
*/
vma->vm_flags |= VM_SOFTDIRTY;
vma_set_page_prot(vma);
return addr;
unmap_and_free_vma:
vma->vm_file = NULL;
fput(file);
/* Undo any partial mapping done by a device driver. */
unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
charged = 0;
if (vm_flags & VM_SHARED)
mapping_unmap_writable(file->f_mapping);
allow_write_and_free_vma:
if (vm_flags & VM_DENYWRITE)
allow_write_access(file);
free_vma:
vm_area_free(vma);
unacct_error:
if (charged)
vm_unacct_memory(charged);
return error;
}
unsigned long unmapped_area(struct vm_unmapped_area_info *info)
{
/*
* We implement the search by looking for an rbtree node that
* immediately follows a suitable gap. That is,
* - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
* - gap_end = vma->vm_start >= info->low_limit + length;
* - gap_end - gap_start >= length
*/
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long length, low_limit, high_limit, gap_start, gap_end;
/* Adjust search length to account for worst case alignment overhead */
length = info->length + info->align_mask;
if (length < info->length)
return -ENOMEM;
/* Adjust search limits by the desired length */
if (info->high_limit < length)
return -ENOMEM;
high_limit = info->high_limit - length;
if (info->low_limit > high_limit)
return -ENOMEM;
low_limit = info->low_limit + length;
/* Check if rbtree root looks promising */
if (RB_EMPTY_ROOT(&mm->mm_rb))
goto check_highest;
vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
if (vma->rb_subtree_gap < length)
goto check_highest;
while (true) {
/* Visit left subtree if it looks promising */
gap_end = vm_start_gap(vma);
if (gap_end >= low_limit && vma->vm_rb.rb_left) {
struct vm_area_struct *left =
rb_entry(vma->vm_rb.rb_left,
struct vm_area_struct, vm_rb);
if (left->rb_subtree_gap >= length) {
vma = left;
continue;
}
}
gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
check_current:
/* Check if current node has a suitable gap */
if (gap_start > high_limit)
return -ENOMEM;
if (gap_end >= low_limit &&
gap_end > gap_start && gap_end - gap_start >= length)
goto found;
/* Visit right subtree if it looks promising */
if (vma->vm_rb.rb_right) {
struct vm_area_struct *right =
rb_entry(vma->vm_rb.rb_right,
struct vm_area_struct, vm_rb);
if (right->rb_subtree_gap >= length) {
vma = right;
continue;
}
}
/* Go back up the rbtree to find next candidate node */
while (true) {
struct rb_node *prev = &vma->vm_rb;
if (!rb_parent(prev))
goto check_highest;
vma = rb_entry(rb_parent(prev),
struct vm_area_struct, vm_rb);
if (prev == vma->vm_rb.rb_left) {
gap_start = vm_end_gap(vma->vm_prev);
gap_end = vm_start_gap(vma);
goto check_current;
}
}
}
check_highest:
/* Check highest gap, which does not precede any rbtree node */
gap_start = mm->highest_vm_end;
gap_end = ULONG_MAX; /* Only for VM_BUG_ON below */
if (gap_start > high_limit)
return -ENOMEM;
found:
/* We found a suitable gap. Clip it with the original low_limit. */
if (gap_start < info->low_limit)
gap_start = info->low_limit;
/* Adjust gap address to the desired alignment */
gap_start += (info->align_offset - gap_start) & info->align_mask;
VM_BUG_ON(gap_start + info->length > info->high_limit);
VM_BUG_ON(gap_start + info->length > gap_end);
return gap_start;
}
unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long length, low_limit, high_limit, gap_start, gap_end;
/* Adjust search length to account for worst case alignment overhead */
length = info->length + info->align_mask;
if (length < info->length)
return -ENOMEM;
/*
* Adjust search limits by the desired length.
* See implementation comment at top of unmapped_area().
*/
gap_end = info->high_limit;
if (gap_end < length)
return -ENOMEM;
high_limit = gap_end - length;
if (info->low_limit > high_limit)
return -ENOMEM;
low_limit = info->low_limit + length;
/* Check highest gap, which does not precede any rbtree node */
gap_start = mm->highest_vm_end;
if (gap_start <= high_limit)
goto found_highest;
/* Check if rbtree root looks promising */
if (RB_EMPTY_ROOT(&mm->mm_rb))
return -ENOMEM;
vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
if (vma->rb_subtree_gap < length)
return -ENOMEM;
while (true) {
/* Visit right subtree if it looks promising */
gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
if (gap_start <= high_limit && vma->vm_rb.rb_right) {
struct vm_area_struct *right =
rb_entry(vma->vm_rb.rb_right,
struct vm_area_struct, vm_rb);
if (right->rb_subtree_gap >= length) {
vma = right;
continue;
}
}
check_current:
/* Check if current node has a suitable gap */
gap_end = vm_start_gap(vma);
if (gap_end < low_limit)
return -ENOMEM;
if (gap_start <= high_limit &&
gap_end > gap_start && gap_end - gap_start >= length)
goto found;
/* Visit left subtree if it looks promising */
if (vma->vm_rb.rb_left) {
struct vm_area_struct *left =
rb_entry(vma->vm_rb.rb_left,
struct vm_area_struct, vm_rb);
if (left->rb_subtree_gap >= length) {
vma = left;
continue;
}
}
/* Go back up the rbtree to find next candidate node */
while (true) {
struct rb_node *prev = &vma->vm_rb;
if (!rb_parent(prev))
return -ENOMEM;
vma = rb_entry(rb_parent(prev),
struct vm_area_struct, vm_rb);
if (prev == vma->vm_rb.rb_right) {
gap_start = vma->vm_prev ?
vm_end_gap(vma->vm_prev) : 0;
goto check_current;
}
}
}
found:
/* We found a suitable gap. Clip it with the original high_limit. */
if (gap_end > info->high_limit)
gap_end = info->high_limit;
found_highest:
/* Compute highest gap address at the desired alignment */
gap_end -= info->length;
gap_end -= (gap_end - info->align_offset) & info->align_mask;
VM_BUG_ON(gap_end < info->low_limit);
VM_BUG_ON(gap_end < gap_start);
return gap_end;
}
#ifndef arch_get_mmap_end
#define arch_get_mmap_end(addr) (TASK_SIZE)
#endif
#ifndef arch_get_mmap_base
#define arch_get_mmap_base(addr, base) (base)
#endif
/* Get an address range which is currently unmapped.
* For shmat() with addr=0.
*
* Ugly calling convention alert:
* Return value with the low bits set means error value,
* ie
* if (ret & ~PAGE_MASK)
* error = ret;
*
* This function "knows" that -ENOMEM has the bits set.
*/
#ifndef HAVE_ARCH_UNMAPPED_AREA
unsigned long
arch_get_unmapped_area(struct file *filp, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma, *prev;
struct vm_unmapped_area_info info;
const unsigned long mmap_end = arch_get_mmap_end(addr);
if (len > mmap_end - mmap_min_addr)
return -ENOMEM;
if (flags & MAP_FIXED)
return addr;
if (addr) {
addr = PAGE_ALIGN(addr);
vma = find_vma_prev(mm, addr, &prev);
if (mmap_end - len >= addr && addr >= mmap_min_addr &&
(!vma || addr + len <= vm_start_gap(vma)) &&
(!prev || addr >= vm_end_gap(prev)))
return addr;
}
info.flags = 0;
info.length = len;
info.low_limit = mm->mmap_base;
info.high_limit = mmap_end;
info.align_mask = 0;
return vm_unmapped_area(&info);
}
#endif
/*
* This mmap-allocator allocates new areas top-down from below the
* stack's low limit (the base):
*/
#ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
unsigned long
arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
const unsigned long len, const unsigned long pgoff,
const unsigned long flags)
{
struct vm_area_struct *vma, *prev;
struct mm_struct *mm = current->mm;
unsigned long addr = addr0;
struct vm_unmapped_area_info info;
const unsigned long mmap_end = arch_get_mmap_end(addr);
/* requested length too big for entire address space */
if (len > mmap_end - mmap_min_addr)
return -ENOMEM;
if (flags & MAP_FIXED)
return addr;
/* requesting a specific address */
if (addr) {
addr = PAGE_ALIGN(addr);
vma = find_vma_prev(mm, addr, &prev);
if (mmap_end - len >= addr && addr >= mmap_min_addr &&
(!vma || addr + len <= vm_start_gap(vma)) &&
(!prev || addr >= vm_end_gap(prev)))
return addr;
}
info.flags = VM_UNMAPPED_AREA_TOPDOWN;
info.length = len;
info.low_limit = max(PAGE_SIZE, mmap_min_addr);
info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
info.align_mask = 0;
addr = vm_unmapped_area(&info);
/*
* A failed mmap() very likely causes application failure,
* so fall back to the bottom-up function here. This scenario
* can happen with large stack limits and large mmap()
* allocations.
*/
if (offset_in_page(addr)) {
VM_BUG_ON(addr != -ENOMEM);
info.flags = 0;
info.low_limit = TASK_UNMAPPED_BASE;
info.high_limit = mmap_end;
addr = vm_unmapped_area(&info);
}
return addr;
}
#endif
unsigned long
get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
unsigned long pgoff, unsigned long flags)
{
unsigned long (*get_area)(struct file *, unsigned long,
unsigned long, unsigned long, unsigned long);
unsigned long error = arch_mmap_check(addr, len, flags);
if (error)
return error;
/* Careful about overflows.. */
if (len > TASK_SIZE)
return -ENOMEM;
get_area = current->mm->get_unmapped_area;
if (file) {
if (file->f_op->get_unmapped_area)
get_area = file->f_op->get_unmapped_area;
} else if (flags & MAP_SHARED) {
/*
* mmap_region() will call shmem_zero_setup() to create a file,
* so use shmem's get_unmapped_area in case it can be huge.
* do_mmap_pgoff() will clear pgoff, so match alignment.
*/
pgoff = 0;
get_area = shmem_get_unmapped_area;
}
addr = get_area(file, addr, len, pgoff, flags);
if (IS_ERR_VALUE(addr))
return addr;
if (addr > TASK_SIZE - len)
return -ENOMEM;
if (offset_in_page(addr))
return -EINVAL;
error = security_mmap_addr(addr);
return error ? error : addr;
}
EXPORT_SYMBOL(get_unmapped_area);
/* Look up the first VMA which satisfies addr < vm_end, NULL if none. */
struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
{
struct rb_node *rb_node;
struct vm_area_struct *vma;
/* Check the cache first. */
vma = vmacache_find(mm, addr);
if (likely(vma))
return vma;
rb_node = mm->mm_rb.rb_node;
while (rb_node) {
struct vm_area_struct *tmp;
tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
if (tmp->vm_end > addr) {
vma = tmp;
if (tmp->vm_start <= addr)
break;
rb_node = rb_node->rb_left;
} else
rb_node = rb_node->rb_right;
}
if (vma)
vmacache_update(addr, vma);
return vma;
}
EXPORT_SYMBOL(find_vma);
/*
* Same as find_vma, but also return a pointer to the previous VMA in *pprev.
*/
struct vm_area_struct *
find_vma_prev(struct mm_struct *mm, unsigned long addr,
struct vm_area_struct **pprev)
{
struct vm_area_struct *vma;
vma = find_vma(mm, addr);
if (vma) {
*pprev = vma->vm_prev;
} else {
struct rb_node *rb_node = mm->mm_rb.rb_node;
*pprev = NULL;
while (rb_node) {
*pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
rb_node = rb_node->rb_right;
}
}
return vma;
}
/*
* Verify that the stack growth is acceptable and
* update accounting. This is shared with both the
* grow-up and grow-down cases.
*/
static int acct_stack_growth(struct vm_area_struct *vma,
unsigned long size, unsigned long grow)
{
struct mm_struct *mm = vma->vm_mm;
unsigned long new_start;
/* address space limit tests */
if (!may_expand_vm(mm, vma->vm_flags, grow))
return -ENOMEM;
/* Stack limit test */
if (size > rlimit(RLIMIT_STACK))
return -ENOMEM;
/* mlock limit tests */
if (vma->vm_flags & VM_LOCKED) {
unsigned long locked;
unsigned long limit;
locked = mm->locked_vm + grow;
limit = rlimit(RLIMIT_MEMLOCK);
limit >>= PAGE_SHIFT;
if (locked > limit && !capable(CAP_IPC_LOCK))
return -ENOMEM;
}
/* Check to ensure the stack will not grow into a hugetlb-only region */
new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
vma->vm_end - size;
if (is_hugepage_only_range(vma->vm_mm, new_start, size))
return -EFAULT;
/*
* Overcommit.. This must be the final test, as it will
* update security statistics.
*/
if (security_vm_enough_memory_mm(mm, grow))
return -ENOMEM;
return 0;
}
#if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
/*
* PA-RISC uses this for its stack; IA64 for its Register Backing Store.
* vma is the last one with address > vma->vm_end. Have to extend vma.
*/
int expand_upwards(struct vm_area_struct *vma, unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *next;
unsigned long gap_addr;
int error = 0;
if (!(vma->vm_flags & VM_GROWSUP))
return -EFAULT;
/* Guard against exceeding limits of the address space. */
address &= PAGE_MASK;
if (address >= (TASK_SIZE & PAGE_MASK))
return -ENOMEM;
address += PAGE_SIZE;
/* Enforce stack_guard_gap */
gap_addr = address + stack_guard_gap;
/* Guard against overflow */
if (gap_addr < address || gap_addr > TASK_SIZE)
gap_addr = TASK_SIZE;
next = vma->vm_next;
if (next && next->vm_start < gap_addr &&
(next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (!(next->vm_flags & VM_GROWSUP))
return -ENOMEM;
/* Check that both stack segments have the same anon_vma? */
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address > vma->vm_end) {
unsigned long size, grow;
size = address - vma->vm_start;
grow = (address - vma->vm_end) >> PAGE_SHIFT;
error = -ENOMEM;
if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_end = address;
anon_vma_interval_tree_post_update_vma(vma);
if (vma->vm_next)
vma_gap_update(vma->vm_next);
else
mm->highest_vm_end = vm_end_gap(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
#endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
/*
* vma is the first one with address < vma->vm_start. Have to extend vma.
*/
int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error = 0;
address &= PAGE_MASK;
if (address < mmap_min_addr)
return -EPERM;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
}
/* enforced gap between the expanding stack and other mappings. */
unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
static int __init cmdline_parse_stack_guard_gap(char *p)
{
unsigned long val;
char *endptr;
val = simple_strtoul(p, &endptr, 10);
if (!*endptr)
stack_guard_gap = val << PAGE_SHIFT;
return 0;
}
__setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
#ifdef CONFIG_STACK_GROWSUP
int expand_stack(struct vm_area_struct *vma, unsigned long address)
{
return expand_upwards(vma, address);
}
struct vm_area_struct *
find_extend_vma(struct mm_struct *mm, unsigned long addr)
{
struct vm_area_struct *vma, *prev;
addr &= PAGE_MASK;
vma = find_vma_prev(mm, addr, &prev);
if (vma && (vma->vm_start <= addr))
return vma;
if (!prev || expand_stack(prev, addr))
return NULL;
if (prev->vm_flags & VM_LOCKED)
populate_vma_page_range(prev, addr, prev->vm_end, NULL);
return prev;
}
#else
int expand_stack(struct vm_area_struct *vma, unsigned long address)
{
return expand_downwards(vma, address);
}
struct vm_area_struct *
find_extend_vma(struct mm_struct *mm, unsigned long addr)
{
struct vm_area_struct *vma;
unsigned long start;
addr &= PAGE_MASK;
vma = find_vma(mm, addr);
if (!vma)
return NULL;
if (vma->vm_start <= addr)
return vma;
if (!(vma->vm_flags & VM_GROWSDOWN))
return NULL;
start = vma->vm_start;
if (expand_stack(vma, addr))
return NULL;
if (vma->vm_flags & VM_LOCKED)
populate_vma_page_range(vma, addr, start, NULL);
return vma;
}
#endif
EXPORT_SYMBOL_GPL(find_extend_vma);
/*
* Ok - we have the memory areas we should free on the vma list,
* so release them, and do the vma updates.
*
* Called with the mm semaphore held.
*/
static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
{
unsigned long nr_accounted = 0;
/* Update high watermark before we lower total_vm */
update_hiwater_vm(mm);
do {
long nrpages = vma_pages(vma);
if (vma->vm_flags & VM_ACCOUNT)
nr_accounted += nrpages;
vm_stat_account(mm, vma->vm_flags, -nrpages);
vma = remove_vma(vma);
} while (vma);
vm_unacct_memory(nr_accounted);
validate_mm(mm);
}
/*
* Get rid of page table information in the indicated region.
*
* Called with the mm semaphore held.
*/
static void unmap_region(struct mm_struct *mm,
struct vm_area_struct *vma, struct vm_area_struct *prev,
unsigned long start, unsigned long end)
{
struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
struct mmu_gather tlb;
lru_add_drain();
tlb_gather_mmu(&tlb, mm, start, end);
update_hiwater_rss(mm);
unmap_vmas(&tlb, vma, start, end);
free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
next ? next->vm_start : USER_PGTABLES_CEILING);
tlb_finish_mmu(&tlb, start, end);
}
/*
* Create a list of vma's touched by the unmap, removing them from the mm's
* vma list as we go..
*/
static void
detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
struct vm_area_struct *prev, unsigned long end)
{
struct vm_area_struct **insertion_point;
struct vm_area_struct *tail_vma = NULL;
insertion_point = (prev ? &prev->vm_next : &mm->mmap);
vma->vm_prev = NULL;
do {
vma_rb_erase(vma, &mm->mm_rb);
mm->map_count--;
tail_vma = vma;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
*insertion_point = vma;
if (vma) {
vma->vm_prev = prev;
vma_gap_update(vma);
} else
mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
tail_vma->vm_next = NULL;
/* Kill the cache */
vmacache_invalidate(mm);
}
/*
* __split_vma() bypasses sysctl_max_map_count checking. We use this where it
* has already been checked or doesn't make sense to fail.
*/
int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long addr, int new_below)
{
struct vm_area_struct *new;
int err;
if (vma->vm_ops && vma->vm_ops->split) {
err = vma->vm_ops->split(vma, addr);
if (err)
return err;
}
new = vm_area_dup(vma);
if (!new)
return -ENOMEM;
if (new_below)
new->vm_end = addr;
else {
new->vm_start = addr;
new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
}
err = vma_dup_policy(vma, new);
if (err)
goto out_free_vma;
err = anon_vma_clone(new, vma);
if (err)
goto out_free_mpol;
if (new->vm_file)
get_file(new->vm_file);
if (new->vm_ops && new->vm_ops->open)
new->vm_ops->open(new);
if (new_below)
err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
((addr - new->vm_start) >> PAGE_SHIFT), new);
else
err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
/* Success. */
if (!err)
return 0;
/* Clean everything up if vma_adjust failed. */
if (new->vm_ops && new->vm_ops->close)
new->vm_ops->close(new);
if (new->vm_file)
fput(new->vm_file);
unlink_anon_vmas(new);
out_free_mpol:
mpol_put(vma_policy(new));
out_free_vma:
vm_area_free(new);
return err;
}
/*
* Split a vma into two pieces at address 'addr', a new vma is allocated
* either for the first part or the tail.
*/
int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long addr, int new_below)
{
if (mm->map_count >= sysctl_max_map_count)
return -ENOMEM;
return __split_vma(mm, vma, addr, new_below);
}
/* Munmap is split into 2 main parts -- this part which finds
* what needs doing, and the areas themselves, which do the
* work. This now handles partial unmappings.
* Jeremy Fitzhardinge <jeremy@goop.org>
*/
int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
struct list_head *uf, bool downgrade)
{
unsigned long end;
struct vm_area_struct *vma, *prev, *last;
if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
return -EINVAL;
len = PAGE_ALIGN(len);
if (len == 0)
return -EINVAL;
/* Find the first overlapping VMA */
vma = find_vma(mm, start);
if (!vma)
return 0;
prev = vma->vm_prev;
/* we have start < vma->vm_end */
/* if it doesn't overlap, we have nothing.. */
end = start + len;
if (vma->vm_start >= end)
return 0;
/*
* If we need to split any vma, do it now to save pain later.
*
* Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
* unmapped vm_area_struct will remain in use: so lower split_vma
* places tmp vma above, and higher split_vma places tmp vma below.
*/
if (start > vma->vm_start) {
int error;
/*
* Make sure that map_count on return from munmap() will
* not exceed its limit; but let map_count go just above
* its limit temporarily, to help free resources as expected.
*/
if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
return -ENOMEM;
error = __split_vma(mm, vma, start, 0);
if (error)
return error;
prev = vma;
}
/* Does it split the last one? */
last = find_vma(mm, end);
if (last && end > last->vm_start) {
int error = __split_vma(mm, last, end, 1);
if (error)
return error;
}
vma = prev ? prev->vm_next : mm->mmap;
if (unlikely(uf)) {
/*
* If userfaultfd_unmap_prep returns an error the vmas
* will remain splitted, but userland will get a
* highly unexpected error anyway. This is no
* different than the case where the first of the two
* __split_vma fails, but we don't undo the first
* split, despite we could. This is unlikely enough
* failure that it's not worth optimizing it for.
*/
int error = userfaultfd_unmap_prep(vma, start, end, uf);
if (error)
return error;
}
/*
* unlock any mlock()ed ranges before detaching vmas
*/
if (mm->locked_vm) {
struct vm_area_struct *tmp = vma;
while (tmp && tmp->vm_start < end) {
if (tmp->vm_flags & VM_LOCKED) {
mm->locked_vm -= vma_pages(tmp);
munlock_vma_pages_all(tmp);
}
tmp = tmp->vm_next;
}
}
/* Detach vmas from rbtree */
detach_vmas_to_be_unmapped(mm, vma, prev, end);
/*
* mpx unmap needs to be called with mmap_sem held for write.
* It is safe to call it before unmap_region().
*/
arch_unmap(mm, vma, start, end);
if (downgrade)
downgrade_write(&mm->mmap_sem);
unmap_region(mm, vma, prev, start, end);
/* Fix up all other VM information */
remove_vma_list(mm, vma);
return downgrade ? 1 : 0;
}
int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
struct list_head *uf)
{
return __do_munmap(mm, start, len, uf, false);
}
static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
{
int ret;
struct mm_struct *mm = current->mm;
LIST_HEAD(uf);
if (down_write_killable(&mm->mmap_sem))
return -EINTR;
ret = __do_munmap(mm, start, len, &uf, downgrade);
/*
* Returning 1 indicates mmap_sem is downgraded.
* But 1 is not legal return value of vm_munmap() and munmap(), reset
* it to 0 before return.
*/
if (ret == 1) {
up_read(&mm->mmap_sem);
ret = 0;
} else
up_write(&mm->mmap_sem);
userfaultfd_unmap_complete(mm, &uf);
return ret;
}
int vm_munmap(unsigned long start, size_t len)
{
return __vm_munmap(start, len, false);
}
EXPORT_SYMBOL(vm_munmap);
SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
{
profile_munmap(addr);
return __vm_munmap(addr, len, true);
}
/*
* Emulation of deprecated remap_file_pages() syscall.
*/
SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long populate = 0;
unsigned long ret = -EINVAL;
struct file *file;
pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.rst.\n",
current->comm, current->pid);
if (prot)
return ret;
start = start & PAGE_MASK;
size = size & PAGE_MASK;
if (start + size <= start)
return ret;
/* Does pgoff wrap? */
if (pgoff + (size >> PAGE_SHIFT) < pgoff)
return ret;
if (down_write_killable(&mm->mmap_sem))
return -EINTR;
vma = find_vma(mm, start);
if (!vma || !(vma->vm_flags & VM_SHARED))
goto out;
if (start < vma->vm_start)
goto out;
if (start + size > vma->vm_end) {
struct vm_area_struct *next;
for (next = vma->vm_next; next; next = next->vm_next) {
/* hole between vmas ? */
if (next->vm_start != next->vm_prev->vm_end)
goto out;
if (next->vm_file != vma->vm_file)
goto out;
if (next->vm_flags != vma->vm_flags)
goto out;
if (start + size <= next->vm_end)
break;
}
if (!next)
goto out;
}
prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
flags &= MAP_NONBLOCK;
flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
if (vma->vm_flags & VM_LOCKED) {
struct vm_area_struct *tmp;
flags |= MAP_LOCKED;
/* drop PG_Mlocked flag for over-mapped range */
for (tmp = vma; tmp->vm_start >= start + size;
tmp = tmp->vm_next) {
/*
* Split pmd and munlock page on the border
* of the range.
*/
vma_adjust_trans_huge(tmp, start, start + size, 0);
munlock_vma_pages_range(tmp,
max(tmp->vm_start, start),
min(tmp->vm_end, start + size));
}
}
file = get_file(vma->vm_file);
ret = do_mmap_pgoff(vma->vm_file, start, size,
prot, flags, pgoff, &populate, NULL);
fput(file);
out:
up_write(&mm->mmap_sem);
if (populate)
mm_populate(ret, populate);
if (!IS_ERR_VALUE(ret))
ret = 0;
return ret;
}
/*
* this is really a simplified "do_mmap". it only handles
* anonymous maps. eventually we may be able to do some
* brk-specific accounting here.
*/
static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma, *prev;
struct rb_node **rb_link, *rb_parent;
pgoff_t pgoff = addr >> PAGE_SHIFT;
int error;
/* Until we need other flags, refuse anything except VM_EXEC. */
if ((flags & (~VM_EXEC)) != 0)
return -EINVAL;
flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
if (offset_in_page(error))
return error;
error = mlock_future_check(mm, mm->def_flags, len);
if (error)
return error;
/*
* Clear old maps. this also does some error checking for us
*/
while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
&rb_parent)) {
if (do_munmap(mm, addr, len, uf))
return -ENOMEM;
}
/* Check against address space limits *after* clearing old maps... */
if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
return -ENOMEM;
if (mm->map_count > sysctl_max_map_count)
return -ENOMEM;
if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
return -ENOMEM;
/* Can we just expand an old private anonymous mapping? */
vma = vma_merge(mm, prev, addr, addr + len, flags,
NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);
if (vma)
goto out;
/*
* create a vma struct for an anonymous mapping
*/
vma = vm_area_alloc(mm);
if (!vma) {
vm_unacct_memory(len >> PAGE_SHIFT);
return -ENOMEM;
}
vma_set_anonymous(vma);
vma->vm_start = addr;
vma->vm_end = addr + len;
vma->vm_pgoff = pgoff;
vma->vm_flags = flags;
vma->vm_page_prot = vm_get_page_prot(flags);
vma_link(mm, vma, prev, rb_link, rb_parent);
out:
perf_event_mmap(vma);
mm->total_vm += len >> PAGE_SHIFT;
mm->data_vm += len >> PAGE_SHIFT;
if (flags & VM_LOCKED)
mm->locked_vm += (len >> PAGE_SHIFT);
vma->vm_flags |= VM_SOFTDIRTY;
return 0;
}
int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
{
struct mm_struct *mm = current->mm;
unsigned long len;
int ret;
bool populate;
LIST_HEAD(uf);
len = PAGE_ALIGN(request);
if (len < request)
return -ENOMEM;
if (!len)
return 0;
if (down_write_killable(&mm->mmap_sem))
return -EINTR;
ret = do_brk_flags(addr, len, flags, &uf);
populate = ((mm->def_flags & VM_LOCKED) != 0);
up_write(&mm->mmap_sem);
userfaultfd_unmap_complete(mm, &uf);
if (populate && !ret)
mm_populate(addr, len);
return ret;
}
EXPORT_SYMBOL(vm_brk_flags);
int vm_brk(unsigned long addr, unsigned long len)
{
return vm_brk_flags(addr, len, 0);
}
EXPORT_SYMBOL(vm_brk);
/* Release all mmaps. */
void exit_mmap(struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
unsigned long nr_accounted = 0;
/* mm's last user has gone, and its about to be pulled down */
mmu_notifier_release(mm);
if (unlikely(mm_is_oom_victim(mm))) {
/*
* Manually reap the mm to free as much memory as possible.
* Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
* this mm from further consideration. Taking mm->mmap_sem for
* write after setting MMF_OOM_SKIP will guarantee that the oom
* reaper will not run on this mm again after mmap_sem is
* dropped.
*
* Nothing can be holding mm->mmap_sem here and the above call
* to mmu_notifier_release(mm) ensures mmu notifier callbacks in
* __oom_reap_task_mm() will not block.
*
* This needs to be done before calling munlock_vma_pages_all(),
* which clears VM_LOCKED, otherwise the oom reaper cannot
* reliably test it.
*/
(void)__oom_reap_task_mm(mm);
set_bit(MMF_OOM_SKIP, &mm->flags);
down_write(&mm->mmap_sem);
up_write(&mm->mmap_sem);
}
if (mm->locked_vm) {
vma = mm->mmap;
while (vma) {
if (vma->vm_flags & VM_LOCKED)
munlock_vma_pages_all(vma);
vma = vma->vm_next;
}
}
arch_exit_mmap(mm);
vma = mm->mmap;
if (!vma) /* Can happen if dup_mmap() received an OOM */
return;
lru_add_drain();
flush_cache_mm(mm);
tlb_gather_mmu(&tlb, mm, 0, -1);
/* update_hiwater_rss(mm) here? but nobody should be looking */
/* Use -1 here to ensure all VMAs in the mm are unmapped */
unmap_vmas(&tlb, vma, 0, -1);
free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
tlb_finish_mmu(&tlb, 0, -1);
/*
* Walk the list again, actually closing and freeing it,
* with preemption enabled, without holding any MM locks.
*/
while (vma) {
if (vma->vm_flags & VM_ACCOUNT)
nr_accounted += vma_pages(vma);
vma = remove_vma(vma);
}
vm_unacct_memory(nr_accounted);
}
/* Insert vm structure into process list sorted by address
* and into the inode's i_mmap tree. If vm_file is non-NULL
* then i_mmap_rwsem is taken here.
*/
int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
{
struct vm_area_struct *prev;
struct rb_node **rb_link, *rb_parent;
if (find_vma_links(mm, vma->vm_start, vma->vm_end,
&prev, &rb_link, &rb_parent))
return -ENOMEM;
if ((vma->vm_flags & VM_ACCOUNT) &&
security_vm_enough_memory_mm(mm, vma_pages(vma)))
return -ENOMEM;
/*
* The vm_pgoff of a purely anonymous vma should be irrelevant
* until its first write fault, when page's anon_vma and index
* are set. But now set the vm_pgoff it will almost certainly
* end up with (unless mremap moves it elsewhere before that
* first wfault), so /proc/pid/maps tells a consistent story.
*
* By setting it to reflect the virtual start address of the
* vma, merges and splits can happen in a seamless way, just
* using the existing file pgoff checks and manipulations.
* Similarly in do_mmap_pgoff and in do_brk.
*/
if (vma_is_anonymous(vma)) {
BUG_ON(vma->anon_vma);
vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
}
vma_link(mm, vma, prev, rb_link, rb_parent);
return 0;
}
/*
* Copy the vma structure to a new location in the same mm,
* prior to moving page table entries, to effect an mremap move.
*/
struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
unsigned long addr, unsigned long len, pgoff_t pgoff,
bool *need_rmap_locks)
{
struct vm_area_struct *vma = *vmap;
unsigned long vma_start = vma->vm_start;
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *new_vma, *prev;
struct rb_node **rb_link, *rb_parent;
bool faulted_in_anon_vma = true;
/*
* If anonymous vma has not yet been faulted, update new pgoff
* to match new location, to increase its chance of merging.
*/
if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
pgoff = addr >> PAGE_SHIFT;
faulted_in_anon_vma = false;
}
if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
return NULL; /* should never get here */
new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
vma->vm_userfaultfd_ctx);
if (new_vma) {
/*
* Source vma may have been merged into new_vma
*/
if (unlikely(vma_start >= new_vma->vm_start &&
vma_start < new_vma->vm_end)) {
/*
* The only way we can get a vma_merge with
* self during an mremap is if the vma hasn't
* been faulted in yet and we were allowed to
* reset the dst vma->vm_pgoff to the
* destination address of the mremap to allow
* the merge to happen. mremap must change the
* vm_pgoff linearity between src and dst vmas
* (in turn preventing a vma_merge) to be
* safe. It is only safe to keep the vm_pgoff
* linear if there are no pages mapped yet.
*/
VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
*vmap = vma = new_vma;
}
*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
} else {
new_vma = vm_area_dup(vma);
if (!new_vma)
goto out;
new_vma->vm_start = addr;
new_vma->vm_end = addr + len;
new_vma->vm_pgoff = pgoff;
if (vma_dup_policy(vma, new_vma))
goto out_free_vma;
if (anon_vma_clone(new_vma, vma))
goto out_free_mempol;
if (new_vma->vm_file)
get_file(new_vma->vm_file);
if (new_vma->vm_ops && new_vma->vm_ops->open)
new_vma->vm_ops->open(new_vma);
vma_link(mm, new_vma, prev, rb_link, rb_parent);
*need_rmap_locks = false;
}
return new_vma;
out_free_mempol:
mpol_put(vma_policy(new_vma));
out_free_vma:
vm_area_free(new_vma);
out:
return NULL;
}
/*
* Return true if the calling process may expand its vm space by the passed
* number of pages
*/
bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
{
if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
return false;
if (is_data_mapping(flags) &&
mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
/* Workaround for Valgrind */
if (rlimit(RLIMIT_DATA) == 0 &&
mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
return true;
pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
current->comm, current->pid,
(mm->data_vm + npages) << PAGE_SHIFT,
rlimit(RLIMIT_DATA),
ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
if (!ignore_rlimit_data)
return false;
}
return true;
}
void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
{
mm->total_vm += npages;
if (is_exec_mapping(flags))
mm->exec_vm += npages;
else if (is_stack_mapping(flags))
mm->stack_vm += npages;
else if (is_data_mapping(flags))
mm->data_vm += npages;
}
static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
/*
* Having a close hook prevents vma merging regardless of flags.
*/
static void special_mapping_close(struct vm_area_struct *vma)
{
}
static const char *special_mapping_name(struct vm_area_struct *vma)
{
return ((struct vm_special_mapping *)vma->vm_private_data)->name;
}
static int special_mapping_mremap(struct vm_area_struct *new_vma)
{
struct vm_special_mapping *sm = new_vma->vm_private_data;
if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
return -EFAULT;
if (sm->mremap)
return sm->mremap(sm, new_vma);
return 0;
}
static const struct vm_operations_struct special_mapping_vmops = {
.close = special_mapping_close,
.fault = special_mapping_fault,
.mremap = special_mapping_mremap,
.name = special_mapping_name,
};
static const struct vm_operations_struct legacy_special_mapping_vmops = {
.close = special_mapping_close,
.fault = special_mapping_fault,
};
static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
{
struct vm_area_struct *vma = vmf->vma;
pgoff_t pgoff;
struct page **pages;
if (vma->vm_ops == &legacy_special_mapping_vmops) {
pages = vma->vm_private_data;
} else {
struct vm_special_mapping *sm = vma->vm_private_data;
if (sm->fault)
return sm->fault(sm, vmf->vma, vmf);
pages = sm->pages;
}
for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
pgoff--;
if (*pages) {
struct page *page = *pages;
get_page(page);
vmf->page = page;
return 0;
}
return VM_FAULT_SIGBUS;
}
static struct vm_area_struct *__install_special_mapping(
struct mm_struct *mm,
unsigned long addr, unsigned long len,
unsigned long vm_flags, void *priv,
const struct vm_operations_struct *ops)
{
int ret;
struct vm_area_struct *vma;
vma = vm_area_alloc(mm);
if (unlikely(vma == NULL))
return ERR_PTR(-ENOMEM);
vma->vm_start = addr;
vma->vm_end = addr + len;
vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
vma->vm_ops = ops;
vma->vm_private_data = priv;
ret = insert_vm_struct(mm, vma);
if (ret)
goto out;
vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
perf_event_mmap(vma);
return vma;
out:
vm_area_free(vma);
return ERR_PTR(ret);
}
bool vma_is_special_mapping(const struct vm_area_struct *vma,
const struct vm_special_mapping *sm)
{
return vma->vm_private_data == sm &&
(vma->vm_ops == &special_mapping_vmops ||
vma->vm_ops == &legacy_special_mapping_vmops);
}
/*
* Called with mm->mmap_sem held for writing.
* Insert a new vma covering the given region, with the given flags.
* Its pages are supplied by the given array of struct page *.
* The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
* The region past the last page supplied will always produce SIGBUS.
* The array pointer and the pages it points to are assumed to stay alive
* for as long as this mapping might exist.
*/
struct vm_area_struct *_install_special_mapping(
struct mm_struct *mm,
unsigned long addr, unsigned long len,
unsigned long vm_flags, const struct vm_special_mapping *spec)
{
return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
&special_mapping_vmops);
}
int install_special_mapping(struct mm_struct *mm,
unsigned long addr, unsigned long len,
unsigned long vm_flags, struct page **pages)
{
struct vm_area_struct *vma = __install_special_mapping(
mm, addr, len, vm_flags, (void *)pages,
&legacy_special_mapping_vmops);
return PTR_ERR_OR_ZERO(vma);
}
static DEFINE_MUTEX(mm_all_locks_mutex);
static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
{
if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
/*
* The LSB of head.next can't change from under us
* because we hold the mm_all_locks_mutex.
*/
down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
/*
* We can safely modify head.next after taking the
* anon_vma->root->rwsem. If some other vma in this mm shares
* the same anon_vma we won't take it again.
*
* No need of atomic instructions here, head.next
* can't change from under us thanks to the
* anon_vma->root->rwsem.
*/
if (__test_and_set_bit(0, (unsigned long *)
&anon_vma->root->rb_root.rb_root.rb_node))
BUG();
}
}
static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
{
if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
/*
* AS_MM_ALL_LOCKS can't change from under us because
* we hold the mm_all_locks_mutex.
*
* Operations on ->flags have to be atomic because
* even if AS_MM_ALL_LOCKS is stable thanks to the
* mm_all_locks_mutex, there may be other cpus
* changing other bitflags in parallel to us.
*/
if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
BUG();
down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);
}
}
/*
* This operation locks against the VM for all pte/vma/mm related
* operations that could ever happen on a certain mm. This includes
* vmtruncate, try_to_unmap, and all page faults.
*
* The caller must take the mmap_sem in write mode before calling
* mm_take_all_locks(). The caller isn't allowed to release the
* mmap_sem until mm_drop_all_locks() returns.
*
* mmap_sem in write mode is required in order to block all operations
* that could modify pagetables and free pages without need of
* altering the vma layout. It's also needed in write mode to avoid new
* anon_vmas to be associated with existing vmas.
*
* A single task can't take more than one mm_take_all_locks() in a row
* or it would deadlock.
*
* The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
* mapping->flags avoid to take the same lock twice, if more than one
* vma in this mm is backed by the same anon_vma or address_space.
*
* We take locks in following order, accordingly to comment at beginning
* of mm/rmap.c:
* - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
* hugetlb mapping);
* - all i_mmap_rwsem locks;
* - all anon_vma->rwseml
*
* We can take all locks within these types randomly because the VM code
* doesn't nest them and we protected from parallel mm_take_all_locks() by
* mm_all_locks_mutex.
*
* mm_take_all_locks() and mm_drop_all_locks are expensive operations
* that may have to take thousand of locks.
*
* mm_take_all_locks() can fail if it's interrupted by signals.
*/
int mm_take_all_locks(struct mm_struct *mm)
{
struct vm_area_struct *vma;
struct anon_vma_chain *avc;
BUG_ON(down_read_trylock(&mm->mmap_sem));
mutex_lock(&mm_all_locks_mutex);
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (signal_pending(current))
goto out_unlock;
if (vma->vm_file && vma->vm_file->f_mapping &&
is_vm_hugetlb_page(vma))
vm_lock_mapping(mm, vma->vm_file->f_mapping);
}
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (signal_pending(current))
goto out_unlock;
if (vma->vm_file && vma->vm_file->f_mapping &&
!is_vm_hugetlb_page(vma))
vm_lock_mapping(mm, vma->vm_file->f_mapping);
}
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (signal_pending(current))
goto out_unlock;
if (vma->anon_vma)
list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
vm_lock_anon_vma(mm, avc->anon_vma);
}
return 0;
out_unlock:
mm_drop_all_locks(mm);
return -EINTR;
}
static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
{
if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
/*
* The LSB of head.next can't change to 0 from under
* us because we hold the mm_all_locks_mutex.
*
* We must however clear the bitflag before unlocking
* the vma so the users using the anon_vma->rb_root will
* never see our bitflag.
*
* No need of atomic instructions here, head.next
* can't change from under us until we release the
* anon_vma->root->rwsem.
*/
if (!__test_and_clear_bit(0, (unsigned long *)
&anon_vma->root->rb_root.rb_root.rb_node))
BUG();
anon_vma_unlock_write(anon_vma);
}
}
static void vm_unlock_mapping(struct address_space *mapping)
{
if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
/*
* AS_MM_ALL_LOCKS can't change to 0 from under us
* because we hold the mm_all_locks_mutex.
*/
i_mmap_unlock_write(mapping);
if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
&mapping->flags))
BUG();
}
}
/*
* The mmap_sem cannot be released by the caller until
* mm_drop_all_locks() returns.
*/
void mm_drop_all_locks(struct mm_struct *mm)
{
struct vm_area_struct *vma;
struct anon_vma_chain *avc;
BUG_ON(down_read_trylock(&mm->mmap_sem));
BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (vma->anon_vma)
list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
vm_unlock_anon_vma(avc->anon_vma);
if (vma->vm_file && vma->vm_file->f_mapping)
vm_unlock_mapping(vma->vm_file->f_mapping);
}
mutex_unlock(&mm_all_locks_mutex);
}
/*
* initialise the percpu counter for VM
*/
void __init mmap_init(void)
{
int ret;
ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
VM_BUG_ON(ret);
}
/*
* Initialise sysctl_user_reserve_kbytes.
*
* This is intended to prevent a user from starting a single memory hogging
* process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
* mode.
*
* The default value is min(3% of free memory, 128MB)
* 128MB is enough to recover with sshd/login, bash, and top/kill.
*/
static int init_user_reserve(void)
{
unsigned long free_kbytes;
free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
return 0;
}
subsys_initcall(init_user_reserve);
/*
* Initialise sysctl_admin_reserve_kbytes.
*
* The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
* to log in and kill a memory hogging process.
*
* Systems with more than 256MB will reserve 8MB, enough to recover
* with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
* only reserve 3% of free pages by default.
*/
static int init_admin_reserve(void)
{
unsigned long free_kbytes;
free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
return 0;
}
subsys_initcall(init_admin_reserve);
/*
* Reinititalise user and admin reserves if memory is added or removed.
*
* The default user reserve max is 128MB, and the default max for the
* admin reserve is 8MB. These are usually, but not always, enough to
* enable recovery from a memory hogging process using login/sshd, a shell,
* and tools like top. It may make sense to increase or even disable the
* reserve depending on the existence of swap or variations in the recovery
* tools. So, the admin may have changed them.
*
* If memory is added and the reserves have been eliminated or increased above
* the default max, then we'll trust the admin.
*
* If memory is removed and there isn't enough free memory, then we
* need to reset the reserves.
*
* Otherwise keep the reserve set by the admin.
*/
static int reserve_mem_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
unsigned long tmp, free_kbytes;
switch (action) {
case MEM_ONLINE:
/* Default max is 128MB. Leave alone if modified by operator. */
tmp = sysctl_user_reserve_kbytes;
if (0 < tmp && tmp < (1UL << 17))
init_user_reserve();
/* Default max is 8MB. Leave alone if modified by operator. */
tmp = sysctl_admin_reserve_kbytes;
if (0 < tmp && tmp < (1UL << 13))
init_admin_reserve();
break;
case MEM_OFFLINE:
free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
if (sysctl_user_reserve_kbytes > free_kbytes) {
init_user_reserve();
pr_info("vm.user_reserve_kbytes reset to %lu\n",
sysctl_user_reserve_kbytes);
}
if (sysctl_admin_reserve_kbytes > free_kbytes) {
init_admin_reserve();
pr_info("vm.admin_reserve_kbytes reset to %lu\n",
sysctl_admin_reserve_kbytes);
}
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block reserve_mem_nb = {
.notifier_call = reserve_mem_notifier,
};
static int __meminit init_reserve_notifier(void)
{
if (register_hotmemory_notifier(&reserve_mem_nb))
pr_err("Failed registering memory add/remove notifier for admin reserve\n");
return 0;
}
subsys_initcall(init_reserve_notifier);
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_1432_0 |
crossvul-cpp_data_bad_3959_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2001 Jean-Fredric Clere, Nikolas Zimmermann, Georg Acher
* Mark Cave-Ayland, Carlo E Prelz, Dick Streefland
* Copyright (c) 2002, 2003 Tuukka Toivonen
* Copyright (c) 2008 Erik Andrén
*
* P/N 861037: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0010: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0020: Sensor Photobit PB100 ASIC STV0600-1 - QuickCam Express
* P/N 861055: Sensor ST VV6410 ASIC STV0610 - LEGO cam
* P/N 861075-0040: Sensor HDCS1000 ASIC
* P/N 961179-0700: Sensor ST VV6410 ASIC STV0602 - Dexxa WebCam USB
* P/N 861040-0000: Sensor ST VV6410 ASIC STV0610 - QuickCam Web
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/input.h>
#include "stv06xx_sensor.h"
MODULE_AUTHOR("Erik Andrén");
MODULE_DESCRIPTION("STV06XX USB Camera Driver");
MODULE_LICENSE("GPL");
static bool dump_bridge;
static bool dump_sensor;
int stv06xx_write_bridge(struct sd *sd, u16 address, u16 i2c_data)
{
int err;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
u8 len = (i2c_data > 0xff) ? 2 : 1;
buf[0] = i2c_data & 0xff;
buf[1] = (i2c_data >> 8) & 0xff;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, address, 0, buf, len,
STV06XX_URB_MSG_TIMEOUT);
gspca_dbg(gspca_dev, D_CONF, "Written 0x%x to address 0x%x, status: %d\n",
i2c_data, address, err);
return (err < 0) ? err : 0;
}
int stv06xx_read_bridge(struct sd *sd, u16 address, u8 *i2c_data)
{
int err;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
err = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
0x04, 0xc0, address, 0, buf, 1,
STV06XX_URB_MSG_TIMEOUT);
*i2c_data = buf[0];
gspca_dbg(gspca_dev, D_CONF, "Reading 0x%x from address 0x%x, status %d\n",
*i2c_data, address, err);
return (err < 0) ? err : 0;
}
/* Wraps the normal write sensor bytes / words functions for writing a
single value */
int stv06xx_write_sensor(struct sd *sd, u8 address, u16 value)
{
if (sd->sensor->i2c_len == 2) {
u16 data[2] = { address, value };
return stv06xx_write_sensor_words(sd, data, 1);
} else {
u8 data[2] = { address, value };
return stv06xx_write_sensor_bytes(sd, data, 1);
}
}
static int stv06xx_write_sensor_finish(struct sd *sd)
{
int err = 0;
if (sd->bridge == BRIDGE_STV610) {
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
buf[0] = 0;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x1704, 0, buf, 1,
STV06XX_URB_MSG_TIMEOUT);
}
return (err < 0) ? err : 0;
}
int stv06xx_write_sensor_bytes(struct sd *sd, const u8 *data, u8 len)
{
int err, i, j;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
gspca_dbg(gspca_dev, D_CONF, "I2C: Command buffer contains %d entries\n",
len);
for (i = 0; i < len;) {
/* Build the command buffer */
memset(buf, 0, I2C_BUFFER_LENGTH);
for (j = 0; j < I2C_MAX_BYTES && i < len; j++, i++) {
buf[j] = data[2*i];
buf[0x10 + j] = data[2*i+1];
gspca_dbg(gspca_dev, D_CONF, "I2C: Writing 0x%02x to reg 0x%02x\n",
data[2*i+1], data[2*i]);
}
buf[0x20] = sd->sensor->i2c_addr;
buf[0x21] = j - 1; /* Number of commands to send - 1 */
buf[0x22] = I2C_WRITE_CMD;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x0400, 0, buf,
I2C_BUFFER_LENGTH,
STV06XX_URB_MSG_TIMEOUT);
if (err < 0)
return err;
}
return stv06xx_write_sensor_finish(sd);
}
int stv06xx_write_sensor_words(struct sd *sd, const u16 *data, u8 len)
{
int err, i, j;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
gspca_dbg(gspca_dev, D_CONF, "I2C: Command buffer contains %d entries\n",
len);
for (i = 0; i < len;) {
/* Build the command buffer */
memset(buf, 0, I2C_BUFFER_LENGTH);
for (j = 0; j < I2C_MAX_WORDS && i < len; j++, i++) {
buf[j] = data[2*i];
buf[0x10 + j * 2] = data[2*i+1];
buf[0x10 + j * 2 + 1] = data[2*i+1] >> 8;
gspca_dbg(gspca_dev, D_CONF, "I2C: Writing 0x%04x to reg 0x%02x\n",
data[2*i+1], data[2*i]);
}
buf[0x20] = sd->sensor->i2c_addr;
buf[0x21] = j - 1; /* Number of commands to send - 1 */
buf[0x22] = I2C_WRITE_CMD;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x0400, 0, buf,
I2C_BUFFER_LENGTH,
STV06XX_URB_MSG_TIMEOUT);
if (err < 0)
return err;
}
return stv06xx_write_sensor_finish(sd);
}
int stv06xx_read_sensor(struct sd *sd, const u8 address, u16 *value)
{
int err;
struct gspca_dev *gspca_dev = (struct gspca_dev *)sd;
struct usb_device *udev = sd->gspca_dev.dev;
__u8 *buf = sd->gspca_dev.usb_buf;
err = stv06xx_write_bridge(sd, STV_I2C_FLUSH, sd->sensor->i2c_flush);
if (err < 0)
return err;
/* Clear mem */
memset(buf, 0, I2C_BUFFER_LENGTH);
buf[0] = address;
buf[0x20] = sd->sensor->i2c_addr;
buf[0x21] = 0;
/* Read I2C register */
buf[0x22] = I2C_READ_CMD;
err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x04, 0x40, 0x1400, 0, buf, I2C_BUFFER_LENGTH,
STV06XX_URB_MSG_TIMEOUT);
if (err < 0) {
pr_err("I2C: Read error writing address: %d\n", err);
return err;
}
err = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
0x04, 0xc0, 0x1410, 0, buf, sd->sensor->i2c_len,
STV06XX_URB_MSG_TIMEOUT);
if (sd->sensor->i2c_len == 2)
*value = buf[0] | (buf[1] << 8);
else
*value = buf[0];
gspca_dbg(gspca_dev, D_CONF, "I2C: Read 0x%x from address 0x%x, status: %d\n",
*value, address, err);
return (err < 0) ? err : 0;
}
/* Dumps all bridge registers */
static void stv06xx_dump_bridge(struct sd *sd)
{
int i;
u8 data, buf;
pr_info("Dumping all stv06xx bridge registers\n");
for (i = 0x1400; i < 0x160f; i++) {
stv06xx_read_bridge(sd, i, &data);
pr_info("Read 0x%x from address 0x%x\n", data, i);
}
pr_info("Testing stv06xx bridge registers for writability\n");
for (i = 0x1400; i < 0x160f; i++) {
stv06xx_read_bridge(sd, i, &data);
buf = data;
stv06xx_write_bridge(sd, i, 0xff);
stv06xx_read_bridge(sd, i, &data);
if (data == 0xff)
pr_info("Register 0x%x is read/write\n", i);
else if (data != buf)
pr_info("Register 0x%x is read/write, but only partially\n",
i);
else
pr_info("Register 0x%x is read-only\n", i);
stv06xx_write_bridge(sd, i, buf);
}
}
/* this function is called at probe and resume time */
static int stv06xx_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int err;
gspca_dbg(gspca_dev, D_PROBE, "Initializing camera\n");
/* Let the usb init settle for a bit
before performing the initialization */
msleep(250);
err = sd->sensor->init(sd);
if (dump_sensor && sd->sensor->dump)
sd->sensor->dump(sd);
return (err < 0) ? err : 0;
}
/* this function is called at probe time */
static int stv06xx_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dbg(gspca_dev, D_PROBE, "Initializing controls\n");
gspca_dev->vdev.ctrl_handler = &gspca_dev->ctrl_handler;
return sd->sensor->init_controls(sd);
}
/* Start the camera */
static int stv06xx_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
struct usb_host_interface *alt;
struct usb_interface *intf;
int err, packet_size;
intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);
alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);
if (!alt) {
gspca_err(gspca_dev, "Couldn't get altsetting\n");
return -EIO;
}
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
err = stv06xx_write_bridge(sd, STV_ISO_SIZE_L, packet_size);
if (err < 0)
return err;
/* Prepare the sensor for start */
err = sd->sensor->start(sd);
if (err < 0)
goto out;
/* Start isochronous streaming */
err = stv06xx_write_bridge(sd, STV_ISO_ENABLE, 1);
out:
if (err < 0)
gspca_dbg(gspca_dev, D_STREAM, "Starting stream failed\n");
else
gspca_dbg(gspca_dev, D_STREAM, "Started streaming\n");
return (err < 0) ? err : 0;
}
static int stv06xx_isoc_init(struct gspca_dev *gspca_dev)
{
struct usb_host_interface *alt;
struct sd *sd = (struct sd *) gspca_dev;
/* Start isoc bandwidth "negotiation" at max isoc bandwidth */
alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];
alt->endpoint[0].desc.wMaxPacketSize =
cpu_to_le16(sd->sensor->max_packet_size[gspca_dev->curr_mode]);
return 0;
}
static int stv06xx_isoc_nego(struct gspca_dev *gspca_dev)
{
int ret, packet_size, min_packet_size;
struct usb_host_interface *alt;
struct sd *sd = (struct sd *) gspca_dev;
alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
min_packet_size = sd->sensor->min_packet_size[gspca_dev->curr_mode];
if (packet_size <= min_packet_size)
return -EIO;
packet_size -= 100;
if (packet_size < min_packet_size)
packet_size = min_packet_size;
alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(packet_size);
ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 1);
if (ret < 0)
gspca_err(gspca_dev, "set alt 1 err %d\n", ret);
return ret;
}
static void stv06xx_stopN(struct gspca_dev *gspca_dev)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
/* stop ISO-streaming */
err = stv06xx_write_bridge(sd, STV_ISO_ENABLE, 0);
if (err < 0)
goto out;
err = sd->sensor->stop(sd);
out:
if (err < 0)
gspca_dbg(gspca_dev, D_STREAM, "Failed to stop stream\n");
else
gspca_dbg(gspca_dev, D_STREAM, "Stopped streaming\n");
}
/*
* Analyse an USB packet of the data stream and store it appropriately.
* Each packet contains an integral number of chunks. Each chunk has
* 2-bytes identification, followed by 2-bytes that describe the chunk
* length. Known/guessed chunk identifications are:
* 8001/8005/C001/C005 - Begin new frame
* 8002/8006/C002/C006 - End frame
* 0200/4200 - Contains actual image data, bayer or compressed
* 0005 - 11 bytes of unknown data
* 0100 - 2 bytes of unknown data
* The 0005 and 0100 chunks seem to appear only in compressed stream.
*/
static void stv06xx_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dbg(gspca_dev, D_PACK, "Packet of length %d arrived\n", len);
/* A packet may contain several frames
loop until the whole packet is reached */
while (len) {
int id, chunk_len;
if (len < 4) {
gspca_dbg(gspca_dev, D_PACK, "Packet is smaller than 4 bytes\n");
return;
}
/* Capture the id */
id = (data[0] << 8) | data[1];
/* Capture the chunk length */
chunk_len = (data[2] << 8) | data[3];
gspca_dbg(gspca_dev, D_PACK, "Chunk id: %x, length: %d\n",
id, chunk_len);
data += 4;
len -= 4;
if (len < chunk_len) {
gspca_err(gspca_dev, "URB packet length is smaller than the specified chunk length\n");
gspca_dev->last_packet_type = DISCARD_PACKET;
return;
}
/* First byte seem to be 02=data 2nd byte is unknown??? */
if (sd->bridge == BRIDGE_ST6422 && (id & 0xff00) == 0x0200)
goto frame_data;
switch (id) {
case 0x0200:
case 0x4200:
frame_data:
gspca_dbg(gspca_dev, D_PACK, "Frame data packet detected\n");
if (sd->to_skip) {
int skip = (sd->to_skip < chunk_len) ?
sd->to_skip : chunk_len;
data += skip;
len -= skip;
chunk_len -= skip;
sd->to_skip -= skip;
}
gspca_frame_add(gspca_dev, INTER_PACKET,
data, chunk_len);
break;
case 0x8001:
case 0x8005:
case 0xc001:
case 0xc005:
gspca_dbg(gspca_dev, D_PACK, "Starting new frame\n");
/* Create a new frame, chunk length should be zero */
gspca_frame_add(gspca_dev, FIRST_PACKET,
NULL, 0);
if (sd->bridge == BRIDGE_ST6422)
sd->to_skip = gspca_dev->pixfmt.width * 4;
if (chunk_len)
gspca_err(gspca_dev, "Chunk length is non-zero on a SOF\n");
break;
case 0x8002:
case 0x8006:
case 0xc002:
gspca_dbg(gspca_dev, D_PACK, "End of frame detected\n");
/* Complete the last frame (if any) */
gspca_frame_add(gspca_dev, LAST_PACKET,
NULL, 0);
if (chunk_len)
gspca_err(gspca_dev, "Chunk length is non-zero on a EOF\n");
break;
case 0x0005:
gspca_dbg(gspca_dev, D_PACK, "Chunk 0x005 detected\n");
/* Unknown chunk with 11 bytes of data,
occurs just before end of each frame
in compressed mode */
break;
case 0x0100:
gspca_dbg(gspca_dev, D_PACK, "Chunk 0x0100 detected\n");
/* Unknown chunk with 2 bytes of data,
occurs 2-3 times per USB interrupt */
break;
case 0x42ff:
gspca_dbg(gspca_dev, D_PACK, "Chunk 0x42ff detected\n");
/* Special chunk seen sometimes on the ST6422 */
break;
default:
gspca_dbg(gspca_dev, D_PACK, "Unknown chunk 0x%04x detected\n",
id);
/* Unknown chunk */
}
data += chunk_len;
len -= chunk_len;
}
}
#if IS_ENABLED(CONFIG_INPUT)
static int sd_int_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* interrupt packet data */
int len) /* interrupt packet length */
{
int ret = -EINVAL;
if (len == 1 && (data[0] == 0x80 || data[0] == 0x10)) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1);
input_sync(gspca_dev->input_dev);
ret = 0;
}
if (len == 1 && (data[0] == 0x88 || data[0] == 0x11)) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
ret = 0;
}
return ret;
}
#endif
static int stv06xx_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id);
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = stv06xx_config,
.init = stv06xx_init,
.init_controls = stv06xx_init_controls,
.start = stv06xx_start,
.stopN = stv06xx_stopN,
.pkt_scan = stv06xx_pkt_scan,
.isoc_init = stv06xx_isoc_init,
.isoc_nego = stv06xx_isoc_nego,
#if IS_ENABLED(CONFIG_INPUT)
.int_pkt_scan = sd_int_pkt_scan,
#endif
};
/* This function is called at probe time */
static int stv06xx_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dbg(gspca_dev, D_PROBE, "Configuring camera\n");
sd->bridge = id->driver_info;
gspca_dev->sd_desc = &sd_desc;
if (dump_bridge)
stv06xx_dump_bridge(sd);
sd->sensor = &stv06xx_sensor_st6422;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_vv6410;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_hdcs1x00;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_hdcs1020;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = &stv06xx_sensor_pb0100;
if (!sd->sensor->probe(sd))
return 0;
sd->sensor = NULL;
return -ENODEV;
}
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x046d, 0x0840), .driver_info = BRIDGE_STV600 }, /* QuickCam Express */
{USB_DEVICE(0x046d, 0x0850), .driver_info = BRIDGE_STV610 }, /* LEGO cam / QuickCam Web */
{USB_DEVICE(0x046d, 0x0870), .driver_info = BRIDGE_STV602 }, /* Dexxa WebCam USB */
{USB_DEVICE(0x046D, 0x08F0), .driver_info = BRIDGE_ST6422 }, /* QuickCam Messenger */
{USB_DEVICE(0x046D, 0x08F5), .driver_info = BRIDGE_ST6422 }, /* QuickCam Communicate */
{USB_DEVICE(0x046D, 0x08F6), .driver_info = BRIDGE_ST6422 }, /* QuickCam Messenger (new) */
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static void sd_disconnect(struct usb_interface *intf)
{
struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
struct sd *sd = (struct sd *) gspca_dev;
void *priv = sd->sensor_priv;
gspca_dbg(gspca_dev, D_PROBE, "Disconnecting the stv06xx device\n");
sd->sensor = NULL;
gspca_disconnect(intf);
kfree(priv);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = sd_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
module_param(dump_bridge, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dump_bridge, "Dumps all usb bridge registers at startup");
module_param(dump_sensor, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dump_sensor, "Dumps all sensor registers at startup");
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3959_0 |
crossvul-cpp_data_good_1070_0 | /**********************************************************************
regparse.c - Onigmo (Oniguruma-mod) (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2008 K.Kosako <sndgk393 AT ybb DOT ne DOT jp>
* Copyright (c) 2011-2019 K.Takata <kentkt AT csc DOT jp>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "regparse.h"
#include <stdarg.h>
#define WARN_BUFSIZE 256
#define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
const OnigSyntaxType OnigSyntaxRuby = {
(( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY |
ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 |
ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS |
ONIG_SYN_OP_ESC_C_CONTROL )
& ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END )
, ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT |
ONIG_SYN_OP2_OPTION_RUBY |
ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF |
ONIG_SYN_OP2_ESC_G_SUBEXP_CALL |
ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY |
ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT |
ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT |
ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL |
ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB |
ONIG_SYN_OP2_ESC_H_XDIGIT |
#ifndef RUBY
ONIG_SYN_OP2_ESC_U_HEX4 |
#endif
ONIG_SYN_OP2_ESC_CAPITAL_X_EXTENDED_GRAPHEME_CLUSTER |
ONIG_SYN_OP2_QMARK_LPAREN_CONDITION |
ONIG_SYN_OP2_ESC_CAPITAL_R_LINEBREAK |
ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP |
ONIG_SYN_OP2_QMARK_TILDE_ABSENT )
, ( SYN_GNU_REGEX_BV |
ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV |
ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND |
ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP |
ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME |
ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY |
ONIG_SYN_WARN_CC_OP_NOT_ESCAPED |
ONIG_SYN_WARN_CC_DUP |
ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT )
, ( ONIG_OPTION_ASCII_RANGE | ONIG_OPTION_POSIX_BRACKET_ALL_RANGE |
ONIG_OPTION_WORD_BOUND_ALL_RANGE )
,
{
(OnigCodePoint )'\\' /* esc */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */
, (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */
}
};
const OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY;
extern void onig_null_warn(const char* s ARG_UNUSED) { }
#ifdef DEFAULT_WARN_FUNCTION
static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION;
#else
static OnigWarnFunc onig_warn = onig_null_warn;
#endif
#ifdef DEFAULT_VERB_WARN_FUNCTION
static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION;
#else
static OnigWarnFunc onig_verb_warn = onig_null_warn;
#endif
extern void onig_set_warn_func(OnigWarnFunc f)
{
onig_warn = f;
}
extern void onig_set_verb_warn_func(OnigWarnFunc f)
{
onig_verb_warn = f;
}
static void CC_DUP_WARN(ScanEnv *env, OnigCodePoint from, OnigCodePoint to);
static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT;
extern unsigned int
onig_get_parse_depth_limit(void)
{
return ParseDepthLimit;
}
extern int
onig_set_parse_depth_limit(unsigned int depth)
{
if (depth == 0)
ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT;
else
ParseDepthLimit = depth;
return 0;
}
static void
bbuf_free(BBuf* bbuf)
{
if (IS_NOT_NULL(bbuf)) {
if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p);
xfree(bbuf);
}
}
static int
bbuf_clone(BBuf** rto, BBuf* from)
{
int r;
BBuf *to;
*rto = to = (BBuf* )xmalloc(sizeof(BBuf));
CHECK_NULL_RETURN_MEMERR(to);
r = BBUF_INIT(to, from->alloc);
if (r != 0) return r;
to->used = from->used;
xmemcpy(to->p, from->p, from->used);
return 0;
}
#define BACKREF_REL_TO_ABS(rel_no, env) \
((env)->num_mem + 1 + (rel_no))
#define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f))
#define MBCODE_START_POS(enc) \
(OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80)
#define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \
add_code_range_to_buf(pbuf, env, MBCODE_START_POS(enc), ONIG_LAST_CODE_POINT)
#define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\
if (! ONIGENC_IS_SINGLEBYTE(enc)) {\
r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\
if (r) return r;\
}\
} while (0)
#define BITSET_SET_BIT_CHKDUP(bs, pos) do { \
if (BITSET_AT(bs, pos)) CC_DUP_WARN(env, pos, pos); \
BS_ROOM(bs, pos) |= BS_BIT(pos); \
} while (0)
#define BITSET_IS_EMPTY(bs,empty) do {\
int i;\
empty = 1;\
for (i = 0; i < BITSET_SIZE; i++) {\
if ((bs)[i] != 0) {\
empty = 0; break;\
}\
}\
} while (0)
static void
bitset_set_range(ScanEnv *env, BitSetRef bs, int from, int to)
{
int i;
for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) {
BITSET_SET_BIT_CHKDUP(bs, i);
}
}
#if 0
static void
bitset_set_all(BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); }
}
#endif
static void
bitset_invert(BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~(bs[i]); }
}
static void
bitset_invert_to(BitSetRef from, BitSetRef to)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { to[i] = ~(from[i]); }
}
static void
bitset_and(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { dest[i] &= bs[i]; }
}
static void
bitset_or(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { dest[i] |= bs[i]; }
}
static void
bitset_copy(BitSetRef dest, BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { dest[i] = bs[i]; }
}
#if defined(USE_NAMED_GROUP) && !defined(USE_ST_LIBRARY)
extern int
onig_strncmp(const UChar* s1, const UChar* s2, int n)
{
int x;
while (n-- > 0) {
x = *s2++ - *s1++;
if (x) return x;
}
return 0;
}
#endif
extern void
onig_strcpy(UChar* dest, const UChar* src, const UChar* end)
{
ptrdiff_t len = end - src;
if (len > 0) {
xmemcpy(dest, src, len);
dest[len] = (UChar )0;
}
}
#ifdef USE_NAMED_GROUP
static UChar*
strdup_with_null(OnigEncoding enc, UChar* s, UChar* end)
{
ptrdiff_t slen;
int term_len, i;
UChar *r;
slen = end - s;
term_len = ONIGENC_MBC_MINLEN(enc);
r = (UChar* )xmalloc(slen + term_len);
CHECK_NULL_RETURN(r);
xmemcpy(r, s, slen);
for (i = 0; i < term_len; i++)
r[slen + i] = (UChar )0;
return r;
}
#endif
/* scan pattern methods */
#define PEND_VALUE 0
#ifdef __GNUC__
/* get rid of Wunused-but-set-variable and Wuninitialized */
# define PFETCH_READY UChar* pfetch_prev = NULL; (void)pfetch_prev
#else
# define PFETCH_READY UChar* pfetch_prev
#endif
#define PEND (p < end ? 0 : 1)
#define PUNFETCH p = pfetch_prev
#define PINC do { \
pfetch_prev = p; \
p += enclen(enc, p, end); \
} while (0)
#define PFETCH(c) do { \
c = ((enc->max_enc_len == 1) ? *p : ONIGENC_MBC_TO_CODE(enc, p, end)); \
pfetch_prev = p; \
p += enclen(enc, p, end); \
} while (0)
#define PINC_S do { \
p += enclen(enc, p, end); \
} while (0)
#define PFETCH_S(c) do { \
c = ((enc->max_enc_len == 1) ? *p : ONIGENC_MBC_TO_CODE(enc, p, end)); \
p += enclen(enc, p, end); \
} while (0)
#define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE)
#define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c)
static UChar*
strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end,
size_t capa)
{
UChar* r;
if (dest)
r = (UChar* )xrealloc(dest, capa + 1);
else
r = (UChar* )xmalloc(capa + 1);
CHECK_NULL_RETURN(r);
onig_strcpy(r + (dest_end - dest), src, src_end);
return r;
}
/* dest on static area */
static UChar*
strcat_capa_from_static(UChar* dest, UChar* dest_end,
const UChar* src, const UChar* src_end, size_t capa)
{
UChar* r;
r = (UChar* )xmalloc(capa + 1);
CHECK_NULL_RETURN(r);
onig_strcpy(r, dest, dest_end);
onig_strcpy(r + (dest_end - dest), src, src_end);
return r;
}
#ifdef USE_ST_LIBRARY
# ifdef RUBY
# include "ruby/st.h"
# else
# include "st.h"
# endif
typedef struct {
const UChar* s;
const UChar* end;
} st_str_end_key;
static int
str_end_cmp(st_data_t xp, st_data_t yp)
{
const st_str_end_key *x, *y;
const UChar *p, *q;
int c;
x = (const st_str_end_key *)xp;
y = (const st_str_end_key *)yp;
if ((x->end - x->s) != (y->end - y->s))
return 1;
p = x->s;
q = y->s;
while (p < x->end) {
c = (int )*p - (int )*q;
if (c != 0) return c;
p++; q++;
}
return 0;
}
static st_index_t
str_end_hash(st_data_t xp)
{
const st_str_end_key *x = (const st_str_end_key *)xp;
const UChar *p;
st_index_t val = 0;
p = x->s;
while (p < x->end) {
val = val * 997 + (int )*p++;
}
return val + (val >> 5);
}
extern hash_table_type*
onig_st_init_strend_table_with_size(st_index_t size)
{
static const struct st_hash_type hashType = {
str_end_cmp,
str_end_hash,
};
return (hash_table_type* )
onig_st_init_table_with_size(&hashType, size);
}
extern int
onig_st_lookup_strend(hash_table_type* table, const UChar* str_key,
const UChar* end_key, hash_data_type *value)
{
st_str_end_key key;
key.s = (UChar* )str_key;
key.end = (UChar* )end_key;
return onig_st_lookup(table, (st_data_t )(&key), value);
}
extern int
onig_st_insert_strend(hash_table_type* table, const UChar* str_key,
const UChar* end_key, hash_data_type value)
{
st_str_end_key* key;
int result;
key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key));
key->s = (UChar* )str_key;
key->end = (UChar* )end_key;
result = onig_st_insert(table, (st_data_t )key, value);
if (result) {
xfree(key);
}
return result;
}
#endif /* USE_ST_LIBRARY */
#ifdef USE_NAMED_GROUP
# define INIT_NAME_BACKREFS_ALLOC_NUM 8
typedef struct {
UChar* name;
size_t name_len; /* byte length */
int back_num; /* number of backrefs */
int back_alloc;
int back_ref1;
int* back_refs;
} NameEntry;
# ifdef USE_ST_LIBRARY
typedef st_table NameTable;
typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */
# ifdef ONIG_DEBUG
static int
i_print_name_entry(UChar* key, NameEntry* e, void* arg)
{
int i;
FILE* fp = (FILE* )arg;
fprintf(fp, "%s: ", e->name);
if (e->back_num == 0)
fputs("-", fp);
else if (e->back_num == 1)
fprintf(fp, "%d", e->back_ref1);
else {
for (i = 0; i < e->back_num; i++) {
if (i > 0) fprintf(fp, ", ");
fprintf(fp, "%d", e->back_refs[i]);
}
}
fputs("\n", fp);
return ST_CONTINUE;
}
extern int
onig_print_names(FILE* fp, regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
fprintf(fp, "name table\n");
onig_st_foreach(t, i_print_name_entry, (HashDataType )fp);
fputs("\n", fp);
}
return 0;
}
# endif /* ONIG_DEBUG */
static int
i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED)
{
xfree(e->name);
if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs);
xfree(key);
xfree(e);
return ST_DELETE;
}
static int
names_clear(regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
onig_st_foreach(t, i_free_name_entry, 0);
}
return 0;
}
extern int
onig_names_free(regex_t* reg)
{
int r;
NameTable* t;
r = names_clear(reg);
if (r) return r;
t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) onig_st_free_table(t);
reg->name_table = (void* )NULL;
return 0;
}
static NameEntry*
name_find(regex_t* reg, const UChar* name, const UChar* name_end)
{
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
e = (NameEntry* )NULL;
if (IS_NOT_NULL(t)) {
onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e)));
}
return e;
}
typedef struct {
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*);
regex_t* reg;
void* arg;
int ret;
OnigEncoding enc;
} INamesArg;
static int
i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg)
{
int r = (*(arg->func))(e->name,
e->name + e->name_len,
e->back_num,
(e->back_num > 1 ? e->back_refs : &(e->back_ref1)),
arg->reg, arg->arg);
if (r != 0) {
arg->ret = r;
return ST_STOP;
}
return ST_CONTINUE;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
INamesArg narg;
NameTable* t = (NameTable* )reg->name_table;
narg.ret = 0;
if (IS_NOT_NULL(t)) {
narg.func = func;
narg.reg = reg;
narg.arg = arg;
narg.enc = reg->enc; /* should be pattern encoding. */
onig_st_foreach(t, i_names, (HashDataType )&narg);
}
return narg.ret;
}
static int
i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map)
{
int i;
if (e->back_num > 1) {
for (i = 0; i < e->back_num; i++) {
e->back_refs[i] = map[e->back_refs[i]].new_val;
}
}
else if (e->back_num == 1) {
e->back_ref1 = map[e->back_ref1].new_val;
}
return ST_CONTINUE;
}
extern int
onig_renumber_name_table(regex_t* reg, GroupNumRemap* map)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
onig_st_foreach(t, i_renumber_name, (HashDataType )map);
}
return 0;
}
extern int
onig_number_of_names(const regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t))
return (int )t->num_entries;
else
return 0;
}
# else /* USE_ST_LIBRARY */
# define INIT_NAMES_ALLOC_NUM 8
typedef struct {
NameEntry* e;
int num;
int alloc;
} NameTable;
# ifdef ONIG_DEBUG
extern int
onig_print_names(FILE* fp, regex_t* reg)
{
int i, j;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t) && t->num > 0) {
fprintf(fp, "name table\n");
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
fprintf(fp, "%s: ", e->name);
if (e->back_num == 0) {
fputs("-", fp);
}
else if (e->back_num == 1) {
fprintf(fp, "%d", e->back_ref1);
}
else {
for (j = 0; j < e->back_num; j++) {
if (j > 0) fprintf(fp, ", ");
fprintf(fp, "%d", e->back_refs[j]);
}
}
fputs("\n", fp);
}
fputs("\n", fp);
}
return 0;
}
# endif
static int
names_clear(regex_t* reg)
{
int i;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
if (IS_NOT_NULL(e->name)) {
xfree(e->name);
e->name = NULL;
e->name_len = 0;
e->back_num = 0;
e->back_alloc = 0;
if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs);
e->back_refs = (int* )NULL;
}
}
if (IS_NOT_NULL(t->e)) {
xfree(t->e);
t->e = NULL;
}
t->num = 0;
}
return 0;
}
extern int
onig_names_free(regex_t* reg)
{
int r;
NameTable* t;
r = names_clear(reg);
if (r) return r;
t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) xfree(t);
reg->name_table = NULL;
return 0;
}
static NameEntry*
name_find(regex_t* reg, const UChar* name, const UChar* name_end)
{
int i, len;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
len = name_end - name;
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
if (len == e->name_len && onig_strncmp(name, e->name, len) == 0)
return e;
}
}
return (NameEntry* )NULL;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
int i, r;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t)) {
for (i = 0; i < t->num; i++) {
e = &(t->e[i]);
r = (*func)(e->name, e->name + e->name_len, e->back_num,
(e->back_num > 1 ? e->back_refs : &(e->back_ref1)),
reg, arg);
if (r != 0) return r;
}
}
return 0;
}
extern int
onig_number_of_names(const regex_t* reg)
{
NameTable* t = (NameTable* )reg->name_table;
if (IS_NOT_NULL(t))
return t->num;
else
return 0;
}
# endif /* else USE_ST_LIBRARY */
static int
name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env)
{
int alloc;
NameEntry* e;
NameTable* t = (NameTable* )reg->name_table;
if (name_end - name <= 0)
return ONIGERR_EMPTY_GROUP_NAME;
e = name_find(reg, name, name_end);
if (IS_NULL(e)) {
# ifdef USE_ST_LIBRARY
if (IS_NULL(t)) {
t = onig_st_init_strend_table_with_size(5);
reg->name_table = (void* )t;
}
e = (NameEntry* )xmalloc(sizeof(NameEntry));
CHECK_NULL_RETURN_MEMERR(e);
e->name = strdup_with_null(reg->enc, name, name_end);
if (IS_NULL(e->name)) {
xfree(e);
return ONIGERR_MEMORY;
}
onig_st_insert_strend(t, e->name, (e->name + (name_end - name)),
(HashDataType )e);
e->name_len = name_end - name;
e->back_num = 0;
e->back_alloc = 0;
e->back_refs = (int* )NULL;
# else
if (IS_NULL(t)) {
alloc = INIT_NAMES_ALLOC_NUM;
t = (NameTable* )xmalloc(sizeof(NameTable));
CHECK_NULL_RETURN_MEMERR(t);
t->e = NULL;
t->alloc = 0;
t->num = 0;
t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc);
if (IS_NULL(t->e)) {
xfree(t);
return ONIGERR_MEMORY;
}
t->alloc = alloc;
reg->name_table = t;
goto clear;
}
else if (t->num == t->alloc) {
int i;
NameEntry* p;
alloc = t->alloc * 2;
p = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc);
CHECK_NULL_RETURN_MEMERR(p);
t->e = p;
t->alloc = alloc;
clear:
for (i = t->num; i < t->alloc; i++) {
t->e[i].name = NULL;
t->e[i].name_len = 0;
t->e[i].back_num = 0;
t->e[i].back_alloc = 0;
t->e[i].back_refs = (int* )NULL;
}
}
e = &(t->e[t->num]);
t->num++;
e->name = strdup_with_null(reg->enc, name, name_end);
if (IS_NULL(e->name)) return ONIGERR_MEMORY;
e->name_len = name_end - name;
# endif
}
if (e->back_num >= 1 &&
! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) {
onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME,
name, name_end);
return ONIGERR_MULTIPLEX_DEFINED_NAME;
}
e->back_num++;
if (e->back_num == 1) {
e->back_ref1 = backref;
}
else {
if (e->back_num == 2) {
alloc = INIT_NAME_BACKREFS_ALLOC_NUM;
e->back_refs = (int* )xmalloc(sizeof(int) * alloc);
CHECK_NULL_RETURN_MEMERR(e->back_refs);
e->back_alloc = alloc;
e->back_refs[0] = e->back_ref1;
e->back_refs[1] = backref;
}
else {
if (e->back_num > e->back_alloc) {
int* p;
alloc = e->back_alloc * 2;
p = (int* )xrealloc(e->back_refs, sizeof(int) * alloc);
CHECK_NULL_RETURN_MEMERR(p);
e->back_refs = p;
e->back_alloc = alloc;
}
e->back_refs[e->back_num - 1] = backref;
}
}
return 0;
}
extern int
onig_name_to_group_numbers(regex_t* reg, const UChar* name,
const UChar* name_end, int** nums)
{
NameEntry* e = name_find(reg, name, name_end);
if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE;
switch (e->back_num) {
case 0:
*nums = 0;
break;
case 1:
*nums = &(e->back_ref1);
break;
default:
*nums = e->back_refs;
break;
}
return e->back_num;
}
extern int
onig_name_to_backref_number(regex_t* reg, const UChar* name,
const UChar* name_end, const OnigRegion *region)
{
int i, n, *nums;
n = onig_name_to_group_numbers(reg, name, name_end, &nums);
if (n < 0)
return n;
else if (n == 0)
return ONIGERR_PARSER_BUG;
else if (n == 1)
return nums[0];
else {
if (IS_NOT_NULL(region)) {
for (i = n - 1; i >= 0; i--) {
if (region->beg[nums[i]] != ONIG_REGION_NOTPOS)
return nums[i];
}
}
return nums[n - 1];
}
}
#else /* USE_NAMED_GROUP */
extern int
onig_name_to_group_numbers(regex_t* reg, const UChar* name,
const UChar* name_end, int** nums)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_name_to_backref_number(regex_t* reg, const UChar* name,
const UChar* name_end, const OnigRegion* region)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_foreach_name(regex_t* reg,
int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg)
{
return ONIG_NO_SUPPORT_CONFIG;
}
extern int
onig_number_of_names(const regex_t* reg)
{
return 0;
}
#endif /* else USE_NAMED_GROUP */
extern int
onig_noname_group_capture_is_active(const regex_t* reg)
{
if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP))
return 0;
#ifdef USE_NAMED_GROUP
if (onig_number_of_names(reg) > 0 &&
IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) &&
!ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) {
return 0;
}
#endif
return 1;
}
#define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16
static void
scan_env_clear(ScanEnv* env)
{
int i;
BIT_STATUS_CLEAR(env->capture_history);
BIT_STATUS_CLEAR(env->bt_mem_start);
BIT_STATUS_CLEAR(env->bt_mem_end);
BIT_STATUS_CLEAR(env->backrefed_mem);
env->error = (UChar* )NULL;
env->error_end = (UChar* )NULL;
env->num_call = 0;
env->num_mem = 0;
#ifdef USE_NAMED_GROUP
env->num_named = 0;
#endif
env->mem_alloc = 0;
env->mem_nodes_dynamic = (Node** )NULL;
for (i = 0; i < SCANENV_MEMNODES_SIZE; i++)
env->mem_nodes_static[i] = NULL_NODE;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
env->num_comb_exp_check = 0;
env->comb_exp_max_regnum = 0;
env->curr_max_regnum = 0;
env->has_recursion = 0;
#endif
env->parse_depth = 0;
env->warnings_flag = 0;
}
static int
scan_env_add_mem_entry(ScanEnv* env)
{
int i, need, alloc;
Node** p;
need = env->num_mem + 1;
if (need > ONIG_MAX_CAPTURE_GROUP_NUM)
return ONIGERR_TOO_MANY_CAPTURE_GROUPS;
if (need >= SCANENV_MEMNODES_SIZE) {
if (env->mem_alloc <= need) {
if (IS_NULL(env->mem_nodes_dynamic)) {
alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE;
p = (Node** )xmalloc(sizeof(Node*) * alloc);
CHECK_NULL_RETURN_MEMERR(p);
xmemcpy(p, env->mem_nodes_static,
sizeof(Node*) * SCANENV_MEMNODES_SIZE);
}
else {
alloc = env->mem_alloc * 2;
p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc);
CHECK_NULL_RETURN_MEMERR(p);
}
for (i = env->num_mem + 1; i < alloc; i++)
p[i] = NULL_NODE;
env->mem_nodes_dynamic = p;
env->mem_alloc = alloc;
}
}
env->num_mem++;
return env->num_mem;
}
static int
scan_env_set_mem_node(ScanEnv* env, int num, Node* node)
{
if (env->num_mem >= num)
SCANENV_MEM_NODES(env)[num] = node;
else
return ONIGERR_PARSER_BUG;
return 0;
}
extern void
onig_node_free(Node* node)
{
start:
if (IS_NULL(node)) return ;
switch (NTYPE(node)) {
case NT_STR:
if (NSTR(node)->capa != 0 &&
IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) {
xfree(NSTR(node)->s);
}
break;
case NT_LIST:
case NT_ALT:
onig_node_free(NCAR(node));
{
Node* next_node = NCDR(node);
xfree(node);
node = next_node;
goto start;
}
break;
case NT_CCLASS:
{
CClassNode* cc = NCCLASS(node);
if (cc->mbuf)
bbuf_free(cc->mbuf);
}
break;
case NT_QTFR:
if (NQTFR(node)->target)
onig_node_free(NQTFR(node)->target);
break;
case NT_ENCLOSE:
if (NENCLOSE(node)->target)
onig_node_free(NENCLOSE(node)->target);
break;
case NT_BREF:
if (IS_NOT_NULL(NBREF(node)->back_dynamic))
xfree(NBREF(node)->back_dynamic);
break;
case NT_ANCHOR:
if (NANCHOR(node)->target)
onig_node_free(NANCHOR(node)->target);
break;
}
xfree(node);
}
static Node*
node_new(void)
{
Node* node;
node = (Node* )xmalloc(sizeof(Node));
/* xmemset(node, 0, sizeof(Node)); */
return node;
}
static void
initialize_cclass(CClassNode* cc)
{
BITSET_CLEAR(cc->bs);
/* cc->base.flags = 0; */
cc->flags = 0;
cc->mbuf = NULL;
}
static Node*
node_new_cclass(void)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CCLASS);
initialize_cclass(NCCLASS(node));
return node;
}
static Node*
node_new_ctype(int type, int not, int ascii_range)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CTYPE);
NCTYPE(node)->ctype = type;
NCTYPE(node)->not = not;
NCTYPE(node)->ascii_range = ascii_range;
return node;
}
static Node*
node_new_anychar(void)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CANY);
return node;
}
static Node*
node_new_list(Node* left, Node* right)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_LIST);
NCAR(node) = left;
NCDR(node) = right;
return node;
}
extern Node*
onig_node_new_list(Node* left, Node* right)
{
return node_new_list(left, right);
}
extern Node*
onig_node_list_add(Node* list, Node* x)
{
Node *n;
n = onig_node_new_list(x, NULL);
if (IS_NULL(n)) return NULL_NODE;
if (IS_NOT_NULL(list)) {
while (IS_NOT_NULL(NCDR(list)))
list = NCDR(list);
NCDR(list) = n;
}
return n;
}
extern Node*
onig_node_new_alt(Node* left, Node* right)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ALT);
NCAR(node) = left;
NCDR(node) = right;
return node;
}
extern Node*
onig_node_new_anchor(int type)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ANCHOR);
NANCHOR(node)->type = type;
NANCHOR(node)->target = NULL;
NANCHOR(node)->char_len = -1;
NANCHOR(node)->ascii_range = 0;
return node;
}
static Node*
node_new_backref(int back_num, int* backrefs, int by_name,
#ifdef USE_BACKREF_WITH_LEVEL
int exist_level, int nest_level,
#endif
ScanEnv* env)
{
int i;
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_BREF);
NBREF(node)->state = 0;
NBREF(node)->back_num = back_num;
NBREF(node)->back_dynamic = (int* )NULL;
if (by_name != 0)
NBREF(node)->state |= NST_NAME_REF;
#ifdef USE_BACKREF_WITH_LEVEL
if (exist_level != 0) {
NBREF(node)->state |= NST_NEST_LEVEL;
NBREF(node)->nest_level = nest_level;
}
#endif
for (i = 0; i < back_num; i++) {
if (backrefs[i] <= env->num_mem &&
IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) {
NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */
break;
}
}
if (back_num <= NODE_BACKREFS_SIZE) {
for (i = 0; i < back_num; i++)
NBREF(node)->back_static[i] = backrefs[i];
}
else {
int* p = (int* )xmalloc(sizeof(int) * back_num);
if (IS_NULL(p)) {
onig_node_free(node);
return NULL;
}
NBREF(node)->back_dynamic = p;
for (i = 0; i < back_num; i++)
p[i] = backrefs[i];
}
return node;
}
#ifdef USE_SUBEXP_CALL
static Node*
node_new_call(UChar* name, UChar* name_end, int gnum)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_CALL);
NCALL(node)->state = 0;
NCALL(node)->target = NULL_NODE;
NCALL(node)->name = name;
NCALL(node)->name_end = name_end;
NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */
return node;
}
#endif
static Node*
node_new_quantifier(int lower, int upper, int by_number)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_QTFR);
NQTFR(node)->state = 0;
NQTFR(node)->target = NULL;
NQTFR(node)->lower = lower;
NQTFR(node)->upper = upper;
NQTFR(node)->greedy = 1;
NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY;
NQTFR(node)->head_exact = NULL_NODE;
NQTFR(node)->next_head_exact = NULL_NODE;
NQTFR(node)->is_referred = 0;
if (by_number != 0)
NQTFR(node)->state |= NST_BY_NUMBER;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
NQTFR(node)->comb_exp_check_num = 0;
#endif
return node;
}
static Node*
node_new_enclose(int type)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_ENCLOSE);
NENCLOSE(node)->type = type;
NENCLOSE(node)->state = 0;
NENCLOSE(node)->regnum = 0;
NENCLOSE(node)->option = 0;
NENCLOSE(node)->target = NULL;
NENCLOSE(node)->call_addr = -1;
NENCLOSE(node)->opt_count = 0;
return node;
}
extern Node*
onig_node_new_enclose(int type)
{
return node_new_enclose(type);
}
static Node*
node_new_enclose_memory(OnigOptionType option, int is_named)
{
Node* node = node_new_enclose(ENCLOSE_MEMORY);
CHECK_NULL_RETURN(node);
if (is_named != 0)
SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP);
#ifdef USE_SUBEXP_CALL
NENCLOSE(node)->option = option;
#endif
return node;
}
static Node*
node_new_option(OnigOptionType option)
{
Node* node = node_new_enclose(ENCLOSE_OPTION);
CHECK_NULL_RETURN(node);
NENCLOSE(node)->option = option;
return node;
}
extern int
onig_node_str_cat(Node* node, const UChar* s, const UChar* end)
{
ptrdiff_t addlen = end - s;
if (addlen > 0) {
ptrdiff_t len = NSTR(node)->end - NSTR(node)->s;
if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) {
UChar* p;
ptrdiff_t capa = len + addlen + NODE_STR_MARGIN;
if (capa <= NSTR(node)->capa) {
onig_strcpy(NSTR(node)->s + len, s, end);
}
else {
if (NSTR(node)->s == NSTR(node)->buf)
p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end,
s, end, capa);
else
p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa);
CHECK_NULL_RETURN_MEMERR(p);
NSTR(node)->s = p;
NSTR(node)->capa = (int )capa;
}
}
else {
onig_strcpy(NSTR(node)->s + len, s, end);
}
NSTR(node)->end = NSTR(node)->s + len + addlen;
}
return 0;
}
extern int
onig_node_str_set(Node* node, const UChar* s, const UChar* end)
{
onig_node_str_clear(node);
return onig_node_str_cat(node, s, end);
}
static int
node_str_cat_char(Node* node, UChar c)
{
UChar s[1];
s[0] = c;
return onig_node_str_cat(node, s, s + 1);
}
static int
node_str_cat_codepoint(Node* node, OnigEncoding enc, OnigCodePoint c)
{
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
int num = ONIGENC_CODE_TO_MBC(enc, c, buf);
if (num < 0) return num;
return onig_node_str_cat(node, buf, buf + num);
}
#if 0
extern void
onig_node_conv_to_str_node(Node* node, int flag)
{
SET_NTYPE(node, NT_STR);
NSTR(node)->flag = flag;
NSTR(node)->capa = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
}
#endif
extern void
onig_node_str_clear(Node* node)
{
if (NSTR(node)->capa != 0 &&
IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) {
xfree(NSTR(node)->s);
}
NSTR(node)->capa = 0;
NSTR(node)->flag = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
}
static Node*
node_new_str(const UChar* s, const UChar* end)
{
Node* node = node_new();
CHECK_NULL_RETURN(node);
SET_NTYPE(node, NT_STR);
NSTR(node)->capa = 0;
NSTR(node)->flag = 0;
NSTR(node)->s = NSTR(node)->buf;
NSTR(node)->end = NSTR(node)->buf;
if (onig_node_str_cat(node, s, end)) {
onig_node_free(node);
return NULL;
}
return node;
}
extern Node*
onig_node_new_str(const UChar* s, const UChar* end)
{
return node_new_str(s, end);
}
static Node*
node_new_str_raw(UChar* s, UChar* end)
{
Node* node = node_new_str(s, end);
if (IS_NOT_NULL(node))
NSTRING_SET_RAW(node);
return node;
}
static Node*
node_new_empty(void)
{
return node_new_str(NULL, NULL);
}
static Node*
node_new_str_raw_char(UChar c)
{
UChar p[1];
p[0] = c;
return node_new_str_raw(p, p + 1);
}
static Node*
str_node_split_last_char(StrNode* sn, OnigEncoding enc)
{
const UChar *p;
Node* n = NULL_NODE;
if (sn->end > sn->s) {
p = onigenc_get_prev_char_head(enc, sn->s, sn->end, sn->end);
if (p && p > sn->s) { /* can be split. */
n = node_new_str(p, sn->end);
if (IS_NOT_NULL(n) && (sn->flag & NSTR_RAW) != 0)
NSTRING_SET_RAW(n);
sn->end = (UChar* )p;
}
}
return n;
}
static int
str_node_can_be_split(StrNode* sn, OnigEncoding enc)
{
if (sn->end > sn->s) {
return ((enclen(enc, sn->s, sn->end) < sn->end - sn->s) ? 1 : 0);
}
return 0;
}
#ifdef USE_PAD_TO_SHORT_BYTE_CHAR
static int
node_str_head_pad(StrNode* sn, int num, UChar val)
{
UChar buf[NODE_STR_BUF_SIZE];
int i, len;
len = sn->end - sn->s;
onig_strcpy(buf, sn->s, sn->end);
onig_strcpy(&(sn->s[num]), buf, buf + len);
sn->end += num;
for (i = 0; i < num; i++) {
sn->s[i] = val;
}
}
#endif
extern int
onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc)
{
unsigned int num, val;
OnigCodePoint c;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
val = (unsigned int )DIGITVAL(c);
if ((INT_MAX_LIMIT - val) / 10UL < num)
return -1; /* overflow */
num = num * 10 + val;
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
static int
scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int minlen,
int maxlen, OnigEncoding enc)
{
OnigCodePoint c;
unsigned int num, val;
int restlen;
UChar* p = *src;
PFETCH_READY;
restlen = maxlen - minlen;
num = 0;
while (!PEND && maxlen-- != 0) {
PFETCH(c);
if (ONIGENC_IS_CODE_XDIGIT(enc, c)) {
val = (unsigned int )XDIGITVAL(enc,c);
if ((INT_MAX_LIMIT - val) / 16UL < num)
return -1; /* overflow */
num = (num << 4) + XDIGITVAL(enc,c);
}
else {
PUNFETCH;
maxlen++;
break;
}
}
if (maxlen > restlen)
return -2; /* not enough digits */
*src = p;
return num;
}
static int
scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen,
OnigEncoding enc)
{
OnigCodePoint c;
unsigned int num, val;
UChar* p = *src;
PFETCH_READY;
num = 0;
while (!PEND && maxlen-- != 0) {
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') {
val = ODIGITVAL(c);
if ((INT_MAX_LIMIT - val) / 8UL < num)
return -1; /* overflow */
num = (num << 3) + val;
}
else {
PUNFETCH;
break;
}
}
*src = p;
return num;
}
#define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \
BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT)
/* data format:
[n][from-1][to-1][from-2][to-2] ... [from-n][to-n]
(all data size is OnigCodePoint)
*/
static int
new_code_range(BBuf** pbuf)
{
#define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5)
int r;
OnigCodePoint n;
BBuf* bbuf;
bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf));
CHECK_NULL_RETURN_MEMERR(*pbuf);
r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE);
if (r) return r;
n = 0;
BBUF_WRITE_CODE_POINT(bbuf, 0, n);
return 0;
}
static int
add_code_range_to_buf0(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to,
int checkdup)
{
int r, inc_n, pos;
OnigCodePoint low, high, bound, x;
OnigCodePoint n, *data;
BBuf* bbuf;
if (from > to) {
n = from; from = to; to = n;
}
if (IS_NULL(*pbuf)) {
r = new_code_range(pbuf);
if (r) return r;
bbuf = *pbuf;
n = 0;
}
else {
bbuf = *pbuf;
GET_CODE_POINT(n, bbuf->p);
}
data = (OnigCodePoint* )(bbuf->p);
data++;
bound = (from == 0) ? 0 : n;
for (low = 0; low < bound; ) {
x = (low + bound) >> 1;
if (from - 1 > data[x*2 + 1])
low = x + 1;
else
bound = x;
}
high = (to == ONIG_LAST_CODE_POINT) ? n : low;
for (bound = n; high < bound; ) {
x = (high + bound) >> 1;
if (to + 1 >= data[x*2])
high = x + 1;
else
bound = x;
}
/* data[(low-1)*2+1] << from <= data[low*2]
* data[(high-1)*2+1] <= to << data[high*2]
*/
inc_n = low + 1 - high;
if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM)
return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES;
if (inc_n != 1) {
if (checkdup && from <= data[low*2+1]
&& (data[low*2] <= from || data[low*2+1] <= to))
CC_DUP_WARN(env, from, to);
if (from > data[low*2])
from = data[low*2];
if (to < data[(high - 1)*2 + 1])
to = data[(high - 1)*2 + 1];
}
if (inc_n != 0) {
int from_pos = SIZE_CODE_POINT * (1 + high * 2);
int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2);
if (inc_n > 0) {
if (high < n) {
int size = (n - high) * 2 * SIZE_CODE_POINT;
BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size);
}
}
else {
BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos);
}
}
pos = SIZE_CODE_POINT * (1 + low * 2);
BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2);
BBUF_WRITE_CODE_POINT(bbuf, pos, from);
BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to);
n += inc_n;
BBUF_WRITE_CODE_POINT(bbuf, 0, n);
return 0;
}
static int
add_code_range_to_buf(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to)
{
return add_code_range_to_buf0(pbuf, env, from, to, 1);
}
static int
add_code_range0(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to, int checkdup)
{
if (from > to) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
return 0;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
return add_code_range_to_buf0(pbuf, env, from, to, checkdup);
}
static int
add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to)
{
return add_code_range0(pbuf, env, from, to, 1);
}
static int
not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf, ScanEnv* env)
{
int r, i, n;
OnigCodePoint pre, from, *data, to = 0;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf)) {
set_all:
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
}
data = (OnigCodePoint* )(bbuf->p);
GET_CODE_POINT(n, data);
data++;
if (n <= 0) goto set_all;
r = 0;
pre = MBCODE_START_POS(enc);
for (i = 0; i < n; i++) {
from = data[i*2];
to = data[i*2+1];
if (pre <= from - 1) {
r = add_code_range_to_buf(pbuf, env, pre, from - 1);
if (r != 0) return r;
}
if (to == ONIG_LAST_CODE_POINT) break;
pre = to + 1;
}
if (to < ONIG_LAST_CODE_POINT) {
r = add_code_range_to_buf(pbuf, env, to + 1, ONIG_LAST_CODE_POINT);
}
return r;
}
#define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\
BBuf *tbuf; \
int tnot; \
tnot = not1; not1 = not2; not2 = tnot; \
tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \
} while (0)
static int
or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1,
BBuf* bbuf2, int not2, BBuf** pbuf, ScanEnv* env)
{
int r;
OnigCodePoint i, n1, *data1;
OnigCodePoint from, to;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) {
if (not1 != 0 || not2 != 0)
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
return 0;
}
r = 0;
if (IS_NULL(bbuf2))
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
if (IS_NULL(bbuf1)) {
if (not1 != 0) {
return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf);
}
else {
if (not2 == 0) {
return bbuf_clone(pbuf, bbuf2);
}
else {
return not_code_range_buf(enc, bbuf2, pbuf, env);
}
}
}
if (not1 != 0)
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
data1 = (OnigCodePoint* )(bbuf1->p);
GET_CODE_POINT(n1, data1);
data1++;
if (not2 == 0 && not1 == 0) { /* 1 OR 2 */
r = bbuf_clone(pbuf, bbuf2);
}
else if (not1 == 0) { /* 1 OR (not 2) */
r = not_code_range_buf(enc, bbuf2, pbuf, env);
}
if (r != 0) return r;
for (i = 0; i < n1; i++) {
from = data1[i*2];
to = data1[i*2+1];
r = add_code_range_to_buf(pbuf, env, from, to);
if (r != 0) return r;
}
return 0;
}
static int
and_code_range1(BBuf** pbuf, ScanEnv* env, OnigCodePoint from1, OnigCodePoint to1,
OnigCodePoint* data, int n)
{
int i, r;
OnigCodePoint from2, to2;
for (i = 0; i < n; i++) {
from2 = data[i*2];
to2 = data[i*2+1];
if (from2 < from1) {
if (to2 < from1) continue;
else {
from1 = to2 + 1;
}
}
else if (from2 <= to1) {
if (to2 < to1) {
if (from1 <= from2 - 1) {
r = add_code_range_to_buf(pbuf, env, from1, from2-1);
if (r != 0) return r;
}
from1 = to2 + 1;
}
else {
to1 = from2 - 1;
}
}
else {
from1 = from2;
}
if (from1 > to1) break;
}
if (from1 <= to1) {
r = add_code_range_to_buf(pbuf, env, from1, to1);
if (r != 0) return r;
}
return 0;
}
static int
and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf, ScanEnv* env)
{
int r;
OnigCodePoint i, j, n1, n2, *data1, *data2;
OnigCodePoint from, to, from1, to1, from2, to2;
*pbuf = (BBuf* )NULL;
if (IS_NULL(bbuf1)) {
if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */
return bbuf_clone(pbuf, bbuf2);
return 0;
}
else if (IS_NULL(bbuf2)) {
if (not2 != 0)
return bbuf_clone(pbuf, bbuf1);
return 0;
}
if (not1 != 0)
SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2);
data1 = (OnigCodePoint* )(bbuf1->p);
data2 = (OnigCodePoint* )(bbuf2->p);
GET_CODE_POINT(n1, data1);
GET_CODE_POINT(n2, data2);
data1++;
data2++;
if (not2 == 0 && not1 == 0) { /* 1 AND 2 */
for (i = 0; i < n1; i++) {
from1 = data1[i*2];
to1 = data1[i*2+1];
for (j = 0; j < n2; j++) {
from2 = data2[j*2];
to2 = data2[j*2+1];
if (from2 > to1) break;
if (to2 < from1) continue;
from = MAX(from1, from2);
to = MIN(to1, to2);
r = add_code_range_to_buf(pbuf, env, from, to);
if (r != 0) return r;
}
}
}
else if (not1 == 0) { /* 1 AND (not 2) */
for (i = 0; i < n1; i++) {
from1 = data1[i*2];
to1 = data1[i*2+1];
r = and_code_range1(pbuf, env, from1, to1, data2, n2);
if (r != 0) return r;
}
}
return 0;
}
static int
and_cclass(CClassNode* dest, CClassNode* cc, ScanEnv* env)
{
OnigEncoding enc = env->enc;
int r, not1, not2;
BBuf *buf1, *buf2, *pbuf = 0;
BitSetRef bsr1, bsr2;
BitSet bs1, bs2;
not1 = IS_NCCLASS_NOT(dest);
bsr1 = dest->bs;
buf1 = dest->mbuf;
not2 = IS_NCCLASS_NOT(cc);
bsr2 = cc->bs;
buf2 = cc->mbuf;
if (not1 != 0) {
bitset_invert_to(bsr1, bs1);
bsr1 = bs1;
}
if (not2 != 0) {
bitset_invert_to(bsr2, bs2);
bsr2 = bs2;
}
bitset_and(bsr1, bsr2);
if (bsr1 != dest->bs) {
bitset_copy(dest->bs, bsr1);
bsr1 = dest->bs;
}
if (not1 != 0) {
bitset_invert(dest->bs);
}
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
if (not1 != 0 && not2 != 0) {
r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf, env);
}
else {
r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf, env);
if (r == 0 && not1 != 0) {
BBuf *tbuf = 0;
r = not_code_range_buf(enc, pbuf, &tbuf, env);
bbuf_free(pbuf);
pbuf = tbuf;
}
}
if (r != 0) {
bbuf_free(pbuf);
return r;
}
dest->mbuf = pbuf;
bbuf_free(buf1);
return r;
}
return 0;
}
static int
or_cclass(CClassNode* dest, CClassNode* cc, ScanEnv* env)
{
OnigEncoding enc = env->enc;
int r, not1, not2;
BBuf *buf1, *buf2, *pbuf = 0;
BitSetRef bsr1, bsr2;
BitSet bs1, bs2;
not1 = IS_NCCLASS_NOT(dest);
bsr1 = dest->bs;
buf1 = dest->mbuf;
not2 = IS_NCCLASS_NOT(cc);
bsr2 = cc->bs;
buf2 = cc->mbuf;
if (not1 != 0) {
bitset_invert_to(bsr1, bs1);
bsr1 = bs1;
}
if (not2 != 0) {
bitset_invert_to(bsr2, bs2);
bsr2 = bs2;
}
bitset_or(bsr1, bsr2);
if (bsr1 != dest->bs) {
bitset_copy(dest->bs, bsr1);
bsr1 = dest->bs;
}
if (not1 != 0) {
bitset_invert(dest->bs);
}
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
if (not1 != 0 && not2 != 0) {
r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf, env);
}
else {
r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf, env);
if (r == 0 && not1 != 0) {
BBuf *tbuf = 0;
r = not_code_range_buf(enc, pbuf, &tbuf, env);
bbuf_free(pbuf);
pbuf = tbuf;
}
}
if (r != 0) {
bbuf_free(pbuf);
return r;
}
dest->mbuf = pbuf;
bbuf_free(buf1);
return r;
}
else
return 0;
}
static void UNKNOWN_ESC_WARN(ScanEnv *env, int c);
static OnigCodePoint
conv_backslash_value(OnigCodePoint c, ScanEnv* env)
{
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) {
switch (c) {
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case 'f': return '\f';
case 'a': return '\007';
case 'b': return '\010';
case 'e': return '\033';
case 'v':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB))
return '\v';
break;
default:
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
UNKNOWN_ESC_WARN(env, c);
break;
}
}
return c;
}
#ifdef USE_NO_INVALID_QUANTIFIER
# define is_invalid_quantifier_target(node) 0
#else
static int
is_invalid_quantifier_target(Node* node)
{
switch (NTYPE(node)) {
case NT_ANCHOR:
return 1;
break;
case NT_ENCLOSE:
/* allow enclosed elements */
/* return is_invalid_quantifier_target(NENCLOSE(node)->target); */
break;
case NT_LIST:
do {
if (! is_invalid_quantifier_target(NCAR(node))) return 0;
} while (IS_NOT_NULL(node = NCDR(node)));
return 0;
break;
case NT_ALT:
do {
if (is_invalid_quantifier_target(NCAR(node))) return 1;
} while (IS_NOT_NULL(node = NCDR(node)));
break;
default:
break;
}
return 0;
}
#endif
/* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */
static int
popular_quantifier_num(QtfrNode* q)
{
if (q->greedy) {
if (q->lower == 0) {
if (q->upper == 1) return 0;
else if (IS_REPEAT_INFINITE(q->upper)) return 1;
}
else if (q->lower == 1) {
if (IS_REPEAT_INFINITE(q->upper)) return 2;
}
}
else {
if (q->lower == 0) {
if (q->upper == 1) return 3;
else if (IS_REPEAT_INFINITE(q->upper)) return 4;
}
else if (q->lower == 1) {
if (IS_REPEAT_INFINITE(q->upper)) return 5;
}
}
return -1;
}
enum ReduceType {
RQ_ASIS = 0, /* as is */
RQ_DEL = 1, /* delete parent */
RQ_A, /* to '*' */
RQ_AQ, /* to '*?' */
RQ_QQ, /* to '??' */
RQ_P_QQ, /* to '+)??' */
RQ_PQ_Q /* to '+?)?' */
};
static enum ReduceType const ReduceTypeTable[6][6] = {
/* '?', '*', '+', '??', '*?', '+?' p / c */
{RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */
{RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */
{RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */
{RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */
{RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */
{RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */
};
extern void
onig_reduce_nested_quantifier(Node* pnode, Node* cnode)
{
int pnum, cnum;
QtfrNode *p, *c;
p = NQTFR(pnode);
c = NQTFR(cnode);
pnum = popular_quantifier_num(p);
cnum = popular_quantifier_num(c);
if (pnum < 0 || cnum < 0) return ;
switch (ReduceTypeTable[cnum][pnum]) {
case RQ_DEL:
*pnode = *cnode;
break;
case RQ_A:
p->target = c->target;
p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1;
break;
case RQ_AQ:
p->target = c->target;
p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0;
break;
case RQ_QQ:
p->target = c->target;
p->lower = 0; p->upper = 1; p->greedy = 0;
break;
case RQ_P_QQ:
p->target = cnode;
p->lower = 0; p->upper = 1; p->greedy = 0;
c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1;
return ;
break;
case RQ_PQ_Q:
p->target = cnode;
p->lower = 0; p->upper = 1; p->greedy = 1;
c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0;
return ;
break;
case RQ_ASIS:
p->target = cnode;
return ;
break;
}
c->target = NULL_NODE;
onig_node_free(cnode);
}
enum TokenSyms {
TK_EOT = 0, /* end of token */
TK_RAW_BYTE = 1,
TK_CHAR,
TK_STRING,
TK_CODE_POINT,
TK_ANYCHAR,
TK_CHAR_TYPE,
TK_BACKREF,
TK_CALL,
TK_ANCHOR,
TK_OP_REPEAT,
TK_INTERVAL,
TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */
TK_ALT,
TK_SUBEXP_OPEN,
TK_SUBEXP_CLOSE,
TK_CC_OPEN,
TK_QUOTE_OPEN,
TK_CHAR_PROPERTY, /* \p{...}, \P{...} */
TK_LINEBREAK,
TK_EXTENDED_GRAPHEME_CLUSTER,
TK_KEEP,
/* in cc */
TK_CC_CLOSE,
TK_CC_RANGE,
TK_POSIX_BRACKET_OPEN,
TK_CC_AND, /* && */
TK_CC_CC_OPEN /* [ */
};
typedef struct {
enum TokenSyms type;
int escaped;
int base; /* is number: 8, 16 (used in [....]) */
UChar* backp;
union {
UChar* s;
int c;
OnigCodePoint code;
struct {
int subtype;
int ascii_range;
} anchor;
struct {
int lower;
int upper;
int greedy;
int possessive;
} repeat;
struct {
int num;
int ref1;
int* refs;
int by_name;
#ifdef USE_BACKREF_WITH_LEVEL
int exist_level;
int level; /* \k<name+n> */
#endif
} backref;
struct {
UChar* name;
UChar* name_end;
int gnum;
int rel;
} call;
struct {
int ctype;
int not;
} prop;
} u;
} OnigToken;
static int
fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env)
{
int low, up, syn_allow, non_low = 0;
int r = 0;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar* p = *src;
PFETCH_READY;
syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL);
if (PEND) {
if (syn_allow)
return 1; /* "....{" : OK! */
else
return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */
}
if (! syn_allow) {
c = PPEEK;
if (c == ')' || c == '(' || c == '|') {
return ONIGERR_END_PATTERN_AT_LEFT_BRACE;
}
}
low = onig_scan_unsigned_number(&p, end, env->enc);
if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (low > ONIG_MAX_REPEAT_NUM)
return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (p == *src) { /* can't read low */
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) {
/* allow {,n} as {0,n} */
low = 0;
non_low = 1;
}
else
goto invalid;
}
if (PEND) goto invalid;
PFETCH(c);
if (c == ',') {
UChar* prev = p;
up = onig_scan_unsigned_number(&p, end, env->enc);
if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (up > ONIG_MAX_REPEAT_NUM)
return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE;
if (p == prev) {
if (non_low != 0)
goto invalid;
up = REPEAT_INFINITE; /* {n,} : {n,infinite} */
}
}
else {
if (non_low != 0)
goto invalid;
PUNFETCH;
up = low; /* {n} : exact n times */
r = 2; /* fixed */
}
if (PEND) goto invalid;
PFETCH(c);
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) {
if (c != MC_ESC(env->syntax)) goto invalid;
if (PEND) goto invalid;
PFETCH(c);
}
if (c != '}') goto invalid;
if (!IS_REPEAT_INFINITE(up) && low > up) {
return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE;
}
tok->type = TK_INTERVAL;
tok->u.repeat.lower = low;
tok->u.repeat.upper = up;
*src = p;
return r; /* 0: normal {n,m}, 2: fixed {n} */
invalid:
if (syn_allow)
return 1; /* OK */
else
return ONIGERR_INVALID_REPEAT_RANGE_PATTERN;
}
/* \M-, \C-, \c, or \... */
static int
fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val)
{
int v;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar* p = *src;
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
PFETCH_S(c);
switch (c) {
case 'M':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) {
if (PEND) return ONIGERR_END_PATTERN_AT_META;
PFETCH_S(c);
if (c != '-') return ONIGERR_META_CODE_SYNTAX;
if (PEND) return ONIGERR_END_PATTERN_AT_META;
PFETCH_S(c);
if (c == MC_ESC(env->syntax)) {
v = fetch_escaped_value(&p, end, env, &c);
if (v < 0) return v;
}
c = ((c & 0xff) | 0x80);
}
else
goto backslash;
break;
case 'C':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) {
if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL;
PFETCH_S(c);
if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX;
goto control;
}
else
goto backslash;
case 'c':
if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) {
control:
if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL;
PFETCH_S(c);
if (c == '?') {
c = 0177;
}
else {
if (c == MC_ESC(env->syntax)) {
v = fetch_escaped_value(&p, end, env, &c);
if (v < 0) return v;
}
c &= 0x9f;
}
break;
}
/* fall through */
default:
{
backslash:
c = conv_backslash_value(c, env);
}
break;
}
*src = p;
*val = c;
return 0;
}
static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env);
static OnigCodePoint
get_name_end_code_point(OnigCodePoint start)
{
switch (start) {
case '<': return (OnigCodePoint )'>'; break;
case '\'': return (OnigCodePoint )'\''; break;
case '(': return (OnigCodePoint )')'; break;
case '{': return (OnigCodePoint )'}'; break;
default:
break;
}
return (OnigCodePoint )0;
}
#ifdef USE_NAMED_GROUP
# ifdef RUBY
# define ONIGENC_IS_CODE_NAME(enc, c) TRUE
# else
# define ONIGENC_IS_CODE_NAME(enc, c) ONIGENC_IS_CODE_WORD(enc, c)
# endif
# ifdef USE_BACKREF_WITH_LEVEL
/*
\k<name+n>, \k<name-n>
\k<num+n>, \k<num-n>
\k<-num+n>, \k<-num-n>
*/
static int
fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env,
int* rback_num, int* rlevel)
{
int r, sign, is_num, exist_level;
OnigCodePoint end_code;
OnigCodePoint c = 0;
OnigEncoding enc = env->enc;
UChar *name_end;
UChar *pnum_head;
UChar *p = *src;
PFETCH_READY;
*rback_num = 0;
is_num = exist_level = 0;
sign = 1;
pnum_head = *src;
end_code = get_name_end_code_point(start_code);
name_end = end;
r = 0;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else if (c == '-') {
is_num = 2;
sign = -1;
pnum_head = p;
}
else if (!ONIGENC_IS_CODE_NAME(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
while (!PEND) {
name_end = p;
PFETCH(c);
if (c == end_code || c == ')' || c == '+' || c == '-') {
if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME;
break;
}
if (is_num != 0) {
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (!ONIGENC_IS_CODE_NAME(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
if (r == 0 && c != end_code) {
if (c == '+' || c == '-') {
int level;
int flag = (c == '-' ? -1 : 1);
if (PEND) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
goto end;
}
PFETCH(c);
if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err;
PUNFETCH;
level = onig_scan_unsigned_number(&p, end, enc);
if (level < 0) return ONIGERR_TOO_BIG_NUMBER;
*rlevel = (level * flag);
exist_level = 1;
if (!PEND) {
PFETCH(c);
if (c == end_code)
goto end;
}
}
err:
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
end:
if (r == 0) {
if (is_num != 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) goto err;
*rback_num *= sign;
}
*rname_end = name_end;
*src = p;
return (exist_level ? 1 : 0);
}
else {
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
# endif /* USE_BACKREF_WITH_LEVEL */
/*
ref: 0 -> define name (don't allow number name)
1 -> reference name (allow number name)
*/
static int
fetch_name(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env, int* rback_num, int ref)
{
int r, is_num, sign;
OnigCodePoint end_code;
OnigCodePoint c = 0;
OnigEncoding enc = env->enc;
UChar *name_end;
UChar *pnum_head;
UChar *p = *src;
*rback_num = 0;
end_code = get_name_end_code_point(start_code);
name_end = end;
pnum_head = *src;
r = 0;
is_num = 0;
sign = 1;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH_S(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
if (ref == 1)
is_num = 1;
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (c == '-') {
if (ref == 1) {
is_num = 2;
sign = -1;
pnum_head = p;
}
else {
r = ONIGERR_INVALID_GROUP_NAME;
is_num = 0;
}
}
else if (!ONIGENC_IS_CODE_NAME(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
if (r == 0) {
while (!PEND) {
name_end = p;
PFETCH_S(c);
if (c == end_code || c == ')') {
if (is_num == 2) {
r = ONIGERR_INVALID_GROUP_NAME;
goto teardown;
}
break;
}
if (is_num != 0) {
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else {
if (!ONIGENC_IS_CODE_WORD(enc, c))
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
else
r = ONIGERR_INVALID_GROUP_NAME;
goto teardown;
}
}
else {
if (!ONIGENC_IS_CODE_NAME(enc, c)) {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
goto teardown;
}
}
}
if (c != end_code) {
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
goto err;
}
if (is_num != 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) {
r = ONIGERR_INVALID_GROUP_NAME;
goto err;
}
*rback_num *= sign;
}
*rname_end = name_end;
*src = p;
return 0;
}
else {
teardown:
while (!PEND) {
name_end = p;
PFETCH_S(c);
if (c == end_code || c == ')')
break;
}
if (PEND)
name_end = end;
err:
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#else
static int
fetch_name(OnigCodePoint start_code, UChar** src, UChar* end,
UChar** rname_end, ScanEnv* env, int* rback_num, int ref)
{
int r, is_num, sign;
OnigCodePoint end_code;
OnigCodePoint c = 0;
UChar *name_end;
OnigEncoding enc = env->enc;
UChar *pnum_head;
UChar *p = *src;
PFETCH_READY;
*rback_num = 0;
end_code = get_name_end_code_point(start_code);
*rname_end = name_end = end;
r = 0;
pnum_head = *src;
is_num = 0;
sign = 1;
if (PEND) {
return ONIGERR_EMPTY_GROUP_NAME;
}
else {
PFETCH(c);
if (c == end_code)
return ONIGERR_EMPTY_GROUP_NAME;
if (ONIGENC_IS_CODE_DIGIT(enc, c)) {
is_num = 1;
}
else if (c == '-') {
is_num = 2;
sign = -1;
pnum_head = p;
}
else {
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
}
while (!PEND) {
name_end = p;
PFETCH(c);
if (c == end_code || c == ')') break;
if (! ONIGENC_IS_CODE_DIGIT(enc, c))
r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME;
}
if (r == 0 && c != end_code) {
r = ONIGERR_INVALID_GROUP_NAME;
name_end = end;
}
if (r == 0) {
*rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc);
if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER;
else if (*rback_num == 0) {
r = ONIGERR_INVALID_GROUP_NAME;
goto err;
}
*rback_num *= sign;
*rname_end = name_end;
*src = p;
return 0;
}
else {
err:
onig_scan_env_set_error_string(env, r, *src, name_end);
return r;
}
}
#endif /* USE_NAMED_GROUP */
static void
onig_syntax_warn(ScanEnv *env, const char *fmt, ...)
{
va_list args;
UChar buf[WARN_BUFSIZE];
va_start(args, fmt);
onig_vsnprintf_with_pattern(buf, WARN_BUFSIZE, env->enc,
env->pattern, env->pattern_end,
(const UChar *)fmt, args);
va_end(args);
#ifdef RUBY
if (env->sourcefile == NULL)
rb_warn("%s", (char *)buf);
else
rb_compile_warn(env->sourcefile, env->sourceline, "%s", (char *)buf);
#else
(*onig_warn)((char* )buf);
#endif
}
static void
CC_ESC_WARN(ScanEnv *env, UChar *c)
{
if (onig_warn == onig_null_warn) return ;
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) {
onig_syntax_warn(env, "character class has '%s' without escape", c);
}
}
static void
CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c)
{
if (onig_warn == onig_null_warn) return ;
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) {
onig_syntax_warn(env, "regular expression has '%s' without escape", c);
}
}
#ifndef RTEST
# define RTEST(v) 1
#endif
static void
CC_DUP_WARN(ScanEnv *env, OnigCodePoint from ARG_UNUSED, OnigCodePoint to ARG_UNUSED)
{
if (onig_warn == onig_null_warn || !RTEST(ruby_verbose)) return ;
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_DUP) &&
!(env->warnings_flag & ONIG_SYN_WARN_CC_DUP)) {
#ifdef WARN_ALL_CC_DUP
onig_syntax_warn(env, "character class has duplicated range: %04x-%04x", from, to);
#else
env->warnings_flag |= ONIG_SYN_WARN_CC_DUP;
onig_syntax_warn(env, "character class has duplicated range");
#endif
}
}
static void
UNKNOWN_ESC_WARN(ScanEnv *env, int c)
{
if (onig_warn == onig_null_warn || !RTEST(ruby_verbose)) return ;
onig_syntax_warn(env, "Unknown escape \\%c is ignored", c);
}
static UChar*
find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to,
UChar **next, OnigEncoding enc)
{
int i;
OnigCodePoint x;
UChar *q;
UChar *p = from;
while (p < to) {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
q = p + enclen(enc, p, to);
if (x == s[0]) {
for (i = 1; i < n && q < to; i++) {
x = ONIGENC_MBC_TO_CODE(enc, q, to);
if (x != s[i]) break;
q += enclen(enc, q, to);
}
if (i >= n) {
if (IS_NOT_NULL(next))
*next = q;
return p;
}
}
p = q;
}
return NULL_UCHARP;
}
static int
str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to,
OnigCodePoint bad, OnigEncoding enc, const OnigSyntaxType* syn)
{
int i, in_esc;
OnigCodePoint x;
UChar *q;
UChar *p = from;
in_esc = 0;
while (p < to) {
if (in_esc) {
in_esc = 0;
p += enclen(enc, p, to);
}
else {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
q = p + enclen(enc, p, to);
if (x == s[0]) {
for (i = 1; i < n && q < to; i++) {
x = ONIGENC_MBC_TO_CODE(enc, q, to);
if (x != s[i]) break;
q += enclen(enc, q, to);
}
if (i >= n) return 1;
p += enclen(enc, p, to);
}
else {
x = ONIGENC_MBC_TO_CODE(enc, p, to);
if (x == bad) return 0;
else if (x == MC_ESC(syn)) in_esc = 1;
p = q;
}
}
}
return 0;
}
static int
fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int num;
OnigCodePoint c, c2;
const OnigSyntaxType* syn = env->syntax;
OnigEncoding enc = env->enc;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
PFETCH(c);
tok->type = TK_CHAR;
tok->base = 0;
tok->u.c = c;
tok->escaped = 0;
if (c == ']') {
tok->type = TK_CC_CLOSE;
}
else if (c == '-') {
tok->type = TK_CC_RANGE;
}
else if (c == MC_ESC(syn)) {
if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC))
goto end;
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
PFETCH(c);
tok->escaped = 1;
tok->u.c = c;
switch (c) {
case 'w':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'd':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 's':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'p':
case 'P':
if (PEND) break;
c2 = PPEEK;
if (c2 == '{' &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c2);
if (c2 == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
else {
onig_syntax_warn(env, "invalid Unicode Property \\%c", c);
}
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
c2 = PPEEK;
if (ONIGENC_IS_CODE_XDIGIT(enc, c2))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if (p > prev + enclen(enc, prev, end) && !PEND && (PPEEK_IS('}'))) {
PINC;
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc);
if (num < -1) return ONIGERR_TOO_SHORT_DIGITS;
else if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case 'o':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) {
PINC;
num = scan_unsigned_octal_number(&p, end, 11, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
c2 = PPEEK;
if (ONIGENC_IS_CODE_DIGIT(enc, c2) && c2 < '8')
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if (p > prev + enclen(enc, prev, end) && !PEND && (PPEEK_IS('}'))) {
PINC;
tok->type = TK_CODE_POINT;
tok->base = 8;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
break;
case '0':
case '1': case '2': case '3': case '4': case '5': case '6': case '7':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
PUNFETCH;
prev = p;
num = scan_unsigned_octal_number(&p, end, 3, enc);
if (num < 0 || 0xff < num) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
break;
default:
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
if ((OnigCodePoint )tok->u.c != c2) {
tok->u.code = (OnigCodePoint )c2;
tok->type = TK_CODE_POINT;
}
break;
}
}
else if (c == '[') {
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) {
OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' };
tok->backp = p; /* point at '[' is read */
PINC;
if (str_exist_check_with_esc(send, 2, p, end,
(OnigCodePoint )']', enc, syn)) {
tok->type = TK_POSIX_BRACKET_OPEN;
}
else {
PUNFETCH;
goto cc_in_cc;
}
}
else {
cc_in_cc:
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) {
tok->type = TK_CC_CC_OPEN;
}
else {
CC_ESC_WARN(env, (UChar* )"[");
}
}
}
else if (c == '&') {
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) &&
!PEND && (PPEEK_IS('&'))) {
PINC;
tok->type = TK_CC_AND;
}
}
end:
*src = p;
return tok->type;
}
#ifdef USE_NAMED_GROUP
static int
fetch_named_backref_token(OnigCodePoint c, OnigToken* tok, UChar** src,
UChar* end, ScanEnv* env)
{
int r, num;
const OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
UChar* name_end;
int* backs;
int back_num;
prev = p;
# ifdef USE_BACKREF_WITH_LEVEL
name_end = NULL_UCHARP; /* no need. escape gcc warning. */
r = fetch_name_with_level(c, &p, end, &name_end,
env, &back_num, &tok->u.backref.level);
if (r == 1) tok->u.backref.exist_level = 1;
else tok->u.backref.exist_level = 0;
# else
r = fetch_name(&p, end, &name_end, env, &back_num, 1);
# endif
if (r < 0) return r;
if (back_num != 0) {
if (back_num < 0) {
back_num = BACKREF_REL_TO_ABS(back_num, env);
if (back_num <= 0)
return ONIGERR_INVALID_BACKREF;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (back_num > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[back_num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 0;
tok->u.backref.num = 1;
tok->u.backref.ref1 = back_num;
}
else {
num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs);
if (num <= 0) {
onig_scan_env_set_error_string(env,
ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
int i;
for (i = 0; i < num; i++) {
if (backs[i] > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[backs[i]]))
return ONIGERR_INVALID_BACKREF;
}
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 1;
if (num == 1 || IS_SYNTAX_BV(syn, ONIG_SYN_USE_LEFT_MOST_NAMED_GROUP)) {
tok->u.backref.num = 1;
tok->u.backref.ref1 = backs[0];
}
else {
tok->u.backref.num = num;
tok->u.backref.refs = backs;
}
}
*src = p;
return 0;
}
#endif
static int
fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int r, num;
OnigCodePoint c;
OnigEncoding enc = env->enc;
const OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
start:
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
tok->type = TK_STRING;
tok->base = 0;
tok->backp = p;
PFETCH(c);
if (IS_MC_ESC_CODE(c, syn)) {
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
tok->backp = p;
PFETCH(c);
tok->u.c = c;
tok->escaped = 1;
switch (c) {
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
greedy_check:
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {
PFETCH(c);
tok->u.repeat.greedy = 0;
tok->u.repeat.possessive = 0;
}
else {
possessive_check:
if (!PEND && PPEEK_IS('+') &&
((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&
tok->type != TK_INTERVAL) ||
(IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&
tok->type == TK_INTERVAL))) {
PFETCH(c);
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 1;
}
else {
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 0;
}
}
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case 'w':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'b':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_WORD_BOUND;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option)
&& ! IS_WORD_BOUND_ALL_RANGE(env->option);
break;
case 'B':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_NOT_WORD_BOUND;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option)
&& ! IS_WORD_BOUND_ALL_RANGE(env->option);
break;
#ifdef USE_WORD_BEGIN_END
case '<':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_WORD_BEGIN;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option);
break;
case '>':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_WORD_END;
tok->u.anchor.ascii_range = IS_ASCII_RANGE(env->option);
break;
#endif
case 's':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'd':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'A':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
begin_buf:
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_BEGIN_BUF;
break;
case 'Z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_SEMI_END_BUF;
break;
case 'z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
end_buf:
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_END_BUF;
break;
case 'G':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = ANCHOR_BEGIN_POSITION;
break;
case '`':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto begin_buf;
break;
case '\'':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto end_buf;
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc);
if (num < -1) return ONIGERR_TOO_SHORT_DIGITS;
else if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case 'o':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) {
PINC;
num = scan_unsigned_octal_number(&p, end, 11, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
OnigCodePoint c = PPEEK;
if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8')
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev, end)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
PUNFETCH;
prev = p;
num = onig_scan_unsigned_number(&p, end, enc);
if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {
goto skip_backref;
}
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&
(num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.num = 1;
tok->u.backref.ref1 = num;
tok->u.backref.by_name = 0;
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level = 0;
#endif
break;
}
skip_backref:
if (c == '8' || c == '9') {
/* normal char */
p = prev; PINC;
break;
}
p = prev;
/* fall through */
case '0':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
prev = p;
num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);
if (num < 0 || 0xff < num) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
else if (c != '0') {
PINC;
}
break;
#ifdef USE_NAMED_GROUP
case 'k':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {
PFETCH(c);
if (c == '<' || c == '\'') {
r = fetch_named_backref_token(c, tok, &p, end, env);
if (r < 0) return r;
}
else {
PUNFETCH;
onig_syntax_warn(env, "invalid back reference");
}
}
break;
#endif
#if defined(USE_SUBEXP_CALL) || defined(USE_NAMED_GROUP)
case 'g':
# ifdef USE_NAMED_GROUP
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_BRACE_BACKREF)) {
PFETCH(c);
if (c == '{') {
r = fetch_named_backref_token(c, tok, &p, end, env);
if (r < 0) return r;
}
else
PUNFETCH;
}
# endif
# ifdef USE_SUBEXP_CALL
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {
PFETCH(c);
if (c == '<' || c == '\'') {
int gnum = -1, rel = 0;
UChar* name_end;
OnigCodePoint cnext;
cnext = PPEEK;
if (cnext == '0') {
PINC;
if (PPEEK_IS(get_name_end_code_point(c))) { /* \g<0>, \g'0' */
PINC;
name_end = p;
gnum = 0;
}
}
else if (cnext == '+') {
PINC;
rel = 1;
}
prev = p;
if (gnum < 0) {
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
}
tok->type = TK_CALL;
tok->u.call.name = prev;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = rel;
}
else {
onig_syntax_warn(env, "invalid subexp call");
PUNFETCH;
}
}
# endif
break;
#endif
case 'Q':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {
tok->type = TK_QUOTE_OPEN;
}
break;
case 'p':
case 'P':
if (PPEEK_IS('{') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c);
if (c == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
else {
onig_syntax_warn(env, "invalid Unicode Property \\%c", c);
}
break;
case 'R':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_R_LINEBREAK)) {
tok->type = TK_LINEBREAK;
}
break;
case 'X':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_X_EXTENDED_GRAPHEME_CLUSTER)) {
tok->type = TK_EXTENDED_GRAPHEME_CLUSTER;
}
break;
case 'K':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_K_KEEP)) {
tok->type = TK_KEEP;
}
break;
default:
{
OnigCodePoint c2;
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
/* set_raw: */
if ((OnigCodePoint )tok->u.c != c2) {
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )c2;
}
else { /* string */
p = tok->backp + enclen(enc, tok->backp, end);
}
}
break;
}
}
else {
tok->u.c = c;
tok->escaped = 0;
#ifdef USE_VARIABLE_META_CHARS
if ((c != ONIG_INEFFECTIVE_META_CHAR) &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {
if (c == MC_ANYCHAR(syn))
goto any_char;
else if (c == MC_ANYTIME(syn))
goto anytime;
else if (c == MC_ZERO_OR_ONE_TIME(syn))
goto zero_or_one_time;
else if (c == MC_ONE_OR_MORE_TIME(syn))
goto one_or_more_time;
else if (c == MC_ANYCHAR_ANYTIME(syn)) {
tok->type = TK_ANYCHAR_ANYTIME;
goto out;
}
}
#endif
switch (c) {
case '.':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;
#ifdef USE_VARIABLE_META_CHARS
any_char:
#endif
tok->type = TK_ANYCHAR;
break;
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
anytime:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
one_or_more_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;
#ifdef USE_VARIABLE_META_CHARS
zero_or_one_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
goto greedy_check;
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (PPEEK_IS('?') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (PPEEK_IS('#')) {
PFETCH(c);
while (1) {
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
if (c == MC_ESC(syn)) {
if (!PEND) PFETCH(c);
}
else {
if (c == ')') break;
}
}
goto start;
}
#ifdef USE_PERL_SUBEXP_CALL
/* (?&name), (?n), (?R), (?0), (?+n), (?-n) */
c = PPEEK;
if ((c == '&' || c == 'R' || ONIGENC_IS_CODE_DIGIT(enc, c)) &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) {
/* (?&name), (?n), (?R), (?0) */
int gnum;
UChar *name;
UChar *name_end;
if (c == 'R' || c == '0') {
PINC; /* skip 'R' / '0' */
if (!PPEEK_IS(')')) {
r = ONIGERR_INVALID_GROUP_NAME;
onig_scan_env_set_error_string(env, r, p - 1, p + 1);
return r;
}
PINC; /* skip ')' */
name_end = name = p;
gnum = 0;
}
else {
int numref = 1;
if (c == '&') { /* (?&name) */
PINC;
numref = 0; /* don't allow number name */
}
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, numref);
if (r < 0) return r;
}
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = 0;
break;
}
else if ((c == '-' || c == '+') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_SUBEXP_CALL)) {
/* (?+n), (?-n) */
int gnum;
UChar *name;
UChar *name_end;
OnigCodePoint cnext;
PFETCH_READY;
PINC; /* skip '-' / '+' */
cnext = PPEEK;
if (ONIGENC_IS_CODE_DIGIT(enc, cnext)) {
if (c == '-') PUNFETCH;
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = 1;
break;
}
}
#endif /* USE_PERL_SUBEXP_CALL */
#ifdef USE_CAPITAL_P_NAMED_GROUP
if (PPEEK_IS('P') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_CAPITAL_P_NAMED_GROUP)) {
int gnum;
UChar *name;
UChar *name_end;
PFETCH_READY;
PINC; /* skip 'P' */
if (PEND) return ONIGERR_UNDEFINED_GROUP_OPTION;
PFETCH(c);
if (c == '=') { /* (?P=name): backref */
r = fetch_named_backref_token((OnigCodePoint )'(', tok, &p, end, env);
if (r < 0) return r;
break;
}
else if (c == '>') { /* (?P>name): subexp call */
name = p;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &gnum, 0);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = name;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
tok->u.call.rel = 0;
break;
}
}
#endif /* USE_CAPITAL_P_NAMED_GROUP */
PUNFETCH;
}
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case '^':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);
break;
case '$':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.anchor.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);
break;
case '[':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;
tok->type = TK_CC_OPEN;
break;
case ']':
if (*src > env->pattern) /* /].../ is allowed. */
CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]");
break;
case '#':
if (IS_EXTEND(env->option)) {
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_NEWLINE(enc, c))
break;
}
goto start;
break;
}
break;
case ' ': case '\t': case '\n': case '\r': case '\f':
if (IS_EXTEND(env->option))
goto start;
break;
default:
/* string */
break;
}
}
#ifdef USE_VARIABLE_META_CHARS
out:
#endif
*src = p;
return tok->type;
}
static int
add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not,
ScanEnv* env,
OnigCodePoint sb_out, const OnigCodePoint mbr[])
{
int i, r;
OnigCodePoint j;
int n = ONIGENC_CODE_RANGE_NUM(mbr);
if (not == 0) {
for (i = 0; i < n; i++) {
for (j = ONIGENC_CODE_RANGE_FROM(mbr, i);
j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) {
if (j >= sb_out) {
if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) {
r = add_code_range_to_buf(&(cc->mbuf), env, j,
ONIGENC_CODE_RANGE_TO(mbr, i));
if (r != 0) return r;
i++;
}
goto sb_end;
}
BITSET_SET_BIT_CHKDUP(cc->bs, j);
}
}
sb_end:
for ( ; i < n; i++) {
r = add_code_range_to_buf(&(cc->mbuf), env,
ONIGENC_CODE_RANGE_FROM(mbr, i),
ONIGENC_CODE_RANGE_TO(mbr, i));
if (r != 0) return r;
}
}
else {
OnigCodePoint prev = 0;
for (i = 0; i < n; i++) {
for (j = prev;
j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) {
if (j >= sb_out) {
goto sb_end2;
}
BITSET_SET_BIT_CHKDUP(cc->bs, j);
}
prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1;
}
for (j = prev; j < sb_out; j++) {
BITSET_SET_BIT_CHKDUP(cc->bs, j);
}
sb_end2:
prev = sb_out;
for (i = 0; i < n; i++) {
if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) {
r = add_code_range_to_buf(&(cc->mbuf), env, prev,
ONIGENC_CODE_RANGE_FROM(mbr, i) - 1);
if (r != 0) return r;
}
prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1;
}
if (prev < 0x7fffffff) {
r = add_code_range_to_buf(&(cc->mbuf), env, prev, 0x7fffffff);
if (r != 0) return r;
}
}
return 0;
}
static int
add_ctype_to_cc(CClassNode* cc, int ctype, int not, int ascii_range, ScanEnv* env)
{
int maxcode;
int c, r;
const OnigCodePoint *ranges;
OnigCodePoint sb_out;
OnigEncoding enc = env->enc;
r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges);
if (r == 0) {
if (ascii_range) {
CClassNode ccwork;
initialize_cclass(&ccwork);
r = add_ctype_to_cc_by_range(&ccwork, ctype, not, env, sb_out,
ranges);
if (r == 0) {
if (not) {
r = add_code_range_to_buf0(&(ccwork.mbuf), env, 0x80, ONIG_LAST_CODE_POINT, FALSE);
}
else {
CClassNode ccascii;
initialize_cclass(&ccascii);
if (ONIGENC_MBC_MINLEN(env->enc) > 1) {
r = add_code_range(&(ccascii.mbuf), env, 0x00, 0x7F);
}
else {
bitset_set_range(env, ccascii.bs, 0x00, 0x7F);
r = 0;
}
if (r == 0) {
r = and_cclass(&ccwork, &ccascii, env);
}
if (IS_NOT_NULL(ccascii.mbuf)) bbuf_free(ccascii.mbuf);
}
if (r == 0) {
r = or_cclass(cc, &ccwork, env);
}
if (IS_NOT_NULL(ccwork.mbuf)) bbuf_free(ccwork.mbuf);
}
}
else {
r = add_ctype_to_cc_by_range(cc, ctype, not, env, sb_out, ranges);
}
return r;
}
else if (r != ONIG_NO_SUPPORT_CONFIG) {
return r;
}
maxcode = ascii_range ? 0x80 : SINGLE_BYTE_SIZE;
r = 0;
switch (ctype) {
case ONIGENC_CTYPE_ALPHA:
case ONIGENC_CTYPE_BLANK:
case ONIGENC_CTYPE_CNTRL:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_LOWER:
case ONIGENC_CTYPE_PUNCT:
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_UPPER:
case ONIGENC_CTYPE_XDIGIT:
case ONIGENC_CTYPE_ASCII:
case ONIGENC_CTYPE_ALNUM:
if (not != 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT_CHKDUP(cc->bs, c);
}
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT_CHKDUP(cc->bs, c);
}
}
break;
case ONIGENC_CTYPE_GRAPH:
case ONIGENC_CTYPE_PRINT:
if (not != 0) {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)
|| c >= maxcode)
BITSET_SET_BIT_CHKDUP(cc->bs, c);
}
if (ascii_range)
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < maxcode; c++) {
if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))
BITSET_SET_BIT_CHKDUP(cc->bs, c);
}
if (! ascii_range)
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
break;
case ONIGENC_CTYPE_WORD:
if (not == 0) {
for (c = 0; c < maxcode; c++) {
if (ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT_CHKDUP(cc->bs, c);
}
if (! ascii_range)
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
else {
for (c = 0; c < SINGLE_BYTE_SIZE; c++) {
if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */
&& (! ONIGENC_IS_CODE_WORD(enc, c) || c >= maxcode))
BITSET_SET_BIT_CHKDUP(cc->bs, c);
}
if (ascii_range)
ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
return r;
}
static int
parse_posix_bracket(CClassNode* cc, CClassNode* asc_cc,
UChar** src, UChar* end, ScanEnv* env)
{
#define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20
#define POSIX_BRACKET_NAME_MIN_LEN 4
static const PosixBracketEntryType PBS[] = {
POSIX_BRACKET_ENTRY_INIT("alnum", ONIGENC_CTYPE_ALNUM),
POSIX_BRACKET_ENTRY_INIT("alpha", ONIGENC_CTYPE_ALPHA),
POSIX_BRACKET_ENTRY_INIT("blank", ONIGENC_CTYPE_BLANK),
POSIX_BRACKET_ENTRY_INIT("cntrl", ONIGENC_CTYPE_CNTRL),
POSIX_BRACKET_ENTRY_INIT("digit", ONIGENC_CTYPE_DIGIT),
POSIX_BRACKET_ENTRY_INIT("graph", ONIGENC_CTYPE_GRAPH),
POSIX_BRACKET_ENTRY_INIT("lower", ONIGENC_CTYPE_LOWER),
POSIX_BRACKET_ENTRY_INIT("print", ONIGENC_CTYPE_PRINT),
POSIX_BRACKET_ENTRY_INIT("punct", ONIGENC_CTYPE_PUNCT),
POSIX_BRACKET_ENTRY_INIT("space", ONIGENC_CTYPE_SPACE),
POSIX_BRACKET_ENTRY_INIT("upper", ONIGENC_CTYPE_UPPER),
POSIX_BRACKET_ENTRY_INIT("xdigit", ONIGENC_CTYPE_XDIGIT),
POSIX_BRACKET_ENTRY_INIT("ascii", ONIGENC_CTYPE_ASCII),
POSIX_BRACKET_ENTRY_INIT("word", ONIGENC_CTYPE_WORD),
};
const PosixBracketEntryType *pb;
int not, i, r;
int ascii_range;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar *p = *src;
if (PPEEK_IS('^')) {
PINC_S;
not = 1;
}
else
not = 0;
if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3)
goto not_posix_bracket;
ascii_range = IS_ASCII_RANGE(env->option) &&
! IS_POSIX_BRACKET_ALL_RANGE(env->option);
for (pb = PBS; pb < PBS + numberof(PBS); pb++) {
if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) {
p = (UChar* )onigenc_step(enc, p, end, pb->len);
if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0)
return ONIGERR_INVALID_POSIX_BRACKET_TYPE;
r = add_ctype_to_cc(cc, pb->ctype, not, ascii_range, env);
if (r != 0) return r;
if (IS_NOT_NULL(asc_cc)) {
if (pb->ctype != ONIGENC_CTYPE_WORD &&
pb->ctype != ONIGENC_CTYPE_ASCII &&
!ascii_range)
r = add_ctype_to_cc(asc_cc, pb->ctype, not, ascii_range, env);
if (r != 0) return r;
}
PINC_S; PINC_S;
*src = p;
return 0;
}
}
not_posix_bracket:
c = 0;
i = 0;
while (!PEND && ((c = PPEEK) != ':') && c != ']') {
PINC_S;
if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break;
}
if (c == ':' && ! PEND) {
PINC_S;
if (! PEND) {
PFETCH_S(c);
if (c == ']')
return ONIGERR_INVALID_POSIX_BRACKET_TYPE;
}
}
return 1; /* 1: is not POSIX bracket, but no error. */
}
static int
fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env)
{
int r;
OnigCodePoint c;
OnigEncoding enc = env->enc;
UChar *prev, *start, *p = *src;
r = 0;
start = prev = p;
while (!PEND) {
prev = p;
PFETCH_S(c);
if (c == '}') {
r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev);
if (r < 0) break;
*src = p;
return r;
}
else if (c == '(' || c == ')' || c == '{' || c == '|') {
r = ONIGERR_INVALID_CHAR_PROPERTY_NAME;
break;
}
}
onig_scan_env_set_error_string(env, r, *src, prev);
return r;
}
static int cclass_case_fold(Node** np, CClassNode* cc, CClassNode* asc_cc, ScanEnv* env);
static int
parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end,
ScanEnv* env)
{
int r, ctype;
CClassNode* cc;
ctype = fetch_char_property_to_ctype(src, end, env);
if (ctype < 0) return ctype;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = NCCLASS(*np);
r = add_ctype_to_cc(cc, ctype, 0, 0, env);
if (r != 0) return r;
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
if (IS_IGNORECASE(env->option)) {
if (ctype != ONIGENC_CTYPE_ASCII)
r = cclass_case_fold(np, cc, cc, env);
}
return r;
}
enum CCSTATE {
CCS_VALUE,
CCS_RANGE,
CCS_COMPLETE,
CCS_START
};
enum CCVALTYPE {
CCV_SB,
CCV_CODE_POINT,
CCV_CLASS
};
static int
next_state_class(CClassNode* cc, CClassNode* asc_cc,
OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB) {
BITSET_SET_BIT_CHKDUP(cc->bs, (int )(*vs));
if (IS_NOT_NULL(asc_cc))
BITSET_SET_BIT(asc_cc->bs, (int )(*vs));
}
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
if (IS_NOT_NULL(asc_cc)) {
r = add_code_range0(&(asc_cc->mbuf), env, *vs, *vs, 0);
if (r < 0) return r;
}
}
}
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
}
static int
next_state_val(CClassNode* cc, CClassNode* asc_cc,
OnigCodePoint *from, OnigCodePoint to,
int* from_israw, int to_israw,
enum CCVALTYPE intype, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
switch (*state) {
case CCS_VALUE:
if (*type == CCV_SB) {
BITSET_SET_BIT_CHKDUP(cc->bs, (int )(*from));
if (IS_NOT_NULL(asc_cc))
BITSET_SET_BIT(asc_cc->bs, (int )(*from));
}
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *from, *from);
if (r < 0) return r;
if (IS_NOT_NULL(asc_cc)) {
r = add_code_range0(&(asc_cc->mbuf), env, *from, *from, 0);
if (r < 0) return r;
}
}
break;
case CCS_RANGE:
if (intype == *type) {
if (intype == CCV_SB) {
if (*from > 0xff || to > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
if (*from > to) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(env, cc->bs, (int )*from, (int )to);
if (IS_NOT_NULL(asc_cc))
bitset_set_range(env, asc_cc->bs, (int )*from, (int )to);
}
else {
r = add_code_range(&(cc->mbuf), env, *from, to);
if (r < 0) return r;
if (IS_NOT_NULL(asc_cc)) {
r = add_code_range0(&(asc_cc->mbuf), env, *from, to, 0);
if (r < 0) return r;
}
}
}
else {
if (*from > to) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(env, cc->bs, (int )*from, (int )(to < 0xff ? to : 0xff));
r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*from, to);
if (r < 0) return r;
if (IS_NOT_NULL(asc_cc)) {
bitset_set_range(env, asc_cc->bs, (int )*from, (int )(to < 0xff ? to : 0xff));
r = add_code_range0(&(asc_cc->mbuf), env, (OnigCodePoint )*from, to, 0);
if (r < 0) return r;
}
}
ccs_range_end:
*state = CCS_COMPLETE;
break;
case CCS_COMPLETE:
case CCS_START:
*state = CCS_VALUE;
break;
default:
break;
}
*from_israw = to_israw;
*from = to;
*type = intype;
return 0;
}
static int
code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped,
ScanEnv* env)
{
int in_esc;
OnigCodePoint code;
OnigEncoding enc = env->enc;
UChar* p = from;
in_esc = 0;
while (! PEND) {
if (ignore_escaped && in_esc) {
in_esc = 0;
}
else {
PFETCH_S(code);
if (code == c) return 1;
if (code == MC_ESC(env->syntax)) in_esc = 1;
}
}
return 0;
}
static int
parse_char_class(Node** np, Node** asc_np, OnigToken* tok, UChar** src, UChar* end,
ScanEnv* env)
{
int r, neg, len, fetched, and_start;
OnigCodePoint v, vs;
UChar *p;
Node* node;
Node* asc_node;
CClassNode *cc, *prev_cc;
CClassNode *asc_cc, *asc_prev_cc;
CClassNode work_cc, asc_work_cc;
enum CCSTATE state;
enum CCVALTYPE val_type, in_type;
int val_israw, in_israw;
*np = *asc_np = NULL_NODE;
env->parse_depth++;
if (env->parse_depth > ParseDepthLimit)
return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
prev_cc = asc_prev_cc = (CClassNode* )NULL;
r = fetch_token_in_cc(tok, src, end, env);
if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) {
neg = 1;
r = fetch_token_in_cc(tok, src, end, env);
}
else {
neg = 0;
}
if (r < 0) return r;
if (r == TK_CC_CLOSE) {
if (! code_exist_check((OnigCodePoint )']',
*src, env->pattern_end, 1, env))
return ONIGERR_EMPTY_CHAR_CLASS;
CC_ESC_WARN(env, (UChar* )"]");
r = tok->type = TK_CHAR; /* allow []...] */
}
*np = node = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(node);
cc = NCCLASS(node);
if (IS_IGNORECASE(env->option)) {
*asc_np = asc_node = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(asc_node);
asc_cc = NCCLASS(asc_node);
}
else {
asc_node = NULL_NODE;
asc_cc = NULL;
}
and_start = 0;
state = CCS_START;
p = *src;
while (r != TK_CC_CLOSE) {
fetched = 0;
switch (r) {
case TK_CHAR:
if ((tok->u.code >= SINGLE_BYTE_SIZE) ||
(len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c)) > 1) {
in_type = CCV_CODE_POINT;
}
else if (len < 0) {
r = len;
goto err;
}
else {
sb_char:
in_type = CCV_SB;
}
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
goto val_entry2;
break;
case TK_RAW_BYTE:
/* tok->base != 0 : octal or hexadec. */
if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) {
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN;
UChar* psave = p;
int i, base = tok->base;
buf[0] = (UChar )tok->u.c;
for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
if (r != TK_RAW_BYTE || tok->base != base) {
fetched = 1;
break;
}
buf[i] = (UChar )tok->u.c;
}
if (i < ONIGENC_MBC_MINLEN(env->enc)) {
r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
goto err;
}
len = enclen(env->enc, buf, buf + i);
if (i < len) {
r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
goto err;
}
else if (i > len) { /* fetch back */
p = psave;
for (i = 1; i < len; i++) {
(void)fetch_token_in_cc(tok, &p, end, env);
/* no need to check the retun value (already checked above) */
}
fetched = 0;
}
if (i == 1) {
v = (OnigCodePoint )buf[0];
goto raw_single;
}
else {
v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe);
in_type = CCV_CODE_POINT;
}
}
else {
v = (OnigCodePoint )tok->u.c;
raw_single:
in_type = CCV_SB;
}
in_israw = 1;
goto val_entry2;
break;
case TK_CODE_POINT:
v = tok->u.code;
in_israw = 1;
val_entry:
len = ONIGENC_CODE_TO_MBCLEN(env->enc, v);
if (len < 0) {
r = len;
goto err;
}
in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT);
val_entry2:
r = next_state_val(cc, asc_cc, &vs, v, &val_israw, in_israw, in_type, &val_type,
&state, env);
if (r != 0) goto err;
break;
case TK_POSIX_BRACKET_OPEN:
r = parse_posix_bracket(cc, asc_cc, &p, end, env);
if (r < 0) goto err;
if (r == 1) { /* is not POSIX bracket */
CC_ESC_WARN(env, (UChar* )"[");
p = tok->backp;
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
goto val_entry;
}
goto next_class;
break;
case TK_CHAR_TYPE:
r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not,
IS_ASCII_RANGE(env->option), env);
if (r != 0) return r;
if (IS_NOT_NULL(asc_cc)) {
if (tok->u.prop.ctype != ONIGENC_CTYPE_WORD)
r = add_ctype_to_cc(asc_cc, tok->u.prop.ctype, tok->u.prop.not,
IS_ASCII_RANGE(env->option), env);
if (r != 0) return r;
}
next_class:
r = next_state_class(cc, asc_cc, &vs, &val_type, &state, env);
if (r != 0) goto err;
break;
case TK_CHAR_PROPERTY:
{
int ctype;
ctype = fetch_char_property_to_ctype(&p, end, env);
if (ctype < 0) return ctype;
r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, 0, env);
if (r != 0) return r;
if (IS_NOT_NULL(asc_cc)) {
if (ctype != ONIGENC_CTYPE_ASCII)
r = add_ctype_to_cc(asc_cc, ctype, tok->u.prop.not, 0, env);
if (r != 0) return r;
}
goto next_class;
}
break;
case TK_CC_RANGE:
if (state == CCS_VALUE) {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
if (r == TK_CC_CLOSE) { /* allow [x-] */
range_end_val:
v = (OnigCodePoint )'-';
in_israw = 0;
goto val_entry;
}
else if (r == TK_CC_AND) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val;
}
if (val_type == CCV_CLASS) {
r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS;
goto err;
}
state = CCS_RANGE;
}
else if (state == CCS_START) {
/* [-xa] is allowed */
v = (OnigCodePoint )tok->u.c;
in_israw = 0;
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
/* [--x] or [a&&-x] is warned. */
if (r == TK_CC_RANGE || and_start != 0)
CC_ESC_WARN(env, (UChar* )"-");
goto val_entry;
}
else if (state == CCS_RANGE) {
CC_ESC_WARN(env, (UChar* )"-");
goto sb_char; /* [!--x] is allowed */
}
else { /* CCS_COMPLETE */
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
fetched = 1;
if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */
else if (r == TK_CC_AND) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val;
}
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) {
CC_ESC_WARN(env, (UChar* )"-");
goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */
}
r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS;
goto err;
}
break;
case TK_CC_CC_OPEN: /* [ */
{
Node *anode, *aasc_node;
CClassNode* acc;
r = parse_char_class(&anode, &aasc_node, tok, &p, end, env);
if (r == 0) {
acc = NCCLASS(anode);
r = or_cclass(cc, acc, env);
}
if (r == 0 && IS_NOT_NULL(aasc_node)) {
acc = NCCLASS(aasc_node);
r = or_cclass(asc_cc, acc, env);
}
onig_node_free(anode);
onig_node_free(aasc_node);
if (r != 0) goto err;
}
break;
case TK_CC_AND: /* && */
{
if (state == CCS_VALUE) {
r = next_state_val(cc, asc_cc, &vs, 0, &val_israw, 0, val_type,
&val_type, &state, env);
if (r != 0) goto err;
}
/* initialize local variables */
and_start = 1;
state = CCS_START;
if (IS_NOT_NULL(prev_cc)) {
r = and_cclass(prev_cc, cc, env);
if (r != 0) goto err;
bbuf_free(cc->mbuf);
if (IS_NOT_NULL(asc_cc)) {
r = and_cclass(asc_prev_cc, asc_cc, env);
if (r != 0) goto err;
bbuf_free(asc_cc->mbuf);
}
}
else {
prev_cc = cc;
cc = &work_cc;
if (IS_NOT_NULL(asc_cc)) {
asc_prev_cc = asc_cc;
asc_cc = &asc_work_cc;
}
}
initialize_cclass(cc);
if (IS_NOT_NULL(asc_cc))
initialize_cclass(asc_cc);
}
break;
case TK_EOT:
r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS;
goto err;
break;
default:
r = ONIGERR_PARSER_BUG;
goto err;
break;
}
if (fetched)
r = tok->type;
else {
r = fetch_token_in_cc(tok, &p, end, env);
if (r < 0) goto err;
}
}
if (state == CCS_VALUE) {
r = next_state_val(cc, asc_cc, &vs, 0, &val_israw, 0, val_type,
&val_type, &state, env);
if (r != 0) goto err;
}
if (IS_NOT_NULL(prev_cc)) {
r = and_cclass(prev_cc, cc, env);
if (r != 0) goto err;
bbuf_free(cc->mbuf);
cc = prev_cc;
if (IS_NOT_NULL(asc_cc)) {
r = and_cclass(asc_prev_cc, asc_cc, env);
if (r != 0) goto err;
bbuf_free(asc_cc->mbuf);
asc_cc = asc_prev_cc;
}
}
if (neg != 0) {
NCCLASS_SET_NOT(cc);
if (IS_NOT_NULL(asc_cc))
NCCLASS_SET_NOT(asc_cc);
}
else {
NCCLASS_CLEAR_NOT(cc);
if (IS_NOT_NULL(asc_cc))
NCCLASS_CLEAR_NOT(asc_cc);
}
if (IS_NCCLASS_NOT(cc) &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) {
int is_empty;
is_empty = (IS_NULL(cc->mbuf) ? 1 : 0);
if (is_empty != 0)
BITSET_IS_EMPTY(cc->bs, is_empty);
if (is_empty == 0) {
#define NEWLINE_CODE 0x0a
if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) {
if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1)
BITSET_SET_BIT_CHKDUP(cc->bs, NEWLINE_CODE);
else {
r = add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE);
if (r < 0) goto err;
}
}
}
}
*src = p;
env->parse_depth--;
return 0;
err:
if (cc != NCCLASS(*np))
bbuf_free(cc->mbuf);
if (IS_NOT_NULL(asc_cc) && (asc_cc != NCCLASS(*asc_np)))
bbuf_free(asc_cc->mbuf);
return r;
}
static int parse_subexp(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env);
static int
parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end,
ScanEnv* env)
{
int r = 0, num;
Node *target, *work1 = NULL, *work2 = NULL;
OnigOptionType option;
OnigCodePoint c;
OnigEncoding enc = env->enc;
#ifdef USE_NAMED_GROUP
int list_capture;
#endif
UChar* p = *src;
PFETCH_READY;
*np = NULL;
if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
option = env->option;
if (PPEEK_IS('?') &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
switch (c) {
case ':': /* (?:...) grouping only */
group:
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(np, tok, term, &p, end, env);
if (r < 0) return r;
*src = p;
return 1; /* group */
break;
case '=':
*np = onig_node_new_anchor(ANCHOR_PREC_READ);
break;
case '!': /* preceding read */
*np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT);
break;
case '>': /* (?>...) stop backtrack */
*np = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
break;
case '~': /* (?~...) absent operator */
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_TILDE_ABSENT)) {
*np = node_new_enclose(ENCLOSE_ABSENT);
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
break;
#ifdef USE_NAMED_GROUP
case '\'':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
goto named_group1;
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
# ifdef USE_CAPITAL_P_NAMED_GROUP
case 'P': /* (?P<name>...) */
if (!PEND &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_CAPITAL_P_NAMED_GROUP)) {
PFETCH(c);
if (c == '<') goto named_group1;
}
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
# endif
#endif
case '<': /* look behind (?<=...), (?<!...) */
if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
PFETCH(c);
if (c == '=')
*np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND);
else if (c == '!')
*np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT);
#ifdef USE_NAMED_GROUP
else { /* (?<name>...) */
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
UChar *name;
UChar *name_end;
PUNFETCH;
c = '<';
named_group1:
list_capture = 0;
# ifdef USE_CAPTURE_HISTORY
named_group2:
# endif
name = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0);
if (r < 0) return r;
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM)
return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY;
r = name_add(env->reg, name, name_end, num, env);
if (r != 0) return r;
*np = node_new_enclose_memory(env->option, 1);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->regnum = num;
if (list_capture != 0)
BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num);
env->num_named++;
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
}
#else
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
#endif
break;
#ifdef USE_CAPTURE_HISTORY
case '@':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) {
# ifdef USE_NAMED_GROUP
if (!PEND &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) {
PFETCH(c);
if (c == '<' || c == '\'') {
list_capture = 1;
goto named_group2; /* (?@<name>...) */
}
PUNFETCH;
}
# endif
*np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(*np);
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
if (num >= (int )BIT_STATUS_BITS_NUM)
return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY;
NENCLOSE(*np)->regnum = num;
BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num);
}
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
break;
#endif /* USE_CAPTURE_HISTORY */
case '(': /* conditional expression: (?(cond)yes), (?(cond)yes|no) */
if (!PEND &&
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LPAREN_CONDITION)) {
UChar *name = NULL;
UChar *name_end;
PFETCH(c);
if (ONIGENC_IS_CODE_DIGIT(enc, c)) { /* (n) */
PUNFETCH;
r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &num, 1);
if (r < 0) return r;
#if 0
/* Relative number is not currently supported. (same as Perl) */
if (num < 0) {
num = BACKREF_REL_TO_ABS(num, env);
if (num <= 0)
return ONIGERR_INVALID_BACKREF;
}
#endif
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[num]))
return ONIGERR_INVALID_BACKREF;
}
}
#ifdef USE_NAMED_GROUP
else if (c == '<' || c == '\'') { /* (<name>), ('name') */
name = p;
r = fetch_named_backref_token(c, tok, &p, end, env);
if (r < 0) return r;
if (!PPEEK_IS(')')) return ONIGERR_UNDEFINED_GROUP_OPTION;
PINC;
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_USE_LEFT_MOST_NAMED_GROUP)) {
num = tok->u.backref.ref1;
}
else {
/* FIXME:
* Use left most named group for now. This is the same as Perl.
* However this should use the same strategy as normal back-
* references on Ruby syntax; search right to left. */
int len = tok->u.backref.num;
num = len > 1 ? tok->u.backref.refs[0] : tok->u.backref.ref1;
}
}
#endif
else
return ONIGERR_INVALID_CONDITION_PATTERN;
*np = node_new_enclose(ENCLOSE_CONDITION);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->regnum = num;
if (IS_NOT_NULL(name)) NENCLOSE(*np)->state |= NST_NAME_REF;
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#if 0
case '|': /* branch reset: (?|...) */
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_VBAR_BRANCH_RESET)) {
/* TODO */
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#endif
case '^': /* loads default options */
if (!PEND && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
/* d-imsx */
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1);
ONOFF(option, ONIG_OPTION_IGNORECASE, 1);
ONOFF(option, ONIG_OPTION_SINGLELINE, 0);
ONOFF(option, ONIG_OPTION_MULTILINE, 1);
ONOFF(option, ONIG_OPTION_EXTEND, 1);
PFETCH(c);
}
#if 0
else if (!PEND && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) {
/* d-imx */
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 0);
ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 0);
ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 0);
ONOFF(option, ONIG_OPTION_IGNORECASE, 1);
ONOFF(option, ONIG_OPTION_MULTILINE, 1);
ONOFF(option, ONIG_OPTION_EXTEND, 1);
PFETCH(c);
}
#endif
else {
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
/* fall through */
#ifdef USE_POSIXLINE_OPTION
case 'p':
#endif
case '-': case 'i': case 'm': case 's': case 'x':
case 'a': case 'd': case 'l': case 'u':
{
int neg = 0;
while (1) {
switch (c) {
case ':':
case ')':
break;
case '-': neg = 1; break;
case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break;
case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break;
case 's':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
ONOFF(option, ONIG_OPTION_MULTILINE, neg);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
case 'm':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) {
ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0));
}
else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) {
ONOFF(option, ONIG_OPTION_MULTILINE, neg);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
#ifdef USE_POSIXLINE_OPTION
case 'p':
ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg);
break;
#endif
case 'a': /* limits \d, \s, \w and POSIX brackets to ASCII range */
if ((IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) ||
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) &&
(neg == 0)) {
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 0);
ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 1);
ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 1);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
case 'u':
if ((IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) ||
IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) &&
(neg == 0)) {
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1);
ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 1);
ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 1);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
case 'd':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) &&
(neg == 0)) {
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1);
}
else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY) &&
(neg == 0)) {
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 0);
ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 0);
ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 0);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
case 'l':
if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) && (neg == 0)) {
ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1);
}
else
return ONIGERR_UNDEFINED_GROUP_OPTION;
break;
default:
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
if (c == ')') {
*np = node_new_option(option);
CHECK_NULL_RETURN_MEMERR(*np);
*src = p;
return 2; /* option only */
}
else if (c == ':') {
OnigOptionType prev = env->option;
env->option = option;
r = fetch_token(tok, &p, end, env);
if (r < 0) {
env->option = prev;
return r;
}
r = parse_subexp(&target, tok, term, &p, end, env);
env->option = prev;
if (r < 0) return r;
*np = node_new_option(option);
CHECK_NULL_RETURN_MEMERR(*np);
NENCLOSE(*np)->target = target;
*src = p;
return 0;
}
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
}
}
break;
default:
return ONIGERR_UNDEFINED_GROUP_OPTION;
}
}
else {
if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP))
goto group;
*np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(*np);
num = scan_env_add_mem_entry(env);
if (num < 0) return num;
NENCLOSE(*np)->regnum = num;
}
CHECK_NULL_RETURN_MEMERR(*np);
r = fetch_token(tok, &p, end, env);
if (r < 0) return r;
r = parse_subexp(&target, tok, term, &p, end, env);
if (r < 0) {
onig_node_free(target);
return r;
}
if (NTYPE(*np) == NT_ANCHOR)
NANCHOR(*np)->target = target;
else {
NENCLOSE(*np)->target = target;
if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) {
/* Don't move this to previous of parse_subexp() */
r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np);
if (r != 0) return r;
}
else if (NENCLOSE(*np)->type == ENCLOSE_CONDITION) {
if (NTYPE(target) != NT_ALT) {
/* convert (?(cond)yes) to (?(cond)yes|empty) */
work1 = node_new_empty();
if (IS_NULL(work1)) goto err;
work2 = onig_node_new_alt(work1, NULL_NODE);
if (IS_NULL(work2)) goto err;
work1 = onig_node_new_alt(target, work2);
if (IS_NULL(work1)) goto err;
NENCLOSE(*np)->target = work1;
}
}
}
*src = p;
return 0;
err:
onig_node_free(work1);
onig_node_free(work2);
onig_node_free(*np);
*np = NULL;
return ONIGERR_MEMORY;
}
static const char* const PopularQStr[] = {
"?", "*", "+", "??", "*?", "+?"
};
static const char* const ReduceQStr[] = {
"", "", "*", "*?", "??", "+ and ??", "+? and ?"
};
static int
set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env)
{
QtfrNode* qn;
qn = NQTFR(qnode);
if (qn->lower == 1 && qn->upper == 1) {
return 1;
}
switch (NTYPE(target)) {
case NT_STR:
if (! group) {
StrNode* sn = NSTR(target);
if (str_node_can_be_split(sn, env->enc)) {
Node* n = str_node_split_last_char(sn, env->enc);
if (IS_NOT_NULL(n)) {
qn->target = n;
return 2;
}
}
}
break;
case NT_QTFR:
{ /* check redundant double repeat. */
/* verbose warn (?:.?)? etc... but not warn (.?)? etc... */
QtfrNode* qnt = NQTFR(target);
int nestq_num = popular_quantifier_num(qn);
int targetq_num = popular_quantifier_num(qnt);
#ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR
if (nestq_num >= 0 && targetq_num >= 0 &&
IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) {
switch (ReduceTypeTable[targetq_num][nestq_num]) {
case RQ_ASIS:
break;
case RQ_DEL:
if (onig_warn != onig_null_warn) {
onig_syntax_warn(env, "regular expression has redundant nested repeat operator '%s'",
PopularQStr[targetq_num]);
}
goto warn_exit;
break;
default:
if (onig_warn != onig_null_warn) {
onig_syntax_warn(env, "nested repeat operator '%s' and '%s' was replaced with '%s' in regular expression",
PopularQStr[targetq_num], PopularQStr[nestq_num],
ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]);
}
goto warn_exit;
break;
}
}
warn_exit:
#endif
if (targetq_num >= 0) {
if (nestq_num >= 0) {
onig_reduce_nested_quantifier(qnode, target);
goto q_exit;
}
else if (targetq_num == 1 || targetq_num == 2) { /* * or + */
/* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */
if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) {
qn->upper = (qn->lower == 0 ? 1 : qn->lower);
}
}
}
}
break;
default:
break;
}
qn->target = target;
q_exit:
return 0;
}
#ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
static int
clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc)
{
BBuf *tbuf;
int r;
if (IS_NCCLASS_NOT(cc)) {
bitset_invert(cc->bs);
if (! ONIGENC_IS_SINGLEBYTE(enc)) {
r = not_code_range_buf(enc, cc->mbuf, &tbuf);
if (r != 0) return r;
bbuf_free(cc->mbuf);
cc->mbuf = tbuf;
}
NCCLASS_CLEAR_NOT(cc);
}
return 0;
}
#endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */
typedef struct {
ScanEnv* env;
CClassNode* cc;
CClassNode* asc_cc;
Node* alt_root;
Node** ptail;
} IApplyCaseFoldArg;
static int
i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[],
int to_len, void* arg)
{
IApplyCaseFoldArg* iarg;
ScanEnv* env;
CClassNode* cc;
CClassNode* asc_cc;
BitSetRef bs;
int add_flag, r;
iarg = (IApplyCaseFoldArg* )arg;
env = iarg->env;
cc = iarg->cc;
asc_cc = iarg->asc_cc;
bs = cc->bs;
if (IS_NULL(asc_cc)) {
add_flag = 0;
}
else if (ONIGENC_IS_ASCII_CODE(from) == ONIGENC_IS_ASCII_CODE(*to)) {
add_flag = 1;
}
else {
add_flag = onig_is_code_in_cc(env->enc, from, asc_cc);
if (IS_NCCLASS_NOT(asc_cc))
add_flag = !add_flag;
}
if (to_len == 1) {
int is_in = onig_is_code_in_cc(env->enc, from, cc);
#ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) ||
(is_in == 0 && IS_NCCLASS_NOT(cc))) {
if (add_flag) {
if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) {
r = add_code_range0(&(cc->mbuf), env, *to, *to, 0);
if (r < 0) return r;
}
else {
BITSET_SET_BIT(bs, *to);
}
}
}
#else
if (is_in != 0) {
if (add_flag) {
if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) {
if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc);
r = add_code_range0(&(cc->mbuf), env, *to, *to, 0);
if (r < 0) return r;
}
else {
if (IS_NCCLASS_NOT(cc)) {
BITSET_CLEAR_BIT(bs, *to);
}
else {
BITSET_SET_BIT(bs, *to);
}
}
}
}
#endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */
}
else {
int r, i, len;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN];
Node *snode = NULL_NODE;
if (onig_is_code_in_cc(env->enc, from, cc)
#ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
&& !IS_NCCLASS_NOT(cc)
#endif
) {
for (i = 0; i < to_len; i++) {
len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf);
if (i == 0) {
snode = onig_node_new_str(buf, buf + len);
CHECK_NULL_RETURN_MEMERR(snode);
/* char-class expanded multi-char only
compare with string folded at match time. */
NSTRING_SET_AMBIG(snode);
}
else {
r = onig_node_str_cat(snode, buf, buf + len);
if (r < 0) {
onig_node_free(snode);
return r;
}
}
}
*(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE);
CHECK_NULL_RETURN_MEMERR(*(iarg->ptail));
iarg->ptail = &(NCDR((*(iarg->ptail))));
}
}
return 0;
}
static int
cclass_case_fold(Node** np, CClassNode* cc, CClassNode* asc_cc, ScanEnv* env)
{
int r;
IApplyCaseFoldArg iarg;
iarg.env = env;
iarg.cc = cc;
iarg.asc_cc = asc_cc;
iarg.alt_root = NULL_NODE;
iarg.ptail = &(iarg.alt_root);
r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag,
i_apply_case_fold, &iarg);
if (r != 0) {
onig_node_free(iarg.alt_root);
return r;
}
if (IS_NOT_NULL(iarg.alt_root)) {
Node* work = onig_node_new_alt(*np, iarg.alt_root);
if (IS_NULL(work)) {
onig_node_free(iarg.alt_root);
return ONIGERR_MEMORY;
}
*np = work;
}
return r;
}
static int
node_linebreak(Node** np, ScanEnv* env)
{
/* same as (?>\x0D\x0A|[\x0A-\x0D\x{85}\x{2028}\x{2029}]) */
Node* left = NULL;
Node* right = NULL;
Node* target1 = NULL;
Node* target2 = NULL;
CClassNode* cc;
int num1, num2, r;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN * 2];
/* \x0D\x0A */
num1 = ONIGENC_CODE_TO_MBC(env->enc, 0x0D, buf);
if (num1 < 0) return num1;
num2 = ONIGENC_CODE_TO_MBC(env->enc, 0x0A, buf + num1);
if (num2 < 0) return num2;
left = node_new_str_raw(buf, buf + num1 + num2);
if (IS_NULL(left)) goto err;
/* [\x0A-\x0D] or [\x0A-\x0D\x{85}\x{2028}\x{2029}] */
right = node_new_cclass();
if (IS_NULL(right)) goto err;
cc = NCCLASS(right);
if (ONIGENC_MBC_MINLEN(env->enc) > 1) {
r = add_code_range(&(cc->mbuf), env, 0x0A, 0x0D);
if (r != 0) goto err;
}
else {
bitset_set_range(env, cc->bs, 0x0A, 0x0D);
}
/* TODO: move this block to enc/unicode.c */
if (ONIGENC_IS_UNICODE(env->enc)) {
/* UTF-8, UTF-16BE/LE, UTF-32BE/LE */
r = add_code_range(&(cc->mbuf), env, 0x85, 0x85);
if (r != 0) goto err;
r = add_code_range(&(cc->mbuf), env, 0x2028, 0x2029);
if (r != 0) goto err;
}
/* ...|... */
target1 = onig_node_new_alt(right, NULL_NODE);
if (IS_NULL(target1)) goto err;
right = NULL;
target2 = onig_node_new_alt(left, target1);
if (IS_NULL(target2)) goto err;
left = NULL;
target1 = NULL;
/* (?>...) */
*np = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
if (IS_NULL(*np)) goto err;
NENCLOSE(*np)->target = target2;
return ONIG_NORMAL;
err:
onig_node_free(left);
onig_node_free(right);
onig_node_free(target1);
onig_node_free(target2);
return ONIGERR_MEMORY;
}
static int
propname2ctype(ScanEnv* env, const char* propname)
{
UChar* name = (UChar* )propname;
UChar* name_end = name + strlen(propname);
int ctype = env->enc->property_name_to_ctype(ONIG_ENCODING_ASCII,
name, name_end);
if (ctype < 0) {
onig_scan_env_set_error_string(env, ctype, name, name_end);
}
return ctype;
}
static int
add_property_to_cc(CClassNode* cc, const char* propname, int not, ScanEnv* env)
{
int ctype = propname2ctype(env, propname);
if (ctype < 0) return ctype;
return add_ctype_to_cc(cc, ctype, not, 0, env);
}
/*
* helper methods for node_extended_grapheme_cluster (/\X/)
*/
static int
create_property_node(Node **np, ScanEnv* env, const char* propname)
{
int r;
CClassNode* cc;
*np = node_new_cclass();
if (IS_NULL(*np)) return ONIGERR_MEMORY;
cc = NCCLASS(*np);
r = add_property_to_cc(cc, propname, 0, env);
if (r != 0)
onig_node_free(*np);
return r;
}
static int
quantify_node(Node **np, int lower, int upper)
{
Node* tmp = node_new_quantifier(lower, upper, 0);
if (IS_NULL(tmp)) return ONIGERR_MEMORY;
NQTFR(tmp)->target = *np;
*np = tmp;
return 0;
}
static int
quantify_property_node(Node **np, ScanEnv* env, const char* propname, char repetitions)
{
int r;
int lower = 0;
int upper = REPEAT_INFINITE;
r = create_property_node(np, env, propname);
if (r != 0) return r;
switch (repetitions) {
case '?': upper = 1; break;
case '+': lower = 1; break;
case '*': break;
case '2': lower = upper = 2; break;
default : return ONIGERR_PARSER_BUG;
}
return quantify_node(np, lower, upper);
}
#define LIST 0
#define ALT 1
/* IMPORTANT: Make sure node_array ends with NULL_NODE */
static int
create_node_from_array(int kind, Node **np, Node **node_array)
{
Node* tmp = NULL_NODE;
int i = 0;
while (node_array[i] != NULL_NODE) i++;
while (--i >= 0) {
*np = kind==LIST ? node_new_list(node_array[i], tmp)
: onig_node_new_alt(node_array[i], tmp);
if (IS_NULL(*np)) {
while (i >= 0) {
onig_node_free(node_array[i]);
node_array[i--] = NULL_NODE;
}
onig_node_free(tmp);
return ONIGERR_MEMORY;
}
else
node_array[i] = NULL_NODE;
tmp = *np;
}
return 0;
}
#define R_ERR(call) r=(call);if(r!=0)goto err
/* Memory layout for common node array:
* The main purpose is to be able to easily free all leftover nodes
* after an error. As a side effect, we share some memory.
*
* The layout is as shown below (each line corresponds to one call of
* create_node_from_array()). Because create_node_from_array sets all
* nodes of the source to NULL_NODE, we can overlap the target array
* as long as we do not override the actual target location.
*
* Target Array name Index
*
* node_array 0 1 2 3 4 5 6 7 8 9 A B C D E F
* top_alts alts[5] 0 1 2 3 4*
* alts+1 list[4] 0 1 2 3*
* list+1 core_alts[7] 0 1 2 3 4 5 6*
* core_alts+0 H_list[4] 0 1 2 3*
* H_list+1 H_alt2[4] 0 1 2 3*
* h_alt2+1 H_list2[3] 0 1 2*
* core_alts+4 XP_list[4] 0 1 2 3*
* XP_list+1 Ex_list[4] 0 1 2 3*
*/
#define NODE_COMMON_SIZE 16
static int
node_extended_grapheme_cluster(Node** np, ScanEnv* env)
{
Node* tmp = NULL;
Node* np1 = NULL;
Node* top_alt = NULL;
int r = 0;
int num1;
int i;
int any_target_position;
UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN * 2];
OnigOptionType option;
/* node_common is function-global so that we can free all nodes
* in case of error. Unused slots are set to NULL_NODE at all times. */
Node *node_common[NODE_COMMON_SIZE];
Node **alts = node_common+0; /* size: 5 */
for (i=0; i<NODE_COMMON_SIZE; i++)
node_common[i] = NULL_NODE;
/* CRLF, common for both Unicode and non-Unicode */
/* \x0D\x0A */
r = ONIGENC_CODE_TO_MBC(env->enc, 0x0D, buf);
if (r < 0) goto err;
num1 = r;
r = ONIGENC_CODE_TO_MBC(env->enc, 0x0A, buf + num1);
if (r < 0) goto err;
alts[0] = node_new_str_raw(buf, buf + num1 + r);
if (IS_NULL(alts[0])) goto err;
#ifdef USE_UNICODE_PROPERTIES
if (ONIGENC_IS_UNICODE(env->enc)) { /* UTF-8, UTF-16BE/LE, UTF-32BE/LE */
CClassNode* cc;
if (propname2ctype(env, "Grapheme_Cluster_Break=Extend") < 0) goto err;
/* Unicode 11.0.0
* CRLF (already done)
* | [Control CR LF]
* | precore* core postcore*
* | . (to catch invalid stuff, because this seems to be spec for String#grapheme_clusters) */
/* [Control CR LF] (CR and LF are not in the spec, but this is a conformed fix) */
alts[1] = node_new_cclass();
if (IS_NULL(alts[1])) goto err;
cc = NCCLASS(alts[1]);
R_ERR(add_property_to_cc(cc, "Grapheme_Cluster_Break=Control", 0, env));
if (ONIGENC_MBC_MINLEN(env->enc) > 1) { /* UTF-16/UTF-32 */
R_ERR(add_code_range(&(cc->mbuf), env, 0x000A, 0x000A)); /* CR */
R_ERR(add_code_range(&(cc->mbuf), env, 0x000D, 0x000D)); /* LF */
}
else {
BITSET_SET_BIT(cc->bs, 0x0a);
BITSET_SET_BIT(cc->bs, 0x0d);
}
/* precore* core postcore* */
{
Node **list = alts + 3; /* size: 4 */
/* precore*; precore := Prepend */
R_ERR(quantify_property_node(list+0, env, "Grapheme_Cluster_Break=Prepend", '*'));
/* core := hangul-syllable
* | ri-sequence
* | xpicto-sequence
* | [^Control CR LF] */
{
Node **core_alts = list + 2; /* size: 7 */
/* hangul-syllable :=
* L* (V+ | LV V* | LVT) T*
* | L+
* | T+ */
/* hangul-syllable is an alternative (would be called H_alt)
* inside an alternative, but we flatten it into core_alts */
/* L* (V+ | LV V* | LVT) T* */
{
Node **H_list = core_alts + 1; /* size: 4 */
R_ERR(quantify_property_node(H_list+0, env, "Grapheme_Cluster_Break=L", '*'));
/* V+ | LV V* | LVT */
{
Node **H_alt2 = H_list + 2; /* size: 4 */
R_ERR(quantify_property_node(H_alt2+0, env, "Grapheme_Cluster_Break=V", '+'));
/* LV V* */
{
Node **H_list2 = H_alt2 + 2; /* size: 3 */
R_ERR(create_property_node(H_list2+0, env, "Grapheme_Cluster_Break=LV"));
R_ERR(quantify_property_node(H_list2+1, env, "Grapheme_Cluster_Break=V", '*'));
R_ERR(create_node_from_array(LIST, H_alt2+1, H_list2));
}
R_ERR(create_property_node(H_alt2+2, env, "Grapheme_Cluster_Break=LVT"));
R_ERR(create_node_from_array(ALT, H_list+1, H_alt2));
}
R_ERR(quantify_property_node(H_list+2, env, "Grapheme_Cluster_Break=T", '*'));
R_ERR(create_node_from_array(LIST, core_alts+0, H_list));
}
R_ERR(quantify_property_node(core_alts+1, env, "Grapheme_Cluster_Break=L", '+'));
R_ERR(quantify_property_node(core_alts+2, env, "Grapheme_Cluster_Break=T", '+'));
/* end of hangul-syllable */
/* ri-sequence := RI RI */
R_ERR(quantify_property_node(core_alts+3, env, "Regional_Indicator", '2'));
/* xpicto-sequence := \p{Extended_Pictographic} (Extend* ZWJ \p{Extended_Pictographic})* */
{
Node **XP_list = core_alts + 5; /* size: 3 */
R_ERR(create_property_node(XP_list+0, env, "Extended_Pictographic"));
/* (Extend* ZWJ \p{Extended_Pictographic})* */
{
Node **Ex_list = XP_list + 2; /* size: 4 */
/* assert(Ex_list+4 == node_common+NODE_COMMON_SIZE); */
R_ERR(quantify_property_node(Ex_list+0, env, "Grapheme_Cluster_Break=Extend", '*'));
/* ZWJ (ZERO WIDTH JOINER) */
r = ONIGENC_CODE_TO_MBC(env->enc, 0x200D, buf);
if (r < 0) goto err;
Ex_list[1] = node_new_str_raw(buf, buf + r);
if (IS_NULL(Ex_list[1])) goto err;
R_ERR(create_property_node(Ex_list+2, env, "Extended_Pictographic"));
R_ERR(create_node_from_array(LIST, XP_list+1, Ex_list));
}
R_ERR(quantify_node(XP_list+1, 0, REPEAT_INFINITE)); /* TODO: Check about node freeing */
R_ERR(create_node_from_array(LIST, core_alts+4, XP_list));
}
/* [^Control CR LF] */
core_alts[5] = node_new_cclass();
if (IS_NULL(core_alts[5])) goto err;
cc = NCCLASS(core_alts[5]);
if (ONIGENC_MBC_MINLEN(env->enc) > 1) { /* UTF-16/UTF-32 */
BBuf *inverted_buf = NULL;
/* Start with a positive buffer and invert at the end.
* Otherwise, adding single-character ranges work the wrong way. */
R_ERR(add_property_to_cc(cc, "Grapheme_Cluster_Break=Control", 0, env));
R_ERR(add_code_range(&(cc->mbuf), env, 0x000A, 0x000A)); /* CR */
R_ERR(add_code_range(&(cc->mbuf), env, 0x000D, 0x000D)); /* LF */
R_ERR(not_code_range_buf(env->enc, cc->mbuf, &inverted_buf, env));
cc->mbuf = inverted_buf; /* TODO: check what to do with buffer before inversion */
}
else {
R_ERR(add_property_to_cc(cc, "Grapheme_Cluster_Break=Control", 1, env));
BITSET_CLEAR_BIT(cc->bs, 0x0a);
BITSET_CLEAR_BIT(cc->bs, 0x0d);
}
R_ERR(create_node_from_array(ALT, list+1, core_alts));
}
/* postcore*; postcore = [Extend ZWJ SpacingMark] */
R_ERR(create_property_node(list+2, env, "Grapheme_Cluster_Break=Extend"));
cc = NCCLASS(list[2]);
R_ERR(add_property_to_cc(cc, "Grapheme_Cluster_Break=SpacingMark", 0, env));
R_ERR(add_code_range(&(cc->mbuf), env, 0x200D, 0x200D));
R_ERR(quantify_node(list+2, 0, REPEAT_INFINITE));
R_ERR(create_node_from_array(LIST, alts+2, list));
}
any_target_position = 3;
}
else
#endif /* USE_UNICODE_PROPERTIES */
{
any_target_position = 1;
}
/* PerlSyntax: (?s:.), RubySyntax: (?m:.), common for both Unicode and non-Unicode */
/* Not in Unicode spec (UAX #29), but added to catch invalid stuff,
* because this is Ruby spec for String#grapheme_clusters. */
np1 = node_new_anychar();
if (IS_NULL(np1)) goto err;
option = env->option;
ONOFF(option, ONIG_OPTION_MULTILINE, 0);
tmp = node_new_option(option);
if (IS_NULL(tmp)) goto err;
NENCLOSE(tmp)->target = np1;
alts[any_target_position] = tmp;
np1 = NULL;
R_ERR(create_node_from_array(ALT, &top_alt, alts));
/* (?>): For efficiency, because there is no text piece
* that is not in a grapheme cluster, and there is only one way
* to split a string into grapheme clusters. */
tmp = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
if (IS_NULL(tmp)) goto err;
NENCLOSE(tmp)->target = top_alt;
np1 = tmp;
#ifdef USE_UNICODE_PROPERTIES
if (ONIGENC_IS_UNICODE(env->enc)) {
/* Don't ignore case. */
option = env->option;
ONOFF(option, ONIG_OPTION_IGNORECASE, 1);
*np = node_new_option(option);
if (IS_NULL(*np)) goto err;
NENCLOSE(*np)->target = np1;
}
else
#endif
{
*np = np1;
}
return ONIG_NORMAL;
err:
onig_node_free(np1);
for (i=0; i<NODE_COMMON_SIZE; i++)
onig_node_free(node_common[i]);
return (r == 0) ? ONIGERR_MEMORY : r;
}
#undef R_ERR
static int
countbits(unsigned int bits)
{
bits = (bits & 0x55555555) + ((bits >> 1) & 0x55555555);
bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
bits = (bits & 0x0f0f0f0f) + ((bits >> 4) & 0x0f0f0f0f);
bits = (bits & 0x00ff00ff) + ((bits >> 8) & 0x00ff00ff);
return (bits & 0x0000ffff) + ((bits >>16) & 0x0000ffff);
}
static int
is_onechar_cclass(CClassNode* cc, OnigCodePoint* code)
{
const OnigCodePoint not_found = ONIG_LAST_CODE_POINT;
OnigCodePoint c = not_found;
int i;
BBuf *bbuf = cc->mbuf;
if (IS_NCCLASS_NOT(cc)) return 0;
/* check bbuf */
if (IS_NOT_NULL(bbuf)) {
OnigCodePoint n, *data;
GET_CODE_POINT(n, bbuf->p);
data = (OnigCodePoint* )(bbuf->p) + 1;
if ((n == 1) && (data[0] == data[1])) {
/* only one char found in the bbuf, save the code point. */
c = data[0];
if (((c < SINGLE_BYTE_SIZE) && BITSET_AT(cc->bs, c))) {
/* skip if c is included in the bitset */
c = not_found;
}
}
else {
return 0; /* the bbuf contains multiple chars */
}
}
/* check bitset */
for (i = 0; i < BITSET_SIZE; i++) {
Bits b1 = cc->bs[i];
if (b1 != 0) {
if (((b1 & (b1 - 1)) == 0) && (c == not_found)) {
c = BITS_IN_ROOM * i + countbits(b1 - 1);
} else {
return 0; /* the character class contains multiple chars */
}
}
}
if (c != not_found) {
*code = c;
return 1;
}
/* the character class contains no char. */
return 0;
}
static int
parse_exp(Node** np, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r, len, group = 0;
Node* qn;
Node** targetp;
*np = NULL;
if (tok->type == (enum TokenSyms )term)
goto end_of_token;
switch (tok->type) {
case TK_ALT:
case TK_EOT:
end_of_token:
*np = node_new_empty();
return tok->type;
break;
case TK_SUBEXP_OPEN:
r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env);
if (r < 0) return r;
if (r == 1) group = 1;
else if (r == 2) { /* option only */
Node* target;
OnigOptionType prev = env->option;
env->option = NENCLOSE(*np)->option;
r = fetch_token(tok, src, end, env);
if (r < 0) {
env->option = prev;
return r;
}
r = parse_subexp(&target, tok, term, src, end, env);
env->option = prev;
if (r < 0) {
onig_node_free(target);
return r;
}
NENCLOSE(*np)->target = target;
return tok->type;
}
break;
case TK_SUBEXP_CLOSE:
if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP))
return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS;
if (tok->escaped) goto tk_raw_byte;
else goto tk_byte;
break;
case TK_LINEBREAK:
r = node_linebreak(np, env);
if (r < 0) return r;
break;
case TK_EXTENDED_GRAPHEME_CLUSTER:
r = node_extended_grapheme_cluster(np, env);
if (r < 0) return r;
break;
case TK_KEEP:
*np = onig_node_new_anchor(ANCHOR_KEEP);
CHECK_NULL_RETURN_MEMERR(*np);
break;
case TK_STRING:
tk_byte:
{
*np = node_new_str(tok->backp, *src);
CHECK_NULL_RETURN_MEMERR(*np);
string_loop:
while (1) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r == TK_STRING) {
r = onig_node_str_cat(*np, tok->backp, *src);
}
#ifndef NUMBERED_CHAR_IS_NOT_CASE_AMBIG
else if (r == TK_CODE_POINT) {
r = node_str_cat_codepoint(*np, env->enc, tok->u.code);
}
#endif
else {
break;
}
if (r < 0) return r;
}
string_end:
targetp = np;
goto repeat;
}
break;
case TK_RAW_BYTE:
tk_raw_byte:
{
*np = node_new_str_raw_char((UChar )tok->u.c);
CHECK_NULL_RETURN_MEMERR(*np);
len = 1;
while (1) {
if (len >= ONIGENC_MBC_MINLEN(env->enc)) {
if (len == enclen(env->enc, NSTR(*np)->s, NSTR(*np)->end)) {
r = fetch_token(tok, src, end, env);
NSTRING_CLEAR_RAW(*np);
goto string_end;
}
}
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
if (r != TK_RAW_BYTE) {
/* Don't use this, it is wrong for little endian encodings. */
#ifdef USE_PAD_TO_SHORT_BYTE_CHAR
int rem;
if (len < ONIGENC_MBC_MINLEN(env->enc)) {
rem = ONIGENC_MBC_MINLEN(env->enc) - len;
(void )node_str_head_pad(NSTR(*np), rem, (UChar )0);
if (len + rem == enclen(env->enc, NSTR(*np)->s)) {
NSTRING_CLEAR_RAW(*np);
goto string_end;
}
}
#endif
return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING;
}
r = node_str_cat_char(*np, (UChar )tok->u.c);
if (r < 0) return r;
len++;
}
}
break;
case TK_CODE_POINT:
{
*np = node_new_empty();
CHECK_NULL_RETURN_MEMERR(*np);
r = node_str_cat_codepoint(*np, env->enc, tok->u.code);
if (r != 0) return r;
#ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG
NSTRING_SET_RAW(*np);
#else
goto string_loop;
#endif
}
break;
case TK_QUOTE_OPEN:
{
OnigCodePoint end_op[2];
UChar *qstart, *qend, *nextp;
end_op[0] = (OnigCodePoint )MC_ESC(env->syntax);
end_op[1] = (OnigCodePoint )'E';
qstart = *src;
qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc);
if (IS_NULL(qend)) {
nextp = qend = end;
}
*np = node_new_str(qstart, qend);
CHECK_NULL_RETURN_MEMERR(*np);
*src = nextp;
}
break;
case TK_CHAR_TYPE:
{
switch (tok->u.prop.ctype) {
case ONIGENC_CTYPE_WORD:
*np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not,
IS_ASCII_RANGE(env->option));
CHECK_NULL_RETURN_MEMERR(*np);
break;
case ONIGENC_CTYPE_SPACE:
case ONIGENC_CTYPE_DIGIT:
case ONIGENC_CTYPE_XDIGIT:
{
CClassNode* cc;
*np = node_new_cclass();
CHECK_NULL_RETURN_MEMERR(*np);
cc = NCCLASS(*np);
r = add_ctype_to_cc(cc, tok->u.prop.ctype, 0,
IS_ASCII_RANGE(env->option), env);
if (r != 0) return r;
if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc);
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
}
break;
case TK_CHAR_PROPERTY:
r = parse_char_property(np, tok, src, end, env);
if (r != 0) return r;
break;
case TK_CC_OPEN:
{
Node *asc_node;
CClassNode* cc;
OnigCodePoint code;
r = parse_char_class(np, &asc_node, tok, src, end, env);
if (r != 0) {
onig_node_free(asc_node);
return r;
}
cc = NCCLASS(*np);
if (is_onechar_cclass(cc, &code)) {
onig_node_free(*np);
onig_node_free(asc_node);
*np = node_new_empty();
CHECK_NULL_RETURN_MEMERR(*np);
r = node_str_cat_codepoint(*np, env->enc, code);
if (r != 0) return r;
goto string_loop;
}
if (IS_IGNORECASE(env->option)) {
r = cclass_case_fold(np, cc, NCCLASS(asc_node), env);
if (r != 0) {
onig_node_free(asc_node);
return r;
}
}
onig_node_free(asc_node);
}
break;
case TK_ANYCHAR:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
break;
case TK_ANYCHAR_ANYTIME:
*np = node_new_anychar();
CHECK_NULL_RETURN_MEMERR(*np);
qn = node_new_quantifier(0, REPEAT_INFINITE, 0);
CHECK_NULL_RETURN_MEMERR(qn);
NQTFR(qn)->target = *np;
*np = qn;
break;
case TK_BACKREF:
len = tok->u.backref.num;
*np = node_new_backref(len,
(len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)),
tok->u.backref.by_name,
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level,
tok->u.backref.level,
#endif
env);
CHECK_NULL_RETURN_MEMERR(*np);
break;
#ifdef USE_SUBEXP_CALL
case TK_CALL:
{
int gnum = tok->u.call.gnum;
if (gnum < 0 || tok->u.call.rel != 0) {
if (gnum > 0) gnum--;
gnum = BACKREF_REL_TO_ABS(gnum, env);
if (gnum <= 0)
return ONIGERR_INVALID_BACKREF;
}
*np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum);
CHECK_NULL_RETURN_MEMERR(*np);
env->num_call++;
}
break;
#endif
case TK_ANCHOR:
*np = onig_node_new_anchor(tok->u.anchor.subtype);
CHECK_NULL_RETURN_MEMERR(*np);
NANCHOR(*np)->ascii_range = tok->u.anchor.ascii_range;
break;
case TK_OP_REPEAT:
case TK_INTERVAL:
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED;
else
*np = node_new_empty();
}
else {
goto tk_byte;
}
break;
default:
return ONIGERR_PARSER_BUG;
break;
}
{
targetp = np;
re_entry:
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
repeat:
if (r == TK_OP_REPEAT || r == TK_INTERVAL) {
if (is_invalid_quantifier_target(*targetp))
return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID;
qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper,
(r == TK_INTERVAL ? 1 : 0));
CHECK_NULL_RETURN_MEMERR(qn);
NQTFR(qn)->greedy = tok->u.repeat.greedy;
r = set_quantifier(qn, *targetp, group, env);
if (r < 0) {
onig_node_free(qn);
return r;
}
if (tok->u.repeat.possessive != 0) {
Node* en;
en = node_new_enclose(ENCLOSE_STOP_BACKTRACK);
if (IS_NULL(en)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
NENCLOSE(en)->target = qn;
qn = en;
}
if (r == 0) {
*targetp = qn;
}
else if (r == 1) {
onig_node_free(qn);
}
else if (r == 2) { /* split case: /abc+/ */
Node *tmp;
*targetp = node_new_list(*targetp, NULL);
if (IS_NULL(*targetp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
tmp = NCDR(*targetp) = node_new_list(qn, NULL);
if (IS_NULL(tmp)) {
onig_node_free(qn);
return ONIGERR_MEMORY;
}
targetp = &(NCAR(tmp));
}
goto re_entry;
}
}
return r;
}
static int
parse_branch(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r;
Node *node, **headp;
*top = NULL;
r = parse_exp(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (r == TK_EOT || r == term || r == TK_ALT) {
*top = node;
}
else {
*top = node_new_list(node, NULL);
headp = &(NCDR(*top));
while (r != TK_EOT && r != term && r != TK_ALT) {
r = parse_exp(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (NTYPE(node) == NT_LIST) {
*headp = node;
while (IS_NOT_NULL(NCDR(node))) node = NCDR(node);
headp = &(NCDR(node));
}
else {
*headp = node_new_list(node, NULL);
headp = &(NCDR(*headp));
}
}
}
return r;
}
/* term_tok: TK_EOT or TK_SUBEXP_CLOSE */
static int
parse_subexp(Node** top, OnigToken* tok, int term,
UChar** src, UChar* end, ScanEnv* env)
{
int r;
Node *node, **headp;
*top = NULL;
env->parse_depth++;
if (env->parse_depth > ParseDepthLimit)
return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
if (r == term) {
*top = node;
}
else if (r == TK_ALT) {
*top = onig_node_new_alt(node, NULL);
headp = &(NCDR(*top));
while (r == TK_ALT) {
r = fetch_token(tok, src, end, env);
if (r < 0) return r;
r = parse_branch(&node, tok, term, src, end, env);
if (r < 0) {
onig_node_free(node);
return r;
}
*headp = onig_node_new_alt(node, NULL);
headp = &(NCDR(*headp));
}
if (tok->type != (enum TokenSyms )term)
goto err;
}
else {
onig_node_free(node);
err:
if (term == TK_SUBEXP_CLOSE)
return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS;
else
return ONIGERR_PARSER_BUG;
}
env->parse_depth--;
return r;
}
static int
parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env)
{
int r;
OnigToken tok;
r = fetch_token(&tok, src, end, env);
if (r < 0) return r;
r = parse_subexp(top, &tok, TK_EOT, src, end, env);
if (r < 0) return r;
#ifdef USE_SUBEXP_CALL
if (env->num_call > 0) {
/* Capture the pattern itself. It is used for (?R), (?0) and \g<0>. */
const int num = 0;
Node* np;
np = node_new_enclose_memory(env->option, 0);
CHECK_NULL_RETURN_MEMERR(np);
NENCLOSE(np)->regnum = num;
NENCLOSE(np)->target = *top;
r = scan_env_set_mem_node(env, num, np);
if (r != 0) {
onig_node_free(np);
return r;
}
*top = np;
}
#endif
return 0;
}
extern int
onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end,
regex_t* reg, ScanEnv* env)
{
int r;
UChar* p;
#ifdef USE_NAMED_GROUP
names_clear(reg);
#endif
scan_env_clear(env);
env->option = reg->options;
env->case_fold_flag = reg->case_fold_flag;
env->enc = reg->enc;
env->syntax = reg->syntax;
env->pattern = (UChar* )pattern;
env->pattern_end = (UChar* )end;
env->reg = reg;
*root = NULL;
p = (UChar* )pattern;
r = parse_regexp(root, &p, (UChar* )end, env);
reg->num_mem = env->num_mem;
return r;
}
extern void
onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED,
UChar* arg, UChar* arg_end)
{
env->error = arg;
env->error_end = arg_end;
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_1070_0 |
crossvul-cpp_data_bad_3370_0 | /*
* Symmetric key cipher operations.
*
* Generic encrypt/decrypt wrapper for ciphers, handles operations across
* multiple page boundaries by using temporary blocks. In user context,
* the kernel is given a chance to schedule us once per page.
*
* Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/internal/aead.h>
#include <crypto/internal/skcipher.h>
#include <crypto/scatterwalk.h>
#include <linux/bug.h>
#include <linux/cryptouser.h>
#include <linux/compiler.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <linux/seq_file.h>
#include <net/netlink.h>
#include "internal.h"
enum {
SKCIPHER_WALK_PHYS = 1 << 0,
SKCIPHER_WALK_SLOW = 1 << 1,
SKCIPHER_WALK_COPY = 1 << 2,
SKCIPHER_WALK_DIFF = 1 << 3,
SKCIPHER_WALK_SLEEP = 1 << 4,
};
struct skcipher_walk_buffer {
struct list_head entry;
struct scatter_walk dst;
unsigned int len;
u8 *data;
u8 buffer[];
};
static int skcipher_walk_next(struct skcipher_walk *walk);
static inline void skcipher_unmap(struct scatter_walk *walk, void *vaddr)
{
if (PageHighMem(scatterwalk_page(walk)))
kunmap_atomic(vaddr);
}
static inline void *skcipher_map(struct scatter_walk *walk)
{
struct page *page = scatterwalk_page(walk);
return (PageHighMem(page) ? kmap_atomic(page) : page_address(page)) +
offset_in_page(walk->offset);
}
static inline void skcipher_map_src(struct skcipher_walk *walk)
{
walk->src.virt.addr = skcipher_map(&walk->in);
}
static inline void skcipher_map_dst(struct skcipher_walk *walk)
{
walk->dst.virt.addr = skcipher_map(&walk->out);
}
static inline void skcipher_unmap_src(struct skcipher_walk *walk)
{
skcipher_unmap(&walk->in, walk->src.virt.addr);
}
static inline void skcipher_unmap_dst(struct skcipher_walk *walk)
{
skcipher_unmap(&walk->out, walk->dst.virt.addr);
}
static inline gfp_t skcipher_walk_gfp(struct skcipher_walk *walk)
{
return walk->flags & SKCIPHER_WALK_SLEEP ? GFP_KERNEL : GFP_ATOMIC;
}
/* Get a spot of the specified length that does not straddle a page.
* The caller needs to ensure that there is enough space for this operation.
*/
static inline u8 *skcipher_get_spot(u8 *start, unsigned int len)
{
u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK);
return max(start, end_page);
}
static int skcipher_done_slow(struct skcipher_walk *walk, unsigned int bsize)
{
u8 *addr;
addr = (u8 *)ALIGN((unsigned long)walk->buffer, walk->alignmask + 1);
addr = skcipher_get_spot(addr, bsize);
scatterwalk_copychunks(addr, &walk->out, bsize,
(walk->flags & SKCIPHER_WALK_PHYS) ? 2 : 1);
return 0;
}
int skcipher_walk_done(struct skcipher_walk *walk, int err)
{
unsigned int n = walk->nbytes - err;
unsigned int nbytes;
nbytes = walk->total - n;
if (unlikely(err < 0)) {
nbytes = 0;
n = 0;
} else if (likely(!(walk->flags & (SKCIPHER_WALK_PHYS |
SKCIPHER_WALK_SLOW |
SKCIPHER_WALK_COPY |
SKCIPHER_WALK_DIFF)))) {
unmap_src:
skcipher_unmap_src(walk);
} else if (walk->flags & SKCIPHER_WALK_DIFF) {
skcipher_unmap_dst(walk);
goto unmap_src;
} else if (walk->flags & SKCIPHER_WALK_COPY) {
skcipher_map_dst(walk);
memcpy(walk->dst.virt.addr, walk->page, n);
skcipher_unmap_dst(walk);
} else if (unlikely(walk->flags & SKCIPHER_WALK_SLOW)) {
if (WARN_ON(err)) {
err = -EINVAL;
nbytes = 0;
} else
n = skcipher_done_slow(walk, n);
}
if (err > 0)
err = 0;
walk->total = nbytes;
walk->nbytes = nbytes;
scatterwalk_advance(&walk->in, n);
scatterwalk_advance(&walk->out, n);
scatterwalk_done(&walk->in, 0, nbytes);
scatterwalk_done(&walk->out, 1, nbytes);
if (nbytes) {
crypto_yield(walk->flags & SKCIPHER_WALK_SLEEP ?
CRYPTO_TFM_REQ_MAY_SLEEP : 0);
return skcipher_walk_next(walk);
}
/* Short-circuit for the common/fast path. */
if (!((unsigned long)walk->buffer | (unsigned long)walk->page))
goto out;
if (walk->flags & SKCIPHER_WALK_PHYS)
goto out;
if (walk->iv != walk->oiv)
memcpy(walk->oiv, walk->iv, walk->ivsize);
if (walk->buffer != walk->page)
kfree(walk->buffer);
if (walk->page)
free_page((unsigned long)walk->page);
out:
return err;
}
EXPORT_SYMBOL_GPL(skcipher_walk_done);
void skcipher_walk_complete(struct skcipher_walk *walk, int err)
{
struct skcipher_walk_buffer *p, *tmp;
list_for_each_entry_safe(p, tmp, &walk->buffers, entry) {
u8 *data;
if (err)
goto done;
data = p->data;
if (!data) {
data = PTR_ALIGN(&p->buffer[0], walk->alignmask + 1);
data = skcipher_get_spot(data, walk->stride);
}
scatterwalk_copychunks(data, &p->dst, p->len, 1);
if (offset_in_page(p->data) + p->len + walk->stride >
PAGE_SIZE)
free_page((unsigned long)p->data);
done:
list_del(&p->entry);
kfree(p);
}
if (!err && walk->iv != walk->oiv)
memcpy(walk->oiv, walk->iv, walk->ivsize);
if (walk->buffer != walk->page)
kfree(walk->buffer);
if (walk->page)
free_page((unsigned long)walk->page);
}
EXPORT_SYMBOL_GPL(skcipher_walk_complete);
static void skcipher_queue_write(struct skcipher_walk *walk,
struct skcipher_walk_buffer *p)
{
p->dst = walk->out;
list_add_tail(&p->entry, &walk->buffers);
}
static int skcipher_next_slow(struct skcipher_walk *walk, unsigned int bsize)
{
bool phys = walk->flags & SKCIPHER_WALK_PHYS;
unsigned alignmask = walk->alignmask;
struct skcipher_walk_buffer *p;
unsigned a;
unsigned n;
u8 *buffer;
void *v;
if (!phys) {
if (!walk->buffer)
walk->buffer = walk->page;
buffer = walk->buffer;
if (buffer)
goto ok;
}
/* Start with the minimum alignment of kmalloc. */
a = crypto_tfm_ctx_alignment() - 1;
n = bsize;
if (phys) {
/* Calculate the minimum alignment of p->buffer. */
a &= (sizeof(*p) ^ (sizeof(*p) - 1)) >> 1;
n += sizeof(*p);
}
/* Minimum size to align p->buffer by alignmask. */
n += alignmask & ~a;
/* Minimum size to ensure p->buffer does not straddle a page. */
n += (bsize - 1) & ~(alignmask | a);
v = kzalloc(n, skcipher_walk_gfp(walk));
if (!v)
return skcipher_walk_done(walk, -ENOMEM);
if (phys) {
p = v;
p->len = bsize;
skcipher_queue_write(walk, p);
buffer = p->buffer;
} else {
walk->buffer = v;
buffer = v;
}
ok:
walk->dst.virt.addr = PTR_ALIGN(buffer, alignmask + 1);
walk->dst.virt.addr = skcipher_get_spot(walk->dst.virt.addr, bsize);
walk->src.virt.addr = walk->dst.virt.addr;
scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0);
walk->nbytes = bsize;
walk->flags |= SKCIPHER_WALK_SLOW;
return 0;
}
static int skcipher_next_copy(struct skcipher_walk *walk)
{
struct skcipher_walk_buffer *p;
u8 *tmp = walk->page;
skcipher_map_src(walk);
memcpy(tmp, walk->src.virt.addr, walk->nbytes);
skcipher_unmap_src(walk);
walk->src.virt.addr = tmp;
walk->dst.virt.addr = tmp;
if (!(walk->flags & SKCIPHER_WALK_PHYS))
return 0;
p = kmalloc(sizeof(*p), skcipher_walk_gfp(walk));
if (!p)
return -ENOMEM;
p->data = walk->page;
p->len = walk->nbytes;
skcipher_queue_write(walk, p);
if (offset_in_page(walk->page) + walk->nbytes + walk->stride >
PAGE_SIZE)
walk->page = NULL;
else
walk->page += walk->nbytes;
return 0;
}
static int skcipher_next_fast(struct skcipher_walk *walk)
{
unsigned long diff;
walk->src.phys.page = scatterwalk_page(&walk->in);
walk->src.phys.offset = offset_in_page(walk->in.offset);
walk->dst.phys.page = scatterwalk_page(&walk->out);
walk->dst.phys.offset = offset_in_page(walk->out.offset);
if (walk->flags & SKCIPHER_WALK_PHYS)
return 0;
diff = walk->src.phys.offset - walk->dst.phys.offset;
diff |= walk->src.virt.page - walk->dst.virt.page;
skcipher_map_src(walk);
walk->dst.virt.addr = walk->src.virt.addr;
if (diff) {
walk->flags |= SKCIPHER_WALK_DIFF;
skcipher_map_dst(walk);
}
return 0;
}
static int skcipher_walk_next(struct skcipher_walk *walk)
{
unsigned int bsize;
unsigned int n;
int err;
walk->flags &= ~(SKCIPHER_WALK_SLOW | SKCIPHER_WALK_COPY |
SKCIPHER_WALK_DIFF);
n = walk->total;
bsize = min(walk->stride, max(n, walk->blocksize));
n = scatterwalk_clamp(&walk->in, n);
n = scatterwalk_clamp(&walk->out, n);
if (unlikely(n < bsize)) {
if (unlikely(walk->total < walk->blocksize))
return skcipher_walk_done(walk, -EINVAL);
slow_path:
err = skcipher_next_slow(walk, bsize);
goto set_phys_lowmem;
}
if (unlikely((walk->in.offset | walk->out.offset) & walk->alignmask)) {
if (!walk->page) {
gfp_t gfp = skcipher_walk_gfp(walk);
walk->page = (void *)__get_free_page(gfp);
if (!walk->page)
goto slow_path;
}
walk->nbytes = min_t(unsigned, n,
PAGE_SIZE - offset_in_page(walk->page));
walk->flags |= SKCIPHER_WALK_COPY;
err = skcipher_next_copy(walk);
goto set_phys_lowmem;
}
walk->nbytes = n;
return skcipher_next_fast(walk);
set_phys_lowmem:
if (!err && (walk->flags & SKCIPHER_WALK_PHYS)) {
walk->src.phys.page = virt_to_page(walk->src.virt.addr);
walk->dst.phys.page = virt_to_page(walk->dst.virt.addr);
walk->src.phys.offset &= PAGE_SIZE - 1;
walk->dst.phys.offset &= PAGE_SIZE - 1;
}
return err;
}
EXPORT_SYMBOL_GPL(skcipher_walk_next);
static int skcipher_copy_iv(struct skcipher_walk *walk)
{
unsigned a = crypto_tfm_ctx_alignment() - 1;
unsigned alignmask = walk->alignmask;
unsigned ivsize = walk->ivsize;
unsigned bs = walk->stride;
unsigned aligned_bs;
unsigned size;
u8 *iv;
aligned_bs = ALIGN(bs, alignmask);
/* Minimum size to align buffer by alignmask. */
size = alignmask & ~a;
if (walk->flags & SKCIPHER_WALK_PHYS)
size += ivsize;
else {
size += aligned_bs + ivsize;
/* Minimum size to ensure buffer does not straddle a page. */
size += (bs - 1) & ~(alignmask | a);
}
walk->buffer = kmalloc(size, skcipher_walk_gfp(walk));
if (!walk->buffer)
return -ENOMEM;
iv = PTR_ALIGN(walk->buffer, alignmask + 1);
iv = skcipher_get_spot(iv, bs) + aligned_bs;
walk->iv = memcpy(iv, walk->iv, walk->ivsize);
return 0;
}
static int skcipher_walk_first(struct skcipher_walk *walk)
{
walk->nbytes = 0;
if (WARN_ON_ONCE(in_irq()))
return -EDEADLK;
if (unlikely(!walk->total))
return 0;
walk->buffer = NULL;
if (unlikely(((unsigned long)walk->iv & walk->alignmask))) {
int err = skcipher_copy_iv(walk);
if (err)
return err;
}
walk->page = NULL;
walk->nbytes = walk->total;
return skcipher_walk_next(walk);
}
static int skcipher_walk_skcipher(struct skcipher_walk *walk,
struct skcipher_request *req)
{
struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
scatterwalk_start(&walk->in, req->src);
scatterwalk_start(&walk->out, req->dst);
walk->total = req->cryptlen;
walk->iv = req->iv;
walk->oiv = req->iv;
walk->flags &= ~SKCIPHER_WALK_SLEEP;
walk->flags |= req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP ?
SKCIPHER_WALK_SLEEP : 0;
walk->blocksize = crypto_skcipher_blocksize(tfm);
walk->stride = crypto_skcipher_walksize(tfm);
walk->ivsize = crypto_skcipher_ivsize(tfm);
walk->alignmask = crypto_skcipher_alignmask(tfm);
return skcipher_walk_first(walk);
}
int skcipher_walk_virt(struct skcipher_walk *walk,
struct skcipher_request *req, bool atomic)
{
int err;
walk->flags &= ~SKCIPHER_WALK_PHYS;
err = skcipher_walk_skcipher(walk, req);
walk->flags &= atomic ? ~SKCIPHER_WALK_SLEEP : ~0;
return err;
}
EXPORT_SYMBOL_GPL(skcipher_walk_virt);
void skcipher_walk_atomise(struct skcipher_walk *walk)
{
walk->flags &= ~SKCIPHER_WALK_SLEEP;
}
EXPORT_SYMBOL_GPL(skcipher_walk_atomise);
int skcipher_walk_async(struct skcipher_walk *walk,
struct skcipher_request *req)
{
walk->flags |= SKCIPHER_WALK_PHYS;
INIT_LIST_HEAD(&walk->buffers);
return skcipher_walk_skcipher(walk, req);
}
EXPORT_SYMBOL_GPL(skcipher_walk_async);
static int skcipher_walk_aead_common(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
int err;
walk->flags &= ~SKCIPHER_WALK_PHYS;
scatterwalk_start(&walk->in, req->src);
scatterwalk_start(&walk->out, req->dst);
scatterwalk_copychunks(NULL, &walk->in, req->assoclen, 2);
scatterwalk_copychunks(NULL, &walk->out, req->assoclen, 2);
walk->iv = req->iv;
walk->oiv = req->iv;
if (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP)
walk->flags |= SKCIPHER_WALK_SLEEP;
else
walk->flags &= ~SKCIPHER_WALK_SLEEP;
walk->blocksize = crypto_aead_blocksize(tfm);
walk->stride = crypto_aead_chunksize(tfm);
walk->ivsize = crypto_aead_ivsize(tfm);
walk->alignmask = crypto_aead_alignmask(tfm);
err = skcipher_walk_first(walk);
if (atomic)
walk->flags &= ~SKCIPHER_WALK_SLEEP;
return err;
}
int skcipher_walk_aead(struct skcipher_walk *walk, struct aead_request *req,
bool atomic)
{
walk->total = req->cryptlen;
return skcipher_walk_aead_common(walk, req, atomic);
}
EXPORT_SYMBOL_GPL(skcipher_walk_aead);
int skcipher_walk_aead_encrypt(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
walk->total = req->cryptlen;
return skcipher_walk_aead_common(walk, req, atomic);
}
EXPORT_SYMBOL_GPL(skcipher_walk_aead_encrypt);
int skcipher_walk_aead_decrypt(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
struct crypto_aead *tfm = crypto_aead_reqtfm(req);
walk->total = req->cryptlen - crypto_aead_authsize(tfm);
return skcipher_walk_aead_common(walk, req, atomic);
}
EXPORT_SYMBOL_GPL(skcipher_walk_aead_decrypt);
static unsigned int crypto_skcipher_extsize(struct crypto_alg *alg)
{
if (alg->cra_type == &crypto_blkcipher_type)
return sizeof(struct crypto_blkcipher *);
if (alg->cra_type == &crypto_ablkcipher_type ||
alg->cra_type == &crypto_givcipher_type)
return sizeof(struct crypto_ablkcipher *);
return crypto_alg_extsize(alg);
}
static int skcipher_setkey_blkcipher(struct crypto_skcipher *tfm,
const u8 *key, unsigned int keylen)
{
struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm);
struct crypto_blkcipher *blkcipher = *ctx;
int err;
crypto_blkcipher_clear_flags(blkcipher, ~0);
crypto_blkcipher_set_flags(blkcipher, crypto_skcipher_get_flags(tfm) &
CRYPTO_TFM_REQ_MASK);
err = crypto_blkcipher_setkey(blkcipher, key, keylen);
crypto_skcipher_set_flags(tfm, crypto_blkcipher_get_flags(blkcipher) &
CRYPTO_TFM_RES_MASK);
return err;
}
static int skcipher_crypt_blkcipher(struct skcipher_request *req,
int (*crypt)(struct blkcipher_desc *,
struct scatterlist *,
struct scatterlist *,
unsigned int))
{
struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm);
struct blkcipher_desc desc = {
.tfm = *ctx,
.info = req->iv,
.flags = req->base.flags,
};
return crypt(&desc, req->dst, req->src, req->cryptlen);
}
static int skcipher_encrypt_blkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
return skcipher_crypt_blkcipher(req, alg->encrypt);
}
static int skcipher_decrypt_blkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
return skcipher_crypt_blkcipher(req, alg->decrypt);
}
static void crypto_exit_skcipher_ops_blkcipher(struct crypto_tfm *tfm)
{
struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm);
crypto_free_blkcipher(*ctx);
}
static int crypto_init_skcipher_ops_blkcipher(struct crypto_tfm *tfm)
{
struct crypto_alg *calg = tfm->__crt_alg;
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm);
struct crypto_blkcipher *blkcipher;
struct crypto_tfm *btfm;
if (!crypto_mod_get(calg))
return -EAGAIN;
btfm = __crypto_alloc_tfm(calg, CRYPTO_ALG_TYPE_BLKCIPHER,
CRYPTO_ALG_TYPE_MASK);
if (IS_ERR(btfm)) {
crypto_mod_put(calg);
return PTR_ERR(btfm);
}
blkcipher = __crypto_blkcipher_cast(btfm);
*ctx = blkcipher;
tfm->exit = crypto_exit_skcipher_ops_blkcipher;
skcipher->setkey = skcipher_setkey_blkcipher;
skcipher->encrypt = skcipher_encrypt_blkcipher;
skcipher->decrypt = skcipher_decrypt_blkcipher;
skcipher->ivsize = crypto_blkcipher_ivsize(blkcipher);
skcipher->keysize = calg->cra_blkcipher.max_keysize;
return 0;
}
static int skcipher_setkey_ablkcipher(struct crypto_skcipher *tfm,
const u8 *key, unsigned int keylen)
{
struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm);
struct crypto_ablkcipher *ablkcipher = *ctx;
int err;
crypto_ablkcipher_clear_flags(ablkcipher, ~0);
crypto_ablkcipher_set_flags(ablkcipher,
crypto_skcipher_get_flags(tfm) &
CRYPTO_TFM_REQ_MASK);
err = crypto_ablkcipher_setkey(ablkcipher, key, keylen);
crypto_skcipher_set_flags(tfm,
crypto_ablkcipher_get_flags(ablkcipher) &
CRYPTO_TFM_RES_MASK);
return err;
}
static int skcipher_crypt_ablkcipher(struct skcipher_request *req,
int (*crypt)(struct ablkcipher_request *))
{
struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm);
struct ablkcipher_request *subreq = skcipher_request_ctx(req);
ablkcipher_request_set_tfm(subreq, *ctx);
ablkcipher_request_set_callback(subreq, skcipher_request_flags(req),
req->base.complete, req->base.data);
ablkcipher_request_set_crypt(subreq, req->src, req->dst, req->cryptlen,
req->iv);
return crypt(subreq);
}
static int skcipher_encrypt_ablkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher;
return skcipher_crypt_ablkcipher(req, alg->encrypt);
}
static int skcipher_decrypt_ablkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher;
return skcipher_crypt_ablkcipher(req, alg->decrypt);
}
static void crypto_exit_skcipher_ops_ablkcipher(struct crypto_tfm *tfm)
{
struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm);
crypto_free_ablkcipher(*ctx);
}
static int crypto_init_skcipher_ops_ablkcipher(struct crypto_tfm *tfm)
{
struct crypto_alg *calg = tfm->__crt_alg;
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm);
struct crypto_ablkcipher *ablkcipher;
struct crypto_tfm *abtfm;
if (!crypto_mod_get(calg))
return -EAGAIN;
abtfm = __crypto_alloc_tfm(calg, 0, 0);
if (IS_ERR(abtfm)) {
crypto_mod_put(calg);
return PTR_ERR(abtfm);
}
ablkcipher = __crypto_ablkcipher_cast(abtfm);
*ctx = ablkcipher;
tfm->exit = crypto_exit_skcipher_ops_ablkcipher;
skcipher->setkey = skcipher_setkey_ablkcipher;
skcipher->encrypt = skcipher_encrypt_ablkcipher;
skcipher->decrypt = skcipher_decrypt_ablkcipher;
skcipher->ivsize = crypto_ablkcipher_ivsize(ablkcipher);
skcipher->reqsize = crypto_ablkcipher_reqsize(ablkcipher) +
sizeof(struct ablkcipher_request);
skcipher->keysize = calg->cra_ablkcipher.max_keysize;
return 0;
}
static void crypto_skcipher_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
alg->exit(skcipher);
}
static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = alg->setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
}
static void crypto_skcipher_free_instance(struct crypto_instance *inst)
{
struct skcipher_instance *skcipher =
container_of(inst, struct skcipher_instance, s.base);
skcipher->free(skcipher);
}
static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg)
__maybe_unused;
static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg)
{
struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg,
base);
seq_printf(m, "type : skcipher\n");
seq_printf(m, "async : %s\n",
alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no");
seq_printf(m, "blocksize : %u\n", alg->cra_blocksize);
seq_printf(m, "min keysize : %u\n", skcipher->min_keysize);
seq_printf(m, "max keysize : %u\n", skcipher->max_keysize);
seq_printf(m, "ivsize : %u\n", skcipher->ivsize);
seq_printf(m, "chunksize : %u\n", skcipher->chunksize);
seq_printf(m, "walksize : %u\n", skcipher->walksize);
}
#ifdef CONFIG_NET
static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg,
base);
strncpy(rblkcipher.type, "skcipher", sizeof(rblkcipher.type));
strncpy(rblkcipher.geniv, "<none>", sizeof(rblkcipher.geniv));
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = skcipher->min_keysize;
rblkcipher.max_keysize = skcipher->max_keysize;
rblkcipher.ivsize = skcipher->ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
#else
static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
return -ENOSYS;
}
#endif
static const struct crypto_type crypto_skcipher_type2 = {
.extsize = crypto_skcipher_extsize,
.init_tfm = crypto_skcipher_init_tfm,
.free = crypto_skcipher_free_instance,
#ifdef CONFIG_PROC_FS
.show = crypto_skcipher_show,
#endif
.report = crypto_skcipher_report,
.maskclear = ~CRYPTO_ALG_TYPE_MASK,
.maskset = CRYPTO_ALG_TYPE_BLKCIPHER_MASK,
.type = CRYPTO_ALG_TYPE_SKCIPHER,
.tfmsize = offsetof(struct crypto_skcipher, base),
};
int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn,
const char *name, u32 type, u32 mask)
{
spawn->base.frontend = &crypto_skcipher_type2;
return crypto_grab_spawn(&spawn->base, name, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_grab_skcipher);
struct crypto_skcipher *crypto_alloc_skcipher(const char *alg_name,
u32 type, u32 mask)
{
return crypto_alloc_tfm(alg_name, &crypto_skcipher_type2, type, mask);
}
EXPORT_SYMBOL_GPL(crypto_alloc_skcipher);
int crypto_has_skcipher2(const char *alg_name, u32 type, u32 mask)
{
return crypto_type_has_alg(alg_name, &crypto_skcipher_type2,
type, mask);
}
EXPORT_SYMBOL_GPL(crypto_has_skcipher2);
static int skcipher_prepare_alg(struct skcipher_alg *alg)
{
struct crypto_alg *base = &alg->base;
if (alg->ivsize > PAGE_SIZE / 8 || alg->chunksize > PAGE_SIZE / 8 ||
alg->walksize > PAGE_SIZE / 8)
return -EINVAL;
if (!alg->chunksize)
alg->chunksize = base->cra_blocksize;
if (!alg->walksize)
alg->walksize = alg->chunksize;
base->cra_type = &crypto_skcipher_type2;
base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK;
base->cra_flags |= CRYPTO_ALG_TYPE_SKCIPHER;
return 0;
}
int crypto_register_skcipher(struct skcipher_alg *alg)
{
struct crypto_alg *base = &alg->base;
int err;
err = skcipher_prepare_alg(alg);
if (err)
return err;
return crypto_register_alg(base);
}
EXPORT_SYMBOL_GPL(crypto_register_skcipher);
void crypto_unregister_skcipher(struct skcipher_alg *alg)
{
crypto_unregister_alg(&alg->base);
}
EXPORT_SYMBOL_GPL(crypto_unregister_skcipher);
int crypto_register_skciphers(struct skcipher_alg *algs, int count)
{
int i, ret;
for (i = 0; i < count; i++) {
ret = crypto_register_skcipher(&algs[i]);
if (ret)
goto err;
}
return 0;
err:
for (--i; i >= 0; --i)
crypto_unregister_skcipher(&algs[i]);
return ret;
}
EXPORT_SYMBOL_GPL(crypto_register_skciphers);
void crypto_unregister_skciphers(struct skcipher_alg *algs, int count)
{
int i;
for (i = count - 1; i >= 0; --i)
crypto_unregister_skcipher(&algs[i]);
}
EXPORT_SYMBOL_GPL(crypto_unregister_skciphers);
int skcipher_register_instance(struct crypto_template *tmpl,
struct skcipher_instance *inst)
{
int err;
err = skcipher_prepare_alg(&inst->alg);
if (err)
return err;
return crypto_register_instance(tmpl, skcipher_crypto_instance(inst));
}
EXPORT_SYMBOL_GPL(skcipher_register_instance);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Symmetric key cipher type");
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3370_0 |
crossvul-cpp_data_good_4809_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "common.h"
#include "git2/types.h"
#include "git2/errors.h"
#include "git2/refs.h"
#include "git2/revwalk.h"
#include "smart.h"
#include "util.h"
#include "netops.h"
#include "posix.h"
#include "buffer.h"
#include <ctype.h>
#define PKT_LEN_SIZE 4
static const char pkt_done_str[] = "0009done\n";
static const char pkt_flush_str[] = "0000";
static const char pkt_have_prefix[] = "0032have ";
static const char pkt_want_prefix[] = "0032want ";
static int flush_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_FLUSH;
*out = pkt;
return 0;
}
/* the rest of the line will be useful for multi_ack and multi_ack_detailed */
static int ack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ack *pkt;
GIT_UNUSED(line);
GIT_UNUSED(len);
pkt = git__calloc(1, sizeof(git_pkt_ack));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ACK;
line += 3;
len -= 3;
if (len >= GIT_OID_HEXSZ) {
git_oid_fromstr(&pkt->oid, line + 1);
line += GIT_OID_HEXSZ + 1;
len -= GIT_OID_HEXSZ + 1;
}
if (len >= 7) {
if (!git__prefixcmp(line + 1, "continue"))
pkt->status = GIT_ACK_CONTINUE;
if (!git__prefixcmp(line + 1, "common"))
pkt->status = GIT_ACK_COMMON;
if (!git__prefixcmp(line + 1, "ready"))
pkt->status = GIT_ACK_READY;
}
*out = (git_pkt *) pkt;
return 0;
}
static int nak_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_NAK;
*out = pkt;
return 0;
}
static int pack_pkt(git_pkt **out)
{
git_pkt *pkt;
pkt = git__malloc(sizeof(git_pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PACK;
*out = pkt;
return 0;
}
static int comment_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_comment *pkt;
size_t alloclen;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_comment), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_COMMENT;
memcpy(pkt->comment, line, len);
pkt->comment[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int err_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloclen;
/* Remove "ERR " from the line */
line += 4;
len -= 4;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *) pkt;
return 0;
}
static int data_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_data *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_DATA;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_progress *pkt;
size_t alloclen;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len);
pkt = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_PROGRESS;
pkt->len = (int) len;
memcpy(pkt->data, line, len);
*out = (git_pkt *) pkt;
return 0;
}
static int sideband_error_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_err *pkt;
size_t alloc_len;
line++;
len--;
GITERR_CHECK_ALLOC_ADD(&alloc_len, sizeof(git_pkt_err), len);
GITERR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1);
pkt = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_ERR;
pkt->len = (int)len;
memcpy(pkt->error, line, len);
pkt->error[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
/*
* Parse an other-ref line.
*/
static int ref_pkt(git_pkt **out, const char *line, size_t len)
{
int error;
git_pkt_ref *pkt;
size_t alloclen;
pkt = git__malloc(sizeof(git_pkt_ref));
GITERR_CHECK_ALLOC(pkt);
memset(pkt, 0x0, sizeof(git_pkt_ref));
pkt->type = GIT_PKT_REF;
if ((error = git_oid_fromstr(&pkt->head.oid, line)) < 0)
goto error_out;
/* Check for a bit of consistency */
if (line[GIT_OID_HEXSZ] != ' ') {
giterr_set(GITERR_NET, "Error parsing pkt-line");
error = -1;
goto error_out;
}
/* Jump from the name */
line += GIT_OID_HEXSZ + 1;
len -= (GIT_OID_HEXSZ + 1);
if (line[len - 1] == '\n')
--len;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->head.name = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->head.name);
memcpy(pkt->head.name, line, len);
pkt->head.name[len] = '\0';
if (strlen(pkt->head.name) < len) {
pkt->capabilities = strchr(pkt->head.name, '\0') + 1;
}
*out = (git_pkt *)pkt;
return 0;
error_out:
git__free(pkt);
return error;
}
static int ok_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ok *pkt;
const char *ptr;
size_t alloc_len;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_OK;
line += 3; /* skip "ok " */
if (!(ptr = strchr(line, '\n'))) {
giterr_set(GITERR_NET, "Invalid packet line");
git__free(pkt);
return -1;
}
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
pkt->ref = git__malloc(alloc_len);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
}
static int ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
line += 3; /* skip "ng " */
if (!(ptr = strchr(line, ' ')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
line = ptr + 1;
if (!(ptr = strchr(line, '\n')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "Invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
static int unpack_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_unpack *pkt;
GIT_UNUSED(len);
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->type = GIT_PKT_UNPACK;
if (!git__prefixcmp(line, "unpack ok"))
pkt->unpack_ok = 1;
else
pkt->unpack_ok = 0;
*out = (git_pkt *)pkt;
return 0;
}
static int32_t parse_len(const char *line)
{
char num[PKT_LEN_SIZE + 1];
int i, k, error;
int32_t len;
const char *num_end;
memcpy(num, line, PKT_LEN_SIZE);
num[PKT_LEN_SIZE] = '\0';
for (i = 0; i < PKT_LEN_SIZE; ++i) {
if (!isxdigit(num[i])) {
/* Make sure there are no special characters before passing to error message */
for (k = 0; k < PKT_LEN_SIZE; ++k) {
if(!isprint(num[k])) {
num[k] = '.';
}
}
giterr_set(GITERR_NET, "invalid hex digit in length: '%s'", num);
return -1;
}
}
if ((error = git__strtol32(&len, num, &num_end, 16)) < 0)
return error;
return len;
}
/*
* As per the documentation, the syntax is:
*
* pkt-line = data-pkt / flush-pkt
* data-pkt = pkt-len pkt-payload
* pkt-len = 4*(HEXDIG)
* pkt-payload = (pkt-len -4)*(OCTET)
* flush-pkt = "0000"
*
* Which means that the first four bytes are the length of the line,
* in ASCII hexadecimal (including itself)
*/
int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* The Git protocol does not specify empty lines as part
* of the protocol. Not knowing what to do with an empty
* line, we should return an error upon hitting one.
*/
if (len == PKT_LEN_SIZE) {
giterr_set_str(GITERR_NET, "Invalid empty packet");
return GIT_ERROR;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
void git_pkt_free(git_pkt *pkt)
{
if (pkt->type == GIT_PKT_REF) {
git_pkt_ref *p = (git_pkt_ref *) pkt;
git__free(p->head.name);
git__free(p->head.symref_target);
}
if (pkt->type == GIT_PKT_OK) {
git_pkt_ok *p = (git_pkt_ok *) pkt;
git__free(p->ref);
}
if (pkt->type == GIT_PKT_NG) {
git_pkt_ng *p = (git_pkt_ng *) pkt;
git__free(p->ref);
git__free(p->msg);
}
git__free(pkt);
}
int git_pkt_buffer_flush(git_buf *buf)
{
return git_buf_put(buf, pkt_flush_str, strlen(pkt_flush_str));
}
static int buffer_want_with_caps(const git_remote_head *head, transport_smart_caps *caps, git_buf *buf)
{
git_buf str = GIT_BUF_INIT;
char oid[GIT_OID_HEXSZ +1] = {0};
size_t len;
/* Prefer multi_ack_detailed */
if (caps->multi_ack_detailed)
git_buf_puts(&str, GIT_CAP_MULTI_ACK_DETAILED " ");
else if (caps->multi_ack)
git_buf_puts(&str, GIT_CAP_MULTI_ACK " ");
/* Prefer side-band-64k if the server supports both */
if (caps->side_band_64k)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND_64K);
else if (caps->side_band)
git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND);
if (caps->include_tag)
git_buf_puts(&str, GIT_CAP_INCLUDE_TAG " ");
if (caps->thin_pack)
git_buf_puts(&str, GIT_CAP_THIN_PACK " ");
if (caps->ofs_delta)
git_buf_puts(&str, GIT_CAP_OFS_DELTA " ");
if (git_buf_oom(&str))
return -1;
len = strlen("XXXXwant ") + GIT_OID_HEXSZ + 1 /* NUL */ +
git_buf_len(&str) + 1 /* LF */;
if (len > 0xffff) {
giterr_set(GITERR_NET,
"Tried to produce packet with invalid length %" PRIuZ, len);
return -1;
}
git_buf_grow_by(buf, len);
git_oid_fmt(oid, &head->oid);
git_buf_printf(buf,
"%04xwant %s %s\n", (unsigned int)len, oid, git_buf_cstr(&str));
git_buf_free(&str);
GITERR_CHECK_ALLOC_BUF(buf);
return 0;
}
/*
* All "want" packets have the same length and format, so what we do
* is overwrite the OID each time.
*/
int git_pkt_buffer_wants(
const git_remote_head * const *refs,
size_t count,
transport_smart_caps *caps,
git_buf *buf)
{
size_t i = 0;
const git_remote_head *head;
if (caps->common) {
for (; i < count; ++i) {
head = refs[i];
if (!head->local)
break;
}
if (buffer_want_with_caps(refs[i], caps, buf) < 0)
return -1;
i++;
}
for (; i < count; ++i) {
char oid[GIT_OID_HEXSZ];
head = refs[i];
if (head->local)
continue;
git_oid_fmt(oid, &head->oid);
git_buf_put(buf, pkt_want_prefix, strlen(pkt_want_prefix));
git_buf_put(buf, oid, GIT_OID_HEXSZ);
git_buf_putc(buf, '\n');
if (git_buf_oom(buf))
return -1;
}
return git_pkt_buffer_flush(buf);
}
int git_pkt_buffer_have(git_oid *oid, git_buf *buf)
{
char oidhex[GIT_OID_HEXSZ + 1];
memset(oidhex, 0x0, sizeof(oidhex));
git_oid_fmt(oidhex, oid);
return git_buf_printf(buf, "%s%s\n", pkt_have_prefix, oidhex);
}
int git_pkt_buffer_done(git_buf *buf)
{
return git_buf_puts(buf, pkt_done_str);
}
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_4809_0 |
crossvul-cpp_data_good_3380_0 | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ecma-alloc.h"
#include "ecma-helpers.h"
#include "ecma-function-object.h"
#include "ecma-literal-storage.h"
#include "js-parser-internal.h"
#include "lit-char-helpers.h"
#if JERRY_JS_PARSER
/** \addtogroup parser Parser
* @{
*
* \addtogroup jsparser JavaScript
* @{
*
* \addtogroup jsparser_lexer Lexer
* @{
*/
#define IS_UTF8_INTERMEDIATE_OCTET(byte) (((byte) & LIT_UTF8_EXTRA_BYTE_MASK) == LIT_UTF8_2_BYTE_CODE_POINT_MIN)
/**
* Align column to the next tab position.
*
* @return aligned position
*/
static parser_line_counter_t
align_column_to_tab (parser_line_counter_t column) /**< current column */
{
/* Tab aligns to zero column start position. */
return (parser_line_counter_t) (((column + (8u - 1u)) & ~ECMA_STRING_CONTAINER_MASK) + 1u);
} /* align_column_to_tab */
/**
* Parse hexadecimal character sequence
*
* @return character value
*/
ecma_char_t
lexer_hex_to_character (parser_context_t *context_p, /**< context */
const uint8_t *source_p, /**< current source position */
int length) /**< source length */
{
uint32_t result = 0;
do
{
uint32_t byte = *source_p++;
result <<= 4;
if (byte >= LIT_CHAR_0 && byte <= LIT_CHAR_9)
{
result += byte - LIT_CHAR_0;
}
else
{
byte = LEXER_TO_ASCII_LOWERCASE (byte);
if (byte >= LIT_CHAR_LOWERCASE_A && byte <= LIT_CHAR_LOWERCASE_F)
{
result += byte - (LIT_CHAR_LOWERCASE_A - 10);
}
else
{
parser_raise_error (context_p, PARSER_ERR_INVALID_ESCAPE_SEQUENCE);
}
}
}
while (--length > 0);
return (ecma_char_t) result;
} /* lexer_hex_to_character */
/**
* Skip space mode
*/
typedef enum
{
LEXER_SKIP_SPACES, /**< skip spaces mode */
LEXER_SKIP_SINGLE_LINE_COMMENT, /**< parse single line comment */
LEXER_SKIP_MULTI_LINE_COMMENT, /**< parse multi line comment */
} skip_mode_t;
/**
* Skip spaces.
*/
static void
skip_spaces (parser_context_t *context_p) /**< context */
{
skip_mode_t mode = LEXER_SKIP_SPACES;
const uint8_t *source_end_p = context_p->source_end_p;
context_p->token.was_newline = 0;
while (true)
{
if (context_p->source_p >= source_end_p)
{
if (mode == LEXER_SKIP_MULTI_LINE_COMMENT)
{
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_MULTILINE_COMMENT);
}
return;
}
switch (context_p->source_p[0])
{
case LIT_CHAR_CR:
{
if (context_p->source_p + 1 < source_end_p
&& context_p->source_p[1] == LIT_CHAR_LF)
{
context_p->source_p++;
}
/* FALLTHRU */
}
case LIT_CHAR_LF:
{
context_p->line++;
context_p->column = 0;
context_p->token.was_newline = 1;
if (mode == LEXER_SKIP_SINGLE_LINE_COMMENT)
{
mode = LEXER_SKIP_SPACES;
}
/* FALLTHRU */
}
case LIT_CHAR_VTAB:
case LIT_CHAR_FF:
case LIT_CHAR_SP:
{
context_p->source_p++;
context_p->column++;
continue;
}
case LIT_CHAR_TAB:
{
context_p->column = align_column_to_tab (context_p->column);
context_p->source_p++;
continue;
}
case LIT_CHAR_SLASH:
{
if (mode == LEXER_SKIP_SPACES
&& context_p->source_p + 1 < source_end_p)
{
if (context_p->source_p[1] == LIT_CHAR_SLASH)
{
mode = LEXER_SKIP_SINGLE_LINE_COMMENT;
}
else if (context_p->source_p[1] == LIT_CHAR_ASTERISK)
{
mode = LEXER_SKIP_MULTI_LINE_COMMENT;
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
}
if (mode != LEXER_SKIP_SPACES)
{
context_p->source_p += 2;
PARSER_PLUS_EQUAL_LC (context_p->column, 2);
continue;
}
}
break;
}
case LIT_CHAR_ASTERISK:
{
if (mode == LEXER_SKIP_MULTI_LINE_COMMENT
&& context_p->source_p + 1 < source_end_p
&& context_p->source_p[1] == LIT_CHAR_SLASH)
{
mode = LEXER_SKIP_SPACES;
context_p->source_p += 2;
PARSER_PLUS_EQUAL_LC (context_p->column, 2);
continue;
}
break;
}
case 0xc2:
{
if (context_p->source_p + 1 < source_end_p
&& context_p->source_p[1] == 0xa0)
{
/* Codepoint \u00A0 */
context_p->source_p += 2;
context_p->column++;
continue;
}
break;
}
case LEXER_NEWLINE_LS_PS_BYTE_1:
{
JERRY_ASSERT (context_p->source_p + 2 < source_end_p);
if (LEXER_NEWLINE_LS_PS_BYTE_23 (context_p->source_p))
{
/* Codepoint \u2028 and \u2029 */
context_p->source_p += 3;
context_p->line++;
context_p->column = 1;
context_p->token.was_newline = 1;
if (mode == LEXER_SKIP_SINGLE_LINE_COMMENT)
{
mode = LEXER_SKIP_SPACES;
}
continue;
}
break;
}
case 0xef:
{
if (context_p->source_p + 2 < source_end_p
&& context_p->source_p[1] == 0xbb
&& context_p->source_p[2] == 0xbf)
{
/* Codepoint \uFEFF */
context_p->source_p += 3;
context_p->column++;
continue;
}
break;
}
default:
{
break;
}
}
if (mode == LEXER_SKIP_SPACES)
{
return;
}
context_p->source_p++;
if (context_p->source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (context_p->source_p[0]))
{
context_p->column++;
}
}
} /* skip_spaces */
/**
* Keyword data.
*/
typedef struct
{
const uint8_t *keyword_p; /**< keyword string */
lexer_token_type_t type; /**< keyword token type */
} keyword_string_t;
#define LEXER_KEYWORD(name, type) { (const uint8_t *) (name), (type) }
#define LEXER_KEYWORD_END() { (const uint8_t *) NULL, LEXER_EOS }
/**
* Keywords with 2 characters.
*/
static const keyword_string_t keyword_length_2[4] =
{
LEXER_KEYWORD ("do", LEXER_KEYW_DO),
LEXER_KEYWORD ("if", LEXER_KEYW_IF),
LEXER_KEYWORD ("in", LEXER_KEYW_IN),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 3 characters.
*/
static const keyword_string_t keyword_length_3[6] =
{
LEXER_KEYWORD ("for", LEXER_KEYW_FOR),
LEXER_KEYWORD ("let", LEXER_KEYW_LET),
LEXER_KEYWORD ("new", LEXER_KEYW_NEW),
LEXER_KEYWORD ("try", LEXER_KEYW_TRY),
LEXER_KEYWORD ("var", LEXER_KEYW_VAR),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 4 characters.
*/
static const keyword_string_t keyword_length_4[9] =
{
LEXER_KEYWORD ("case", LEXER_KEYW_CASE),
LEXER_KEYWORD ("else", LEXER_KEYW_ELSE),
LEXER_KEYWORD ("enum", LEXER_KEYW_ENUM),
LEXER_KEYWORD ("null", LEXER_LIT_NULL),
LEXER_KEYWORD ("this", LEXER_KEYW_THIS),
LEXER_KEYWORD ("true", LEXER_LIT_TRUE),
LEXER_KEYWORD ("void", LEXER_KEYW_VOID),
LEXER_KEYWORD ("with", LEXER_KEYW_WITH),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 5 characters.
*/
static const keyword_string_t keyword_length_5[10] =
{
LEXER_KEYWORD ("break", LEXER_KEYW_BREAK),
LEXER_KEYWORD ("catch", LEXER_KEYW_CATCH),
LEXER_KEYWORD ("class", LEXER_KEYW_CLASS),
LEXER_KEYWORD ("const", LEXER_KEYW_CONST),
LEXER_KEYWORD ("false", LEXER_LIT_FALSE),
LEXER_KEYWORD ("super", LEXER_KEYW_SUPER),
LEXER_KEYWORD ("throw", LEXER_KEYW_THROW),
LEXER_KEYWORD ("while", LEXER_KEYW_WHILE),
LEXER_KEYWORD ("yield", LEXER_KEYW_YIELD),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 6 characters.
*/
static const keyword_string_t keyword_length_6[9] =
{
LEXER_KEYWORD ("delete", LEXER_KEYW_DELETE),
LEXER_KEYWORD ("export", LEXER_KEYW_EXPORT),
LEXER_KEYWORD ("import", LEXER_KEYW_IMPORT),
LEXER_KEYWORD ("public", LEXER_KEYW_PUBLIC),
LEXER_KEYWORD ("return", LEXER_KEYW_RETURN),
LEXER_KEYWORD ("static", LEXER_KEYW_STATIC),
LEXER_KEYWORD ("switch", LEXER_KEYW_SWITCH),
LEXER_KEYWORD ("typeof", LEXER_KEYW_TYPEOF),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 7 characters.
*/
static const keyword_string_t keyword_length_7[6] =
{
LEXER_KEYWORD ("default", LEXER_KEYW_DEFAULT),
LEXER_KEYWORD ("extends", LEXER_KEYW_EXTENDS),
LEXER_KEYWORD ("finally", LEXER_KEYW_FINALLY),
LEXER_KEYWORD ("package", LEXER_KEYW_PACKAGE),
LEXER_KEYWORD ("private", LEXER_KEYW_PRIVATE),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 8 characters.
*/
static const keyword_string_t keyword_length_8[4] =
{
LEXER_KEYWORD ("continue", LEXER_KEYW_CONTINUE),
LEXER_KEYWORD ("debugger", LEXER_KEYW_DEBUGGER),
LEXER_KEYWORD ("function", LEXER_KEYW_FUNCTION),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 9 characters.
*/
static const keyword_string_t keyword_length_9[3] =
{
LEXER_KEYWORD ("interface", LEXER_KEYW_INTERFACE),
LEXER_KEYWORD ("protected", LEXER_KEYW_PROTECTED),
LEXER_KEYWORD_END ()
};
/**
* Keywords with 10 characters.
*/
static const keyword_string_t keyword_length_10[3] =
{
LEXER_KEYWORD ("implements", LEXER_KEYW_IMPLEMENTS),
LEXER_KEYWORD ("instanceof", LEXER_KEYW_INSTANCEOF),
LEXER_KEYWORD_END ()
};
/**
* List to the keywords.
*/
static const keyword_string_t * const keyword_string_list[9] =
{
keyword_length_2,
keyword_length_3,
keyword_length_4,
keyword_length_5,
keyword_length_6,
keyword_length_7,
keyword_length_8,
keyword_length_9,
keyword_length_10
};
#undef LEXER_KEYWORD
#undef LEXER_KEYWORD_END
/**
* Parse identifier.
*/
static void
lexer_parse_identifier (parser_context_t *context_p, /**< context */
bool check_keywords) /**< check keywords */
{
/* Only very few identifiers contains \u escape sequences. */
const uint8_t *source_p = context_p->source_p;
const uint8_t *ident_start_p = context_p->source_p;
/* Note: newline or tab cannot be part of an identifier. */
parser_line_counter_t column = context_p->column;
const uint8_t *source_end_p = context_p->source_end_p;
size_t length = 0;
context_p->token.type = LEXER_LITERAL;
context_p->token.literal_is_reserved = false;
context_p->token.lit_location.type = LEXER_IDENT_LITERAL;
context_p->token.lit_location.has_escape = false;
do
{
if (*source_p == LIT_CHAR_BACKSLASH)
{
uint16_t character;
context_p->token.lit_location.has_escape = true;
context_p->source_p = source_p;
context_p->token.column = column;
if ((source_p + 6 > source_end_p) || (source_p[1] != LIT_CHAR_LOWERCASE_U))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_UNICODE_ESCAPE_SEQUENCE);
}
character = lexer_hex_to_character (context_p, source_p + 2, 4);
if (length == 0)
{
if (!lit_char_is_identifier_start_character (character))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_IDENTIFIER_START);
}
}
else
{
if (!lit_char_is_identifier_part_character (character))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_IDENTIFIER_PART);
}
}
length += lit_char_get_utf8_length (character);
source_p += 6;
PARSER_PLUS_EQUAL_LC (column, 6);
continue;
}
/* Valid identifiers cannot contain 4 byte long utf-8
* characters, since those characters are represented
* by 2 ecmascript (UTF-16) characters, and those
* characters cannot be literal characters. */
JERRY_ASSERT (source_p[0] < LEXER_UTF8_4BYTE_START);
source_p++;
length++;
column++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (source_p[0]))
{
source_p++;
length++;
}
}
while (source_p < source_end_p
&& (lit_char_is_identifier_part (source_p) || *source_p == LIT_CHAR_BACKSLASH));
context_p->source_p = ident_start_p;
context_p->token.column = context_p->column;
if (length > PARSER_MAXIMUM_IDENT_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_TOO_LONG);
}
/* Check keywords (Only if there is no \u escape sequence in the pattern). */
if (check_keywords
&& !context_p->token.lit_location.has_escape
&& (length >= 2 && length <= 10))
{
const keyword_string_t *keyword_p = keyword_string_list[length - 2];
do
{
if (ident_start_p[0] == keyword_p->keyword_p[0]
&& ident_start_p[1] == keyword_p->keyword_p[1]
&& memcmp (ident_start_p, keyword_p->keyword_p, length) == 0)
{
if (keyword_p->type >= LEXER_FIRST_FUTURE_STRICT_RESERVED_WORD)
{
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_STRICT_IDENT_NOT_ALLOWED);
}
context_p->token.literal_is_reserved = true;
break;
}
context_p->token.type = keyword_p->type;
break;
}
keyword_p++;
}
while (keyword_p->type != LEXER_EOS);
}
if (context_p->token.type == LEXER_LITERAL)
{
/* Fill literal data. */
context_p->token.lit_location.char_p = ident_start_p;
context_p->token.lit_location.length = (uint16_t) length;
}
context_p->source_p = source_p;
context_p->column = column;
} /* lexer_parse_identifier */
/**
* Parse string.
*/
static void
lexer_parse_string (parser_context_t *context_p) /**< context */
{
uint8_t str_end_character = context_p->source_p[0];
const uint8_t *source_p = context_p->source_p + 1;
const uint8_t *string_start_p = source_p;
const uint8_t *source_end_p = context_p->source_end_p;
parser_line_counter_t line = context_p->line;
parser_line_counter_t column = (parser_line_counter_t) (context_p->column + 1);
parser_line_counter_t original_line = line;
parser_line_counter_t original_column = column;
size_t length = 0;
uint8_t has_escape = false;
while (true)
{
if (source_p >= source_end_p)
{
context_p->token.line = original_line;
context_p->token.column = (parser_line_counter_t) (original_column - 1);
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_STRING);
}
if (*source_p == str_end_character)
{
break;
}
if (*source_p == LIT_CHAR_BACKSLASH)
{
source_p++;
column++;
if (source_p >= source_end_p)
{
/* Will throw an unterminated string error. */
continue;
}
has_escape = true;
/* Newline is ignored. */
if (*source_p == LIT_CHAR_CR
|| *source_p == LIT_CHAR_LF
|| (*source_p == LEXER_NEWLINE_LS_PS_BYTE_1 && LEXER_NEWLINE_LS_PS_BYTE_23 (source_p)))
{
if (*source_p == LIT_CHAR_CR)
{
source_p++;
if (source_p < source_end_p
&& *source_p == LIT_CHAR_LF)
{
source_p++;
}
}
else if (*source_p == LIT_CHAR_LF)
{
source_p++;
}
else
{
source_p += 3;
}
line++;
column = 1;
continue;
}
/* Except \x, \u, and octal numbers, everything is
* converted to a character which has the same byte length. */
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_3)
{
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_ESCAPE_NOT_ALLOWED);
}
source_p++;
column++;
if (source_p < source_end_p && *source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
source_p++;
column++;
if (source_p < source_end_p && *source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
/* Numbers >= 0x200 (0x80) requires
* two bytes for encoding in UTF-8. */
if (source_p[-2] >= LIT_CHAR_2)
{
length++;
}
source_p++;
column++;
}
}
length++;
continue;
}
if (*source_p >= LIT_CHAR_4 && *source_p <= LIT_CHAR_7)
{
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_ESCAPE_NOT_ALLOWED);
}
source_p++;
column++;
if (source_p < source_end_p && *source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
source_p++;
column++;
}
/* The maximum number is 0x4d so the UTF-8
* representation is always one byte. */
length++;
continue;
}
if (*source_p == LIT_CHAR_LOWERCASE_X || *source_p == LIT_CHAR_LOWERCASE_U)
{
uint8_t hex_part_length = (*source_p == LIT_CHAR_LOWERCASE_X) ? 2 : 4;
context_p->token.line = line;
context_p->token.column = (parser_line_counter_t) (column - 1);
if (source_p + 1 + hex_part_length > source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_ESCAPE_SEQUENCE);
}
length += lit_char_get_utf8_length (lexer_hex_to_character (context_p,
source_p + 1,
hex_part_length));
source_p += hex_part_length + 1;
PARSER_PLUS_EQUAL_LC (column, hex_part_length + 1u);
continue;
}
}
if (*source_p >= LEXER_UTF8_4BYTE_START)
{
/* Processing 4 byte unicode sequence (even if it is
* after a backslash). Always converted to two 3 byte
* long sequence. */
length += 2 * 3;
has_escape = true;
source_p += 4;
column++;
continue;
}
else if (*source_p == LIT_CHAR_CR
|| *source_p == LIT_CHAR_LF
|| (*source_p == LEXER_NEWLINE_LS_PS_BYTE_1 && LEXER_NEWLINE_LS_PS_BYTE_23 (source_p)))
{
context_p->token.line = line;
context_p->token.column = column;
parser_raise_error (context_p, PARSER_ERR_NEWLINE_NOT_ALLOWED);
}
else if (*source_p == LIT_CHAR_TAB)
{
column = align_column_to_tab (column);
/* Subtract -1 because column is increased below. */
column--;
}
source_p++;
column++;
length++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (*source_p))
{
source_p++;
length++;
}
}
if (length > PARSER_MAXIMUM_STRING_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_STRING_TOO_LONG);
}
context_p->token.type = LEXER_LITERAL;
/* Fill literal data. */
context_p->token.lit_location.char_p = string_start_p;
context_p->token.lit_location.length = (uint16_t) length;
context_p->token.lit_location.type = LEXER_STRING_LITERAL;
context_p->token.lit_location.has_escape = has_escape;
context_p->source_p = source_p + 1;
context_p->line = line;
context_p->column = (parser_line_counter_t) (column + 1);
} /* lexer_parse_string */
/**
* Parse number.
*/
static void
lexer_parse_number (parser_context_t *context_p) /**< context */
{
const uint8_t *source_p = context_p->source_p;
const uint8_t *source_end_p = context_p->source_end_p;
bool can_be_float = false;
size_t length;
context_p->token.type = LEXER_LITERAL;
context_p->token.literal_is_reserved = false;
context_p->token.extra_value = LEXER_NUMBER_DECIMAL;
context_p->token.lit_location.char_p = source_p;
context_p->token.lit_location.type = LEXER_NUMBER_LITERAL;
context_p->token.lit_location.has_escape = false;
if (source_p[0] == LIT_CHAR_0
&& source_p + 1 < source_end_p)
{
if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X)
{
context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL;
source_p += 2;
if (source_p >= source_end_p
|| !lit_char_is_hex_digit (source_p[0]))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT);
}
do
{
source_p++;
}
while (source_p < source_end_p
&& lit_char_is_hex_digit (source_p[0]));
}
else if (source_p[1] >= LIT_CHAR_0
&& source_p[1] <= LIT_CHAR_7)
{
context_p->token.extra_value = LEXER_NUMBER_OCTAL;
if (context_p->status_flags & PARSER_IS_STRICT)
{
parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED);
}
do
{
source_p++;
}
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_7);
if (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_8
&& source_p[0] <= LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);
}
}
else if (source_p[1] >= LIT_CHAR_8
&& source_p[1] <= LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER);
}
else
{
can_be_float = true;
source_p++;
}
}
else
{
do
{
source_p++;
}
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_9);
can_be_float = true;
}
if (can_be_float)
{
if (source_p < source_end_p
&& source_p[0] == LIT_CHAR_DOT)
{
source_p++;
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_9)
{
source_p++;
}
}
if (source_p < source_end_p
&& LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E)
{
source_p++;
if (source_p < source_end_p
&& (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS))
{
source_p++;
}
if (source_p >= source_end_p
|| source_p[0] < LIT_CHAR_0
|| source_p[0] > LIT_CHAR_9)
{
parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT);
}
do
{
source_p++;
}
while (source_p < source_end_p
&& source_p[0] >= LIT_CHAR_0
&& source_p[0] <= LIT_CHAR_9);
}
}
if (source_p < source_end_p
&& (lit_char_is_identifier_start (source_p) || source_p[0] == LIT_CHAR_BACKSLASH))
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER);
}
length = (size_t) (source_p - context_p->source_p);
if (length > PARSER_MAXIMUM_IDENT_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG);
}
context_p->token.lit_location.length = (uint16_t) length;
PARSER_PLUS_EQUAL_LC (context_p->column, length);
context_p->source_p = source_p;
} /* lexer_parse_number */
#define LEXER_TYPE_A_TOKEN(char1, type1) \
case (uint8_t) (char1) : \
{ \
context_p->token.type = (type1); \
length = 1; \
break; \
}
#define LEXER_TYPE_B_TOKEN(char1, type1, char2, type2) \
case (uint8_t) (char1) : \
{ \
if (length >= 2 && context_p->source_p[1] == (uint8_t) (char2)) \
{ \
context_p->token.type = (type2); \
length = 2; \
break; \
} \
\
context_p->token.type = (type1); \
length = 1; \
break; \
}
#define LEXER_TYPE_C_TOKEN(char1, type1, char2, type2, char3, type3) \
case (uint8_t) (char1) : \
{ \
if (length >= 2) \
{ \
if (context_p->source_p[1] == (uint8_t) (char2)) \
{ \
context_p->token.type = (type2); \
length = 2; \
break; \
} \
\
if (context_p->source_p[1] == (uint8_t) (char3)) \
{ \
context_p->token.type = (type3); \
length = 2; \
break; \
} \
} \
\
context_p->token.type = (type1); \
length = 1; \
break; \
}
#define LEXER_TYPE_D_TOKEN(char1, type1, char2, type2, char3, type3) \
case (uint8_t) (char1) : \
{ \
if (length >= 2 && context_p->source_p[1] == (uint8_t) (char2)) \
{ \
if (length >= 3 && context_p->source_p[2] == (uint8_t) (char3)) \
{ \
context_p->token.type = (type3); \
length = 3; \
break; \
} \
\
context_p->token.type = (type2); \
length = 2; \
break; \
} \
\
context_p->token.type = (type1); \
length = 1; \
break; \
}
/**
* Get next token.
*/
void
lexer_next_token (parser_context_t *context_p) /**< context */
{
size_t length;
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
length = (size_t) (context_p->source_end_p - context_p->source_p);
if (length == 0)
{
context_p->token.type = LEXER_EOS;
return;
}
if (lit_char_is_identifier_start (context_p->source_p)
|| context_p->source_p[0] == LIT_CHAR_BACKSLASH)
{
lexer_parse_identifier (context_p, true);
return;
}
if (context_p->source_p[0] >= LIT_CHAR_0 && context_p->source_p[0] <= LIT_CHAR_9)
{
lexer_parse_number (context_p);
return;
}
switch (context_p->source_p[0])
{
LEXER_TYPE_A_TOKEN (LIT_CHAR_LEFT_BRACE, LEXER_LEFT_BRACE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_LEFT_PAREN, LEXER_LEFT_PAREN);
LEXER_TYPE_A_TOKEN (LIT_CHAR_LEFT_SQUARE, LEXER_LEFT_SQUARE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_RIGHT_BRACE, LEXER_RIGHT_BRACE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_RIGHT_PAREN, LEXER_RIGHT_PAREN);
LEXER_TYPE_A_TOKEN (LIT_CHAR_RIGHT_SQUARE, LEXER_RIGHT_SQUARE);
LEXER_TYPE_A_TOKEN (LIT_CHAR_SEMICOLON, LEXER_SEMICOLON);
LEXER_TYPE_A_TOKEN (LIT_CHAR_COMMA, LEXER_COMMA);
case (uint8_t) LIT_CHAR_DOT :
{
if (length >= 2
&& (context_p->source_p[1] >= LIT_CHAR_0 && context_p->source_p[1] <= LIT_CHAR_9))
{
lexer_parse_number (context_p);
return;
}
context_p->token.type = LEXER_DOT;
length = 1;
break;
}
case (uint8_t) LIT_CHAR_LESS_THAN:
{
if (length >= 2)
{
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_LESS_EQUAL;
length = 2;
break;
}
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_LESS_THAN)
{
if (length >= 3 && context_p->source_p[2] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_ASSIGN_LEFT_SHIFT;
length = 3;
break;
}
context_p->token.type = LEXER_LEFT_SHIFT;
length = 2;
break;
}
}
context_p->token.type = LEXER_LESS;
length = 1;
break;
}
case LIT_CHAR_GREATER_THAN:
{
if (length >= 2)
{
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_GREATER_EQUAL;
length = 2;
break;
}
if (context_p->source_p[1] == (uint8_t) LIT_CHAR_GREATER_THAN)
{
if (length >= 3)
{
if (context_p->source_p[2] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_ASSIGN_RIGHT_SHIFT;
length = 3;
break;
}
if (context_p->source_p[2] == (uint8_t) LIT_CHAR_GREATER_THAN)
{
if (length >= 4 && context_p->source_p[3] == (uint8_t) LIT_CHAR_EQUALS)
{
context_p->token.type = LEXER_ASSIGN_UNS_RIGHT_SHIFT;
length = 4;
break;
}
context_p->token.type = LEXER_UNS_RIGHT_SHIFT;
length = 3;
break;
}
}
context_p->token.type = LEXER_RIGHT_SHIFT;
length = 2;
break;
}
}
context_p->token.type = LEXER_GREATER;
length = 1;
break;
}
LEXER_TYPE_D_TOKEN (LIT_CHAR_EQUALS, LEXER_ASSIGN, LIT_CHAR_EQUALS,
LEXER_EQUAL, LIT_CHAR_EQUALS, LEXER_STRICT_EQUAL)
LEXER_TYPE_D_TOKEN (LIT_CHAR_EXCLAMATION, LEXER_LOGICAL_NOT, LIT_CHAR_EQUALS,
LEXER_NOT_EQUAL, LIT_CHAR_EQUALS, LEXER_STRICT_NOT_EQUAL)
LEXER_TYPE_C_TOKEN (LIT_CHAR_PLUS, LEXER_ADD, LIT_CHAR_EQUALS,
LEXER_ASSIGN_ADD, LIT_CHAR_PLUS, LEXER_INCREASE)
LEXER_TYPE_C_TOKEN (LIT_CHAR_MINUS, LEXER_SUBTRACT, LIT_CHAR_EQUALS,
LEXER_ASSIGN_SUBTRACT, LIT_CHAR_MINUS, LEXER_DECREASE)
LEXER_TYPE_B_TOKEN (LIT_CHAR_ASTERISK, LEXER_MULTIPLY, LIT_CHAR_EQUALS,
LEXER_ASSIGN_MULTIPLY)
LEXER_TYPE_B_TOKEN (LIT_CHAR_SLASH, LEXER_DIVIDE, LIT_CHAR_EQUALS,
LEXER_ASSIGN_DIVIDE)
LEXER_TYPE_B_TOKEN (LIT_CHAR_PERCENT, LEXER_MODULO, LIT_CHAR_EQUALS,
LEXER_ASSIGN_MODULO)
LEXER_TYPE_C_TOKEN (LIT_CHAR_AMPERSAND, LEXER_BIT_AND, LIT_CHAR_EQUALS,
LEXER_ASSIGN_BIT_AND, LIT_CHAR_AMPERSAND, LEXER_LOGICAL_AND)
LEXER_TYPE_C_TOKEN (LIT_CHAR_VLINE, LEXER_BIT_OR, LIT_CHAR_EQUALS,
LEXER_ASSIGN_BIT_OR, LIT_CHAR_VLINE, LEXER_LOGICAL_OR)
LEXER_TYPE_B_TOKEN (LIT_CHAR_CIRCUMFLEX, LEXER_BIT_XOR, LIT_CHAR_EQUALS,
LEXER_ASSIGN_BIT_XOR)
LEXER_TYPE_A_TOKEN (LIT_CHAR_TILDE, LEXER_BIT_NOT);
LEXER_TYPE_A_TOKEN (LIT_CHAR_QUESTION, LEXER_QUESTION_MARK);
LEXER_TYPE_A_TOKEN (LIT_CHAR_COLON, LEXER_COLON);
case LIT_CHAR_SINGLE_QUOTE:
case LIT_CHAR_DOUBLE_QUOTE:
{
lexer_parse_string (context_p);
return;
}
default:
{
parser_raise_error (context_p, PARSER_ERR_INVALID_CHARACTER);
}
}
context_p->source_p += length;
PARSER_PLUS_EQUAL_LC (context_p->column, length);
} /* lexer_next_token */
#undef LEXER_TYPE_A_TOKEN
#undef LEXER_TYPE_B_TOKEN
#undef LEXER_TYPE_C_TOKEN
#undef LEXER_TYPE_D_TOKEN
/**
* Search or append the string to the literal pool.
*/
static void
lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
if (length == 0)
{
has_escape = false;
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */
/* Maximum buffer size for identifiers which contains escape sequences. */
#define LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE 48
/**
* Construct a literal object from an identifier.
*/
void
lexer_construct_literal_object (parser_context_t *context_p, /**< context */
lexer_lit_location_t *literal_p, /**< literal location */
uint8_t literal_type) /**< final literal type */
{
uint8_t *destination_start_p;
const uint8_t *source_p;
uint8_t local_byte_array[LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE];
JERRY_ASSERT (literal_p->type == LEXER_IDENT_LITERAL
|| literal_p->type == LEXER_STRING_LITERAL);
JERRY_ASSERT (context_p->allocated_buffer_p == NULL);
destination_start_p = local_byte_array;
source_p = literal_p->char_p;
if (literal_p->has_escape)
{
uint8_t *destination_p;
if (literal_p->length > LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE)
{
destination_start_p = (uint8_t *) parser_malloc_local (context_p, literal_p->length);
context_p->allocated_buffer_p = destination_start_p;
context_p->allocated_buffer_size = literal_p->length;
}
destination_p = destination_start_p;
if (literal_p->type == LEXER_IDENT_LITERAL)
{
const uint8_t *source_end_p = context_p->source_end_p;
JERRY_ASSERT (literal_p->length <= PARSER_MAXIMUM_IDENT_LENGTH);
do
{
if (*source_p == LIT_CHAR_BACKSLASH)
{
destination_p += lit_char_to_utf8_bytes (destination_p,
lexer_hex_to_character (context_p, source_p + 2, 4));
source_p += 6;
continue;
}
*destination_p++ = *source_p++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (*source_p))
{
*destination_p++ = *source_p++;
}
}
while (source_p < source_end_p
&& (lit_char_is_identifier_part (source_p) || *source_p == LIT_CHAR_BACKSLASH));
JERRY_ASSERT (destination_p == destination_start_p + literal_p->length);
}
else
{
uint8_t str_end_character = source_p[-1];
while (true)
{
if (*source_p == str_end_character)
{
break;
}
if (*source_p == LIT_CHAR_BACKSLASH)
{
uint8_t conv_character;
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
/* Newline is ignored. */
if (*source_p == LIT_CHAR_CR
|| *source_p == LIT_CHAR_LF
|| (*source_p == LEXER_NEWLINE_LS_PS_BYTE_1 && LEXER_NEWLINE_LS_PS_BYTE_23 (source_p)))
{
if (*source_p == LIT_CHAR_CR)
{
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p == LIT_CHAR_LF)
{
source_p++;
}
}
else if (*source_p == LIT_CHAR_LF)
{
source_p++;
}
else
{
source_p += 3;
}
continue;
}
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_3)
{
uint32_t octal_number = (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
octal_number = octal_number * 8 + (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
octal_number = octal_number * 8 + (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
}
}
destination_p += lit_char_to_utf8_bytes (destination_p, (uint16_t) octal_number);
continue;
}
if (*source_p >= LIT_CHAR_4 && *source_p <= LIT_CHAR_7)
{
uint32_t octal_number = (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
if (*source_p >= LIT_CHAR_0 && *source_p <= LIT_CHAR_7)
{
octal_number = octal_number * 8 + (uint32_t) (*source_p - LIT_CHAR_0);
source_p++;
JERRY_ASSERT (source_p < context_p->source_end_p);
}
*destination_p++ = (uint8_t) octal_number;
continue;
}
if (*source_p == LIT_CHAR_LOWERCASE_X || *source_p == LIT_CHAR_LOWERCASE_U)
{
int hex_part_length = (*source_p == LIT_CHAR_LOWERCASE_X) ? 2 : 4;
JERRY_ASSERT (source_p + 1 + hex_part_length <= context_p->source_end_p);
destination_p += lit_char_to_utf8_bytes (destination_p,
lexer_hex_to_character (context_p,
source_p + 1,
hex_part_length));
source_p += hex_part_length + 1;
continue;
}
conv_character = *source_p;
switch (*source_p)
{
case LIT_CHAR_LOWERCASE_B:
{
conv_character = 0x08;
break;
}
case LIT_CHAR_LOWERCASE_T:
{
conv_character = 0x09;
break;
}
case LIT_CHAR_LOWERCASE_N:
{
conv_character = 0x0a;
break;
}
case LIT_CHAR_LOWERCASE_V:
{
conv_character = 0x0b;
break;
}
case LIT_CHAR_LOWERCASE_F:
{
conv_character = 0x0c;
break;
}
case LIT_CHAR_LOWERCASE_R:
{
conv_character = 0x0d;
break;
}
}
if (conv_character != *source_p)
{
*destination_p++ = conv_character;
source_p++;
continue;
}
}
if (*source_p >= LEXER_UTF8_4BYTE_START)
{
/* Processing 4 byte unicode sequence (even if it is
* after a backslash). Always converted to two 3 byte
* long sequence. */
uint32_t character = ((((uint32_t) source_p[0]) & 0x7) << 18);
character |= ((((uint32_t) source_p[1]) & LIT_UTF8_LAST_6_BITS_MASK) << 12);
character |= ((((uint32_t) source_p[2]) & LIT_UTF8_LAST_6_BITS_MASK) << 6);
character |= (((uint32_t) source_p[3]) & LIT_UTF8_LAST_6_BITS_MASK);
JERRY_ASSERT (character >= 0x10000);
character -= 0x10000;
destination_p += lit_char_to_utf8_bytes (destination_p,
(ecma_char_t) (0xd800 | (character >> 10)));
destination_p += lit_char_to_utf8_bytes (destination_p,
(ecma_char_t) (0xdc00 | (character & LIT_UTF16_LAST_10_BITS_MASK)));
source_p += 4;
continue;
}
*destination_p++ = *source_p++;
/* There is no need to check the source_end_p
* since the string is terminated by a quotation mark. */
while (IS_UTF8_INTERMEDIATE_OCTET (*source_p))
{
*destination_p++ = *source_p++;
}
}
JERRY_ASSERT (destination_p == destination_start_p + literal_p->length);
}
source_p = destination_start_p;
}
lexer_process_char_literal (context_p,
source_p,
literal_p->length,
literal_type,
literal_p->has_escape);
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
if (literal_type == LEXER_IDENT_LITERAL)
{
if ((context_p->status_flags & PARSER_INSIDE_WITH)
&& context_p->lit_object.literal_p->type == LEXER_IDENT_LITERAL)
{
context_p->lit_object.literal_p->status_flags |= LEXER_FLAG_NO_REG_STORE;
}
if (literal_p->length == 4
&& source_p[0] == LIT_CHAR_LOWERCASE_E
&& source_p[3] == LIT_CHAR_LOWERCASE_L
&& source_p[1] == LIT_CHAR_LOWERCASE_V
&& source_p[2] == LIT_CHAR_LOWERCASE_A)
{
context_p->lit_object.type = LEXER_LITERAL_OBJECT_EVAL;
}
if (literal_p->length == 9
&& source_p[0] == LIT_CHAR_LOWERCASE_A
&& source_p[8] == LIT_CHAR_LOWERCASE_S
&& memcmp (source_p + 1, "rgument", 7) == 0)
{
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ARGUMENTS;
if (!(context_p->status_flags & PARSER_ARGUMENTS_NOT_NEEDED))
{
context_p->status_flags |= PARSER_ARGUMENTS_NEEDED | PARSER_LEXICAL_ENV_NEEDED;
context_p->lit_object.literal_p->status_flags |= LEXER_FLAG_NO_REG_STORE;
}
}
}
if (destination_start_p != local_byte_array)
{
JERRY_ASSERT (context_p->allocated_buffer_p == destination_start_p);
context_p->allocated_buffer_p = NULL;
parser_free_local (destination_start_p,
context_p->allocated_buffer_size);
}
JERRY_ASSERT (context_p->allocated_buffer_p == NULL);
} /* lexer_construct_literal_object */
#undef LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE
/**
* Construct a number object.
*
* @return true if number is small number
*/
bool
lexer_construct_number_object (parser_context_t *context_p, /**< context */
bool push_number_allowed, /**< push number support is allowed */
bool is_negative_number) /**< sign is negative */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
ecma_number_t num;
uint32_t literal_index = 0;
uint16_t length = context_p->token.lit_location.length;
if (context_p->token.extra_value != LEXER_NUMBER_OCTAL)
{
num = ecma_utf8_string_to_number (context_p->token.lit_location.char_p,
length);
}
else
{
const uint8_t *src_p = context_p->token.lit_location.char_p;
const uint8_t *src_end_p = src_p + length - 1;
num = 0;
do
{
src_p++;
num = num * 8 + (ecma_number_t) (*src_p - LIT_CHAR_0);
}
while (src_p < src_end_p);
}
if (push_number_allowed)
{
int32_t int_num = (int32_t) num;
if (int_num == num)
{
if (int_num <= CBC_PUSH_NUMBER_BYTE_RANGE_END
&& (int_num != 0 || !is_negative_number))
{
context_p->lit_object.index = (uint16_t) int_num;
return true;
}
}
}
if (is_negative_number)
{
num = -num;
}
jmem_cpointer_t lit_cp = ecma_find_or_create_literal_number (num);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == LEXER_NUMBER_LITERAL
&& literal_p->u.value == lit_cp)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
return false;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = context_p->token.lit_location.length;
literal_p->type = LEXER_UNUSED_LITERAL;
literal_p->status_flags = 0;
context_p->literal_count++;
literal_p->u.value = lit_cp;
literal_p->type = LEXER_NUMBER_LITERAL;
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
return false;
} /* lexer_construct_number_object */
/**
* Construct a function literal object.
*
* @return function object literal index
*/
uint16_t
lexer_construct_function_object (parser_context_t *context_p, /**< context */
uint32_t extra_status_flags) /**< extra status flags */
{
ecma_compiled_code_t *compiled_code_p;
lexer_literal_t *literal_p;
uint16_t result_index;
if (context_p->literal_count >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
if (context_p->status_flags & PARSER_RESOLVE_THIS_FOR_CALLS)
{
extra_status_flags |= PARSER_RESOLVE_THIS_FOR_CALLS;
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->type = LEXER_UNUSED_LITERAL;
literal_p->status_flags = 0;
result_index = context_p->literal_count;
context_p->literal_count++;
compiled_code_p = parser_parse_function (context_p, extra_status_flags);
literal_p->u.bytecode_p = compiled_code_p;
literal_p->type = LEXER_FUNCTION_LITERAL;
return result_index;
} /* lexer_construct_function_object */
/**
* Construct a regular expression object.
*/
void
lexer_construct_regexp_object (parser_context_t *context_p, /**< context */
bool parse_only) /**< parse only */
{
#ifndef CONFIG_DISABLE_REGEXP_BUILTIN
const uint8_t *source_p = context_p->source_p;
const uint8_t *regex_start_p = context_p->source_p;
const uint8_t *regex_end_p = regex_start_p;
const uint8_t *source_end_p = context_p->source_end_p;
parser_line_counter_t column = context_p->column;
lexer_literal_t *literal_p;
bool in_class = false;
uint16_t current_flags;
lit_utf8_size_t length;
JERRY_ASSERT (context_p->token.type == LEXER_DIVIDE
|| context_p->token.type == LEXER_ASSIGN_DIVIDE);
if (context_p->token.type == LEXER_ASSIGN_DIVIDE)
{
regex_start_p--;
}
while (true)
{
if (source_p >= source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_REGEXP);
}
if (!in_class && source_p[0] == LIT_CHAR_SLASH)
{
regex_end_p = source_p;
source_p++;
column++;
break;
}
switch (source_p[0])
{
case LIT_CHAR_CR:
case LIT_CHAR_LF:
case LEXER_NEWLINE_LS_PS_BYTE_1:
{
if (source_p[0] != LEXER_NEWLINE_LS_PS_BYTE_1
|| LEXER_NEWLINE_LS_PS_BYTE_23 (source_p))
{
parser_raise_error (context_p, PARSER_ERR_NEWLINE_NOT_ALLOWED);
}
break;
}
case LIT_CHAR_TAB:
{
column = align_column_to_tab (column);
/* Subtract -1 because column is increased below. */
column--;
break;
}
case LIT_CHAR_LEFT_SQUARE:
{
in_class = true;
break;
}
case LIT_CHAR_RIGHT_SQUARE:
{
in_class = false;
break;
}
case LIT_CHAR_BACKSLASH:
{
if (source_p + 1 >= source_end_p)
{
parser_raise_error (context_p, PARSER_ERR_UNTERMINATED_REGEXP);
}
if (source_p[1] >= 0x20 && source_p[1] <= LIT_UTF8_1_BYTE_CODE_POINT_MAX)
{
source_p++;
column++;
}
}
}
source_p++;
column++;
while (source_p < source_end_p
&& IS_UTF8_INTERMEDIATE_OCTET (source_p[0]))
{
source_p++;
}
}
current_flags = 0;
while (source_p < source_end_p)
{
uint32_t flag = 0;
if (source_p[0] == LIT_CHAR_LOWERCASE_G)
{
flag = RE_FLAG_GLOBAL;
}
else if (source_p[0] == LIT_CHAR_LOWERCASE_I)
{
flag = RE_FLAG_IGNORE_CASE;
}
else if (source_p[0] == LIT_CHAR_LOWERCASE_M)
{
flag = RE_FLAG_MULTILINE;
}
if (flag == 0)
{
break;
}
if (current_flags & flag)
{
parser_raise_error (context_p, PARSER_ERR_DUPLICATED_REGEXP_FLAG);
}
current_flags = (uint16_t) (current_flags | flag);
source_p++;
column++;
}
if (source_p < source_end_p
&& lit_char_is_identifier_part (source_p))
{
parser_raise_error (context_p, PARSER_ERR_UNKNOWN_REGEXP_FLAG);
}
context_p->source_p = source_p;
context_p->column = column;
length = (lit_utf8_size_t) (regex_end_p - regex_start_p);
if (length > PARSER_MAXIMUM_STRING_LENGTH)
{
parser_raise_error (context_p, PARSER_ERR_REGEXP_TOO_LONG);
}
context_p->column = column;
context_p->source_p = source_p;
if (parse_only)
{
return;
}
if (context_p->literal_count >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = LEXER_UNUSED_LITERAL;
literal_p->status_flags = 0;
context_p->literal_count++;
/* Compile the RegExp literal and store the RegExp bytecode pointer */
const re_compiled_code_t *re_bytecode_p = NULL;
ecma_value_t completion_value;
ecma_string_t *pattern_str_p = ecma_new_ecma_string_from_utf8 (regex_start_p, length);
completion_value = re_compile_bytecode (&re_bytecode_p,
pattern_str_p,
current_flags);
ecma_deref_ecma_string (pattern_str_p);
bool is_throw = ECMA_IS_VALUE_ERROR (completion_value);
ecma_free_value (completion_value);
if (is_throw)
{
parser_raise_error (context_p, PARSER_ERR_INVALID_REGEXP);
}
literal_p->type = LEXER_REGEXP_LITERAL;
literal_p->u.bytecode_p = (ecma_compiled_code_t *) re_bytecode_p;
context_p->token.type = LEXER_LITERAL;
context_p->token.literal_is_reserved = false;
context_p->token.lit_location.type = LEXER_REGEXP_LITERAL;
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) (context_p->literal_count - 1);
context_p->lit_object.type = LEXER_LITERAL_OBJECT_ANY;
#else /* CONFIG_DISABLE_REGEXP_BUILTIN */
JERRY_UNUSED (parse_only);
parser_raise_error (context_p, PARSER_ERR_UNSUPPORTED_REGEXP);
#endif /* !CONFIG_DISABLE_REGEXP_BUILTIN */
} /* lexer_construct_regexp_object */
/**
* Next token must be an identifier.
*/
void
lexer_expect_identifier (parser_context_t *context_p, /**< context */
uint8_t literal_type) /**< literal type */
{
JERRY_ASSERT (literal_type == LEXER_STRING_LITERAL
|| literal_type == LEXER_IDENT_LITERAL);
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
if (context_p->source_p < context_p->source_end_p
&& (lit_char_is_identifier_start (context_p->source_p) || context_p->source_p[0] == LIT_CHAR_BACKSLASH))
{
lexer_parse_identifier (context_p, literal_type != LEXER_STRING_LITERAL);
if (context_p->token.type == LEXER_LITERAL)
{
lexer_construct_literal_object (context_p,
&context_p->token.lit_location,
literal_type);
if (literal_type == LEXER_IDENT_LITERAL
&& (context_p->status_flags & PARSER_IS_STRICT)
&& context_p->lit_object.type != LEXER_LITERAL_OBJECT_ANY)
{
parser_error_t error;
if (context_p->lit_object.type == LEXER_LITERAL_OBJECT_EVAL)
{
error = PARSER_ERR_EVAL_NOT_ALLOWED;
}
else
{
JERRY_ASSERT (context_p->lit_object.type == LEXER_LITERAL_OBJECT_ARGUMENTS);
error = PARSER_ERR_ARGUMENTS_NOT_ALLOWED;
}
parser_raise_error (context_p, error);
}
context_p->token.lit_location.type = literal_type;
return;
}
}
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED);
} /* lexer_expect_identifier */
static const lexer_lit_location_t lexer_get_literal =
{
(const uint8_t *) "get", 3, LEXER_IDENT_LITERAL, false
};
static const lexer_lit_location_t lexer_set_literal =
{
(const uint8_t *) "set", 3, LEXER_IDENT_LITERAL, false
};
/**
* Next token must be an identifier.
*/
void
lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */
bool must_be_identifier) /**< only identifiers are accepted */
{
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
if (context_p->source_p < context_p->source_end_p)
{
bool create_literal_object = false;
if (lit_char_is_identifier_start (context_p->source_p) || context_p->source_p[0] == LIT_CHAR_BACKSLASH)
{
lexer_parse_identifier (context_p, false);
if (!must_be_identifier
&& context_p->token.lit_location.length == 3)
{
skip_spaces (context_p);
if (context_p->source_p < context_p->source_end_p
&& context_p->source_p[0] != LIT_CHAR_COLON)
{
if (lexer_compare_identifier_to_current (context_p, &lexer_get_literal))
{
context_p->token.type = LEXER_PROPERTY_GETTER;
return;
}
else if (lexer_compare_identifier_to_current (context_p, &lexer_set_literal))
{
context_p->token.type = LEXER_PROPERTY_SETTER;
return;
}
}
}
create_literal_object = true;
}
else if (context_p->source_p[0] == LIT_CHAR_DOUBLE_QUOTE
|| context_p->source_p[0] == LIT_CHAR_SINGLE_QUOTE)
{
lexer_parse_string (context_p);
create_literal_object = true;
}
else if (!must_be_identifier && context_p->source_p[0] == LIT_CHAR_RIGHT_BRACE)
{
context_p->token.type = LEXER_RIGHT_BRACE;
context_p->source_p += 1;
context_p->column++;
return;
}
else
{
const uint8_t *char_p = context_p->source_p;
if (char_p[0] == LIT_CHAR_DOT)
{
char_p++;
}
if (char_p < context_p->source_end_p
&& char_p[0] >= LIT_CHAR_0
&& char_p[0] <= LIT_CHAR_9)
{
lexer_parse_number (context_p);
lexer_construct_number_object (context_p, false, false);
return;
}
}
if (create_literal_object)
{
lexer_construct_literal_object (context_p,
&context_p->token.lit_location,
LEXER_STRING_LITERAL);
return;
}
}
parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED);
} /* lexer_expect_object_literal_id */
/**
* Next token must be an identifier.
*/
void
lexer_scan_identifier (parser_context_t *context_p, /**< context */
bool propety_name) /**< property name */
{
skip_spaces (context_p);
context_p->token.line = context_p->line;
context_p->token.column = context_p->column;
if (context_p->source_p < context_p->source_end_p
&& (lit_char_is_identifier_start (context_p->source_p) || context_p->source_p[0] == LIT_CHAR_BACKSLASH))
{
lexer_parse_identifier (context_p, false);
if (propety_name && context_p->token.lit_location.length == 3)
{
skip_spaces (context_p);
if (context_p->source_p < context_p->source_end_p
&& context_p->source_p[0] != LIT_CHAR_COLON)
{
if (lexer_compare_identifier_to_current (context_p, &lexer_get_literal))
{
context_p->token.type = LEXER_PROPERTY_GETTER;
}
else if (lexer_compare_identifier_to_current (context_p, &lexer_set_literal))
{
context_p->token.type = LEXER_PROPERTY_SETTER;
}
}
}
return;
}
if (propety_name)
{
lexer_next_token (context_p);
if (context_p->token.type == LEXER_LITERAL
|| context_p->token.type == LEXER_RIGHT_BRACE)
{
return;
}
}
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED);
} /* lexer_scan_identifier */
/**
* Compares the given identifier to that which is the current token
* in the parser context.
*
* @return true if the input identifiers are the same
*/
bool
lexer_compare_identifier_to_current (parser_context_t *context_p, /**< context */
const lexer_lit_location_t *right) /**< identifier */
{
lexer_lit_location_t *left = &context_p->token.lit_location;
const uint8_t *left_p;
const uint8_t *right_p;
size_t count;
JERRY_ASSERT (left->length > 0 && right->length > 0);
if (left->length != right->length)
{
return 0;
}
if (!left->has_escape && !right->has_escape)
{
return memcmp (left->char_p, right->char_p, left->length) == 0;
}
left_p = left->char_p;
right_p = right->char_p;
count = left->length;
do
{
uint8_t utf8_buf[3];
size_t utf8_len, offset;
/* Backslash cannot be part of a multibyte UTF-8 character. */
if (*left_p != LIT_CHAR_BACKSLASH && *right_p != LIT_CHAR_BACKSLASH)
{
if (*left_p++ != *right_p++)
{
return false;
}
count--;
continue;
}
if (*left_p == LIT_CHAR_BACKSLASH && *right_p == LIT_CHAR_BACKSLASH)
{
uint16_t left_chr = lexer_hex_to_character (context_p, left_p, 6);
if (left_chr != lexer_hex_to_character (context_p, right_p, 6))
{
return false;
}
left_p += 6;
right_p += 6;
count += lit_char_get_utf8_length (left_chr);
continue;
}
/* One character is encoded as unicode sequence. */
if (*right_p == LIT_CHAR_BACKSLASH)
{
/* The pointers can be swapped. */
const uint8_t *swap_p = left_p;
left_p = right_p;
right_p = swap_p;
}
utf8_len = lit_char_to_utf8_bytes (utf8_buf, lexer_hex_to_character (context_p, left_p, 6));
JERRY_ASSERT (utf8_len > 0);
count -= utf8_len;
offset = 0;
do
{
if (utf8_buf[offset] != *right_p++)
{
return false;
}
offset++;
}
while (offset < utf8_len);
left_p += 6;
}
while (count > 0);
return true;
} /* lexer_compare_identifier_to_current */
/**
* @}
* @}
* @}
*/
#endif /* JERRY_JS_PARSER */
| ./CrossVul/dataset_final_sorted/CWE-476/c/good_3380_0 |
crossvul-cpp_data_bad_3060_0 | /* Asymmetric public-key cryptography key type
*
* See Documentation/security/asymmetric-keys.txt
*
* Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "asymmetric_keys.h"
MODULE_LICENSE("GPL");
static LIST_HEAD(asymmetric_key_parsers);
static DECLARE_RWSEM(asymmetric_key_parsers_sem);
/*
* Match asymmetric key id with partial match
* @id: key id to match in a form "id:<id>"
*/
int asymmetric_keyid_match(const char *kid, const char *id)
{
size_t idlen, kidlen;
if (!kid || !id)
return 0;
/* make it possible to use id as in the request: "id:<id>" */
if (strncmp(id, "id:", 3) == 0)
id += 3;
/* Anything after here requires a partial match on the ID string */
idlen = strlen(id);
kidlen = strlen(kid);
if (idlen > kidlen)
return 0;
kid += kidlen - idlen;
if (strcasecmp(id, kid) != 0)
return 0;
return 1;
}
EXPORT_SYMBOL_GPL(asymmetric_keyid_match);
/*
* Match asymmetric keys on (part of) their name
* We have some shorthand methods for matching keys. We allow:
*
* "<desc>" - request a key by description
* "id:<id>" - request a key matching the ID
* "<subtype>:<id>" - request a key of a subtype
*/
static int asymmetric_key_match(const struct key *key,
const struct key_match_data *match_data)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *description = match_data->raw_data;
const char *spec = description;
const char *id;
ptrdiff_t speclen;
if (!subtype || !spec || !*spec)
return 0;
/* See if the full key description matches as is */
if (key->description && strcmp(key->description, description) == 0)
return 1;
/* All tests from here on break the criterion description into a
* specifier, a colon and then an identifier.
*/
id = strchr(spec, ':');
if (!id)
return 0;
speclen = id - spec;
id++;
if (speclen == 2 && memcmp(spec, "id", 2) == 0)
return asymmetric_keyid_match(asymmetric_key_id(key), id);
if (speclen == subtype->name_len &&
memcmp(spec, subtype->name, speclen) == 0)
return 1;
return 0;
}
/*
* Preparse the match criterion. If we don't set lookup_type and cmp,
* the default will be an exact match on the key description.
*
* There are some specifiers for matching key IDs rather than by the key
* description:
*
* "id:<id>" - request a key by any available ID
*
* These have to be searched by iteration rather than by direct lookup because
* the key is hashed according to its description.
*/
static int asymmetric_key_match_preparse(struct key_match_data *match_data)
{
match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
return 0;
}
/*
* Free the preparsed the match criterion.
*/
static void asymmetric_key_match_free(struct key_match_data *match_data)
{
}
/*
* Describe the asymmetric key
*/
static void asymmetric_key_describe(const struct key *key, struct seq_file *m)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *kid = asymmetric_key_id(key);
size_t n;
seq_puts(m, key->description);
if (subtype) {
seq_puts(m, ": ");
subtype->describe(key, m);
if (kid) {
seq_putc(m, ' ');
n = strlen(kid);
if (n <= 8)
seq_puts(m, kid);
else
seq_puts(m, kid + n - 8);
}
seq_puts(m, " [");
/* put something here to indicate the key's capabilities */
seq_putc(m, ']');
}
}
/*
* Preparse a asymmetric payload to get format the contents appropriately for the
* internal payload to cut down on the number of scans of the data performed.
*
* We also generate a proposed description from the contents of the key that
* can be used to name the key if the user doesn't want to provide one.
*/
static int asymmetric_key_preparse(struct key_preparsed_payload *prep)
{
struct asymmetric_key_parser *parser;
int ret;
pr_devel("==>%s()\n", __func__);
if (prep->datalen == 0)
return -EINVAL;
down_read(&asymmetric_key_parsers_sem);
ret = -EBADMSG;
list_for_each_entry(parser, &asymmetric_key_parsers, link) {
pr_debug("Trying parser '%s'\n", parser->name);
ret = parser->parse(prep);
if (ret != -EBADMSG) {
pr_debug("Parser recognised the format (ret %d)\n",
ret);
break;
}
}
up_read(&asymmetric_key_parsers_sem);
pr_devel("<==%s() = %d\n", __func__, ret);
return ret;
}
/*
* Clean up the preparse data
*/
static void asymmetric_key_free_preparse(struct key_preparsed_payload *prep)
{
struct asymmetric_key_subtype *subtype = prep->type_data[0];
pr_devel("==>%s()\n", __func__);
if (subtype) {
subtype->destroy(prep->payload[0]);
module_put(subtype->owner);
}
kfree(prep->type_data[1]);
kfree(prep->description);
}
/*
* dispose of the data dangling from the corpse of a asymmetric key
*/
static void asymmetric_key_destroy(struct key *key)
{
struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
if (subtype) {
subtype->destroy(key->payload.data);
module_put(subtype->owner);
key->type_data.p[0] = NULL;
}
kfree(key->type_data.p[1]);
key->type_data.p[1] = NULL;
}
struct key_type key_type_asymmetric = {
.name = "asymmetric",
.preparse = asymmetric_key_preparse,
.free_preparse = asymmetric_key_free_preparse,
.instantiate = generic_key_instantiate,
.match_preparse = asymmetric_key_match_preparse,
.match = asymmetric_key_match,
.match_free = asymmetric_key_match_free,
.destroy = asymmetric_key_destroy,
.describe = asymmetric_key_describe,
};
EXPORT_SYMBOL_GPL(key_type_asymmetric);
/**
* register_asymmetric_key_parser - Register a asymmetric key blob parser
* @parser: The parser to register
*/
int register_asymmetric_key_parser(struct asymmetric_key_parser *parser)
{
struct asymmetric_key_parser *cursor;
int ret;
down_write(&asymmetric_key_parsers_sem);
list_for_each_entry(cursor, &asymmetric_key_parsers, link) {
if (strcmp(cursor->name, parser->name) == 0) {
pr_err("Asymmetric key parser '%s' already registered\n",
parser->name);
ret = -EEXIST;
goto out;
}
}
list_add_tail(&parser->link, &asymmetric_key_parsers);
pr_notice("Asymmetric key parser '%s' registered\n", parser->name);
ret = 0;
out:
up_write(&asymmetric_key_parsers_sem);
return ret;
}
EXPORT_SYMBOL_GPL(register_asymmetric_key_parser);
/**
* unregister_asymmetric_key_parser - Unregister a asymmetric key blob parser
* @parser: The parser to unregister
*/
void unregister_asymmetric_key_parser(struct asymmetric_key_parser *parser)
{
down_write(&asymmetric_key_parsers_sem);
list_del(&parser->link);
up_write(&asymmetric_key_parsers_sem);
pr_notice("Asymmetric key parser '%s' unregistered\n", parser->name);
}
EXPORT_SYMBOL_GPL(unregister_asymmetric_key_parser);
/*
* Module stuff
*/
static int __init asymmetric_key_init(void)
{
return register_key_type(&key_type_asymmetric);
}
static void __exit asymmetric_key_cleanup(void)
{
unregister_key_type(&key_type_asymmetric);
}
module_init(asymmetric_key_init);
module_exit(asymmetric_key_cleanup);
| ./CrossVul/dataset_final_sorted/CWE-476/c/bad_3060_0 |
crossvul-cpp_data_good_5246_10 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* acl.c
*
* Copyright (C) 2004, 2008 Oracle. All rights reserved.
*
* CREDITS:
* Lots of code in this file is copy from linux/fs/ext3/acl.c.
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "dlmglue.h"
#include "file.h"
#include "inode.h"
#include "journal.h"
#include "ocfs2_fs.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from xattr value to acl struct.
*/
static struct posix_acl *ocfs2_acl_from_xattr(const void *value, size_t size)
{
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(struct posix_acl_entry))
return ERR_PTR(-EINVAL);
count = size / sizeof(struct posix_acl_entry);
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
struct ocfs2_acl_entry *entry =
(struct ocfs2_acl_entry *)value;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER:
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
break;
}
value += sizeof(struct posix_acl_entry);
}
return acl;
}
/*
* Convert acl struct to xattr value.
*/
static void *ocfs2_acl_to_xattr(const struct posix_acl *acl, size_t *size)
{
struct ocfs2_acl_entry *entry = NULL;
char *ocfs2_acl;
size_t n;
*size = acl->a_count * sizeof(struct posix_acl_entry);
ocfs2_acl = kmalloc(*size, GFP_NOFS);
if (!ocfs2_acl)
return ERR_PTR(-ENOMEM);
entry = (struct ocfs2_acl_entry *)ocfs2_acl;
for (n = 0; n < acl->a_count; n++, entry++) {
entry->e_tag = cpu_to_le16(acl->a_entries[n].e_tag);
entry->e_perm = cpu_to_le16(acl->a_entries[n].e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns,
acl->a_entries[n].e_uid));
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns,
acl->a_entries[n].e_gid));
break;
default:
entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
break;
}
}
return ocfs2_acl;
}
static struct posix_acl *ocfs2_get_acl_nolock(struct inode *inode,
int type,
struct buffer_head *di_bh)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
retval = ocfs2_xattr_get_nolock(inode, di_bh, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ocfs2_xattr_get_nolock(inode, di_bh, name_index,
"", value, retval);
}
if (retval > 0)
acl = ocfs2_acl_from_xattr(value, retval);
else if (retval == -ENODATA || retval == 0)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* Helper function to set i_mode in memory and disk. Some call paths
* will not have di_bh or a journal handle to pass, in which case it
* will create it's own.
*/
static int ocfs2_acl_set_mode(struct inode *inode, struct buffer_head *di_bh,
handle_t *handle, umode_t new_mode)
{
int ret, commit_handle = 0;
struct ocfs2_dinode *di;
if (di_bh == NULL) {
ret = ocfs2_read_inode_block(inode, &di_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
} else
get_bh(di_bh);
if (handle == NULL) {
handle = ocfs2_start_trans(OCFS2_SB(inode->i_sb),
OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out_brelse;
}
commit_handle = 1;
}
di = (struct ocfs2_dinode *)di_bh->b_data;
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
inode->i_mode = new_mode;
inode->i_ctime = CURRENT_TIME;
di->i_mode = cpu_to_le16(inode->i_mode);
di->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
di->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
ocfs2_update_inode_fsync_trans(handle, inode, 0);
ocfs2_journal_dirty(handle, di_bh);
out_commit:
if (commit_handle)
ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
out_brelse:
brelse(di_bh);
out:
return ret;
}
/*
* Set the access or default ACL of an inode.
*/
int ocfs2_set_acl(handle_t *handle,
struct inode *inode,
struct buffer_head *di_bh,
int type,
struct posix_acl *acl,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_alloc_context *data_ac)
{
int name_index;
void *value = NULL;
size_t size = 0;
int ret;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
umode_t mode;
ret = posix_acl_update_mode(inode, &mode, &acl);
if (ret)
return ret;
ret = ocfs2_acl_set_mode(inode, di_bh,
handle, mode);
if (ret)
return ret;
}
break;
case ACL_TYPE_DEFAULT:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ocfs2_acl_to_xattr(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
if (handle)
ret = ocfs2_xattr_set_handle(handle, inode, di_bh, name_index,
"", value, size, 0,
meta_ac, data_ac);
else
ret = ocfs2_xattr_set(inode, name_index, "", value, size, 0);
kfree(value);
return ret;
}
int ocfs2_iop_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct buffer_head *bh = NULL;
int status = 0;
status = ocfs2_inode_lock(inode, &bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
status = ocfs2_set_acl(NULL, inode, bh, type, acl, NULL, NULL);
ocfs2_inode_unlock(inode, 1);
brelse(bh);
return status;
}
struct posix_acl *ocfs2_iop_get_acl(struct inode *inode, int type)
{
struct ocfs2_super *osb;
struct buffer_head *di_bh = NULL;
struct posix_acl *acl;
int ret;
osb = OCFS2_SB(inode->i_sb);
if (!(osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL))
return NULL;
ret = ocfs2_inode_lock(inode, &di_bh, 0);
if (ret < 0) {
if (ret != -ENOENT)
mlog_errno(ret);
return ERR_PTR(ret);
}
acl = ocfs2_get_acl_nolock(inode, type, di_bh);
ocfs2_inode_unlock(inode, 0);
brelse(di_bh);
return acl;
}
int ocfs2_acl_chmod(struct inode *inode, struct buffer_head *bh)
{
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct posix_acl *acl;
int ret;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!(osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL))
return 0;
acl = ocfs2_get_acl_nolock(inode, ACL_TYPE_ACCESS, bh);
if (IS_ERR(acl) || !acl)
return PTR_ERR(acl);
ret = __posix_acl_chmod(&acl, GFP_KERNEL, inode->i_mode);
if (ret)
return ret;
ret = ocfs2_set_acl(NULL, inode, NULL, ACL_TYPE_ACCESS,
acl, NULL, NULL);
posix_acl_release(acl);
return ret;
}
/*
* Initialize the ACLs of a new inode. If parent directory has default ACL,
* then clone to new inode. Called from ocfs2_mknod.
*/
int ocfs2_init_acl(handle_t *handle,
struct inode *inode,
struct inode *dir,
struct buffer_head *di_bh,
struct buffer_head *dir_bh,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_alloc_context *data_ac)
{
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct posix_acl *acl = NULL;
int ret = 0, ret2;
umode_t mode;
if (!S_ISLNK(inode->i_mode)) {
if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) {
acl = ocfs2_get_acl_nolock(dir, ACL_TYPE_DEFAULT,
dir_bh);
if (IS_ERR(acl))
return PTR_ERR(acl);
}
if (!acl) {
mode = inode->i_mode & ~current_umask();
ret = ocfs2_acl_set_mode(inode, di_bh, handle, mode);
if (ret) {
mlog_errno(ret);
goto cleanup;
}
}
}
if ((osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) && acl) {
if (S_ISDIR(inode->i_mode)) {
ret = ocfs2_set_acl(handle, inode, di_bh,
ACL_TYPE_DEFAULT, acl,
meta_ac, data_ac);
if (ret)
goto cleanup;
}
mode = inode->i_mode;
ret = __posix_acl_create(&acl, GFP_NOFS, &mode);
if (ret < 0)
return ret;
ret2 = ocfs2_acl_set_mode(inode, di_bh, handle, mode);
if (ret2) {
mlog_errno(ret2);
ret = ret2;
goto cleanup;
}
if (ret > 0) {
ret = ocfs2_set_acl(handle, inode,
di_bh, ACL_TYPE_ACCESS,
acl, meta_ac, data_ac);
}
}
cleanup:
posix_acl_release(acl);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_10 |
crossvul-cpp_data_bad_5246_3 | /*
* linux/fs/ext2/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *
ext2_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(ext2_acl_header))
return ERR_PTR(-EINVAL);
if (((ext2_acl_header *)value)->a_version !=
cpu_to_le32(EXT2_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(ext2_acl_header);
count = ext2_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n=0; n < count; n++) {
ext2_acl_entry *entry =
(ext2_acl_entry *)value;
if ((char *)value + sizeof(ext2_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(ext2_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(ext2_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(ext2_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *
ext2_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
ext2_acl_header *ext_acl;
char *e;
size_t n;
*size = ext2_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(ext2_acl_header) + acl->a_count *
sizeof(ext2_acl_entry), GFP_KERNEL);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(EXT2_ACL_VERSION);
e = (char *)ext_acl + sizeof(ext2_acl_header);
for (n=0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext2_acl_entry *entry = (ext2_acl_entry *)e;
entry->e_tag = cpu_to_le16(acl_e->e_tag);
entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(ext2_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(ext2_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(ext2_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* inode->i_mutex: don't care
*/
struct posix_acl *
ext2_get_acl(struct inode *inode, int type)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = ext2_xattr_get(inode, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ext2_xattr_get(inode, name_index, "", value, retval);
}
if (retval > 0)
acl = ext2_acl_from_disk(value, retval);
else if (retval == -ENODATA || retval == -ENOSYS)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* inode->i_mutex: down
*/
int
ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch(type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext2_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext2_xattr_set(inode, name_index, "", value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
/*
* Initialize the ACLs of a new inode. Called from ext2_new_inode.
*
* dir->i_mutex: down
* inode->i_mutex: up (access to inode is still exclusive)
*/
int
ext2_init_acl(struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = ext2_set_acl(inode, default_acl, ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = ext2_set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_3 |
crossvul-cpp_data_good_5246_1 | /*
* Copyright (C) 2007 Red Hat. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/posix_acl.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include "ctree.h"
#include "btrfs_inode.h"
#include "xattr.h"
struct posix_acl *btrfs_get_acl(struct inode *inode, int type)
{
int size;
const char *name;
char *value = NULL;
struct posix_acl *acl;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
size = __btrfs_getxattr(inode, name, "", 0);
if (size > 0) {
value = kzalloc(size, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
size = __btrfs_getxattr(inode, name, value, size);
}
if (size > 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
} else if (size == -ERANGE || size == -ENODATA || size == 0) {
acl = NULL;
} else {
acl = ERR_PTR(-EIO);
}
kfree(value);
return acl;
}
/*
* Needs to be called with fs_mutex held
*/
static int __btrfs_set_acl(struct btrfs_trans_handle *trans,
struct inode *inode, struct posix_acl *acl, int type)
{
int ret, size = 0;
const char *name;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (ret)
return ret;
}
ret = 0;
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode))
return acl ? -EINVAL : 0;
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out;
}
ret = __btrfs_setxattr(trans, inode, name, value, size, 0);
out:
kfree(value);
if (!ret)
set_cached_acl(inode, type, acl);
return ret;
}
int btrfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
return __btrfs_set_acl(NULL, inode, acl, type);
}
/*
* btrfs_init_acl is already generally called under fs_mutex, so the locking
* stuff has been fixed to work with that. If the locking stuff changes, we
* need to re-evaluate the acl locking stuff.
*/
int btrfs_init_acl(struct btrfs_trans_handle *trans,
struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int ret = 0;
/* this happens with subvols */
if (!dir)
return 0;
ret = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (ret)
return ret;
if (default_acl) {
ret = __btrfs_set_acl(trans, inode, default_acl,
ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!ret)
ret = __btrfs_set_acl(trans, inode, acl,
ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
if (!default_acl && !acl)
cache_no_acl(inode);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_1 |
crossvul-cpp_data_good_5246_3 | /*
* linux/fs/ext2/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include "ext2.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *
ext2_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(ext2_acl_header))
return ERR_PTR(-EINVAL);
if (((ext2_acl_header *)value)->a_version !=
cpu_to_le32(EXT2_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(ext2_acl_header);
count = ext2_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n=0; n < count; n++) {
ext2_acl_entry *entry =
(ext2_acl_entry *)value;
if ((char *)value + sizeof(ext2_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(ext2_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(ext2_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(ext2_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *
ext2_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
ext2_acl_header *ext_acl;
char *e;
size_t n;
*size = ext2_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(ext2_acl_header) + acl->a_count *
sizeof(ext2_acl_entry), GFP_KERNEL);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(EXT2_ACL_VERSION);
e = (char *)ext_acl + sizeof(ext2_acl_header);
for (n=0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext2_acl_entry *entry = (ext2_acl_entry *)e;
entry->e_tag = cpu_to_le16(acl_e->e_tag);
entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(ext2_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(ext2_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(ext2_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* inode->i_mutex: don't care
*/
struct posix_acl *
ext2_get_acl(struct inode *inode, int type)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = ext2_xattr_get(inode, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ext2_xattr_get(inode, name_index, "", value, retval);
}
if (retval > 0)
acl = ext2_acl_from_disk(value, retval);
else if (retval == -ENODATA || retval == -ENOSYS)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* inode->i_mutex: down
*/
int
ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch(type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext2_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext2_xattr_set(inode, name_index, "", value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
/*
* Initialize the ACLs of a new inode. Called from ext2_new_inode.
*
* dir->i_mutex: down
* inode->i_mutex: up (access to inode is still exclusive)
*/
int
ext2_init_acl(struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = ext2_set_acl(inode, default_acl, ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = ext2_set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_3 |
crossvul-cpp_data_bad_5246_2 | /*
* linux/fs/ceph/acl.c
*
* Copyright (C) 2013 Guangliang Zhao, <lucienchao@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/ceph/ceph_debug.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/posix_acl.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include "super.h"
static inline void ceph_set_cached_acl(struct inode *inode,
int type, struct posix_acl *acl)
{
struct ceph_inode_info *ci = ceph_inode(inode);
spin_lock(&ci->i_ceph_lock);
if (__ceph_caps_issued_mask(ci, CEPH_CAP_XATTR_SHARED, 0))
set_cached_acl(inode, type, acl);
else
forget_cached_acl(inode, type);
spin_unlock(&ci->i_ceph_lock);
}
struct posix_acl *ceph_get_acl(struct inode *inode, int type)
{
int size;
const char *name;
char *value = NULL;
struct posix_acl *acl;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
size = __ceph_getxattr(inode, name, "", 0);
if (size > 0) {
value = kzalloc(size, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
size = __ceph_getxattr(inode, name, value, size);
}
if (size > 0)
acl = posix_acl_from_xattr(&init_user_ns, value, size);
else if (size == -ERANGE || size == -ENODATA || size == 0)
acl = NULL;
else
acl = ERR_PTR(-EIO);
kfree(value);
if (!IS_ERR(acl))
ceph_set_cached_acl(inode, type, acl);
return acl;
}
int ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int ret = 0, size = 0;
const char *name = NULL;
char *value = NULL;
struct iattr newattrs;
umode_t new_mode = inode->i_mode, old_mode = inode->i_mode;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_equiv_mode(acl, &new_mode);
if (ret < 0)
goto out;
if (ret == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
ret = acl ? -EINVAL : 0;
goto out;
}
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
ret = -EINVAL;
goto out;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_NOFS);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out_free;
}
if (new_mode != old_mode) {
newattrs.ia_mode = new_mode;
newattrs.ia_valid = ATTR_MODE;
ret = __ceph_setattr(inode, &newattrs);
if (ret)
goto out_free;
}
ret = __ceph_setxattr(inode, name, value, size, 0);
if (ret) {
if (new_mode != old_mode) {
newattrs.ia_mode = old_mode;
newattrs.ia_valid = ATTR_MODE;
__ceph_setattr(inode, &newattrs);
}
goto out_free;
}
ceph_set_cached_acl(inode, type, acl);
out_free:
kfree(value);
out:
return ret;
}
int ceph_pre_init_acls(struct inode *dir, umode_t *mode,
struct ceph_acls_info *info)
{
struct posix_acl *acl, *default_acl;
size_t val_size1 = 0, val_size2 = 0;
struct ceph_pagelist *pagelist = NULL;
void *tmp_buf = NULL;
int err;
err = posix_acl_create(dir, mode, &default_acl, &acl);
if (err)
return err;
if (acl) {
int ret = posix_acl_equiv_mode(acl, mode);
if (ret < 0)
goto out_err;
if (ret == 0) {
posix_acl_release(acl);
acl = NULL;
}
}
if (!default_acl && !acl)
return 0;
if (acl)
val_size1 = posix_acl_xattr_size(acl->a_count);
if (default_acl)
val_size2 = posix_acl_xattr_size(default_acl->a_count);
err = -ENOMEM;
tmp_buf = kmalloc(max(val_size1, val_size2), GFP_KERNEL);
if (!tmp_buf)
goto out_err;
pagelist = kmalloc(sizeof(struct ceph_pagelist), GFP_KERNEL);
if (!pagelist)
goto out_err;
ceph_pagelist_init(pagelist);
err = ceph_pagelist_reserve(pagelist, PAGE_SIZE);
if (err)
goto out_err;
ceph_pagelist_encode_32(pagelist, acl && default_acl ? 2 : 1);
if (acl) {
size_t len = strlen(XATTR_NAME_POSIX_ACL_ACCESS);
err = ceph_pagelist_reserve(pagelist, len + val_size1 + 8);
if (err)
goto out_err;
ceph_pagelist_encode_string(pagelist, XATTR_NAME_POSIX_ACL_ACCESS,
len);
err = posix_acl_to_xattr(&init_user_ns, acl,
tmp_buf, val_size1);
if (err < 0)
goto out_err;
ceph_pagelist_encode_32(pagelist, val_size1);
ceph_pagelist_append(pagelist, tmp_buf, val_size1);
}
if (default_acl) {
size_t len = strlen(XATTR_NAME_POSIX_ACL_DEFAULT);
err = ceph_pagelist_reserve(pagelist, len + val_size2 + 8);
if (err)
goto out_err;
err = ceph_pagelist_encode_string(pagelist,
XATTR_NAME_POSIX_ACL_DEFAULT, len);
err = posix_acl_to_xattr(&init_user_ns, default_acl,
tmp_buf, val_size2);
if (err < 0)
goto out_err;
ceph_pagelist_encode_32(pagelist, val_size2);
ceph_pagelist_append(pagelist, tmp_buf, val_size2);
}
kfree(tmp_buf);
info->acl = acl;
info->default_acl = default_acl;
info->pagelist = pagelist;
return 0;
out_err:
posix_acl_release(acl);
posix_acl_release(default_acl);
kfree(tmp_buf);
if (pagelist)
ceph_pagelist_release(pagelist);
return err;
}
void ceph_init_inode_acls(struct inode* inode, struct ceph_acls_info *info)
{
if (!inode)
return;
ceph_set_cached_acl(inode, ACL_TYPE_ACCESS, info->acl);
ceph_set_cached_acl(inode, ACL_TYPE_DEFAULT, info->default_acl);
}
void ceph_release_acls_info(struct ceph_acls_info *info)
{
posix_acl_release(info->acl);
posix_acl_release(info->default_acl);
if (info->pagelist)
ceph_pagelist_release(info->pagelist);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_2 |
crossvul-cpp_data_good_5246_6 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <linux/gfs2_ondisk.h>
#include "gfs2.h"
#include "incore.h"
#include "acl.h"
#include "xattr.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
static const char *gfs2_acl_name(int type)
{
switch (type) {
case ACL_TYPE_ACCESS:
return XATTR_POSIX_ACL_ACCESS;
case ACL_TYPE_DEFAULT:
return XATTR_POSIX_ACL_DEFAULT;
}
return NULL;
}
static struct posix_acl *__gfs2_get_acl(struct inode *inode, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct posix_acl *acl;
const char *name;
char *data;
int len;
if (!ip->i_eattr)
return NULL;
name = gfs2_acl_name(type);
len = gfs2_xattr_acl_get(ip, name, &data);
if (len <= 0)
return ERR_PTR(len);
acl = posix_acl_from_xattr(&init_user_ns, data, len);
kfree(data);
return acl;
}
struct posix_acl *gfs2_get_acl(struct inode *inode, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
bool need_unlock = false;
struct posix_acl *acl;
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
int ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED,
LM_FLAG_ANY, &gh);
if (ret)
return ERR_PTR(ret);
need_unlock = true;
}
acl = __gfs2_get_acl(inode, type);
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
return acl;
}
int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
int len;
char *data;
const char *name = gfs2_acl_name(type);
if (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode)))
return -E2BIG;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
if (mode != inode->i_mode)
mark_inode_dirty(inode);
}
if (acl) {
len = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0);
if (len == 0)
return 0;
data = kmalloc(len, GFP_NOFS);
if (data == NULL)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, data, len);
if (error < 0)
goto out;
} else {
data = NULL;
len = 0;
}
error = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS);
if (error)
goto out;
set_cached_acl(inode, type, acl);
out:
kfree(data);
return error;
}
int gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
bool need_unlock = false;
int ret;
ret = gfs2_rsqa_alloc(ip);
if (ret)
return ret;
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (ret)
return ret;
need_unlock = true;
}
ret = __gfs2_set_acl(inode, acl, type);
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_6 |
crossvul-cpp_data_bad_5246_5 | /*
* fs/f2fs/acl.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Portions of this code from linux/fs/ext2/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/f2fs_fs.h>
#include "f2fs.h"
#include "xattr.h"
#include "acl.h"
static inline size_t f2fs_acl_size(int count)
{
if (count <= 4) {
return sizeof(struct f2fs_acl_header) +
count * sizeof(struct f2fs_acl_entry_short);
} else {
return sizeof(struct f2fs_acl_header) +
4 * sizeof(struct f2fs_acl_entry_short) +
(count - 4) * sizeof(struct f2fs_acl_entry);
}
}
static inline int f2fs_acl_count(size_t size)
{
ssize_t s;
size -= sizeof(struct f2fs_acl_header);
s = size - 4 * sizeof(struct f2fs_acl_entry_short);
if (s < 0) {
if (size % sizeof(struct f2fs_acl_entry_short))
return -1;
return size / sizeof(struct f2fs_acl_entry_short);
} else {
if (s % sizeof(struct f2fs_acl_entry))
return -1;
return s / sizeof(struct f2fs_acl_entry) + 4;
}
}
static struct posix_acl *f2fs_acl_from_disk(const char *value, size_t size)
{
int i, count;
struct posix_acl *acl;
struct f2fs_acl_header *hdr = (struct f2fs_acl_header *)value;
struct f2fs_acl_entry *entry = (struct f2fs_acl_entry *)(hdr + 1);
const char *end = value + size;
if (hdr->a_version != cpu_to_le32(F2FS_ACL_VERSION))
return ERR_PTR(-EINVAL);
count = f2fs_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
if ((char *)entry > end)
goto fail;
acl->a_entries[i].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[i].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[i].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry_short));
break;
case ACL_USER:
acl->a_entries[i].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
case ACL_GROUP:
acl->a_entries[i].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
default:
goto fail;
}
}
if ((char *)entry != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
static void *f2fs_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
struct f2fs_acl_header *f2fs_acl;
struct f2fs_acl_entry *entry;
int i;
f2fs_acl = f2fs_kmalloc(sizeof(struct f2fs_acl_header) + acl->a_count *
sizeof(struct f2fs_acl_entry), GFP_NOFS);
if (!f2fs_acl)
return ERR_PTR(-ENOMEM);
f2fs_acl->a_version = cpu_to_le32(F2FS_ACL_VERSION);
entry = (struct f2fs_acl_entry *)(f2fs_acl + 1);
for (i = 0; i < acl->a_count; i++) {
entry->e_tag = cpu_to_le16(acl->a_entries[i].e_tag);
entry->e_perm = cpu_to_le16(acl->a_entries[i].e_perm);
switch (acl->a_entries[i].e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns,
acl->a_entries[i].e_uid));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns,
acl->a_entries[i].e_gid));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry_short));
break;
default:
goto fail;
}
}
*size = f2fs_acl_size(acl->a_count);
return (void *)f2fs_acl;
fail:
kfree(f2fs_acl);
return ERR_PTR(-EINVAL);
}
static struct posix_acl *__f2fs_get_acl(struct inode *inode, int type,
struct page *dpage)
{
int name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
void *value = NULL;
struct posix_acl *acl;
int retval;
if (type == ACL_TYPE_ACCESS)
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
retval = f2fs_getxattr(inode, name_index, "", NULL, 0, dpage);
if (retval > 0) {
value = f2fs_kmalloc(retval, GFP_F2FS_ZERO);
if (!value)
return ERR_PTR(-ENOMEM);
retval = f2fs_getxattr(inode, name_index, "", value,
retval, dpage);
}
if (retval > 0)
acl = f2fs_acl_from_disk(value, retval);
else if (retval == -ENODATA)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
struct posix_acl *f2fs_get_acl(struct inode *inode, int type)
{
return __f2fs_get_acl(inode, type, NULL);
}
static int __f2fs_set_acl(struct inode *inode, int type,
struct posix_acl *acl, struct page *ipage)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
set_acl_inode(inode, inode->i_mode);
if (error == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = f2fs_acl_to_disk(acl, &size);
if (IS_ERR(value)) {
clear_inode_flag(inode, FI_ACL_MODE);
return (int)PTR_ERR(value);
}
}
error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
clear_inode_flag(inode, FI_ACL_MODE);
return error;
}
int f2fs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
return __f2fs_set_acl(inode, type, acl, NULL);
}
/*
* Most part of f2fs_acl_clone, f2fs_acl_create_masq, f2fs_acl_create
* are copied from posix_acl.c
*/
static struct posix_acl *f2fs_acl_clone(const struct posix_acl *acl,
gfp_t flags)
{
struct posix_acl *clone = NULL;
if (acl) {
int size = sizeof(struct posix_acl) + acl->a_count *
sizeof(struct posix_acl_entry);
clone = kmemdup(acl, size, flags);
if (clone)
atomic_set(&clone->a_refcount, 1);
}
return clone;
}
static int f2fs_acl_create_masq(struct posix_acl *acl, umode_t *mode_p)
{
struct posix_acl_entry *pa, *pe;
struct posix_acl_entry *group_obj = NULL, *mask_obj = NULL;
umode_t mode = *mode_p;
int not_equiv = 0;
/* assert(atomic_read(acl->a_refcount) == 1); */
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
pa->e_perm &= (mode >> 6) | ~S_IRWXO;
mode &= (pa->e_perm << 6) | ~S_IRWXU;
break;
case ACL_USER:
case ACL_GROUP:
not_equiv = 1;
break;
case ACL_GROUP_OBJ:
group_obj = pa;
break;
case ACL_OTHER:
pa->e_perm &= mode | ~S_IRWXO;
mode &= pa->e_perm | ~S_IRWXO;
break;
case ACL_MASK:
mask_obj = pa;
not_equiv = 1;
break;
default:
return -EIO;
}
}
if (mask_obj) {
mask_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (mask_obj->e_perm << 3) | ~S_IRWXG;
} else {
if (!group_obj)
return -EIO;
group_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (group_obj->e_perm << 3) | ~S_IRWXG;
}
*mode_p = (*mode_p & ~S_IRWXUGO) | mode;
return not_equiv;
}
static int f2fs_acl_create(struct inode *dir, umode_t *mode,
struct posix_acl **default_acl, struct posix_acl **acl,
struct page *dpage)
{
struct posix_acl *p;
struct posix_acl *clone;
int ret;
*acl = NULL;
*default_acl = NULL;
if (S_ISLNK(*mode) || !IS_POSIXACL(dir))
return 0;
p = __f2fs_get_acl(dir, ACL_TYPE_DEFAULT, dpage);
if (!p || p == ERR_PTR(-EOPNOTSUPP)) {
*mode &= ~current_umask();
return 0;
}
if (IS_ERR(p))
return PTR_ERR(p);
clone = f2fs_acl_clone(p, GFP_NOFS);
if (!clone)
goto no_mem;
ret = f2fs_acl_create_masq(clone, mode);
if (ret < 0)
goto no_mem_clone;
if (ret == 0)
posix_acl_release(clone);
else
*acl = clone;
if (!S_ISDIR(*mode))
posix_acl_release(p);
else
*default_acl = p;
return 0;
no_mem_clone:
posix_acl_release(clone);
no_mem:
posix_acl_release(p);
return -ENOMEM;
}
int f2fs_init_acl(struct inode *inode, struct inode *dir, struct page *ipage,
struct page *dpage)
{
struct posix_acl *default_acl = NULL, *acl = NULL;
int error = 0;
error = f2fs_acl_create(dir, &inode->i_mode, &default_acl, &acl, dpage);
if (error)
return error;
f2fs_mark_inode_dirty_sync(inode);
if (default_acl) {
error = __f2fs_set_acl(inode, ACL_TYPE_DEFAULT, default_acl,
ipage);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = __f2fs_set_acl(inode, ACL_TYPE_ACCESS, acl,
ipage);
posix_acl_release(acl);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_5 |
crossvul-cpp_data_good_5246_0 | /*
* Copyright IBM Corporation, 2010
* Author Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2.1 of the GNU Lesser General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <net/9p/9p.h>
#include <net/9p/client.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/posix_acl_xattr.h>
#include "xattr.h"
#include "acl.h"
#include "v9fs.h"
#include "v9fs_vfs.h"
#include "fid.h"
static struct posix_acl *__v9fs_get_acl(struct p9_fid *fid, char *name)
{
ssize_t size;
void *value = NULL;
struct posix_acl *acl = NULL;
size = v9fs_fid_xattr_get(fid, name, NULL, 0);
if (size > 0) {
value = kzalloc(size, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
size = v9fs_fid_xattr_get(fid, name, value, size);
if (size > 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
goto err_out;
}
} else if (size == -ENODATA || size == 0 ||
size == -ENOSYS || size == -EOPNOTSUPP) {
acl = NULL;
} else
acl = ERR_PTR(-EIO);
err_out:
kfree(value);
return acl;
}
int v9fs_get_acl(struct inode *inode, struct p9_fid *fid)
{
int retval = 0;
struct posix_acl *pacl, *dacl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_inode2v9ses(inode);
if (((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) ||
((v9ses->flags & V9FS_ACL_MASK) != V9FS_POSIX_ACL)) {
set_cached_acl(inode, ACL_TYPE_DEFAULT, NULL);
set_cached_acl(inode, ACL_TYPE_ACCESS, NULL);
return 0;
}
/* get the default/access acl values and cache them */
dacl = __v9fs_get_acl(fid, XATTR_NAME_POSIX_ACL_DEFAULT);
pacl = __v9fs_get_acl(fid, XATTR_NAME_POSIX_ACL_ACCESS);
if (!IS_ERR(dacl) && !IS_ERR(pacl)) {
set_cached_acl(inode, ACL_TYPE_DEFAULT, dacl);
set_cached_acl(inode, ACL_TYPE_ACCESS, pacl);
} else
retval = -EIO;
if (!IS_ERR(dacl))
posix_acl_release(dacl);
if (!IS_ERR(pacl))
posix_acl_release(pacl);
return retval;
}
static struct posix_acl *v9fs_get_cached_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
/*
* 9p Always cache the acl value when
* instantiating the inode (v9fs_inode_from_fid)
*/
acl = get_cached_acl(inode, type);
BUG_ON(is_uncached_acl(acl));
return acl;
}
struct posix_acl *v9fs_iop_get_acl(struct inode *inode, int type)
{
struct v9fs_session_info *v9ses;
v9ses = v9fs_inode2v9ses(inode);
if (((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) ||
((v9ses->flags & V9FS_ACL_MASK) != V9FS_POSIX_ACL)) {
/*
* On access = client and acl = on mode get the acl
* values from the server
*/
return NULL;
}
return v9fs_get_cached_acl(inode, type);
}
static int v9fs_set_acl(struct p9_fid *fid, int type, struct posix_acl *acl)
{
int retval;
char *name;
size_t size;
void *buffer;
if (!acl)
return 0;
/* Set a setxattr request to server */
size = posix_acl_xattr_size(acl->a_count);
buffer = kmalloc(size, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
retval = posix_acl_to_xattr(&init_user_ns, acl, buffer, size);
if (retval < 0)
goto err_free_out;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = v9fs_fid_xattr_set(fid, name, buffer, size, 0);
err_free_out:
kfree(buffer);
return retval;
}
int v9fs_acl_chmod(struct inode *inode, struct p9_fid *fid)
{
int retval = 0;
struct posix_acl *acl;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
acl = v9fs_get_cached_acl(inode, ACL_TYPE_ACCESS);
if (acl) {
retval = __posix_acl_chmod(&acl, GFP_KERNEL, inode->i_mode);
if (retval)
return retval;
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
retval = v9fs_set_acl(fid, ACL_TYPE_ACCESS, acl);
posix_acl_release(acl);
}
return retval;
}
int v9fs_set_create_acl(struct inode *inode, struct p9_fid *fid,
struct posix_acl *dacl, struct posix_acl *acl)
{
set_cached_acl(inode, ACL_TYPE_DEFAULT, dacl);
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
v9fs_set_acl(fid, ACL_TYPE_DEFAULT, dacl);
v9fs_set_acl(fid, ACL_TYPE_ACCESS, acl);
return 0;
}
void v9fs_put_acl(struct posix_acl *dacl,
struct posix_acl *acl)
{
posix_acl_release(dacl);
posix_acl_release(acl);
}
int v9fs_acl_mode(struct inode *dir, umode_t *modep,
struct posix_acl **dpacl, struct posix_acl **pacl)
{
int retval = 0;
umode_t mode = *modep;
struct posix_acl *acl = NULL;
if (!S_ISLNK(mode)) {
acl = v9fs_get_cached_acl(dir, ACL_TYPE_DEFAULT);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (!acl)
mode &= ~current_umask();
}
if (acl) {
if (S_ISDIR(mode))
*dpacl = posix_acl_dup(acl);
retval = __posix_acl_create(&acl, GFP_NOFS, &mode);
if (retval < 0)
return retval;
if (retval > 0)
*pacl = acl;
else
posix_acl_release(acl);
}
*modep = mode;
return 0;
}
static int v9fs_xattr_get_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, void *buffer, size_t size)
{
struct v9fs_session_info *v9ses;
struct posix_acl *acl;
int error;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* We allow set/get/list of acl when access=client is not specified
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_get(dentry, handler->name, buffer, size);
acl = v9fs_get_cached_acl(inode, handler->flags);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (acl == NULL)
return -ENODATA;
error = posix_acl_to_xattr(&init_user_ns, acl, buffer, size);
posix_acl_release(acl);
return error;
}
static int v9fs_xattr_set_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
int retval;
struct posix_acl *acl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* set the attribute on the remote. Without even looking at the
* xattr value. We leave it to the server to validate
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_set(dentry, handler->name, value, size,
flags);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value) {
/* update the cached acl value */
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
else if (acl) {
retval = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (retval)
goto err_out;
}
} else
acl = NULL;
switch (handler->flags) {
case ACL_TYPE_ACCESS:
if (acl) {
struct iattr iattr;
retval = posix_acl_update_mode(inode, &iattr.ia_mode, &acl);
if (retval)
goto err_out;
if (!acl) {
/*
* ACL can be represented
* by the mode bits. So don't
* update ACL.
*/
value = NULL;
size = 0;
}
iattr.ia_valid = ATTR_MODE;
/* FIXME should we update ctime ?
* What is the following setxattr update the
* mode ?
*/
v9fs_vfs_setattr_dotl(dentry, &iattr);
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
retval = acl ? -EINVAL : 0;
goto err_out;
}
break;
default:
BUG();
}
retval = v9fs_xattr_set(dentry, handler->name, value, size, flags);
if (!retval)
set_cached_acl(inode, handler->flags, acl);
err_out:
posix_acl_release(acl);
return retval;
}
const struct xattr_handler v9fs_xattr_acl_access_handler = {
.name = XATTR_NAME_POSIX_ACL_ACCESS,
.flags = ACL_TYPE_ACCESS,
.get = v9fs_xattr_get_acl,
.set = v9fs_xattr_set_acl,
};
const struct xattr_handler v9fs_xattr_acl_default_handler = {
.name = XATTR_NAME_POSIX_ACL_DEFAULT,
.flags = ACL_TYPE_DEFAULT,
.get = v9fs_xattr_get_acl,
.set = v9fs_xattr_set_acl,
};
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_0 |
crossvul-cpp_data_bad_5246_6 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <linux/gfs2_ondisk.h>
#include "gfs2.h"
#include "incore.h"
#include "acl.h"
#include "xattr.h"
#include "glock.h"
#include "inode.h"
#include "meta_io.h"
#include "rgrp.h"
#include "trans.h"
#include "util.h"
static const char *gfs2_acl_name(int type)
{
switch (type) {
case ACL_TYPE_ACCESS:
return XATTR_POSIX_ACL_ACCESS;
case ACL_TYPE_DEFAULT:
return XATTR_POSIX_ACL_DEFAULT;
}
return NULL;
}
static struct posix_acl *__gfs2_get_acl(struct inode *inode, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct posix_acl *acl;
const char *name;
char *data;
int len;
if (!ip->i_eattr)
return NULL;
name = gfs2_acl_name(type);
len = gfs2_xattr_acl_get(ip, name, &data);
if (len <= 0)
return ERR_PTR(len);
acl = posix_acl_from_xattr(&init_user_ns, data, len);
kfree(data);
return acl;
}
struct posix_acl *gfs2_get_acl(struct inode *inode, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
bool need_unlock = false;
struct posix_acl *acl;
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
int ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED,
LM_FLAG_ANY, &gh);
if (ret)
return ERR_PTR(ret);
need_unlock = true;
}
acl = __gfs2_get_acl(inode, type);
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
return acl;
}
int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
int len;
char *data;
const char *name = gfs2_acl_name(type);
if (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode)))
return -E2BIG;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_equiv_mode(acl, &mode);
if (error < 0)
return error;
if (error == 0)
acl = NULL;
if (mode != inode->i_mode) {
inode->i_mode = mode;
mark_inode_dirty(inode);
}
}
if (acl) {
len = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0);
if (len == 0)
return 0;
data = kmalloc(len, GFP_NOFS);
if (data == NULL)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, data, len);
if (error < 0)
goto out;
} else {
data = NULL;
len = 0;
}
error = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS);
if (error)
goto out;
set_cached_acl(inode, type, acl);
out:
kfree(data);
return error;
}
int gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
bool need_unlock = false;
int ret;
ret = gfs2_rsqa_alloc(ip);
if (ret)
return ret;
if (!gfs2_glock_is_locked_by_me(ip->i_gl)) {
ret = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &gh);
if (ret)
return ret;
need_unlock = true;
}
ret = __gfs2_set_acl(inode, acl, type);
if (need_unlock)
gfs2_glock_dq_uninit(&gh);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_6 |
crossvul-cpp_data_good_5246_5 | /*
* fs/f2fs/acl.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Portions of this code from linux/fs/ext2/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/f2fs_fs.h>
#include "f2fs.h"
#include "xattr.h"
#include "acl.h"
static inline size_t f2fs_acl_size(int count)
{
if (count <= 4) {
return sizeof(struct f2fs_acl_header) +
count * sizeof(struct f2fs_acl_entry_short);
} else {
return sizeof(struct f2fs_acl_header) +
4 * sizeof(struct f2fs_acl_entry_short) +
(count - 4) * sizeof(struct f2fs_acl_entry);
}
}
static inline int f2fs_acl_count(size_t size)
{
ssize_t s;
size -= sizeof(struct f2fs_acl_header);
s = size - 4 * sizeof(struct f2fs_acl_entry_short);
if (s < 0) {
if (size % sizeof(struct f2fs_acl_entry_short))
return -1;
return size / sizeof(struct f2fs_acl_entry_short);
} else {
if (s % sizeof(struct f2fs_acl_entry))
return -1;
return s / sizeof(struct f2fs_acl_entry) + 4;
}
}
static struct posix_acl *f2fs_acl_from_disk(const char *value, size_t size)
{
int i, count;
struct posix_acl *acl;
struct f2fs_acl_header *hdr = (struct f2fs_acl_header *)value;
struct f2fs_acl_entry *entry = (struct f2fs_acl_entry *)(hdr + 1);
const char *end = value + size;
if (hdr->a_version != cpu_to_le32(F2FS_ACL_VERSION))
return ERR_PTR(-EINVAL);
count = f2fs_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
if ((char *)entry > end)
goto fail;
acl->a_entries[i].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[i].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[i].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry_short));
break;
case ACL_USER:
acl->a_entries[i].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
case ACL_GROUP:
acl->a_entries[i].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
default:
goto fail;
}
}
if ((char *)entry != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
static void *f2fs_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
struct f2fs_acl_header *f2fs_acl;
struct f2fs_acl_entry *entry;
int i;
f2fs_acl = f2fs_kmalloc(sizeof(struct f2fs_acl_header) + acl->a_count *
sizeof(struct f2fs_acl_entry), GFP_NOFS);
if (!f2fs_acl)
return ERR_PTR(-ENOMEM);
f2fs_acl->a_version = cpu_to_le32(F2FS_ACL_VERSION);
entry = (struct f2fs_acl_entry *)(f2fs_acl + 1);
for (i = 0; i < acl->a_count; i++) {
entry->e_tag = cpu_to_le16(acl->a_entries[i].e_tag);
entry->e_perm = cpu_to_le16(acl->a_entries[i].e_perm);
switch (acl->a_entries[i].e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns,
acl->a_entries[i].e_uid));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns,
acl->a_entries[i].e_gid));
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry));
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
entry = (struct f2fs_acl_entry *)((char *)entry +
sizeof(struct f2fs_acl_entry_short));
break;
default:
goto fail;
}
}
*size = f2fs_acl_size(acl->a_count);
return (void *)f2fs_acl;
fail:
kfree(f2fs_acl);
return ERR_PTR(-EINVAL);
}
static struct posix_acl *__f2fs_get_acl(struct inode *inode, int type,
struct page *dpage)
{
int name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
void *value = NULL;
struct posix_acl *acl;
int retval;
if (type == ACL_TYPE_ACCESS)
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
retval = f2fs_getxattr(inode, name_index, "", NULL, 0, dpage);
if (retval > 0) {
value = f2fs_kmalloc(retval, GFP_F2FS_ZERO);
if (!value)
return ERR_PTR(-ENOMEM);
retval = f2fs_getxattr(inode, name_index, "", value,
retval, dpage);
}
if (retval > 0)
acl = f2fs_acl_from_disk(value, retval);
else if (retval == -ENODATA)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
struct posix_acl *f2fs_get_acl(struct inode *inode, int type)
{
return __f2fs_get_acl(inode, type, NULL);
}
static int __f2fs_set_acl(struct inode *inode, int type,
struct posix_acl *acl, struct page *ipage)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
set_acl_inode(inode, inode->i_mode);
}
break;
case ACL_TYPE_DEFAULT:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = f2fs_acl_to_disk(acl, &size);
if (IS_ERR(value)) {
clear_inode_flag(inode, FI_ACL_MODE);
return (int)PTR_ERR(value);
}
}
error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
clear_inode_flag(inode, FI_ACL_MODE);
return error;
}
int f2fs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
return __f2fs_set_acl(inode, type, acl, NULL);
}
/*
* Most part of f2fs_acl_clone, f2fs_acl_create_masq, f2fs_acl_create
* are copied from posix_acl.c
*/
static struct posix_acl *f2fs_acl_clone(const struct posix_acl *acl,
gfp_t flags)
{
struct posix_acl *clone = NULL;
if (acl) {
int size = sizeof(struct posix_acl) + acl->a_count *
sizeof(struct posix_acl_entry);
clone = kmemdup(acl, size, flags);
if (clone)
atomic_set(&clone->a_refcount, 1);
}
return clone;
}
static int f2fs_acl_create_masq(struct posix_acl *acl, umode_t *mode_p)
{
struct posix_acl_entry *pa, *pe;
struct posix_acl_entry *group_obj = NULL, *mask_obj = NULL;
umode_t mode = *mode_p;
int not_equiv = 0;
/* assert(atomic_read(acl->a_refcount) == 1); */
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
pa->e_perm &= (mode >> 6) | ~S_IRWXO;
mode &= (pa->e_perm << 6) | ~S_IRWXU;
break;
case ACL_USER:
case ACL_GROUP:
not_equiv = 1;
break;
case ACL_GROUP_OBJ:
group_obj = pa;
break;
case ACL_OTHER:
pa->e_perm &= mode | ~S_IRWXO;
mode &= pa->e_perm | ~S_IRWXO;
break;
case ACL_MASK:
mask_obj = pa;
not_equiv = 1;
break;
default:
return -EIO;
}
}
if (mask_obj) {
mask_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (mask_obj->e_perm << 3) | ~S_IRWXG;
} else {
if (!group_obj)
return -EIO;
group_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (group_obj->e_perm << 3) | ~S_IRWXG;
}
*mode_p = (*mode_p & ~S_IRWXUGO) | mode;
return not_equiv;
}
static int f2fs_acl_create(struct inode *dir, umode_t *mode,
struct posix_acl **default_acl, struct posix_acl **acl,
struct page *dpage)
{
struct posix_acl *p;
struct posix_acl *clone;
int ret;
*acl = NULL;
*default_acl = NULL;
if (S_ISLNK(*mode) || !IS_POSIXACL(dir))
return 0;
p = __f2fs_get_acl(dir, ACL_TYPE_DEFAULT, dpage);
if (!p || p == ERR_PTR(-EOPNOTSUPP)) {
*mode &= ~current_umask();
return 0;
}
if (IS_ERR(p))
return PTR_ERR(p);
clone = f2fs_acl_clone(p, GFP_NOFS);
if (!clone)
goto no_mem;
ret = f2fs_acl_create_masq(clone, mode);
if (ret < 0)
goto no_mem_clone;
if (ret == 0)
posix_acl_release(clone);
else
*acl = clone;
if (!S_ISDIR(*mode))
posix_acl_release(p);
else
*default_acl = p;
return 0;
no_mem_clone:
posix_acl_release(clone);
no_mem:
posix_acl_release(p);
return -ENOMEM;
}
int f2fs_init_acl(struct inode *inode, struct inode *dir, struct page *ipage,
struct page *dpage)
{
struct posix_acl *default_acl = NULL, *acl = NULL;
int error = 0;
error = f2fs_acl_create(dir, &inode->i_mode, &default_acl, &acl, dpage);
if (error)
return error;
f2fs_mark_inode_dirty_sync(inode);
if (default_acl) {
error = __f2fs_set_acl(inode, ACL_TYPE_DEFAULT, default_acl,
ipage);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = __f2fs_set_acl(inode, ACL_TYPE_ACCESS, acl,
ipage);
posix_acl_release(acl);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_5 |
crossvul-cpp_data_bad_5246_10 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* acl.c
*
* Copyright (C) 2004, 2008 Oracle. All rights reserved.
*
* CREDITS:
* Lots of code in this file is copy from linux/fs/ext3/acl.c.
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "dlmglue.h"
#include "file.h"
#include "inode.h"
#include "journal.h"
#include "ocfs2_fs.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from xattr value to acl struct.
*/
static struct posix_acl *ocfs2_acl_from_xattr(const void *value, size_t size)
{
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(struct posix_acl_entry))
return ERR_PTR(-EINVAL);
count = size / sizeof(struct posix_acl_entry);
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
struct ocfs2_acl_entry *entry =
(struct ocfs2_acl_entry *)value;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER:
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
break;
}
value += sizeof(struct posix_acl_entry);
}
return acl;
}
/*
* Convert acl struct to xattr value.
*/
static void *ocfs2_acl_to_xattr(const struct posix_acl *acl, size_t *size)
{
struct ocfs2_acl_entry *entry = NULL;
char *ocfs2_acl;
size_t n;
*size = acl->a_count * sizeof(struct posix_acl_entry);
ocfs2_acl = kmalloc(*size, GFP_NOFS);
if (!ocfs2_acl)
return ERR_PTR(-ENOMEM);
entry = (struct ocfs2_acl_entry *)ocfs2_acl;
for (n = 0; n < acl->a_count; n++, entry++) {
entry->e_tag = cpu_to_le16(acl->a_entries[n].e_tag);
entry->e_perm = cpu_to_le16(acl->a_entries[n].e_perm);
switch(acl->a_entries[n].e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns,
acl->a_entries[n].e_uid));
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns,
acl->a_entries[n].e_gid));
break;
default:
entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
break;
}
}
return ocfs2_acl;
}
static struct posix_acl *ocfs2_get_acl_nolock(struct inode *inode,
int type,
struct buffer_head *di_bh)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
retval = ocfs2_xattr_get_nolock(inode, di_bh, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ocfs2_xattr_get_nolock(inode, di_bh, name_index,
"", value, retval);
}
if (retval > 0)
acl = ocfs2_acl_from_xattr(value, retval);
else if (retval == -ENODATA || retval == 0)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* Helper function to set i_mode in memory and disk. Some call paths
* will not have di_bh or a journal handle to pass, in which case it
* will create it's own.
*/
static int ocfs2_acl_set_mode(struct inode *inode, struct buffer_head *di_bh,
handle_t *handle, umode_t new_mode)
{
int ret, commit_handle = 0;
struct ocfs2_dinode *di;
if (di_bh == NULL) {
ret = ocfs2_read_inode_block(inode, &di_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
} else
get_bh(di_bh);
if (handle == NULL) {
handle = ocfs2_start_trans(OCFS2_SB(inode->i_sb),
OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out_brelse;
}
commit_handle = 1;
}
di = (struct ocfs2_dinode *)di_bh->b_data;
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
inode->i_mode = new_mode;
inode->i_ctime = CURRENT_TIME;
di->i_mode = cpu_to_le16(inode->i_mode);
di->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
di->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
ocfs2_update_inode_fsync_trans(handle, inode, 0);
ocfs2_journal_dirty(handle, di_bh);
out_commit:
if (commit_handle)
ocfs2_commit_trans(OCFS2_SB(inode->i_sb), handle);
out_brelse:
brelse(di_bh);
out:
return ret;
}
/*
* Set the access or default ACL of an inode.
*/
int ocfs2_set_acl(handle_t *handle,
struct inode *inode,
struct buffer_head *di_bh,
int type,
struct posix_acl *acl,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_alloc_context *data_ac)
{
int name_index;
void *value = NULL;
size_t size = 0;
int ret;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
umode_t mode = inode->i_mode;
ret = posix_acl_equiv_mode(acl, &mode);
if (ret < 0)
return ret;
if (ret == 0)
acl = NULL;
ret = ocfs2_acl_set_mode(inode, di_bh,
handle, mode);
if (ret)
return ret;
}
break;
case ACL_TYPE_DEFAULT:
name_index = OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ocfs2_acl_to_xattr(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
if (handle)
ret = ocfs2_xattr_set_handle(handle, inode, di_bh, name_index,
"", value, size, 0,
meta_ac, data_ac);
else
ret = ocfs2_xattr_set(inode, name_index, "", value, size, 0);
kfree(value);
return ret;
}
int ocfs2_iop_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct buffer_head *bh = NULL;
int status = 0;
status = ocfs2_inode_lock(inode, &bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
return status;
}
status = ocfs2_set_acl(NULL, inode, bh, type, acl, NULL, NULL);
ocfs2_inode_unlock(inode, 1);
brelse(bh);
return status;
}
struct posix_acl *ocfs2_iop_get_acl(struct inode *inode, int type)
{
struct ocfs2_super *osb;
struct buffer_head *di_bh = NULL;
struct posix_acl *acl;
int ret;
osb = OCFS2_SB(inode->i_sb);
if (!(osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL))
return NULL;
ret = ocfs2_inode_lock(inode, &di_bh, 0);
if (ret < 0) {
if (ret != -ENOENT)
mlog_errno(ret);
return ERR_PTR(ret);
}
acl = ocfs2_get_acl_nolock(inode, type, di_bh);
ocfs2_inode_unlock(inode, 0);
brelse(di_bh);
return acl;
}
int ocfs2_acl_chmod(struct inode *inode, struct buffer_head *bh)
{
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct posix_acl *acl;
int ret;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!(osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL))
return 0;
acl = ocfs2_get_acl_nolock(inode, ACL_TYPE_ACCESS, bh);
if (IS_ERR(acl) || !acl)
return PTR_ERR(acl);
ret = __posix_acl_chmod(&acl, GFP_KERNEL, inode->i_mode);
if (ret)
return ret;
ret = ocfs2_set_acl(NULL, inode, NULL, ACL_TYPE_ACCESS,
acl, NULL, NULL);
posix_acl_release(acl);
return ret;
}
/*
* Initialize the ACLs of a new inode. If parent directory has default ACL,
* then clone to new inode. Called from ocfs2_mknod.
*/
int ocfs2_init_acl(handle_t *handle,
struct inode *inode,
struct inode *dir,
struct buffer_head *di_bh,
struct buffer_head *dir_bh,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_alloc_context *data_ac)
{
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct posix_acl *acl = NULL;
int ret = 0, ret2;
umode_t mode;
if (!S_ISLNK(inode->i_mode)) {
if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) {
acl = ocfs2_get_acl_nolock(dir, ACL_TYPE_DEFAULT,
dir_bh);
if (IS_ERR(acl))
return PTR_ERR(acl);
}
if (!acl) {
mode = inode->i_mode & ~current_umask();
ret = ocfs2_acl_set_mode(inode, di_bh, handle, mode);
if (ret) {
mlog_errno(ret);
goto cleanup;
}
}
}
if ((osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) && acl) {
if (S_ISDIR(inode->i_mode)) {
ret = ocfs2_set_acl(handle, inode, di_bh,
ACL_TYPE_DEFAULT, acl,
meta_ac, data_ac);
if (ret)
goto cleanup;
}
mode = inode->i_mode;
ret = __posix_acl_create(&acl, GFP_NOFS, &mode);
if (ret < 0)
return ret;
ret2 = ocfs2_acl_set_mode(inode, di_bh, handle, mode);
if (ret2) {
mlog_errno(ret2);
ret = ret2;
goto cleanup;
}
if (ret > 0) {
ret = ocfs2_set_acl(handle, inode,
di_bh, ACL_TYPE_ACCESS,
acl, meta_ac, data_ac);
}
}
cleanup:
posix_acl_release(acl);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_10 |
crossvul-cpp_data_good_5246_7 | /*
* linux/fs/hfsplus/posix_acl.c
*
* Vyacheslav Dubeyko <slava@dubeyko.com>
*
* Handler for Posix Access Control Lists (ACLs) support.
*/
#include "hfsplus_fs.h"
#include "xattr.h"
#include "acl.h"
struct posix_acl *hfsplus_get_posix_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
char *xattr_name;
char *value = NULL;
ssize_t size;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
size = __hfsplus_getxattr(inode, xattr_name, NULL, 0);
if (size > 0) {
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return ERR_PTR(-ENOMEM);
size = __hfsplus_getxattr(inode, xattr_name, value, size);
}
if (size > 0)
acl = posix_acl_from_xattr(&init_user_ns, value, size);
else if (size == -ENODATA)
acl = NULL;
else
acl = ERR_PTR(size);
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
return acl;
}
int hfsplus_set_posix_acl(struct inode *inode, struct posix_acl *acl,
int type)
{
int err;
char *xattr_name;
size_t size = 0;
char *value = NULL;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
err = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (err)
return err;
}
err = 0;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
if (unlikely(size > HFSPLUS_MAX_INLINE_DATA_SIZE))
return -ENOMEM;
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return -ENOMEM;
err = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (unlikely(err < 0))
goto end_set_acl;
}
err = __hfsplus_setxattr(inode, xattr_name, value, size, 0);
end_set_acl:
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
if (!err)
set_cached_acl(inode, type, acl);
return err;
}
int hfsplus_init_posix_acl(struct inode *inode, struct inode *dir)
{
int err = 0;
struct posix_acl *default_acl, *acl;
hfs_dbg(ACL_MOD,
"[%s]: ino %lu, dir->ino %lu\n",
__func__, inode->i_ino, dir->i_ino);
if (S_ISLNK(inode->i_mode))
return 0;
err = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (err)
return err;
if (default_acl) {
err = hfsplus_set_posix_acl(inode, default_acl,
ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!err)
err = hfsplus_set_posix_acl(inode, acl,
ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_7 |
crossvul-cpp_data_good_5246_14 | /*
* Copyright (c) 2008, Christoph Hellwig
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_mount.h"
#include "xfs_inode.h"
#include "xfs_acl.h"
#include "xfs_attr.h"
#include "xfs_trace.h"
#include <linux/slab.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
/*
* Locking scheme:
* - all ACL updates are protected by inode->i_mutex, which is taken before
* calling into this file.
*/
STATIC struct posix_acl *
xfs_acl_from_disk(
const struct xfs_acl *aclp,
int len,
int max_entries)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
const struct xfs_acl_entry *ace;
unsigned int count, i;
if (len < sizeof(*aclp))
return ERR_PTR(-EFSCORRUPTED);
count = be32_to_cpu(aclp->acl_cnt);
if (count > max_entries || XFS_ACL_SIZE(count) != len)
return ERR_PTR(-EFSCORRUPTED);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
acl_e->e_uid = xfs_uid_to_kuid(be32_to_cpu(ace->ae_id));
break;
case ACL_GROUP:
acl_e->e_gid = xfs_gid_to_kgid(be32_to_cpu(ace->ae_id));
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
STATIC void
xfs_acl_to_disk(struct xfs_acl *aclp, const struct posix_acl *acl)
{
const struct posix_acl_entry *acl_e;
struct xfs_acl_entry *ace;
int i;
aclp->acl_cnt = cpu_to_be32(acl->a_count);
for (i = 0; i < acl->a_count; i++) {
ace = &aclp->acl_entry[i];
acl_e = &acl->a_entries[i];
ace->ae_tag = cpu_to_be32(acl_e->e_tag);
switch (acl_e->e_tag) {
case ACL_USER:
ace->ae_id = cpu_to_be32(xfs_kuid_to_uid(acl_e->e_uid));
break;
case ACL_GROUP:
ace->ae_id = cpu_to_be32(xfs_kgid_to_gid(acl_e->e_gid));
break;
default:
ace->ae_id = cpu_to_be32(ACL_UNDEFINED_ID);
break;
}
ace->ae_perm = cpu_to_be16(acl_e->e_perm);
}
}
struct posix_acl *
xfs_get_acl(struct inode *inode, int type)
{
struct xfs_inode *ip = XFS_I(inode);
struct posix_acl *acl = NULL;
struct xfs_acl *xfs_acl;
unsigned char *ea_name;
int error;
int len;
trace_xfs_get_acl(ip);
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = SGI_ACL_FILE;
break;
case ACL_TYPE_DEFAULT:
ea_name = SGI_ACL_DEFAULT;
break;
default:
BUG();
}
/*
* If we have a cached ACLs value just return it, not need to
* go out to the disk.
*/
len = XFS_ACL_MAX_SIZE(ip->i_mount);
xfs_acl = kmem_zalloc_large(len, KM_SLEEP);
if (!xfs_acl)
return ERR_PTR(-ENOMEM);
error = xfs_attr_get(ip, ea_name, (unsigned char *)xfs_acl,
&len, ATTR_ROOT);
if (error) {
/*
* If the attribute doesn't exist make sure we have a negative
* cache entry, for any other error assume it is transient.
*/
if (error != -ENOATTR)
acl = ERR_PTR(error);
} else {
acl = xfs_acl_from_disk(xfs_acl, len,
XFS_ACL_MAX_ENTRIES(ip->i_mount));
}
kmem_free(xfs_acl);
return acl;
}
STATIC int
__xfs_set_acl(struct inode *inode, int type, struct posix_acl *acl)
{
struct xfs_inode *ip = XFS_I(inode);
unsigned char *ea_name;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = SGI_ACL_FILE;
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
ea_name = SGI_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
struct xfs_acl *xfs_acl;
int len = XFS_ACL_MAX_SIZE(ip->i_mount);
xfs_acl = kmem_zalloc_large(len, KM_SLEEP);
if (!xfs_acl)
return -ENOMEM;
xfs_acl_to_disk(xfs_acl, acl);
/* subtract away the unused acl entries */
len -= sizeof(struct xfs_acl_entry) *
(XFS_ACL_MAX_ENTRIES(ip->i_mount) - acl->a_count);
error = xfs_attr_set(ip, ea_name, (unsigned char *)xfs_acl,
len, ATTR_ROOT);
kmem_free(xfs_acl);
} else {
/*
* A NULL ACL argument means we want to remove the ACL.
*/
error = xfs_attr_remove(ip, ea_name, ATTR_ROOT);
/*
* If the attribute didn't exist to start with that's fine.
*/
if (error == -ENOATTR)
error = 0;
}
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
static int
xfs_set_mode(struct inode *inode, umode_t mode)
{
int error = 0;
if (mode != inode->i_mode) {
struct iattr iattr;
iattr.ia_valid = ATTR_MODE | ATTR_CTIME;
iattr.ia_mode = mode;
iattr.ia_ctime = current_fs_time(inode->i_sb);
error = xfs_setattr_nonsize(XFS_I(inode), &iattr, XFS_ATTR_NOACL);
}
return error;
}
int
xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode;
error = posix_acl_update_mode(inode, &mode, &acl);
if (error)
return error;
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_14 |
crossvul-cpp_data_bad_5246_4 | /*
* linux/fs/ext4/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*/
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *
ext4_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(ext4_acl_header))
return ERR_PTR(-EINVAL);
if (((ext4_acl_header *)value)->a_version !=
cpu_to_le32(EXT4_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(ext4_acl_header);
count = ext4_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
ext4_acl_entry *entry =
(ext4_acl_entry *)value;
if ((char *)value + sizeof(ext4_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(ext4_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(ext4_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(ext4_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *
ext4_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
ext4_acl_header *ext_acl;
char *e;
size_t n;
*size = ext4_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(ext4_acl_header) + acl->a_count *
sizeof(ext4_acl_entry), GFP_NOFS);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(EXT4_ACL_VERSION);
e = (char *)ext_acl + sizeof(ext4_acl_header);
for (n = 0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext4_acl_entry *entry = (ext4_acl_entry *)e;
entry->e_tag = cpu_to_le16(acl_e->e_tag);
entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch (acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(ext4_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(ext4_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(ext4_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* Inode operation get_posix_acl().
*
* inode->i_mutex: don't care
*/
struct posix_acl *
ext4_get_acl(struct inode *inode, int type)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = ext4_xattr_get(inode, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ext4_xattr_get(inode, name_index, "", value, retval);
}
if (retval > 0)
acl = ext4_acl_from_disk(value, retval);
else if (retval == -ENODATA || retval == -ENOSYS)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* Set the access or default ACL of an inode.
*
* inode->i_mutex: down unless called from ext4_new_inode
*/
static int
__ext4_set_acl(handle_t *handle, struct inode *inode, int type,
struct posix_acl *acl)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext4_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext4_xattr_set_handle(handle, inode, name_index, "",
value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
int
ext4_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
handle_t *handle;
int error, retries = 0;
retry:
handle = ext4_journal_start(inode, EXT4_HT_XATTR,
ext4_jbd2_credits_xattr(inode));
if (IS_ERR(handle))
return PTR_ERR(handle);
error = __ext4_set_acl(handle, inode, type, acl);
ext4_journal_stop(handle);
if (error == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
return error;
}
/*
* Initialize the ACLs of a new inode. Called from ext4_new_inode.
*
* dir->i_mutex: down
* inode->i_mutex: up (access to inode is still exclusive)
*/
int
ext4_init_acl(handle_t *handle, struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = __ext4_set_acl(handle, inode, ACL_TYPE_DEFAULT,
default_acl);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = __ext4_set_acl(handle, inode, ACL_TYPE_ACCESS,
acl);
posix_acl_release(acl);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_4 |
crossvul-cpp_data_bad_5246_9 | /*
* Copyright (C) International Business Machines Corp., 2002-2004
* Copyright (C) Andreas Gruenbacher, 2001
* Copyright (C) Linus Torvalds, 1991, 1992
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/posix_acl_xattr.h>
#include "jfs_incore.h"
#include "jfs_txnmgr.h"
#include "jfs_xattr.h"
#include "jfs_acl.h"
struct posix_acl *jfs_get_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
char *ea_name;
int size;
char *value = NULL;
switch(type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
size = __jfs_getxattr(inode, ea_name, NULL, 0);
if (size > 0) {
value = kmalloc(size, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
size = __jfs_getxattr(inode, ea_name, value, size);
}
if (size < 0) {
if (size == -ENODATA)
acl = NULL;
else
acl = ERR_PTR(size);
} else {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
}
kfree(value);
return acl;
}
static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_equiv_mode(acl, &inode->i_mode);
if (rc < 0)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
if (rc == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
int jfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int rc;
tid_t tid;
tid = txBegin(inode->i_sb, 0);
mutex_lock(&JFS_IP(inode)->commit_mutex);
rc = __jfs_set_acl(tid, inode, type, acl);
if (!rc)
rc = txCommit(tid, 1, &inode, 0);
txEnd(tid);
mutex_unlock(&JFS_IP(inode)->commit_mutex);
return rc;
}
int jfs_init_acl(tid_t tid, struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int rc = 0;
rc = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (rc)
return rc;
if (default_acl) {
rc = __jfs_set_acl(tid, inode, ACL_TYPE_DEFAULT, default_acl);
posix_acl_release(default_acl);
}
if (acl) {
if (!rc)
rc = __jfs_set_acl(tid, inode, ACL_TYPE_ACCESS, acl);
posix_acl_release(acl);
}
JFS_IP(inode)->mode2 = (JFS_IP(inode)->mode2 & 0xffff0000) |
inode->i_mode;
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_9 |
crossvul-cpp_data_bad_5246_14 | /*
* Copyright (c) 2008, Christoph Hellwig
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_mount.h"
#include "xfs_inode.h"
#include "xfs_acl.h"
#include "xfs_attr.h"
#include "xfs_trace.h"
#include <linux/slab.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
/*
* Locking scheme:
* - all ACL updates are protected by inode->i_mutex, which is taken before
* calling into this file.
*/
STATIC struct posix_acl *
xfs_acl_from_disk(
const struct xfs_acl *aclp,
int len,
int max_entries)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
const struct xfs_acl_entry *ace;
unsigned int count, i;
if (len < sizeof(*aclp))
return ERR_PTR(-EFSCORRUPTED);
count = be32_to_cpu(aclp->acl_cnt);
if (count > max_entries || XFS_ACL_SIZE(count) != len)
return ERR_PTR(-EFSCORRUPTED);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
acl_e->e_uid = xfs_uid_to_kuid(be32_to_cpu(ace->ae_id));
break;
case ACL_GROUP:
acl_e->e_gid = xfs_gid_to_kgid(be32_to_cpu(ace->ae_id));
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
STATIC void
xfs_acl_to_disk(struct xfs_acl *aclp, const struct posix_acl *acl)
{
const struct posix_acl_entry *acl_e;
struct xfs_acl_entry *ace;
int i;
aclp->acl_cnt = cpu_to_be32(acl->a_count);
for (i = 0; i < acl->a_count; i++) {
ace = &aclp->acl_entry[i];
acl_e = &acl->a_entries[i];
ace->ae_tag = cpu_to_be32(acl_e->e_tag);
switch (acl_e->e_tag) {
case ACL_USER:
ace->ae_id = cpu_to_be32(xfs_kuid_to_uid(acl_e->e_uid));
break;
case ACL_GROUP:
ace->ae_id = cpu_to_be32(xfs_kgid_to_gid(acl_e->e_gid));
break;
default:
ace->ae_id = cpu_to_be32(ACL_UNDEFINED_ID);
break;
}
ace->ae_perm = cpu_to_be16(acl_e->e_perm);
}
}
struct posix_acl *
xfs_get_acl(struct inode *inode, int type)
{
struct xfs_inode *ip = XFS_I(inode);
struct posix_acl *acl = NULL;
struct xfs_acl *xfs_acl;
unsigned char *ea_name;
int error;
int len;
trace_xfs_get_acl(ip);
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = SGI_ACL_FILE;
break;
case ACL_TYPE_DEFAULT:
ea_name = SGI_ACL_DEFAULT;
break;
default:
BUG();
}
/*
* If we have a cached ACLs value just return it, not need to
* go out to the disk.
*/
len = XFS_ACL_MAX_SIZE(ip->i_mount);
xfs_acl = kmem_zalloc_large(len, KM_SLEEP);
if (!xfs_acl)
return ERR_PTR(-ENOMEM);
error = xfs_attr_get(ip, ea_name, (unsigned char *)xfs_acl,
&len, ATTR_ROOT);
if (error) {
/*
* If the attribute doesn't exist make sure we have a negative
* cache entry, for any other error assume it is transient.
*/
if (error != -ENOATTR)
acl = ERR_PTR(error);
} else {
acl = xfs_acl_from_disk(xfs_acl, len,
XFS_ACL_MAX_ENTRIES(ip->i_mount));
}
kmem_free(xfs_acl);
return acl;
}
STATIC int
__xfs_set_acl(struct inode *inode, int type, struct posix_acl *acl)
{
struct xfs_inode *ip = XFS_I(inode);
unsigned char *ea_name;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = SGI_ACL_FILE;
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
ea_name = SGI_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
struct xfs_acl *xfs_acl;
int len = XFS_ACL_MAX_SIZE(ip->i_mount);
xfs_acl = kmem_zalloc_large(len, KM_SLEEP);
if (!xfs_acl)
return -ENOMEM;
xfs_acl_to_disk(xfs_acl, acl);
/* subtract away the unused acl entries */
len -= sizeof(struct xfs_acl_entry) *
(XFS_ACL_MAX_ENTRIES(ip->i_mount) - acl->a_count);
error = xfs_attr_set(ip, ea_name, (unsigned char *)xfs_acl,
len, ATTR_ROOT);
kmem_free(xfs_acl);
} else {
/*
* A NULL ACL argument means we want to remove the ACL.
*/
error = xfs_attr_remove(ip, ea_name, ATTR_ROOT);
/*
* If the attribute didn't exist to start with that's fine.
*/
if (error == -ENOATTR)
error = 0;
}
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
static int
xfs_set_mode(struct inode *inode, umode_t mode)
{
int error = 0;
if (mode != inode->i_mode) {
struct iattr iattr;
iattr.ia_valid = ATTR_MODE | ATTR_CTIME;
iattr.ia_mode = mode;
iattr.ia_ctime = current_fs_time(inode->i_sb);
error = xfs_setattr_nonsize(XFS_I(inode), &iattr, XFS_ATTR_NOACL);
}
return error;
}
int
xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_equiv_mode(acl, &mode);
if (error <= 0) {
acl = NULL;
if (error < 0)
return error;
}
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_14 |
crossvul-cpp_data_bad_5246_12 | /*
* Copyright (C) 2002,2003 by Andreas Gruenbacher <a.gruenbacher@computer.org>
*
* Fixes from William Schumacher incorporated on 15 March 2001.
* (Reported by Charles Bertsch, <CBertsch@microtest.com>).
*/
/*
* This file contains generic functions for manipulating
* POSIX 1003.1e draft standard 17 ACLs.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/atomic.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <linux/xattr.h>
#include <linux/export.h>
#include <linux/user_namespace.h>
static struct posix_acl **acl_by_type(struct inode *inode, int type)
{
switch (type) {
case ACL_TYPE_ACCESS:
return &inode->i_acl;
case ACL_TYPE_DEFAULT:
return &inode->i_default_acl;
default:
BUG();
}
}
struct posix_acl *get_cached_acl(struct inode *inode, int type)
{
struct posix_acl **p = acl_by_type(inode, type);
struct posix_acl *acl;
for (;;) {
rcu_read_lock();
acl = rcu_dereference(*p);
if (!acl || is_uncached_acl(acl) ||
atomic_inc_not_zero(&acl->a_refcount))
break;
rcu_read_unlock();
cpu_relax();
}
rcu_read_unlock();
return acl;
}
EXPORT_SYMBOL(get_cached_acl);
struct posix_acl *get_cached_acl_rcu(struct inode *inode, int type)
{
return rcu_dereference(*acl_by_type(inode, type));
}
EXPORT_SYMBOL(get_cached_acl_rcu);
void set_cached_acl(struct inode *inode, int type, struct posix_acl *acl)
{
struct posix_acl **p = acl_by_type(inode, type);
struct posix_acl *old;
old = xchg(p, posix_acl_dup(acl));
if (!is_uncached_acl(old))
posix_acl_release(old);
}
EXPORT_SYMBOL(set_cached_acl);
static void __forget_cached_acl(struct posix_acl **p)
{
struct posix_acl *old;
old = xchg(p, ACL_NOT_CACHED);
if (!is_uncached_acl(old))
posix_acl_release(old);
}
void forget_cached_acl(struct inode *inode, int type)
{
__forget_cached_acl(acl_by_type(inode, type));
}
EXPORT_SYMBOL(forget_cached_acl);
void forget_all_cached_acls(struct inode *inode)
{
__forget_cached_acl(&inode->i_acl);
__forget_cached_acl(&inode->i_default_acl);
}
EXPORT_SYMBOL(forget_all_cached_acls);
struct posix_acl *get_acl(struct inode *inode, int type)
{
void *sentinel;
struct posix_acl **p;
struct posix_acl *acl;
/*
* The sentinel is used to detect when another operation like
* set_cached_acl() or forget_cached_acl() races with get_acl().
* It is guaranteed that is_uncached_acl(sentinel) is true.
*/
acl = get_cached_acl(inode, type);
if (!is_uncached_acl(acl))
return acl;
if (!IS_POSIXACL(inode))
return NULL;
sentinel = uncached_acl_sentinel(current);
p = acl_by_type(inode, type);
/*
* If the ACL isn't being read yet, set our sentinel. Otherwise, the
* current value of the ACL will not be ACL_NOT_CACHED and so our own
* sentinel will not be set; another task will update the cache. We
* could wait for that other task to complete its job, but it's easier
* to just call ->get_acl to fetch the ACL ourself. (This is going to
* be an unlikely race.)
*/
if (cmpxchg(p, ACL_NOT_CACHED, sentinel) != ACL_NOT_CACHED)
/* fall through */ ;
/*
* Normally, the ACL returned by ->get_acl will be cached.
* A filesystem can prevent that by calling
* forget_cached_acl(inode, type) in ->get_acl.
*
* If the filesystem doesn't have a get_acl() function at all, we'll
* just create the negative cache entry.
*/
if (!inode->i_op->get_acl) {
set_cached_acl(inode, type, NULL);
return NULL;
}
acl = inode->i_op->get_acl(inode, type);
if (IS_ERR(acl)) {
/*
* Remove our sentinel so that we don't block future attempts
* to cache the ACL.
*/
cmpxchg(p, sentinel, ACL_NOT_CACHED);
return acl;
}
/*
* Cache the result, but only if our sentinel is still in place.
*/
posix_acl_dup(acl);
if (unlikely(cmpxchg(p, sentinel, acl) != sentinel))
posix_acl_release(acl);
return acl;
}
EXPORT_SYMBOL(get_acl);
/*
* Init a fresh posix_acl
*/
void
posix_acl_init(struct posix_acl *acl, int count)
{
atomic_set(&acl->a_refcount, 1);
acl->a_count = count;
}
EXPORT_SYMBOL(posix_acl_init);
/*
* Allocate a new ACL with the specified number of entries.
*/
struct posix_acl *
posix_acl_alloc(int count, gfp_t flags)
{
const size_t size = sizeof(struct posix_acl) +
count * sizeof(struct posix_acl_entry);
struct posix_acl *acl = kmalloc(size, flags);
if (acl)
posix_acl_init(acl, count);
return acl;
}
EXPORT_SYMBOL(posix_acl_alloc);
/*
* Clone an ACL.
*/
static struct posix_acl *
posix_acl_clone(const struct posix_acl *acl, gfp_t flags)
{
struct posix_acl *clone = NULL;
if (acl) {
int size = sizeof(struct posix_acl) + acl->a_count *
sizeof(struct posix_acl_entry);
clone = kmemdup(acl, size, flags);
if (clone)
atomic_set(&clone->a_refcount, 1);
}
return clone;
}
/*
* Check if an acl is valid. Returns 0 if it is, or -E... otherwise.
*/
int
posix_acl_valid(struct user_namespace *user_ns, const struct posix_acl *acl)
{
const struct posix_acl_entry *pa, *pe;
int state = ACL_USER_OBJ;
int needs_mask = 0;
FOREACH_ACL_ENTRY(pa, acl, pe) {
if (pa->e_perm & ~(ACL_READ|ACL_WRITE|ACL_EXECUTE))
return -EINVAL;
switch (pa->e_tag) {
case ACL_USER_OBJ:
if (state == ACL_USER_OBJ) {
state = ACL_USER;
break;
}
return -EINVAL;
case ACL_USER:
if (state != ACL_USER)
return -EINVAL;
if (!kuid_has_mapping(user_ns, pa->e_uid))
return -EINVAL;
needs_mask = 1;
break;
case ACL_GROUP_OBJ:
if (state == ACL_USER) {
state = ACL_GROUP;
break;
}
return -EINVAL;
case ACL_GROUP:
if (state != ACL_GROUP)
return -EINVAL;
if (!kgid_has_mapping(user_ns, pa->e_gid))
return -EINVAL;
needs_mask = 1;
break;
case ACL_MASK:
if (state != ACL_GROUP)
return -EINVAL;
state = ACL_OTHER;
break;
case ACL_OTHER:
if (state == ACL_OTHER ||
(state == ACL_GROUP && !needs_mask)) {
state = 0;
break;
}
return -EINVAL;
default:
return -EINVAL;
}
}
if (state == 0)
return 0;
return -EINVAL;
}
EXPORT_SYMBOL(posix_acl_valid);
/*
* Returns 0 if the acl can be exactly represented in the traditional
* file mode permission bits, or else 1. Returns -E... on error.
*/
int
posix_acl_equiv_mode(const struct posix_acl *acl, umode_t *mode_p)
{
const struct posix_acl_entry *pa, *pe;
umode_t mode = 0;
int not_equiv = 0;
/*
* A null ACL can always be presented as mode bits.
*/
if (!acl)
return 0;
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch (pa->e_tag) {
case ACL_USER_OBJ:
mode |= (pa->e_perm & S_IRWXO) << 6;
break;
case ACL_GROUP_OBJ:
mode |= (pa->e_perm & S_IRWXO) << 3;
break;
case ACL_OTHER:
mode |= pa->e_perm & S_IRWXO;
break;
case ACL_MASK:
mode = (mode & ~S_IRWXG) |
((pa->e_perm & S_IRWXO) << 3);
not_equiv = 1;
break;
case ACL_USER:
case ACL_GROUP:
not_equiv = 1;
break;
default:
return -EINVAL;
}
}
if (mode_p)
*mode_p = (*mode_p & ~S_IRWXUGO) | mode;
return not_equiv;
}
EXPORT_SYMBOL(posix_acl_equiv_mode);
/*
* Create an ACL representing the file mode permission bits of an inode.
*/
struct posix_acl *
posix_acl_from_mode(umode_t mode, gfp_t flags)
{
struct posix_acl *acl = posix_acl_alloc(3, flags);
if (!acl)
return ERR_PTR(-ENOMEM);
acl->a_entries[0].e_tag = ACL_USER_OBJ;
acl->a_entries[0].e_perm = (mode & S_IRWXU) >> 6;
acl->a_entries[1].e_tag = ACL_GROUP_OBJ;
acl->a_entries[1].e_perm = (mode & S_IRWXG) >> 3;
acl->a_entries[2].e_tag = ACL_OTHER;
acl->a_entries[2].e_perm = (mode & S_IRWXO);
return acl;
}
EXPORT_SYMBOL(posix_acl_from_mode);
/*
* Return 0 if current is granted want access to the inode
* by the acl. Returns -E... otherwise.
*/
int
posix_acl_permission(struct inode *inode, const struct posix_acl *acl, int want)
{
const struct posix_acl_entry *pa, *pe, *mask_obj;
int found = 0;
want &= MAY_READ | MAY_WRITE | MAY_EXEC | MAY_NOT_BLOCK;
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
/* (May have been checked already) */
if (uid_eq(inode->i_uid, current_fsuid()))
goto check_perm;
break;
case ACL_USER:
if (uid_eq(pa->e_uid, current_fsuid()))
goto mask;
break;
case ACL_GROUP_OBJ:
if (in_group_p(inode->i_gid)) {
found = 1;
if ((pa->e_perm & want) == want)
goto mask;
}
break;
case ACL_GROUP:
if (in_group_p(pa->e_gid)) {
found = 1;
if ((pa->e_perm & want) == want)
goto mask;
}
break;
case ACL_MASK:
break;
case ACL_OTHER:
if (found)
return -EACCES;
else
goto check_perm;
default:
return -EIO;
}
}
return -EIO;
mask:
for (mask_obj = pa+1; mask_obj != pe; mask_obj++) {
if (mask_obj->e_tag == ACL_MASK) {
if ((pa->e_perm & mask_obj->e_perm & want) == want)
return 0;
return -EACCES;
}
}
check_perm:
if ((pa->e_perm & want) == want)
return 0;
return -EACCES;
}
/*
* Modify acl when creating a new inode. The caller must ensure the acl is
* only referenced once.
*
* mode_p initially must contain the mode parameter to the open() / creat()
* system calls. All permissions that are not granted by the acl are removed.
* The permissions in the acl are changed to reflect the mode_p parameter.
*/
static int posix_acl_create_masq(struct posix_acl *acl, umode_t *mode_p)
{
struct posix_acl_entry *pa, *pe;
struct posix_acl_entry *group_obj = NULL, *mask_obj = NULL;
umode_t mode = *mode_p;
int not_equiv = 0;
/* assert(atomic_read(acl->a_refcount) == 1); */
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
pa->e_perm &= (mode >> 6) | ~S_IRWXO;
mode &= (pa->e_perm << 6) | ~S_IRWXU;
break;
case ACL_USER:
case ACL_GROUP:
not_equiv = 1;
break;
case ACL_GROUP_OBJ:
group_obj = pa;
break;
case ACL_OTHER:
pa->e_perm &= mode | ~S_IRWXO;
mode &= pa->e_perm | ~S_IRWXO;
break;
case ACL_MASK:
mask_obj = pa;
not_equiv = 1;
break;
default:
return -EIO;
}
}
if (mask_obj) {
mask_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (mask_obj->e_perm << 3) | ~S_IRWXG;
} else {
if (!group_obj)
return -EIO;
group_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (group_obj->e_perm << 3) | ~S_IRWXG;
}
*mode_p = (*mode_p & ~S_IRWXUGO) | mode;
return not_equiv;
}
/*
* Modify the ACL for the chmod syscall.
*/
static int __posix_acl_chmod_masq(struct posix_acl *acl, umode_t mode)
{
struct posix_acl_entry *group_obj = NULL, *mask_obj = NULL;
struct posix_acl_entry *pa, *pe;
/* assert(atomic_read(acl->a_refcount) == 1); */
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
pa->e_perm = (mode & S_IRWXU) >> 6;
break;
case ACL_USER:
case ACL_GROUP:
break;
case ACL_GROUP_OBJ:
group_obj = pa;
break;
case ACL_MASK:
mask_obj = pa;
break;
case ACL_OTHER:
pa->e_perm = (mode & S_IRWXO);
break;
default:
return -EIO;
}
}
if (mask_obj) {
mask_obj->e_perm = (mode & S_IRWXG) >> 3;
} else {
if (!group_obj)
return -EIO;
group_obj->e_perm = (mode & S_IRWXG) >> 3;
}
return 0;
}
int
__posix_acl_create(struct posix_acl **acl, gfp_t gfp, umode_t *mode_p)
{
struct posix_acl *clone = posix_acl_clone(*acl, gfp);
int err = -ENOMEM;
if (clone) {
err = posix_acl_create_masq(clone, mode_p);
if (err < 0) {
posix_acl_release(clone);
clone = NULL;
}
}
posix_acl_release(*acl);
*acl = clone;
return err;
}
EXPORT_SYMBOL(__posix_acl_create);
int
__posix_acl_chmod(struct posix_acl **acl, gfp_t gfp, umode_t mode)
{
struct posix_acl *clone = posix_acl_clone(*acl, gfp);
int err = -ENOMEM;
if (clone) {
err = __posix_acl_chmod_masq(clone, mode);
if (err) {
posix_acl_release(clone);
clone = NULL;
}
}
posix_acl_release(*acl);
*acl = clone;
return err;
}
EXPORT_SYMBOL(__posix_acl_chmod);
int
posix_acl_chmod(struct inode *inode, umode_t mode)
{
struct posix_acl *acl;
int ret = 0;
if (!IS_POSIXACL(inode))
return 0;
if (!inode->i_op->set_acl)
return -EOPNOTSUPP;
acl = get_acl(inode, ACL_TYPE_ACCESS);
if (IS_ERR_OR_NULL(acl)) {
if (acl == ERR_PTR(-EOPNOTSUPP))
return 0;
return PTR_ERR(acl);
}
ret = __posix_acl_chmod(&acl, GFP_KERNEL, mode);
if (ret)
return ret;
ret = inode->i_op->set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
return ret;
}
EXPORT_SYMBOL(posix_acl_chmod);
int
posix_acl_create(struct inode *dir, umode_t *mode,
struct posix_acl **default_acl, struct posix_acl **acl)
{
struct posix_acl *p;
struct posix_acl *clone;
int ret;
*acl = NULL;
*default_acl = NULL;
if (S_ISLNK(*mode) || !IS_POSIXACL(dir))
return 0;
p = get_acl(dir, ACL_TYPE_DEFAULT);
if (!p || p == ERR_PTR(-EOPNOTSUPP)) {
*mode &= ~current_umask();
return 0;
}
if (IS_ERR(p))
return PTR_ERR(p);
clone = posix_acl_clone(p, GFP_NOFS);
if (!clone)
goto no_mem;
ret = posix_acl_create_masq(clone, mode);
if (ret < 0)
goto no_mem_clone;
if (ret == 0)
posix_acl_release(clone);
else
*acl = clone;
if (!S_ISDIR(*mode))
posix_acl_release(p);
else
*default_acl = p;
return 0;
no_mem_clone:
posix_acl_release(clone);
no_mem:
posix_acl_release(p);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(posix_acl_create);
/*
* Fix up the uids and gids in posix acl extended attributes in place.
*/
static void posix_acl_fix_xattr_userns(
struct user_namespace *to, struct user_namespace *from,
void *value, size_t size)
{
posix_acl_xattr_header *header = (posix_acl_xattr_header *)value;
posix_acl_xattr_entry *entry = (posix_acl_xattr_entry *)(header+1), *end;
int count;
kuid_t uid;
kgid_t gid;
if (!value)
return;
if (size < sizeof(posix_acl_xattr_header))
return;
if (header->a_version != cpu_to_le32(POSIX_ACL_XATTR_VERSION))
return;
count = posix_acl_xattr_count(size);
if (count < 0)
return;
if (count == 0)
return;
for (end = entry + count; entry != end; entry++) {
switch(le16_to_cpu(entry->e_tag)) {
case ACL_USER:
uid = make_kuid(from, le32_to_cpu(entry->e_id));
entry->e_id = cpu_to_le32(from_kuid(to, uid));
break;
case ACL_GROUP:
gid = make_kgid(from, le32_to_cpu(entry->e_id));
entry->e_id = cpu_to_le32(from_kgid(to, gid));
break;
default:
break;
}
}
}
void posix_acl_fix_xattr_from_user(void *value, size_t size)
{
struct user_namespace *user_ns = current_user_ns();
if (user_ns == &init_user_ns)
return;
posix_acl_fix_xattr_userns(&init_user_ns, user_ns, value, size);
}
void posix_acl_fix_xattr_to_user(void *value, size_t size)
{
struct user_namespace *user_ns = current_user_ns();
if (user_ns == &init_user_ns)
return;
posix_acl_fix_xattr_userns(user_ns, &init_user_ns, value, size);
}
/*
* Convert from extended attribute to in-memory representation.
*/
struct posix_acl *
posix_acl_from_xattr(struct user_namespace *user_ns,
const void *value, size_t size)
{
posix_acl_xattr_header *header = (posix_acl_xattr_header *)value;
posix_acl_xattr_entry *entry = (posix_acl_xattr_entry *)(header+1), *end;
int count;
struct posix_acl *acl;
struct posix_acl_entry *acl_e;
if (!value)
return NULL;
if (size < sizeof(posix_acl_xattr_header))
return ERR_PTR(-EINVAL);
if (header->a_version != cpu_to_le32(POSIX_ACL_XATTR_VERSION))
return ERR_PTR(-EOPNOTSUPP);
count = posix_acl_xattr_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
acl_e = acl->a_entries;
for (end = entry + count; entry != end; acl_e++, entry++) {
acl_e->e_tag = le16_to_cpu(entry->e_tag);
acl_e->e_perm = le16_to_cpu(entry->e_perm);
switch(acl_e->e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
break;
case ACL_USER:
acl_e->e_uid =
make_kuid(user_ns,
le32_to_cpu(entry->e_id));
if (!uid_valid(acl_e->e_uid))
goto fail;
break;
case ACL_GROUP:
acl_e->e_gid =
make_kgid(user_ns,
le32_to_cpu(entry->e_id));
if (!gid_valid(acl_e->e_gid))
goto fail;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
EXPORT_SYMBOL (posix_acl_from_xattr);
/*
* Convert from in-memory to extended attribute representation.
*/
int
posix_acl_to_xattr(struct user_namespace *user_ns, const struct posix_acl *acl,
void *buffer, size_t size)
{
posix_acl_xattr_header *ext_acl = (posix_acl_xattr_header *)buffer;
posix_acl_xattr_entry *ext_entry;
int real_size, n;
real_size = posix_acl_xattr_size(acl->a_count);
if (!buffer)
return real_size;
if (real_size > size)
return -ERANGE;
ext_entry = ext_acl->a_entries;
ext_acl->a_version = cpu_to_le32(POSIX_ACL_XATTR_VERSION);
for (n=0; n < acl->a_count; n++, ext_entry++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext_entry->e_tag = cpu_to_le16(acl_e->e_tag);
ext_entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
ext_entry->e_id =
cpu_to_le32(from_kuid(user_ns, acl_e->e_uid));
break;
case ACL_GROUP:
ext_entry->e_id =
cpu_to_le32(from_kgid(user_ns, acl_e->e_gid));
break;
default:
ext_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
break;
}
}
return real_size;
}
EXPORT_SYMBOL (posix_acl_to_xattr);
static int
posix_acl_xattr_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *value, size_t size)
{
struct posix_acl *acl;
int error;
if (!IS_POSIXACL(inode))
return -EOPNOTSUPP;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
acl = get_acl(inode, handler->flags);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (acl == NULL)
return -ENODATA;
error = posix_acl_to_xattr(&init_user_ns, acl, value, size);
posix_acl_release(acl);
return error;
}
int
set_posix_acl(struct inode *inode, int type, struct posix_acl *acl)
{
if (!IS_POSIXACL(inode))
return -EOPNOTSUPP;
if (!inode->i_op->set_acl)
return -EOPNOTSUPP;
if (type == ACL_TYPE_DEFAULT && !S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (acl) {
int ret = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (ret)
return ret;
}
return inode->i_op->set_acl(inode, acl, type);
}
EXPORT_SYMBOL(set_posix_acl);
static int
posix_acl_xattr_set(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
struct posix_acl *acl = NULL;
int ret;
if (value) {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
}
ret = set_posix_acl(inode, handler->flags, acl);
posix_acl_release(acl);
return ret;
}
static bool
posix_acl_xattr_list(struct dentry *dentry)
{
return IS_POSIXACL(d_backing_inode(dentry));
}
const struct xattr_handler posix_acl_access_xattr_handler = {
.name = XATTR_NAME_POSIX_ACL_ACCESS,
.flags = ACL_TYPE_ACCESS,
.list = posix_acl_xattr_list,
.get = posix_acl_xattr_get,
.set = posix_acl_xattr_set,
};
EXPORT_SYMBOL_GPL(posix_acl_access_xattr_handler);
const struct xattr_handler posix_acl_default_xattr_handler = {
.name = XATTR_NAME_POSIX_ACL_DEFAULT,
.flags = ACL_TYPE_DEFAULT,
.list = posix_acl_xattr_list,
.get = posix_acl_xattr_get,
.set = posix_acl_xattr_set,
};
EXPORT_SYMBOL_GPL(posix_acl_default_xattr_handler);
int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
if (type == ACL_TYPE_ACCESS) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return 0;
if (error == 0)
acl = NULL;
}
inode->i_ctime = CURRENT_TIME;
set_cached_acl(inode, type, acl);
return 0;
}
int simple_acl_create(struct inode *dir, struct inode *inode)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
set_cached_acl(inode, ACL_TYPE_DEFAULT, default_acl);
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
if (default_acl)
posix_acl_release(default_acl);
if (acl)
posix_acl_release(acl);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_12 |
crossvul-cpp_data_good_5246_12 | /*
* Copyright (C) 2002,2003 by Andreas Gruenbacher <a.gruenbacher@computer.org>
*
* Fixes from William Schumacher incorporated on 15 March 2001.
* (Reported by Charles Bertsch, <CBertsch@microtest.com>).
*/
/*
* This file contains generic functions for manipulating
* POSIX 1003.1e draft standard 17 ACLs.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/atomic.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#include <linux/xattr.h>
#include <linux/export.h>
#include <linux/user_namespace.h>
static struct posix_acl **acl_by_type(struct inode *inode, int type)
{
switch (type) {
case ACL_TYPE_ACCESS:
return &inode->i_acl;
case ACL_TYPE_DEFAULT:
return &inode->i_default_acl;
default:
BUG();
}
}
struct posix_acl *get_cached_acl(struct inode *inode, int type)
{
struct posix_acl **p = acl_by_type(inode, type);
struct posix_acl *acl;
for (;;) {
rcu_read_lock();
acl = rcu_dereference(*p);
if (!acl || is_uncached_acl(acl) ||
atomic_inc_not_zero(&acl->a_refcount))
break;
rcu_read_unlock();
cpu_relax();
}
rcu_read_unlock();
return acl;
}
EXPORT_SYMBOL(get_cached_acl);
struct posix_acl *get_cached_acl_rcu(struct inode *inode, int type)
{
return rcu_dereference(*acl_by_type(inode, type));
}
EXPORT_SYMBOL(get_cached_acl_rcu);
void set_cached_acl(struct inode *inode, int type, struct posix_acl *acl)
{
struct posix_acl **p = acl_by_type(inode, type);
struct posix_acl *old;
old = xchg(p, posix_acl_dup(acl));
if (!is_uncached_acl(old))
posix_acl_release(old);
}
EXPORT_SYMBOL(set_cached_acl);
static void __forget_cached_acl(struct posix_acl **p)
{
struct posix_acl *old;
old = xchg(p, ACL_NOT_CACHED);
if (!is_uncached_acl(old))
posix_acl_release(old);
}
void forget_cached_acl(struct inode *inode, int type)
{
__forget_cached_acl(acl_by_type(inode, type));
}
EXPORT_SYMBOL(forget_cached_acl);
void forget_all_cached_acls(struct inode *inode)
{
__forget_cached_acl(&inode->i_acl);
__forget_cached_acl(&inode->i_default_acl);
}
EXPORT_SYMBOL(forget_all_cached_acls);
struct posix_acl *get_acl(struct inode *inode, int type)
{
void *sentinel;
struct posix_acl **p;
struct posix_acl *acl;
/*
* The sentinel is used to detect when another operation like
* set_cached_acl() or forget_cached_acl() races with get_acl().
* It is guaranteed that is_uncached_acl(sentinel) is true.
*/
acl = get_cached_acl(inode, type);
if (!is_uncached_acl(acl))
return acl;
if (!IS_POSIXACL(inode))
return NULL;
sentinel = uncached_acl_sentinel(current);
p = acl_by_type(inode, type);
/*
* If the ACL isn't being read yet, set our sentinel. Otherwise, the
* current value of the ACL will not be ACL_NOT_CACHED and so our own
* sentinel will not be set; another task will update the cache. We
* could wait for that other task to complete its job, but it's easier
* to just call ->get_acl to fetch the ACL ourself. (This is going to
* be an unlikely race.)
*/
if (cmpxchg(p, ACL_NOT_CACHED, sentinel) != ACL_NOT_CACHED)
/* fall through */ ;
/*
* Normally, the ACL returned by ->get_acl will be cached.
* A filesystem can prevent that by calling
* forget_cached_acl(inode, type) in ->get_acl.
*
* If the filesystem doesn't have a get_acl() function at all, we'll
* just create the negative cache entry.
*/
if (!inode->i_op->get_acl) {
set_cached_acl(inode, type, NULL);
return NULL;
}
acl = inode->i_op->get_acl(inode, type);
if (IS_ERR(acl)) {
/*
* Remove our sentinel so that we don't block future attempts
* to cache the ACL.
*/
cmpxchg(p, sentinel, ACL_NOT_CACHED);
return acl;
}
/*
* Cache the result, but only if our sentinel is still in place.
*/
posix_acl_dup(acl);
if (unlikely(cmpxchg(p, sentinel, acl) != sentinel))
posix_acl_release(acl);
return acl;
}
EXPORT_SYMBOL(get_acl);
/*
* Init a fresh posix_acl
*/
void
posix_acl_init(struct posix_acl *acl, int count)
{
atomic_set(&acl->a_refcount, 1);
acl->a_count = count;
}
EXPORT_SYMBOL(posix_acl_init);
/*
* Allocate a new ACL with the specified number of entries.
*/
struct posix_acl *
posix_acl_alloc(int count, gfp_t flags)
{
const size_t size = sizeof(struct posix_acl) +
count * sizeof(struct posix_acl_entry);
struct posix_acl *acl = kmalloc(size, flags);
if (acl)
posix_acl_init(acl, count);
return acl;
}
EXPORT_SYMBOL(posix_acl_alloc);
/*
* Clone an ACL.
*/
static struct posix_acl *
posix_acl_clone(const struct posix_acl *acl, gfp_t flags)
{
struct posix_acl *clone = NULL;
if (acl) {
int size = sizeof(struct posix_acl) + acl->a_count *
sizeof(struct posix_acl_entry);
clone = kmemdup(acl, size, flags);
if (clone)
atomic_set(&clone->a_refcount, 1);
}
return clone;
}
/*
* Check if an acl is valid. Returns 0 if it is, or -E... otherwise.
*/
int
posix_acl_valid(struct user_namespace *user_ns, const struct posix_acl *acl)
{
const struct posix_acl_entry *pa, *pe;
int state = ACL_USER_OBJ;
int needs_mask = 0;
FOREACH_ACL_ENTRY(pa, acl, pe) {
if (pa->e_perm & ~(ACL_READ|ACL_WRITE|ACL_EXECUTE))
return -EINVAL;
switch (pa->e_tag) {
case ACL_USER_OBJ:
if (state == ACL_USER_OBJ) {
state = ACL_USER;
break;
}
return -EINVAL;
case ACL_USER:
if (state != ACL_USER)
return -EINVAL;
if (!kuid_has_mapping(user_ns, pa->e_uid))
return -EINVAL;
needs_mask = 1;
break;
case ACL_GROUP_OBJ:
if (state == ACL_USER) {
state = ACL_GROUP;
break;
}
return -EINVAL;
case ACL_GROUP:
if (state != ACL_GROUP)
return -EINVAL;
if (!kgid_has_mapping(user_ns, pa->e_gid))
return -EINVAL;
needs_mask = 1;
break;
case ACL_MASK:
if (state != ACL_GROUP)
return -EINVAL;
state = ACL_OTHER;
break;
case ACL_OTHER:
if (state == ACL_OTHER ||
(state == ACL_GROUP && !needs_mask)) {
state = 0;
break;
}
return -EINVAL;
default:
return -EINVAL;
}
}
if (state == 0)
return 0;
return -EINVAL;
}
EXPORT_SYMBOL(posix_acl_valid);
/*
* Returns 0 if the acl can be exactly represented in the traditional
* file mode permission bits, or else 1. Returns -E... on error.
*/
int
posix_acl_equiv_mode(const struct posix_acl *acl, umode_t *mode_p)
{
const struct posix_acl_entry *pa, *pe;
umode_t mode = 0;
int not_equiv = 0;
/*
* A null ACL can always be presented as mode bits.
*/
if (!acl)
return 0;
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch (pa->e_tag) {
case ACL_USER_OBJ:
mode |= (pa->e_perm & S_IRWXO) << 6;
break;
case ACL_GROUP_OBJ:
mode |= (pa->e_perm & S_IRWXO) << 3;
break;
case ACL_OTHER:
mode |= pa->e_perm & S_IRWXO;
break;
case ACL_MASK:
mode = (mode & ~S_IRWXG) |
((pa->e_perm & S_IRWXO) << 3);
not_equiv = 1;
break;
case ACL_USER:
case ACL_GROUP:
not_equiv = 1;
break;
default:
return -EINVAL;
}
}
if (mode_p)
*mode_p = (*mode_p & ~S_IRWXUGO) | mode;
return not_equiv;
}
EXPORT_SYMBOL(posix_acl_equiv_mode);
/*
* Create an ACL representing the file mode permission bits of an inode.
*/
struct posix_acl *
posix_acl_from_mode(umode_t mode, gfp_t flags)
{
struct posix_acl *acl = posix_acl_alloc(3, flags);
if (!acl)
return ERR_PTR(-ENOMEM);
acl->a_entries[0].e_tag = ACL_USER_OBJ;
acl->a_entries[0].e_perm = (mode & S_IRWXU) >> 6;
acl->a_entries[1].e_tag = ACL_GROUP_OBJ;
acl->a_entries[1].e_perm = (mode & S_IRWXG) >> 3;
acl->a_entries[2].e_tag = ACL_OTHER;
acl->a_entries[2].e_perm = (mode & S_IRWXO);
return acl;
}
EXPORT_SYMBOL(posix_acl_from_mode);
/*
* Return 0 if current is granted want access to the inode
* by the acl. Returns -E... otherwise.
*/
int
posix_acl_permission(struct inode *inode, const struct posix_acl *acl, int want)
{
const struct posix_acl_entry *pa, *pe, *mask_obj;
int found = 0;
want &= MAY_READ | MAY_WRITE | MAY_EXEC | MAY_NOT_BLOCK;
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
/* (May have been checked already) */
if (uid_eq(inode->i_uid, current_fsuid()))
goto check_perm;
break;
case ACL_USER:
if (uid_eq(pa->e_uid, current_fsuid()))
goto mask;
break;
case ACL_GROUP_OBJ:
if (in_group_p(inode->i_gid)) {
found = 1;
if ((pa->e_perm & want) == want)
goto mask;
}
break;
case ACL_GROUP:
if (in_group_p(pa->e_gid)) {
found = 1;
if ((pa->e_perm & want) == want)
goto mask;
}
break;
case ACL_MASK:
break;
case ACL_OTHER:
if (found)
return -EACCES;
else
goto check_perm;
default:
return -EIO;
}
}
return -EIO;
mask:
for (mask_obj = pa+1; mask_obj != pe; mask_obj++) {
if (mask_obj->e_tag == ACL_MASK) {
if ((pa->e_perm & mask_obj->e_perm & want) == want)
return 0;
return -EACCES;
}
}
check_perm:
if ((pa->e_perm & want) == want)
return 0;
return -EACCES;
}
/*
* Modify acl when creating a new inode. The caller must ensure the acl is
* only referenced once.
*
* mode_p initially must contain the mode parameter to the open() / creat()
* system calls. All permissions that are not granted by the acl are removed.
* The permissions in the acl are changed to reflect the mode_p parameter.
*/
static int posix_acl_create_masq(struct posix_acl *acl, umode_t *mode_p)
{
struct posix_acl_entry *pa, *pe;
struct posix_acl_entry *group_obj = NULL, *mask_obj = NULL;
umode_t mode = *mode_p;
int not_equiv = 0;
/* assert(atomic_read(acl->a_refcount) == 1); */
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
pa->e_perm &= (mode >> 6) | ~S_IRWXO;
mode &= (pa->e_perm << 6) | ~S_IRWXU;
break;
case ACL_USER:
case ACL_GROUP:
not_equiv = 1;
break;
case ACL_GROUP_OBJ:
group_obj = pa;
break;
case ACL_OTHER:
pa->e_perm &= mode | ~S_IRWXO;
mode &= pa->e_perm | ~S_IRWXO;
break;
case ACL_MASK:
mask_obj = pa;
not_equiv = 1;
break;
default:
return -EIO;
}
}
if (mask_obj) {
mask_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (mask_obj->e_perm << 3) | ~S_IRWXG;
} else {
if (!group_obj)
return -EIO;
group_obj->e_perm &= (mode >> 3) | ~S_IRWXO;
mode &= (group_obj->e_perm << 3) | ~S_IRWXG;
}
*mode_p = (*mode_p & ~S_IRWXUGO) | mode;
return not_equiv;
}
/*
* Modify the ACL for the chmod syscall.
*/
static int __posix_acl_chmod_masq(struct posix_acl *acl, umode_t mode)
{
struct posix_acl_entry *group_obj = NULL, *mask_obj = NULL;
struct posix_acl_entry *pa, *pe;
/* assert(atomic_read(acl->a_refcount) == 1); */
FOREACH_ACL_ENTRY(pa, acl, pe) {
switch(pa->e_tag) {
case ACL_USER_OBJ:
pa->e_perm = (mode & S_IRWXU) >> 6;
break;
case ACL_USER:
case ACL_GROUP:
break;
case ACL_GROUP_OBJ:
group_obj = pa;
break;
case ACL_MASK:
mask_obj = pa;
break;
case ACL_OTHER:
pa->e_perm = (mode & S_IRWXO);
break;
default:
return -EIO;
}
}
if (mask_obj) {
mask_obj->e_perm = (mode & S_IRWXG) >> 3;
} else {
if (!group_obj)
return -EIO;
group_obj->e_perm = (mode & S_IRWXG) >> 3;
}
return 0;
}
int
__posix_acl_create(struct posix_acl **acl, gfp_t gfp, umode_t *mode_p)
{
struct posix_acl *clone = posix_acl_clone(*acl, gfp);
int err = -ENOMEM;
if (clone) {
err = posix_acl_create_masq(clone, mode_p);
if (err < 0) {
posix_acl_release(clone);
clone = NULL;
}
}
posix_acl_release(*acl);
*acl = clone;
return err;
}
EXPORT_SYMBOL(__posix_acl_create);
int
__posix_acl_chmod(struct posix_acl **acl, gfp_t gfp, umode_t mode)
{
struct posix_acl *clone = posix_acl_clone(*acl, gfp);
int err = -ENOMEM;
if (clone) {
err = __posix_acl_chmod_masq(clone, mode);
if (err) {
posix_acl_release(clone);
clone = NULL;
}
}
posix_acl_release(*acl);
*acl = clone;
return err;
}
EXPORT_SYMBOL(__posix_acl_chmod);
int
posix_acl_chmod(struct inode *inode, umode_t mode)
{
struct posix_acl *acl;
int ret = 0;
if (!IS_POSIXACL(inode))
return 0;
if (!inode->i_op->set_acl)
return -EOPNOTSUPP;
acl = get_acl(inode, ACL_TYPE_ACCESS);
if (IS_ERR_OR_NULL(acl)) {
if (acl == ERR_PTR(-EOPNOTSUPP))
return 0;
return PTR_ERR(acl);
}
ret = __posix_acl_chmod(&acl, GFP_KERNEL, mode);
if (ret)
return ret;
ret = inode->i_op->set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
return ret;
}
EXPORT_SYMBOL(posix_acl_chmod);
int
posix_acl_create(struct inode *dir, umode_t *mode,
struct posix_acl **default_acl, struct posix_acl **acl)
{
struct posix_acl *p;
struct posix_acl *clone;
int ret;
*acl = NULL;
*default_acl = NULL;
if (S_ISLNK(*mode) || !IS_POSIXACL(dir))
return 0;
p = get_acl(dir, ACL_TYPE_DEFAULT);
if (!p || p == ERR_PTR(-EOPNOTSUPP)) {
*mode &= ~current_umask();
return 0;
}
if (IS_ERR(p))
return PTR_ERR(p);
clone = posix_acl_clone(p, GFP_NOFS);
if (!clone)
goto no_mem;
ret = posix_acl_create_masq(clone, mode);
if (ret < 0)
goto no_mem_clone;
if (ret == 0)
posix_acl_release(clone);
else
*acl = clone;
if (!S_ISDIR(*mode))
posix_acl_release(p);
else
*default_acl = p;
return 0;
no_mem_clone:
posix_acl_release(clone);
no_mem:
posix_acl_release(p);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(posix_acl_create);
/**
* posix_acl_update_mode - update mode in set_acl
*
* Update the file mode when setting an ACL: compute the new file permission
* bits based on the ACL. In addition, if the ACL is equivalent to the new
* file mode, set *acl to NULL to indicate that no ACL should be set.
*
* As with chmod, clear the setgit bit if the caller is not in the owning group
* or capable of CAP_FSETID (see inode_change_ok).
*
* Called from set_acl inode operations.
*/
int posix_acl_update_mode(struct inode *inode, umode_t *mode_p,
struct posix_acl **acl)
{
umode_t mode = inode->i_mode;
int error;
error = posix_acl_equiv_mode(*acl, &mode);
if (error < 0)
return error;
if (error == 0)
*acl = NULL;
if (!in_group_p(inode->i_gid) &&
!capable_wrt_inode_uidgid(inode, CAP_FSETID))
mode &= ~S_ISGID;
*mode_p = mode;
return 0;
}
EXPORT_SYMBOL(posix_acl_update_mode);
/*
* Fix up the uids and gids in posix acl extended attributes in place.
*/
static void posix_acl_fix_xattr_userns(
struct user_namespace *to, struct user_namespace *from,
void *value, size_t size)
{
posix_acl_xattr_header *header = (posix_acl_xattr_header *)value;
posix_acl_xattr_entry *entry = (posix_acl_xattr_entry *)(header+1), *end;
int count;
kuid_t uid;
kgid_t gid;
if (!value)
return;
if (size < sizeof(posix_acl_xattr_header))
return;
if (header->a_version != cpu_to_le32(POSIX_ACL_XATTR_VERSION))
return;
count = posix_acl_xattr_count(size);
if (count < 0)
return;
if (count == 0)
return;
for (end = entry + count; entry != end; entry++) {
switch(le16_to_cpu(entry->e_tag)) {
case ACL_USER:
uid = make_kuid(from, le32_to_cpu(entry->e_id));
entry->e_id = cpu_to_le32(from_kuid(to, uid));
break;
case ACL_GROUP:
gid = make_kgid(from, le32_to_cpu(entry->e_id));
entry->e_id = cpu_to_le32(from_kgid(to, gid));
break;
default:
break;
}
}
}
void posix_acl_fix_xattr_from_user(void *value, size_t size)
{
struct user_namespace *user_ns = current_user_ns();
if (user_ns == &init_user_ns)
return;
posix_acl_fix_xattr_userns(&init_user_ns, user_ns, value, size);
}
void posix_acl_fix_xattr_to_user(void *value, size_t size)
{
struct user_namespace *user_ns = current_user_ns();
if (user_ns == &init_user_ns)
return;
posix_acl_fix_xattr_userns(user_ns, &init_user_ns, value, size);
}
/*
* Convert from extended attribute to in-memory representation.
*/
struct posix_acl *
posix_acl_from_xattr(struct user_namespace *user_ns,
const void *value, size_t size)
{
posix_acl_xattr_header *header = (posix_acl_xattr_header *)value;
posix_acl_xattr_entry *entry = (posix_acl_xattr_entry *)(header+1), *end;
int count;
struct posix_acl *acl;
struct posix_acl_entry *acl_e;
if (!value)
return NULL;
if (size < sizeof(posix_acl_xattr_header))
return ERR_PTR(-EINVAL);
if (header->a_version != cpu_to_le32(POSIX_ACL_XATTR_VERSION))
return ERR_PTR(-EOPNOTSUPP);
count = posix_acl_xattr_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
acl_e = acl->a_entries;
for (end = entry + count; entry != end; acl_e++, entry++) {
acl_e->e_tag = le16_to_cpu(entry->e_tag);
acl_e->e_perm = le16_to_cpu(entry->e_perm);
switch(acl_e->e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
break;
case ACL_USER:
acl_e->e_uid =
make_kuid(user_ns,
le32_to_cpu(entry->e_id));
if (!uid_valid(acl_e->e_uid))
goto fail;
break;
case ACL_GROUP:
acl_e->e_gid =
make_kgid(user_ns,
le32_to_cpu(entry->e_id));
if (!gid_valid(acl_e->e_gid))
goto fail;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
EXPORT_SYMBOL (posix_acl_from_xattr);
/*
* Convert from in-memory to extended attribute representation.
*/
int
posix_acl_to_xattr(struct user_namespace *user_ns, const struct posix_acl *acl,
void *buffer, size_t size)
{
posix_acl_xattr_header *ext_acl = (posix_acl_xattr_header *)buffer;
posix_acl_xattr_entry *ext_entry;
int real_size, n;
real_size = posix_acl_xattr_size(acl->a_count);
if (!buffer)
return real_size;
if (real_size > size)
return -ERANGE;
ext_entry = ext_acl->a_entries;
ext_acl->a_version = cpu_to_le32(POSIX_ACL_XATTR_VERSION);
for (n=0; n < acl->a_count; n++, ext_entry++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext_entry->e_tag = cpu_to_le16(acl_e->e_tag);
ext_entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
ext_entry->e_id =
cpu_to_le32(from_kuid(user_ns, acl_e->e_uid));
break;
case ACL_GROUP:
ext_entry->e_id =
cpu_to_le32(from_kgid(user_ns, acl_e->e_gid));
break;
default:
ext_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
break;
}
}
return real_size;
}
EXPORT_SYMBOL (posix_acl_to_xattr);
static int
posix_acl_xattr_get(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, void *value, size_t size)
{
struct posix_acl *acl;
int error;
if (!IS_POSIXACL(inode))
return -EOPNOTSUPP;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
acl = get_acl(inode, handler->flags);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (acl == NULL)
return -ENODATA;
error = posix_acl_to_xattr(&init_user_ns, acl, value, size);
posix_acl_release(acl);
return error;
}
int
set_posix_acl(struct inode *inode, int type, struct posix_acl *acl)
{
if (!IS_POSIXACL(inode))
return -EOPNOTSUPP;
if (!inode->i_op->set_acl)
return -EOPNOTSUPP;
if (type == ACL_TYPE_DEFAULT && !S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (acl) {
int ret = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (ret)
return ret;
}
return inode->i_op->set_acl(inode, acl, type);
}
EXPORT_SYMBOL(set_posix_acl);
static int
posix_acl_xattr_set(const struct xattr_handler *handler,
struct dentry *unused, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
struct posix_acl *acl = NULL;
int ret;
if (value) {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
}
ret = set_posix_acl(inode, handler->flags, acl);
posix_acl_release(acl);
return ret;
}
static bool
posix_acl_xattr_list(struct dentry *dentry)
{
return IS_POSIXACL(d_backing_inode(dentry));
}
const struct xattr_handler posix_acl_access_xattr_handler = {
.name = XATTR_NAME_POSIX_ACL_ACCESS,
.flags = ACL_TYPE_ACCESS,
.list = posix_acl_xattr_list,
.get = posix_acl_xattr_get,
.set = posix_acl_xattr_set,
};
EXPORT_SYMBOL_GPL(posix_acl_access_xattr_handler);
const struct xattr_handler posix_acl_default_xattr_handler = {
.name = XATTR_NAME_POSIX_ACL_DEFAULT,
.flags = ACL_TYPE_DEFAULT,
.list = posix_acl_xattr_list,
.get = posix_acl_xattr_get,
.set = posix_acl_xattr_set,
};
EXPORT_SYMBOL_GPL(posix_acl_default_xattr_handler);
int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
if (type == ACL_TYPE_ACCESS) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return 0;
if (error == 0)
acl = NULL;
}
inode->i_ctime = CURRENT_TIME;
set_cached_acl(inode, type, acl);
return 0;
}
int simple_acl_create(struct inode *dir, struct inode *inode)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
set_cached_acl(inode, ACL_TYPE_DEFAULT, default_acl);
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
if (default_acl)
posix_acl_release(default_acl);
if (acl)
posix_acl_release(acl);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_12 |
crossvul-cpp_data_bad_5246_7 | /*
* linux/fs/hfsplus/posix_acl.c
*
* Vyacheslav Dubeyko <slava@dubeyko.com>
*
* Handler for Posix Access Control Lists (ACLs) support.
*/
#include "hfsplus_fs.h"
#include "xattr.h"
#include "acl.h"
struct posix_acl *hfsplus_get_posix_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
char *xattr_name;
char *value = NULL;
ssize_t size;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
size = __hfsplus_getxattr(inode, xattr_name, NULL, 0);
if (size > 0) {
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return ERR_PTR(-ENOMEM);
size = __hfsplus_getxattr(inode, xattr_name, value, size);
}
if (size > 0)
acl = posix_acl_from_xattr(&init_user_ns, value, size);
else if (size == -ENODATA)
acl = NULL;
else
acl = ERR_PTR(size);
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
return acl;
}
int hfsplus_set_posix_acl(struct inode *inode, struct posix_acl *acl,
int type)
{
int err;
char *xattr_name;
size_t size = 0;
char *value = NULL;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
err = posix_acl_equiv_mode(acl, &inode->i_mode);
if (err < 0)
return err;
}
err = 0;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
if (unlikely(size > HFSPLUS_MAX_INLINE_DATA_SIZE))
return -ENOMEM;
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return -ENOMEM;
err = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (unlikely(err < 0))
goto end_set_acl;
}
err = __hfsplus_setxattr(inode, xattr_name, value, size, 0);
end_set_acl:
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
if (!err)
set_cached_acl(inode, type, acl);
return err;
}
int hfsplus_init_posix_acl(struct inode *inode, struct inode *dir)
{
int err = 0;
struct posix_acl *default_acl, *acl;
hfs_dbg(ACL_MOD,
"[%s]: ino %lu, dir->ino %lu\n",
__func__, inode->i_ino, dir->i_ino);
if (S_ISLNK(inode->i_mode))
return 0;
err = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (err)
return err;
if (default_acl) {
err = hfsplus_set_posix_acl(inode, default_acl,
ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!err)
err = hfsplus_set_posix_acl(inode, acl,
ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_7 |
crossvul-cpp_data_good_5246_8 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2006 NEC Corporation
*
* Created by KaiGai Kohei <kaigai@ak.jp.nec.com>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/crc32.h>
#include <linux/jffs2.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/mtd/mtd.h>
#include "nodelist.h"
static size_t jffs2_acl_size(int count)
{
if (count <= 4) {
return sizeof(struct jffs2_acl_header)
+ count * sizeof(struct jffs2_acl_entry_short);
} else {
return sizeof(struct jffs2_acl_header)
+ 4 * sizeof(struct jffs2_acl_entry_short)
+ (count - 4) * sizeof(struct jffs2_acl_entry);
}
}
static int jffs2_acl_count(size_t size)
{
size_t s;
size -= sizeof(struct jffs2_acl_header);
if (size < 4 * sizeof(struct jffs2_acl_entry_short)) {
if (size % sizeof(struct jffs2_acl_entry_short))
return -1;
return size / sizeof(struct jffs2_acl_entry_short);
} else {
s = size - 4 * sizeof(struct jffs2_acl_entry_short);
if (s % sizeof(struct jffs2_acl_entry))
return -1;
return s / sizeof(struct jffs2_acl_entry) + 4;
}
}
static struct posix_acl *jffs2_acl_from_medium(void *value, size_t size)
{
void *end = value + size;
struct jffs2_acl_header *header = value;
struct jffs2_acl_entry *entry;
struct posix_acl *acl;
uint32_t ver;
int i, count;
if (!value)
return NULL;
if (size < sizeof(struct jffs2_acl_header))
return ERR_PTR(-EINVAL);
ver = je32_to_cpu(header->a_version);
if (ver != JFFS2_ACL_VERSION) {
JFFS2_WARNING("Invalid ACL version. (=%u)\n", ver);
return ERR_PTR(-EINVAL);
}
value += sizeof(struct jffs2_acl_header);
count = jffs2_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i=0; i < count; i++) {
entry = value;
if (value + sizeof(struct jffs2_acl_entry_short) > end)
goto fail;
acl->a_entries[i].e_tag = je16_to_cpu(entry->e_tag);
acl->a_entries[i].e_perm = je16_to_cpu(entry->e_perm);
switch (acl->a_entries[i].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value += sizeof(struct jffs2_acl_entry_short);
break;
case ACL_USER:
value += sizeof(struct jffs2_acl_entry);
if (value > end)
goto fail;
acl->a_entries[i].e_uid =
make_kuid(&init_user_ns,
je32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value += sizeof(struct jffs2_acl_entry);
if (value > end)
goto fail;
acl->a_entries[i].e_gid =
make_kgid(&init_user_ns,
je32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
static void *jffs2_acl_to_medium(const struct posix_acl *acl, size_t *size)
{
struct jffs2_acl_header *header;
struct jffs2_acl_entry *entry;
void *e;
size_t i;
*size = jffs2_acl_size(acl->a_count);
header = kmalloc(sizeof(*header) + acl->a_count * sizeof(*entry), GFP_KERNEL);
if (!header)
return ERR_PTR(-ENOMEM);
header->a_version = cpu_to_je32(JFFS2_ACL_VERSION);
e = header + 1;
for (i=0; i < acl->a_count; i++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[i];
entry = e;
entry->e_tag = cpu_to_je16(acl_e->e_tag);
entry->e_perm = cpu_to_je16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_je32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(struct jffs2_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_je32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(struct jffs2_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(struct jffs2_acl_entry_short);
break;
default:
goto fail;
}
}
return header;
fail:
kfree(header);
return ERR_PTR(-EINVAL);
}
struct posix_acl *jffs2_get_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
char *value = NULL;
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
break;
default:
BUG();
}
rc = do_jffs2_getxattr(inode, xprefix, "", NULL, 0);
if (rc > 0) {
value = kmalloc(rc, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
rc = do_jffs2_getxattr(inode, xprefix, "", value, rc);
}
if (rc > 0) {
acl = jffs2_acl_from_medium(value, rc);
} else if (rc == -ENODATA || rc == -ENOSYS) {
acl = NULL;
} else {
acl = ERR_PTR(rc);
}
kfree(value);
return acl;
}
static int __jffs2_set_acl(struct inode *inode, int xprefix, struct posix_acl *acl)
{
char *value = NULL;
size_t size = 0;
int rc;
if (acl) {
value = jffs2_acl_to_medium(acl, &size);
if (IS_ERR(value))
return PTR_ERR(value);
}
rc = do_jffs2_setxattr(inode, xprefix, "", value, size, 0);
if (!value && rc == -ENODATA)
rc = 0;
kfree(value);
return rc;
}
int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
if (acl) {
umode_t mode;
rc = posix_acl_update_mode(inode, &mode, &acl);
if (rc)
return rc;
if (inode->i_mode != mode) {
struct iattr attr;
attr.ia_valid = ATTR_MODE | ATTR_CTIME;
attr.ia_mode = mode;
attr.ia_ctime = CURRENT_TIME_SEC;
rc = jffs2_do_setattr(inode, &attr);
if (rc < 0)
return rc;
}
}
break;
case ACL_TYPE_DEFAULT:
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
rc = __jffs2_set_acl(inode, xprefix, acl);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
int jffs2_init_acl_pre(struct inode *dir_i, struct inode *inode, umode_t *i_mode)
{
struct posix_acl *default_acl, *acl;
int rc;
cache_no_acl(inode);
rc = posix_acl_create(dir_i, i_mode, &default_acl, &acl);
if (rc)
return rc;
if (default_acl) {
set_cached_acl(inode, ACL_TYPE_DEFAULT, default_acl);
posix_acl_release(default_acl);
}
if (acl) {
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
posix_acl_release(acl);
}
return 0;
}
int jffs2_init_acl_post(struct inode *inode)
{
int rc;
if (inode->i_default_acl) {
rc = __jffs2_set_acl(inode, JFFS2_XPREFIX_ACL_DEFAULT, inode->i_default_acl);
if (rc)
return rc;
}
if (inode->i_acl) {
rc = __jffs2_set_acl(inode, JFFS2_XPREFIX_ACL_ACCESS, inode->i_acl);
if (rc)
return rc;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_8 |
crossvul-cpp_data_good_5246_9 | /*
* Copyright (C) International Business Machines Corp., 2002-2004
* Copyright (C) Andreas Gruenbacher, 2001
* Copyright (C) Linus Torvalds, 1991, 1992
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/posix_acl_xattr.h>
#include "jfs_incore.h"
#include "jfs_txnmgr.h"
#include "jfs_xattr.h"
#include "jfs_acl.h"
struct posix_acl *jfs_get_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
char *ea_name;
int size;
char *value = NULL;
switch(type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
size = __jfs_getxattr(inode, ea_name, NULL, 0);
if (size > 0) {
value = kmalloc(size, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
size = __jfs_getxattr(inode, ea_name, value, size);
}
if (size < 0) {
if (size == -ENODATA)
acl = NULL;
else
acl = ERR_PTR(size);
} else {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
}
kfree(value);
return acl;
}
static int __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (rc)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
int jfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int rc;
tid_t tid;
tid = txBegin(inode->i_sb, 0);
mutex_lock(&JFS_IP(inode)->commit_mutex);
rc = __jfs_set_acl(tid, inode, type, acl);
if (!rc)
rc = txCommit(tid, 1, &inode, 0);
txEnd(tid);
mutex_unlock(&JFS_IP(inode)->commit_mutex);
return rc;
}
int jfs_init_acl(tid_t tid, struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int rc = 0;
rc = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (rc)
return rc;
if (default_acl) {
rc = __jfs_set_acl(tid, inode, ACL_TYPE_DEFAULT, default_acl);
posix_acl_release(default_acl);
}
if (acl) {
if (!rc)
rc = __jfs_set_acl(tid, inode, ACL_TYPE_ACCESS, acl);
posix_acl_release(acl);
}
JFS_IP(inode)->mode2 = (JFS_IP(inode)->mode2 & 0xffff0000) |
inode->i_mode;
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_9 |
crossvul-cpp_data_bad_5243_0 | /*
* Copyright (C) 2004 Andrew Beekhof <andrew@beekhof.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <crm_internal.h>
#include <sys/param.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#include <errno.h>
#include <fcntl.h>
#include <bzlib.h>
#include <crm/crm.h>
#include <crm/msg_xml.h>
#include <crm/common/ipc.h>
#include <crm/common/ipcs.h>
#define PCMK_IPC_VERSION 1
struct crm_ipc_response_header {
struct qb_ipc_response_header qb;
uint32_t size_uncompressed;
uint32_t size_compressed;
uint32_t flags;
uint8_t version; /* Protect against version changes for anyone that might bother to statically link us */
};
static int hdr_offset = 0;
static unsigned int ipc_buffer_max = 0;
static unsigned int pick_ipc_buffer(unsigned int max);
static inline void
crm_ipc_init(void)
{
if (hdr_offset == 0) {
hdr_offset = sizeof(struct crm_ipc_response_header);
}
if (ipc_buffer_max == 0) {
ipc_buffer_max = pick_ipc_buffer(0);
}
}
unsigned int
crm_ipc_default_buffer_size(void)
{
return pick_ipc_buffer(0);
}
static char *
generateReference(const char *custom1, const char *custom2)
{
static uint ref_counter = 0;
const char *local_cust1 = custom1;
const char *local_cust2 = custom2;
int reference_len = 4;
char *since_epoch = NULL;
reference_len += 20; /* too big */
reference_len += 40; /* too big */
if (local_cust1 == NULL) {
local_cust1 = "_empty_";
}
reference_len += strlen(local_cust1);
if (local_cust2 == NULL) {
local_cust2 = "_empty_";
}
reference_len += strlen(local_cust2);
since_epoch = calloc(1, reference_len);
if (since_epoch != NULL) {
sprintf(since_epoch, "%s-%s-%lu-%u",
local_cust1, local_cust2, (unsigned long)time(NULL), ref_counter++);
}
return since_epoch;
}
xmlNode *
create_request_adv(const char *task, xmlNode * msg_data,
const char *host_to, const char *sys_to,
const char *sys_from, const char *uuid_from, const char *origin)
{
char *true_from = NULL;
xmlNode *request = NULL;
char *reference = generateReference(task, sys_from);
if (uuid_from != NULL) {
true_from = generate_hash_key(sys_from, uuid_from);
} else if (sys_from != NULL) {
true_from = strdup(sys_from);
} else {
crm_err("No sys from specified");
}
/* host_from will get set for us if necessary by CRMd when routed */
request = create_xml_node(NULL, __FUNCTION__);
crm_xml_add(request, F_CRM_ORIGIN, origin);
crm_xml_add(request, F_TYPE, T_CRM);
crm_xml_add(request, F_CRM_VERSION, CRM_FEATURE_SET);
crm_xml_add(request, F_CRM_MSG_TYPE, XML_ATTR_REQUEST);
crm_xml_add(request, F_CRM_REFERENCE, reference);
crm_xml_add(request, F_CRM_TASK, task);
crm_xml_add(request, F_CRM_SYS_TO, sys_to);
crm_xml_add(request, F_CRM_SYS_FROM, true_from);
/* HOSTTO will be ignored if it is to the DC anyway. */
if (host_to != NULL && strlen(host_to) > 0) {
crm_xml_add(request, F_CRM_HOST_TO, host_to);
}
if (msg_data != NULL) {
add_message_xml(request, F_CRM_DATA, msg_data);
}
free(reference);
free(true_from);
return request;
}
/*
* This method adds a copy of xml_response_data
*/
xmlNode *
create_reply_adv(xmlNode * original_request, xmlNode * xml_response_data, const char *origin)
{
xmlNode *reply = NULL;
const char *host_from = crm_element_value(original_request, F_CRM_HOST_FROM);
const char *sys_from = crm_element_value(original_request, F_CRM_SYS_FROM);
const char *sys_to = crm_element_value(original_request, F_CRM_SYS_TO);
const char *type = crm_element_value(original_request, F_CRM_MSG_TYPE);
const char *operation = crm_element_value(original_request, F_CRM_TASK);
const char *crm_msg_reference = crm_element_value(original_request, F_CRM_REFERENCE);
if (type == NULL) {
crm_err("Cannot create new_message, no message type in original message");
CRM_ASSERT(type != NULL);
return NULL;
#if 0
} else if (strcasecmp(XML_ATTR_REQUEST, type) != 0) {
crm_err("Cannot create new_message, original message was not a request");
return NULL;
#endif
}
reply = create_xml_node(NULL, __FUNCTION__);
if (reply == NULL) {
crm_err("Cannot create new_message, malloc failed");
return NULL;
}
crm_xml_add(reply, F_CRM_ORIGIN, origin);
crm_xml_add(reply, F_TYPE, T_CRM);
crm_xml_add(reply, F_CRM_VERSION, CRM_FEATURE_SET);
crm_xml_add(reply, F_CRM_MSG_TYPE, XML_ATTR_RESPONSE);
crm_xml_add(reply, F_CRM_REFERENCE, crm_msg_reference);
crm_xml_add(reply, F_CRM_TASK, operation);
/* since this is a reply, we reverse the from and to */
crm_xml_add(reply, F_CRM_SYS_TO, sys_from);
crm_xml_add(reply, F_CRM_SYS_FROM, sys_to);
/* HOSTTO will be ignored if it is to the DC anyway. */
if (host_from != NULL && strlen(host_from) > 0) {
crm_xml_add(reply, F_CRM_HOST_TO, host_from);
}
if (xml_response_data != NULL) {
add_message_xml(reply, F_CRM_DATA, xml_response_data);
}
return reply;
}
/* Libqb based IPC */
/* Server... */
GHashTable *client_connections = NULL;
crm_client_t *
crm_client_get(qb_ipcs_connection_t * c)
{
if (client_connections) {
return g_hash_table_lookup(client_connections, c);
}
crm_trace("No client found for %p", c);
return NULL;
}
crm_client_t *
crm_client_get_by_id(const char *id)
{
gpointer key;
crm_client_t *client;
GHashTableIter iter;
if (client_connections && id) {
g_hash_table_iter_init(&iter, client_connections);
while (g_hash_table_iter_next(&iter, &key, (gpointer *) & client)) {
if (strcmp(client->id, id) == 0) {
return client;
}
}
}
crm_trace("No client found with id=%s", id);
return NULL;
}
const char *
crm_client_name(crm_client_t * c)
{
if (c == NULL) {
return "null";
} else if (c->name == NULL && c->id == NULL) {
return "unknown";
} else if (c->name == NULL) {
return c->id;
} else {
return c->name;
}
}
void
crm_client_init(void)
{
if (client_connections == NULL) {
crm_trace("Creating client hash table");
client_connections = g_hash_table_new(g_direct_hash, g_direct_equal);
}
}
void
crm_client_cleanup(void)
{
if (client_connections != NULL) {
int active = g_hash_table_size(client_connections);
if (active) {
crm_err("Exiting with %d active connections", active);
}
g_hash_table_destroy(client_connections); client_connections = NULL;
}
}
void
crm_client_disconnect_all(qb_ipcs_service_t *service)
{
qb_ipcs_connection_t *c = NULL;
if (service == NULL) {
return;
}
c = qb_ipcs_connection_first_get(service);
while (c != NULL) {
qb_ipcs_connection_t *last = c;
c = qb_ipcs_connection_next_get(service, last);
/* There really shouldn't be anyone connected at this point */
crm_notice("Disconnecting client %p, pid=%d...", last, crm_ipcs_client_pid(last));
qb_ipcs_disconnect(last);
qb_ipcs_connection_unref(last);
}
}
crm_client_t *
crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client)
{
static uid_t uid_server = 0;
static gid_t gid_cluster = 0;
crm_client_t *client = NULL;
CRM_LOG_ASSERT(c);
if (c == NULL) {
return NULL;
}
if (gid_cluster == 0) {
uid_server = getuid();
if(crm_user_lookup(CRM_DAEMON_USER, NULL, &gid_cluster) < 0) {
static bool have_error = FALSE;
if(have_error == FALSE) {
crm_warn("Could not find group for user %s", CRM_DAEMON_USER);
have_error = TRUE;
}
}
}
if(gid_cluster != 0 && gid_client != 0) {
uid_t best_uid = -1; /* Passing -1 to chown(2) means don't change */
if(uid_client == 0 || uid_server == 0) { /* Someone is priveliged, but the other may not be */
best_uid = QB_MAX(uid_client, uid_server);
crm_trace("Allowing user %u to clean up after disconnect", best_uid);
}
crm_trace("Giving access to group %u", gid_cluster);
qb_ipcs_connection_auth_set(c, best_uid, gid_cluster, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
}
crm_client_init();
/* TODO: Do our own auth checking, return NULL if unauthorized */
client = calloc(1, sizeof(crm_client_t));
client->ipcs = c;
client->kind = CRM_CLIENT_IPC;
client->pid = crm_ipcs_client_pid(c);
client->id = crm_generate_uuid();
crm_debug("Connecting %p for uid=%d gid=%d pid=%u id=%s", c, uid_client, gid_client, client->pid, client->id);
#if ENABLE_ACL
client->user = uid2username(uid_client);
#endif
g_hash_table_insert(client_connections, c, client);
return client;
}
void
crm_client_destroy(crm_client_t * c)
{
if (c == NULL) {
return;
}
if (client_connections) {
if (c->ipcs) {
crm_trace("Destroying %p/%p (%d remaining)",
c, c->ipcs, crm_hash_table_size(client_connections) - 1);
g_hash_table_remove(client_connections, c->ipcs);
} else {
crm_trace("Destroying remote connection %p (%d remaining)",
c, crm_hash_table_size(client_connections) - 1);
g_hash_table_remove(client_connections, c->id);
}
}
if (c->event_timer) {
g_source_remove(c->event_timer);
}
crm_debug("Destroying %d events", g_list_length(c->event_queue));
while (c->event_queue) {
struct iovec *event = c->event_queue->data;
c->event_queue = g_list_remove(c->event_queue, event);
free(event[0].iov_base);
free(event[1].iov_base);
free(event);
}
free(c->id);
free(c->name);
free(c->user);
if (c->remote) {
if (c->remote->auth_timeout) {
g_source_remove(c->remote->auth_timeout);
}
free(c->remote->buffer);
free(c->remote);
}
free(c);
}
int
crm_ipcs_client_pid(qb_ipcs_connection_t * c)
{
struct qb_ipcs_connection_stats stats;
stats.client_pid = 0;
qb_ipcs_connection_stats_get(c, &stats, 0);
return stats.client_pid;
}
xmlNode *
crm_ipcs_recv(crm_client_t * c, void *data, size_t size, uint32_t * id, uint32_t * flags)
{
xmlNode *xml = NULL;
char *uncompressed = NULL;
char *text = ((char *)data) + sizeof(struct crm_ipc_response_header);
struct crm_ipc_response_header *header = data;
if (id) {
*id = ((struct qb_ipc_response_header *)data)->id;
}
if (flags) {
*flags = header->flags;
}
if (is_set(header->flags, crm_ipc_proxied)) {
/* mark this client as being the endpoint of a proxy connection.
* Proxy connections responses are sent on the event channel to avoid
* blocking the proxy daemon (crmd) */
c->flags |= crm_client_flag_ipc_proxied;
}
if(header->version > PCMK_IPC_VERSION) {
crm_err("Filtering incompatible v%d IPC message, we only support versions <= %d",
header->version, PCMK_IPC_VERSION);
return NULL;
}
if (header->size_compressed) {
int rc = 0;
unsigned int size_u = 1 + header->size_uncompressed;
uncompressed = calloc(1, size_u);
crm_trace("Decompressing message data %u bytes into %u bytes",
header->size_compressed, size_u);
rc = BZ2_bzBuffToBuffDecompress(uncompressed, &size_u, text, header->size_compressed, 1, 0);
text = uncompressed;
if (rc != BZ_OK) {
crm_err("Decompression failed: %s (%d)", bz2_strerror(rc), rc);
free(uncompressed);
return NULL;
}
}
CRM_ASSERT(text[header->size_uncompressed - 1] == 0);
crm_trace("Received %.200s", text);
xml = string2xml(text);
free(uncompressed);
return xml;
}
ssize_t crm_ipcs_flush_events(crm_client_t * c);
static gboolean
crm_ipcs_flush_events_cb(gpointer data)
{
crm_client_t *c = data;
c->event_timer = 0;
crm_ipcs_flush_events(c);
return FALSE;
}
ssize_t
crm_ipcs_flush_events(crm_client_t * c)
{
int sent = 0;
ssize_t rc = 0;
int queue_len = 0;
if (c == NULL) {
return pcmk_ok;
} else if (c->event_timer) {
/* There is already a timer, wait until it goes off */
crm_trace("Timer active for %p - %d", c->ipcs, c->event_timer);
return pcmk_ok;
}
queue_len = g_list_length(c->event_queue);
while (c->event_queue && sent < 100) {
struct crm_ipc_response_header *header = NULL;
struct iovec *event = c->event_queue->data;
rc = qb_ipcs_event_sendv(c->ipcs, event, 2);
if (rc < 0) {
break;
}
sent++;
header = event[0].iov_base;
if (header->size_compressed) {
crm_trace("Event %d to %p[%d] (%lld compressed bytes) sent",
header->qb.id, c->ipcs, c->pid, (long long) rc);
} else {
crm_trace("Event %d to %p[%d] (%lld bytes) sent: %.120s",
header->qb.id, c->ipcs, c->pid, (long long) rc,
(char *) (event[1].iov_base));
}
c->event_queue = g_list_remove(c->event_queue, event);
free(event[0].iov_base);
free(event[1].iov_base);
free(event);
}
queue_len -= sent;
if (sent > 0 || c->event_queue) {
crm_trace("Sent %d events (%d remaining) for %p[%d]: %s (%lld)",
sent, queue_len, c->ipcs, c->pid,
pcmk_strerror(rc < 0 ? rc : 0), (long long) rc);
}
if (c->event_queue) {
if (queue_len % 100 == 0 && queue_len > 99) {
crm_warn("Event queue for %p[%d] has grown to %d", c->ipcs, c->pid, queue_len);
} else if (queue_len > 500) {
crm_err("Evicting slow client %p[%d]: event queue reached %d entries",
c->ipcs, c->pid, queue_len);
qb_ipcs_disconnect(c->ipcs);
return rc;
}
c->event_timer = g_timeout_add(1000 + 100 * queue_len, crm_ipcs_flush_events_cb, c);
}
return rc;
}
ssize_t
crm_ipc_prepare(uint32_t request, xmlNode * message, struct iovec ** result, uint32_t max_send_size)
{
static unsigned int biggest = 0;
struct iovec *iov;
unsigned int total = 0;
char *compressed = NULL;
char *buffer = dump_xml_unformatted(message);
struct crm_ipc_response_header *header = calloc(1, sizeof(struct crm_ipc_response_header));
CRM_ASSERT(result != NULL);
crm_ipc_init();
if (max_send_size == 0) {
max_send_size = ipc_buffer_max;
}
CRM_LOG_ASSERT(max_send_size != 0);
*result = NULL;
iov = calloc(2, sizeof(struct iovec));
iov[0].iov_len = hdr_offset;
iov[0].iov_base = header;
header->version = PCMK_IPC_VERSION;
header->size_uncompressed = 1 + strlen(buffer);
total = iov[0].iov_len + header->size_uncompressed;
if (total < max_send_size) {
iov[1].iov_base = buffer;
iov[1].iov_len = header->size_uncompressed;
} else {
unsigned int new_size = 0;
if (crm_compress_string
(buffer, header->size_uncompressed, max_send_size, &compressed, &new_size)) {
header->flags |= crm_ipc_compressed;
header->size_compressed = new_size;
iov[1].iov_len = header->size_compressed;
iov[1].iov_base = compressed;
free(buffer);
biggest = QB_MAX(header->size_compressed, biggest);
} else {
ssize_t rc = -EMSGSIZE;
crm_log_xml_trace(message, "EMSGSIZE");
biggest = QB_MAX(header->size_uncompressed, biggest);
crm_err
("Could not compress the message (%u bytes) into less than the configured ipc limit (%u bytes). "
"Set PCMK_ipc_buffer to a higher value (%u bytes suggested)",
header->size_uncompressed, max_send_size, 4 * biggest);
free(compressed);
free(buffer);
free(header);
free(iov);
return rc;
}
}
header->qb.size = iov[0].iov_len + iov[1].iov_len;
header->qb.id = (int32_t)request; /* Replying to a specific request */
*result = iov;
CRM_ASSERT(header->qb.size > 0);
return header->qb.size;
}
ssize_t
crm_ipcs_sendv(crm_client_t * c, struct iovec * iov, enum crm_ipc_flags flags)
{
ssize_t rc;
static uint32_t id = 1;
struct crm_ipc_response_header *header = iov[0].iov_base;
if (c->flags & crm_client_flag_ipc_proxied) {
/* _ALL_ replies to proxied connections need to be sent as events */
if (is_not_set(flags, crm_ipc_server_event)) {
flags |= crm_ipc_server_event;
/* this flag lets us know this was originally meant to be a response.
* even though we're sending it over the event channel. */
flags |= crm_ipc_proxied_relay_response;
}
}
header->flags |= flags;
if (flags & crm_ipc_server_event) {
header->qb.id = id++; /* We don't really use it, but doesn't hurt to set one */
if (flags & crm_ipc_server_free) {
crm_trace("Sending the original to %p[%d]", c->ipcs, c->pid);
c->event_queue = g_list_append(c->event_queue, iov);
} else {
struct iovec *iov_copy = calloc(2, sizeof(struct iovec));
crm_trace("Sending a copy to %p[%d]", c->ipcs, c->pid);
iov_copy[0].iov_len = iov[0].iov_len;
iov_copy[0].iov_base = malloc(iov[0].iov_len);
memcpy(iov_copy[0].iov_base, iov[0].iov_base, iov[0].iov_len);
iov_copy[1].iov_len = iov[1].iov_len;
iov_copy[1].iov_base = malloc(iov[1].iov_len);
memcpy(iov_copy[1].iov_base, iov[1].iov_base, iov[1].iov_len);
c->event_queue = g_list_append(c->event_queue, iov_copy);
}
} else {
CRM_LOG_ASSERT(header->qb.id != 0); /* Replying to a specific request */
rc = qb_ipcs_response_sendv(c->ipcs, iov, 2);
if (rc < header->qb.size) {
crm_notice("Response %d to %p[%d] (%u bytes) failed: %s (%d)",
header->qb.id, c->ipcs, c->pid, header->qb.size, pcmk_strerror(rc), rc);
} else {
crm_trace("Response %d sent, %lld bytes to %p[%d]",
header->qb.id, (long long) rc, c->ipcs, c->pid);
}
if (flags & crm_ipc_server_free) {
free(iov[0].iov_base);
free(iov[1].iov_base);
free(iov);
}
}
if (flags & crm_ipc_server_event) {
rc = crm_ipcs_flush_events(c);
} else {
crm_ipcs_flush_events(c);
}
if (rc == -EPIPE || rc == -ENOTCONN) {
crm_trace("Client %p disconnected", c->ipcs);
}
return rc;
}
ssize_t
crm_ipcs_send(crm_client_t * c, uint32_t request, xmlNode * message,
enum crm_ipc_flags flags)
{
struct iovec *iov = NULL;
ssize_t rc = 0;
if(c == NULL) {
return -EDESTADDRREQ;
}
crm_ipc_init();
rc = crm_ipc_prepare(request, message, &iov, ipc_buffer_max);
if (rc > 0) {
rc = crm_ipcs_sendv(c, iov, flags | crm_ipc_server_free);
} else {
free(iov);
crm_notice("Message to %p[%d] failed: %s (%d)",
c->ipcs, c->pid, pcmk_strerror(rc), rc);
}
return rc;
}
void
crm_ipcs_send_ack(crm_client_t * c, uint32_t request, uint32_t flags, const char *tag, const char *function,
int line)
{
if (flags & crm_ipc_client_response) {
xmlNode *ack = create_xml_node(NULL, tag);
crm_trace("Ack'ing msg from %s (%p)", crm_client_name(c), c);
c->request_id = 0;
crm_xml_add(ack, "function", function);
crm_xml_add_int(ack, "line", line);
crm_ipcs_send(c, request, ack, flags);
free_xml(ack);
}
}
/* Client... */
#define MIN_MSG_SIZE 12336 /* sizeof(struct qb_ipc_connection_response) */
#define MAX_MSG_SIZE 128*1024 /* 128k default */
struct crm_ipc_s {
struct pollfd pfd;
/* the max size we can send/receive over ipc */
unsigned int max_buf_size;
/* Size of the allocated 'buffer' */
unsigned int buf_size;
int msg_size;
int need_reply;
char *buffer;
char *name;
uint32_t buffer_flags;
qb_ipcc_connection_t *ipc;
};
static unsigned int
pick_ipc_buffer(unsigned int max)
{
static unsigned int global_max = 0;
if (global_max == 0) {
const char *env = getenv("PCMK_ipc_buffer");
if (env) {
int env_max = crm_parse_int(env, "0");
global_max = (env_max > 0)? QB_MAX(MIN_MSG_SIZE, env_max) : MAX_MSG_SIZE;
} else {
global_max = MAX_MSG_SIZE;
}
}
return QB_MAX(max, global_max);
}
crm_ipc_t *
crm_ipc_new(const char *name, size_t max_size)
{
crm_ipc_t *client = NULL;
client = calloc(1, sizeof(crm_ipc_t));
client->name = strdup(name);
client->buf_size = pick_ipc_buffer(max_size);
client->buffer = malloc(client->buf_size);
/* Clients initiating connection pick the max buf size */
client->max_buf_size = client->buf_size;
client->pfd.fd = -1;
client->pfd.events = POLLIN;
client->pfd.revents = 0;
return client;
}
/*!
* \brief Establish an IPC connection to a Pacemaker component
*
* \param[in] client Connection instance obtained from crm_ipc_new()
*
* \return TRUE on success, FALSE otherwise (in which case errno will be set)
*/
bool
crm_ipc_connect(crm_ipc_t * client)
{
client->need_reply = FALSE;
client->ipc = qb_ipcc_connect(client->name, client->buf_size);
if (client->ipc == NULL) {
crm_debug("Could not establish %s connection: %s (%d)", client->name, pcmk_strerror(errno), errno);
return FALSE;
}
client->pfd.fd = crm_ipc_get_fd(client);
if (client->pfd.fd < 0) {
crm_debug("Could not obtain file descriptor for %s connection: %s (%d)", client->name, pcmk_strerror(errno), errno);
return FALSE;
}
qb_ipcc_context_set(client->ipc, client);
#ifdef HAVE_IPCS_GET_BUFFER_SIZE
client->max_buf_size = qb_ipcc_get_buffer_size(client->ipc);
if (client->max_buf_size > client->buf_size) {
free(client->buffer);
client->buffer = calloc(1, client->max_buf_size);
client->buf_size = client->max_buf_size;
}
#endif
return TRUE;
}
void
crm_ipc_close(crm_ipc_t * client)
{
if (client) {
crm_trace("Disconnecting %s IPC connection %p (%p)", client->name, client, client->ipc);
if (client->ipc) {
qb_ipcc_connection_t *ipc = client->ipc;
client->ipc = NULL;
qb_ipcc_disconnect(ipc);
}
}
}
void
crm_ipc_destroy(crm_ipc_t * client)
{
if (client) {
if (client->ipc && qb_ipcc_is_connected(client->ipc)) {
crm_notice("Destroying an active IPC connection to %s", client->name);
/* The next line is basically unsafe
*
* If this connection was attached to mainloop and mainloop is active,
* the 'disconnected' callback will end up back here and we'll end
* up free'ing the memory twice - something that can still happen
* even without this if we destroy a connection and it closes before
* we call exit
*/
/* crm_ipc_close(client); */
}
crm_trace("Destroying IPC connection to %s: %p", client->name, client);
free(client->buffer);
free(client->name);
free(client);
}
}
int
crm_ipc_get_fd(crm_ipc_t * client)
{
int fd = 0;
if (client && client->ipc && (qb_ipcc_fd_get(client->ipc, &fd) == 0)) {
return fd;
}
errno = EINVAL;
crm_perror(LOG_ERR, "Could not obtain file IPC descriptor for %s",
(client? client->name : "unspecified client"));
return -errno;
}
bool
crm_ipc_connected(crm_ipc_t * client)
{
bool rc = FALSE;
if (client == NULL) {
crm_trace("No client");
return FALSE;
} else if (client->ipc == NULL) {
crm_trace("No connection");
return FALSE;
} else if (client->pfd.fd < 0) {
crm_trace("Bad descriptor");
return FALSE;
}
rc = qb_ipcc_is_connected(client->ipc);
if (rc == FALSE) {
client->pfd.fd = -EINVAL;
}
return rc;
}
/*!
* \brief Check whether an IPC connection is ready to be read
*
* \param[in] client Connection to check
*
* \return Positive value if ready to be read, 0 if not ready, -errno on error
*/
int
crm_ipc_ready(crm_ipc_t *client)
{
int rc;
CRM_ASSERT(client != NULL);
if (crm_ipc_connected(client) == FALSE) {
return -ENOTCONN;
}
client->pfd.revents = 0;
rc = poll(&(client->pfd), 1, 0);
return (rc < 0)? -errno : rc;
}
static int
crm_ipc_decompress(crm_ipc_t * client)
{
struct crm_ipc_response_header *header = (struct crm_ipc_response_header *)(void*)client->buffer;
if (header->size_compressed) {
int rc = 0;
unsigned int size_u = 1 + header->size_uncompressed;
/* never let buf size fall below our max size required for ipc reads. */
unsigned int new_buf_size = QB_MAX((hdr_offset + size_u), client->max_buf_size);
char *uncompressed = calloc(1, new_buf_size);
crm_trace("Decompressing message data %u bytes into %u bytes",
header->size_compressed, size_u);
rc = BZ2_bzBuffToBuffDecompress(uncompressed + hdr_offset, &size_u,
client->buffer + hdr_offset, header->size_compressed, 1, 0);
if (rc != BZ_OK) {
crm_err("Decompression failed: %s (%d)", bz2_strerror(rc), rc);
free(uncompressed);
return -EILSEQ;
}
/*
* This assert no longer holds true. For an identical msg, some clients may
* require compression, and others may not. If that same msg (event) is sent
* to multiple clients, it could result in some clients receiving a compressed
* msg even though compression was not explicitly required for them.
*
* CRM_ASSERT((header->size_uncompressed + hdr_offset) >= ipc_buffer_max);
*/
CRM_ASSERT(size_u == header->size_uncompressed);
memcpy(uncompressed, client->buffer, hdr_offset); /* Preserve the header */
header = (struct crm_ipc_response_header *)(void*)uncompressed;
free(client->buffer);
client->buf_size = new_buf_size;
client->buffer = uncompressed;
}
CRM_ASSERT(client->buffer[hdr_offset + header->size_uncompressed - 1] == 0);
return pcmk_ok;
}
long
crm_ipc_read(crm_ipc_t * client)
{
struct crm_ipc_response_header *header = NULL;
CRM_ASSERT(client != NULL);
CRM_ASSERT(client->ipc != NULL);
CRM_ASSERT(client->buffer != NULL);
crm_ipc_init();
client->buffer[0] = 0;
client->msg_size = qb_ipcc_event_recv(client->ipc, client->buffer, client->buf_size - 1, 0);
if (client->msg_size >= 0) {
int rc = crm_ipc_decompress(client);
if (rc != pcmk_ok) {
return rc;
}
header = (struct crm_ipc_response_header *)(void*)client->buffer;
if(header->version > PCMK_IPC_VERSION) {
crm_err("Filtering incompatible v%d IPC message, we only support versions <= %d",
header->version, PCMK_IPC_VERSION);
return -EBADMSG;
}
crm_trace("Received %s event %d, size=%u, rc=%d, text: %.100s",
client->name, header->qb.id, header->qb.size, client->msg_size,
client->buffer + hdr_offset);
} else {
crm_trace("No message from %s received: %s", client->name, pcmk_strerror(client->msg_size));
}
if (crm_ipc_connected(client) == FALSE || client->msg_size == -ENOTCONN) {
crm_err("Connection to %s failed", client->name);
}
if (header) {
/* Data excluding the header */
return header->size_uncompressed;
}
return -ENOMSG;
}
const char *
crm_ipc_buffer(crm_ipc_t * client)
{
CRM_ASSERT(client != NULL);
return client->buffer + sizeof(struct crm_ipc_response_header);
}
uint32_t
crm_ipc_buffer_flags(crm_ipc_t * client)
{
struct crm_ipc_response_header *header = NULL;
CRM_ASSERT(client != NULL);
if (client->buffer == NULL) {
return 0;
}
header = (struct crm_ipc_response_header *)(void*)client->buffer;
return header->flags;
}
const char *
crm_ipc_name(crm_ipc_t * client)
{
CRM_ASSERT(client != NULL);
return client->name;
}
static int
internal_ipc_send_recv(crm_ipc_t * client, const void *iov)
{
int rc = 0;
do {
rc = qb_ipcc_sendv_recv(client->ipc, iov, 2, client->buffer, client->buf_size, -1);
} while (rc == -EAGAIN && crm_ipc_connected(client));
return rc;
}
static int
internal_ipc_send_request(crm_ipc_t * client, const void *iov, int ms_timeout)
{
int rc = 0;
time_t timeout = time(NULL) + 1 + (ms_timeout / 1000);
do {
rc = qb_ipcc_sendv(client->ipc, iov, 2);
} while (rc == -EAGAIN && time(NULL) < timeout && crm_ipc_connected(client));
return rc;
}
static int
internal_ipc_get_reply(crm_ipc_t * client, int request_id, int ms_timeout)
{
time_t timeout = time(NULL) + 1 + (ms_timeout / 1000);
int rc = 0;
crm_ipc_init();
/* get the reply */
crm_trace("client %s waiting on reply to msg id %d", client->name, request_id);
do {
rc = qb_ipcc_recv(client->ipc, client->buffer, client->buf_size, 1000);
if (rc > 0) {
struct crm_ipc_response_header *hdr = NULL;
int rc = crm_ipc_decompress(client);
if (rc != pcmk_ok) {
return rc;
}
hdr = (struct crm_ipc_response_header *)(void*)client->buffer;
if (hdr->qb.id == request_id) {
/* Got it */
break;
} else if (hdr->qb.id < request_id) {
xmlNode *bad = string2xml(crm_ipc_buffer(client));
crm_err("Discarding old reply %d (need %d)", hdr->qb.id, request_id);
crm_log_xml_notice(bad, "OldIpcReply");
} else {
xmlNode *bad = string2xml(crm_ipc_buffer(client));
crm_err("Discarding newer reply %d (need %d)", hdr->qb.id, request_id);
crm_log_xml_notice(bad, "ImpossibleReply");
CRM_ASSERT(hdr->qb.id <= request_id);
}
} else if (crm_ipc_connected(client) == FALSE) {
crm_err("Server disconnected client %s while waiting for msg id %d", client->name,
request_id);
break;
}
} while (time(NULL) < timeout);
return rc;
}
int
crm_ipc_send(crm_ipc_t * client, xmlNode * message, enum crm_ipc_flags flags, int32_t ms_timeout,
xmlNode ** reply)
{
long rc = 0;
struct iovec *iov;
static uint32_t id = 0;
static int factor = 8;
struct crm_ipc_response_header *header;
crm_ipc_init();
if (client == NULL) {
crm_notice("Invalid connection");
return -ENOTCONN;
} else if (crm_ipc_connected(client) == FALSE) {
/* Don't even bother */
crm_notice("Connection to %s closed", client->name);
return -ENOTCONN;
}
if (ms_timeout == 0) {
ms_timeout = 5000;
}
if (client->need_reply) {
crm_trace("Trying again to obtain pending reply from %s", client->name);
rc = qb_ipcc_recv(client->ipc, client->buffer, client->buf_size, ms_timeout);
if (rc < 0) {
crm_warn("Sending to %s (%p) is disabled until pending reply is received", client->name,
client->ipc);
return -EALREADY;
} else {
crm_notice("Lost reply from %s (%p) finally arrived, sending re-enabled", client->name,
client->ipc);
client->need_reply = FALSE;
}
}
id++;
CRM_LOG_ASSERT(id != 0); /* Crude wrap-around detection */
rc = crm_ipc_prepare(id, message, &iov, client->max_buf_size);
if(rc < 0) {
return rc;
}
header = iov[0].iov_base;
header->flags |= flags;
if(is_set(flags, crm_ipc_proxied)) {
/* Don't look for a synchronous response */
clear_bit(flags, crm_ipc_client_response);
}
if(header->size_compressed) {
if(factor < 10 && (client->max_buf_size / 10) < (rc / factor)) {
crm_notice("Compressed message exceeds %d0%% of the configured ipc limit (%u bytes), "
"consider setting PCMK_ipc_buffer to %u or higher",
factor, client->max_buf_size, 2 * client->max_buf_size);
factor++;
}
}
crm_trace("Sending from client: %s request id: %d bytes: %u timeout:%d msg...",
client->name, header->qb.id, header->qb.size, ms_timeout);
if (ms_timeout > 0 || is_not_set(flags, crm_ipc_client_response)) {
rc = internal_ipc_send_request(client, iov, ms_timeout);
if (rc <= 0) {
crm_trace("Failed to send from client %s request %d with %u bytes...",
client->name, header->qb.id, header->qb.size);
goto send_cleanup;
} else if (is_not_set(flags, crm_ipc_client_response)) {
crm_trace("Message sent, not waiting for reply to %d from %s to %u bytes...",
header->qb.id, client->name, header->qb.size);
goto send_cleanup;
}
rc = internal_ipc_get_reply(client, header->qb.id, ms_timeout);
if (rc < 0) {
/* No reply, for now, disable sending
*
* The alternative is to close the connection since we don't know
* how to detect and discard out-of-sequence replies
*
* TODO - implement the above
*/
client->need_reply = TRUE;
}
} else {
rc = internal_ipc_send_recv(client, iov);
}
if (rc > 0) {
struct crm_ipc_response_header *hdr = (struct crm_ipc_response_header *)(void*)client->buffer;
crm_trace("Received response %d, size=%u, rc=%ld, text: %.200s", hdr->qb.id, hdr->qb.size,
rc, crm_ipc_buffer(client));
if (reply) {
*reply = string2xml(crm_ipc_buffer(client));
}
} else {
crm_trace("Response not received: rc=%ld, errno=%d", rc, errno);
}
send_cleanup:
if (crm_ipc_connected(client) == FALSE) {
crm_notice("Connection to %s closed: %s (%ld)", client->name, pcmk_strerror(rc), rc);
} else if (rc == -ETIMEDOUT) {
crm_warn("Request %d to %s (%p) failed: %s (%ld) after %dms",
header->qb.id, client->name, client->ipc, pcmk_strerror(rc), rc, ms_timeout);
crm_write_blackbox(0, NULL);
} else if (rc <= 0) {
crm_warn("Request %d to %s (%p) failed: %s (%ld)",
header->qb.id, client->name, client->ipc, pcmk_strerror(rc), rc);
}
free(header);
free(iov[1].iov_base);
free(iov);
return rc;
}
/* Utils */
xmlNode *
create_hello_message(const char *uuid,
const char *client_name, const char *major_version, const char *minor_version)
{
xmlNode *hello_node = NULL;
xmlNode *hello = NULL;
if (uuid == NULL || strlen(uuid) == 0
|| client_name == NULL || strlen(client_name) == 0
|| major_version == NULL || strlen(major_version) == 0
|| minor_version == NULL || strlen(minor_version) == 0) {
crm_err("Missing fields, Hello message will not be valid.");
return NULL;
}
hello_node = create_xml_node(NULL, XML_TAG_OPTIONS);
crm_xml_add(hello_node, "major_version", major_version);
crm_xml_add(hello_node, "minor_version", minor_version);
crm_xml_add(hello_node, "client_name", client_name);
crm_xml_add(hello_node, "client_uuid", uuid);
crm_trace("creating hello message");
hello = create_request(CRM_OP_HELLO, hello_node, NULL, NULL, client_name, uuid);
free_xml(hello_node);
return hello;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5243_0 |
crossvul-cpp_data_good_5266_0 | /* modules/m_sasl.c
* Copyright (C) 2006 Michael Tharp <gxti@partiallystapled.com>
* Copyright (C) 2006 charybdis development team
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2.Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3.The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: m_sasl.c 1409 2006-05-21 14:46:17Z jilles $
*/
#include "stdinc.h"
#include "client.h"
#include "hash.h"
#include "send.h"
#include "msg.h"
#include "modules.h"
#include "numeric.h"
#include "s_serv.h"
#include "s_stats.h"
#include "string.h"
#include "s_newconf.h"
#include "s_conf.h"
static int m_authenticate(struct Client *, struct Client *, int, const char **);
static int me_sasl(struct Client *, struct Client *, int, const char **);
static void abort_sasl(struct Client *);
static void abort_sasl_exit(hook_data_client_exit *);
static void advertise_sasl(struct Client *);
static void advertise_sasl_exit(hook_data_client_exit *);
struct Message authenticate_msgtab = {
"AUTHENTICATE", 0, 0, 0, MFLG_SLOW,
{{m_authenticate, 2}, {m_authenticate, 2}, mg_ignore, mg_ignore, mg_ignore, {m_authenticate, 2}}
};
struct Message sasl_msgtab = {
"SASL", 0, 0, 0, MFLG_SLOW,
{mg_ignore, mg_ignore, mg_ignore, mg_ignore, {me_sasl, 5}, mg_ignore}
};
mapi_clist_av1 sasl_clist[] = {
&authenticate_msgtab, &sasl_msgtab, NULL
};
mapi_hfn_list_av1 sasl_hfnlist[] = {
{ "new_local_user", (hookfn) abort_sasl },
{ "client_exit", (hookfn) abort_sasl_exit },
{ "new_remote_user", (hookfn) advertise_sasl },
{ "client_exit", (hookfn) advertise_sasl_exit },
{ NULL, NULL }
};
DECLARE_MODULE_AV1(sasl, NULL, NULL, sasl_clist, NULL, sasl_hfnlist, "$Revision: 1409 $");
static int
m_authenticate(struct Client *client_p, struct Client *source_p,
int parc, const char *parv[])
{
struct Client *agent_p = NULL;
struct Client *saslserv_p = NULL;
/* They really should use CAP for their own sake. */
if(!IsCapable(source_p, CLICAP_SASL))
return 0;
if (strlen(client_p->id) == 3)
{
exit_client(client_p, client_p, client_p, "Mixing client and server protocol");
return 0;
}
if (*parv[1] == ':' || strchr(parv[1], ' '))
{
exit_client(client_p, client_p, client_p, "Malformed AUTHENTICATE");
return 0;
}
saslserv_p = find_named_client(ConfigFileEntry.sasl_service);
if (saslserv_p == NULL || !IsService(saslserv_p))
{
sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name);
return 0;
}
if(source_p->localClient->sasl_complete)
{
*source_p->localClient->sasl_agent = '\0';
source_p->localClient->sasl_complete = 0;
}
if(strlen(parv[1]) > 400)
{
sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name);
return 0;
}
if(!*source_p->id)
{
/* Allocate a UID. */
strcpy(source_p->id, generate_uid());
add_to_id_hash(source_p->id, source_p);
}
if(*source_p->localClient->sasl_agent)
agent_p = find_id(source_p->localClient->sasl_agent);
if(agent_p == NULL)
{
sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s",
me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id,
source_p->host, source_p->sockhost);
if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL)
sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s",
me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id,
parv[1], source_p->certfp);
else
sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s",
me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id,
parv[1]);
rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN);
}
else
sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s",
me.id, agent_p->servptr->name, source_p->id, agent_p->id,
parv[1]);
source_p->localClient->sasl_out++;
return 0;
}
static int
me_sasl(struct Client *client_p, struct Client *source_p,
int parc, const char *parv[])
{
struct Client *target_p, *agent_p;
/* Let propagate if not addressed to us, or if broadcast.
* Only SASL agents can answer global requests.
*/
if(strncmp(parv[2], me.id, 3))
return 0;
if((target_p = find_id(parv[2])) == NULL)
return 0;
if((agent_p = find_id(parv[1])) == NULL)
return 0;
if(source_p != agent_p->servptr) /* WTF?! */
return 0;
/* We only accept messages from SASL agents; these must have umode +S
* (so the server must be listed in a service{} block).
*/
if(!IsService(agent_p))
return 0;
/* Reject if someone has already answered. */
if(*target_p->localClient->sasl_agent && strncmp(parv[1], target_p->localClient->sasl_agent, IDLEN))
return 0;
else if(!*target_p->localClient->sasl_agent)
rb_strlcpy(target_p->localClient->sasl_agent, parv[1], IDLEN);
if(*parv[3] == 'C')
sendto_one(target_p, "AUTHENTICATE %s", parv[4]);
else if(*parv[3] == 'D')
{
if(*parv[4] == 'F')
sendto_one(target_p, form_str(ERR_SASLFAIL), me.name, EmptyString(target_p->name) ? "*" : target_p->name);
else if(*parv[4] == 'S') {
sendto_one(target_p, form_str(RPL_SASLSUCCESS), me.name, EmptyString(target_p->name) ? "*" : target_p->name);
target_p->localClient->sasl_complete = 1;
ServerStats.is_ssuc++;
}
*target_p->localClient->sasl_agent = '\0'; /* Blank the stored agent so someone else can answer */
}
else if(*parv[3] == 'M')
sendto_one(target_p, form_str(RPL_SASLMECHS), me.name, EmptyString(target_p->name) ? "*" : target_p->name, parv[4]);
return 0;
}
/* If the client never finished authenticating but is
* registering anyway, abort the exchange.
*/
static void
abort_sasl(struct Client *data)
{
if(data->localClient->sasl_out == 0 || data->localClient->sasl_complete)
return;
data->localClient->sasl_out = data->localClient->sasl_complete = 0;
ServerStats.is_sbad++;
if(!IsClosing(data))
sendto_one(data, form_str(ERR_SASLABORTED), me.name, EmptyString(data->name) ? "*" : data->name);
if(*data->localClient->sasl_agent)
{
struct Client *agent_p = find_id(data->localClient->sasl_agent);
if(agent_p)
{
sendto_one(agent_p, ":%s ENCAP %s SASL %s %s D A", me.id, agent_p->servptr->name,
data->id, agent_p->id);
return;
}
}
sendto_server(NULL, NULL, CAP_TS6|CAP_ENCAP, NOCAPS, ":%s ENCAP * SASL %s * D A", me.id,
data->id);
}
static void
abort_sasl_exit(hook_data_client_exit *data)
{
if (data->target->localClient)
abort_sasl(data->target);
}
static void
advertise_sasl(struct Client *client_p)
{
if (!ConfigFileEntry.sasl_service)
return;
if (irccmp(client_p->name, ConfigFileEntry.sasl_service))
return;
sendto_local_clients_with_capability(CLICAP_CAP_NOTIFY, ":%s CAP * NEW :sasl", me.name);
}
static void
advertise_sasl_exit(hook_data_client_exit *data)
{
if (!ConfigFileEntry.sasl_service)
return;
if (irccmp(data->target->name, ConfigFileEntry.sasl_service))
return;
sendto_local_clients_with_capability(CLICAP_CAP_NOTIFY, ":%s CAP * DEL :sasl", me.name);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5266_0 |
crossvul-cpp_data_bad_5246_8 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2006 NEC Corporation
*
* Created by KaiGai Kohei <kaigai@ak.jp.nec.com>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/crc32.h>
#include <linux/jffs2.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/mtd/mtd.h>
#include "nodelist.h"
static size_t jffs2_acl_size(int count)
{
if (count <= 4) {
return sizeof(struct jffs2_acl_header)
+ count * sizeof(struct jffs2_acl_entry_short);
} else {
return sizeof(struct jffs2_acl_header)
+ 4 * sizeof(struct jffs2_acl_entry_short)
+ (count - 4) * sizeof(struct jffs2_acl_entry);
}
}
static int jffs2_acl_count(size_t size)
{
size_t s;
size -= sizeof(struct jffs2_acl_header);
if (size < 4 * sizeof(struct jffs2_acl_entry_short)) {
if (size % sizeof(struct jffs2_acl_entry_short))
return -1;
return size / sizeof(struct jffs2_acl_entry_short);
} else {
s = size - 4 * sizeof(struct jffs2_acl_entry_short);
if (s % sizeof(struct jffs2_acl_entry))
return -1;
return s / sizeof(struct jffs2_acl_entry) + 4;
}
}
static struct posix_acl *jffs2_acl_from_medium(void *value, size_t size)
{
void *end = value + size;
struct jffs2_acl_header *header = value;
struct jffs2_acl_entry *entry;
struct posix_acl *acl;
uint32_t ver;
int i, count;
if (!value)
return NULL;
if (size < sizeof(struct jffs2_acl_header))
return ERR_PTR(-EINVAL);
ver = je32_to_cpu(header->a_version);
if (ver != JFFS2_ACL_VERSION) {
JFFS2_WARNING("Invalid ACL version. (=%u)\n", ver);
return ERR_PTR(-EINVAL);
}
value += sizeof(struct jffs2_acl_header);
count = jffs2_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i=0; i < count; i++) {
entry = value;
if (value + sizeof(struct jffs2_acl_entry_short) > end)
goto fail;
acl->a_entries[i].e_tag = je16_to_cpu(entry->e_tag);
acl->a_entries[i].e_perm = je16_to_cpu(entry->e_perm);
switch (acl->a_entries[i].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value += sizeof(struct jffs2_acl_entry_short);
break;
case ACL_USER:
value += sizeof(struct jffs2_acl_entry);
if (value > end)
goto fail;
acl->a_entries[i].e_uid =
make_kuid(&init_user_ns,
je32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value += sizeof(struct jffs2_acl_entry);
if (value > end)
goto fail;
acl->a_entries[i].e_gid =
make_kgid(&init_user_ns,
je32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
static void *jffs2_acl_to_medium(const struct posix_acl *acl, size_t *size)
{
struct jffs2_acl_header *header;
struct jffs2_acl_entry *entry;
void *e;
size_t i;
*size = jffs2_acl_size(acl->a_count);
header = kmalloc(sizeof(*header) + acl->a_count * sizeof(*entry), GFP_KERNEL);
if (!header)
return ERR_PTR(-ENOMEM);
header->a_version = cpu_to_je32(JFFS2_ACL_VERSION);
e = header + 1;
for (i=0; i < acl->a_count; i++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[i];
entry = e;
entry->e_tag = cpu_to_je16(acl_e->e_tag);
entry->e_perm = cpu_to_je16(acl_e->e_perm);
switch(acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_je32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(struct jffs2_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_je32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(struct jffs2_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(struct jffs2_acl_entry_short);
break;
default:
goto fail;
}
}
return header;
fail:
kfree(header);
return ERR_PTR(-EINVAL);
}
struct posix_acl *jffs2_get_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
char *value = NULL;
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
break;
default:
BUG();
}
rc = do_jffs2_getxattr(inode, xprefix, "", NULL, 0);
if (rc > 0) {
value = kmalloc(rc, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
rc = do_jffs2_getxattr(inode, xprefix, "", value, rc);
}
if (rc > 0) {
acl = jffs2_acl_from_medium(value, rc);
} else if (rc == -ENODATA || rc == -ENOSYS) {
acl = NULL;
} else {
acl = ERR_PTR(rc);
}
kfree(value);
return acl;
}
static int __jffs2_set_acl(struct inode *inode, int xprefix, struct posix_acl *acl)
{
char *value = NULL;
size_t size = 0;
int rc;
if (acl) {
value = jffs2_acl_to_medium(acl, &size);
if (IS_ERR(value))
return PTR_ERR(value);
}
rc = do_jffs2_setxattr(inode, xprefix, "", value, size, 0);
if (!value && rc == -ENODATA)
rc = 0;
kfree(value);
return rc;
}
int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
if (acl) {
umode_t mode = inode->i_mode;
rc = posix_acl_equiv_mode(acl, &mode);
if (rc < 0)
return rc;
if (inode->i_mode != mode) {
struct iattr attr;
attr.ia_valid = ATTR_MODE | ATTR_CTIME;
attr.ia_mode = mode;
attr.ia_ctime = CURRENT_TIME_SEC;
rc = jffs2_do_setattr(inode, &attr);
if (rc < 0)
return rc;
}
if (rc == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
rc = __jffs2_set_acl(inode, xprefix, acl);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
int jffs2_init_acl_pre(struct inode *dir_i, struct inode *inode, umode_t *i_mode)
{
struct posix_acl *default_acl, *acl;
int rc;
cache_no_acl(inode);
rc = posix_acl_create(dir_i, i_mode, &default_acl, &acl);
if (rc)
return rc;
if (default_acl) {
set_cached_acl(inode, ACL_TYPE_DEFAULT, default_acl);
posix_acl_release(default_acl);
}
if (acl) {
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
posix_acl_release(acl);
}
return 0;
}
int jffs2_init_acl_post(struct inode *inode)
{
int rc;
if (inode->i_default_acl) {
rc = __jffs2_set_acl(inode, JFFS2_XPREFIX_ACL_DEFAULT, inode->i_default_acl);
if (rc)
return rc;
}
if (inode->i_acl) {
rc = __jffs2_set_acl(inode, JFFS2_XPREFIX_ACL_ACCESS, inode->i_acl);
if (rc)
return rc;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_8 |
crossvul-cpp_data_bad_5246_1 | /*
* Copyright (C) 2007 Red Hat. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/posix_acl.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include "ctree.h"
#include "btrfs_inode.h"
#include "xattr.h"
struct posix_acl *btrfs_get_acl(struct inode *inode, int type)
{
int size;
const char *name;
char *value = NULL;
struct posix_acl *acl;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
size = __btrfs_getxattr(inode, name, "", 0);
if (size > 0) {
value = kzalloc(size, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
size = __btrfs_getxattr(inode, name, value, size);
}
if (size > 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
} else if (size == -ERANGE || size == -ENODATA || size == 0) {
acl = NULL;
} else {
acl = ERR_PTR(-EIO);
}
kfree(value);
return acl;
}
/*
* Needs to be called with fs_mutex held
*/
static int __btrfs_set_acl(struct btrfs_trans_handle *trans,
struct inode *inode, struct posix_acl *acl, int type)
{
int ret, size = 0;
const char *name;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_equiv_mode(acl, &inode->i_mode);
if (ret < 0)
return ret;
if (ret == 0)
acl = NULL;
}
ret = 0;
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode))
return acl ? -EINVAL : 0;
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out;
}
ret = __btrfs_setxattr(trans, inode, name, value, size, 0);
out:
kfree(value);
if (!ret)
set_cached_acl(inode, type, acl);
return ret;
}
int btrfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
return __btrfs_set_acl(NULL, inode, acl, type);
}
/*
* btrfs_init_acl is already generally called under fs_mutex, so the locking
* stuff has been fixed to work with that. If the locking stuff changes, we
* need to re-evaluate the acl locking stuff.
*/
int btrfs_init_acl(struct btrfs_trans_handle *trans,
struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int ret = 0;
/* this happens with subvols */
if (!dir)
return 0;
ret = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (ret)
return ret;
if (default_acl) {
ret = __btrfs_set_acl(trans, inode, default_acl,
ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!ret)
ret = __btrfs_set_acl(trans, inode, acl,
ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
if (!default_acl && !acl)
cache_no_acl(inode);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_1 |
crossvul-cpp_data_bad_5246_13 | #include <linux/capability.h>
#include <linux/fs.h>
#include <linux/posix_acl.h>
#include "reiserfs.h"
#include <linux/errno.h>
#include <linux/pagemap.h>
#include <linux/xattr.h>
#include <linux/slab.h>
#include <linux/posix_acl_xattr.h>
#include "xattr.h"
#include "acl.h"
#include <linux/uaccess.h>
static int __reiserfs_set_acl(struct reiserfs_transaction_handle *th,
struct inode *inode, int type,
struct posix_acl *acl);
int
reiserfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error, error2;
struct reiserfs_transaction_handle th;
size_t jcreate_blocks;
int size = acl ? posix_acl_xattr_size(acl->a_count) : 0;
/*
* Pessimism: We can't assume that anything from the xattr root up
* has been created.
*/
jcreate_blocks = reiserfs_xattr_jcreate_nblocks(inode) +
reiserfs_xattr_nblocks(inode, size) * 2;
reiserfs_write_lock(inode->i_sb);
error = journal_begin(&th, inode->i_sb, jcreate_blocks);
reiserfs_write_unlock(inode->i_sb);
if (error == 0) {
error = __reiserfs_set_acl(&th, inode, type, acl);
reiserfs_write_lock(inode->i_sb);
error2 = journal_end(&th);
reiserfs_write_unlock(inode->i_sb);
if (error2)
error = error2;
}
return error;
}
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *reiserfs_posix_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(reiserfs_acl_header))
return ERR_PTR(-EINVAL);
if (((reiserfs_acl_header *) value)->a_version !=
cpu_to_le32(REISERFS_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(reiserfs_acl_header);
count = reiserfs_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
reiserfs_acl_entry *entry = (reiserfs_acl_entry *) value;
if ((char *)value + sizeof(reiserfs_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(reiserfs_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(reiserfs_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(reiserfs_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *reiserfs_posix_acl_to_disk(const struct posix_acl *acl, size_t * size)
{
reiserfs_acl_header *ext_acl;
char *e;
int n;
*size = reiserfs_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(reiserfs_acl_header) +
acl->a_count *
sizeof(reiserfs_acl_entry),
GFP_NOFS);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(REISERFS_ACL_VERSION);
e = (char *)ext_acl + sizeof(reiserfs_acl_header);
for (n = 0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
reiserfs_acl_entry *entry = (reiserfs_acl_entry *) e;
entry->e_tag = cpu_to_le16(acl->a_entries[n].e_tag);
entry->e_perm = cpu_to_le16(acl->a_entries[n].e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(reiserfs_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(reiserfs_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(reiserfs_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* Inode operation get_posix_acl().
*
* inode->i_mutex: down
* BKL held [before 2.5.x]
*/
struct posix_acl *reiserfs_get_acl(struct inode *inode, int type)
{
char *name, *value;
struct posix_acl *acl;
int size;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
size = reiserfs_xattr_get(inode, name, NULL, 0);
if (size < 0) {
if (size == -ENODATA || size == -ENOSYS)
return NULL;
return ERR_PTR(size);
}
value = kmalloc(size, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = reiserfs_xattr_get(inode, name, value, size);
if (retval == -ENODATA || retval == -ENOSYS) {
/*
* This shouldn't actually happen as it should have
* been caught above.. but just in case
*/
acl = NULL;
} else if (retval < 0) {
acl = ERR_PTR(retval);
} else {
acl = reiserfs_posix_acl_from_disk(value, retval);
}
kfree(value);
return acl;
}
/*
* Inode operation set_posix_acl().
*
* inode->i_mutex: down
* BKL held [before 2.5.x]
*/
static int
__reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
/*
* dir->i_mutex: locked,
* inode is new and not released into the wild yet
*/
int
reiserfs_inherit_default_acl(struct reiserfs_transaction_handle *th,
struct inode *dir, struct dentry *dentry,
struct inode *inode)
{
struct posix_acl *default_acl, *acl;
int err = 0;
/* ACLs only get applied to files and directories */
if (S_ISLNK(inode->i_mode))
return 0;
/*
* ACLs can only be used on "new" objects, so if it's an old object
* there is nothing to inherit from
*/
if (get_inode_sd_version(dir) == STAT_DATA_V1)
goto apply_umask;
/*
* Don't apply ACLs to objects in the .reiserfs_priv tree.. This
* would be useless since permissions are ignored, and a pain because
* it introduces locking cycles
*/
if (IS_PRIVATE(dir)) {
inode->i_flags |= S_PRIVATE;
goto apply_umask;
}
err = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (err)
return err;
if (default_acl) {
err = __reiserfs_set_acl(th, inode, ACL_TYPE_DEFAULT,
default_acl);
posix_acl_release(default_acl);
}
if (acl) {
if (!err)
err = __reiserfs_set_acl(th, inode, ACL_TYPE_ACCESS,
acl);
posix_acl_release(acl);
}
return err;
apply_umask:
/* no ACL, apply umask */
inode->i_mode &= ~current_umask();
return err;
}
/* This is used to cache the default acl before a new object is created.
* The biggest reason for this is to get an idea of how many blocks will
* actually be required for the create operation if we must inherit an ACL.
* An ACL write can add up to 3 object creations and an additional file write
* so we'd prefer not to reserve that many blocks in the journal if we can.
* It also has the advantage of not loading the ACL with a transaction open,
* this may seem silly, but if the owner of the directory is doing the
* creation, the ACL may not be loaded since the permissions wouldn't require
* it.
* We return the number of blocks required for the transaction.
*/
int reiserfs_cache_default_acl(struct inode *inode)
{
struct posix_acl *acl;
int nblocks = 0;
if (IS_PRIVATE(inode))
return 0;
acl = get_acl(inode, ACL_TYPE_DEFAULT);
if (acl && !IS_ERR(acl)) {
int size = reiserfs_acl_size(acl->a_count);
/* Other xattrs can be created during inode creation. We don't
* want to claim too many blocks, so we check to see if we
* we need to create the tree to the xattrs, and then we
* just want two files. */
nblocks = reiserfs_xattr_jcreate_nblocks(inode);
nblocks += JOURNAL_BLOCKS_PER_OBJECT(inode->i_sb);
REISERFS_I(inode)->i_flags |= i_has_xattr_dir;
/* We need to account for writes + bitmaps for two files */
nblocks += reiserfs_xattr_nblocks(inode, size) * 4;
posix_acl_release(acl);
}
return nblocks;
}
/*
* Called under i_mutex
*/
int reiserfs_acl_chmod(struct inode *inode)
{
if (IS_PRIVATE(inode))
return 0;
if (get_inode_sd_version(inode) == STAT_DATA_V1 ||
!reiserfs_posixacl(inode->i_sb))
return 0;
return posix_acl_chmod(inode, inode->i_mode);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_13 |
crossvul-cpp_data_good_5243_0 | /*
* Copyright (C) 2004 Andrew Beekhof <andrew@beekhof.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <crm_internal.h>
#include <sys/param.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#include <errno.h>
#include <fcntl.h>
#include <bzlib.h>
#include <crm/crm.h>
#include <crm/msg_xml.h>
#include <crm/common/ipc.h>
#include <crm/common/ipcs.h>
#define PCMK_IPC_VERSION 1
struct crm_ipc_response_header {
struct qb_ipc_response_header qb;
uint32_t size_uncompressed;
uint32_t size_compressed;
uint32_t flags;
uint8_t version; /* Protect against version changes for anyone that might bother to statically link us */
};
static int hdr_offset = 0;
static unsigned int ipc_buffer_max = 0;
static unsigned int pick_ipc_buffer(unsigned int max);
static inline void
crm_ipc_init(void)
{
if (hdr_offset == 0) {
hdr_offset = sizeof(struct crm_ipc_response_header);
}
if (ipc_buffer_max == 0) {
ipc_buffer_max = pick_ipc_buffer(0);
}
}
unsigned int
crm_ipc_default_buffer_size(void)
{
return pick_ipc_buffer(0);
}
static char *
generateReference(const char *custom1, const char *custom2)
{
static uint ref_counter = 0;
const char *local_cust1 = custom1;
const char *local_cust2 = custom2;
int reference_len = 4;
char *since_epoch = NULL;
reference_len += 20; /* too big */
reference_len += 40; /* too big */
if (local_cust1 == NULL) {
local_cust1 = "_empty_";
}
reference_len += strlen(local_cust1);
if (local_cust2 == NULL) {
local_cust2 = "_empty_";
}
reference_len += strlen(local_cust2);
since_epoch = calloc(1, reference_len);
if (since_epoch != NULL) {
sprintf(since_epoch, "%s-%s-%lu-%u",
local_cust1, local_cust2, (unsigned long)time(NULL), ref_counter++);
}
return since_epoch;
}
xmlNode *
create_request_adv(const char *task, xmlNode * msg_data,
const char *host_to, const char *sys_to,
const char *sys_from, const char *uuid_from, const char *origin)
{
char *true_from = NULL;
xmlNode *request = NULL;
char *reference = generateReference(task, sys_from);
if (uuid_from != NULL) {
true_from = generate_hash_key(sys_from, uuid_from);
} else if (sys_from != NULL) {
true_from = strdup(sys_from);
} else {
crm_err("No sys from specified");
}
/* host_from will get set for us if necessary by CRMd when routed */
request = create_xml_node(NULL, __FUNCTION__);
crm_xml_add(request, F_CRM_ORIGIN, origin);
crm_xml_add(request, F_TYPE, T_CRM);
crm_xml_add(request, F_CRM_VERSION, CRM_FEATURE_SET);
crm_xml_add(request, F_CRM_MSG_TYPE, XML_ATTR_REQUEST);
crm_xml_add(request, F_CRM_REFERENCE, reference);
crm_xml_add(request, F_CRM_TASK, task);
crm_xml_add(request, F_CRM_SYS_TO, sys_to);
crm_xml_add(request, F_CRM_SYS_FROM, true_from);
/* HOSTTO will be ignored if it is to the DC anyway. */
if (host_to != NULL && strlen(host_to) > 0) {
crm_xml_add(request, F_CRM_HOST_TO, host_to);
}
if (msg_data != NULL) {
add_message_xml(request, F_CRM_DATA, msg_data);
}
free(reference);
free(true_from);
return request;
}
/*
* This method adds a copy of xml_response_data
*/
xmlNode *
create_reply_adv(xmlNode * original_request, xmlNode * xml_response_data, const char *origin)
{
xmlNode *reply = NULL;
const char *host_from = crm_element_value(original_request, F_CRM_HOST_FROM);
const char *sys_from = crm_element_value(original_request, F_CRM_SYS_FROM);
const char *sys_to = crm_element_value(original_request, F_CRM_SYS_TO);
const char *type = crm_element_value(original_request, F_CRM_MSG_TYPE);
const char *operation = crm_element_value(original_request, F_CRM_TASK);
const char *crm_msg_reference = crm_element_value(original_request, F_CRM_REFERENCE);
if (type == NULL) {
crm_err("Cannot create new_message, no message type in original message");
CRM_ASSERT(type != NULL);
return NULL;
#if 0
} else if (strcasecmp(XML_ATTR_REQUEST, type) != 0) {
crm_err("Cannot create new_message, original message was not a request");
return NULL;
#endif
}
reply = create_xml_node(NULL, __FUNCTION__);
if (reply == NULL) {
crm_err("Cannot create new_message, malloc failed");
return NULL;
}
crm_xml_add(reply, F_CRM_ORIGIN, origin);
crm_xml_add(reply, F_TYPE, T_CRM);
crm_xml_add(reply, F_CRM_VERSION, CRM_FEATURE_SET);
crm_xml_add(reply, F_CRM_MSG_TYPE, XML_ATTR_RESPONSE);
crm_xml_add(reply, F_CRM_REFERENCE, crm_msg_reference);
crm_xml_add(reply, F_CRM_TASK, operation);
/* since this is a reply, we reverse the from and to */
crm_xml_add(reply, F_CRM_SYS_TO, sys_from);
crm_xml_add(reply, F_CRM_SYS_FROM, sys_to);
/* HOSTTO will be ignored if it is to the DC anyway. */
if (host_from != NULL && strlen(host_from) > 0) {
crm_xml_add(reply, F_CRM_HOST_TO, host_from);
}
if (xml_response_data != NULL) {
add_message_xml(reply, F_CRM_DATA, xml_response_data);
}
return reply;
}
/* Libqb based IPC */
/* Server... */
GHashTable *client_connections = NULL;
crm_client_t *
crm_client_get(qb_ipcs_connection_t * c)
{
if (client_connections) {
return g_hash_table_lookup(client_connections, c);
}
crm_trace("No client found for %p", c);
return NULL;
}
crm_client_t *
crm_client_get_by_id(const char *id)
{
gpointer key;
crm_client_t *client;
GHashTableIter iter;
if (client_connections && id) {
g_hash_table_iter_init(&iter, client_connections);
while (g_hash_table_iter_next(&iter, &key, (gpointer *) & client)) {
if (strcmp(client->id, id) == 0) {
return client;
}
}
}
crm_trace("No client found with id=%s", id);
return NULL;
}
const char *
crm_client_name(crm_client_t * c)
{
if (c == NULL) {
return "null";
} else if (c->name == NULL && c->id == NULL) {
return "unknown";
} else if (c->name == NULL) {
return c->id;
} else {
return c->name;
}
}
void
crm_client_init(void)
{
if (client_connections == NULL) {
crm_trace("Creating client hash table");
client_connections = g_hash_table_new(g_direct_hash, g_direct_equal);
}
}
void
crm_client_cleanup(void)
{
if (client_connections != NULL) {
int active = g_hash_table_size(client_connections);
if (active) {
crm_err("Exiting with %d active connections", active);
}
g_hash_table_destroy(client_connections); client_connections = NULL;
}
}
void
crm_client_disconnect_all(qb_ipcs_service_t *service)
{
qb_ipcs_connection_t *c = NULL;
if (service == NULL) {
return;
}
c = qb_ipcs_connection_first_get(service);
while (c != NULL) {
qb_ipcs_connection_t *last = c;
c = qb_ipcs_connection_next_get(service, last);
/* There really shouldn't be anyone connected at this point */
crm_notice("Disconnecting client %p, pid=%d...", last, crm_ipcs_client_pid(last));
qb_ipcs_disconnect(last);
qb_ipcs_connection_unref(last);
}
}
crm_client_t *
crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client)
{
static gid_t gid_cluster = 0;
crm_client_t *client = NULL;
CRM_LOG_ASSERT(c);
if (c == NULL) {
return NULL;
}
if (gid_cluster == 0) {
if(crm_user_lookup(CRM_DAEMON_USER, NULL, &gid_cluster) < 0) {
static bool have_error = FALSE;
if(have_error == FALSE) {
crm_warn("Could not find group for user %s", CRM_DAEMON_USER);
have_error = TRUE;
}
}
}
if (uid_client != 0) {
crm_trace("Giving access to group %u", gid_cluster);
/* Passing -1 to chown(2) means don't change */
qb_ipcs_connection_auth_set(c, -1, gid_cluster, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
}
crm_client_init();
/* TODO: Do our own auth checking, return NULL if unauthorized */
client = calloc(1, sizeof(crm_client_t));
client->ipcs = c;
client->kind = CRM_CLIENT_IPC;
client->pid = crm_ipcs_client_pid(c);
client->id = crm_generate_uuid();
crm_debug("Connecting %p for uid=%d gid=%d pid=%u id=%s", c, uid_client, gid_client, client->pid, client->id);
#if ENABLE_ACL
client->user = uid2username(uid_client);
#endif
g_hash_table_insert(client_connections, c, client);
return client;
}
void
crm_client_destroy(crm_client_t * c)
{
if (c == NULL) {
return;
}
if (client_connections) {
if (c->ipcs) {
crm_trace("Destroying %p/%p (%d remaining)",
c, c->ipcs, crm_hash_table_size(client_connections) - 1);
g_hash_table_remove(client_connections, c->ipcs);
} else {
crm_trace("Destroying remote connection %p (%d remaining)",
c, crm_hash_table_size(client_connections) - 1);
g_hash_table_remove(client_connections, c->id);
}
}
if (c->event_timer) {
g_source_remove(c->event_timer);
}
crm_debug("Destroying %d events", g_list_length(c->event_queue));
while (c->event_queue) {
struct iovec *event = c->event_queue->data;
c->event_queue = g_list_remove(c->event_queue, event);
free(event[0].iov_base);
free(event[1].iov_base);
free(event);
}
free(c->id);
free(c->name);
free(c->user);
if (c->remote) {
if (c->remote->auth_timeout) {
g_source_remove(c->remote->auth_timeout);
}
free(c->remote->buffer);
free(c->remote);
}
free(c);
}
int
crm_ipcs_client_pid(qb_ipcs_connection_t * c)
{
struct qb_ipcs_connection_stats stats;
stats.client_pid = 0;
qb_ipcs_connection_stats_get(c, &stats, 0);
return stats.client_pid;
}
xmlNode *
crm_ipcs_recv(crm_client_t * c, void *data, size_t size, uint32_t * id, uint32_t * flags)
{
xmlNode *xml = NULL;
char *uncompressed = NULL;
char *text = ((char *)data) + sizeof(struct crm_ipc_response_header);
struct crm_ipc_response_header *header = data;
if (id) {
*id = ((struct qb_ipc_response_header *)data)->id;
}
if (flags) {
*flags = header->flags;
}
if (is_set(header->flags, crm_ipc_proxied)) {
/* mark this client as being the endpoint of a proxy connection.
* Proxy connections responses are sent on the event channel to avoid
* blocking the proxy daemon (crmd) */
c->flags |= crm_client_flag_ipc_proxied;
}
if(header->version > PCMK_IPC_VERSION) {
crm_err("Filtering incompatible v%d IPC message, we only support versions <= %d",
header->version, PCMK_IPC_VERSION);
return NULL;
}
if (header->size_compressed) {
int rc = 0;
unsigned int size_u = 1 + header->size_uncompressed;
uncompressed = calloc(1, size_u);
crm_trace("Decompressing message data %u bytes into %u bytes",
header->size_compressed, size_u);
rc = BZ2_bzBuffToBuffDecompress(uncompressed, &size_u, text, header->size_compressed, 1, 0);
text = uncompressed;
if (rc != BZ_OK) {
crm_err("Decompression failed: %s (%d)", bz2_strerror(rc), rc);
free(uncompressed);
return NULL;
}
}
CRM_ASSERT(text[header->size_uncompressed - 1] == 0);
crm_trace("Received %.200s", text);
xml = string2xml(text);
free(uncompressed);
return xml;
}
ssize_t crm_ipcs_flush_events(crm_client_t * c);
static gboolean
crm_ipcs_flush_events_cb(gpointer data)
{
crm_client_t *c = data;
c->event_timer = 0;
crm_ipcs_flush_events(c);
return FALSE;
}
ssize_t
crm_ipcs_flush_events(crm_client_t * c)
{
int sent = 0;
ssize_t rc = 0;
int queue_len = 0;
if (c == NULL) {
return pcmk_ok;
} else if (c->event_timer) {
/* There is already a timer, wait until it goes off */
crm_trace("Timer active for %p - %d", c->ipcs, c->event_timer);
return pcmk_ok;
}
queue_len = g_list_length(c->event_queue);
while (c->event_queue && sent < 100) {
struct crm_ipc_response_header *header = NULL;
struct iovec *event = c->event_queue->data;
rc = qb_ipcs_event_sendv(c->ipcs, event, 2);
if (rc < 0) {
break;
}
sent++;
header = event[0].iov_base;
if (header->size_compressed) {
crm_trace("Event %d to %p[%d] (%lld compressed bytes) sent",
header->qb.id, c->ipcs, c->pid, (long long) rc);
} else {
crm_trace("Event %d to %p[%d] (%lld bytes) sent: %.120s",
header->qb.id, c->ipcs, c->pid, (long long) rc,
(char *) (event[1].iov_base));
}
c->event_queue = g_list_remove(c->event_queue, event);
free(event[0].iov_base);
free(event[1].iov_base);
free(event);
}
queue_len -= sent;
if (sent > 0 || c->event_queue) {
crm_trace("Sent %d events (%d remaining) for %p[%d]: %s (%lld)",
sent, queue_len, c->ipcs, c->pid,
pcmk_strerror(rc < 0 ? rc : 0), (long long) rc);
}
if (c->event_queue) {
if (queue_len % 100 == 0 && queue_len > 99) {
crm_warn("Event queue for %p[%d] has grown to %d", c->ipcs, c->pid, queue_len);
} else if (queue_len > 500) {
crm_err("Evicting slow client %p[%d]: event queue reached %d entries",
c->ipcs, c->pid, queue_len);
qb_ipcs_disconnect(c->ipcs);
return rc;
}
c->event_timer = g_timeout_add(1000 + 100 * queue_len, crm_ipcs_flush_events_cb, c);
}
return rc;
}
ssize_t
crm_ipc_prepare(uint32_t request, xmlNode * message, struct iovec ** result, uint32_t max_send_size)
{
static unsigned int biggest = 0;
struct iovec *iov;
unsigned int total = 0;
char *compressed = NULL;
char *buffer = dump_xml_unformatted(message);
struct crm_ipc_response_header *header = calloc(1, sizeof(struct crm_ipc_response_header));
CRM_ASSERT(result != NULL);
crm_ipc_init();
if (max_send_size == 0) {
max_send_size = ipc_buffer_max;
}
CRM_LOG_ASSERT(max_send_size != 0);
*result = NULL;
iov = calloc(2, sizeof(struct iovec));
iov[0].iov_len = hdr_offset;
iov[0].iov_base = header;
header->version = PCMK_IPC_VERSION;
header->size_uncompressed = 1 + strlen(buffer);
total = iov[0].iov_len + header->size_uncompressed;
if (total < max_send_size) {
iov[1].iov_base = buffer;
iov[1].iov_len = header->size_uncompressed;
} else {
unsigned int new_size = 0;
if (crm_compress_string
(buffer, header->size_uncompressed, max_send_size, &compressed, &new_size)) {
header->flags |= crm_ipc_compressed;
header->size_compressed = new_size;
iov[1].iov_len = header->size_compressed;
iov[1].iov_base = compressed;
free(buffer);
biggest = QB_MAX(header->size_compressed, biggest);
} else {
ssize_t rc = -EMSGSIZE;
crm_log_xml_trace(message, "EMSGSIZE");
biggest = QB_MAX(header->size_uncompressed, biggest);
crm_err
("Could not compress the message (%u bytes) into less than the configured ipc limit (%u bytes). "
"Set PCMK_ipc_buffer to a higher value (%u bytes suggested)",
header->size_uncompressed, max_send_size, 4 * biggest);
free(compressed);
free(buffer);
free(header);
free(iov);
return rc;
}
}
header->qb.size = iov[0].iov_len + iov[1].iov_len;
header->qb.id = (int32_t)request; /* Replying to a specific request */
*result = iov;
CRM_ASSERT(header->qb.size > 0);
return header->qb.size;
}
ssize_t
crm_ipcs_sendv(crm_client_t * c, struct iovec * iov, enum crm_ipc_flags flags)
{
ssize_t rc;
static uint32_t id = 1;
struct crm_ipc_response_header *header = iov[0].iov_base;
if (c->flags & crm_client_flag_ipc_proxied) {
/* _ALL_ replies to proxied connections need to be sent as events */
if (is_not_set(flags, crm_ipc_server_event)) {
flags |= crm_ipc_server_event;
/* this flag lets us know this was originally meant to be a response.
* even though we're sending it over the event channel. */
flags |= crm_ipc_proxied_relay_response;
}
}
header->flags |= flags;
if (flags & crm_ipc_server_event) {
header->qb.id = id++; /* We don't really use it, but doesn't hurt to set one */
if (flags & crm_ipc_server_free) {
crm_trace("Sending the original to %p[%d]", c->ipcs, c->pid);
c->event_queue = g_list_append(c->event_queue, iov);
} else {
struct iovec *iov_copy = calloc(2, sizeof(struct iovec));
crm_trace("Sending a copy to %p[%d]", c->ipcs, c->pid);
iov_copy[0].iov_len = iov[0].iov_len;
iov_copy[0].iov_base = malloc(iov[0].iov_len);
memcpy(iov_copy[0].iov_base, iov[0].iov_base, iov[0].iov_len);
iov_copy[1].iov_len = iov[1].iov_len;
iov_copy[1].iov_base = malloc(iov[1].iov_len);
memcpy(iov_copy[1].iov_base, iov[1].iov_base, iov[1].iov_len);
c->event_queue = g_list_append(c->event_queue, iov_copy);
}
} else {
CRM_LOG_ASSERT(header->qb.id != 0); /* Replying to a specific request */
rc = qb_ipcs_response_sendv(c->ipcs, iov, 2);
if (rc < header->qb.size) {
crm_notice("Response %d to %p[%d] (%u bytes) failed: %s (%d)",
header->qb.id, c->ipcs, c->pid, header->qb.size, pcmk_strerror(rc), rc);
} else {
crm_trace("Response %d sent, %lld bytes to %p[%d]",
header->qb.id, (long long) rc, c->ipcs, c->pid);
}
if (flags & crm_ipc_server_free) {
free(iov[0].iov_base);
free(iov[1].iov_base);
free(iov);
}
}
if (flags & crm_ipc_server_event) {
rc = crm_ipcs_flush_events(c);
} else {
crm_ipcs_flush_events(c);
}
if (rc == -EPIPE || rc == -ENOTCONN) {
crm_trace("Client %p disconnected", c->ipcs);
}
return rc;
}
ssize_t
crm_ipcs_send(crm_client_t * c, uint32_t request, xmlNode * message,
enum crm_ipc_flags flags)
{
struct iovec *iov = NULL;
ssize_t rc = 0;
if(c == NULL) {
return -EDESTADDRREQ;
}
crm_ipc_init();
rc = crm_ipc_prepare(request, message, &iov, ipc_buffer_max);
if (rc > 0) {
rc = crm_ipcs_sendv(c, iov, flags | crm_ipc_server_free);
} else {
free(iov);
crm_notice("Message to %p[%d] failed: %s (%d)",
c->ipcs, c->pid, pcmk_strerror(rc), rc);
}
return rc;
}
void
crm_ipcs_send_ack(crm_client_t * c, uint32_t request, uint32_t flags, const char *tag, const char *function,
int line)
{
if (flags & crm_ipc_client_response) {
xmlNode *ack = create_xml_node(NULL, tag);
crm_trace("Ack'ing msg from %s (%p)", crm_client_name(c), c);
c->request_id = 0;
crm_xml_add(ack, "function", function);
crm_xml_add_int(ack, "line", line);
crm_ipcs_send(c, request, ack, flags);
free_xml(ack);
}
}
/* Client... */
#define MIN_MSG_SIZE 12336 /* sizeof(struct qb_ipc_connection_response) */
#define MAX_MSG_SIZE 128*1024 /* 128k default */
struct crm_ipc_s {
struct pollfd pfd;
/* the max size we can send/receive over ipc */
unsigned int max_buf_size;
/* Size of the allocated 'buffer' */
unsigned int buf_size;
int msg_size;
int need_reply;
char *buffer;
char *name;
uint32_t buffer_flags;
qb_ipcc_connection_t *ipc;
};
static unsigned int
pick_ipc_buffer(unsigned int max)
{
static unsigned int global_max = 0;
if (global_max == 0) {
const char *env = getenv("PCMK_ipc_buffer");
if (env) {
int env_max = crm_parse_int(env, "0");
global_max = (env_max > 0)? QB_MAX(MIN_MSG_SIZE, env_max) : MAX_MSG_SIZE;
} else {
global_max = MAX_MSG_SIZE;
}
}
return QB_MAX(max, global_max);
}
crm_ipc_t *
crm_ipc_new(const char *name, size_t max_size)
{
crm_ipc_t *client = NULL;
client = calloc(1, sizeof(crm_ipc_t));
client->name = strdup(name);
client->buf_size = pick_ipc_buffer(max_size);
client->buffer = malloc(client->buf_size);
/* Clients initiating connection pick the max buf size */
client->max_buf_size = client->buf_size;
client->pfd.fd = -1;
client->pfd.events = POLLIN;
client->pfd.revents = 0;
return client;
}
/*!
* \brief Establish an IPC connection to a Pacemaker component
*
* \param[in] client Connection instance obtained from crm_ipc_new()
*
* \return TRUE on success, FALSE otherwise (in which case errno will be set)
*/
bool
crm_ipc_connect(crm_ipc_t * client)
{
client->need_reply = FALSE;
client->ipc = qb_ipcc_connect(client->name, client->buf_size);
if (client->ipc == NULL) {
crm_debug("Could not establish %s connection: %s (%d)", client->name, pcmk_strerror(errno), errno);
return FALSE;
}
client->pfd.fd = crm_ipc_get_fd(client);
if (client->pfd.fd < 0) {
crm_debug("Could not obtain file descriptor for %s connection: %s (%d)", client->name, pcmk_strerror(errno), errno);
return FALSE;
}
qb_ipcc_context_set(client->ipc, client);
#ifdef HAVE_IPCS_GET_BUFFER_SIZE
client->max_buf_size = qb_ipcc_get_buffer_size(client->ipc);
if (client->max_buf_size > client->buf_size) {
free(client->buffer);
client->buffer = calloc(1, client->max_buf_size);
client->buf_size = client->max_buf_size;
}
#endif
return TRUE;
}
void
crm_ipc_close(crm_ipc_t * client)
{
if (client) {
crm_trace("Disconnecting %s IPC connection %p (%p)", client->name, client, client->ipc);
if (client->ipc) {
qb_ipcc_connection_t *ipc = client->ipc;
client->ipc = NULL;
qb_ipcc_disconnect(ipc);
}
}
}
void
crm_ipc_destroy(crm_ipc_t * client)
{
if (client) {
if (client->ipc && qb_ipcc_is_connected(client->ipc)) {
crm_notice("Destroying an active IPC connection to %s", client->name);
/* The next line is basically unsafe
*
* If this connection was attached to mainloop and mainloop is active,
* the 'disconnected' callback will end up back here and we'll end
* up free'ing the memory twice - something that can still happen
* even without this if we destroy a connection and it closes before
* we call exit
*/
/* crm_ipc_close(client); */
}
crm_trace("Destroying IPC connection to %s: %p", client->name, client);
free(client->buffer);
free(client->name);
free(client);
}
}
int
crm_ipc_get_fd(crm_ipc_t * client)
{
int fd = 0;
if (client && client->ipc && (qb_ipcc_fd_get(client->ipc, &fd) == 0)) {
return fd;
}
errno = EINVAL;
crm_perror(LOG_ERR, "Could not obtain file IPC descriptor for %s",
(client? client->name : "unspecified client"));
return -errno;
}
bool
crm_ipc_connected(crm_ipc_t * client)
{
bool rc = FALSE;
if (client == NULL) {
crm_trace("No client");
return FALSE;
} else if (client->ipc == NULL) {
crm_trace("No connection");
return FALSE;
} else if (client->pfd.fd < 0) {
crm_trace("Bad descriptor");
return FALSE;
}
rc = qb_ipcc_is_connected(client->ipc);
if (rc == FALSE) {
client->pfd.fd = -EINVAL;
}
return rc;
}
/*!
* \brief Check whether an IPC connection is ready to be read
*
* \param[in] client Connection to check
*
* \return Positive value if ready to be read, 0 if not ready, -errno on error
*/
int
crm_ipc_ready(crm_ipc_t *client)
{
int rc;
CRM_ASSERT(client != NULL);
if (crm_ipc_connected(client) == FALSE) {
return -ENOTCONN;
}
client->pfd.revents = 0;
rc = poll(&(client->pfd), 1, 0);
return (rc < 0)? -errno : rc;
}
static int
crm_ipc_decompress(crm_ipc_t * client)
{
struct crm_ipc_response_header *header = (struct crm_ipc_response_header *)(void*)client->buffer;
if (header->size_compressed) {
int rc = 0;
unsigned int size_u = 1 + header->size_uncompressed;
/* never let buf size fall below our max size required for ipc reads. */
unsigned int new_buf_size = QB_MAX((hdr_offset + size_u), client->max_buf_size);
char *uncompressed = calloc(1, new_buf_size);
crm_trace("Decompressing message data %u bytes into %u bytes",
header->size_compressed, size_u);
rc = BZ2_bzBuffToBuffDecompress(uncompressed + hdr_offset, &size_u,
client->buffer + hdr_offset, header->size_compressed, 1, 0);
if (rc != BZ_OK) {
crm_err("Decompression failed: %s (%d)", bz2_strerror(rc), rc);
free(uncompressed);
return -EILSEQ;
}
/*
* This assert no longer holds true. For an identical msg, some clients may
* require compression, and others may not. If that same msg (event) is sent
* to multiple clients, it could result in some clients receiving a compressed
* msg even though compression was not explicitly required for them.
*
* CRM_ASSERT((header->size_uncompressed + hdr_offset) >= ipc_buffer_max);
*/
CRM_ASSERT(size_u == header->size_uncompressed);
memcpy(uncompressed, client->buffer, hdr_offset); /* Preserve the header */
header = (struct crm_ipc_response_header *)(void*)uncompressed;
free(client->buffer);
client->buf_size = new_buf_size;
client->buffer = uncompressed;
}
CRM_ASSERT(client->buffer[hdr_offset + header->size_uncompressed - 1] == 0);
return pcmk_ok;
}
long
crm_ipc_read(crm_ipc_t * client)
{
struct crm_ipc_response_header *header = NULL;
CRM_ASSERT(client != NULL);
CRM_ASSERT(client->ipc != NULL);
CRM_ASSERT(client->buffer != NULL);
crm_ipc_init();
client->buffer[0] = 0;
client->msg_size = qb_ipcc_event_recv(client->ipc, client->buffer, client->buf_size - 1, 0);
if (client->msg_size >= 0) {
int rc = crm_ipc_decompress(client);
if (rc != pcmk_ok) {
return rc;
}
header = (struct crm_ipc_response_header *)(void*)client->buffer;
if(header->version > PCMK_IPC_VERSION) {
crm_err("Filtering incompatible v%d IPC message, we only support versions <= %d",
header->version, PCMK_IPC_VERSION);
return -EBADMSG;
}
crm_trace("Received %s event %d, size=%u, rc=%d, text: %.100s",
client->name, header->qb.id, header->qb.size, client->msg_size,
client->buffer + hdr_offset);
} else {
crm_trace("No message from %s received: %s", client->name, pcmk_strerror(client->msg_size));
}
if (crm_ipc_connected(client) == FALSE || client->msg_size == -ENOTCONN) {
crm_err("Connection to %s failed", client->name);
}
if (header) {
/* Data excluding the header */
return header->size_uncompressed;
}
return -ENOMSG;
}
const char *
crm_ipc_buffer(crm_ipc_t * client)
{
CRM_ASSERT(client != NULL);
return client->buffer + sizeof(struct crm_ipc_response_header);
}
uint32_t
crm_ipc_buffer_flags(crm_ipc_t * client)
{
struct crm_ipc_response_header *header = NULL;
CRM_ASSERT(client != NULL);
if (client->buffer == NULL) {
return 0;
}
header = (struct crm_ipc_response_header *)(void*)client->buffer;
return header->flags;
}
const char *
crm_ipc_name(crm_ipc_t * client)
{
CRM_ASSERT(client != NULL);
return client->name;
}
static int
internal_ipc_send_recv(crm_ipc_t * client, const void *iov)
{
int rc = 0;
do {
rc = qb_ipcc_sendv_recv(client->ipc, iov, 2, client->buffer, client->buf_size, -1);
} while (rc == -EAGAIN && crm_ipc_connected(client));
return rc;
}
static int
internal_ipc_send_request(crm_ipc_t * client, const void *iov, int ms_timeout)
{
int rc = 0;
time_t timeout = time(NULL) + 1 + (ms_timeout / 1000);
do {
rc = qb_ipcc_sendv(client->ipc, iov, 2);
} while (rc == -EAGAIN && time(NULL) < timeout && crm_ipc_connected(client));
return rc;
}
static int
internal_ipc_get_reply(crm_ipc_t * client, int request_id, int ms_timeout)
{
time_t timeout = time(NULL) + 1 + (ms_timeout / 1000);
int rc = 0;
crm_ipc_init();
/* get the reply */
crm_trace("client %s waiting on reply to msg id %d", client->name, request_id);
do {
rc = qb_ipcc_recv(client->ipc, client->buffer, client->buf_size, 1000);
if (rc > 0) {
struct crm_ipc_response_header *hdr = NULL;
int rc = crm_ipc_decompress(client);
if (rc != pcmk_ok) {
return rc;
}
hdr = (struct crm_ipc_response_header *)(void*)client->buffer;
if (hdr->qb.id == request_id) {
/* Got it */
break;
} else if (hdr->qb.id < request_id) {
xmlNode *bad = string2xml(crm_ipc_buffer(client));
crm_err("Discarding old reply %d (need %d)", hdr->qb.id, request_id);
crm_log_xml_notice(bad, "OldIpcReply");
} else {
xmlNode *bad = string2xml(crm_ipc_buffer(client));
crm_err("Discarding newer reply %d (need %d)", hdr->qb.id, request_id);
crm_log_xml_notice(bad, "ImpossibleReply");
CRM_ASSERT(hdr->qb.id <= request_id);
}
} else if (crm_ipc_connected(client) == FALSE) {
crm_err("Server disconnected client %s while waiting for msg id %d", client->name,
request_id);
break;
}
} while (time(NULL) < timeout);
return rc;
}
int
crm_ipc_send(crm_ipc_t * client, xmlNode * message, enum crm_ipc_flags flags, int32_t ms_timeout,
xmlNode ** reply)
{
long rc = 0;
struct iovec *iov;
static uint32_t id = 0;
static int factor = 8;
struct crm_ipc_response_header *header;
crm_ipc_init();
if (client == NULL) {
crm_notice("Invalid connection");
return -ENOTCONN;
} else if (crm_ipc_connected(client) == FALSE) {
/* Don't even bother */
crm_notice("Connection to %s closed", client->name);
return -ENOTCONN;
}
if (ms_timeout == 0) {
ms_timeout = 5000;
}
if (client->need_reply) {
crm_trace("Trying again to obtain pending reply from %s", client->name);
rc = qb_ipcc_recv(client->ipc, client->buffer, client->buf_size, ms_timeout);
if (rc < 0) {
crm_warn("Sending to %s (%p) is disabled until pending reply is received", client->name,
client->ipc);
return -EALREADY;
} else {
crm_notice("Lost reply from %s (%p) finally arrived, sending re-enabled", client->name,
client->ipc);
client->need_reply = FALSE;
}
}
id++;
CRM_LOG_ASSERT(id != 0); /* Crude wrap-around detection */
rc = crm_ipc_prepare(id, message, &iov, client->max_buf_size);
if(rc < 0) {
return rc;
}
header = iov[0].iov_base;
header->flags |= flags;
if(is_set(flags, crm_ipc_proxied)) {
/* Don't look for a synchronous response */
clear_bit(flags, crm_ipc_client_response);
}
if(header->size_compressed) {
if(factor < 10 && (client->max_buf_size / 10) < (rc / factor)) {
crm_notice("Compressed message exceeds %d0%% of the configured ipc limit (%u bytes), "
"consider setting PCMK_ipc_buffer to %u or higher",
factor, client->max_buf_size, 2 * client->max_buf_size);
factor++;
}
}
crm_trace("Sending from client: %s request id: %d bytes: %u timeout:%d msg...",
client->name, header->qb.id, header->qb.size, ms_timeout);
if (ms_timeout > 0 || is_not_set(flags, crm_ipc_client_response)) {
rc = internal_ipc_send_request(client, iov, ms_timeout);
if (rc <= 0) {
crm_trace("Failed to send from client %s request %d with %u bytes...",
client->name, header->qb.id, header->qb.size);
goto send_cleanup;
} else if (is_not_set(flags, crm_ipc_client_response)) {
crm_trace("Message sent, not waiting for reply to %d from %s to %u bytes...",
header->qb.id, client->name, header->qb.size);
goto send_cleanup;
}
rc = internal_ipc_get_reply(client, header->qb.id, ms_timeout);
if (rc < 0) {
/* No reply, for now, disable sending
*
* The alternative is to close the connection since we don't know
* how to detect and discard out-of-sequence replies
*
* TODO - implement the above
*/
client->need_reply = TRUE;
}
} else {
rc = internal_ipc_send_recv(client, iov);
}
if (rc > 0) {
struct crm_ipc_response_header *hdr = (struct crm_ipc_response_header *)(void*)client->buffer;
crm_trace("Received response %d, size=%u, rc=%ld, text: %.200s", hdr->qb.id, hdr->qb.size,
rc, crm_ipc_buffer(client));
if (reply) {
*reply = string2xml(crm_ipc_buffer(client));
}
} else {
crm_trace("Response not received: rc=%ld, errno=%d", rc, errno);
}
send_cleanup:
if (crm_ipc_connected(client) == FALSE) {
crm_notice("Connection to %s closed: %s (%ld)", client->name, pcmk_strerror(rc), rc);
} else if (rc == -ETIMEDOUT) {
crm_warn("Request %d to %s (%p) failed: %s (%ld) after %dms",
header->qb.id, client->name, client->ipc, pcmk_strerror(rc), rc, ms_timeout);
crm_write_blackbox(0, NULL);
} else if (rc <= 0) {
crm_warn("Request %d to %s (%p) failed: %s (%ld)",
header->qb.id, client->name, client->ipc, pcmk_strerror(rc), rc);
}
free(header);
free(iov[1].iov_base);
free(iov);
return rc;
}
/* Utils */
xmlNode *
create_hello_message(const char *uuid,
const char *client_name, const char *major_version, const char *minor_version)
{
xmlNode *hello_node = NULL;
xmlNode *hello = NULL;
if (uuid == NULL || strlen(uuid) == 0
|| client_name == NULL || strlen(client_name) == 0
|| major_version == NULL || strlen(major_version) == 0
|| minor_version == NULL || strlen(minor_version) == 0) {
crm_err("Missing fields, Hello message will not be valid.");
return NULL;
}
hello_node = create_xml_node(NULL, XML_TAG_OPTIONS);
crm_xml_add(hello_node, "major_version", major_version);
crm_xml_add(hello_node, "minor_version", minor_version);
crm_xml_add(hello_node, "client_name", client_name);
crm_xml_add(hello_node, "client_uuid", uuid);
crm_trace("creating hello message");
hello = create_request(CRM_OP_HELLO, hello_node, NULL, NULL, client_name, uuid);
free_xml(hello_node);
return hello;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5243_0 |
crossvul-cpp_data_good_5246_2 | /*
* linux/fs/ceph/acl.c
*
* Copyright (C) 2013 Guangliang Zhao, <lucienchao@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/ceph/ceph_debug.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/posix_acl.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include "super.h"
static inline void ceph_set_cached_acl(struct inode *inode,
int type, struct posix_acl *acl)
{
struct ceph_inode_info *ci = ceph_inode(inode);
spin_lock(&ci->i_ceph_lock);
if (__ceph_caps_issued_mask(ci, CEPH_CAP_XATTR_SHARED, 0))
set_cached_acl(inode, type, acl);
else
forget_cached_acl(inode, type);
spin_unlock(&ci->i_ceph_lock);
}
struct posix_acl *ceph_get_acl(struct inode *inode, int type)
{
int size;
const char *name;
char *value = NULL;
struct posix_acl *acl;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
size = __ceph_getxattr(inode, name, "", 0);
if (size > 0) {
value = kzalloc(size, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
size = __ceph_getxattr(inode, name, value, size);
}
if (size > 0)
acl = posix_acl_from_xattr(&init_user_ns, value, size);
else if (size == -ERANGE || size == -ENODATA || size == 0)
acl = NULL;
else
acl = ERR_PTR(-EIO);
kfree(value);
if (!IS_ERR(acl))
ceph_set_cached_acl(inode, type, acl);
return acl;
}
int ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int ret = 0, size = 0;
const char *name = NULL;
char *value = NULL;
struct iattr newattrs;
umode_t new_mode = inode->i_mode, old_mode = inode->i_mode;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_update_mode(inode, &new_mode, &acl);
if (ret)
goto out;
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
ret = acl ? -EINVAL : 0;
goto out;
}
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
ret = -EINVAL;
goto out;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_NOFS);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out_free;
}
if (new_mode != old_mode) {
newattrs.ia_mode = new_mode;
newattrs.ia_valid = ATTR_MODE;
ret = __ceph_setattr(inode, &newattrs);
if (ret)
goto out_free;
}
ret = __ceph_setxattr(inode, name, value, size, 0);
if (ret) {
if (new_mode != old_mode) {
newattrs.ia_mode = old_mode;
newattrs.ia_valid = ATTR_MODE;
__ceph_setattr(inode, &newattrs);
}
goto out_free;
}
ceph_set_cached_acl(inode, type, acl);
out_free:
kfree(value);
out:
return ret;
}
int ceph_pre_init_acls(struct inode *dir, umode_t *mode,
struct ceph_acls_info *info)
{
struct posix_acl *acl, *default_acl;
size_t val_size1 = 0, val_size2 = 0;
struct ceph_pagelist *pagelist = NULL;
void *tmp_buf = NULL;
int err;
err = posix_acl_create(dir, mode, &default_acl, &acl);
if (err)
return err;
if (acl) {
int ret = posix_acl_equiv_mode(acl, mode);
if (ret < 0)
goto out_err;
if (ret == 0) {
posix_acl_release(acl);
acl = NULL;
}
}
if (!default_acl && !acl)
return 0;
if (acl)
val_size1 = posix_acl_xattr_size(acl->a_count);
if (default_acl)
val_size2 = posix_acl_xattr_size(default_acl->a_count);
err = -ENOMEM;
tmp_buf = kmalloc(max(val_size1, val_size2), GFP_KERNEL);
if (!tmp_buf)
goto out_err;
pagelist = kmalloc(sizeof(struct ceph_pagelist), GFP_KERNEL);
if (!pagelist)
goto out_err;
ceph_pagelist_init(pagelist);
err = ceph_pagelist_reserve(pagelist, PAGE_SIZE);
if (err)
goto out_err;
ceph_pagelist_encode_32(pagelist, acl && default_acl ? 2 : 1);
if (acl) {
size_t len = strlen(XATTR_NAME_POSIX_ACL_ACCESS);
err = ceph_pagelist_reserve(pagelist, len + val_size1 + 8);
if (err)
goto out_err;
ceph_pagelist_encode_string(pagelist, XATTR_NAME_POSIX_ACL_ACCESS,
len);
err = posix_acl_to_xattr(&init_user_ns, acl,
tmp_buf, val_size1);
if (err < 0)
goto out_err;
ceph_pagelist_encode_32(pagelist, val_size1);
ceph_pagelist_append(pagelist, tmp_buf, val_size1);
}
if (default_acl) {
size_t len = strlen(XATTR_NAME_POSIX_ACL_DEFAULT);
err = ceph_pagelist_reserve(pagelist, len + val_size2 + 8);
if (err)
goto out_err;
err = ceph_pagelist_encode_string(pagelist,
XATTR_NAME_POSIX_ACL_DEFAULT, len);
err = posix_acl_to_xattr(&init_user_ns, default_acl,
tmp_buf, val_size2);
if (err < 0)
goto out_err;
ceph_pagelist_encode_32(pagelist, val_size2);
ceph_pagelist_append(pagelist, tmp_buf, val_size2);
}
kfree(tmp_buf);
info->acl = acl;
info->default_acl = default_acl;
info->pagelist = pagelist;
return 0;
out_err:
posix_acl_release(acl);
posix_acl_release(default_acl);
kfree(tmp_buf);
if (pagelist)
ceph_pagelist_release(pagelist);
return err;
}
void ceph_init_inode_acls(struct inode* inode, struct ceph_acls_info *info)
{
if (!inode)
return;
ceph_set_cached_acl(inode, ACL_TYPE_ACCESS, info->acl);
ceph_set_cached_acl(inode, ACL_TYPE_DEFAULT, info->default_acl);
}
void ceph_release_acls_info(struct ceph_acls_info *info)
{
posix_acl_release(info->acl);
posix_acl_release(info->default_acl);
if (info->pagelist)
ceph_pagelist_release(info->pagelist);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_2 |
crossvul-cpp_data_good_5246_11 | /*
* (C) 2001 Clemson University and The University of Chicago
*
* See COPYING in top-level directory.
*/
#include "protocol.h"
#include "orangefs-kernel.h"
#include "orangefs-bufmap.h"
#include <linux/posix_acl_xattr.h>
#include <linux/fs_struct.h>
struct posix_acl *orangefs_get_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
int ret;
char *key = NULL, *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
key = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
key = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
gossip_err("orangefs_get_acl: bogus value of type %d\n", type);
return ERR_PTR(-EINVAL);
}
/*
* Rather than incurring a network call just to determine the exact
* length of the attribute, I just allocate a max length to save on
* the network call. Conceivably, we could pass NULL to
* orangefs_inode_getxattr() to probe the length of the value, but
* I don't do that for now.
*/
value = kmalloc(ORANGEFS_MAX_XATTR_VALUELEN, GFP_KERNEL);
if (value == NULL)
return ERR_PTR(-ENOMEM);
gossip_debug(GOSSIP_ACL_DEBUG,
"inode %pU, key %s, type %d\n",
get_khandle_from_ino(inode),
key,
type);
ret = orangefs_inode_getxattr(inode, key, value,
ORANGEFS_MAX_XATTR_VALUELEN);
/* if the key exists, convert it to an in-memory rep */
if (ret > 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, ret);
} else if (ret == -ENODATA || ret == -ENOSYS) {
acl = NULL;
} else {
gossip_err("inode %pU retrieving acl's failed with error %d\n",
get_khandle_from_ino(inode),
ret);
acl = ERR_PTR(ret);
}
/* kfree(NULL) is safe, so don't worry if value ever got used */
kfree(value);
return acl;
}
int orangefs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
int error = 0;
void *value = NULL;
size_t size = 0;
const char *name = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
umode_t mode;
error = posix_acl_update_mode(inode, &mode, &acl);
if (error) {
gossip_err("%s: posix_acl_update_mode err: %d\n",
__func__,
error);
return error;
}
if (inode->i_mode != mode)
SetModeFlag(orangefs_inode);
inode->i_mode = mode;
mark_inode_dirty_sync(inode);
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
gossip_err("%s: invalid type %d!\n", __func__, type);
return -EINVAL;
}
gossip_debug(GOSSIP_ACL_DEBUG,
"%s: inode %pU, key %s type %d\n",
__func__, get_khandle_from_ino(inode),
name,
type);
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (error < 0)
goto out;
}
gossip_debug(GOSSIP_ACL_DEBUG,
"%s: name %s, value %p, size %zd, acl %p\n",
__func__, name, value, size, acl);
/*
* Go ahead and set the extended attribute now. NOTE: Suppose acl
* was NULL, then value will be NULL and size will be 0 and that
* will xlate to a removexattr. However, we don't want removexattr
* complain if attributes does not exist.
*/
error = orangefs_inode_setxattr(inode, name, value, size, 0);
out:
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
int orangefs_init_acl(struct inode *inode, struct inode *dir)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct posix_acl *default_acl, *acl;
umode_t mode = inode->i_mode;
int error = 0;
ClearModeFlag(orangefs_inode);
error = posix_acl_create(dir, &mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = orangefs_set_acl(inode, default_acl, ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = orangefs_set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
/* If mode of the inode was changed, then do a forcible ->setattr */
if (mode != inode->i_mode) {
SetModeFlag(orangefs_inode);
inode->i_mode = mode;
orangefs_flush_inode(inode);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_11 |
crossvul-cpp_data_good_5246_4 | /*
* linux/fs/ext4/acl.c
*
* Copyright (C) 2001-2003 Andreas Gruenbacher, <agruen@suse.de>
*/
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
#include "acl.h"
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *
ext4_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(ext4_acl_header))
return ERR_PTR(-EINVAL);
if (((ext4_acl_header *)value)->a_version !=
cpu_to_le32(EXT4_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(ext4_acl_header);
count = ext4_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
ext4_acl_entry *entry =
(ext4_acl_entry *)value;
if ((char *)value + sizeof(ext4_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(ext4_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(ext4_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(ext4_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *
ext4_acl_to_disk(const struct posix_acl *acl, size_t *size)
{
ext4_acl_header *ext_acl;
char *e;
size_t n;
*size = ext4_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(ext4_acl_header) + acl->a_count *
sizeof(ext4_acl_entry), GFP_NOFS);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(EXT4_ACL_VERSION);
e = (char *)ext_acl + sizeof(ext4_acl_header);
for (n = 0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
ext4_acl_entry *entry = (ext4_acl_entry *)e;
entry->e_tag = cpu_to_le16(acl_e->e_tag);
entry->e_perm = cpu_to_le16(acl_e->e_perm);
switch (acl_e->e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(ext4_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(ext4_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(ext4_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* Inode operation get_posix_acl().
*
* inode->i_mutex: don't care
*/
struct posix_acl *
ext4_get_acl(struct inode *inode, int type)
{
int name_index;
char *value = NULL;
struct posix_acl *acl;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = ext4_xattr_get(inode, name_index, "", NULL, 0);
if (retval > 0) {
value = kmalloc(retval, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = ext4_xattr_get(inode, name_index, "", value, retval);
}
if (retval > 0)
acl = ext4_acl_from_disk(value, retval);
else if (retval == -ENODATA || retval == -ENOSYS)
acl = NULL;
else
acl = ERR_PTR(retval);
kfree(value);
return acl;
}
/*
* Set the access or default ACL of an inode.
*
* inode->i_mutex: down unless called from ext4_new_inode
*/
static int
__ext4_set_acl(handle_t *handle, struct inode *inode, int type,
struct posix_acl *acl)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
}
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext4_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext4_xattr_set_handle(handle, inode, name_index, "",
value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
int
ext4_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
handle_t *handle;
int error, retries = 0;
retry:
handle = ext4_journal_start(inode, EXT4_HT_XATTR,
ext4_jbd2_credits_xattr(inode));
if (IS_ERR(handle))
return PTR_ERR(handle);
error = __ext4_set_acl(handle, inode, type, acl);
ext4_journal_stop(handle);
if (error == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
return error;
}
/*
* Initialize the ACLs of a new inode. Called from ext4_new_inode.
*
* dir->i_mutex: down
* inode->i_mutex: up (access to inode is still exclusive)
*/
int
ext4_init_acl(handle_t *handle, struct inode *inode, struct inode *dir)
{
struct posix_acl *default_acl, *acl;
int error;
error = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = __ext4_set_acl(handle, inode, ACL_TYPE_DEFAULT,
default_acl);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = __ext4_set_acl(handle, inode, ACL_TYPE_ACCESS,
acl);
posix_acl_release(acl);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_4 |
crossvul-cpp_data_good_5246_13 | #include <linux/capability.h>
#include <linux/fs.h>
#include <linux/posix_acl.h>
#include "reiserfs.h"
#include <linux/errno.h>
#include <linux/pagemap.h>
#include <linux/xattr.h>
#include <linux/slab.h>
#include <linux/posix_acl_xattr.h>
#include "xattr.h"
#include "acl.h"
#include <linux/uaccess.h>
static int __reiserfs_set_acl(struct reiserfs_transaction_handle *th,
struct inode *inode, int type,
struct posix_acl *acl);
int
reiserfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error, error2;
struct reiserfs_transaction_handle th;
size_t jcreate_blocks;
int size = acl ? posix_acl_xattr_size(acl->a_count) : 0;
/*
* Pessimism: We can't assume that anything from the xattr root up
* has been created.
*/
jcreate_blocks = reiserfs_xattr_jcreate_nblocks(inode) +
reiserfs_xattr_nblocks(inode, size) * 2;
reiserfs_write_lock(inode->i_sb);
error = journal_begin(&th, inode->i_sb, jcreate_blocks);
reiserfs_write_unlock(inode->i_sb);
if (error == 0) {
error = __reiserfs_set_acl(&th, inode, type, acl);
reiserfs_write_lock(inode->i_sb);
error2 = journal_end(&th);
reiserfs_write_unlock(inode->i_sb);
if (error2)
error = error2;
}
return error;
}
/*
* Convert from filesystem to in-memory representation.
*/
static struct posix_acl *reiserfs_posix_acl_from_disk(const void *value, size_t size)
{
const char *end = (char *)value + size;
int n, count;
struct posix_acl *acl;
if (!value)
return NULL;
if (size < sizeof(reiserfs_acl_header))
return ERR_PTR(-EINVAL);
if (((reiserfs_acl_header *) value)->a_version !=
cpu_to_le32(REISERFS_ACL_VERSION))
return ERR_PTR(-EINVAL);
value = (char *)value + sizeof(reiserfs_acl_header);
count = reiserfs_acl_count(size);
if (count < 0)
return ERR_PTR(-EINVAL);
if (count == 0)
return NULL;
acl = posix_acl_alloc(count, GFP_NOFS);
if (!acl)
return ERR_PTR(-ENOMEM);
for (n = 0; n < count; n++) {
reiserfs_acl_entry *entry = (reiserfs_acl_entry *) value;
if ((char *)value + sizeof(reiserfs_acl_entry_short) > end)
goto fail;
acl->a_entries[n].e_tag = le16_to_cpu(entry->e_tag);
acl->a_entries[n].e_perm = le16_to_cpu(entry->e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
value = (char *)value +
sizeof(reiserfs_acl_entry_short);
break;
case ACL_USER:
value = (char *)value + sizeof(reiserfs_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_uid =
make_kuid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
case ACL_GROUP:
value = (char *)value + sizeof(reiserfs_acl_entry);
if ((char *)value > end)
goto fail;
acl->a_entries[n].e_gid =
make_kgid(&init_user_ns,
le32_to_cpu(entry->e_id));
break;
default:
goto fail;
}
}
if (value != end)
goto fail;
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
/*
* Convert from in-memory to filesystem representation.
*/
static void *reiserfs_posix_acl_to_disk(const struct posix_acl *acl, size_t * size)
{
reiserfs_acl_header *ext_acl;
char *e;
int n;
*size = reiserfs_acl_size(acl->a_count);
ext_acl = kmalloc(sizeof(reiserfs_acl_header) +
acl->a_count *
sizeof(reiserfs_acl_entry),
GFP_NOFS);
if (!ext_acl)
return ERR_PTR(-ENOMEM);
ext_acl->a_version = cpu_to_le32(REISERFS_ACL_VERSION);
e = (char *)ext_acl + sizeof(reiserfs_acl_header);
for (n = 0; n < acl->a_count; n++) {
const struct posix_acl_entry *acl_e = &acl->a_entries[n];
reiserfs_acl_entry *entry = (reiserfs_acl_entry *) e;
entry->e_tag = cpu_to_le16(acl->a_entries[n].e_tag);
entry->e_perm = cpu_to_le16(acl->a_entries[n].e_perm);
switch (acl->a_entries[n].e_tag) {
case ACL_USER:
entry->e_id = cpu_to_le32(
from_kuid(&init_user_ns, acl_e->e_uid));
e += sizeof(reiserfs_acl_entry);
break;
case ACL_GROUP:
entry->e_id = cpu_to_le32(
from_kgid(&init_user_ns, acl_e->e_gid));
e += sizeof(reiserfs_acl_entry);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
e += sizeof(reiserfs_acl_entry_short);
break;
default:
goto fail;
}
}
return (char *)ext_acl;
fail:
kfree(ext_acl);
return ERR_PTR(-EINVAL);
}
/*
* Inode operation get_posix_acl().
*
* inode->i_mutex: down
* BKL held [before 2.5.x]
*/
struct posix_acl *reiserfs_get_acl(struct inode *inode, int type)
{
char *name, *value;
struct posix_acl *acl;
int size;
int retval;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
size = reiserfs_xattr_get(inode, name, NULL, 0);
if (size < 0) {
if (size == -ENODATA || size == -ENOSYS)
return NULL;
return ERR_PTR(size);
}
value = kmalloc(size, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
retval = reiserfs_xattr_get(inode, name, value, size);
if (retval == -ENODATA || retval == -ENOSYS) {
/*
* This shouldn't actually happen as it should have
* been caught above.. but just in case
*/
acl = NULL;
} else if (retval < 0) {
acl = ERR_PTR(retval);
} else {
acl = reiserfs_posix_acl_from_disk(value, retval);
}
kfree(value);
return acl;
}
/*
* Inode operation set_posix_acl().
*
* inode->i_mutex: down
* BKL held [before 2.5.x]
*/
static int
__reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
/*
* dir->i_mutex: locked,
* inode is new and not released into the wild yet
*/
int
reiserfs_inherit_default_acl(struct reiserfs_transaction_handle *th,
struct inode *dir, struct dentry *dentry,
struct inode *inode)
{
struct posix_acl *default_acl, *acl;
int err = 0;
/* ACLs only get applied to files and directories */
if (S_ISLNK(inode->i_mode))
return 0;
/*
* ACLs can only be used on "new" objects, so if it's an old object
* there is nothing to inherit from
*/
if (get_inode_sd_version(dir) == STAT_DATA_V1)
goto apply_umask;
/*
* Don't apply ACLs to objects in the .reiserfs_priv tree.. This
* would be useless since permissions are ignored, and a pain because
* it introduces locking cycles
*/
if (IS_PRIVATE(dir)) {
inode->i_flags |= S_PRIVATE;
goto apply_umask;
}
err = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
if (err)
return err;
if (default_acl) {
err = __reiserfs_set_acl(th, inode, ACL_TYPE_DEFAULT,
default_acl);
posix_acl_release(default_acl);
}
if (acl) {
if (!err)
err = __reiserfs_set_acl(th, inode, ACL_TYPE_ACCESS,
acl);
posix_acl_release(acl);
}
return err;
apply_umask:
/* no ACL, apply umask */
inode->i_mode &= ~current_umask();
return err;
}
/* This is used to cache the default acl before a new object is created.
* The biggest reason for this is to get an idea of how many blocks will
* actually be required for the create operation if we must inherit an ACL.
* An ACL write can add up to 3 object creations and an additional file write
* so we'd prefer not to reserve that many blocks in the journal if we can.
* It also has the advantage of not loading the ACL with a transaction open,
* this may seem silly, but if the owner of the directory is doing the
* creation, the ACL may not be loaded since the permissions wouldn't require
* it.
* We return the number of blocks required for the transaction.
*/
int reiserfs_cache_default_acl(struct inode *inode)
{
struct posix_acl *acl;
int nblocks = 0;
if (IS_PRIVATE(inode))
return 0;
acl = get_acl(inode, ACL_TYPE_DEFAULT);
if (acl && !IS_ERR(acl)) {
int size = reiserfs_acl_size(acl->a_count);
/* Other xattrs can be created during inode creation. We don't
* want to claim too many blocks, so we check to see if we
* we need to create the tree to the xattrs, and then we
* just want two files. */
nblocks = reiserfs_xattr_jcreate_nblocks(inode);
nblocks += JOURNAL_BLOCKS_PER_OBJECT(inode->i_sb);
REISERFS_I(inode)->i_flags |= i_has_xattr_dir;
/* We need to account for writes + bitmaps for two files */
nblocks += reiserfs_xattr_nblocks(inode, size) * 4;
posix_acl_release(acl);
}
return nblocks;
}
/*
* Called under i_mutex
*/
int reiserfs_acl_chmod(struct inode *inode)
{
if (IS_PRIVATE(inode))
return 0;
if (get_inode_sd_version(inode) == STAT_DATA_V1 ||
!reiserfs_posixacl(inode->i_sb))
return 0;
return posix_acl_chmod(inode, inode->i_mode);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/good_5246_13 |
crossvul-cpp_data_bad_5246_11 | /*
* (C) 2001 Clemson University and The University of Chicago
*
* See COPYING in top-level directory.
*/
#include "protocol.h"
#include "orangefs-kernel.h"
#include "orangefs-bufmap.h"
#include <linux/posix_acl_xattr.h>
#include <linux/fs_struct.h>
struct posix_acl *orangefs_get_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
int ret;
char *key = NULL, *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
key = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
key = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
gossip_err("orangefs_get_acl: bogus value of type %d\n", type);
return ERR_PTR(-EINVAL);
}
/*
* Rather than incurring a network call just to determine the exact
* length of the attribute, I just allocate a max length to save on
* the network call. Conceivably, we could pass NULL to
* orangefs_inode_getxattr() to probe the length of the value, but
* I don't do that for now.
*/
value = kmalloc(ORANGEFS_MAX_XATTR_VALUELEN, GFP_KERNEL);
if (value == NULL)
return ERR_PTR(-ENOMEM);
gossip_debug(GOSSIP_ACL_DEBUG,
"inode %pU, key %s, type %d\n",
get_khandle_from_ino(inode),
key,
type);
ret = orangefs_inode_getxattr(inode, key, value,
ORANGEFS_MAX_XATTR_VALUELEN);
/* if the key exists, convert it to an in-memory rep */
if (ret > 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, ret);
} else if (ret == -ENODATA || ret == -ENOSYS) {
acl = NULL;
} else {
gossip_err("inode %pU retrieving acl's failed with error %d\n",
get_khandle_from_ino(inode),
ret);
acl = ERR_PTR(ret);
}
/* kfree(NULL) is safe, so don't worry if value ever got used */
kfree(value);
return acl;
}
int orangefs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
int error = 0;
void *value = NULL;
size_t size = 0;
const char *name = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
umode_t mode = inode->i_mode;
/*
* can we represent this with the traditional file
* mode permission bits?
*/
error = posix_acl_equiv_mode(acl, &mode);
if (error < 0) {
gossip_err("%s: posix_acl_equiv_mode err: %d\n",
__func__,
error);
return error;
}
if (inode->i_mode != mode)
SetModeFlag(orangefs_inode);
inode->i_mode = mode;
mark_inode_dirty_sync(inode);
if (error == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
gossip_err("%s: invalid type %d!\n", __func__, type);
return -EINVAL;
}
gossip_debug(GOSSIP_ACL_DEBUG,
"%s: inode %pU, key %s type %d\n",
__func__, get_khandle_from_ino(inode),
name,
type);
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (error < 0)
goto out;
}
gossip_debug(GOSSIP_ACL_DEBUG,
"%s: name %s, value %p, size %zd, acl %p\n",
__func__, name, value, size, acl);
/*
* Go ahead and set the extended attribute now. NOTE: Suppose acl
* was NULL, then value will be NULL and size will be 0 and that
* will xlate to a removexattr. However, we don't want removexattr
* complain if attributes does not exist.
*/
error = orangefs_inode_setxattr(inode, name, value, size, 0);
out:
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
int orangefs_init_acl(struct inode *inode, struct inode *dir)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct posix_acl *default_acl, *acl;
umode_t mode = inode->i_mode;
int error = 0;
ClearModeFlag(orangefs_inode);
error = posix_acl_create(dir, &mode, &default_acl, &acl);
if (error)
return error;
if (default_acl) {
error = orangefs_set_acl(inode, default_acl, ACL_TYPE_DEFAULT);
posix_acl_release(default_acl);
}
if (acl) {
if (!error)
error = orangefs_set_acl(inode, acl, ACL_TYPE_ACCESS);
posix_acl_release(acl);
}
/* If mode of the inode was changed, then do a forcible ->setattr */
if (mode != inode->i_mode) {
SetModeFlag(orangefs_inode);
inode->i_mode = mode;
orangefs_flush_inode(inode);
}
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_11 |
crossvul-cpp_data_bad_5246_0 | /*
* Copyright IBM Corporation, 2010
* Author Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2.1 of the GNU Lesser General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <net/9p/9p.h>
#include <net/9p/client.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/posix_acl_xattr.h>
#include "xattr.h"
#include "acl.h"
#include "v9fs.h"
#include "v9fs_vfs.h"
#include "fid.h"
static struct posix_acl *__v9fs_get_acl(struct p9_fid *fid, char *name)
{
ssize_t size;
void *value = NULL;
struct posix_acl *acl = NULL;
size = v9fs_fid_xattr_get(fid, name, NULL, 0);
if (size > 0) {
value = kzalloc(size, GFP_NOFS);
if (!value)
return ERR_PTR(-ENOMEM);
size = v9fs_fid_xattr_get(fid, name, value, size);
if (size > 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
goto err_out;
}
} else if (size == -ENODATA || size == 0 ||
size == -ENOSYS || size == -EOPNOTSUPP) {
acl = NULL;
} else
acl = ERR_PTR(-EIO);
err_out:
kfree(value);
return acl;
}
int v9fs_get_acl(struct inode *inode, struct p9_fid *fid)
{
int retval = 0;
struct posix_acl *pacl, *dacl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_inode2v9ses(inode);
if (((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) ||
((v9ses->flags & V9FS_ACL_MASK) != V9FS_POSIX_ACL)) {
set_cached_acl(inode, ACL_TYPE_DEFAULT, NULL);
set_cached_acl(inode, ACL_TYPE_ACCESS, NULL);
return 0;
}
/* get the default/access acl values and cache them */
dacl = __v9fs_get_acl(fid, XATTR_NAME_POSIX_ACL_DEFAULT);
pacl = __v9fs_get_acl(fid, XATTR_NAME_POSIX_ACL_ACCESS);
if (!IS_ERR(dacl) && !IS_ERR(pacl)) {
set_cached_acl(inode, ACL_TYPE_DEFAULT, dacl);
set_cached_acl(inode, ACL_TYPE_ACCESS, pacl);
} else
retval = -EIO;
if (!IS_ERR(dacl))
posix_acl_release(dacl);
if (!IS_ERR(pacl))
posix_acl_release(pacl);
return retval;
}
static struct posix_acl *v9fs_get_cached_acl(struct inode *inode, int type)
{
struct posix_acl *acl;
/*
* 9p Always cache the acl value when
* instantiating the inode (v9fs_inode_from_fid)
*/
acl = get_cached_acl(inode, type);
BUG_ON(is_uncached_acl(acl));
return acl;
}
struct posix_acl *v9fs_iop_get_acl(struct inode *inode, int type)
{
struct v9fs_session_info *v9ses;
v9ses = v9fs_inode2v9ses(inode);
if (((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT) ||
((v9ses->flags & V9FS_ACL_MASK) != V9FS_POSIX_ACL)) {
/*
* On access = client and acl = on mode get the acl
* values from the server
*/
return NULL;
}
return v9fs_get_cached_acl(inode, type);
}
static int v9fs_set_acl(struct p9_fid *fid, int type, struct posix_acl *acl)
{
int retval;
char *name;
size_t size;
void *buffer;
if (!acl)
return 0;
/* Set a setxattr request to server */
size = posix_acl_xattr_size(acl->a_count);
buffer = kmalloc(size, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
retval = posix_acl_to_xattr(&init_user_ns, acl, buffer, size);
if (retval < 0)
goto err_free_out;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
BUG();
}
retval = v9fs_fid_xattr_set(fid, name, buffer, size, 0);
err_free_out:
kfree(buffer);
return retval;
}
int v9fs_acl_chmod(struct inode *inode, struct p9_fid *fid)
{
int retval = 0;
struct posix_acl *acl;
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
acl = v9fs_get_cached_acl(inode, ACL_TYPE_ACCESS);
if (acl) {
retval = __posix_acl_chmod(&acl, GFP_KERNEL, inode->i_mode);
if (retval)
return retval;
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
retval = v9fs_set_acl(fid, ACL_TYPE_ACCESS, acl);
posix_acl_release(acl);
}
return retval;
}
int v9fs_set_create_acl(struct inode *inode, struct p9_fid *fid,
struct posix_acl *dacl, struct posix_acl *acl)
{
set_cached_acl(inode, ACL_TYPE_DEFAULT, dacl);
set_cached_acl(inode, ACL_TYPE_ACCESS, acl);
v9fs_set_acl(fid, ACL_TYPE_DEFAULT, dacl);
v9fs_set_acl(fid, ACL_TYPE_ACCESS, acl);
return 0;
}
void v9fs_put_acl(struct posix_acl *dacl,
struct posix_acl *acl)
{
posix_acl_release(dacl);
posix_acl_release(acl);
}
int v9fs_acl_mode(struct inode *dir, umode_t *modep,
struct posix_acl **dpacl, struct posix_acl **pacl)
{
int retval = 0;
umode_t mode = *modep;
struct posix_acl *acl = NULL;
if (!S_ISLNK(mode)) {
acl = v9fs_get_cached_acl(dir, ACL_TYPE_DEFAULT);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (!acl)
mode &= ~current_umask();
}
if (acl) {
if (S_ISDIR(mode))
*dpacl = posix_acl_dup(acl);
retval = __posix_acl_create(&acl, GFP_NOFS, &mode);
if (retval < 0)
return retval;
if (retval > 0)
*pacl = acl;
else
posix_acl_release(acl);
}
*modep = mode;
return 0;
}
static int v9fs_xattr_get_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, void *buffer, size_t size)
{
struct v9fs_session_info *v9ses;
struct posix_acl *acl;
int error;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* We allow set/get/list of acl when access=client is not specified
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_get(dentry, handler->name, buffer, size);
acl = v9fs_get_cached_acl(inode, handler->flags);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (acl == NULL)
return -ENODATA;
error = posix_acl_to_xattr(&init_user_ns, acl, buffer, size);
posix_acl_release(acl);
return error;
}
static int v9fs_xattr_set_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
int retval;
struct posix_acl *acl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* set the attribute on the remote. Without even looking at the
* xattr value. We leave it to the server to validate
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_set(dentry, handler->name, value, size,
flags);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value) {
/* update the cached acl value */
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
else if (acl) {
retval = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (retval)
goto err_out;
}
} else
acl = NULL;
switch (handler->flags) {
case ACL_TYPE_ACCESS:
if (acl) {
umode_t mode = inode->i_mode;
retval = posix_acl_equiv_mode(acl, &mode);
if (retval < 0)
goto err_out;
else {
struct iattr iattr;
if (retval == 0) {
/*
* ACL can be represented
* by the mode bits. So don't
* update ACL.
*/
acl = NULL;
value = NULL;
size = 0;
}
/* Updte the mode bits */
iattr.ia_mode = ((mode & S_IALLUGO) |
(inode->i_mode & ~S_IALLUGO));
iattr.ia_valid = ATTR_MODE;
/* FIXME should we update ctime ?
* What is the following setxattr update the
* mode ?
*/
v9fs_vfs_setattr_dotl(dentry, &iattr);
}
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
retval = acl ? -EINVAL : 0;
goto err_out;
}
break;
default:
BUG();
}
retval = v9fs_xattr_set(dentry, handler->name, value, size, flags);
if (!retval)
set_cached_acl(inode, handler->flags, acl);
err_out:
posix_acl_release(acl);
return retval;
}
const struct xattr_handler v9fs_xattr_acl_access_handler = {
.name = XATTR_NAME_POSIX_ACL_ACCESS,
.flags = ACL_TYPE_ACCESS,
.get = v9fs_xattr_get_acl,
.set = v9fs_xattr_set_acl,
};
const struct xattr_handler v9fs_xattr_acl_default_handler = {
.name = XATTR_NAME_POSIX_ACL_DEFAULT,
.flags = ACL_TYPE_DEFAULT,
.get = v9fs_xattr_get_acl,
.set = v9fs_xattr_set_acl,
};
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5246_0 |
crossvul-cpp_data_bad_5266_0 | /* modules/m_sasl.c
* Copyright (C) 2006 Michael Tharp <gxti@partiallystapled.com>
* Copyright (C) 2006 charybdis development team
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2.Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3.The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: m_sasl.c 1409 2006-05-21 14:46:17Z jilles $
*/
#include "stdinc.h"
#include "client.h"
#include "hash.h"
#include "send.h"
#include "msg.h"
#include "modules.h"
#include "numeric.h"
#include "s_serv.h"
#include "s_stats.h"
#include "string.h"
#include "s_newconf.h"
#include "s_conf.h"
static int m_authenticate(struct Client *, struct Client *, int, const char **);
static int me_sasl(struct Client *, struct Client *, int, const char **);
static void abort_sasl(struct Client *);
static void abort_sasl_exit(hook_data_client_exit *);
static void advertise_sasl(struct Client *);
static void advertise_sasl_exit(hook_data_client_exit *);
struct Message authenticate_msgtab = {
"AUTHENTICATE", 0, 0, 0, MFLG_SLOW,
{{m_authenticate, 2}, {m_authenticate, 2}, mg_ignore, mg_ignore, mg_ignore, {m_authenticate, 2}}
};
struct Message sasl_msgtab = {
"SASL", 0, 0, 0, MFLG_SLOW,
{mg_ignore, mg_ignore, mg_ignore, mg_ignore, {me_sasl, 5}, mg_ignore}
};
mapi_clist_av1 sasl_clist[] = {
&authenticate_msgtab, &sasl_msgtab, NULL
};
mapi_hfn_list_av1 sasl_hfnlist[] = {
{ "new_local_user", (hookfn) abort_sasl },
{ "client_exit", (hookfn) abort_sasl_exit },
{ "new_remote_user", (hookfn) advertise_sasl },
{ "client_exit", (hookfn) advertise_sasl_exit },
{ NULL, NULL }
};
DECLARE_MODULE_AV1(sasl, NULL, NULL, sasl_clist, NULL, sasl_hfnlist, "$Revision: 1409 $");
static int
m_authenticate(struct Client *client_p, struct Client *source_p,
int parc, const char *parv[])
{
struct Client *agent_p = NULL;
struct Client *saslserv_p = NULL;
/* They really should use CAP for their own sake. */
if(!IsCapable(source_p, CLICAP_SASL))
return 0;
if (strlen(client_p->id) == 3)
{
exit_client(client_p, client_p, client_p, "Mixing client and server protocol");
return 0;
}
saslserv_p = find_named_client(ConfigFileEntry.sasl_service);
if (saslserv_p == NULL || !IsService(saslserv_p))
{
sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name);
return 0;
}
if(source_p->localClient->sasl_complete)
{
*source_p->localClient->sasl_agent = '\0';
source_p->localClient->sasl_complete = 0;
}
if(strlen(parv[1]) > 400)
{
sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name);
return 0;
}
if(!*source_p->id)
{
/* Allocate a UID. */
strcpy(source_p->id, generate_uid());
add_to_id_hash(source_p->id, source_p);
}
if(*source_p->localClient->sasl_agent)
agent_p = find_id(source_p->localClient->sasl_agent);
if(agent_p == NULL)
{
sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s",
me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id,
source_p->host, source_p->sockhost);
if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL)
sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s",
me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id,
parv[1], source_p->certfp);
else
sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s",
me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id,
parv[1]);
rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN);
}
else
sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s",
me.id, agent_p->servptr->name, source_p->id, agent_p->id,
parv[1]);
source_p->localClient->sasl_out++;
return 0;
}
static int
me_sasl(struct Client *client_p, struct Client *source_p,
int parc, const char *parv[])
{
struct Client *target_p, *agent_p;
/* Let propagate if not addressed to us, or if broadcast.
* Only SASL agents can answer global requests.
*/
if(strncmp(parv[2], me.id, 3))
return 0;
if((target_p = find_id(parv[2])) == NULL)
return 0;
if((agent_p = find_id(parv[1])) == NULL)
return 0;
if(source_p != agent_p->servptr) /* WTF?! */
return 0;
/* We only accept messages from SASL agents; these must have umode +S
* (so the server must be listed in a service{} block).
*/
if(!IsService(agent_p))
return 0;
/* Reject if someone has already answered. */
if(*target_p->localClient->sasl_agent && strncmp(parv[1], target_p->localClient->sasl_agent, IDLEN))
return 0;
else if(!*target_p->localClient->sasl_agent)
rb_strlcpy(target_p->localClient->sasl_agent, parv[1], IDLEN);
if(*parv[3] == 'C')
sendto_one(target_p, "AUTHENTICATE %s", parv[4]);
else if(*parv[3] == 'D')
{
if(*parv[4] == 'F')
sendto_one(target_p, form_str(ERR_SASLFAIL), me.name, EmptyString(target_p->name) ? "*" : target_p->name);
else if(*parv[4] == 'S') {
sendto_one(target_p, form_str(RPL_SASLSUCCESS), me.name, EmptyString(target_p->name) ? "*" : target_p->name);
target_p->localClient->sasl_complete = 1;
ServerStats.is_ssuc++;
}
*target_p->localClient->sasl_agent = '\0'; /* Blank the stored agent so someone else can answer */
}
else if(*parv[3] == 'M')
sendto_one(target_p, form_str(RPL_SASLMECHS), me.name, EmptyString(target_p->name) ? "*" : target_p->name, parv[4]);
return 0;
}
/* If the client never finished authenticating but is
* registering anyway, abort the exchange.
*/
static void
abort_sasl(struct Client *data)
{
if(data->localClient->sasl_out == 0 || data->localClient->sasl_complete)
return;
data->localClient->sasl_out = data->localClient->sasl_complete = 0;
ServerStats.is_sbad++;
if(!IsClosing(data))
sendto_one(data, form_str(ERR_SASLABORTED), me.name, EmptyString(data->name) ? "*" : data->name);
if(*data->localClient->sasl_agent)
{
struct Client *agent_p = find_id(data->localClient->sasl_agent);
if(agent_p)
{
sendto_one(agent_p, ":%s ENCAP %s SASL %s %s D A", me.id, agent_p->servptr->name,
data->id, agent_p->id);
return;
}
}
sendto_server(NULL, NULL, CAP_TS6|CAP_ENCAP, NOCAPS, ":%s ENCAP * SASL %s * D A", me.id,
data->id);
}
static void
abort_sasl_exit(hook_data_client_exit *data)
{
if (data->target->localClient)
abort_sasl(data->target);
}
static void
advertise_sasl(struct Client *client_p)
{
if (!ConfigFileEntry.sasl_service)
return;
if (irccmp(client_p->name, ConfigFileEntry.sasl_service))
return;
sendto_local_clients_with_capability(CLICAP_CAP_NOTIFY, ":%s CAP * NEW :sasl", me.name);
}
static void
advertise_sasl_exit(hook_data_client_exit *data)
{
if (!ConfigFileEntry.sasl_service)
return;
if (irccmp(data->target->name, ConfigFileEntry.sasl_service))
return;
sendto_local_clients_with_capability(CLICAP_CAP_NOTIFY, ":%s CAP * DEL :sasl", me.name);
}
| ./CrossVul/dataset_final_sorted/CWE-285/c/bad_5266_0 |
crossvul-cpp_data_good_1025_0 | /*
* Copyright (c) 2002 - 2003
* NetGroup, Politecnico di Torino (Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "ftmacros.h"
#include "varattrs.h"
#include <errno.h> // for the errno variable
#include <stdlib.h> // for malloc(), free(), ...
#include <string.h> // for strlen(), ...
#ifdef _WIN32
#include <process.h> // for threads
#else
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h> // for select() and such
#include <pwd.h> // for password management
#endif
#ifdef HAVE_GETSPNAM
#include <shadow.h> // for password management
#endif
#include <pcap.h> // for libpcap/WinPcap calls
#include "fmtutils.h"
#include "sockutils.h" // for socket calls
#include "portability.h"
#include "rpcap-protocol.h"
#include "daemon.h"
#include "log.h"
//
// Timeout, in seconds, when we're waiting for a client to send us an
// authentication request; if they don't send us a request within that
// interval, we drop the connection, so we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_INIT 90
//
// Timeout, in seconds, when we're waiting for an authenticated client
// to send us a request, if a capture isn't in progress; if they don't
// send us a request within that interval, we drop the connection, so
// we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_RUNTIME 180
//
// Time, in seconds, that we wait after a failed authentication attempt
// before processing the next request; this prevents a client from
// rapidly trying different accounts or passwords.
//
#define RPCAP_SUSPEND_WRONGAUTH 1
// Parameters for the service loop.
struct daemon_slpars
{
SOCKET sockctrl; //!< SOCKET ID of the control connection
int isactive; //!< Not null if the daemon has to run in active mode
int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
};
//
// Data for a session managed by a thread.
// It includes both a Boolean indicating whether we *have* a thread,
// and a platform-dependent (UN*X vs. Windows) identifier for the
// thread; on Windows, we could use an invalid handle to indicate
// that we don't have a thread, but there *is* no portable "no thread"
// value for a pthread_t on UN*X.
//
struct session {
SOCKET sockctrl;
SOCKET sockdata;
uint8 protocol_version;
pcap_t *fp;
unsigned int TotCapt;
int have_thread;
#ifdef _WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
};
// Locally defined functions
static int daemon_msg_err(SOCKET sockctrl, uint32 plen);
static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen);
static int daemon_AuthUserPwd(char *username, char *password, char *errbuf);
static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen);
static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, size_t sourcelen);
static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, struct session **sessionp,
struct rpcap_sampling *samp_param);
static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session);
static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen);
static int daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errbuf);
static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt);
static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, struct rpcap_sampling *samp_param);
static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout);
#ifdef _WIN32
static unsigned __stdcall daemon_thrdatamain(void *ptr);
#else
static void *daemon_thrdatamain(void *ptr);
static void noop_handler(int sign);
#endif
static int rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp);
static int rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf);
static int rpcapd_discard(SOCKET sock, uint32 len);
static void session_close(struct session *);
static int is_url(const char *source);
int
daemon_serviceloop(SOCKET sockctrl, int isactive, char *passiveClients,
int nullAuthAllowed)
{
struct daemon_slpars pars; // service loop parameters
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client
int host_port_check_status;
int nrecv;
struct rpcap_header header; // RPCAP message general header
uint32 plen; // payload length from header
int authenticated = 0; // 1 if the client has successfully authenticated
char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open
int got_source = 0; // 1 if we've gotten the source from an open request
#ifndef _WIN32
struct sigaction action;
#endif
struct session *session = NULL; // struct session main variable
const char *msg_type_string; // string for message type
int client_told_us_to_close = 0; // 1 if the client told us to close the capture
// needed to save the values of the statistics
struct pcap_stat stats;
unsigned int svrcapt;
struct rpcap_sampling samp_param; // in case sampling has been requested
// Structures needed for the select() call
fd_set rfds; // set of socket descriptors we have to check
struct timeval tv; // maximum time the select() can block waiting for data
int retval; // select() return value
*errbuf = 0; // Initialize errbuf
// Set parameters structure
pars.sockctrl = sockctrl;
pars.isactive = isactive; // active mode
pars.nullAuthAllowed = nullAuthAllowed;
//
// We have a connection.
//
// If it's a passive mode connection, check whether the connecting
// host is among the ones allowed.
//
// In either case, we were handed a copy of the host list; free it
// as soon as we're done with it.
//
if (pars.isactive)
{
// Nothing to do.
free(passiveClients);
passiveClients = NULL;
}
else
{
struct sockaddr_storage from;
socklen_t fromlen;
//
// Get the address of the other end of the connection.
//
fromlen = sizeof(struct sockaddr_storage);
if (getpeername(pars.sockctrl, (struct sockaddr *)&from,
&fromlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
//
// Are they in the list of host/port combinations we allow?
//
host_port_check_status = sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE);
free(passiveClients);
passiveClients = NULL;
if (host_port_check_status < 0)
{
if (host_port_check_status == -2) {
//
// We got an error; log it.
//
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
//
// Sorry, we can't let you in.
//
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
#ifndef _WIN32
//
// Catch SIGUSR1, but do nothing. We use it to interrupt the
// capture thread to break it out of a loop in which it's
// blocked waiting for packets to arrive.
//
// We don't want interrupted system calls to restart, so that
// the read routine for the pcap_t gets EINTR rather than
// restarting if it's blocked in a system call.
//
memset(&action, 0, sizeof (action));
action.sa_handler = noop_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
#endif
//
// The client must first authenticate; loop until they send us a
// message with a version we support and credentials we accept,
// they send us a close message indicating that they're giving up,
// or we get a network error or other fatal error.
//
while (!authenticated)
{
//
// If we're not in active mode, we use select(), with a
// timeout, to wait for an authentication request; if
// the timeout expires, we drop the connection, so that
// a client can't just connect to us and leave us
// waiting forever.
//
if (!pars.isactive)
{
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_INIT;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// While we're in the authentication pharse, all requests
// must use version 0.
//
if (header.ver != 0)
{
//
// Send it back to them with their version.
//
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGVER,
"RPCAP version in requests in the authentication phase must be 0",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message and drop the
// connection.
(void)rpcapd_discard(pars.sockctrl, plen);
goto end;
}
switch (header.type)
{
case RPCAP_MSG_AUTH_REQ:
retval = daemon_msg_auth_req(&pars, plen);
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
if (retval == -2)
{
// Non-fatal error; we sent back
// an error message, so let them
// try again.
continue;
}
// OK, we're authenticated; we sent back
// a reply, so start serving requests.
authenticated = 1;
break;
case RPCAP_MSG_CLOSE:
//
// The client is giving up.
// Discard the rest of the message, if
// there is anything more.
//
(void)rpcapd_discard(pars.sockctrl, plen);
// We're done with this client.
goto end;
case RPCAP_MSG_ERROR:
// Log this and close the connection?
// XXX - is this what happens in active
// mode, where *we* initiate the
// connection, and the client gives us
// an error message rather than a "let
// me log in" message, indicating that
// we're not allowed to connect to them?
(void)daemon_msg_err(pars.sockctrl, plen);
goto end;
case RPCAP_MSG_FINDALLIF_REQ:
case RPCAP_MSG_OPEN_REQ:
case RPCAP_MSG_STARTCAP_REQ:
case RPCAP_MSG_UPDATEFILTER_REQ:
case RPCAP_MSG_STATS_REQ:
case RPCAP_MSG_ENDCAP_REQ:
case RPCAP_MSG_SETSAMPLING_REQ:
//
// These requests can't be sent until
// the client is authenticated.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Network error.
goto end;
}
break;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
default:
//
// Unknown message type.
//
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
}
}
//
// OK, the client has authenticated itself, and we can start
// processing regular requests from it.
//
//
// We don't have any statistics yet.
//
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
//
// Service requests.
//
for (;;)
{
errbuf[0] = 0; // clear errbuf
// Avoid zombies connections; check if the connection is opens but no commands are performed
// from more than RPCAP_TIMEOUT_RUNTIME
// Conditions:
// - I have to be in normal mode (no active mode)
// - if the device is open, I don't have to be in the middle of a capture (session->sockdata)
// - if the device is closed, I have always to check if a new command arrives
//
// Be carefully: the capture can have been started, but an error occurred (so session != NULL, but
// sockdata is 0
if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0))))
{
// Check for the initial timeout
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_RUNTIME;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_INITTIMEOUT,
"The RPCAP initial timeout has expired",
errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// Did the client specify a protocol version that we
// support?
//
if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
{
//
// Tell them it's not a supported version.
// Send the error message with their version,
// so they don't reject it as having the wrong
// version.
//
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_WRONGVER,
"RPCAP version in message isn't supported by the server",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
(void)rpcapd_discard(pars.sockctrl, plen);
// Give up on them.
goto end;
}
switch (header.type)
{
case RPCAP_MSG_ERROR: // The other endpoint reported an error
{
(void)daemon_msg_err(pars.sockctrl, plen);
// Do nothing; just exit; the error code is already into the errbuf
// XXX - actually exit....
break;
}
case RPCAP_MSG_FINDALLIF_REQ:
{
if (daemon_msg_findallif_req(header.ver, &pars, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_OPEN_REQ:
{
//
// Process the open request, and keep
// the source from it, for use later
// when the capture is started.
//
// XXX - we don't care if the client sends
// us multiple open requests, the last
// one wins.
//
retval = daemon_msg_open_req(header.ver, &pars,
plen, source, sizeof(source));
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
got_source = 1;
break;
}
case RPCAP_MSG_STARTCAP_REQ:
{
if (!got_source)
{
// They never told us what device
// to capture on!
if (rpcap_senderror(pars.sockctrl,
header.ver,
PCAP_ERR_STARTCAPTURE,
"No capture device was specified",
errbuf) == -1)
{
// Fatal error; log an
// error and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
goto end;
}
break;
}
if (daemon_msg_startcap_req(header.ver, &pars,
plen, source, &session, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_UPDATEFILTER_REQ:
{
if (session)
{
if (daemon_msg_updatefilter_req(header.ver,
&pars, session, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
}
else
{
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_UPDATEFILTER,
"Device not opened. Cannot update filter",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
break;
}
case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session
{
//
// Indicate to our caller that the client
// closed the control connection.
// This is used only in case of active mode.
//
client_told_us_to_close = 1;
rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection.");
goto end;
}
case RPCAP_MSG_STATS_REQ:
{
if (daemon_msg_stats_req(header.ver, &pars,
session, plen, &stats, svrcapt) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session
{
if (session)
{
// Save statistics (we can need them in the future)
if (pcap_stats(session->fp, &stats))
{
svrcapt = session->TotCapt;
}
else
{
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
}
if (daemon_msg_endcap_req(header.ver,
&pars, session) == -1)
{
free(session);
session = NULL;
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
free(session);
session = NULL;
}
else
{
rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_ENDCAPTURE,
"Device not opened. Cannot close the capture",
errbuf);
}
break;
}
case RPCAP_MSG_SETSAMPLING_REQ:
{
if (daemon_msg_setsampling_req(header.ver,
&pars, plen, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_AUTH_REQ:
{
//
// We're already authenticated; you don't
// get to reauthenticate.
//
rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed");
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG,
"RPCAP_MSG_AUTH_REQ request sent after authentication was completed",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
default:
//
// Unknown message type.
//
rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errbuf, errmsgbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
}
}
}
end:
// The service loop is finishing up.
// If we have a capture session running, close it.
if (session)
{
session_close(session);
free(session);
session = NULL;
}
sock_close(sockctrl, NULL, 0);
// Print message and return
rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop");
return client_told_us_to_close;
}
/*
* This handles the RPCAP_MSG_ERR message.
*/
static int
daemon_msg_err(SOCKET sockctrl, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char remote_errbuf[PCAP_ERRBUF_SIZE];
if (plen >= PCAP_ERRBUF_SIZE)
{
/*
* Message is too long; just read as much of it as we
* can into the buffer provided, and discard the rest.
*/
if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1)
{
// Network error.
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
}
else if (plen == 0)
{
/* Empty error string. */
remote_errbuf[0] = '\0';
}
else
{
if (sock_recv(sockctrl, remote_errbuf, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[plen] = '\0';
}
// Log the message
rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf);
return 0;
}
/*
* This handles the RPCAP_MSG_AUTH_REQ message.
* It checks if the authentication credentials supplied by the user are valid.
*
* This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ
* message in its authentication loop. It reads the body of the
* authentication message from the network and checks whether the
* credentials are valid.
*
* \param sockctrl: the socket for the control connection.
*
* \param nullAuthAllowed: '1' if the NULL authentication is allowed.
*
* \param errbuf: a user-allocated buffer in which the error message
* (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE
* bytes long.
*
* \return '0' if everything is fine, '-1' if an unrecoverable error occurred,
* or '-2' if the authentication failed. For errors, an error message is
* returned in the 'errbuf' variable; this gives a message for the
* unrecoverable error or for the authentication failure.
*/
static int
daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int status;
struct rpcap_auth auth; // RPCAP authentication header
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_authreply *authreply; // authentication reply message
status = rpcapd_recv(pars->sockctrl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
switch (ntohs(auth.type))
{
case RPCAP_RMTAUTH_NULL:
{
if (!pars->nullAuthAllowed)
{
// Send the client an error reply.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication failed; NULL authentication not permitted.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
break;
}
case RPCAP_RMTAUTH_PWD:
{
char *username, *passwd;
uint32 usernamelen, passwdlen;
usernamelen = ntohs(auth.slen1);
username = (char *) malloc (usernamelen + 1);
if (username == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
goto error;
}
status = rpcapd_recv(pars->sockctrl, username, usernamelen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
return -1;
}
if (status == -2)
{
free(username);
goto error;
}
username[usernamelen] = '\0';
passwdlen = ntohs(auth.slen2);
passwd = (char *) malloc (passwdlen + 1);
if (passwd == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
free(username);
goto error;
}
status = rpcapd_recv(pars->sockctrl, passwd, passwdlen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
free(passwd);
return -1;
}
if (status == -2)
{
free(username);
free(passwd);
goto error;
}
passwd[passwdlen] = '\0';
if (daemon_AuthUserPwd(username, passwd, errmsgbuf))
{
//
// Authentication failed. Let the client
// know.
//
free(username);
free(passwd);
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
//
// Suspend for 1 second, so that they can't
// hammer us with repeated tries with an
// attack such as a dictionary attack.
//
// WARNING: this delay is inserted only
// at this point; if the client closes the
// connection and reconnects, the suspension
// time does not have any effect.
//
sleep_secs(RPCAP_SUSPEND_WRONGAUTH);
goto error_noreply;
}
free(username);
free(passwd);
break;
}
default:
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication type not recognized.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_TYPE_NOTSUP, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
// The authentication succeeded; let the client know.
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
RPCAP_MSG_AUTH_REPLY, 0, sizeof(struct rpcap_authreply));
authreply = (struct rpcap_authreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_authreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
//
// Indicate to our peer what versions we support.
//
memset(authreply, 0, sizeof(struct rpcap_authreply));
authreply->minvers = RPCAP_MIN_VERSION;
authreply->maxvers = RPCAP_MAX_VERSION;
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH, errmsgbuf,
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
error_noreply:
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return -2;
}
static int
daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
DWORD error;
HANDLE Token;
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to log
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
error = GetLastError();
if (error != ERROR_LOGON_FAILURE)
{
// Some error other than an authentication error;
// log it.
pcap_fmt_errmsg_for_win32_err(errmsgbuf,
PCAP_ERRBUF_SIZE, error, "LogonUser() failed");
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
pcap_fmt_errmsg_for_win32_err(errmsgbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
int error;
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
//
// The Single UNIX Specification says that if crypt() fails it
// sets errno, but some implementatons that haven't been run
// through the SUS test suite might not do so.
//
errno = 0;
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
error = errno;
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
if (error == 0)
{
// It didn't set errno.
rpcapd_log(LOGPRIO_ERROR, "crypt() failed");
}
else
{
rpcapd_log(LOGPRIO_ERROR, "crypt() failed: %s",
strerror(error));
}
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (setuid(user->pw_uid))
{
error = errno;
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
error, "setuid");
rpcapd_log(LOGPRIO_ERROR, "setuid() failed: %s",
strerror(error));
return -1;
}
/* if (setgid(user->pw_gid))
{
error = errno;
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
rpcapd_log(LOGPRIO_ERROR, "setgid() failed: %s",
strerror(error));
return -1;
}
*/
return 0;
#endif
}
static int
daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint16 nif = 0; // counts the number of interface listed
// Discard the rest of the message; there shouldn't be any payload.
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// Retrieve the device list
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
// checks the number of interfaces and it computes the total length of the payload
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
plen+= strlen(d->description);
if (d->name)
plen+= strlen(d->name);
plen+= sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
plen+= (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
// RPCAP findalldevs command
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
// send the interface list
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
// send all addresses
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
// We no longer need the device list. Free it.
pcap_freealldevs(alldevs);
// Send a final command that says "now send it!"
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, size_t sourcelen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
pcap_t *fp; // pcap_t main variable
int nread;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_openreply *openreply; // open reply message
if (plen > sourcelen - 1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
goto error;
}
nread = sock_recv(pars->sockctrl, source, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
source[nread] = '\0';
plen -= nread;
// Is this a URL rather than a device?
// If so, reject it.
if (is_url(source))
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string refers to a remote device");
goto error;
}
// Open the selected device
// This is a fake open, since we do that only to get the needed parameters, then we close the device again
if ((fp = pcap_open_live(source,
1500 /* fake snaplen */,
0 /* no promis */,
1000 /* fake timeout */,
errmsgbuf)) == NULL)
goto error;
// Now, I can send a RPCAP open reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(openreply, 0, sizeof(struct rpcap_openreply));
openreply->linktype = htonl(pcap_datalink(fp));
openreply->tzoff = 0; /* This is always 0 for live captures */
// We're done with the pcap_t.
pcap_close(fp);
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, struct session **sessionp,
struct rpcap_sampling *samp_param _U_)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
struct session *session = NULL; // saves state of session
int status;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
// socket-related variables
struct addrinfo hints; // temp, needed to open a socket connection
struct addrinfo *addrinfo; // temp, needed to open a socket connection
struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
int ret; // return value from functions
// RPCAP-related variables
struct rpcap_startcapreq startcapreq; // start capture request message
struct rpcap_startcapreply *startcapreply; // start capture reply message
int serveropen_dp; // keeps who is going to open the data connection
addrinfo = NULL;
status = rpcapd_recv(pars->sockctrl, (char *) &startcapreq,
sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
if (status == -1)
{
goto fatal_error;
}
if (status == -2)
{
goto error;
}
startcapreq.flags = ntohs(startcapreq.flags);
// Create a session structure
session = malloc(sizeof(struct session));
if (session == NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
goto error;
}
session->sockdata = INVALID_SOCKET;
// We don't have a thread yet.
session->have_thread = 0;
//
// We *shouldn't* have to initialize the thread indicator
// itself, because the compiler *should* realize that we
// only use this if have_thread isn't 0, but we *do* have
// to do it, because not all compilers *do* realize that.
//
// There is no "invalid thread handle" value for a UN*X
// pthread_t, so we just zero it out.
//
#ifdef _WIN32
session->thread = INVALID_HANDLE_VALUE;
#else
memset(&session->thread, 0, sizeof(session->thread));
#endif
// Open the selected device
if ((session->fp = pcap_open_live(source,
ntohl(startcapreq.snaplen),
(startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
ntohl(startcapreq.read_timeout),
errmsgbuf)) == NULL)
goto error;
#if 0
// Apply sampling parameters
fp->rmt_samp.method = samp_param->method;
fp->rmt_samp.value = samp_param->value;
#endif
/*
We're in active mode if:
- we're using TCP, and the user wants us to be in active mode
- we're using UDP
*/
serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
/*
Gets the sockaddr structure referred to the other peer in the ctrl connection
We need that because:
- if we're in passive mode, we need to know the address family we want to use
(the same used for the ctrl socket)
- if we're in active mode, we need to know the network address of the other host
we want to connect to
*/
saddrlen = sizeof(struct sockaddr_storage);
if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_family = saddr.ss_family;
// Now we have to create a new socket to send packets
if (serveropen_dp) // Data connection is opened by the server toward the client
{
pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
// Get the name of the other peer (needed to connect to that specific network address)
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
}
else // Data connection is opened by the client toward the server
{
hints.ai_flags = AI_PASSIVE;
// Let's the server socket pick up a free network port for us
if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
// get the complete sockaddr structure used in the data connection
saddrlen = sizeof(struct sockaddr_storage);
if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getsockname()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
// Get the local port the system picked up
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
0, portdata, sizeof(portdata), NI_NUMERICSERV))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
}
// addrinfo is no longer used
freeaddrinfo(addrinfo);
addrinfo = NULL;
// Needed to send an error on the ctrl connection
session->sockctrl = pars->sockctrl;
session->protocol_version = ver;
// Now I can set the filter
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
goto fatal_error;
}
if (ret == -2)
{
// Non-fatal error. Send an error message to the client.
goto error;
}
// Now, I can send a RPCAP start capture reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
if (!serveropen_dp)
{
unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
startcapreply->portdata = htons(port);
}
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto fatal_error;
}
if (!serveropen_dp)
{
SOCKET socktemp; // We need another socket, since we're going to accept() a connection
// Connection creation
saddrlen = sizeof(struct sockaddr_storage);
socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen);
if (socktemp == INVALID_SOCKET)
{
sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
errbuf);
goto error;
}
// Now that I accepted the connection, the server socket is no longer needed
sock_close(session->sockdata, NULL, 0);
session->sockdata = socktemp;
}
// Now we have to create a new thread to receive packets
#ifdef _WIN32
session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
(void *) session, 0, NULL);
if (session->thread == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
goto error;
}
#else
ret = pthread_create(&session->thread, NULL, daemon_thrdatamain,
(void *) session);
if (ret != 0)
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
ret, "Error creating the data thread");
goto error;
}
#endif
session->have_thread = 1;
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
goto fatal_error;
*sessionp = session;
return 0;
error:
//
// Not a fatal error, so send the client an error message and
// keep serving client requests.
//
*sessionp = NULL;
if (addrinfo)
freeaddrinfo(addrinfo);
if (session)
{
session_close(session);
free(session);
}
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_STARTCAPTURE,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
return 0;
fatal_error:
//
// Fatal network error, so don't try to communicate with
// the client, just give up.
//
*sessionp = NULL;
if (session)
{
session_close(session);
free(session);
}
return -1;
}
static int
daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
struct rpcap_header header;
session_close(session);
rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
static int
daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errmsgbuf)
{
int status;
struct rpcap_filter filter;
struct rpcap_filterbpf_insn insn;
struct bpf_insn *bf_insn;
struct bpf_program bf_prog;
unsigned int i;
status = rpcapd_recv(sockctrl, (char *) &filter,
sizeof(struct rpcap_filter), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_prog.bf_len = ntohl(filter.nitems);
if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
return -2;
}
bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
if (bf_insn == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
errno, "malloc() failed");
return -2;
}
bf_prog.bf_insns = bf_insn;
for (i = 0; i < bf_prog.bf_len; i++)
{
status = rpcapd_recv(sockctrl, (char *) &insn,
sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_insn->code = ntohs(insn.code);
bf_insn->jf = insn.jf;
bf_insn->jt = insn.jt;
bf_insn->k = ntohl(insn.k);
bf_insn++;
}
if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
return -2;
}
if (pcap_setfilter(session->fp, &bf_prog))
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
return -2;
}
return 0;
}
static int
daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int ret; // status of daemon_unpackapplyfilter()
struct rpcap_header header; // keeps the answer to the updatefilter command
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
return -1;
}
if (ret == -2)
{
// Non-fatal error. Send an error reply to the client.
goto error;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_UPDATEFILTER,
errmsgbuf, NULL);
return 0;
}
/*!
\brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
*/
static int
daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
struct rpcap_sampling *samp_param)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE];
struct rpcap_header header;
struct rpcap_sampling rpcap_samp;
int status;
status = rpcapd_recv(pars->sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
// Save these settings in the pcap_t
samp_param->method = rpcap_samp.method;
samp_param->value = ntohl(rpcap_samp.value);
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_SETSAMPLING,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
static int
daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_stats *netstats; // statistics sent on the network
// Checks that the header does not contain other data; if so, discard it
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if (session && session->fp)
{
if (pcap_stats(session->fp, stats) == -1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
goto error;
}
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(session->TotCapt);
}
else
{
// We have to keep compatibility with old applications,
// which ask for statistics also when the capture has
// already stopped.
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(svrcapt);
}
// Send the packet
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_GETSTATS,
errmsgbuf, NULL);
return 0;
}
#ifdef _WIN32
static unsigned __stdcall
#else
static void *
#endif
daemon_thrdatamain(void *ptr)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
struct session *session; // pointer to the struct session for this session
int retval; // general variable used to keep the return value of other functions
struct rpcap_pkthdr *net_pkt_header;// header of the packet
struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
u_char *pkt_data; // pointer to the buffer that contains the current packet
size_t sendbufsize; // size for the send buffer
char *sendbuf; // temporary buffer in which data to be sent is buffered
int sendbufidx; // index which keeps the number of bytes currently buffered
int status;
#ifndef _WIN32
sigset_t sigusr1; // signal set with just SIGUSR1
#endif
session = (struct session *) ptr;
session->TotCapt = 0; // counter which is incremented each time a packet is received
// Initialize errbuf
memset(errbuf, 0, sizeof(errbuf));
//
// We need a buffer large enough to hold a buffer large enough
// for a maximum-size packet for this pcap_t.
//
if (pcap_snapshot(session->fp) < 0)
{
//
// The snapshot length is negative.
// This "should not happen".
//
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
pcap_snapshot(session->fp));
sendbuf = NULL; // we can't allocate a buffer, so nothing to free
goto error;
}
//
// size_t is unsigned, and the result of pcap_snapshot() is signed;
// on no platform that we support is int larger than size_t.
// This means that, unless the extra information we prepend to
// a maximum-sized packet is impossibly large, the sum of the
// snapshot length and the size of that extra information will
// fit in a size_t.
//
// So we don't need to make sure that sendbufsize will overflow.
//
sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
sendbuf = (char *) malloc (sendbufsize);
if (sendbuf == NULL)
{
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread");
goto error;
}
#ifndef _WIN32
//
// Set the signal set to include just SIGUSR1, and block that
// signal; we only want it unblocked when we're reading
// packets - we dn't want any other system calls, such as
// ones being used to send to the client or to log messages,
// to be interrupted.
//
sigemptyset(&sigusr1);
sigaddset(&sigusr1, SIGUSR1);
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
// Retrieve the packets
for (;;)
{
#ifndef _WIN32
//
// Unblock SIGUSR1 while we might be waiting for packets.
//
pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL);
#endif
retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning
#ifndef _WIN32
//
// Now block it again.
//
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
if (retval < 0)
break; // error
if (retval == 0) // Read timeout elapsed
continue;
sendbufidx = 0;
// Bufferize the general header
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
rpcap_createhdr((struct rpcap_header *) sendbuf,
session->protocol_version, RPCAP_MSG_PACKET, 0,
(uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
// Bufferize the pkt header
if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
net_pkt_header->caplen = htonl(pkt_header->caplen);
net_pkt_header->len = htonl(pkt_header->len);
net_pkt_header->npkt = htonl(++(session->TotCapt));
net_pkt_header->timestamp_sec = htonl(pkt_header->ts.tv_sec);
net_pkt_header->timestamp_usec = htonl(pkt_header->ts.tv_usec);
// Bufferize the pkt data
if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
sendbuf, &sendbufidx, sendbufsize, SOCKBUF_BUFFERIZE,
errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
// Send the packet
// If the client dropped the connection, don't report an
// error, just quit.
status = sock_send(session->sockdata, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
if (status < 0)
{
if (status == -1)
{
//
// Error other than "client closed the
// connection out from under us"; report
// it.
//
rpcapd_log(LOGPRIO_ERROR,
"Send of packet to client failed: %s",
errbuf);
}
//
// Give up in either case.
//
goto error;
}
}
if (retval < 0 && retval != PCAP_ERROR_BREAK)
{
//
// Failed with an error other than "we were told to break
// out of the loop".
//
// The latter just means that the client told us to stop
// capturing, so there's no error to report.
//
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
rpcap_senderror(session->sockctrl, session->protocol_version,
PCAP_ERR_READEX, errbuf, NULL);
}
error:
//
// The main thread will clean up the session structure.
//
free(sendbuf);
return 0;
}
#ifndef _WIN32
//
// Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to
// interrupt the data thread if it's blocked in a system call waiting
// for packets to arrive.
//
static void noop_handler(int sign _U_)
{
}
#endif
/*!
\brief It serializes a network address.
It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
that can be used to be sent on the network. Basically, it applies all the hton()
conversion required to the input variable.
\param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
\param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
the serialized data. This variable has to be allocated by the user.
\warning This function supports only AF_INET and AF_INET6 address families.
*/
static void
daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
{
memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
// There can be the case in which the sockaddrin is not available
if (sockaddrin == NULL) return;
// Warning: we support only AF_INET and AF_INET6
switch (sockaddrin->ss_family)
{
case AF_INET:
{
struct sockaddr_in *sockaddrin_ipv4;
struct rpcap_sockaddr_in *sockaddrout_ipv4;
sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
break;
}
#ifdef AF_INET6
case AF_INET6:
{
struct sockaddr_in6 *sockaddrin_ipv6;
struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
break;
}
#endif
}
}
/*!
\brief Suspends a thread for secs seconds.
*/
void sleep_secs(int secs)
{
#ifdef _WIN32
Sleep(secs*1000);
#else
unsigned secs_remaining;
if (secs <= 0)
return;
secs_remaining = secs;
while (secs_remaining != 0)
secs_remaining = sleep(secs_remaining);
#endif
}
/*
* Read the header of a message.
*/
static int
rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
nread = sock_recv(sock, (char *) headerp, sizeof(struct rpcap_header),
SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (nread == 0)
{
// Immediate EOF; that's treated like a close message.
return -2;
}
headerp->plen = ntohl(headerp->plen);
return 0;
}
/*
* Read data from a message.
* If we're trying to read more data that remains, puts an error
* message into errmsgbuf and returns -2. Otherwise, tries to read
* the data and, if that succeeds, subtracts the amount read from
* the number of bytes of data that remains.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
if (toread > *plen)
{
// Tell the client and continue.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
return -2;
}
nread = sock_recv(sock, buffer, toread,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
*plen -= nread;
return 0;
}
/*
* Discard data from a connection.
* Mostly used to discard wrong-sized messages.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_discard(SOCKET sock, uint32 len)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
if (len != 0)
{
if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
}
return 0;
}
//
// Shut down any packet-capture thread associated with the session,
// close the SSL handle for the data socket if we have one, close
// the data socket if we have one, and close the underlying packet
// capture handle if we have one.
//
// We do not, of course, touch the controlling socket that's also
// copied into the session, as the service loop might still use it.
//
static void session_close(struct session *session)
{
if (session->have_thread)
{
//
// Tell the data connection thread main capture loop to
// break out of that loop.
//
// This may be sufficient to wake up a blocked thread,
// but it's not guaranteed to be sufficient.
//
pcap_breakloop(session->fp);
#ifdef _WIN32
//
// Set the event on which a read would block, so that,
// if it's currently blocked waiting for packets to
// arrive, it'll wake up, so it can see the "break
// out of the loop" indication. (pcap_breakloop()
// might do this, but older versions don't. Setting
// it twice should, at worst, cause an extra wakeup,
// which shouldn't be a problem.)
//
// XXX - what about modules other than NPF?
//
SetEvent(pcap_getevent(session->fp));
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
WaitForSingleObject(session->thread, INFINITE);
//
// Release the thread handle, as we're done with
// it.
//
CloseHandle(session->thread);
session->have_thread = 0;
session->thread = INVALID_HANDLE_VALUE;
#else
//
// Send a SIGUSR1 signal to the thread, so that, if
// it's currently blocked waiting for packets to arrive,
// it'll wake up (we've turned off SA_RESTART for
// SIGUSR1, so that the system call in which it's blocked
// should return EINTR rather than restarting).
//
pthread_kill(session->thread, SIGUSR1);
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
pthread_join(session->thread, NULL);
session->have_thread = 0;
memset(&session->thread, 0, sizeof(session->thread));
#endif
}
if (session->sockdata != INVALID_SOCKET)
{
sock_close(session->sockdata, NULL, 0);
session->sockdata = INVALID_SOCKET;
}
if (session->fp)
{
pcap_close(session->fp);
session->fp = NULL;
}
}
// Check whether a capture source string is a URL or not.
// This includes URLs that refer to a local device; a scheme, followed
// by ://, followed by *another* scheme and ://, is just silly, and
// anybody who supplies that will get an error.
//
static int
is_url(const char *source)
{
char *colonp;
/*
* RFC 3986 says:
*
* URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
*
* hier-part = "//" authority path-abempty
* / path-absolute
* / path-rootless
* / path-empty
*
* authority = [ userinfo "@" ] host [ ":" port ]
*
* userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
*
* Step 1: look for the ":" at the end of the scheme.
* A colon in the source is *NOT* sufficient to indicate that
* this is a URL, as interface names on some platforms might
* include colons (e.g., I think some Solaris interfaces
* might).
*/
colonp = strchr(source, ':');
if (colonp == NULL)
{
/*
* The source is the device to open. It's not a URL.
*/
return (0);
}
/*
* All schemes must have "//" after them, i.e. we only support
* hier-part = "//" authority path-abempty, not
* hier-part = path-absolute
* hier-part = path-rootless
* hier-part = path-empty
*
* We need that in order to distinguish between a local device
* name that happens to contain a colon and a URI.
*/
if (strncmp(colonp + 1, "//", 2) != 0)
{
/*
* The source is the device to open. It's not a URL.
*/
return (0);
}
/*
* It's a URL.
*/
return (1);
}
| ./CrossVul/dataset_final_sorted/CWE-918/c/good_1025_0 |
crossvul-cpp_data_bad_1025_0 | /*
* Copyright (c) 2002 - 2003
* NetGroup, Politecnico di Torino (Italy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "ftmacros.h"
#include "varattrs.h"
#include <errno.h> // for the errno variable
#include <stdlib.h> // for malloc(), free(), ...
#include <string.h> // for strlen(), ...
#ifdef _WIN32
#include <process.h> // for threads
#else
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h> // for select() and such
#include <pwd.h> // for password management
#endif
#ifdef HAVE_GETSPNAM
#include <shadow.h> // for password management
#endif
#include <pcap.h> // for libpcap/WinPcap calls
#include "fmtutils.h"
#include "sockutils.h" // for socket calls
#include "portability.h"
#include "rpcap-protocol.h"
#include "daemon.h"
#include "log.h"
//
// Timeout, in seconds, when we're waiting for a client to send us an
// authentication request; if they don't send us a request within that
// interval, we drop the connection, so we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_INIT 90
//
// Timeout, in seconds, when we're waiting for an authenticated client
// to send us a request, if a capture isn't in progress; if they don't
// send us a request within that interval, we drop the connection, so
// we don't stay stuck forever.
//
#define RPCAP_TIMEOUT_RUNTIME 180
//
// Time, in seconds, that we wait after a failed authentication attempt
// before processing the next request; this prevents a client from
// rapidly trying different accounts or passwords.
//
#define RPCAP_SUSPEND_WRONGAUTH 1
// Parameters for the service loop.
struct daemon_slpars
{
SOCKET sockctrl; //!< SOCKET ID of the control connection
int isactive; //!< Not null if the daemon has to run in active mode
int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
};
//
// Data for a session managed by a thread.
// It includes both a Boolean indicating whether we *have* a thread,
// and a platform-dependent (UN*X vs. Windows) identifier for the
// thread; on Windows, we could use an invalid handle to indicate
// that we don't have a thread, but there *is* no portable "no thread"
// value for a pthread_t on UN*X.
//
struct session {
SOCKET sockctrl;
SOCKET sockdata;
uint8 protocol_version;
pcap_t *fp;
unsigned int TotCapt;
int have_thread;
#ifdef _WIN32
HANDLE thread;
#else
pthread_t thread;
#endif
};
// Locally defined functions
static int daemon_msg_err(SOCKET sockctrl, uint32 plen);
static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen);
static int daemon_AuthUserPwd(char *username, char *password, char *errbuf);
static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen);
static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, size_t sourcelen);
static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, char *source, struct session **sessionp,
struct rpcap_sampling *samp_param);
static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session);
static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen);
static int daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errbuf);
static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt);
static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars,
uint32 plen, struct rpcap_sampling *samp_param);
static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout);
#ifdef _WIN32
static unsigned __stdcall daemon_thrdatamain(void *ptr);
#else
static void *daemon_thrdatamain(void *ptr);
static void noop_handler(int sign);
#endif
static int rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp);
static int rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf);
static int rpcapd_discard(SOCKET sock, uint32 len);
static void session_close(struct session *);
int
daemon_serviceloop(SOCKET sockctrl, int isactive, char *passiveClients,
int nullAuthAllowed)
{
struct daemon_slpars pars; // service loop parameters
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client
int host_port_check_status;
int nrecv;
struct rpcap_header header; // RPCAP message general header
uint32 plen; // payload length from header
int authenticated = 0; // 1 if the client has successfully authenticated
char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open
int got_source = 0; // 1 if we've gotten the source from an open request
#ifndef _WIN32
struct sigaction action;
#endif
struct session *session = NULL; // struct session main variable
const char *msg_type_string; // string for message type
int client_told_us_to_close = 0; // 1 if the client told us to close the capture
// needed to save the values of the statistics
struct pcap_stat stats;
unsigned int svrcapt;
struct rpcap_sampling samp_param; // in case sampling has been requested
// Structures needed for the select() call
fd_set rfds; // set of socket descriptors we have to check
struct timeval tv; // maximum time the select() can block waiting for data
int retval; // select() return value
*errbuf = 0; // Initialize errbuf
// Set parameters structure
pars.sockctrl = sockctrl;
pars.isactive = isactive; // active mode
pars.nullAuthAllowed = nullAuthAllowed;
//
// We have a connection.
//
// If it's a passive mode connection, check whether the connecting
// host is among the ones allowed.
//
// In either case, we were handed a copy of the host list; free it
// as soon as we're done with it.
//
if (pars.isactive)
{
// Nothing to do.
free(passiveClients);
passiveClients = NULL;
}
else
{
struct sockaddr_storage from;
socklen_t fromlen;
//
// Get the address of the other end of the connection.
//
fromlen = sizeof(struct sockaddr_storage);
if (getpeername(pars.sockctrl, (struct sockaddr *)&from,
&fromlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
//
// Are they in the list of host/port combinations we allow?
//
host_port_check_status = sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE);
free(passiveClients);
passiveClients = NULL;
if (host_port_check_status < 0)
{
if (host_port_check_status == -2) {
//
// We got an error; log it.
//
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
//
// Sorry, we can't let you in.
//
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
#ifndef _WIN32
//
// Catch SIGUSR1, but do nothing. We use it to interrupt the
// capture thread to break it out of a loop in which it's
// blocked waiting for packets to arrive.
//
// We don't want interrupted system calls to restart, so that
// the read routine for the pcap_t gets EINTR rather than
// restarting if it's blocked in a system call.
//
memset(&action, 0, sizeof (action));
action.sa_handler = noop_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
#endif
//
// The client must first authenticate; loop until they send us a
// message with a version we support and credentials we accept,
// they send us a close message indicating that they're giving up,
// or we get a network error or other fatal error.
//
while (!authenticated)
{
//
// If we're not in active mode, we use select(), with a
// timeout, to wait for an authentication request; if
// the timeout expires, we drop the connection, so that
// a client can't just connect to us and leave us
// waiting forever.
//
if (!pars.isactive)
{
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_INIT;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// While we're in the authentication pharse, all requests
// must use version 0.
//
if (header.ver != 0)
{
//
// Send it back to them with their version.
//
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGVER,
"RPCAP version in requests in the authentication phase must be 0",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message and drop the
// connection.
(void)rpcapd_discard(pars.sockctrl, plen);
goto end;
}
switch (header.type)
{
case RPCAP_MSG_AUTH_REQ:
retval = daemon_msg_auth_req(&pars, plen);
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
if (retval == -2)
{
// Non-fatal error; we sent back
// an error message, so let them
// try again.
continue;
}
// OK, we're authenticated; we sent back
// a reply, so start serving requests.
authenticated = 1;
break;
case RPCAP_MSG_CLOSE:
//
// The client is giving up.
// Discard the rest of the message, if
// there is anything more.
//
(void)rpcapd_discard(pars.sockctrl, plen);
// We're done with this client.
goto end;
case RPCAP_MSG_ERROR:
// Log this and close the connection?
// XXX - is this what happens in active
// mode, where *we* initiate the
// connection, and the client gives us
// an error message rather than a "let
// me log in" message, indicating that
// we're not allowed to connect to them?
(void)daemon_msg_err(pars.sockctrl, plen);
goto end;
case RPCAP_MSG_FINDALLIF_REQ:
case RPCAP_MSG_OPEN_REQ:
case RPCAP_MSG_STARTCAP_REQ:
case RPCAP_MSG_UPDATEFILTER_REQ:
case RPCAP_MSG_STATS_REQ:
case RPCAP_MSG_ENDCAP_REQ:
case RPCAP_MSG_SETSAMPLING_REQ:
//
// These requests can't be sent until
// the client is authenticated.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Network error.
goto end;
}
break;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
default:
//
// Unknown message type.
//
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
break;
}
}
//
// OK, the client has authenticated itself, and we can start
// processing regular requests from it.
//
//
// We don't have any statistics yet.
//
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
//
// Service requests.
//
for (;;)
{
errbuf[0] = 0; // clear errbuf
// Avoid zombies connections; check if the connection is opens but no commands are performed
// from more than RPCAP_TIMEOUT_RUNTIME
// Conditions:
// - I have to be in normal mode (no active mode)
// - if the device is open, I don't have to be in the middle of a capture (session->sockdata)
// - if the device is closed, I have always to check if a new command arrives
//
// Be carefully: the capture can have been started, but an error occurred (so session != NULL, but
// sockdata is 0
if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0))))
{
// Check for the initial timeout
FD_ZERO(&rfds);
// We do not have to block here
tv.tv_sec = RPCAP_TIMEOUT_RUNTIME;
tv.tv_usec = 0;
FD_SET(pars.sockctrl, &rfds);
retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
if (retval == -1)
{
sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// The timeout has expired
// So, this was a fake connection. Drop it down
if (retval == 0)
{
if (rpcap_senderror(pars.sockctrl, 0,
PCAP_ERR_INITTIMEOUT,
"The RPCAP initial timeout has expired",
errbuf) == -1)
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
//
// Read the message header from the client.
//
nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header);
if (nrecv == -1)
{
// Fatal error.
goto end;
}
if (nrecv == -2)
{
// Client closed the connection.
goto end;
}
plen = header.plen;
//
// Did the client specify a protocol version that we
// support?
//
if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
{
//
// Tell them it's not a supported version.
// Send the error message with their version,
// so they don't reject it as having the wrong
// version.
//
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_WRONGVER,
"RPCAP version in message isn't supported by the server",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
(void)rpcapd_discard(pars.sockctrl, plen);
// Give up on them.
goto end;
}
switch (header.type)
{
case RPCAP_MSG_ERROR: // The other endpoint reported an error
{
(void)daemon_msg_err(pars.sockctrl, plen);
// Do nothing; just exit; the error code is already into the errbuf
// XXX - actually exit....
break;
}
case RPCAP_MSG_FINDALLIF_REQ:
{
if (daemon_msg_findallif_req(header.ver, &pars, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_OPEN_REQ:
{
//
// Process the open request, and keep
// the source from it, for use later
// when the capture is started.
//
// XXX - we don't care if the client sends
// us multiple open requests, the last
// one wins.
//
retval = daemon_msg_open_req(header.ver, &pars,
plen, source, sizeof(source));
if (retval == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
got_source = 1;
break;
}
case RPCAP_MSG_STARTCAP_REQ:
{
if (!got_source)
{
// They never told us what device
// to capture on!
if (rpcap_senderror(pars.sockctrl,
header.ver,
PCAP_ERR_STARTCAPTURE,
"No capture device was specified",
errbuf) == -1)
{
// Fatal error; log an
// error and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
goto end;
}
break;
}
if (daemon_msg_startcap_req(header.ver, &pars,
plen, source, &session, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_UPDATEFILTER_REQ:
{
if (session)
{
if (daemon_msg_updatefilter_req(header.ver,
&pars, session, plen) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
}
else
{
if (rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_UPDATEFILTER,
"Device not opened. Cannot update filter",
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
}
break;
}
case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session
{
//
// Indicate to our caller that the client
// closed the control connection.
// This is used only in case of active mode.
//
client_told_us_to_close = 1;
rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection.");
goto end;
}
case RPCAP_MSG_STATS_REQ:
{
if (daemon_msg_stats_req(header.ver, &pars,
session, plen, &stats, svrcapt) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session
{
if (session)
{
// Save statistics (we can need them in the future)
if (pcap_stats(session->fp, &stats))
{
svrcapt = session->TotCapt;
}
else
{
stats.ps_ifdrop = 0;
stats.ps_recv = 0;
stats.ps_drop = 0;
svrcapt = 0;
}
if (daemon_msg_endcap_req(header.ver,
&pars, session) == -1)
{
free(session);
session = NULL;
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
free(session);
session = NULL;
}
else
{
rpcap_senderror(pars.sockctrl,
header.ver, PCAP_ERR_ENDCAPTURE,
"Device not opened. Cannot close the capture",
errbuf);
}
break;
}
case RPCAP_MSG_SETSAMPLING_REQ:
{
if (daemon_msg_setsampling_req(header.ver,
&pars, plen, &samp_param) == -1)
{
// Fatal error; a message has
// been logged, so just give up.
goto end;
}
break;
}
case RPCAP_MSG_AUTH_REQ:
{
//
// We're already authenticated; you don't
// get to reauthenticate.
//
rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed");
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG,
"RPCAP_MSG_AUTH_REQ request sent after authentication was completed",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
case RPCAP_MSG_PACKET:
case RPCAP_MSG_FINDALLIF_REPLY:
case RPCAP_MSG_OPEN_REPLY:
case RPCAP_MSG_STARTCAP_REPLY:
case RPCAP_MSG_UPDATEFILTER_REPLY:
case RPCAP_MSG_AUTH_REPLY:
case RPCAP_MSG_STATS_REPLY:
case RPCAP_MSG_ENDCAP_REPLY:
case RPCAP_MSG_SETSAMPLING_REPLY:
//
// These are server-to-client messages.
//
msg_type_string = rpcap_msg_type_string(header.type);
if (msg_type_string != NULL)
{
rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
}
else
{
rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
}
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
default:
//
// Unknown message type.
//
rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type);
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
if (rpcap_senderror(pars.sockctrl, header.ver,
PCAP_ERR_WRONGMSG, errbuf, errmsgbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto end;
}
// Discard the rest of the message.
if (rpcapd_discard(pars.sockctrl, plen) == -1)
{
// Fatal error.
goto end;
}
goto end;
}
}
}
end:
// The service loop is finishing up.
// If we have a capture session running, close it.
if (session)
{
session_close(session);
free(session);
session = NULL;
}
sock_close(sockctrl, NULL, 0);
// Print message and return
rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop");
return client_told_us_to_close;
}
/*
* This handles the RPCAP_MSG_ERR message.
*/
static int
daemon_msg_err(SOCKET sockctrl, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char remote_errbuf[PCAP_ERRBUF_SIZE];
if (plen >= PCAP_ERRBUF_SIZE)
{
/*
* Message is too long; just read as much of it as we
* can into the buffer provided, and discard the rest.
*/
if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1)
{
// Network error.
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
}
else if (plen == 0)
{
/* Empty error string. */
remote_errbuf[0] = '\0';
}
else
{
if (sock_recv(sockctrl, remote_errbuf, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
/*
* Null-terminate it.
*/
remote_errbuf[plen] = '\0';
}
// Log the message
rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf);
return 0;
}
/*
* This handles the RPCAP_MSG_AUTH_REQ message.
* It checks if the authentication credentials supplied by the user are valid.
*
* This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ
* message in its authentication loop. It reads the body of the
* authentication message from the network and checks whether the
* credentials are valid.
*
* \param sockctrl: the socket for the control connection.
*
* \param nullAuthAllowed: '1' if the NULL authentication is allowed.
*
* \param errbuf: a user-allocated buffer in which the error message
* (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE
* bytes long.
*
* \return '0' if everything is fine, '-1' if an unrecoverable error occurred,
* or '-2' if the authentication failed. For errors, an error message is
* returned in the 'errbuf' variable; this gives a message for the
* unrecoverable error or for the authentication failure.
*/
static int
daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int status;
struct rpcap_auth auth; // RPCAP authentication header
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_authreply *authreply; // authentication reply message
status = rpcapd_recv(pars->sockctrl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
switch (ntohs(auth.type))
{
case RPCAP_RMTAUTH_NULL:
{
if (!pars->nullAuthAllowed)
{
// Send the client an error reply.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication failed; NULL authentication not permitted.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
break;
}
case RPCAP_RMTAUTH_PWD:
{
char *username, *passwd;
uint32 usernamelen, passwdlen;
usernamelen = ntohs(auth.slen1);
username = (char *) malloc (usernamelen + 1);
if (username == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
goto error;
}
status = rpcapd_recv(pars->sockctrl, username, usernamelen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
return -1;
}
if (status == -2)
{
free(username);
goto error;
}
username[usernamelen] = '\0';
passwdlen = ntohs(auth.slen2);
passwd = (char *) malloc (passwdlen + 1);
if (passwd == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf,
PCAP_ERRBUF_SIZE, errno, "malloc() failed");
free(username);
goto error;
}
status = rpcapd_recv(pars->sockctrl, passwd, passwdlen, &plen, errmsgbuf);
if (status == -1)
{
free(username);
free(passwd);
return -1;
}
if (status == -2)
{
free(username);
free(passwd);
goto error;
}
passwd[passwdlen] = '\0';
if (daemon_AuthUserPwd(username, passwd, errmsgbuf))
{
//
// Authentication failed. Let the client
// know.
//
free(username);
free(passwd);
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
//
// Suspend for 1 second, so that they can't
// hammer us with repeated tries with an
// attack such as a dictionary attack.
//
// WARNING: this delay is inserted only
// at this point; if the client closes the
// connection and reconnects, the suspension
// time does not have any effect.
//
sleep_secs(RPCAP_SUSPEND_WRONGAUTH);
goto error_noreply;
}
free(username);
free(passwd);
break;
}
default:
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
"Authentication type not recognized.");
if (rpcap_senderror(pars->sockctrl, 0,
PCAP_ERR_AUTH_TYPE_NOTSUP, errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
goto error_noreply;
}
// The authentication succeeded; let the client know.
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
RPCAP_MSG_AUTH_REPLY, 0, sizeof(struct rpcap_authreply));
authreply = (struct rpcap_authreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_authreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
//
// Indicate to our peer what versions we support.
//
memset(authreply, 0, sizeof(struct rpcap_authreply));
authreply->minvers = RPCAP_MIN_VERSION;
authreply->maxvers = RPCAP_MAX_VERSION;
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH, errmsgbuf,
errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
error_noreply:
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return -2;
}
static int
daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
DWORD error;
HANDLE Token;
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to log
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
error = GetLastError();
if (error != ERROR_LOGON_FAILURE)
{
// Some error other than an authentication error;
// log it.
pcap_fmt_errmsg_for_win32_err(errmsgbuf,
PCAP_ERRBUF_SIZE, error, "LogonUser() failed");
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
}
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
pcap_fmt_errmsg_for_win32_err(errmsgbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
int error;
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
//
// The Single UNIX Specification says that if crypt() fails it
// sets errno, but some implementatons that haven't been run
// through the SUS test suite might not do so.
//
errno = 0;
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
error = errno;
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
if (error == 0)
{
// It didn't set errno.
rpcapd_log(LOGPRIO_ERROR, "crypt() failed");
}
else
{
rpcapd_log(LOGPRIO_ERROR, "crypt() failed: %s",
strerror(error));
}
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (setuid(user->pw_uid))
{
error = errno;
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
error, "setuid");
rpcapd_log(LOGPRIO_ERROR, "setuid() failed: %s",
strerror(error));
return -1;
}
/* if (setgid(user->pw_gid))
{
error = errno;
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
rpcapd_log(LOGPRIO_ERROR, "setgid() failed: %s",
strerror(error));
return -1;
}
*/
return 0;
#endif
}
static int
daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint16 nif = 0; // counts the number of interface listed
// Discard the rest of the message; there shouldn't be any payload.
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// Retrieve the device list
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
// checks the number of interfaces and it computes the total length of the payload
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
plen+= strlen(d->description);
if (d->name)
plen+= strlen(d->name);
plen+= sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
plen+= (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
// RPCAP findalldevs command
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
// send the interface list
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
// send all addresses
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
// We no longer need the device list. Free it.
pcap_freealldevs(alldevs);
// Send a final command that says "now send it!"
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, size_t sourcelen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
pcap_t *fp; // pcap_t main variable
int nread;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_openreply *openreply; // open reply message
if (plen > sourcelen - 1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
goto error;
}
nread = sock_recv(pars->sockctrl, source, plen,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
source[nread] = '\0';
plen -= nread;
// XXX - make sure it's *not* a URL; we don't support opening
// remote devices here.
// Open the selected device
// This is a fake open, since we do that only to get the needed parameters, then we close the device again
if ((fp = pcap_open_live(source,
1500 /* fake snaplen */,
0 /* no promis */,
1000 /* fake timeout */,
errmsgbuf)) == NULL)
goto error;
// Now, I can send a RPCAP open reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(openreply, 0, sizeof(struct rpcap_openreply));
openreply->linktype = htonl(pcap_datalink(fp));
openreply->tzoff = 0; /* This is always 0 for live captures */
// We're done with the pcap_t.
pcap_close(fp);
// Send the reply.
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
/*
\param plen: the length of the current message (needed in order to be able
to discard excess data in the message, if present)
*/
static int
daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
char *source, struct session **sessionp,
struct rpcap_sampling *samp_param _U_)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
struct session *session = NULL; // saves state of session
int status;
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
// socket-related variables
struct addrinfo hints; // temp, needed to open a socket connection
struct addrinfo *addrinfo; // temp, needed to open a socket connection
struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
int ret; // return value from functions
// RPCAP-related variables
struct rpcap_startcapreq startcapreq; // start capture request message
struct rpcap_startcapreply *startcapreply; // start capture reply message
int serveropen_dp; // keeps who is going to open the data connection
addrinfo = NULL;
status = rpcapd_recv(pars->sockctrl, (char *) &startcapreq,
sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
if (status == -1)
{
goto fatal_error;
}
if (status == -2)
{
goto error;
}
startcapreq.flags = ntohs(startcapreq.flags);
// Create a session structure
session = malloc(sizeof(struct session));
if (session == NULL)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
goto error;
}
session->sockdata = INVALID_SOCKET;
// We don't have a thread yet.
session->have_thread = 0;
//
// We *shouldn't* have to initialize the thread indicator
// itself, because the compiler *should* realize that we
// only use this if have_thread isn't 0, but we *do* have
// to do it, because not all compilers *do* realize that.
//
// There is no "invalid thread handle" value for a UN*X
// pthread_t, so we just zero it out.
//
#ifdef _WIN32
session->thread = INVALID_HANDLE_VALUE;
#else
memset(&session->thread, 0, sizeof(session->thread));
#endif
// Open the selected device
if ((session->fp = pcap_open_live(source,
ntohl(startcapreq.snaplen),
(startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
ntohl(startcapreq.read_timeout),
errmsgbuf)) == NULL)
goto error;
#if 0
// Apply sampling parameters
fp->rmt_samp.method = samp_param->method;
fp->rmt_samp.value = samp_param->value;
#endif
/*
We're in active mode if:
- we're using TCP, and the user wants us to be in active mode
- we're using UDP
*/
serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
/*
Gets the sockaddr structure referred to the other peer in the ctrl connection
We need that because:
- if we're in passive mode, we need to know the address family we want to use
(the same used for the ctrl socket)
- if we're in active mode, we need to know the network address of the other host
we want to connect to
*/
saddrlen = sizeof(struct sockaddr_storage);
if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_family = saddr.ss_family;
// Now we have to create a new socket to send packets
if (serveropen_dp) // Data connection is opened by the server toward the client
{
pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
// Get the name of the other peer (needed to connect to that specific network address)
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
}
else // Data connection is opened by the client toward the server
{
hints.ai_flags = AI_PASSIVE;
// Let's the server socket pick up a free network port for us
if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
goto error;
// get the complete sockaddr structure used in the data connection
saddrlen = sizeof(struct sockaddr_storage);
if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
{
sock_geterror("getsockname()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
// Get the local port the system picked up
if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
0, portdata, sizeof(portdata), NI_NUMERICSERV))
{
sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
goto error;
}
}
// addrinfo is no longer used
freeaddrinfo(addrinfo);
addrinfo = NULL;
// Needed to send an error on the ctrl connection
session->sockctrl = pars->sockctrl;
session->protocol_version = ver;
// Now I can set the filter
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
goto fatal_error;
}
if (ret == -2)
{
// Non-fatal error. Send an error message to the client.
goto error;
}
// Now, I can send a RPCAP start capture reply message
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
if (!serveropen_dp)
{
unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
startcapreply->portdata = htons(port);
}
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
goto fatal_error;
}
if (!serveropen_dp)
{
SOCKET socktemp; // We need another socket, since we're going to accept() a connection
// Connection creation
saddrlen = sizeof(struct sockaddr_storage);
socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen);
if (socktemp == INVALID_SOCKET)
{
sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
errbuf);
goto error;
}
// Now that I accepted the connection, the server socket is no longer needed
sock_close(session->sockdata, NULL, 0);
session->sockdata = socktemp;
}
// Now we have to create a new thread to receive packets
#ifdef _WIN32
session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
(void *) session, 0, NULL);
if (session->thread == 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
goto error;
}
#else
ret = pthread_create(&session->thread, NULL, daemon_thrdatamain,
(void *) session);
if (ret != 0)
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
ret, "Error creating the data thread");
goto error;
}
#endif
session->have_thread = 1;
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
goto fatal_error;
*sessionp = session;
return 0;
error:
//
// Not a fatal error, so send the client an error message and
// keep serving client requests.
//
*sessionp = NULL;
if (addrinfo)
freeaddrinfo(addrinfo);
if (session)
{
session_close(session);
free(session);
}
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_STARTCAPTURE,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
return 0;
fatal_error:
//
// Fatal network error, so don't try to communicate with
// the client, just give up.
//
*sessionp = NULL;
if (session)
{
session_close(session);
free(session);
}
return -1;
}
static int
daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
struct session *session)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
struct rpcap_header header;
session_close(session);
rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
static int
daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errmsgbuf)
{
int status;
struct rpcap_filter filter;
struct rpcap_filterbpf_insn insn;
struct bpf_insn *bf_insn;
struct bpf_program bf_prog;
unsigned int i;
status = rpcapd_recv(sockctrl, (char *) &filter,
sizeof(struct rpcap_filter), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_prog.bf_len = ntohl(filter.nitems);
if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
return -2;
}
bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
if (bf_insn == NULL)
{
pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
errno, "malloc() failed");
return -2;
}
bf_prog.bf_insns = bf_insn;
for (i = 0; i < bf_prog.bf_len; i++)
{
status = rpcapd_recv(sockctrl, (char *) &insn,
sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
return -2;
}
bf_insn->code = ntohs(insn.code);
bf_insn->jf = insn.jf;
bf_insn->jt = insn.jt;
bf_insn->k = ntohl(insn.k);
bf_insn++;
}
if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
return -2;
}
if (pcap_setfilter(session->fp, &bf_prog))
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
return -2;
}
return 0;
}
static int
daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE];
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
int ret; // status of daemon_unpackapplyfilter()
struct rpcap_header header; // keeps the answer to the updatefilter command
ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf);
if (ret == -1)
{
// Fatal error. A message has been logged; just give up.
return -1;
}
if (ret == -2)
{
// Non-fatal error. Send an error reply to the client.
goto error;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_UPDATEFILTER,
errmsgbuf, NULL);
return 0;
}
/*!
\brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
*/
static int
daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
struct rpcap_sampling *samp_param)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE];
struct rpcap_header header;
struct rpcap_sampling rpcap_samp;
int status;
status = rpcapd_recv(pars->sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
if (status == -1)
{
return -1;
}
if (status == -2)
{
goto error;
}
// Save these settings in the pcap_t
samp_param->method = rpcap_samp.method;
samp_param->value = ntohl(rpcap_samp.value);
// A response is needed, otherwise the other host does not know that everything went well
rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// That failed; log a messsage and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
error:
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_SETSAMPLING,
errmsgbuf, errbuf) == -1)
{
// That failed; log a message and give up.
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
// Check if all the data has been read; if not, discard the data in excess
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
return 0;
}
static int
daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
struct session *session, uint32 plen, struct pcap_stat *stats,
unsigned int svrcapt)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
struct rpcap_stats *netstats; // statistics sent on the network
// Checks that the header does not contain other data; if so, discard it
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
// Network error.
return -1;
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
if (session && session->fp)
{
if (pcap_stats(session->fp, stats) == -1)
{
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
goto error;
}
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(session->TotCapt);
}
else
{
// We have to keep compatibility with old applications,
// which ask for statistics also when the capture has
// already stopped.
netstats->ifdrop = htonl(stats->ps_ifdrop);
netstats->ifrecv = htonl(stats->ps_recv);
netstats->krnldrop = htonl(stats->ps_drop);
netstats->svrcapt = htonl(svrcapt);
}
// Send the packet
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_GETSTATS,
errmsgbuf, NULL);
return 0;
}
#ifdef _WIN32
static unsigned __stdcall
#else
static void *
#endif
daemon_thrdatamain(void *ptr)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
struct session *session; // pointer to the struct session for this session
int retval; // general variable used to keep the return value of other functions
struct rpcap_pkthdr *net_pkt_header;// header of the packet
struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
u_char *pkt_data; // pointer to the buffer that contains the current packet
size_t sendbufsize; // size for the send buffer
char *sendbuf; // temporary buffer in which data to be sent is buffered
int sendbufidx; // index which keeps the number of bytes currently buffered
int status;
#ifndef _WIN32
sigset_t sigusr1; // signal set with just SIGUSR1
#endif
session = (struct session *) ptr;
session->TotCapt = 0; // counter which is incremented each time a packet is received
// Initialize errbuf
memset(errbuf, 0, sizeof(errbuf));
//
// We need a buffer large enough to hold a buffer large enough
// for a maximum-size packet for this pcap_t.
//
if (pcap_snapshot(session->fp) < 0)
{
//
// The snapshot length is negative.
// This "should not happen".
//
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
pcap_snapshot(session->fp));
sendbuf = NULL; // we can't allocate a buffer, so nothing to free
goto error;
}
//
// size_t is unsigned, and the result of pcap_snapshot() is signed;
// on no platform that we support is int larger than size_t.
// This means that, unless the extra information we prepend to
// a maximum-sized packet is impossibly large, the sum of the
// snapshot length and the size of that extra information will
// fit in a size_t.
//
// So we don't need to make sure that sendbufsize will overflow.
//
sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
sendbuf = (char *) malloc (sendbufsize);
if (sendbuf == NULL)
{
rpcapd_log(LOGPRIO_ERROR,
"Unable to allocate the buffer for this child thread");
goto error;
}
#ifndef _WIN32
//
// Set the signal set to include just SIGUSR1, and block that
// signal; we only want it unblocked when we're reading
// packets - we dn't want any other system calls, such as
// ones being used to send to the client or to log messages,
// to be interrupted.
//
sigemptyset(&sigusr1);
sigaddset(&sigusr1, SIGUSR1);
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
// Retrieve the packets
for (;;)
{
#ifndef _WIN32
//
// Unblock SIGUSR1 while we might be waiting for packets.
//
pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL);
#endif
retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning
#ifndef _WIN32
//
// Now block it again.
//
pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
#endif
if (retval < 0)
break; // error
if (retval == 0) // Read timeout elapsed
continue;
sendbufidx = 0;
// Bufferize the general header
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
rpcap_createhdr((struct rpcap_header *) sendbuf,
session->protocol_version, RPCAP_MSG_PACKET, 0,
(uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
// Bufferize the pkt header
if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
&sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf,
PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
net_pkt_header->caplen = htonl(pkt_header->caplen);
net_pkt_header->len = htonl(pkt_header->len);
net_pkt_header->npkt = htonl(++(session->TotCapt));
net_pkt_header->timestamp_sec = htonl(pkt_header->ts.tv_sec);
net_pkt_header->timestamp_usec = htonl(pkt_header->ts.tv_usec);
// Bufferize the pkt data
if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
sendbuf, &sendbufidx, sendbufsize, SOCKBUF_BUFFERIZE,
errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR,
"sock_bufferize() error sending packet message: %s",
errbuf);
goto error;
}
// Send the packet
// If the client dropped the connection, don't report an
// error, just quit.
status = sock_send(session->sockdata, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
if (status < 0)
{
if (status == -1)
{
//
// Error other than "client closed the
// connection out from under us"; report
// it.
//
rpcapd_log(LOGPRIO_ERROR,
"Send of packet to client failed: %s",
errbuf);
}
//
// Give up in either case.
//
goto error;
}
}
if (retval < 0 && retval != PCAP_ERROR_BREAK)
{
//
// Failed with an error other than "we were told to break
// out of the loop".
//
// The latter just means that the client told us to stop
// capturing, so there's no error to report.
//
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
rpcap_senderror(session->sockctrl, session->protocol_version,
PCAP_ERR_READEX, errbuf, NULL);
}
error:
//
// The main thread will clean up the session structure.
//
free(sendbuf);
return 0;
}
#ifndef _WIN32
//
// Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to
// interrupt the data thread if it's blocked in a system call waiting
// for packets to arrive.
//
static void noop_handler(int sign _U_)
{
}
#endif
/*!
\brief It serializes a network address.
It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
that can be used to be sent on the network. Basically, it applies all the hton()
conversion required to the input variable.
\param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
\param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
the serialized data. This variable has to be allocated by the user.
\warning This function supports only AF_INET and AF_INET6 address families.
*/
static void
daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
{
memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
// There can be the case in which the sockaddrin is not available
if (sockaddrin == NULL) return;
// Warning: we support only AF_INET and AF_INET6
switch (sockaddrin->ss_family)
{
case AF_INET:
{
struct sockaddr_in *sockaddrin_ipv4;
struct rpcap_sockaddr_in *sockaddrout_ipv4;
sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
break;
}
#ifdef AF_INET6
case AF_INET6:
{
struct sockaddr_in6 *sockaddrin_ipv6;
struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
break;
}
#endif
}
}
/*!
\brief Suspends a thread for secs seconds.
*/
void sleep_secs(int secs)
{
#ifdef _WIN32
Sleep(secs*1000);
#else
unsigned secs_remaining;
if (secs <= 0)
return;
secs_remaining = secs;
while (secs_remaining != 0)
secs_remaining = sleep(secs_remaining);
#endif
}
/*
* Read the header of a message.
*/
static int
rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
nread = sock_recv(sock, (char *) headerp, sizeof(struct rpcap_header),
SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
if (nread == 0)
{
// Immediate EOF; that's treated like a close message.
return -2;
}
headerp->plen = ntohl(headerp->plen);
return 0;
}
/*
* Read data from a message.
* If we're trying to read more data that remains, puts an error
* message into errmsgbuf and returns -2. Otherwise, tries to read
* the data and, if that succeeds, subtracts the amount read from
* the number of bytes of data that remains.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
{
int nread;
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
if (toread > *plen)
{
// Tell the client and continue.
pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
return -2;
}
nread = sock_recv(sock, buffer, toread,
SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
if (nread == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
*plen -= nread;
return 0;
}
/*
* Discard data from a connection.
* Mostly used to discard wrong-sized messages.
* Returns 0 on success, logs a message and returns -1 on a network
* error.
*/
static int
rpcapd_discard(SOCKET sock, uint32 len)
{
char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
if (len != 0)
{
if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
// Network error.
rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
return -1;
}
}
return 0;
}
//
// Shut down any packet-capture thread associated with the session,
// close the SSL handle for the data socket if we have one, close
// the data socket if we have one, and close the underlying packet
// capture handle if we have one.
//
// We do not, of course, touch the controlling socket that's also
// copied into the session, as the service loop might still use it.
//
static void session_close(struct session *session)
{
if (session->have_thread)
{
//
// Tell the data connection thread main capture loop to
// break out of that loop.
//
// This may be sufficient to wake up a blocked thread,
// but it's not guaranteed to be sufficient.
//
pcap_breakloop(session->fp);
#ifdef _WIN32
//
// Set the event on which a read would block, so that,
// if it's currently blocked waiting for packets to
// arrive, it'll wake up, so it can see the "break
// out of the loop" indication. (pcap_breakloop()
// might do this, but older versions don't. Setting
// it twice should, at worst, cause an extra wakeup,
// which shouldn't be a problem.)
//
// XXX - what about modules other than NPF?
//
SetEvent(pcap_getevent(session->fp));
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
WaitForSingleObject(session->thread, INFINITE);
//
// Release the thread handle, as we're done with
// it.
//
CloseHandle(session->thread);
session->have_thread = 0;
session->thread = INVALID_HANDLE_VALUE;
#else
//
// Send a SIGUSR1 signal to the thread, so that, if
// it's currently blocked waiting for packets to arrive,
// it'll wake up (we've turned off SA_RESTART for
// SIGUSR1, so that the system call in which it's blocked
// should return EINTR rather than restarting).
//
pthread_kill(session->thread, SIGUSR1);
//
// Wait for the thread to exit, so we don't close
// sockets out from under it.
//
// XXX - have a timeout, so we don't wait forever?
//
pthread_join(session->thread, NULL);
session->have_thread = 0;
memset(&session->thread, 0, sizeof(session->thread));
#endif
}
if (session->sockdata != INVALID_SOCKET)
{
sock_close(session->sockdata, NULL, 0);
session->sockdata = INVALID_SOCKET;
}
if (session->fp)
{
pcap_close(session->fp);
session->fp = NULL;
}
}
| ./CrossVul/dataset_final_sorted/CWE-918/c/bad_1025_0 |
crossvul-cpp_data_bad_4096_0 | /*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "synergy/ProtocolUtil.h"
#include "io/IStream.h"
#include "base/Log.h"
#include "common/stdvector.h"
#include <cctype>
#include <cstring>
//
// ProtocolUtil
//
void
ProtocolUtil::writef(synergy::IStream* stream, const char* fmt, ...)
{
assert(stream != NULL);
assert(fmt != NULL);
LOG((CLOG_DEBUG2 "writef(%s)", fmt));
va_list args;
va_start(args, fmt);
UInt32 size = getLength(fmt, args);
va_end(args);
va_start(args, fmt);
vwritef(stream, fmt, size, args);
va_end(args);
}
bool
ProtocolUtil::readf(synergy::IStream* stream, const char* fmt, ...)
{
assert(stream != NULL);
assert(fmt != NULL);
LOG((CLOG_DEBUG2 "readf(%s)", fmt));
bool result;
va_list args;
va_start(args, fmt);
try {
vreadf(stream, fmt, args);
result = true;
}
catch (XIO&) {
result = false;
}
va_end(args);
return result;
}
void
ProtocolUtil::vwritef(synergy::IStream* stream,
const char* fmt, UInt32 size, va_list args)
{
assert(stream != NULL);
assert(fmt != NULL);
// done if nothing to write
if (size == 0) {
return;
}
// fill buffer
UInt8* buffer = new UInt8[size];
writef(buffer, fmt, args);
try {
// write buffer
stream->write(buffer, size);
LOG((CLOG_DEBUG2 "wrote %d bytes", size));
delete[] buffer;
}
catch (XBase&) {
delete[] buffer;
throw;
}
}
void
ProtocolUtil::vreadf(synergy::IStream* stream, const char* fmt, va_list args)
{
assert(stream != NULL);
assert(fmt != NULL);
// begin scanning
while (*fmt) {
if (*fmt == '%') {
// format specifier. determine argument size.
++fmt;
UInt32 len = eatLength(&fmt);
switch (*fmt) {
case 'i': {
// check for valid length
assert(len == 1 || len == 2 || len == 4);
// read the data
UInt8 buffer[4];
read(stream, buffer, len);
// convert it
void* v = va_arg(args, void*);
switch (len) {
case 1:
// 1 byte integer
*static_cast<UInt8*>(v) = buffer[0];
LOG((CLOG_DEBUG2 "readf: read %d byte integer: %d (0x%x)", len, *static_cast<UInt8*>(v), *static_cast<UInt8*>(v)));
break;
case 2:
// 2 byte integer
*static_cast<UInt16*>(v) =
static_cast<UInt16>(
(static_cast<UInt16>(buffer[0]) << 8) |
static_cast<UInt16>(buffer[1]));
LOG((CLOG_DEBUG2 "readf: read %d byte integer: %d (0x%x)", len, *static_cast<UInt16*>(v), *static_cast<UInt16*>(v)));
break;
case 4:
// 4 byte integer
*static_cast<UInt32*>(v) =
(static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]);
LOG((CLOG_DEBUG2 "readf: read %d byte integer: %d (0x%x)", len, *static_cast<UInt32*>(v), *static_cast<UInt32*>(v)));
break;
}
break;
}
case 'I': {
// check for valid length
assert(len == 1 || len == 2 || len == 4);
// read the vector length
UInt8 buffer[4];
read(stream, buffer, 4);
UInt32 n = (static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]);
// convert it
void* v = va_arg(args, void*);
switch (len) {
case 1:
// 1 byte integer
for (UInt32 i = 0; i < n; ++i) {
read(stream, buffer, 1);
static_cast<std::vector<UInt8>*>(v)->push_back(
buffer[0]);
LOG((CLOG_DEBUG2 "readf: read %d byte integer[%d]: %d (0x%x)", len, i, static_cast<std::vector<UInt8>*>(v)->back(), static_cast<std::vector<UInt8>*>(v)->back()));
}
break;
case 2:
// 2 byte integer
for (UInt32 i = 0; i < n; ++i) {
read(stream, buffer, 2);
static_cast<std::vector<UInt16>*>(v)->push_back(
static_cast<UInt16>(
(static_cast<UInt16>(buffer[0]) << 8) |
static_cast<UInt16>(buffer[1])));
LOG((CLOG_DEBUG2 "readf: read %d byte integer[%d]: %d (0x%x)", len, i, static_cast<std::vector<UInt16>*>(v)->back(), static_cast<std::vector<UInt16>*>(v)->back()));
}
break;
case 4:
// 4 byte integer
for (UInt32 i = 0; i < n; ++i) {
read(stream, buffer, 4);
static_cast<std::vector<UInt32>*>(v)->push_back(
(static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]));
LOG((CLOG_DEBUG2 "readf: read %d byte integer[%d]: %d (0x%x)", len, i, static_cast<std::vector<UInt32>*>(v)->back(), static_cast<std::vector<UInt32>*>(v)->back()));
}
break;
}
break;
}
case 's': {
assert(len == 0);
// read the string length
UInt8 buffer[128];
read(stream, buffer, 4);
UInt32 len = (static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]);
// use a fixed size buffer if its big enough
const bool useFixed = (len <= sizeof(buffer));
// allocate a buffer to read the data
UInt8* sBuffer = buffer;
if (!useFixed) {
sBuffer = new UInt8[len];
}
// read the data
try {
read(stream, sBuffer, len);
}
catch (...) {
if (!useFixed) {
delete[] sBuffer;
}
throw;
}
LOG((CLOG_DEBUG2 "readf: read %d byte string", len));
// save the data
String* dst = va_arg(args, String*);
dst->assign((const char*)sBuffer, len);
// release the buffer
if (!useFixed) {
delete[] sBuffer;
}
break;
}
case '%':
assert(len == 0);
break;
default:
assert(0 && "invalid format specifier");
}
// next format character
++fmt;
}
else {
// read next character
char buffer[1];
read(stream, buffer, 1);
// verify match
if (buffer[0] != *fmt) {
LOG((CLOG_DEBUG2 "readf: format mismatch: %c vs %c", *fmt, buffer[0]));
throw XIOReadMismatch();
}
// next format character
++fmt;
}
}
}
UInt32
ProtocolUtil::getLength(const char* fmt, va_list args)
{
UInt32 n = 0;
while (*fmt) {
if (*fmt == '%') {
// format specifier. determine argument size.
++fmt;
UInt32 len = eatLength(&fmt);
switch (*fmt) {
case 'i':
assert(len == 1 || len == 2 || len == 4);
(void)va_arg(args, UInt32);
break;
case 'I':
assert(len == 1 || len == 2 || len == 4);
switch (len) {
case 1:
len = (UInt32)(va_arg(args, std::vector<UInt8>*))->size() + 4;
break;
case 2:
len = 2 * (UInt32)(va_arg(args, std::vector<UInt16>*))->size() + 4;
break;
case 4:
len = 4 * (UInt32)(va_arg(args, std::vector<UInt32>*))->size() + 4;
break;
}
break;
case 's':
assert(len == 0);
len = (UInt32)(va_arg(args, String*))->size() + 4;
(void)va_arg(args, UInt8*);
break;
case 'S':
assert(len == 0);
len = va_arg(args, UInt32) + 4;
(void)va_arg(args, UInt8*);
break;
case '%':
assert(len == 0);
len = 1;
break;
default:
assert(0 && "invalid format specifier");
}
// accumulate size
n += len;
++fmt;
}
else {
// regular character
++n;
++fmt;
}
}
return n;
}
void
ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
{
UInt8* dst = static_cast<UInt8*>(buffer);
while (*fmt) {
if (*fmt == '%') {
// format specifier. determine argument size.
++fmt;
UInt32 len = eatLength(&fmt);
switch (*fmt) {
case 'i': {
const UInt32 v = va_arg(args, UInt32);
switch (len) {
case 1:
// 1 byte integer
*dst++ = static_cast<UInt8>(v & 0xff);
break;
case 2:
// 2 byte integer
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
break;
case 4:
// 4 byte integer
*dst++ = static_cast<UInt8>((v >> 24) & 0xff);
*dst++ = static_cast<UInt8>((v >> 16) & 0xff);
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
break;
default:
assert(0 && "invalid integer format length");
return;
}
break;
}
case 'I': {
switch (len) {
case 1: {
// 1 byte integers
const std::vector<UInt8>* list =
va_arg(args, const std::vector<UInt8>*);
const UInt32 n = (UInt32)list->size();
*dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff);
*dst++ = static_cast<UInt8>( n & 0xff);
for (UInt32 i = 0; i < n; ++i) {
*dst++ = (*list)[i];
}
break;
}
case 2: {
// 2 byte integers
const std::vector<UInt16>* list =
va_arg(args, const std::vector<UInt16>*);
const UInt32 n = (UInt32)list->size();
*dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff);
*dst++ = static_cast<UInt8>( n & 0xff);
for (UInt32 i = 0; i < n; ++i) {
const UInt16 v = (*list)[i];
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
}
break;
}
case 4: {
// 4 byte integers
const std::vector<UInt32>* list =
va_arg(args, const std::vector<UInt32>*);
const UInt32 n = (UInt32)list->size();
*dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff);
*dst++ = static_cast<UInt8>( n & 0xff);
for (UInt32 i = 0; i < n; ++i) {
const UInt32 v = (*list)[i];
*dst++ = static_cast<UInt8>((v >> 24) & 0xff);
*dst++ = static_cast<UInt8>((v >> 16) & 0xff);
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
}
break;
}
default:
assert(0 && "invalid integer vector format length");
return;
}
break;
}
case 's': {
assert(len == 0);
const String* src = va_arg(args, String*);
const UInt32 len = (src != NULL) ? (UInt32)src->size() : 0;
*dst++ = static_cast<UInt8>((len >> 24) & 0xff);
*dst++ = static_cast<UInt8>((len >> 16) & 0xff);
*dst++ = static_cast<UInt8>((len >> 8) & 0xff);
*dst++ = static_cast<UInt8>( len & 0xff);
if (len != 0) {
memcpy(dst, src->data(), len);
dst += len;
}
break;
}
case 'S': {
assert(len == 0);
const UInt32 len = va_arg(args, UInt32);
const UInt8* src = va_arg(args, UInt8*);
*dst++ = static_cast<UInt8>((len >> 24) & 0xff);
*dst++ = static_cast<UInt8>((len >> 16) & 0xff);
*dst++ = static_cast<UInt8>((len >> 8) & 0xff);
*dst++ = static_cast<UInt8>( len & 0xff);
memcpy(dst, src, len);
dst += len;
break;
}
case '%':
assert(len == 0);
*dst++ = '%';
break;
default:
assert(0 && "invalid format specifier");
}
// next format character
++fmt;
}
else {
// copy regular character
*dst++ = *fmt++;
}
}
}
UInt32
ProtocolUtil::eatLength(const char** pfmt)
{
const char* fmt = *pfmt;
UInt32 n = 0;
for (;;) {
UInt32 d;
switch (*fmt) {
case '0': d = 0; break;
case '1': d = 1; break;
case '2': d = 2; break;
case '3': d = 3; break;
case '4': d = 4; break;
case '5': d = 5; break;
case '6': d = 6; break;
case '7': d = 7; break;
case '8': d = 8; break;
case '9': d = 9; break;
default: *pfmt = fmt; return n;
}
n = 10 * n + d;
++fmt;
}
}
void
ProtocolUtil::read(synergy::IStream* stream, void* vbuffer, UInt32 count)
{
assert(stream != NULL);
assert(vbuffer != NULL);
UInt8* buffer = static_cast<UInt8*>(vbuffer);
while (count > 0) {
// read more
UInt32 n = stream->read(buffer, count);
// bail if stream has hungup
if (n == 0) {
LOG((CLOG_DEBUG2 "unexpected disconnect in readf(), %d bytes left", count));
throw XIOEndOfStream();
}
// prepare for next read
buffer += n;
count -= n;
}
}
//
// XIOReadMismatch
//
String
XIOReadMismatch::getWhat() const throw()
{
return format("XIOReadMismatch", "ProtocolUtil::readf() mismatch");
}
| ./CrossVul/dataset_final_sorted/CWE-755/cpp/bad_4096_0 |
crossvul-cpp_data_good_4096_0 | /*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "synergy/ProtocolUtil.h"
#include "io/IStream.h"
#include "base/Log.h"
#include "common/stdvector.h"
#include <cctype>
#include <cstring>
//
// ProtocolUtil
//
void
ProtocolUtil::writef(synergy::IStream* stream, const char* fmt, ...)
{
assert(stream != NULL);
assert(fmt != NULL);
LOG((CLOG_DEBUG2 "writef(%s)", fmt));
va_list args;
va_start(args, fmt);
UInt32 size = getLength(fmt, args);
va_end(args);
va_start(args, fmt);
vwritef(stream, fmt, size, args);
va_end(args);
}
bool
ProtocolUtil::readf(synergy::IStream* stream, const char* fmt, ...)
{
assert(stream != NULL);
assert(fmt != NULL);
LOG((CLOG_DEBUG2 "readf(%s)", fmt));
bool result;
va_list args;
va_start(args, fmt);
try {
vreadf(stream, fmt, args);
result = true;
}
catch (XIO&) {
result = false;
}
catch (std::bad_alloc & exception) {
result = false;
}
va_end(args);
return result;
}
void
ProtocolUtil::vwritef(synergy::IStream* stream,
const char* fmt, UInt32 size, va_list args)
{
assert(stream != NULL);
assert(fmt != NULL);
// done if nothing to write
if (size == 0) {
return;
}
// fill buffer
UInt8* buffer = new UInt8[size];
writef(buffer, fmt, args);
try {
// write buffer
stream->write(buffer, size);
LOG((CLOG_DEBUG2 "wrote %d bytes", size));
delete[] buffer;
}
catch (XBase&) {
delete[] buffer;
throw;
}
}
void
ProtocolUtil::vreadf(synergy::IStream* stream, const char* fmt, va_list args)
{
assert(stream != NULL);
assert(fmt != NULL);
// begin scanning
while (*fmt) {
if (*fmt == '%') {
// format specifier. determine argument size.
++fmt;
UInt32 len = eatLength(&fmt);
switch (*fmt) {
case 'i': {
// check for valid length
assert(len == 1 || len == 2 || len == 4);
// read the data
UInt8 buffer[4];
read(stream, buffer, len);
// convert it
void* v = va_arg(args, void*);
switch (len) {
case 1:
// 1 byte integer
*static_cast<UInt8*>(v) = buffer[0];
LOG((CLOG_DEBUG2 "readf: read %d byte integer: %d (0x%x)", len, *static_cast<UInt8*>(v), *static_cast<UInt8*>(v)));
break;
case 2:
// 2 byte integer
*static_cast<UInt16*>(v) =
static_cast<UInt16>(
(static_cast<UInt16>(buffer[0]) << 8) |
static_cast<UInt16>(buffer[1]));
LOG((CLOG_DEBUG2 "readf: read %d byte integer: %d (0x%x)", len, *static_cast<UInt16*>(v), *static_cast<UInt16*>(v)));
break;
case 4:
// 4 byte integer
*static_cast<UInt32*>(v) =
(static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]);
LOG((CLOG_DEBUG2 "readf: read %d byte integer: %d (0x%x)", len, *static_cast<UInt32*>(v), *static_cast<UInt32*>(v)));
break;
}
break;
}
case 'I': {
// check for valid length
assert(len == 1 || len == 2 || len == 4);
// read the vector length
UInt8 buffer[4];
read(stream, buffer, 4);
UInt32 n = (static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]);
// convert it
void* v = va_arg(args, void*);
switch (len) {
case 1:
// 1 byte integer
for (UInt32 i = 0; i < n; ++i) {
read(stream, buffer, 1);
static_cast<std::vector<UInt8>*>(v)->push_back(
buffer[0]);
LOG((CLOG_DEBUG2 "readf: read %d byte integer[%d]: %d (0x%x)", len, i, static_cast<std::vector<UInt8>*>(v)->back(), static_cast<std::vector<UInt8>*>(v)->back()));
}
break;
case 2:
// 2 byte integer
for (UInt32 i = 0; i < n; ++i) {
read(stream, buffer, 2);
static_cast<std::vector<UInt16>*>(v)->push_back(
static_cast<UInt16>(
(static_cast<UInt16>(buffer[0]) << 8) |
static_cast<UInt16>(buffer[1])));
LOG((CLOG_DEBUG2 "readf: read %d byte integer[%d]: %d (0x%x)", len, i, static_cast<std::vector<UInt16>*>(v)->back(), static_cast<std::vector<UInt16>*>(v)->back()));
}
break;
case 4:
// 4 byte integer
for (UInt32 i = 0; i < n; ++i) {
read(stream, buffer, 4);
static_cast<std::vector<UInt32>*>(v)->push_back(
(static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]));
LOG((CLOG_DEBUG2 "readf: read %d byte integer[%d]: %d (0x%x)", len, i, static_cast<std::vector<UInt32>*>(v)->back(), static_cast<std::vector<UInt32>*>(v)->back()));
}
break;
}
break;
}
case 's': {
assert(len == 0);
// read the string length
UInt8 buffer[128];
read(stream, buffer, 4);
UInt32 len = (static_cast<UInt32>(buffer[0]) << 24) |
(static_cast<UInt32>(buffer[1]) << 16) |
(static_cast<UInt32>(buffer[2]) << 8) |
static_cast<UInt32>(buffer[3]);
// use a fixed size buffer if its big enough
const bool useFixed = (len <= sizeof(buffer));
// allocate a buffer to read the data
UInt8* sBuffer = buffer;
if (!useFixed) {
try{
sBuffer = new UInt8[len];
}
catch (std::bad_alloc & exception) {
// Added try catch due to GHSA-chfm-333q-gfpp
LOG((CLOG_ERR "ALLOC: Unable to allocate memory %d bytes", len));
LOG((CLOG_DEBUG "bad_alloc detected: Do you have enough free memory?"));
throw exception;
}
}
// read the data
try {
read(stream, sBuffer, len);
}
catch (...) {
if (!useFixed) {
delete[] sBuffer;
}
throw;
}
LOG((CLOG_DEBUG2 "readf: read %d byte string", len));
// save the data
String* dst = va_arg(args, String*);
dst->assign((const char*)sBuffer, len);
// release the buffer
if (!useFixed) {
delete[] sBuffer;
}
break;
}
case '%':
assert(len == 0);
break;
default:
assert(0 && "invalid format specifier");
}
// next format character
++fmt;
}
else {
// read next character
char buffer[1];
read(stream, buffer, 1);
// verify match
if (buffer[0] != *fmt) {
LOG((CLOG_DEBUG2 "readf: format mismatch: %c vs %c", *fmt, buffer[0]));
throw XIOReadMismatch();
}
// next format character
++fmt;
}
}
}
UInt32
ProtocolUtil::getLength(const char* fmt, va_list args)
{
UInt32 n = 0;
while (*fmt) {
if (*fmt == '%') {
// format specifier. determine argument size.
++fmt;
UInt32 len = eatLength(&fmt);
switch (*fmt) {
case 'i':
assert(len == 1 || len == 2 || len == 4);
(void)va_arg(args, UInt32);
break;
case 'I':
assert(len == 1 || len == 2 || len == 4);
switch (len) {
case 1:
len = (UInt32)(va_arg(args, std::vector<UInt8>*))->size() + 4;
break;
case 2:
len = 2 * (UInt32)(va_arg(args, std::vector<UInt16>*))->size() + 4;
break;
case 4:
len = 4 * (UInt32)(va_arg(args, std::vector<UInt32>*))->size() + 4;
break;
}
break;
case 's':
assert(len == 0);
len = (UInt32)(va_arg(args, String*))->size() + 4;
(void)va_arg(args, UInt8*);
break;
case 'S':
assert(len == 0);
len = va_arg(args, UInt32) + 4;
(void)va_arg(args, UInt8*);
break;
case '%':
assert(len == 0);
len = 1;
break;
default:
assert(0 && "invalid format specifier");
}
// accumulate size
n += len;
++fmt;
}
else {
// regular character
++n;
++fmt;
}
}
return n;
}
void
ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
{
UInt8* dst = static_cast<UInt8*>(buffer);
while (*fmt) {
if (*fmt == '%') {
// format specifier. determine argument size.
++fmt;
UInt32 len = eatLength(&fmt);
switch (*fmt) {
case 'i': {
const UInt32 v = va_arg(args, UInt32);
switch (len) {
case 1:
// 1 byte integer
*dst++ = static_cast<UInt8>(v & 0xff);
break;
case 2:
// 2 byte integer
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
break;
case 4:
// 4 byte integer
*dst++ = static_cast<UInt8>((v >> 24) & 0xff);
*dst++ = static_cast<UInt8>((v >> 16) & 0xff);
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
break;
default:
assert(0 && "invalid integer format length");
return;
}
break;
}
case 'I': {
switch (len) {
case 1: {
// 1 byte integers
const std::vector<UInt8>* list =
va_arg(args, const std::vector<UInt8>*);
const UInt32 n = (UInt32)list->size();
*dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff);
*dst++ = static_cast<UInt8>( n & 0xff);
for (UInt32 i = 0; i < n; ++i) {
*dst++ = (*list)[i];
}
break;
}
case 2: {
// 2 byte integers
const std::vector<UInt16>* list =
va_arg(args, const std::vector<UInt16>*);
const UInt32 n = (UInt32)list->size();
*dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff);
*dst++ = static_cast<UInt8>( n & 0xff);
for (UInt32 i = 0; i < n; ++i) {
const UInt16 v = (*list)[i];
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
}
break;
}
case 4: {
// 4 byte integers
const std::vector<UInt32>* list =
va_arg(args, const std::vector<UInt32>*);
const UInt32 n = (UInt32)list->size();
*dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff);
*dst++ = static_cast<UInt8>( n & 0xff);
for (UInt32 i = 0; i < n; ++i) {
const UInt32 v = (*list)[i];
*dst++ = static_cast<UInt8>((v >> 24) & 0xff);
*dst++ = static_cast<UInt8>((v >> 16) & 0xff);
*dst++ = static_cast<UInt8>((v >> 8) & 0xff);
*dst++ = static_cast<UInt8>( v & 0xff);
}
break;
}
default:
assert(0 && "invalid integer vector format length");
return;
}
break;
}
case 's': {
assert(len == 0);
const String* src = va_arg(args, String*);
const UInt32 len = (src != NULL) ? (UInt32)src->size() : 0;
*dst++ = static_cast<UInt8>((len >> 24) & 0xff);
*dst++ = static_cast<UInt8>((len >> 16) & 0xff);
*dst++ = static_cast<UInt8>((len >> 8) & 0xff);
*dst++ = static_cast<UInt8>( len & 0xff);
if (len != 0) {
memcpy(dst, src->data(), len);
dst += len;
}
break;
}
case 'S': {
assert(len == 0);
const UInt32 len = va_arg(args, UInt32);
const UInt8* src = va_arg(args, UInt8*);
*dst++ = static_cast<UInt8>((len >> 24) & 0xff);
*dst++ = static_cast<UInt8>((len >> 16) & 0xff);
*dst++ = static_cast<UInt8>((len >> 8) & 0xff);
*dst++ = static_cast<UInt8>( len & 0xff);
memcpy(dst, src, len);
dst += len;
break;
}
case '%':
assert(len == 0);
*dst++ = '%';
break;
default:
assert(0 && "invalid format specifier");
}
// next format character
++fmt;
}
else {
// copy regular character
*dst++ = *fmt++;
}
}
}
UInt32
ProtocolUtil::eatLength(const char** pfmt)
{
const char* fmt = *pfmt;
UInt32 n = 0;
for (;;) {
UInt32 d;
switch (*fmt) {
case '0': d = 0; break;
case '1': d = 1; break;
case '2': d = 2; break;
case '3': d = 3; break;
case '4': d = 4; break;
case '5': d = 5; break;
case '6': d = 6; break;
case '7': d = 7; break;
case '8': d = 8; break;
case '9': d = 9; break;
default: *pfmt = fmt; return n;
}
n = 10 * n + d;
++fmt;
}
}
void
ProtocolUtil::read(synergy::IStream* stream, void* vbuffer, UInt32 count)
{
assert(stream != NULL);
assert(vbuffer != NULL);
UInt8* buffer = static_cast<UInt8*>(vbuffer);
while (count > 0) {
// read more
UInt32 n = stream->read(buffer, count);
// bail if stream has hungup
if (n == 0) {
LOG((CLOG_DEBUG2 "unexpected disconnect in readf(), %d bytes left", count));
throw XIOEndOfStream();
}
// prepare for next read
buffer += n;
count -= n;
}
}
//
// XIOReadMismatch
//
String
XIOReadMismatch::getWhat() const throw()
{
return format("XIOReadMismatch", "ProtocolUtil::readf() mismatch");
}
| ./CrossVul/dataset_final_sorted/CWE-755/cpp/good_4096_0 |
crossvul-cpp_data_bad_1129_0 | #include "Note.hpp"
#include "prf.h"
#include "crypto/sha256.h"
#include "random.h"
#include "version.h"
#include "streams.h"
#include "zcash/util.h"
#include "librustzcash.h"
using namespace libzcash;
SproutNote::SproutNote() {
a_pk = random_uint256();
rho = random_uint256();
r = random_uint256();
}
uint256 SproutNote::cm() const {
unsigned char discriminant = 0xb0;
CSHA256 hasher;
hasher.Write(&discriminant, 1);
hasher.Write(a_pk.begin(), 32);
auto value_vec = convertIntToVectorLE(value_);
hasher.Write(&value_vec[0], value_vec.size());
hasher.Write(rho.begin(), 32);
hasher.Write(r.begin(), 32);
uint256 result;
hasher.Finalize(result.begin());
return result;
}
uint256 SproutNote::nullifier(const SproutSpendingKey& a_sk) const {
return PRF_nf(a_sk, rho);
}
// Construct and populate Sapling note for a given payment address and value.
SaplingNote::SaplingNote(const SaplingPaymentAddress& address, const uint64_t value) : BaseNote(value) {
d = address.d;
pk_d = address.pk_d;
librustzcash_sapling_generate_r(r.begin());
}
// Call librustzcash to compute the commitment
boost::optional<uint256> SaplingNote::cm() const {
uint256 result;
if (!librustzcash_sapling_compute_cm(
d.data(),
pk_d.begin(),
value(),
r.begin(),
result.begin()
))
{
return boost::none;
}
return result;
}
// Call librustzcash to compute the nullifier
boost::optional<uint256> SaplingNote::nullifier(const SaplingFullViewingKey& vk, const uint64_t position) const
{
auto ak = vk.ak;
auto nk = vk.nk;
uint256 result;
if (!librustzcash_sapling_compute_nf(
d.data(),
pk_d.begin(),
value(),
r.begin(),
ak.begin(),
nk.begin(),
position,
result.begin()
))
{
return boost::none;
}
return result;
}
SproutNotePlaintext::SproutNotePlaintext(
const SproutNote& note,
std::array<unsigned char, ZC_MEMO_SIZE> memo) : BaseNotePlaintext(note, memo)
{
rho = note.rho;
r = note.r;
}
SproutNote SproutNotePlaintext::note(const SproutPaymentAddress& addr) const
{
return SproutNote(addr.a_pk, value_, rho, r);
}
SproutNotePlaintext SproutNotePlaintext::decrypt(const ZCNoteDecryption& decryptor,
const ZCNoteDecryption::Ciphertext& ciphertext,
const uint256& ephemeralKey,
const uint256& h_sig,
unsigned char nonce
)
{
auto plaintext = decryptor.decrypt(ciphertext, ephemeralKey, h_sig, nonce);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << plaintext;
SproutNotePlaintext ret;
ss >> ret;
assert(ss.size() == 0);
return ret;
}
ZCNoteEncryption::Ciphertext SproutNotePlaintext::encrypt(ZCNoteEncryption& encryptor,
const uint256& pk_enc
) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << (*this);
ZCNoteEncryption::Plaintext pt;
assert(pt.size() == ss.size());
memcpy(&pt[0], &ss[0], pt.size());
return encryptor.encrypt(pk_enc, pt);
}
// Construct and populate SaplingNotePlaintext for a given note and memo.
SaplingNotePlaintext::SaplingNotePlaintext(
const SaplingNote& note,
std::array<unsigned char, ZC_MEMO_SIZE> memo) : BaseNotePlaintext(note, memo)
{
d = note.d;
rcm = note.r;
}
boost::optional<SaplingNote> SaplingNotePlaintext::note(const SaplingIncomingViewingKey& ivk) const
{
auto addr = ivk.address(d);
if (addr) {
return SaplingNote(d, addr.get().pk_d, value_, rcm);
} else {
return boost::none;
}
}
boost::optional<SaplingOutgoingPlaintext> SaplingOutgoingPlaintext::decrypt(
const SaplingOutCiphertext &ciphertext,
const uint256& ovk,
const uint256& cv,
const uint256& cm,
const uint256& epk
)
{
auto pt = AttemptSaplingOutDecryption(ciphertext, ovk, cv, cm, epk);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
SaplingOutgoingPlaintext ret;
ss >> ret;
assert(ss.size() == 0);
return ret;
}
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &ivk,
const uint256 &epk,
const uint256 &cmu
)
{
auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
SaplingNotePlaintext ret;
ss >> ret;
assert(ss.size() == 0);
uint256 pk_d;
if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {
return boost::none;
}
uint256 cmu_expected;
if (!librustzcash_sapling_compute_cm(
ret.d.data(),
pk_d.begin(),
ret.value(),
ret.rcm.begin(),
cmu_expected.begin()
))
{
return boost::none;
}
if (cmu_expected != cmu) {
return boost::none;
}
return ret;
}
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &epk,
const uint256 &esk,
const uint256 &pk_d,
const uint256 &cmu
)
{
auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
SaplingNotePlaintext ret;
ss >> ret;
uint256 cmu_expected;
if (!librustzcash_sapling_compute_cm(
ret.d.data(),
pk_d.begin(),
ret.value(),
ret.rcm.begin(),
cmu_expected.begin()
))
{
return boost::none;
}
if (cmu_expected != cmu) {
return boost::none;
}
assert(ss.size() == 0);
return ret;
}
boost::optional<SaplingNotePlaintextEncryptionResult> SaplingNotePlaintext::encrypt(const uint256& pk_d) const
{
// Get the encryptor
auto sne = SaplingNoteEncryption::FromDiversifier(d);
if (!sne) {
return boost::none;
}
auto enc = sne.get();
// Create the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << (*this);
SaplingEncPlaintext pt;
assert(pt.size() == ss.size());
memcpy(&pt[0], &ss[0], pt.size());
// Encrypt the plaintext
auto encciphertext = enc.encrypt_to_recipient(pk_d, pt);
if (!encciphertext) {
return boost::none;
}
return SaplingNotePlaintextEncryptionResult(encciphertext.get(), enc);
}
SaplingOutCiphertext SaplingOutgoingPlaintext::encrypt(
const uint256& ovk,
const uint256& cv,
const uint256& cm,
SaplingNoteEncryption& enc
) const
{
// Create the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << (*this);
SaplingOutPlaintext pt;
assert(pt.size() == ss.size());
memcpy(&pt[0], &ss[0], pt.size());
return enc.encrypt_to_ourselves(ovk, cv, cm, pt);
}
| ./CrossVul/dataset_final_sorted/CWE-755/cpp/bad_1129_0 |
crossvul-cpp_data_good_1129_0 | #include "Note.hpp"
#include "prf.h"
#include "crypto/sha256.h"
#include "random.h"
#include "version.h"
#include "streams.h"
#include "zcash/util.h"
#include "librustzcash.h"
using namespace libzcash;
SproutNote::SproutNote() {
a_pk = random_uint256();
rho = random_uint256();
r = random_uint256();
}
uint256 SproutNote::cm() const {
unsigned char discriminant = 0xb0;
CSHA256 hasher;
hasher.Write(&discriminant, 1);
hasher.Write(a_pk.begin(), 32);
auto value_vec = convertIntToVectorLE(value_);
hasher.Write(&value_vec[0], value_vec.size());
hasher.Write(rho.begin(), 32);
hasher.Write(r.begin(), 32);
uint256 result;
hasher.Finalize(result.begin());
return result;
}
uint256 SproutNote::nullifier(const SproutSpendingKey& a_sk) const {
return PRF_nf(a_sk, rho);
}
// Construct and populate Sapling note for a given payment address and value.
SaplingNote::SaplingNote(const SaplingPaymentAddress& address, const uint64_t value) : BaseNote(value) {
d = address.d;
pk_d = address.pk_d;
librustzcash_sapling_generate_r(r.begin());
}
// Call librustzcash to compute the commitment
boost::optional<uint256> SaplingNote::cm() const {
uint256 result;
if (!librustzcash_sapling_compute_cm(
d.data(),
pk_d.begin(),
value(),
r.begin(),
result.begin()
))
{
return boost::none;
}
return result;
}
// Call librustzcash to compute the nullifier
boost::optional<uint256> SaplingNote::nullifier(const SaplingFullViewingKey& vk, const uint64_t position) const
{
auto ak = vk.ak;
auto nk = vk.nk;
uint256 result;
if (!librustzcash_sapling_compute_nf(
d.data(),
pk_d.begin(),
value(),
r.begin(),
ak.begin(),
nk.begin(),
position,
result.begin()
))
{
return boost::none;
}
return result;
}
SproutNotePlaintext::SproutNotePlaintext(
const SproutNote& note,
std::array<unsigned char, ZC_MEMO_SIZE> memo) : BaseNotePlaintext(note, memo)
{
rho = note.rho;
r = note.r;
}
SproutNote SproutNotePlaintext::note(const SproutPaymentAddress& addr) const
{
return SproutNote(addr.a_pk, value_, rho, r);
}
SproutNotePlaintext SproutNotePlaintext::decrypt(const ZCNoteDecryption& decryptor,
const ZCNoteDecryption::Ciphertext& ciphertext,
const uint256& ephemeralKey,
const uint256& h_sig,
unsigned char nonce
)
{
auto plaintext = decryptor.decrypt(ciphertext, ephemeralKey, h_sig, nonce);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << plaintext;
SproutNotePlaintext ret;
ss >> ret;
assert(ss.size() == 0);
return ret;
}
ZCNoteEncryption::Ciphertext SproutNotePlaintext::encrypt(ZCNoteEncryption& encryptor,
const uint256& pk_enc
) const
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << (*this);
ZCNoteEncryption::Plaintext pt;
assert(pt.size() == ss.size());
memcpy(&pt[0], &ss[0], pt.size());
return encryptor.encrypt(pk_enc, pt);
}
// Construct and populate SaplingNotePlaintext for a given note and memo.
SaplingNotePlaintext::SaplingNotePlaintext(
const SaplingNote& note,
std::array<unsigned char, ZC_MEMO_SIZE> memo) : BaseNotePlaintext(note, memo)
{
d = note.d;
rcm = note.r;
}
boost::optional<SaplingNote> SaplingNotePlaintext::note(const SaplingIncomingViewingKey& ivk) const
{
auto addr = ivk.address(d);
if (addr) {
return SaplingNote(d, addr.get().pk_d, value_, rcm);
} else {
return boost::none;
}
}
boost::optional<SaplingOutgoingPlaintext> SaplingOutgoingPlaintext::decrypt(
const SaplingOutCiphertext &ciphertext,
const uint256& ovk,
const uint256& cv,
const uint256& cm,
const uint256& epk
)
{
auto pt = AttemptSaplingOutDecryption(ciphertext, ovk, cv, cm, epk);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
try {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
SaplingOutgoingPlaintext ret;
ss >> ret;
assert(ss.size() == 0);
return ret;
} catch (const boost::thread_interrupted&) {
throw;
} catch (...) {
return boost::none;
}
}
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &ivk,
const uint256 &epk,
const uint256 &cmu
)
{
auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
SaplingNotePlaintext ret;
try {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
ss >> ret;
assert(ss.size() == 0);
} catch (const boost::thread_interrupted&) {
throw;
} catch (...) {
return boost::none;
}
uint256 pk_d;
if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {
return boost::none;
}
uint256 cmu_expected;
if (!librustzcash_sapling_compute_cm(
ret.d.data(),
pk_d.begin(),
ret.value(),
ret.rcm.begin(),
cmu_expected.begin()
))
{
return boost::none;
}
if (cmu_expected != cmu) {
return boost::none;
}
return ret;
}
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
const SaplingEncCiphertext &ciphertext,
const uint256 &epk,
const uint256 &esk,
const uint256 &pk_d,
const uint256 &cmu
)
{
auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);
if (!pt) {
return boost::none;
}
// Deserialize from the plaintext
SaplingNotePlaintext ret;
try {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pt.get();
ss >> ret;
assert(ss.size() == 0);
} catch (const boost::thread_interrupted&) {
throw;
} catch (...) {
return boost::none;
}
uint256 cmu_expected;
if (!librustzcash_sapling_compute_cm(
ret.d.data(),
pk_d.begin(),
ret.value(),
ret.rcm.begin(),
cmu_expected.begin()
))
{
return boost::none;
}
if (cmu_expected != cmu) {
return boost::none;
}
return ret;
}
boost::optional<SaplingNotePlaintextEncryptionResult> SaplingNotePlaintext::encrypt(const uint256& pk_d) const
{
// Get the encryptor
auto sne = SaplingNoteEncryption::FromDiversifier(d);
if (!sne) {
return boost::none;
}
auto enc = sne.get();
// Create the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << (*this);
SaplingEncPlaintext pt;
assert(pt.size() == ss.size());
memcpy(&pt[0], &ss[0], pt.size());
// Encrypt the plaintext
auto encciphertext = enc.encrypt_to_recipient(pk_d, pt);
if (!encciphertext) {
return boost::none;
}
return SaplingNotePlaintextEncryptionResult(encciphertext.get(), enc);
}
SaplingOutCiphertext SaplingOutgoingPlaintext::encrypt(
const uint256& ovk,
const uint256& cv,
const uint256& cm,
SaplingNoteEncryption& enc
) const
{
// Create the plaintext
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << (*this);
SaplingOutPlaintext pt;
assert(pt.size() == ss.size());
memcpy(&pt[0], &ss[0], pt.size());
return enc.encrypt_to_ourselves(ovk, cv, cm, pt);
}
| ./CrossVul/dataset_final_sorted/CWE-755/cpp/good_1129_0 |
crossvul-cpp_data_good_2582_0 | /******************************************************************************
*
* Module Name: nsutils - Utilities for accessing ACPI namespace, accessing
* parents and siblings and Scope manipulation
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2017, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "amlcode.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nsutils")
/* Local prototypes */
#ifdef ACPI_OBSOLETE_FUNCTIONS
acpi_name acpi_ns_find_parent_name(struct acpi_namespace_node *node_to_search);
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ns_print_node_pathname
*
* PARAMETERS: node - Object
* message - Prefix message
*
* DESCRIPTION: Print an object's full namespace pathname
* Manages allocation/freeing of a pathname buffer
*
******************************************************************************/
void
acpi_ns_print_node_pathname(struct acpi_namespace_node *node,
const char *message)
{
struct acpi_buffer buffer;
acpi_status status;
if (!node) {
acpi_os_printf("[NULL NAME]");
return;
}
/* Convert handle to full pathname and print it (with supplied message) */
buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER;
status = acpi_ns_handle_to_pathname(node, &buffer, TRUE);
if (ACPI_SUCCESS(status)) {
if (message) {
acpi_os_printf("%s ", message);
}
acpi_os_printf("[%s] (Node %p)", (char *)buffer.pointer, node);
ACPI_FREE(buffer.pointer);
}
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_type
*
* PARAMETERS: node - Parent Node to be examined
*
* RETURN: Type field from Node whose handle is passed
*
* DESCRIPTION: Return the type of a Namespace node
*
******************************************************************************/
acpi_object_type acpi_ns_get_type(struct acpi_namespace_node * node)
{
ACPI_FUNCTION_TRACE(ns_get_type);
if (!node) {
ACPI_WARNING((AE_INFO, "Null Node parameter"));
return_UINT8(ACPI_TYPE_ANY);
}
return_UINT8(node->type);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_local
*
* PARAMETERS: type - A namespace object type
*
* RETURN: LOCAL if names must be found locally in objects of the
* passed type, 0 if enclosing scopes should be searched
*
* DESCRIPTION: Returns scope rule for the given object type.
*
******************************************************************************/
u32 acpi_ns_local(acpi_object_type type)
{
ACPI_FUNCTION_TRACE(ns_local);
if (!acpi_ut_valid_object_type(type)) {
/* Type code out of range */
ACPI_WARNING((AE_INFO, "Invalid Object Type 0x%X", type));
return_UINT32(ACPI_NS_NORMAL);
}
return_UINT32(acpi_gbl_ns_properties[type] & ACPI_NS_LOCAL);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_internal_name_length
*
* PARAMETERS: info - Info struct initialized with the
* external name pointer.
*
* RETURN: None
*
* DESCRIPTION: Calculate the length of the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
void acpi_ns_get_internal_name_length(struct acpi_namestring_info *info)
{
const char *next_external_char;
u32 i;
ACPI_FUNCTION_ENTRY();
next_external_char = info->external_name;
info->num_carats = 0;
info->num_segments = 0;
info->fully_qualified = FALSE;
/*
* For the internal name, the required length is 4 bytes per segment,
* plus 1 each for root_prefix, multi_name_prefix_op, segment count,
* trailing null (which is not really needed, but no there's harm in
* putting it there)
*
* strlen() + 1 covers the first name_seg, which has no path separator
*/
if (ACPI_IS_ROOT_PREFIX(*next_external_char)) {
info->fully_qualified = TRUE;
next_external_char++;
/* Skip redundant root_prefix, like \\_SB.PCI0.SBRG.EC0 */
while (ACPI_IS_ROOT_PREFIX(*next_external_char)) {
next_external_char++;
}
} else {
/* Handle Carat prefixes */
while (ACPI_IS_PARENT_PREFIX(*next_external_char)) {
info->num_carats++;
next_external_char++;
}
}
/*
* Determine the number of ACPI name "segments" by counting the number of
* path separators within the string. Start with one segment since the
* segment count is [(# separators) + 1], and zero separators is ok.
*/
if (*next_external_char) {
info->num_segments = 1;
for (i = 0; next_external_char[i]; i++) {
if (ACPI_IS_PATH_SEPARATOR(next_external_char[i])) {
info->num_segments++;
}
}
}
info->length = (ACPI_NAME_SIZE * info->num_segments) +
4 + info->num_carats;
info->next_external_char = next_external_char;
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_build_internal_name
*
* PARAMETERS: info - Info struct fully initialized
*
* RETURN: Status
*
* DESCRIPTION: Construct the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
acpi_status acpi_ns_build_internal_name(struct acpi_namestring_info *info)
{
u32 num_segments = info->num_segments;
char *internal_name = info->internal_name;
const char *external_name = info->next_external_char;
char *result = NULL;
u32 i;
ACPI_FUNCTION_TRACE(ns_build_internal_name);
/* Setup the correct prefixes, counts, and pointers */
if (info->fully_qualified) {
internal_name[0] = AML_ROOT_PREFIX;
if (num_segments <= 1) {
result = &internal_name[1];
} else if (num_segments == 2) {
internal_name[1] = AML_DUAL_NAME_PREFIX;
result = &internal_name[2];
} else {
internal_name[1] = AML_MULTI_NAME_PREFIX_OP;
internal_name[2] = (char)num_segments;
result = &internal_name[3];
}
} else {
/*
* Not fully qualified.
* Handle Carats first, then append the name segments
*/
i = 0;
if (info->num_carats) {
for (i = 0; i < info->num_carats; i++) {
internal_name[i] = AML_PARENT_PREFIX;
}
}
if (num_segments <= 1) {
result = &internal_name[i];
} else if (num_segments == 2) {
internal_name[i] = AML_DUAL_NAME_PREFIX;
result = &internal_name[(acpi_size)i + 1];
} else {
internal_name[i] = AML_MULTI_NAME_PREFIX_OP;
internal_name[(acpi_size)i + 1] = (char)num_segments;
result = &internal_name[(acpi_size)i + 2];
}
}
/* Build the name (minus path separators) */
for (; num_segments; num_segments--) {
for (i = 0; i < ACPI_NAME_SIZE; i++) {
if (ACPI_IS_PATH_SEPARATOR(*external_name) ||
(*external_name == 0)) {
/* Pad the segment with underscore(s) if segment is short */
result[i] = '_';
} else {
/* Convert the character to uppercase and save it */
result[i] = (char)toupper((int)*external_name);
external_name++;
}
}
/* Now we must have a path separator, or the pathname is bad */
if (!ACPI_IS_PATH_SEPARATOR(*external_name) &&
(*external_name != 0)) {
return_ACPI_STATUS(AE_BAD_PATHNAME);
}
/* Move on the next segment */
external_name++;
result += ACPI_NAME_SIZE;
}
/* Terminate the string */
*result = 0;
if (info->fully_qualified) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Returning [%p] (abs) \"\\%s\"\n",
internal_name, internal_name));
} else {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Returning [%p] (rel) \"%s\"\n",
internal_name, internal_name));
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_internalize_name
*
* PARAMETERS: *external_name - External representation of name
* **Converted name - Where to return the resulting
* internal represention of the name
*
* RETURN: Status
*
* DESCRIPTION: Convert an external representation (e.g. "\_PR_.CPU0")
* to internal form (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
*
*******************************************************************************/
acpi_status
acpi_ns_internalize_name(const char *external_name, char **converted_name)
{
char *internal_name;
struct acpi_namestring_info info;
acpi_status status;
ACPI_FUNCTION_TRACE(ns_internalize_name);
if ((!external_name) || (*external_name == 0) || (!converted_name)) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Get the length of the new internal name */
info.external_name = external_name;
acpi_ns_get_internal_name_length(&info);
/* We need a segment to store the internal name */
internal_name = ACPI_ALLOCATE_ZEROED(info.length);
if (!internal_name) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Build the name */
info.internal_name = internal_name;
status = acpi_ns_build_internal_name(&info);
if (ACPI_FAILURE(status)) {
ACPI_FREE(internal_name);
return_ACPI_STATUS(status);
}
*converted_name = internal_name;
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_externalize_name
*
* PARAMETERS: internal_name_length - Lenth of the internal name below
* internal_name - Internal representation of name
* converted_name_length - Where the length is returned
* converted_name - Where the resulting external name
* is returned
*
* RETURN: Status
*
* DESCRIPTION: Convert internal name (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
* to its external (printable) form (e.g. "\_PR_.CPU0")
*
******************************************************************************/
acpi_status
acpi_ns_externalize_name(u32 internal_name_length,
const char *internal_name,
u32 * converted_name_length, char **converted_name)
{
u32 names_index = 0;
u32 num_segments = 0;
u32 required_length;
u32 prefix_length = 0;
u32 i = 0;
u32 j = 0;
ACPI_FUNCTION_TRACE(ns_externalize_name);
if (!internal_name_length || !internal_name || !converted_name) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Check for a prefix (one '\' | one or more '^') */
switch (internal_name[0]) {
case AML_ROOT_PREFIX:
prefix_length = 1;
break;
case AML_PARENT_PREFIX:
for (i = 0; i < internal_name_length; i++) {
if (ACPI_IS_PARENT_PREFIX(internal_name[i])) {
prefix_length = i + 1;
} else {
break;
}
}
if (i == internal_name_length) {
prefix_length = i;
}
break;
default:
break;
}
/*
* Check for object names. Note that there could be 0-255 of these
* 4-byte elements.
*/
if (prefix_length < internal_name_length) {
switch (internal_name[prefix_length]) {
case AML_MULTI_NAME_PREFIX_OP:
/* <count> 4-byte names */
names_index = prefix_length + 2;
num_segments = (u8)
internal_name[(acpi_size)prefix_length + 1];
break;
case AML_DUAL_NAME_PREFIX:
/* Two 4-byte names */
names_index = prefix_length + 1;
num_segments = 2;
break;
case 0:
/* null_name */
names_index = 0;
num_segments = 0;
break;
default:
/* one 4-byte name */
names_index = prefix_length;
num_segments = 1;
break;
}
}
/*
* Calculate the length of converted_name, which equals the length
* of the prefix, length of all object names, length of any required
* punctuation ('.') between object names, plus the NULL terminator.
*/
required_length = prefix_length + (4 * num_segments) +
((num_segments > 0) ? (num_segments - 1) : 0) + 1;
/*
* Check to see if we're still in bounds. If not, there's a problem
* with internal_name (invalid format).
*/
if (required_length > internal_name_length) {
ACPI_ERROR((AE_INFO, "Invalid internal name"));
return_ACPI_STATUS(AE_BAD_PATHNAME);
}
/* Build the converted_name */
*converted_name = ACPI_ALLOCATE_ZEROED(required_length);
if (!(*converted_name)) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
j = 0;
for (i = 0; i < prefix_length; i++) {
(*converted_name)[j++] = internal_name[i];
}
if (num_segments > 0) {
for (i = 0; i < num_segments; i++) {
if (i > 0) {
(*converted_name)[j++] = '.';
}
/* Copy and validate the 4-char name segment */
ACPI_MOVE_NAME(&(*converted_name)[j],
&internal_name[names_index]);
acpi_ut_repair_name(&(*converted_name)[j]);
j += ACPI_NAME_SIZE;
names_index += ACPI_NAME_SIZE;
}
}
if (converted_name_length) {
*converted_name_length = (u32) required_length;
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_validate_handle
*
* PARAMETERS: handle - Handle to be validated and typecast to a
* namespace node.
*
* RETURN: A pointer to a namespace node
*
* DESCRIPTION: Convert a namespace handle to a namespace node. Handles special
* cases for the root node.
*
* NOTE: Real integer handles would allow for more verification
* and keep all pointers within this subsystem - however this introduces
* more overhead and has not been necessary to this point. Drivers
* holding handles are typically notified before a node becomes invalid
* due to a table unload.
*
******************************************************************************/
struct acpi_namespace_node *acpi_ns_validate_handle(acpi_handle handle)
{
ACPI_FUNCTION_ENTRY();
/* Parameter validation */
if ((!handle) || (handle == ACPI_ROOT_OBJECT)) {
return (acpi_gbl_root_node);
}
/* We can at least attempt to verify the handle */
if (ACPI_GET_DESCRIPTOR_TYPE(handle) != ACPI_DESC_TYPE_NAMED) {
return (NULL);
}
return (ACPI_CAST_PTR(struct acpi_namespace_node, handle));
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_terminate
*
* PARAMETERS: none
*
* RETURN: none
*
* DESCRIPTION: free memory allocated for namespace and ACPI table storage.
*
******************************************************************************/
void acpi_ns_terminate(void)
{
acpi_status status;
union acpi_operand_object *prev;
union acpi_operand_object *next;
ACPI_FUNCTION_TRACE(ns_terminate);
/* Delete any module-level code blocks */
next = acpi_gbl_module_code_list;
while (next) {
prev = next;
next = next->method.mutex;
prev->method.mutex = NULL; /* Clear the Mutex (cheated) field */
acpi_ut_remove_reference(prev);
}
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
acpi_ns_delete_namespace_subtree(acpi_gbl_root_node);
/* Delete any objects attached to the root node */
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_VOID;
}
acpi_ns_delete_node(acpi_gbl_root_node);
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_opens_scope
*
* PARAMETERS: type - A valid namespace type
*
* RETURN: NEWSCOPE if the passed type "opens a name scope" according
* to the ACPI specification, else 0
*
******************************************************************************/
u32 acpi_ns_opens_scope(acpi_object_type type)
{
ACPI_FUNCTION_ENTRY();
if (type > ACPI_TYPE_LOCAL_MAX) {
/* type code out of range */
ACPI_WARNING((AE_INFO, "Invalid Object Type 0x%X", type));
return (ACPI_NS_NORMAL);
}
return (((u32)acpi_gbl_ns_properties[type]) & ACPI_NS_NEWSCOPE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_node_unlocked
*
* PARAMETERS: *pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* prefix_node - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first s8 is '\'), the passed value
* of Scope will not be accessed.
* flags - Used to indicate whether to perform upsearch or
* not.
* return_node - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Doesn't locks namespace
*
******************************************************************************/
acpi_status
acpi_ns_get_node_unlocked(struct acpi_namespace_node *prefix_node,
const char *pathname,
u32 flags, struct acpi_namespace_node **return_node)
{
union acpi_generic_state scope_info;
acpi_status status;
char *internal_path;
ACPI_FUNCTION_TRACE_PTR(ns_get_node_unlocked,
ACPI_CAST_PTR(char, pathname));
/* Simplest case is a null pathname */
if (!pathname) {
*return_node = prefix_node;
if (!prefix_node) {
*return_node = acpi_gbl_root_node;
}
return_ACPI_STATUS(AE_OK);
}
/* Quick check for a reference to the root */
if (ACPI_IS_ROOT_PREFIX(pathname[0]) && (!pathname[1])) {
*return_node = acpi_gbl_root_node;
return_ACPI_STATUS(AE_OK);
}
/* Convert path to internal representation */
status = acpi_ns_internalize_name(pathname, &internal_path);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Setup lookup scope (search starting point) */
scope_info.scope.node = prefix_node;
/* Lookup the name in the namespace */
status = acpi_ns_lookup(&scope_info, internal_path, ACPI_TYPE_ANY,
ACPI_IMODE_EXECUTE,
(flags | ACPI_NS_DONT_OPEN_SCOPE), NULL,
return_node);
if (ACPI_FAILURE(status)) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "%s, %s\n",
pathname, acpi_format_exception(status)));
}
ACPI_FREE(internal_path);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_node
*
* PARAMETERS: *pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* prefix_node - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first s8 is '\'), the passed value
* of Scope will not be accessed.
* flags - Used to indicate whether to perform upsearch or
* not.
* return_node - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Locks namespace
*
******************************************************************************/
acpi_status
acpi_ns_get_node(struct acpi_namespace_node *prefix_node,
const char *pathname,
u32 flags, struct acpi_namespace_node **return_node)
{
acpi_status status;
ACPI_FUNCTION_TRACE_PTR(ns_get_node, ACPI_CAST_PTR(char, pathname));
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
status = acpi_ns_get_node_unlocked(prefix_node, pathname,
flags, return_node);
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
return_ACPI_STATUS(status);
}
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_2582_0 |
crossvul-cpp_data_good_1352_2 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle SELECT statements in SQLite.
*/
#include "sqliteInt.h"
/*
** Trace output macros
*/
#if SELECTTRACE_ENABLED
/***/ int sqlite3SelectTrace = 0;
# define SELECTTRACE(K,P,S,X) \
if(sqlite3SelectTrace&(K)) \
sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
sqlite3DebugPrintf X
#else
# define SELECTTRACE(K,P,S,X)
#endif
/*
** An instance of the following object is used to record information about
** how to process the DISTINCT keyword, to simplify passing that information
** into the selectInnerLoop() routine.
*/
typedef struct DistinctCtx DistinctCtx;
struct DistinctCtx {
u8 isTnct; /* True if the DISTINCT keyword is present */
u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
int tabTnct; /* Ephemeral table used for DISTINCT processing */
int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
};
/*
** An instance of the following object is used to record information about
** the ORDER BY (or GROUP BY) clause of query is being coded.
**
** The aDefer[] array is used by the sorter-references optimization. For
** example, assuming there is no index that can be used for the ORDER BY,
** for the query:
**
** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
**
** it may be more efficient to add just the "a" values to the sorter, and
** retrieve the associated "bigblob" values directly from table t1 as the
** 10 smallest "a" values are extracted from the sorter.
**
** When the sorter-reference optimization is used, there is one entry in the
** aDefer[] array for each database table that may be read as values are
** extracted from the sorter.
*/
typedef struct SortCtx SortCtx;
struct SortCtx {
ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
int nOBSat; /* Number of ORDER BY terms satisfied by indices */
int iECursor; /* Cursor number for the sorter */
int regReturn; /* Register holding block-output return address */
int labelBkOut; /* Start label for the block-output subroutine */
int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
int labelDone; /* Jump here when done, ex: LIMIT reached */
int labelOBLopt; /* Jump here when sorter is full */
u8 sortFlags; /* Zero or more SORTFLAG_* bits */
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
u8 nDefer; /* Number of valid entries in aDefer[] */
struct DeferredCsr {
Table *pTab; /* Table definition */
int iCsr; /* Cursor number for table */
int nKey; /* Number of PK columns for table pTab (>=1) */
} aDefer[4];
#endif
struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
};
#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
/*
** Delete all the content of a Select structure. Deallocate the structure
** itself depending on the value of bFree
**
** If bFree==1, call sqlite3DbFree() on the p object.
** If bFree==0, Leave the first Select object unfreed
*/
static void clearSelect(sqlite3 *db, Select *p, int bFree){
while( p ){
Select *pPrior = p->pPrior;
sqlite3ExprListDelete(db, p->pEList);
sqlite3SrcListDelete(db, p->pSrc);
sqlite3ExprDelete(db, p->pWhere);
sqlite3ExprListDelete(db, p->pGroupBy);
sqlite3ExprDelete(db, p->pHaving);
sqlite3ExprListDelete(db, p->pOrderBy);
sqlite3ExprDelete(db, p->pLimit);
#ifndef SQLITE_OMIT_WINDOWFUNC
if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
sqlite3WindowListDelete(db, p->pWinDefn);
}
assert( p->pWin==0 );
#endif
if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
if( bFree ) sqlite3DbFreeNN(db, p);
p = pPrior;
bFree = 1;
}
}
/*
** Initialize a SelectDest structure.
*/
void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
pDest->eDest = (u8)eDest;
pDest->iSDParm = iParm;
pDest->zAffSdst = 0;
pDest->iSdst = 0;
pDest->nSdst = 0;
}
/*
** Allocate a new Select structure and return a pointer to that
** structure.
*/
Select *sqlite3SelectNew(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* which columns to include in the result */
SrcList *pSrc, /* the FROM clause -- which tables to scan */
Expr *pWhere, /* the WHERE clause */
ExprList *pGroupBy, /* the GROUP BY clause */
Expr *pHaving, /* the HAVING clause */
ExprList *pOrderBy, /* the ORDER BY clause */
u32 selFlags, /* Flag parameters, such as SF_Distinct */
Expr *pLimit /* LIMIT value. NULL means not used */
){
Select *pNew;
Select standin;
pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
if( pNew==0 ){
assert( pParse->db->mallocFailed );
pNew = &standin;
}
if( pEList==0 ){
pEList = sqlite3ExprListAppend(pParse, 0,
sqlite3Expr(pParse->db,TK_ASTERISK,0));
}
pNew->pEList = pEList;
pNew->op = TK_SELECT;
pNew->selFlags = selFlags;
pNew->iLimit = 0;
pNew->iOffset = 0;
pNew->selId = ++pParse->nSelect;
pNew->addrOpenEphm[0] = -1;
pNew->addrOpenEphm[1] = -1;
pNew->nSelectRow = 0;
if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
pNew->pSrc = pSrc;
pNew->pWhere = pWhere;
pNew->pGroupBy = pGroupBy;
pNew->pHaving = pHaving;
pNew->pOrderBy = pOrderBy;
pNew->pPrior = 0;
pNew->pNext = 0;
pNew->pLimit = pLimit;
pNew->pWith = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
pNew->pWin = 0;
pNew->pWinDefn = 0;
#endif
if( pParse->db->mallocFailed ) {
clearSelect(pParse->db, pNew, pNew!=&standin);
pNew = 0;
}else{
assert( pNew->pSrc!=0 || pParse->nErr>0 );
}
assert( pNew!=&standin );
return pNew;
}
/*
** Delete the given Select structure and all of its substructures.
*/
void sqlite3SelectDelete(sqlite3 *db, Select *p){
if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
}
/*
** Delete all the substructure for p, but keep p allocated. Redefine
** p to be a single SELECT where every column of the result set has a
** value of NULL.
*/
void sqlite3SelectReset(Parse *pParse, Select *p){
if( ALWAYS(p) ){
clearSelect(pParse->db, p, 0);
memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit));
p->pEList = sqlite3ExprListAppend(pParse, 0,
sqlite3ExprAlloc(pParse->db,TK_NULL,0,0));
}
}
/*
** Return a pointer to the right-most SELECT statement in a compound.
*/
static Select *findRightmost(Select *p){
while( p->pNext ) p = p->pNext;
return p;
}
/*
** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
** type of join. Return an integer constant that expresses that type
** in terms of the following bit values:
**
** JT_INNER
** JT_CROSS
** JT_OUTER
** JT_NATURAL
** JT_LEFT
** JT_RIGHT
**
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
**
** If an illegal or unsupported join type is seen, then still return
** a join type, but put an error in the pParse structure.
*/
int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
int jointype = 0;
Token *apAll[3];
Token *p;
/* 0123456789 123456789 123456789 123 */
static const char zKeyText[] = "naturaleftouterightfullinnercross";
static const struct {
u8 i; /* Beginning of keyword text in zKeyText[] */
u8 nChar; /* Length of the keyword in characters */
u8 code; /* Join type mask */
} aKeyword[] = {
/* natural */ { 0, 7, JT_NATURAL },
/* left */ { 6, 4, JT_LEFT|JT_OUTER },
/* outer */ { 10, 5, JT_OUTER },
/* right */ { 14, 5, JT_RIGHT|JT_OUTER },
/* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
/* inner */ { 23, 5, JT_INNER },
/* cross */ { 28, 5, JT_INNER|JT_CROSS },
};
int i, j;
apAll[0] = pA;
apAll[1] = pB;
apAll[2] = pC;
for(i=0; i<3 && apAll[i]; i++){
p = apAll[i];
for(j=0; j<ArraySize(aKeyword); j++){
if( p->n==aKeyword[j].nChar
&& sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
jointype |= aKeyword[j].code;
break;
}
}
testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
if( j>=ArraySize(aKeyword) ){
jointype |= JT_ERROR;
break;
}
}
if(
(jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
(jointype & JT_ERROR)!=0
){
const char *zSp = " ";
assert( pB!=0 );
if( pC==0 ){ zSp++; }
sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
"%T %T%s%T", pA, pB, zSp, pC);
jointype = JT_INNER;
}else if( (jointype & JT_OUTER)!=0
&& (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
sqlite3ErrorMsg(pParse,
"RIGHT and FULL OUTER JOINs are not currently supported");
jointype = JT_INNER;
}
return jointype;
}
/*
** Return the index of a column in a table. Return -1 if the column
** is not contained in the table.
*/
static int columnIndex(Table *pTab, const char *zCol){
int i;
for(i=0; i<pTab->nCol; i++){
if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
}
return -1;
}
/*
** Search the first N tables in pSrc, from left to right, looking for a
** table that has a column named zCol.
**
** When found, set *piTab and *piCol to the table index and column index
** of the matching column and return TRUE.
**
** If not found, return FALSE.
*/
static int tableAndColumnIndex(
SrcList *pSrc, /* Array of tables to search */
int N, /* Number of tables in pSrc->a[] to search */
const char *zCol, /* Name of the column we are looking for */
int *piTab, /* Write index of pSrc->a[] here */
int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
){
int i; /* For looping over tables in pSrc */
int iCol; /* Index of column matching zCol */
assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
for(i=0; i<N; i++){
iCol = columnIndex(pSrc->a[i].pTab, zCol);
if( iCol>=0 ){
if( piTab ){
*piTab = i;
*piCol = iCol;
}
return 1;
}
}
return 0;
}
/*
** This function is used to add terms implied by JOIN syntax to the
** WHERE clause expression of a SELECT statement. The new term, which
** is ANDed with the existing WHERE clause, is of the form:
**
** (tab1.col1 = tab2.col2)
**
** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
** column iColRight of tab2.
*/
static void addWhereTerm(
Parse *pParse, /* Parsing context */
SrcList *pSrc, /* List of tables in FROM clause */
int iLeft, /* Index of first table to join in pSrc */
int iColLeft, /* Index of column in first table */
int iRight, /* Index of second table in pSrc */
int iColRight, /* Index of column in second table */
int isOuterJoin, /* True if this is an OUTER join */
Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
){
sqlite3 *db = pParse->db;
Expr *pE1;
Expr *pE2;
Expr *pEq;
assert( iLeft<iRight );
assert( pSrc->nSrc>iRight );
assert( pSrc->a[iLeft].pTab );
assert( pSrc->a[iRight].pTab );
pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
if( pEq && isOuterJoin ){
ExprSetProperty(pEq, EP_FromJoin);
assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(pEq, EP_NoReduce);
pEq->iRightJoinTable = (i16)pE2->iTable;
}
*ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
}
/*
** Set the EP_FromJoin property on all terms of the given expression.
** And set the Expr.iRightJoinTable to iTable for every term in the
** expression.
**
** The EP_FromJoin property is used on terms of an expression to tell
** the LEFT OUTER JOIN processing logic that this term is part of the
** join restriction specified in the ON or USING clause and not a part
** of the more general WHERE clause. These terms are moved over to the
** WHERE clause during join processing but we need to remember that they
** originated in the ON or USING clause.
**
** The Expr.iRightJoinTable tells the WHERE clause processing that the
** expression depends on table iRightJoinTable even if that table is not
** explicitly mentioned in the expression. That information is needed
** for cases like this:
**
** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
**
** The where clause needs to defer the handling of the t1.x=5
** term until after the t2 loop of the join. In that way, a
** NULL t2 row will be inserted whenever t1.x!=5. If we do not
** defer the handling of t1.x=5, it will be processed immediately
** after the t1 loop and rows with t1.x!=5 will never appear in
** the output, which is incorrect.
*/
void sqlite3SetJoinExpr(Expr *p, int iTable){
while( p ){
ExprSetProperty(p, EP_FromJoin);
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(p, EP_NoReduce);
p->iRightJoinTable = (i16)iTable;
if( p->op==TK_FUNCTION && p->x.pList ){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
}
}
sqlite3SetJoinExpr(p->pLeft, iTable);
p = p->pRight;
}
}
/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
** an ordinary term that omits the EP_FromJoin mark.
**
** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
*/
static void unsetJoinExpr(Expr *p, int iTable){
while( p ){
if( ExprHasProperty(p, EP_FromJoin)
&& (iTable<0 || p->iRightJoinTable==iTable) ){
ExprClearProperty(p, EP_FromJoin);
}
if( p->op==TK_FUNCTION && p->x.pList ){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
}
}
unsetJoinExpr(p->pLeft, iTable);
p = p->pRight;
}
}
/*
** This routine processes the join information for a SELECT statement.
** ON and USING clauses are converted into extra terms of the WHERE clause.
** NATURAL joins also create extra WHERE clause terms.
**
** The terms of a FROM clause are contained in the Select.pSrc structure.
** The left most table is the first entry in Select.pSrc. The right-most
** table is the last entry. The join operator is held in the entry to
** the left. Thus entry 0 contains the join operator for the join between
** entries 0 and 1. Any ON or USING clauses associated with the join are
** also attached to the left entry.
**
** This routine returns the number of errors encountered.
*/
static int sqliteProcessJoin(Parse *pParse, Select *p){
SrcList *pSrc; /* All tables in the FROM clause */
int i, j; /* Loop counters */
struct SrcList_item *pLeft; /* Left table being joined */
struct SrcList_item *pRight; /* Right table being joined */
pSrc = p->pSrc;
pLeft = &pSrc->a[0];
pRight = &pLeft[1];
for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
Table *pRightTab = pRight->pTab;
int isOuter;
if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
/* When the NATURAL keyword is present, add WHERE clause terms for
** every column that the two tables have in common.
*/
if( pRight->fg.jointype & JT_NATURAL ){
if( pRight->pOn || pRight->pUsing ){
sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
"an ON or USING clause", 0);
return 1;
}
for(j=0; j<pRightTab->nCol; j++){
char *zName; /* Name of column in the right table */
int iLeft; /* Matching left table */
int iLeftCol; /* Matching column in the left table */
zName = pRightTab->aCol[j].zName;
if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
isOuter, &p->pWhere);
}
}
}
/* Disallow both ON and USING clauses in the same join
*/
if( pRight->pOn && pRight->pUsing ){
sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
"clauses in the same join");
return 1;
}
/* Add the ON clause to the end of the WHERE clause, connected by
** an AND operator.
*/
if( pRight->pOn ){
if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);
p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
pRight->pOn = 0;
}
/* Create extra terms on the WHERE clause for each column named
** in the USING clause. Example: If the two tables to be joined are
** A and B and the USING clause names X, Y, and Z, then add this
** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
** Report an error if any column mentioned in the USING clause is
** not contained in both tables to be joined.
*/
if( pRight->pUsing ){
IdList *pList = pRight->pUsing;
for(j=0; j<pList->nId; j++){
char *zName; /* Name of the term in the USING clause */
int iLeft; /* Table on the left with matching column name */
int iLeftCol; /* Column number of matching column on the left */
int iRightCol; /* Column number of matching column on the right */
zName = pList->a[j].zName;
iRightCol = columnIndex(pRightTab, zName);
if( iRightCol<0
|| !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
){
sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
"not present in both tables", zName);
return 1;
}
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
isOuter, &p->pWhere);
}
}
}
return 0;
}
/*
** An instance of this object holds information (beyond pParse and pSelect)
** needed to load the next result row that is to be added to the sorter.
*/
typedef struct RowLoadInfo RowLoadInfo;
struct RowLoadInfo {
int regResult; /* Store results in array of registers here */
u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
ExprList *pExtra; /* Extra columns needed by sorter refs */
int regExtraResult; /* Where to load the extra columns */
#endif
};
/*
** This routine does the work of loading query data into an array of
** registers so that it can be added to the sorter.
*/
static void innerLoopLoadRow(
Parse *pParse, /* Statement under construction */
Select *pSelect, /* The query being coded */
RowLoadInfo *pInfo /* Info needed to complete the row load */
){
sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
0, pInfo->ecelFlags);
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pInfo->pExtra ){
sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
}
#endif
}
/*
** Code the OP_MakeRecord instruction that generates the entry to be
** added into the sorter.
**
** Return the register in which the result is stored.
*/
static int makeSorterRecord(
Parse *pParse,
SortCtx *pSort,
Select *pSelect,
int regBase,
int nBase
){
int nOBSat = pSort->nOBSat;
Vdbe *v = pParse->pVdbe;
int regOut = ++pParse->nMem;
if( pSort->pDeferredRowLoad ){
innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
return regOut;
}
/*
** Generate code that will push the record in registers regData
** through regData+nData-1 onto the sorter.
*/
static void pushOntoSorter(
Parse *pParse, /* Parser context */
SortCtx *pSort, /* Information about the ORDER BY clause */
Select *pSelect, /* The whole SELECT statement */
int regData, /* First register holding data to be sorted */
int regOrigData, /* First register holding data before packing */
int nData, /* Number of elements in the regData data array */
int nPrefixReg /* No. of reg prior to regData available for use */
){
Vdbe *v = pParse->pVdbe; /* Stmt under construction */
int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
int regBase; /* Regs for sorter record */
int regRecord = 0; /* Assembled sorter record */
int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
int op; /* Opcode to add sorter record to sorter */
int iLimit; /* LIMIT counter */
int iSkip = 0; /* End of the sorter insert loop */
assert( bSeq==0 || bSeq==1 );
/* Three cases:
** (1) The data to be sorted has already been packed into a Record
** by a prior OP_MakeRecord. In this case nData==1 and regData
** will be completely unrelated to regOrigData.
** (2) All output columns are included in the sort record. In that
** case regData==regOrigData.
** (3) Some output columns are omitted from the sort record due to
** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
** SQLITE_ECEL_OMITREF optimization, or due to the
** SortCtx.pDeferredRowLoad optimiation. In any of these cases
** regOrigData is 0 to prevent this routine from trying to copy
** values that might not yet exist.
*/
assert( nData==1 || regData==regOrigData || regOrigData==0 );
if( nPrefixReg ){
assert( nPrefixReg==nExpr+bSeq );
regBase = regData - nPrefixReg;
}else{
regBase = pParse->nMem + 1;
pParse->nMem += nBase;
}
assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
if( bSeq ){
sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
}
if( nPrefixReg==0 && nData>0 ){
sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
}
if( nOBSat>0 ){
int regPrevKey; /* The first nOBSat columns of the previous row */
int addrFirst; /* Address of the OP_IfNot opcode */
int addrJmp; /* Address of the OP_Jump opcode */
VdbeOp *pOp; /* Opcode that opens the sorter */
int nKey; /* Number of sorting key columns, including OP_Sequence */
KeyInfo *pKI; /* Original KeyInfo on the sorter table */
regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
regPrevKey = pParse->nMem+1;
pParse->nMem += pSort->nOBSat;
nKey = nExpr - pSort->nOBSat + bSeq;
if( bSeq ){
addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
}else{
addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
}
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
if( pParse->db->mallocFailed ) return;
pOp->p2 = nKey + nData;
pKI = pOp->p4.pKeyInfo;
memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
testcase( pKI->nAllField > pKI->nKeyField+2 );
pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
pKI->nAllField-pKI->nKeyField-1);
pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
addrJmp = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
pSort->regReturn = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
if( iLimit ){
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
VdbeCoverage(v);
}
sqlite3VdbeJumpHere(v, addrFirst);
sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
sqlite3VdbeJumpHere(v, addrJmp);
}
if( iLimit ){
/* At this point the values for the new sorter entry are stored
** in an array of registers. They need to be composed into a record
** and inserted into the sorter if either (a) there are currently
** less than LIMIT+OFFSET items or (b) the new record is smaller than
** the largest record currently in the sorter. If (b) is true and there
** are already LIMIT+OFFSET items in the sorter, delete the largest
** entry before inserting the new one. This way there are never more
** than LIMIT+OFFSET items in the sorter.
**
** If the new record does not need to be inserted into the sorter,
** jump to the next iteration of the loop. If the pSort->labelOBLopt
** value is not zero, then it is a label of where to jump. Otherwise,
** just bypass the row insert logic. See the header comment on the
** sqlite3WhereOrderByLimitOptLabel() function for additional info.
*/
int iCsr = pSort->iECursor;
sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
VdbeCoverage(v);
sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
VdbeCoverage(v);
sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
}
if( regRecord==0 ){
regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
}
if( pSort->sortFlags & SORTFLAG_UseSorter ){
op = OP_SorterInsert;
}else{
op = OP_IdxInsert;
}
sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
regBase+nOBSat, nBase-nOBSat);
if( iSkip ){
sqlite3VdbeChangeP2(v, iSkip,
pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
}
}
/*
** Add code to implement the OFFSET
*/
static void codeOffset(
Vdbe *v, /* Generate code into this VM */
int iOffset, /* Register holding the offset counter */
int iContinue /* Jump here to skip the current record */
){
if( iOffset>0 ){
sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
VdbeComment((v, "OFFSET"));
}
}
/*
** Add code that will check to make sure the N registers starting at iMem
** form a distinct entry. iTab is a sorting index that holds previously
** seen combinations of the N values. A new entry is made in iTab
** if the current N values are new.
**
** A jump to addrRepeat is made and the N+1 values are popped from the
** stack if the top N elements are not distinct.
*/
static void codeDistinct(
Parse *pParse, /* Parsing and code generating context */
int iTab, /* A sorting index used to test for distinctness */
int addrRepeat, /* Jump to here if not distinct */
int N, /* Number of elements */
int iMem /* First element */
){
Vdbe *v;
int r1;
v = pParse->pVdbe;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
sqlite3ReleaseTempReg(pParse, r1);
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
/*
** This function is called as part of inner-loop generation for a SELECT
** statement with an ORDER BY that is not optimized by an index. It
** determines the expressions, if any, that the sorter-reference
** optimization should be used for. The sorter-reference optimization
** is used for SELECT queries like:
**
** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
**
** If the optimization is used for expression "bigblob", then instead of
** storing values read from that column in the sorter records, the PK of
** the row from table t1 is stored instead. Then, as records are extracted from
** the sorter to return to the user, the required value of bigblob is
** retrieved directly from table t1. If the values are very large, this
** can be more efficient than storing them directly in the sorter records.
**
** The ExprList_item.bSorterRef flag is set for each expression in pEList
** for which the sorter-reference optimization should be enabled.
** Additionally, the pSort->aDefer[] array is populated with entries
** for all cursors required to evaluate all selected expressions. Finally.
** output variable (*ppExtra) is set to an expression list containing
** expressions for all extra PK values that should be stored in the
** sorter records.
*/
static void selectExprDefer(
Parse *pParse, /* Leave any error here */
SortCtx *pSort, /* Sorter context */
ExprList *pEList, /* Expressions destined for sorter */
ExprList **ppExtra /* Expressions to append to sorter record */
){
int i;
int nDefer = 0;
ExprList *pExtra = 0;
for(i=0; i<pEList->nExpr; i++){
struct ExprList_item *pItem = &pEList->a[i];
if( pItem->u.x.iOrderByCol==0 ){
Expr *pExpr = pItem->pExpr;
Table *pTab = pExpr->y.pTab;
if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
&& (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
){
int j;
for(j=0; j<nDefer; j++){
if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
}
if( j==nDefer ){
if( nDefer==ArraySize(pSort->aDefer) ){
continue;
}else{
int nKey = 1;
int k;
Index *pPk = 0;
if( !HasRowid(pTab) ){
pPk = sqlite3PrimaryKeyIndex(pTab);
nKey = pPk->nKeyCol;
}
for(k=0; k<nKey; k++){
Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
if( pNew ){
pNew->iTable = pExpr->iTable;
pNew->y.pTab = pExpr->y.pTab;
pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
}
}
pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
pSort->aDefer[nDefer].iCsr = pExpr->iTable;
pSort->aDefer[nDefer].nKey = nKey;
nDefer++;
}
}
pItem->bSorterRef = 1;
}
}
}
pSort->nDefer = (u8)nDefer;
*ppExtra = pExtra;
}
#endif
/*
** This routine generates the code for the inside of the inner loop
** of a SELECT.
**
** If srcTab is negative, then the p->pEList expressions
** are evaluated in order to get the data for this row. If srcTab is
** zero or more, then data is pulled from srcTab and p->pEList is used only
** to get the number of columns and the collation sequence for each column.
*/
static void selectInnerLoop(
Parse *pParse, /* The parser context */
Select *p, /* The complete select statement being coded */
int srcTab, /* Pull data from this table if non-negative */
SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
SelectDest *pDest, /* How to dispose of the results */
int iContinue, /* Jump here to continue with next row */
int iBreak /* Jump here to break out of the inner loop */
){
Vdbe *v = pParse->pVdbe;
int i;
int hasDistinct; /* True if the DISTINCT keyword is present */
int eDest = pDest->eDest; /* How to dispose of results */
int iParm = pDest->iSDParm; /* First argument to disposal method */
int nResultCol; /* Number of result columns */
int nPrefixReg = 0; /* Number of extra registers before regResult */
RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
/* Usually, regResult is the first cell in an array of memory cells
** containing the current result row. In this case regOrig is set to the
** same value. However, if the results are being sent to the sorter, the
** values for any expressions that are also part of the sort-key are omitted
** from this array. In this case regOrig is set to zero. */
int regResult; /* Start of memory holding current results */
int regOrig; /* Start of memory holding full result (or 0) */
assert( v );
assert( p->pEList!=0 );
hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
if( pSort && pSort->pOrderBy==0 ) pSort = 0;
if( pSort==0 && !hasDistinct ){
assert( iContinue!=0 );
codeOffset(v, p->iOffset, iContinue);
}
/* Pull the requested columns.
*/
nResultCol = p->pEList->nExpr;
if( pDest->iSdst==0 ){
if( pSort ){
nPrefixReg = pSort->pOrderBy->nExpr;
if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
pParse->nMem += nPrefixReg;
}
pDest->iSdst = pParse->nMem+1;
pParse->nMem += nResultCol;
}else if( pDest->iSdst+nResultCol > pParse->nMem ){
/* This is an error condition that can result, for example, when a SELECT
** on the right-hand side of an INSERT contains more result columns than
** there are columns in the table on the left. The error will be caught
** and reported later. But we need to make sure enough memory is allocated
** to avoid other spurious errors in the meantime. */
pParse->nMem += nResultCol;
}
pDest->nSdst = nResultCol;
regOrig = regResult = pDest->iSdst;
if( srcTab>=0 ){
for(i=0; i<nResultCol; i++){
sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
VdbeComment((v, "%s", p->pEList->a[i].zName));
}
}else if( eDest!=SRT_Exists ){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
ExprList *pExtra = 0;
#endif
/* If the destination is an EXISTS(...) expression, the actual
** values returned by the SELECT are not required.
*/
u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
ExprList *pEList;
if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
ecelFlags = SQLITE_ECEL_DUP;
}else{
ecelFlags = 0;
}
if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
/* For each expression in p->pEList that is a copy of an expression in
** the ORDER BY clause (pSort->pOrderBy), set the associated
** iOrderByCol value to one more than the index of the ORDER BY
** expression within the sort-key that pushOntoSorter() will generate.
** This allows the p->pEList field to be omitted from the sorted record,
** saving space and CPU cycles. */
ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
int j;
if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
}
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
selectExprDefer(pParse, pSort, p->pEList, &pExtra);
if( pExtra && pParse->db->mallocFailed==0 ){
/* If there are any extra PK columns to add to the sorter records,
** allocate extra memory cells and adjust the OpenEphemeral
** instruction to account for the larger records. This is only
** required if there are one or more WITHOUT ROWID tables with
** composite primary keys in the SortCtx.aDefer[] array. */
VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
pOp->p2 += (pExtra->nExpr - pSort->nDefer);
pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
pParse->nMem += pExtra->nExpr;
}
#endif
/* Adjust nResultCol to account for columns that are omitted
** from the sorter by the optimizations in this branch */
pEList = p->pEList;
for(i=0; i<pEList->nExpr; i++){
if( pEList->a[i].u.x.iOrderByCol>0
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
|| pEList->a[i].bSorterRef
#endif
){
nResultCol--;
regOrig = 0;
}
}
testcase( regOrig );
testcase( eDest==SRT_Set );
testcase( eDest==SRT_Mem );
testcase( eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
assert( eDest==SRT_Set || eDest==SRT_Mem
|| eDest==SRT_Coroutine || eDest==SRT_Output );
}
sRowLoadInfo.regResult = regResult;
sRowLoadInfo.ecelFlags = ecelFlags;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
sRowLoadInfo.pExtra = pExtra;
sRowLoadInfo.regExtraResult = regResult + nResultCol;
if( pExtra ) nResultCol += pExtra->nExpr;
#endif
if( p->iLimit
&& (ecelFlags & SQLITE_ECEL_OMITREF)!=0
&& nPrefixReg>0
){
assert( pSort!=0 );
assert( hasDistinct==0 );
pSort->pDeferredRowLoad = &sRowLoadInfo;
regOrig = 0;
}else{
innerLoopLoadRow(pParse, p, &sRowLoadInfo);
}
}
/* If the DISTINCT keyword was present on the SELECT statement
** and this row has been seen before, then do not make this row
** part of the result.
*/
if( hasDistinct ){
switch( pDistinct->eTnctType ){
case WHERE_DISTINCT_ORDERED: {
VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
int iJump; /* Jump destination */
int regPrev; /* Previous row content */
/* Allocate space for the previous row */
regPrev = pParse->nMem+1;
pParse->nMem += nResultCol;
/* Change the OP_OpenEphemeral coded earlier to an OP_Null
** sets the MEM_Cleared bit on the first register of the
** previous value. This will cause the OP_Ne below to always
** fail on the first iteration of the loop even if the first
** row is all NULLs.
*/
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
pOp->opcode = OP_Null;
pOp->p1 = 1;
pOp->p2 = regPrev;
pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */
iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
for(i=0; i<nResultCol; i++){
CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
if( i<nResultCol-1 ){
sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
VdbeCoverage(v);
}else{
sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
VdbeCoverage(v);
}
sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
}
assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
break;
}
case WHERE_DISTINCT_UNIQUE: {
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
break;
}
default: {
assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
regResult);
break;
}
}
if( pSort==0 ){
codeOffset(v, p->iOffset, iContinue);
}
}
switch( eDest ){
/* In this mode, write each query result to the key of the temporary
** table iParm.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
case SRT_Union: {
int r1;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
/* Construct a record from the query result, but instead of
** saving that record, use it as a key to delete elements from
** the temporary table iParm.
*/
case SRT_Except: {
sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
break;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
/* Store the result as data using a unique key.
*/
case SRT_Fifo:
case SRT_DistFifo:
case SRT_Table:
case SRT_EphemTab: {
int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
testcase( eDest==SRT_Table );
testcase( eDest==SRT_EphemTab );
testcase( eDest==SRT_Fifo );
testcase( eDest==SRT_DistFifo );
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
#ifndef SQLITE_OMIT_CTE
if( eDest==SRT_DistFifo ){
/* If the destination is DistFifo, then cursor (iParm+1) is open
** on an ephemeral index. If the current row is already present
** in the index, do not write it to the output. If not, add the
** current row to the index and proceed with writing it to the
** output table as well. */
int addr = sqlite3VdbeCurrentAddr(v) + 4;
sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
VdbeCoverage(v);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
assert( pSort==0 );
}
#endif
if( pSort ){
assert( regResult==regOrig );
pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
}else{
int r2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3ReleaseTempReg(pParse, r2);
}
sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
/* If we are creating a set for an "expr IN (SELECT ...)" construct,
** then there should be a single item on the stack. Write this
** item into the set table with bogus data.
*/
case SRT_Set: {
if( pSort ){
/* At first glance you would think we could optimize out the
** ORDER BY in this case since the order of entries in the set
** does not matter. But there might be a LIMIT clause, in which
** case the order does matter */
pushOntoSorter(
pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
}else{
int r1 = sqlite3GetTempReg(pParse);
assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
r1, pDest->zAffSdst, nResultCol);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
sqlite3ReleaseTempReg(pParse, r1);
}
break;
}
/* If any row exist in the result set, record that fact and abort.
*/
case SRT_Exists: {
sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
/* The LIMIT clause will terminate the loop for us */
break;
}
/* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell or array of
** memory cells and break out of the scan loop.
*/
case SRT_Mem: {
if( pSort ){
assert( nResultCol<=pDest->nSdst );
pushOntoSorter(
pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
}else{
assert( nResultCol==pDest->nSdst );
assert( regResult==iParm );
/* The LIMIT clause will jump out of the loop for us */
}
break;
}
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
case SRT_Coroutine: /* Send data to a co-routine */
case SRT_Output: { /* Return the results */
testcase( eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
if( pSort ){
pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
nPrefixReg);
}else if( eDest==SRT_Coroutine ){
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
}else{
sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
}
break;
}
#ifndef SQLITE_OMIT_CTE
/* Write the results into a priority queue that is order according to
** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
** index with pSO->nExpr+2 columns. Build a key using pSO for the first
** pSO->nExpr columns, then make sure all keys are unique by adding a
** final OP_Sequence column. The last column is the record as a blob.
*/
case SRT_DistQueue:
case SRT_Queue: {
int nKey;
int r1, r2, r3;
int addrTest = 0;
ExprList *pSO;
pSO = pDest->pOrderBy;
assert( pSO );
nKey = pSO->nExpr;
r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3GetTempRange(pParse, nKey+2);
r3 = r2+nKey+1;
if( eDest==SRT_DistQueue ){
/* If the destination is DistQueue, then cursor (iParm+1) is open
** on a second ephemeral index that holds all values every previously
** added to the queue. */
addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
regResult, nResultCol);
VdbeCoverage(v);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
if( eDest==SRT_DistQueue ){
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
}
for(i=0; i<nKey; i++){
sqlite3VdbeAddOp2(v, OP_SCopy,
regResult + pSO->a[i].u.x.iOrderByCol - 1,
r2+i);
}
sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
sqlite3ReleaseTempReg(pParse, r1);
sqlite3ReleaseTempRange(pParse, r2, nKey+2);
break;
}
#endif /* SQLITE_OMIT_CTE */
#if !defined(SQLITE_OMIT_TRIGGER)
/* Discard the results. This is used for SELECT statements inside
** the body of a TRIGGER. The purpose of such selects is to call
** user-defined functions that have side effects. We do not care
** about the actual results of the select.
*/
default: {
assert( eDest==SRT_Discard );
break;
}
#endif
}
/* Jump to the end of the loop if the LIMIT is reached. Except, if
** there is a sorter, in which case the sorter has already limited
** the output for us.
*/
if( pSort==0 && p->iLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
}
}
/*
** Allocate a KeyInfo object sufficient for an index of N key columns and
** X extra columns.
*/
KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
if( p ){
p->aSortFlags = (u8*)&p->aColl[N+X];
p->nKeyField = (u16)N;
p->nAllField = (u16)(N+X);
p->enc = ENC(db);
p->db = db;
p->nRef = 1;
memset(&p[1], 0, nExtra);
}else{
sqlite3OomFault(db);
}
return p;
}
/*
** Deallocate a KeyInfo object
*/
void sqlite3KeyInfoUnref(KeyInfo *p){
if( p ){
assert( p->nRef>0 );
p->nRef--;
if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
}
}
/*
** Make a new pointer to a KeyInfo object
*/
KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
if( p ){
assert( p->nRef>0 );
p->nRef++;
}
return p;
}
#ifdef SQLITE_DEBUG
/*
** Return TRUE if a KeyInfo object can be change. The KeyInfo object
** can only be changed if this is just a single reference to the object.
**
** This routine is used only inside of assert() statements.
*/
int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
#endif /* SQLITE_DEBUG */
/*
** Given an expression list, generate a KeyInfo structure that records
** the collating sequence for each expression in that expression list.
**
** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
** KeyInfo structure is appropriate for initializing a virtual index to
** implement that clause. If the ExprList is the result set of a SELECT
** then the KeyInfo structure is appropriate for initializing a virtual
** index to implement a DISTINCT test.
**
** Space to hold the KeyInfo structure is obtained from malloc. The calling
** function is responsible for seeing that this structure is eventually
** freed.
*/
KeyInfo *sqlite3KeyInfoFromExprList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* Form the KeyInfo object from this ExprList */
int iStart, /* Begin with this column of pList */
int nExtra /* Add this many extra columns to the end */
){
int nExpr;
KeyInfo *pInfo;
struct ExprList_item *pItem;
sqlite3 *db = pParse->db;
int i;
nExpr = pList->nExpr;
pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
if( pInfo ){
assert( sqlite3KeyInfoIsWriteable(pInfo) );
for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
pInfo->aSortFlags[i-iStart] = pItem->sortFlags;
}
}
return pInfo;
}
/*
** Name of the connection operator, used for error messages.
*/
static const char *selectOpName(int id){
char *z;
switch( id ){
case TK_ALL: z = "UNION ALL"; break;
case TK_INTERSECT: z = "INTERSECT"; break;
case TK_EXCEPT: z = "EXCEPT"; break;
default: z = "UNION"; break;
}
return z;
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
** is a no-op. Otherwise, it adds a single row of output to the EQP result,
** where the caption is of the form:
**
** "USE TEMP B-TREE FOR xxx"
**
** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
** is determined by the zUsage argument.
*/
static void explainTempTable(Parse *pParse, const char *zUsage){
ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
}
/*
** Assign expression b to lvalue a. A second, no-op, version of this macro
** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
** in sqlite3Select() to assign values to structure member variables that
** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
** code with #ifndef directives.
*/
# define explainSetInteger(a, b) a = b
#else
/* No-op versions of the explainXXX() functions and macros. */
# define explainTempTable(y,z)
# define explainSetInteger(y,z)
#endif
/*
** If the inner loop was generated using a non-null pOrderBy argument,
** then the results were placed in a sorter. After the loop is terminated
** we need to run the sorter and output the results. The following
** routine generates the code needed to do that.
*/
static void generateSortTail(
Parse *pParse, /* Parsing context */
Select *p, /* The SELECT statement */
SortCtx *pSort, /* Information on the ORDER BY clause */
int nColumn, /* Number of columns of data */
SelectDest *pDest /* Write the sorted results here */
){
Vdbe *v = pParse->pVdbe; /* The prepared statement */
int addrBreak = pSort->labelDone; /* Jump here to exit loop */
int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
int addr; /* Top of output loop. Jump for Next. */
int addrOnce = 0;
int iTab;
ExprList *pOrderBy = pSort->pOrderBy;
int eDest = pDest->eDest;
int iParm = pDest->iSDParm;
int regRow;
int regRowid;
int iCol;
int nKey; /* Number of key columns in sorter record */
int iSortTab; /* Sorter cursor to read from */
int i;
int bSeq; /* True if sorter record includes seq. no. */
int nRefKey = 0;
struct ExprList_item *aOutEx = p->pEList->a;
assert( addrBreak<0 );
if( pSort->labelBkOut ){
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
sqlite3VdbeGoto(v, addrBreak);
sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
/* Open any cursors needed for sorter-reference expressions */
for(i=0; i<pSort->nDefer; i++){
Table *pTab = pSort->aDefer[i].pTab;
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
}
#endif
iTab = pSort->iECursor;
if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
regRowid = 0;
regRow = pDest->iSdst;
}else{
regRowid = sqlite3GetTempReg(pParse);
if( eDest==SRT_EphemTab || eDest==SRT_Table ){
regRow = sqlite3GetTempReg(pParse);
nColumn = 0;
}else{
regRow = sqlite3GetTempRange(pParse, nColumn);
}
}
nKey = pOrderBy->nExpr - pSort->nOBSat;
if( pSort->sortFlags & SORTFLAG_UseSorter ){
int regSortOut = ++pParse->nMem;
iSortTab = pParse->nTab++;
if( pSort->labelBkOut ){
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
nKey+1+nColumn+nRefKey);
if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
VdbeCoverage(v);
codeOffset(v, p->iOffset, addrContinue);
sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
bSeq = 0;
}else{
addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
codeOffset(v, p->iOffset, addrContinue);
iSortTab = iTab;
bSeq = 1;
}
for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( aOutEx[i].bSorterRef ) continue;
#endif
if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pSort->nDefer ){
int iKey = iCol+1;
int regKey = sqlite3GetTempRange(pParse, nRefKey);
for(i=0; i<pSort->nDefer; i++){
int iCsr = pSort->aDefer[i].iCsr;
Table *pTab = pSort->aDefer[i].pTab;
int nKey = pSort->aDefer[i].nKey;
sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
if( HasRowid(pTab) ){
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
sqlite3VdbeCurrentAddr(v)+1, regKey);
}else{
int k;
int iJmp;
assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
for(k=0; k<nKey; k++){
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
}
iJmp = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
}
}
sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
}
#endif
for(i=nColumn-1; i>=0; i--){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( aOutEx[i].bSorterRef ){
sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
}else
#endif
{
int iRead;
if( aOutEx[i].u.x.iOrderByCol ){
iRead = aOutEx[i].u.x.iOrderByCol-1;
}else{
iRead = iCol--;
}
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
}
}
switch( eDest ){
case SRT_Table:
case SRT_EphemTab: {
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case SRT_Set: {
assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
pDest->zAffSdst, nColumn);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
break;
}
case SRT_Mem: {
/* The LIMIT clause will terminate the loop for us */
break;
}
#endif
default: {
assert( eDest==SRT_Output || eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
testcase( eDest==SRT_Coroutine );
if( eDest==SRT_Output ){
sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
}else{
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
}
break;
}
}
if( regRowid ){
if( eDest==SRT_Set ){
sqlite3ReleaseTempRange(pParse, regRow, nColumn);
}else{
sqlite3ReleaseTempReg(pParse, regRow);
}
sqlite3ReleaseTempReg(pParse, regRowid);
}
/* The bottom of the loop
*/
sqlite3VdbeResolveLabel(v, addrContinue);
if( pSort->sortFlags & SORTFLAG_UseSorter ){
sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
}else{
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
}
if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
sqlite3VdbeResolveLabel(v, addrBreak);
}
/*
** Return a pointer to a string containing the 'declaration type' of the
** expression pExpr. The string may be treated as static by the caller.
**
** Also try to estimate the size of the returned value and return that
** result in *pEstWidth.
**
** The declaration type is the exact datatype definition extracted from the
** original CREATE TABLE statement if the expression is a column. The
** declaration type for a ROWID field is INTEGER. Exactly when an expression
** is considered a column can be complex in the presence of subqueries. The
** result-set expression in all of the following SELECT statements is
** considered a column by this function.
**
** SELECT col FROM tbl;
** SELECT (SELECT col FROM tbl;
** SELECT (SELECT col FROM tbl);
** SELECT abc FROM (SELECT col AS abc FROM tbl);
**
** The declaration type for any expression other than a column is NULL.
**
** This routine has either 3 or 6 parameters depending on whether or not
** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
*/
#ifdef SQLITE_ENABLE_COLUMN_METADATA
# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
# define columnType(A,B,C,D,E) columnTypeImpl(A,B)
#endif
static const char *columnTypeImpl(
NameContext *pNC,
#ifndef SQLITE_ENABLE_COLUMN_METADATA
Expr *pExpr
#else
Expr *pExpr,
const char **pzOrigDb,
const char **pzOrigTab,
const char **pzOrigCol
#endif
){
char const *zType = 0;
int j;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
char const *zOrigDb = 0;
char const *zOrigTab = 0;
char const *zOrigCol = 0;
#endif
assert( pExpr!=0 );
assert( pNC->pSrcList!=0 );
switch( pExpr->op ){
case TK_COLUMN: {
/* The expression is a column. Locate the table the column is being
** extracted from in NameContext.pSrcList. This table may be real
** database table or a subquery.
*/
Table *pTab = 0; /* Table structure column is extracted from */
Select *pS = 0; /* Select the column is extracted from */
int iCol = pExpr->iColumn; /* Index of column in pTab */
while( pNC && !pTab ){
SrcList *pTabList = pNC->pSrcList;
for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
if( j<pTabList->nSrc ){
pTab = pTabList->a[j].pTab;
pS = pTabList->a[j].pSelect;
}else{
pNC = pNC->pNext;
}
}
if( pTab==0 ){
/* At one time, code such as "SELECT new.x" within a trigger would
** cause this condition to run. Since then, we have restructured how
** trigger code is generated and so this condition is no longer
** possible. However, it can still be true for statements like
** the following:
**
** CREATE TABLE t1(col INTEGER);
** SELECT (SELECT t1.col) FROM FROM t1;
**
** when columnType() is called on the expression "t1.col" in the
** sub-select. In this case, set the column type to NULL, even
** though it should really be "INTEGER".
**
** This is not a problem, as the column type of "t1.col" is never
** used. When columnType() is called on the expression
** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
** branch below. */
break;
}
assert( pTab && pExpr->y.pTab==pTab );
if( pS ){
/* The "table" is actually a sub-select or a view in the FROM clause
** of the SELECT statement. Return the declaration type and origin
** data for the result-set column of the sub-select.
*/
if( iCol>=0 && iCol<pS->pEList->nExpr ){
/* If iCol is less than zero, then the expression requests the
** rowid of the sub-select or view. This expression is legal (see
** test case misc2.2.2) - it always evaluates to NULL.
*/
NameContext sNC;
Expr *p = pS->pEList->a[iCol].pExpr;
sNC.pSrcList = pS->pSrc;
sNC.pNext = pNC;
sNC.pParse = pNC->pParse;
zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
}
}else{
/* A real table or a CTE table */
assert( !pS );
#ifdef SQLITE_ENABLE_COLUMN_METADATA
if( iCol<0 ) iCol = pTab->iPKey;
assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zType = "INTEGER";
zOrigCol = "rowid";
}else{
zOrigCol = pTab->aCol[iCol].zName;
zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
}
zOrigTab = pTab->zName;
if( pNC->pParse && pTab->pSchema ){
int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
}
#else
assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zType = "INTEGER";
}else{
zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
}
#endif
}
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_SELECT: {
/* The expression is a sub-select. Return the declaration type and
** origin info for the single column in the result set of the SELECT
** statement.
*/
NameContext sNC;
Select *pS = pExpr->x.pSelect;
Expr *p = pS->pEList->a[0].pExpr;
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
sNC.pSrcList = pS->pSrc;
sNC.pNext = pNC;
sNC.pParse = pNC->pParse;
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
break;
}
#endif
}
#ifdef SQLITE_ENABLE_COLUMN_METADATA
if( pzOrigDb ){
assert( pzOrigTab && pzOrigCol );
*pzOrigDb = zOrigDb;
*pzOrigTab = zOrigTab;
*pzOrigCol = zOrigCol;
}
#endif
return zType;
}
/*
** Generate code that will tell the VDBE the declaration types of columns
** in the result set.
*/
static void generateColumnTypes(
Parse *pParse, /* Parser context */
SrcList *pTabList, /* List of tables */
ExprList *pEList /* Expressions defining the result set */
){
#ifndef SQLITE_OMIT_DECLTYPE
Vdbe *v = pParse->pVdbe;
int i;
NameContext sNC;
sNC.pSrcList = pTabList;
sNC.pParse = pParse;
sNC.pNext = 0;
for(i=0; i<pEList->nExpr; i++){
Expr *p = pEList->a[i].pExpr;
const char *zType;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
const char *zOrigDb = 0;
const char *zOrigTab = 0;
const char *zOrigCol = 0;
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
/* The vdbe must make its own copy of the column-type and other
** column specific strings, in case the schema is reset before this
** virtual machine is deleted.
*/
sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
#else
zType = columnType(&sNC, p, 0, 0, 0);
#endif
sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
}
#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
}
/*
** Compute the column names for a SELECT statement.
**
** The only guarantee that SQLite makes about column names is that if the
** column has an AS clause assigning it a name, that will be the name used.
** That is the only documented guarantee. However, countless applications
** developed over the years have made baseless assumptions about column names
** and will break if those assumptions changes. Hence, use extreme caution
** when modifying this routine to avoid breaking legacy.
**
** See Also: sqlite3ColumnsFromExprList()
**
** The PRAGMA short_column_names and PRAGMA full_column_names settings are
** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
** applications should operate this way. Nevertheless, we need to support the
** other modes for legacy:
**
** short=OFF, full=OFF: Column name is the text of the expression has it
** originally appears in the SELECT statement. In
** other words, the zSpan of the result expression.
**
** short=ON, full=OFF: (This is the default setting). If the result
** refers directly to a table column, then the
** result column name is just the table column
** name: COLUMN. Otherwise use zSpan.
**
** full=ON, short=ANY: If the result refers directly to a table column,
** then the result column name with the table name
** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
*/
static void generateColumnNames(
Parse *pParse, /* Parser context */
Select *pSelect /* Generate column names for this SELECT statement */
){
Vdbe *v = pParse->pVdbe;
int i;
Table *pTab;
SrcList *pTabList;
ExprList *pEList;
sqlite3 *db = pParse->db;
int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
#ifndef SQLITE_OMIT_EXPLAIN
/* If this is an EXPLAIN, skip this step */
if( pParse->explain ){
return;
}
#endif
if( pParse->colNamesSet ) return;
/* Column names are determined by the left-most term of a compound select */
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
pTabList = pSelect->pSrc;
pEList = pSelect->pEList;
assert( v!=0 );
assert( pTabList!=0 );
pParse->colNamesSet = 1;
fullName = (db->flags & SQLITE_FullColNames)!=0;
srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
sqlite3VdbeSetNumCols(v, pEList->nExpr);
for(i=0; i<pEList->nExpr; i++){
Expr *p = pEList->a[i].pExpr;
assert( p!=0 );
assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
if( pEList->a[i].zName ){
/* An AS clause always takes first priority */
char *zName = pEList->a[i].zName;
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
}else if( srcName && p->op==TK_COLUMN ){
char *zCol;
int iCol = p->iColumn;
pTab = p->y.pTab;
assert( pTab!=0 );
if( iCol<0 ) iCol = pTab->iPKey;
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zCol = "rowid";
}else{
zCol = pTab->aCol[iCol].zName;
}
if( fullName ){
char *zName = 0;
zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
}else{
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
}
}else{
const char *z = pEList->a[i].zSpan;
z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
}
}
generateColumnTypes(pParse, pTabList, pEList);
}
/*
** Given an expression list (which is really the list of expressions
** that form the result set of a SELECT statement) compute appropriate
** column names for a table that would hold the expression list.
**
** All column names will be unique.
**
** Only the column names are computed. Column.zType, Column.zColl,
** and other fields of Column are zeroed.
**
** Return SQLITE_OK on success. If a memory allocation error occurs,
** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
**
** The only guarantee that SQLite makes about column names is that if the
** column has an AS clause assigning it a name, that will be the name used.
** That is the only documented guarantee. However, countless applications
** developed over the years have made baseless assumptions about column names
** and will break if those assumptions changes. Hence, use extreme caution
** when modifying this routine to avoid breaking legacy.
**
** See Also: generateColumnNames()
*/
int sqlite3ColumnsFromExprList(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* Expr list from which to derive column names */
i16 *pnCol, /* Write the number of columns here */
Column **paCol /* Write the new column list here */
){
sqlite3 *db = pParse->db; /* Database connection */
int i, j; /* Loop counters */
u32 cnt; /* Index added to make the name unique */
Column *aCol, *pCol; /* For looping over result columns */
int nCol; /* Number of columns in the result set */
char *zName; /* Column name */
int nName; /* Size of name in zName[] */
Hash ht; /* Hash table of column names */
sqlite3HashInit(&ht);
if( pEList ){
nCol = pEList->nExpr;
aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
testcase( aCol==0 );
if( nCol>32767 ) nCol = 32767;
}else{
nCol = 0;
aCol = 0;
}
assert( nCol==(i16)nCol );
*pnCol = nCol;
*paCol = aCol;
for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
/* Get an appropriate name for the column
*/
if( (zName = pEList->a[i].zName)!=0 ){
/* If the column contains an "AS <name>" phrase, use <name> as the name */
}else{
Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);
while( pColExpr->op==TK_DOT ){
pColExpr = pColExpr->pRight;
assert( pColExpr!=0 );
}
if( pColExpr->op==TK_COLUMN ){
/* For columns use the column name name */
int iCol = pColExpr->iColumn;
Table *pTab = pColExpr->y.pTab;
assert( pTab!=0 );
if( iCol<0 ) iCol = pTab->iPKey;
zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
}else if( pColExpr->op==TK_ID ){
assert( !ExprHasProperty(pColExpr, EP_IntValue) );
zName = pColExpr->u.zToken;
}else{
/* Use the original text of the column expression as its name */
zName = pEList->a[i].zSpan;
}
}
if( zName ){
zName = sqlite3DbStrDup(db, zName);
}else{
zName = sqlite3MPrintf(db,"column%d",i+1);
}
/* Make sure the column name is unique. If the name is not unique,
** append an integer to the name so that it becomes unique.
*/
cnt = 0;
while( zName && sqlite3HashFind(&ht, zName)!=0 ){
nName = sqlite3Strlen30(zName);
if( nName>0 ){
for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
if( zName[j]==':' ) nName = j;
}
zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
}
pCol->zName = zName;
sqlite3ColumnPropertiesFromName(0, pCol);
if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
sqlite3OomFault(db);
}
}
sqlite3HashClear(&ht);
if( db->mallocFailed ){
for(j=0; j<i; j++){
sqlite3DbFree(db, aCol[j].zName);
}
sqlite3DbFree(db, aCol);
*paCol = 0;
*pnCol = 0;
return SQLITE_NOMEM_BKPT;
}
return SQLITE_OK;
}
/*
** Add type and collation information to a column list based on
** a SELECT statement.
**
** The column list presumably came from selectColumnNamesFromExprList().
** The column list has only names, not types or collations. This
** routine goes through and adds the types and collations.
**
** This routine requires that all identifiers in the SELECT
** statement be resolved.
*/
void sqlite3SelectAddColumnTypeAndCollation(
Parse *pParse, /* Parsing contexts */
Table *pTab, /* Add column type information to this table */
Select *pSelect, /* SELECT used to determine types and collations */
char aff /* Default affinity for columns */
){
sqlite3 *db = pParse->db;
NameContext sNC;
Column *pCol;
CollSeq *pColl;
int i;
Expr *p;
struct ExprList_item *a;
assert( pSelect!=0 );
assert( (pSelect->selFlags & SF_Resolved)!=0 );
assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
if( db->mallocFailed ) return;
memset(&sNC, 0, sizeof(sNC));
sNC.pSrcList = pSelect->pSrc;
a = pSelect->pEList->a;
for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
const char *zType;
int n, m;
p = a[i].pExpr;
zType = columnType(&sNC, p, 0, 0, 0);
/* pCol->szEst = ... // Column size est for SELECT tables never used */
pCol->affinity = sqlite3ExprAffinity(p);
if( zType ){
m = sqlite3Strlen30(zType);
n = sqlite3Strlen30(pCol->zName);
pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
if( pCol->zName ){
memcpy(&pCol->zName[n+1], zType, m+1);
pCol->colFlags |= COLFLAG_HASTYPE;
}
}
if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
pColl = sqlite3ExprCollSeq(pParse, p);
if( pColl && pCol->zColl==0 ){
pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
}
}
pTab->szTabRow = 1; /* Any non-zero value works */
}
/*
** Given a SELECT statement, generate a Table structure that describes
** the result set of that SELECT.
*/
Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
Table *pTab;
sqlite3 *db = pParse->db;
u64 savedFlags;
savedFlags = db->flags;
db->flags &= ~(u64)SQLITE_FullColNames;
db->flags |= SQLITE_ShortColNames;
sqlite3SelectPrep(pParse, pSelect, 0);
db->flags = savedFlags;
if( pParse->nErr ) return 0;
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
pTab = sqlite3DbMallocZero(db, sizeof(Table) );
if( pTab==0 ){
return 0;
}
pTab->nTabRef = 1;
pTab->zName = 0;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);
pTab->iPKey = -1;
if( db->mallocFailed ){
sqlite3DeleteTable(db, pTab);
return 0;
}
return pTab;
}
/*
** Get a VDBE for the given parser context. Create a new one if necessary.
** If an error occurs, return NULL and leave a message in pParse.
*/
Vdbe *sqlite3GetVdbe(Parse *pParse){
if( pParse->pVdbe ){
return pParse->pVdbe;
}
if( pParse->pToplevel==0
&& OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
){
pParse->okConstFactor = 1;
}
return sqlite3VdbeCreate(pParse);
}
/*
** Compute the iLimit and iOffset fields of the SELECT based on the
** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
** that appear in the original SQL statement after the LIMIT and OFFSET
** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
** are the integer memory register numbers for counters used to compute
** the limit and offset. If there is no limit and/or offset, then
** iLimit and iOffset are negative.
**
** This routine changes the values of iLimit and iOffset only if
** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
** and iOffset should have been preset to appropriate default values (zero)
** prior to calling this routine.
**
** The iOffset register (if it exists) is initialized to the value
** of the OFFSET. The iLimit register is initialized to LIMIT. Register
** iOffset+1 is initialized to LIMIT+OFFSET.
**
** Only if pLimit->pLeft!=0 do the limit registers get
** redefined. The UNION ALL operator uses this property to force
** the reuse of the same limit and offset registers across multiple
** SELECT statements.
*/
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
Vdbe *v = 0;
int iLimit = 0;
int iOffset;
int n;
Expr *pLimit = p->pLimit;
if( p->iLimit ) return;
/*
** "LIMIT -1" always shows all rows. There is some
** controversy about what the correct behavior should be.
** The current implementation interprets "LIMIT 0" to mean
** no rows.
*/
if( pLimit ){
assert( pLimit->op==TK_LIMIT );
assert( pLimit->pLeft!=0 );
p->iLimit = iLimit = ++pParse->nMem;
v = sqlite3GetVdbe(pParse);
assert( v!=0 );
if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
VdbeComment((v, "LIMIT counter"));
if( n==0 ){
sqlite3VdbeGoto(v, iBreak);
}else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
p->nSelectRow = sqlite3LogEst((u64)n);
p->selFlags |= SF_FixedLimit;
}
}else{
sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
VdbeComment((v, "LIMIT counter"));
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
}
if( pLimit->pRight ){
p->iOffset = iOffset = ++pParse->nMem;
pParse->nMem++; /* Allocate an extra register for limit+offset */
sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
VdbeComment((v, "OFFSET counter"));
sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
VdbeComment((v, "LIMIT+OFFSET"));
}
}
}
#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** Return the appropriate collating sequence for the iCol-th column of
** the result set for the compound-select statement "p". Return NULL if
** the column has no default collating sequence.
**
** The collating sequence for the compound select is taken from the
** left-most term of the select that has a collating sequence.
*/
static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
CollSeq *pRet;
if( p->pPrior ){
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
}else{
pRet = 0;
}
assert( iCol>=0 );
/* iCol must be less than p->pEList->nExpr. Otherwise an error would
** have been thrown during name resolution and we would not have gotten
** this far */
if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
}
return pRet;
}
/*
** The select statement passed as the second parameter is a compound SELECT
** with an ORDER BY clause. This function allocates and returns a KeyInfo
** structure suitable for implementing the ORDER BY.
**
** Space to hold the KeyInfo structure is obtained from malloc. The calling
** function is responsible for ensuring that this structure is eventually
** freed.
*/
static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
ExprList *pOrderBy = p->pOrderBy;
int nOrderBy = p->pOrderBy->nExpr;
sqlite3 *db = pParse->db;
KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
if( pRet ){
int i;
for(i=0; i<nOrderBy; i++){
struct ExprList_item *pItem = &pOrderBy->a[i];
Expr *pTerm = pItem->pExpr;
CollSeq *pColl;
if( pTerm->flags & EP_Collate ){
pColl = sqlite3ExprCollSeq(pParse, pTerm);
}else{
pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
if( pColl==0 ) pColl = db->pDfltColl;
pOrderBy->a[i].pExpr =
sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
}
assert( sqlite3KeyInfoIsWriteable(pRet) );
pRet->aColl[i] = pColl;
pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags;
}
}
return pRet;
}
#ifndef SQLITE_OMIT_CTE
/*
** This routine generates VDBE code to compute the content of a WITH RECURSIVE
** query of the form:
**
** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
** \___________/ \_______________/
** p->pPrior p
**
**
** There is exactly one reference to the recursive-table in the FROM clause
** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
**
** The setup-query runs once to generate an initial set of rows that go
** into a Queue table. Rows are extracted from the Queue table one by
** one. Each row extracted from Queue is output to pDest. Then the single
** extracted row (now in the iCurrent table) becomes the content of the
** recursive-table for a recursive-query run. The output of the recursive-query
** is added back into the Queue table. Then another row is extracted from Queue
** and the iteration continues until the Queue table is empty.
**
** If the compound query operator is UNION then no duplicate rows are ever
** inserted into the Queue table. The iDistinct table keeps a copy of all rows
** that have ever been inserted into Queue and causes duplicates to be
** discarded. If the operator is UNION ALL, then duplicates are allowed.
**
** If the query has an ORDER BY, then entries in the Queue table are kept in
** ORDER BY order and the first entry is extracted for each cycle. Without
** an ORDER BY, the Queue table is just a FIFO.
**
** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
** have been output to pDest. A LIMIT of zero means to output no rows and a
** negative LIMIT means to output all rows. If there is also an OFFSET clause
** with a positive value, then the first OFFSET outputs are discarded rather
** than being sent to pDest. The LIMIT count does not begin until after OFFSET
** rows have been skipped.
*/
static void generateWithRecursiveQuery(
Parse *pParse, /* Parsing context */
Select *p, /* The recursive SELECT to be coded */
SelectDest *pDest /* What to do with query results */
){
SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
Select *pSetup = p->pPrior; /* The setup query */
int addrTop; /* Top of the loop */
int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
int iCurrent = 0; /* The Current table */
int regCurrent; /* Register holding Current table */
int iQueue; /* The Queue table */
int iDistinct = 0; /* To ensure unique results if UNION */
int eDest = SRT_Fifo; /* How to write to Queue */
SelectDest destQueue; /* SelectDest targetting the Queue table */
int i; /* Loop counter */
int rc; /* Result code */
ExprList *pOrderBy; /* The ORDER BY clause */
Expr *pLimit; /* Saved LIMIT and OFFSET */
int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin ){
sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
return;
}
#endif
/* Obtain authorization to do a recursive query */
if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
/* Process the LIMIT and OFFSET clauses, if they exist */
addrBreak = sqlite3VdbeMakeLabel(pParse);
p->nSelectRow = 320; /* 4 billion rows */
computeLimitRegisters(pParse, p, addrBreak);
pLimit = p->pLimit;
regLimit = p->iLimit;
regOffset = p->iOffset;
p->pLimit = 0;
p->iLimit = p->iOffset = 0;
pOrderBy = p->pOrderBy;
/* Locate the cursor number of the Current table */
for(i=0; ALWAYS(i<pSrc->nSrc); i++){
if( pSrc->a[i].fg.isRecursive ){
iCurrent = pSrc->a[i].iCursor;
break;
}
}
/* Allocate cursors numbers for Queue and Distinct. The cursor number for
** the Distinct table must be exactly one greater than Queue in order
** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
iQueue = pParse->nTab++;
if( p->op==TK_UNION ){
eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
iDistinct = pParse->nTab++;
}else{
eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
}
sqlite3SelectDestInit(&destQueue, eDest, iQueue);
/* Allocate cursors for Current, Queue, and Distinct. */
regCurrent = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
if( pOrderBy ){
KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
(char*)pKeyInfo, P4_KEYINFO);
destQueue.pOrderBy = pOrderBy;
}else{
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
}
VdbeComment((v, "Queue table"));
if( iDistinct ){
p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
p->selFlags |= SF_UsesEphemeral;
}
/* Detach the ORDER BY clause from the compound SELECT */
p->pOrderBy = 0;
/* Store the results of the setup-query in Queue. */
pSetup->pNext = 0;
ExplainQueryPlan((pParse, 1, "SETUP"));
rc = sqlite3Select(pParse, pSetup, &destQueue);
pSetup->pNext = p;
if( rc ) goto end_of_recursive_query;
/* Find the next row in the Queue and output that row */
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
/* Transfer the next row in Queue over to Current */
sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
if( pOrderBy ){
sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
}else{
sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
}
sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
/* Output the single row in Current */
addrCont = sqlite3VdbeMakeLabel(pParse);
codeOffset(v, regOffset, addrCont);
selectInnerLoop(pParse, p, iCurrent,
0, 0, pDest, addrCont, addrBreak);
if( regLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
VdbeCoverage(v);
}
sqlite3VdbeResolveLabel(v, addrCont);
/* Execute the recursive SELECT taking the single row in Current as
** the value for the recursive-table. Store the results in the Queue.
*/
if( p->selFlags & SF_Aggregate ){
sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
}else{
p->pPrior = 0;
ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
sqlite3Select(pParse, p, &destQueue);
assert( p->pPrior==0 );
p->pPrior = pSetup;
}
/* Keep running the loop until the Queue is empty */
sqlite3VdbeGoto(v, addrTop);
sqlite3VdbeResolveLabel(v, addrBreak);
end_of_recursive_query:
sqlite3ExprListDelete(pParse->db, p->pOrderBy);
p->pOrderBy = pOrderBy;
p->pLimit = pLimit;
return;
}
#endif /* SQLITE_OMIT_CTE */
/* Forward references */
static int multiSelectOrderBy(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
);
/*
** Handle the special case of a compound-select that originates from a
** VALUES clause. By handling this as a special case, we avoid deep
** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
** on a VALUES clause.
**
** Because the Select object originates from a VALUES clause:
** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
** (2) All terms are UNION ALL
** (3) There is no ORDER BY clause
**
** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
*/
static int multiSelectValues(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int nRow = 1;
int rc = 0;
int bShowAll = p->pLimit==0;
assert( p->selFlags & SF_MultiValue );
do{
assert( p->selFlags & SF_Values );
assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
if( p->pWin ) return -1;
if( p->pPrior==0 ) break;
assert( p->pPrior->pNext==p );
p = p->pPrior;
nRow += bShowAll;
}while(1);
ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
nRow==1 ? "" : "S"));
while( p ){
selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
if( !bShowAll ) break;
p->nSelectRow = nRow;
p = p->pNext;
}
return rc;
}
/*
** This routine is called to process a compound query form from
** two or more separate queries using UNION, UNION ALL, EXCEPT, or
** INTERSECT
**
** "p" points to the right-most of the two queries. the query on the
** left is p->pPrior. The left query could also be a compound query
** in which case this routine will be called recursively.
**
** The results of the total query are to be written into a destination
** of type eDest with parameter iParm.
**
** Example 1: Consider a three-way compound SQL statement.
**
** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
**
** This statement is parsed up as follows:
**
** SELECT c FROM t3
** |
** `-----> SELECT b FROM t2
** |
** `------> SELECT a FROM t1
**
** The arrows in the diagram above represent the Select.pPrior pointer.
** So if this routine is called with p equal to the t3 query, then
** pPrior will be the t2 query. p->op will be TK_UNION in this case.
**
** Notice that because of the way SQLite parses compound SELECTs, the
** individual selects always group from left to right.
*/
static int multiSelect(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int rc = SQLITE_OK; /* Success code from a subroutine */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest dest; /* Alternative data destination */
Select *pDelete = 0; /* Chain of simple selects to delete */
sqlite3 *db; /* Database connection */
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
*/
assert( p && p->pPrior ); /* Calling function guarantees this much */
assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
assert( p->selFlags & SF_Compound );
db = pParse->db;
pPrior = p->pPrior;
dest = *pDest;
if( pPrior->pOrderBy || pPrior->pLimit ){
sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
rc = 1;
goto multi_select_end;
}
v = sqlite3GetVdbe(pParse);
assert( v!=0 ); /* The VDBE already created by calling function */
/* Create the destination temporary table if necessary
*/
if( dest.eDest==SRT_EphemTab ){
assert( p->pEList );
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
dest.eDest = SRT_Table;
}
/* Special handling for a compound-select that originates as a VALUES clause.
*/
if( p->selFlags & SF_MultiValue ){
rc = multiSelectValues(pParse, p, &dest);
if( rc>=0 ) goto multi_select_end;
rc = SQLITE_OK;
}
/* Make sure all SELECTs in the statement have the same number of elements
** in their result sets.
*/
assert( p->pEList && pPrior->pEList );
assert( p->pEList->nExpr==pPrior->pEList->nExpr );
#ifndef SQLITE_OMIT_CTE
if( p->selFlags & SF_Recursive ){
generateWithRecursiveQuery(pParse, p, &dest);
}else
#endif
/* Compound SELECTs that have an ORDER BY clause are handled separately.
*/
if( p->pOrderBy ){
return multiSelectOrderBy(pParse, p, pDest);
}else{
#ifndef SQLITE_OMIT_EXPLAIN
if( pPrior->pPrior==0 ){
ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
}
#endif
/* Generate code for the left and right SELECT statements.
*/
switch( p->op ){
case TK_ALL: {
int addr = 0;
int nLimit;
assert( !pPrior->pLimit );
pPrior->iLimit = p->iLimit;
pPrior->iOffset = p->iOffset;
pPrior->pLimit = p->pLimit;
rc = sqlite3Select(pParse, pPrior, &dest);
p->pLimit = 0;
if( rc ){
goto multi_select_end;
}
p->pPrior = 0;
p->iLimit = pPrior->iLimit;
p->iOffset = pPrior->iOffset;
if( p->iLimit ){
addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
VdbeComment((v, "Jump ahead if LIMIT reached"));
if( p->iOffset ){
sqlite3VdbeAddOp3(v, OP_OffsetLimit,
p->iLimit, p->iOffset+1, p->iOffset);
}
}
ExplainQueryPlan((pParse, 1, "UNION ALL"));
rc = sqlite3Select(pParse, p, &dest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
if( pPrior->pLimit
&& sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
&& nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
){
p->nSelectRow = sqlite3LogEst((u64)nLimit);
}
if( addr ){
sqlite3VdbeJumpHere(v, addr);
}
break;
}
case TK_EXCEPT:
case TK_UNION: {
int unionTab; /* Cursor number of the temp table holding result */
u8 op = 0; /* One of the SRT_ operations to apply to self */
int priorOp; /* The SRT_ operation to apply to prior selects */
Expr *pLimit; /* Saved values of p->nLimit */
int addr;
SelectDest uniondest;
testcase( p->op==TK_EXCEPT );
testcase( p->op==TK_UNION );
priorOp = SRT_Union;
if( dest.eDest==priorOp ){
/* We can reuse a temporary table generated by a SELECT to our
** right.
*/
assert( p->pLimit==0 ); /* Not allowed on leftward elements */
unionTab = dest.iSDParm;
}else{
/* We will need to create our own temporary table to hold the
** intermediate results.
*/
unionTab = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
}
/* Code the SELECT statements to our left
*/
assert( !pPrior->pOrderBy );
sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
rc = sqlite3Select(pParse, pPrior, &uniondest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT statement
*/
if( p->op==TK_EXCEPT ){
op = SRT_Except;
}else{
assert( p->op==TK_UNION );
op = SRT_Union;
}
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
uniondest.eDest = op;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &uniondest);
testcase( rc!=SQLITE_OK );
/* Query flattening in sqlite3Select() might refill p->pOrderBy.
** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
sqlite3ExprListDelete(db, p->pOrderBy);
pDelete = p->pPrior;
p->pPrior = pPrior;
p->pOrderBy = 0;
if( p->op==TK_UNION ){
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
p->iLimit = 0;
p->iOffset = 0;
/* Convert the data in the temporary table into whatever form
** it is that we currently need.
*/
assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
assert( p->pEList || db->mallocFailed );
if( dest.eDest!=priorOp && db->mallocFailed==0 ){
int iCont, iBreak, iStart;
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
iStart = sqlite3VdbeCurrentAddr(v);
selectInnerLoop(pParse, p, unionTab,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
}
break;
}
default: assert( p->op==TK_INTERSECT ); {
int tab1, tab2;
int iCont, iBreak, iStart;
Expr *pLimit;
int addr;
SelectDest intersectdest;
int r1;
/* INTERSECT is different from the others since it requires
** two temporary tables. Hence it has its own case. Begin
** by allocating the tables we will need.
*/
tab1 = pParse->nTab++;
tab2 = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
/* Code the SELECTs to our left into temporary table "tab1".
*/
sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
rc = sqlite3Select(pParse, pPrior, &intersectdest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT into temporary table "tab2"
*/
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
assert( p->addrOpenEphm[1] == -1 );
p->addrOpenEphm[1] = addr;
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
intersectdest.iSDParm = tab2;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &intersectdest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
if( p->nSelectRow>pPrior->nSelectRow ){
p->nSelectRow = pPrior->nSelectRow;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
/* Generate code to take the intersection of the two temporary
** tables.
*/
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
r1 = sqlite3GetTempReg(pParse);
iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r1);
selectInnerLoop(pParse, p, tab1,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
break;
}
}
#ifndef SQLITE_OMIT_EXPLAIN
if( p->pNext==0 ){
ExplainQueryPlanPop(pParse);
}
#endif
}
if( pParse->nErr ) goto multi_select_end;
/* Compute collating sequences used by
** temporary tables needed to implement the compound select.
** Attach the KeyInfo structure to all temporary tables.
**
** This section is run by the right-most SELECT statement only.
** SELECT statements to the left always skip this part. The right-most
** SELECT might also skip this part if it has no ORDER BY clause and
** no temp tables are required.
*/
if( p->selFlags & SF_UsesEphemeral ){
int i; /* Loop counter */
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
Select *pLoop; /* For looping through SELECT statements */
CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
int nCol; /* Number of columns in result set */
assert( p->pNext==0 );
nCol = p->pEList->nExpr;
pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
if( !pKeyInfo ){
rc = SQLITE_NOMEM_BKPT;
goto multi_select_end;
}
for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
*apColl = multiSelectCollSeq(pParse, p, i);
if( 0==*apColl ){
*apColl = db->pDfltColl;
}
}
for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
for(i=0; i<2; i++){
int addr = pLoop->addrOpenEphm[i];
if( addr<0 ){
/* If [0] is unused then [1] is also unused. So we can
** always safely abort as soon as the first unused slot is found */
assert( pLoop->addrOpenEphm[1]<0 );
break;
}
sqlite3VdbeChangeP2(v, addr, nCol);
sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
P4_KEYINFO);
pLoop->addrOpenEphm[i] = -1;
}
}
sqlite3KeyInfoUnref(pKeyInfo);
}
multi_select_end:
pDest->iSdst = dest.iSdst;
pDest->nSdst = dest.nSdst;
sqlite3SelectDelete(db, pDelete);
return rc;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
/*
** Error message for when two or more terms of a compound select have different
** size result sets.
*/
void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
if( p->selFlags & SF_Values ){
sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
}else{
sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
" do not have the same number of result columns", selectOpName(p->op));
}
}
/*
** Code an output subroutine for a coroutine implementation of a
** SELECT statment.
**
** The data to be output is contained in pIn->iSdst. There are
** pIn->nSdst columns to be output. pDest is where the output should
** be sent.
**
** regReturn is the number of the register holding the subroutine
** return address.
**
** If regPrev>0 then it is the first register in a vector that
** records the previous output. mem[regPrev] is a flag that is false
** if there has been no previous output. If regPrev>0 then code is
** generated to suppress duplicates. pKeyInfo is used for comparing
** keys.
**
** If the LIMIT found in p->iLimit is reached, jump immediately to
** iBreak.
*/
static int generateOutputSubroutine(
Parse *pParse, /* Parsing context */
Select *p, /* The SELECT statement */
SelectDest *pIn, /* Coroutine supplying data */
SelectDest *pDest, /* Where to send the data */
int regReturn, /* The return address register */
int regPrev, /* Previous result register. No uniqueness if 0 */
KeyInfo *pKeyInfo, /* For comparing with previous entry */
int iBreak /* Jump here if we hit the LIMIT */
){
Vdbe *v = pParse->pVdbe;
int iContinue;
int addr;
addr = sqlite3VdbeCurrentAddr(v);
iContinue = sqlite3VdbeMakeLabel(pParse);
/* Suppress duplicates for UNION, EXCEPT, and INTERSECT
*/
if( regPrev ){
int addr1, addr2;
addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
}
if( pParse->db->mallocFailed ) return 0;
/* Suppress the first OFFSET entries if there is an OFFSET clause
*/
codeOffset(v, p->iOffset, iContinue);
assert( pDest->eDest!=SRT_Exists );
assert( pDest->eDest!=SRT_Table );
switch( pDest->eDest ){
/* Store the result as data using a unique key.
*/
case SRT_EphemTab: {
int r1 = sqlite3GetTempReg(pParse);
int r2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3ReleaseTempReg(pParse, r2);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
/* If we are creating a set for an "expr IN (SELECT ...)".
*/
case SRT_Set: {
int r1;
testcase( pIn->nSdst>1 );
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
r1, pDest->zAffSdst, pIn->nSdst);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
pIn->iSdst, pIn->nSdst);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
/* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell and break out
** of the scan loop. Note that the select might return multiple columns
** if it is the RHS of a row-value IN operator.
*/
case SRT_Mem: {
if( pParse->nErr==0 ){
testcase( pIn->nSdst>1 );
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
}
/* The LIMIT clause will jump out of the loop for us */
break;
}
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
/* The results are stored in a sequence of registers
** starting at pDest->iSdst. Then the co-routine yields.
*/
case SRT_Coroutine: {
if( pDest->iSdst==0 ){
pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
pDest->nSdst = pIn->nSdst;
}
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
break;
}
/* If none of the above, then the result destination must be
** SRT_Output. This routine is never called with any other
** destination other than the ones handled above or SRT_Output.
**
** For SRT_Output, results are stored in a sequence of registers.
** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
** return the next row of result.
*/
default: {
assert( pDest->eDest==SRT_Output );
sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
break;
}
}
/* Jump to the end of the loop if the LIMIT is reached.
*/
if( p->iLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
}
/* Generate the subroutine return
*/
sqlite3VdbeResolveLabel(v, iContinue);
sqlite3VdbeAddOp1(v, OP_Return, regReturn);
return addr;
}
/*
** Alternative compound select code generator for cases when there
** is an ORDER BY clause.
**
** We assume a query of the following form:
**
** <selectA> <operator> <selectB> ORDER BY <orderbylist>
**
** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
** is to code both <selectA> and <selectB> with the ORDER BY clause as
** co-routines. Then run the co-routines in parallel and merge the results
** into the output. In addition to the two coroutines (called selectA and
** selectB) there are 7 subroutines:
**
** outA: Move the output of the selectA coroutine into the output
** of the compound query.
**
** outB: Move the output of the selectB coroutine into the output
** of the compound query. (Only generated for UNION and
** UNION ALL. EXCEPT and INSERTSECT never output a row that
** appears only in B.)
**
** AltB: Called when there is data from both coroutines and A<B.
**
** AeqB: Called when there is data from both coroutines and A==B.
**
** AgtB: Called when there is data from both coroutines and A>B.
**
** EofA: Called when data is exhausted from selectA.
**
** EofB: Called when data is exhausted from selectB.
**
** The implementation of the latter five subroutines depend on which
** <operator> is used:
**
**
** UNION ALL UNION EXCEPT INTERSECT
** ------------- ----------------- -------------- -----------------
** AltB: outA, nextA outA, nextA outA, nextA nextA
**
** AeqB: outA, nextA nextA nextA outA, nextA
**
** AgtB: outB, nextB outB, nextB nextB nextB
**
** EofA: outB, nextB outB, nextB halt halt
**
** EofB: outA, nextA outA, nextA outA, nextA halt
**
** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
** causes an immediate jump to EofA and an EOF on B following nextB causes
** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
** following nextX causes a jump to the end of the select processing.
**
** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
** within the output subroutine. The regPrev register set holds the previously
** output value. A comparison is made against this value and the output
** is skipped if the next results would be the same as the previous.
**
** The implementation plan is to implement the two coroutines and seven
** subroutines first, then put the control logic at the bottom. Like this:
**
** goto Init
** coA: coroutine for left query (A)
** coB: coroutine for right query (B)
** outA: output one row of A
** outB: output one row of B (UNION and UNION ALL only)
** EofA: ...
** EofB: ...
** AltB: ...
** AeqB: ...
** AgtB: ...
** Init: initialize coroutine registers
** yield coA
** if eof(A) goto EofA
** yield coB
** if eof(B) goto EofB
** Cmpr: Compare A, B
** Jump AltB, AeqB, AgtB
** End: ...
**
** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
** actually called using Gosub and they do not Return. EofA and EofB loop
** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
** and AgtB jump to either L2 or to one of EofA or EofB.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
static int multiSelectOrderBy(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int i, j; /* Loop counters */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest destA; /* Destination for coroutine A */
SelectDest destB; /* Destination for coroutine B */
int regAddrA; /* Address register for select-A coroutine */
int regAddrB; /* Address register for select-B coroutine */
int addrSelectA; /* Address of the select-A coroutine */
int addrSelectB; /* Address of the select-B coroutine */
int regOutA; /* Address register for the output-A subroutine */
int regOutB; /* Address register for the output-B subroutine */
int addrOutA; /* Address of the output-A subroutine */
int addrOutB = 0; /* Address of the output-B subroutine */
int addrEofA; /* Address of the select-A-exhausted subroutine */
int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
int addrEofB; /* Address of the select-B-exhausted subroutine */
int addrAltB; /* Address of the A<B subroutine */
int addrAeqB; /* Address of the A==B subroutine */
int addrAgtB; /* Address of the A>B subroutine */
int regLimitA; /* Limit register for select-A */
int regLimitB; /* Limit register for select-A */
int regPrev; /* A range of registers to hold previous output */
int savedLimit; /* Saved value of p->iLimit */
int savedOffset; /* Saved value of p->iOffset */
int labelCmpr; /* Label for the start of the merge algorithm */
int labelEnd; /* Label for the end of the overall SELECT stmt */
int addr1; /* Jump instructions that get retargetted */
int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
KeyInfo *pKeyMerge; /* Comparison information for merging rows */
sqlite3 *db; /* Database connection */
ExprList *pOrderBy; /* The ORDER BY clause */
int nOrderBy; /* Number of terms in the ORDER BY clause */
int *aPermute; /* Mapping from ORDER BY terms to result set columns */
assert( p->pOrderBy!=0 );
assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
db = pParse->db;
v = pParse->pVdbe;
assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
labelEnd = sqlite3VdbeMakeLabel(pParse);
labelCmpr = sqlite3VdbeMakeLabel(pParse);
/* Patch up the ORDER BY clause
*/
op = p->op;
pPrior = p->pPrior;
assert( pPrior->pOrderBy==0 );
pOrderBy = p->pOrderBy;
assert( pOrderBy );
nOrderBy = pOrderBy->nExpr;
/* For operators other than UNION ALL we have to make sure that
** the ORDER BY clause covers every term of the result set. Add
** terms to the ORDER BY clause as necessary.
*/
if( op!=TK_ALL ){
for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
struct ExprList_item *pItem;
for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
assert( pItem->u.x.iOrderByCol>0 );
if( pItem->u.x.iOrderByCol==i ) break;
}
if( j==nOrderBy ){
Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
if( pNew==0 ) return SQLITE_NOMEM_BKPT;
pNew->flags |= EP_IntValue;
pNew->u.iValue = i;
p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
}
}
}
/* Compute the comparison permutation and keyinfo that is used with
** the permutation used to determine if the next
** row of results comes from selectA or selectB. Also add explicit
** collations to the ORDER BY clause terms so that when the subqueries
** to the right and the left are evaluated, they use the correct
** collation.
*/
aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
if( aPermute ){
struct ExprList_item *pItem;
aPermute[0] = nOrderBy;
for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
assert( pItem->u.x.iOrderByCol>0 );
assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
aPermute[i] = pItem->u.x.iOrderByCol - 1;
}
pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
}else{
pKeyMerge = 0;
}
/* Reattach the ORDER BY clause to the query.
*/
p->pOrderBy = pOrderBy;
pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
/* Allocate a range of temporary registers and the KeyInfo needed
** for the logic that removes duplicate result rows when the
** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
*/
if( op==TK_ALL ){
regPrev = 0;
}else{
int nExpr = p->pEList->nExpr;
assert( nOrderBy>=nExpr || db->mallocFailed );
regPrev = pParse->nMem+1;
pParse->nMem += nExpr+1;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
if( pKeyDup ){
assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
for(i=0; i<nExpr; i++){
pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
pKeyDup->aSortFlags[i] = 0;
}
}
}
/* Separate the left and the right query from one another
*/
p->pPrior = 0;
pPrior->pNext = 0;
sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
if( pPrior->pPrior==0 ){
sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
}
/* Compute the limit registers */
computeLimitRegisters(pParse, p, labelEnd);
if( p->iLimit && op==TK_ALL ){
regLimitA = ++pParse->nMem;
regLimitB = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
regLimitA);
sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
}else{
regLimitA = regLimitB = 0;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = 0;
regAddrA = ++pParse->nMem;
regAddrB = ++pParse->nMem;
regOutA = ++pParse->nMem;
regOutB = ++pParse->nMem;
sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
/* Generate a coroutine to evaluate the SELECT statement to the
** left of the compound operator - the "A" select.
*/
addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
VdbeComment((v, "left SELECT"));
pPrior->iLimit = regLimitA;
ExplainQueryPlan((pParse, 1, "LEFT"));
sqlite3Select(pParse, pPrior, &destA);
sqlite3VdbeEndCoroutine(v, regAddrA);
sqlite3VdbeJumpHere(v, addr1);
/* Generate a coroutine to evaluate the SELECT statement on
** the right - the "B" select
*/
addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
VdbeComment((v, "right SELECT"));
savedLimit = p->iLimit;
savedOffset = p->iOffset;
p->iLimit = regLimitB;
p->iOffset = 0;
ExplainQueryPlan((pParse, 1, "RIGHT"));
sqlite3Select(pParse, p, &destB);
p->iLimit = savedLimit;
p->iOffset = savedOffset;
sqlite3VdbeEndCoroutine(v, regAddrB);
/* Generate a subroutine that outputs the current row of the A
** select as the next output row of the compound select.
*/
VdbeNoopComment((v, "Output routine for A"));
addrOutA = generateOutputSubroutine(pParse,
p, &destA, pDest, regOutA,
regPrev, pKeyDup, labelEnd);
/* Generate a subroutine that outputs the current row of the B
** select as the next output row of the compound select.
*/
if( op==TK_ALL || op==TK_UNION ){
VdbeNoopComment((v, "Output routine for B"));
addrOutB = generateOutputSubroutine(pParse,
p, &destB, pDest, regOutB,
regPrev, pKeyDup, labelEnd);
}
sqlite3KeyInfoUnref(pKeyDup);
/* Generate a subroutine to run when the results from select A
** are exhausted and only data in select B remains.
*/
if( op==TK_EXCEPT || op==TK_INTERSECT ){
addrEofA_noB = addrEofA = labelEnd;
}else{
VdbeNoopComment((v, "eof-A subroutine"));
addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
VdbeCoverage(v);
sqlite3VdbeGoto(v, addrEofA);
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
/* Generate a subroutine to run when the results from select B
** are exhausted and only data in select A remains.
*/
if( op==TK_INTERSECT ){
addrEofB = addrEofA;
if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
}else{
VdbeNoopComment((v, "eof-B subroutine"));
addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
sqlite3VdbeGoto(v, addrEofB);
}
/* Generate code to handle the case of A<B
*/
VdbeNoopComment((v, "A-lt-B subroutine"));
addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
/* Generate code to handle the case of A==B
*/
if( op==TK_ALL ){
addrAeqB = addrAltB;
}else if( op==TK_INTERSECT ){
addrAeqB = addrAltB;
addrAltB++;
}else{
VdbeNoopComment((v, "A-eq-B subroutine"));
addrAeqB =
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
}
/* Generate code to handle the case of A>B
*/
VdbeNoopComment((v, "A-gt-B subroutine"));
addrAgtB = sqlite3VdbeCurrentAddr(v);
if( op==TK_ALL || op==TK_UNION ){
sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
}
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
/* This code runs once to initialize everything.
*/
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
/* Implement the main merge loop
*/
sqlite3VdbeResolveLabel(v, labelCmpr);
sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
(char*)pKeyMerge, P4_KEYINFO);
sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
/* Jump to the this point in order to terminate the query.
*/
sqlite3VdbeResolveLabel(v, labelEnd);
/* Reassembly the compound query so that it will be freed correctly
** by the calling function */
if( p->pPrior ){
sqlite3SelectDelete(db, p->pPrior);
}
p->pPrior = pPrior;
pPrior->pNext = p;
/*** TBD: Insert subroutine calls to close cursors on incomplete
**** subqueries ****/
ExplainQueryPlanPop(pParse);
return pParse->nErr!=0;
}
#endif
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* An instance of the SubstContext object describes an substitution edit
** to be performed on a parse tree.
**
** All references to columns in table iTable are to be replaced by corresponding
** expressions in pEList.
*/
typedef struct SubstContext {
Parse *pParse; /* The parsing context */
int iTable; /* Replace references to this table */
int iNewTable; /* New table number */
int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
ExprList *pEList; /* Replacement expressions */
} SubstContext;
/* Forward Declarations */
static void substExprList(SubstContext*, ExprList*);
static void substSelect(SubstContext*, Select*, int);
/*
** Scan through the expression pExpr. Replace every reference to
** a column in table number iTable with a copy of the iColumn-th
** entry in pEList. (But leave references to the ROWID column
** unchanged.)
**
** This routine is part of the flattening procedure. A subquery
** whose result set is defined by pEList appears as entry in the
** FROM clause of a SELECT such that the VDBE cursor assigned to that
** FORM clause entry is iTable. This routine makes the necessary
** changes to pExpr so that it refers directly to the source table
** of the subquery rather the result set of the subquery.
*/
static Expr *substExpr(
SubstContext *pSubst, /* Description of the substitution */
Expr *pExpr /* Expr in which substitution occurs */
){
if( pExpr==0 ) return 0;
if( ExprHasProperty(pExpr, EP_FromJoin)
&& pExpr->iRightJoinTable==pSubst->iTable
){
pExpr->iRightJoinTable = pSubst->iNewTable;
}
if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
if( pExpr->iColumn<0 ){
pExpr->op = TK_NULL;
}else{
Expr *pNew;
Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
Expr ifNullRow;
assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
assert( pExpr->pRight==0 );
if( sqlite3ExprIsVector(pCopy) ){
sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
}else{
sqlite3 *db = pSubst->pParse->db;
if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
memset(&ifNullRow, 0, sizeof(ifNullRow));
ifNullRow.op = TK_IF_NULL_ROW;
ifNullRow.pLeft = pCopy;
ifNullRow.iTable = pSubst->iNewTable;
pCopy = &ifNullRow;
}
testcase( ExprHasProperty(pCopy, EP_Subquery) );
pNew = sqlite3ExprDup(db, pCopy, 0);
if( pNew && pSubst->isLeftJoin ){
ExprSetProperty(pNew, EP_CanBeNull);
}
if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
pNew->iRightJoinTable = pExpr->iRightJoinTable;
ExprSetProperty(pNew, EP_FromJoin);
}
sqlite3ExprDelete(db, pExpr);
pExpr = pNew;
/* Ensure that the expression now has an implicit collation sequence,
** just as it did when it was a column of a view or sub-query. */
if( pExpr ){
if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
(pColl ? pColl->zName : "BINARY")
);
}
ExprClearProperty(pExpr, EP_Collate);
}
}
}
}else{
if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
pExpr->iTable = pSubst->iNewTable;
}
pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
pExpr->pRight = substExpr(pSubst, pExpr->pRight);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
substSelect(pSubst, pExpr->x.pSelect, 1);
}else{
substExprList(pSubst, pExpr->x.pList);
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
Window *pWin = pExpr->y.pWin;
pWin->pFilter = substExpr(pSubst, pWin->pFilter);
substExprList(pSubst, pWin->pPartition);
substExprList(pSubst, pWin->pOrderBy);
}
#endif
}
return pExpr;
}
static void substExprList(
SubstContext *pSubst, /* Description of the substitution */
ExprList *pList /* List to scan and in which to make substitutes */
){
int i;
if( pList==0 ) return;
for(i=0; i<pList->nExpr; i++){
pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
}
}
static void substSelect(
SubstContext *pSubst, /* Description of the substitution */
Select *p, /* SELECT statement in which to make substitutions */
int doPrior /* Do substitutes on p->pPrior too */
){
SrcList *pSrc;
struct SrcList_item *pItem;
int i;
if( !p ) return;
do{
substExprList(pSubst, p->pEList);
substExprList(pSubst, p->pGroupBy);
substExprList(pSubst, p->pOrderBy);
p->pHaving = substExpr(pSubst, p->pHaving);
p->pWhere = substExpr(pSubst, p->pWhere);
pSrc = p->pSrc;
assert( pSrc!=0 );
for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
substSelect(pSubst, pItem->pSelect, 1);
if( pItem->fg.isTabFunc ){
substExprList(pSubst, pItem->u1.pFuncArg);
}
}
}while( doPrior && (p = p->pPrior)!=0 );
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** This routine attempts to flatten subqueries as a performance optimization.
** This routine returns 1 if it makes changes and 0 if no flattening occurs.
**
** To understand the concept of flattening, consider the following
** query:
**
** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
**
** The default way of implementing this query is to execute the
** subquery first and store the results in a temporary table, then
** run the outer query on that temporary table. This requires two
** passes over the data. Furthermore, because the temporary table
** has no indices, the WHERE clause on the outer query cannot be
** optimized.
**
** This routine attempts to rewrite queries such as the above into
** a single flat select, like this:
**
** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
**
** The code generated for this simplification gives the same result
** but only has to scan the data once. And because indices might
** exist on the table t1, a complete scan of the data might be
** avoided.
**
** Flattening is subject to the following constraints:
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** The subquery and the outer query cannot both be aggregates.
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** (2) If the subquery is an aggregate then
** (2a) the outer query must not be a join and
** (2b) the outer query must not use subqueries
** other than the one FROM-clause subquery that is a candidate
** for flattening. (This is due to ticket [2f7170d73bf9abf80]
** from 2015-02-09.)
**
** (3) If the subquery is the right operand of a LEFT JOIN then
** (3a) the subquery may not be a join and
** (3b) the FROM clause of the subquery may not contain a virtual
** table and
** (3c) the outer query may not be an aggregate.
** (3d) the outer query may not be DISTINCT.
**
** (4) The subquery can not be DISTINCT.
**
** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
** sub-queries that were excluded from this optimization. Restriction
** (4) has since been expanded to exclude all DISTINCT subqueries.
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** If the subquery is aggregate, the outer query may not be DISTINCT.
**
** (7) The subquery must have a FROM clause. TODO: For subqueries without
** A FROM clause, consider adding a FROM clause with the special
** table sqlite_once that consists of a single row containing a
** single NULL.
**
** (8) If the subquery uses LIMIT then the outer query may not be a join.
**
** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
**
** (**) Restriction (10) was removed from the code on 2005-02-05 but we
** accidently carried the comment forward until 2014-09-15. Original
** constraint: "If the subquery is aggregate then the outer query
** may not use LIMIT."
**
** (11) The subquery and the outer query may not both have ORDER BY clauses.
**
** (**) Not implemented. Subsumed into restriction (3). Was previously
** a separate restriction deriving from ticket #350.
**
** (13) The subquery and outer query may not both use LIMIT.
**
** (14) The subquery may not use OFFSET.
**
** (15) If the outer query is part of a compound select, then the
** subquery may not use LIMIT.
** (See ticket #2339 and ticket [02a8e81d44]).
**
** (16) If the outer query is aggregate, then the subquery may not
** use ORDER BY. (Ticket #2942) This used to not matter
** until we introduced the group_concat() function.
**
** (17) If the subquery is a compound select, then
** (17a) all compound operators must be a UNION ALL, and
** (17b) no terms within the subquery compound may be aggregate
** or DISTINCT, and
** (17c) every term within the subquery compound must have a FROM clause
** (17d) the outer query may not be
** (17d1) aggregate, or
** (17d2) DISTINCT, or
** (17d3) a join.
**
** The parent and sub-query may contain WHERE clauses. Subject to
** rules (11), (13) and (14), they may also contain ORDER BY,
** LIMIT and OFFSET clauses. The subquery cannot use any compound
** operator other than UNION ALL because all the other compound
** operators have an implied DISTINCT which is disallowed by
** restriction (4).
**
** Also, each component of the sub-query must return the same number
** of result columns. This is actually a requirement for any compound
** SELECT statement, but all the code here does is make sure that no
** such (illegal) sub-query is flattened. The caller will detect the
** syntax error and return a detailed message.
**
** (18) If the sub-query is a compound select, then all terms of the
** ORDER BY clause of the parent must be simple references to
** columns of the sub-query.
**
** (19) If the subquery uses LIMIT then the outer query may not
** have a WHERE clause.
**
** (20) If the sub-query is a compound select, then it must not use
** an ORDER BY clause. Ticket #3773. We could relax this constraint
** somewhat by saying that the terms of the ORDER BY clause must
** appear as unmodified result columns in the outer query. But we
** have other optimizations in mind to deal with that case.
**
** (21) If the subquery uses LIMIT then the outer query may not be
** DISTINCT. (See ticket [752e1646fc]).
**
** (22) The subquery may not be a recursive CTE.
**
** (**) Subsumed into restriction (17d3). Was: If the outer query is
** a recursive CTE, then the sub-query may not be a compound query.
** This restriction is because transforming the
** parent to a compound query confuses the code that handles
** recursive queries in multiSelect().
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** The subquery may not be an aggregate that uses the built-in min() or
** or max() functions. (Without this restriction, a query like:
** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
** return the value X for which Y was maximal.)
**
** (25) If either the subquery or the parent query contains a window
** function in the select list or ORDER BY clause, flattening
** is not attempted.
**
**
** In this routine, the "p" parameter is a pointer to the outer query.
** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
** uses aggregates.
**
** If flattening is not attempted, this routine is a no-op and returns 0.
** If flattening is attempted this routine returns 1.
**
** All of the expression analysis must occur on both the outer query and
** the subquery before this routine runs.
*/
static int flattenSubquery(
Parse *pParse, /* Parsing context */
Select *p, /* The parent or outer SELECT statement */
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
int isAgg /* True if outer SELECT uses aggregate functions */
){
const char *zSavedAuthContext = pParse->zAuthContext;
Select *pParent; /* Current UNION ALL term of the other query */
Select *pSub; /* The inner query or "subquery" */
Select *pSub1; /* Pointer to the rightmost select in sub-query */
SrcList *pSrc; /* The FROM clause of the outer query */
SrcList *pSubSrc; /* The FROM clause of the subquery */
int iParent; /* VDBE cursor number of the pSub result set temp table */
int iNewParent = -1;/* Replacement table for iParent */
int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
int i; /* Loop counter */
Expr *pWhere; /* The WHERE clause */
struct SrcList_item *pSubitem; /* The subquery */
sqlite3 *db = pParse->db;
/* Check to see if flattening is permitted. Return 0 if not.
*/
assert( p!=0 );
assert( p->pPrior==0 );
if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
pSrc = p->pSrc;
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
pSubitem = &pSrc->a[iFrom];
iParent = pSubitem->iCursor;
pSub = pSubitem->pSelect;
assert( pSub!=0 );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
#endif
pSubSrc = pSub->pSrc;
assert( pSubSrc );
/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
** because they could be computed at compile-time. But when LIMIT and OFFSET
** became arbitrary expressions, we were forced to add restrictions (13)
** and (14). */
if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
return 0; /* Restriction (15) */
}
if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
return 0; /* Restrictions (8)(9) */
}
if( p->pOrderBy && pSub->pOrderBy ){
return 0; /* Restriction (11) */
}
if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
return 0; /* Restriction (21) */
}
if( pSub->selFlags & (SF_Recursive) ){
return 0; /* Restrictions (22) */
}
/*
** If the subquery is the right operand of a LEFT JOIN, then the
** subquery may not be a join itself (3a). Example of why this is not
** allowed:
**
** t1 LEFT OUTER JOIN (t2 JOIN t3)
**
** If we flatten the above, we would get
**
** (t1 LEFT OUTER JOIN t2) JOIN t3
**
** which is not at all the same thing.
**
** If the subquery is the right operand of a LEFT JOIN, then the outer
** query cannot be an aggregate. (3c) This is an artifact of the way
** aggregates are processed - there is no mechanism to determine if
** the LEFT JOIN table should be all-NULL.
**
** See also tickets #306, #350, and #3300.
*/
if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
isLeftJoin = 1;
if( pSubSrc->nSrc>1 /* (3a) */
|| isAgg /* (3b) */
|| IsVirtual(pSubSrc->a[0].pTab) /* (3c) */
|| (p->selFlags & SF_Distinct)!=0 /* (3d) */
){
return 0;
}
}
#ifdef SQLITE_EXTRA_IFNULLROW
else if( iFrom>0 && !isAgg ){
/* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
** every reference to any result column from subquery in a join, even
** though they are not necessary. This will stress-test the OP_IfNullRow
** opcode. */
isLeftJoin = -1;
}
#endif
/* Restriction (17): If the sub-query is a compound SELECT, then it must
** use only the UNION ALL operator. And none of the simple select queries
** that make up the compound SELECT are allowed to be aggregate or distinct
** queries.
*/
if( pSub->pPrior ){
if( pSub->pOrderBy ){
return 0; /* Restriction (20) */
}
if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
return 0; /* (17d1), (17d2), or (17d3) */
}
for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
assert( pSub->pSrc!=0 );
assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
|| (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
|| pSub1->pSrc->nSrc<1 /* (17c) */
){
return 0;
}
testcase( pSub1->pSrc->nSrc>1 );
}
/* Restriction (18). */
if( p->pOrderBy ){
int ii;
for(ii=0; ii<p->pOrderBy->nExpr; ii++){
if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
}
}
}
/* Ex-restriction (23):
** The only way that the recursive part of a CTE can contain a compound
** subquery is for the subquery to be one term of a join. But if the
** subquery is a join, then the flattening has already been stopped by
** restriction (17d3)
*/
assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
/***** If we reach this point, flattening is permitted. *****/
SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
pSub->selId, pSub, iFrom));
/* Authorize the subquery */
pParse->zAuthContext = pSubitem->zName;
TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
testcase( i==SQLITE_DENY );
pParse->zAuthContext = zSavedAuthContext;
/* If the sub-query is a compound SELECT statement, then (by restrictions
** 17 and 18 above) it must be a UNION ALL and the parent query must
** be of the form:
**
** SELECT <expr-list> FROM (<sub-query>) <where-clause>
**
** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
** OFFSET clauses and joins them to the left-hand-side of the original
** using UNION ALL operators. In this case N is the number of simple
** select statements in the compound sub-query.
**
** Example:
**
** SELECT a+1 FROM (
** SELECT x FROM tab
** UNION ALL
** SELECT y FROM tab
** UNION ALL
** SELECT abs(z*2) FROM tab2
** ) WHERE a!=5 ORDER BY 1
**
** Transformed into:
**
** SELECT x+1 FROM tab WHERE x+1!=5
** UNION ALL
** SELECT y+1 FROM tab WHERE y+1!=5
** UNION ALL
** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
** ORDER BY 1
**
** We call this the "compound-subquery flattening".
*/
for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
Select *pNew;
ExprList *pOrderBy = p->pOrderBy;
Expr *pLimit = p->pLimit;
Select *pPrior = p->pPrior;
p->pOrderBy = 0;
p->pSrc = 0;
p->pPrior = 0;
p->pLimit = 0;
pNew = sqlite3SelectDup(db, p, 0);
p->pLimit = pLimit;
p->pOrderBy = pOrderBy;
p->pSrc = pSrc;
p->op = TK_ALL;
if( pNew==0 ){
p->pPrior = pPrior;
}else{
pNew->pPrior = pPrior;
if( pPrior ) pPrior->pNext = pNew;
pNew->pNext = p;
p->pPrior = pNew;
SELECTTRACE(2,pParse,p,("compound-subquery flattener"
" creates %u as peer\n",pNew->selId));
}
if( db->mallocFailed ) return 1;
}
/* Begin flattening the iFrom-th entry of the FROM clause
** in the outer query.
*/
pSub = pSub1 = pSubitem->pSelect;
/* Delete the transient table structure associated with the
** subquery
*/
sqlite3DbFree(db, pSubitem->zDatabase);
sqlite3DbFree(db, pSubitem->zName);
sqlite3DbFree(db, pSubitem->zAlias);
pSubitem->zDatabase = 0;
pSubitem->zName = 0;
pSubitem->zAlias = 0;
pSubitem->pSelect = 0;
/* Defer deleting the Table object associated with the
** subquery until code generation is
** complete, since there may still exist Expr.pTab entries that
** refer to the subquery even after flattening. Ticket #3346.
**
** pSubitem->pTab is always non-NULL by test restrictions and tests above.
*/
if( ALWAYS(pSubitem->pTab!=0) ){
Table *pTabToDel = pSubitem->pTab;
if( pTabToDel->nTabRef==1 ){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pTabToDel->pNextZombie = pToplevel->pZombieTab;
pToplevel->pZombieTab = pTabToDel;
}else{
pTabToDel->nTabRef--;
}
pSubitem->pTab = 0;
}
/* The following loop runs once for each term in a compound-subquery
** flattening (as described above). If we are doing a different kind
** of flattening - a flattening other than a compound-subquery flattening -
** then this loop only runs once.
**
** This loop moves all of the FROM elements of the subquery into the
** the FROM clause of the outer query. Before doing this, remember
** the cursor number for the original outer query FROM element in
** iParent. The iParent cursor will never be used. Subsequent code
** will scan expressions looking for iParent references and replace
** those references with expressions that resolve to the subquery FROM
** elements we are now copying in.
*/
for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
int nSubSrc;
u8 jointype = 0;
assert( pSub!=0 );
pSubSrc = pSub->pSrc; /* FROM clause of subquery */
nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
pSrc = pParent->pSrc; /* FROM clause of the outer query */
if( pSrc ){
assert( pParent==p ); /* First time through the loop */
jointype = pSubitem->fg.jointype;
}else{
assert( pParent!=p ); /* 2nd and subsequent times through the loop */
pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* The subquery uses a single slot of the FROM clause of the outer
** query. If the subquery has more than one element in its FROM clause,
** then expand the outer query to make space for it to hold all elements
** of the subquery.
**
** Example:
**
** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
**
** The outer query has 3 slots in its FROM clause. One slot of the
** outer query (the middle slot) is used by the subquery. The next
** block of code will expand the outer query FROM clause to 4 slots.
** The middle slot is expanded to two slots in order to make space
** for the two elements in the FROM clause of the subquery.
*/
if( nSubSrc>1 ){
pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* Transfer the FROM clause terms from the subquery into the
** outer query.
*/
for(i=0; i<nSubSrc; i++){
sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
pSrc->a[i+iFrom] = pSubSrc->a[i];
iNewParent = pSubSrc->a[i].iCursor;
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
}
pSrc->a[iFrom].fg.jointype = jointype;
/* Now begin substituting subquery result set expressions for
** references to the iParent in the outer query.
**
** Example:
**
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
** \ \_____________ subquery __________/ /
** \_____________________ outer query ______________________________/
**
** We look at every expression in the outer query and every place we see
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
*/
if( pSub->pOrderBy ){
/* At this point, any non-zero iOrderByCol values indicate that the
** ORDER BY column expression is identical to the iOrderByCol'th
** expression returned by SELECT statement pSub. Since these values
** do not necessarily correspond to columns in SELECT statement pParent,
** zero them before transfering the ORDER BY clause.
**
** Not doing this may cause an error if a subsequent call to this
** function attempts to flatten a compound sub-query into pParent
** (the only way this can happen is if the compound sub-query is
** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
ExprList *pOrderBy = pSub->pOrderBy;
for(i=0; i<pOrderBy->nExpr; i++){
pOrderBy->a[i].u.x.iOrderByCol = 0;
}
assert( pParent->pOrderBy==0 );
pParent->pOrderBy = pOrderBy;
pSub->pOrderBy = 0;
}
pWhere = pSub->pWhere;
pSub->pWhere = 0;
if( isLeftJoin>0 ){
sqlite3SetJoinExpr(pWhere, iNewParent);
}
pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
if( db->mallocFailed==0 ){
SubstContext x;
x.pParse = pParse;
x.iTable = iParent;
x.iNewTable = iNewParent;
x.isLeftJoin = isLeftJoin;
x.pEList = pSub->pEList;
substSelect(&x, pParent, 0);
}
/* The flattened query is a compound if either the inner or the
** outer query is a compound. */
pParent->selFlags |= pSub->selFlags & SF_Compound;
assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
/*
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
**
** One is tempted to try to add a and b to combine the limits. But this
** does not work if either limit is negative.
*/
if( pSub->pLimit ){
pParent->pLimit = pSub->pLimit;
pSub->pLimit = 0;
}
}
/* Finially, delete what is left of the subquery and return
** success.
*/
sqlite3SelectDelete(db, pSub1);
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
/*
** A structure to keep track of all of the column values that are fixed to
** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
*/
typedef struct WhereConst WhereConst;
struct WhereConst {
Parse *pParse; /* Parsing context */
int nConst; /* Number for COLUMN=CONSTANT terms */
int nChng; /* Number of times a constant is propagated */
Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
};
/*
** Add a new entry to the pConst object. Except, do not add duplicate
** pColumn entires.
*/
static void constInsert(
WhereConst *pConst, /* The WhereConst into which we are inserting */
Expr *pColumn, /* The COLUMN part of the constraint */
Expr *pValue /* The VALUE part of the constraint */
){
int i;
assert( pColumn->op==TK_COLUMN );
/* 2018-10-25 ticket [cf5ed20f]
** Make sure the same pColumn is not inserted more than once */
for(i=0; i<pConst->nConst; i++){
const Expr *pExpr = pConst->apExpr[i*2];
assert( pExpr->op==TK_COLUMN );
if( pExpr->iTable==pColumn->iTable
&& pExpr->iColumn==pColumn->iColumn
){
return; /* Already present. Return without doing anything. */
}
}
pConst->nConst++;
pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
pConst->nConst*2*sizeof(Expr*));
if( pConst->apExpr==0 ){
pConst->nConst = 0;
}else{
if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
pConst->apExpr[pConst->nConst*2-2] = pColumn;
pConst->apExpr[pConst->nConst*2-1] = pValue;
}
}
/*
** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
** is a constant expression and where the term must be true because it
** is part of the AND-connected terms of the expression. For each term
** found, add it to the pConst structure.
*/
static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
Expr *pRight, *pLeft;
if( pExpr==0 ) return;
if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
if( pExpr->op==TK_AND ){
findConstInWhere(pConst, pExpr->pRight);
findConstInWhere(pConst, pExpr->pLeft);
return;
}
if( pExpr->op!=TK_EQ ) return;
pRight = pExpr->pRight;
pLeft = pExpr->pLeft;
assert( pRight!=0 );
assert( pLeft!=0 );
if( pRight->op==TK_COLUMN
&& !ExprHasProperty(pRight, EP_FixedCol)
&& sqlite3ExprIsConstant(pLeft)
&& sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr))
){
constInsert(pConst, pRight, pLeft);
}else
if( pLeft->op==TK_COLUMN
&& !ExprHasProperty(pLeft, EP_FixedCol)
&& sqlite3ExprIsConstant(pRight)
&& sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr))
){
constInsert(pConst, pLeft, pRight);
}
}
/*
** This is a Walker expression callback. pExpr is a candidate expression
** to be replaced by a value. If pExpr is equivalent to one of the
** columns named in pWalker->u.pConst, then overwrite it with its
** corresponding value.
*/
static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
int i;
WhereConst *pConst;
if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
pConst = pWalker->u.pConst;
for(i=0; i<pConst->nConst; i++){
Expr *pColumn = pConst->apExpr[i*2];
if( pColumn==pExpr ) continue;
if( pColumn->iTable!=pExpr->iTable ) continue;
if( pColumn->iColumn!=pExpr->iColumn ) continue;
/* A match is found. Add the EP_FixedCol property */
pConst->nChng++;
ExprClearProperty(pExpr, EP_Leaf);
ExprSetProperty(pExpr, EP_FixedCol);
assert( pExpr->pLeft==0 );
pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
break;
}
return WRC_Prune;
}
/*
** The WHERE-clause constant propagation optimization.
**
** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
** then throughout the query replace all other occurrences of COLUMN
** with CONSTANT within the WHERE clause.
**
** For example, the query:
**
** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
**
** Is transformed into
**
** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
**
** Return true if any transformations where made and false if not.
**
** Implementation note: Constant propagation is tricky due to affinity
** and collating sequence interactions. Consider this example:
**
** CREATE TABLE t1(a INT,b TEXT);
** INSERT INTO t1 VALUES(123,'0123');
** SELECT * FROM t1 WHERE a=123 AND b=a;
** SELECT * FROM t1 WHERE a=123 AND b=123;
**
** The two SELECT statements above should return different answers. b=a
** is alway true because the comparison uses numeric affinity, but b=123
** is false because it uses text affinity and '0123' is not the same as '123'.
** To work around this, the expression tree is not actually changed from
** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
** and the "123" value is hung off of the pLeft pointer. Code generator
** routines know to generate the constant "123" instead of looking up the
** column value. Also, to avoid collation problems, this optimization is
** only attempted if the "a=123" term uses the default BINARY collation.
*/
static int propagateConstants(
Parse *pParse, /* The parsing context */
Select *p /* The query in which to propagate constants */
){
WhereConst x;
Walker w;
int nChng = 0;
x.pParse = pParse;
do{
x.nConst = 0;
x.nChng = 0;
x.apExpr = 0;
findConstInWhere(&x, p->pWhere);
if( x.nConst ){
memset(&w, 0, sizeof(w));
w.pParse = pParse;
w.xExprCallback = propagateConstantExprRewrite;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.xSelectCallback2 = 0;
w.walkerDepth = 0;
w.u.pConst = &x;
sqlite3WalkExpr(&w, p->pWhere);
sqlite3DbFree(x.pParse->db, x.apExpr);
nChng += x.nChng;
}
}while( x.nChng );
return nChng;
}
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** Make copies of relevant WHERE clause terms of the outer query into
** the WHERE clause of subquery. Example:
**
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
**
** Transformed into:
**
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
** WHERE x=5 AND y=10;
**
** The hope is that the terms added to the inner query will make it more
** efficient.
**
** Do not attempt this optimization if:
**
** (1) (** This restriction was removed on 2017-09-29. We used to
** disallow this optimization for aggregate subqueries, but now
** it is allowed by putting the extra terms on the HAVING clause.
** The added HAVING clause is pointless if the subquery lacks
** a GROUP BY clause. But such a HAVING clause is also harmless
** so there does not appear to be any reason to add extra logic
** to suppress it. **)
**
** (2) The inner query is the recursive part of a common table expression.
**
** (3) The inner query has a LIMIT clause (since the changes to the WHERE
** clause would change the meaning of the LIMIT).
**
** (4) The inner query is the right operand of a LEFT JOIN and the
** expression to be pushed down does not come from the ON clause
** on that LEFT JOIN.
**
** (5) The WHERE clause expression originates in the ON or USING clause
** of a LEFT JOIN where iCursor is not the right-hand table of that
** left join. An example:
**
** SELECT *
** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
**
** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
** But if the (b2=2) term were to be pushed down into the bb subquery,
** then the (1,1,NULL) row would be suppressed.
**
** (6) The inner query features one or more window-functions (since
** changes to the WHERE clause of the inner query could change the
** window over which window functions are calculated).
**
** Return 0 if no changes are made and non-zero if one or more WHERE clause
** terms are duplicated into the subquery.
*/
static int pushDownWhereTerms(
Parse *pParse, /* Parse context (for malloc() and error reporting) */
Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
Expr *pWhere, /* The WHERE clause of the outer query */
int iCursor, /* Cursor number of the subquery */
int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
){
Expr *pNew;
int nChng = 0;
if( pWhere==0 ) return 0;
if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pSubq->pWin ) return 0; /* restriction (6) */
#endif
#ifdef SQLITE_DEBUG
/* Only the first term of a compound can have a WITH clause. But make
** sure no other terms are marked SF_Recursive in case something changes
** in the future.
*/
{
Select *pX;
for(pX=pSubq; pX; pX=pX->pPrior){
assert( (pX->selFlags & (SF_Recursive))==0 );
}
}
#endif
if( pSubq->pLimit!=0 ){
return 0; /* restriction (3) */
}
while( pWhere->op==TK_AND ){
nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
iCursor, isLeftJoin);
pWhere = pWhere->pLeft;
}
if( isLeftJoin
&& (ExprHasProperty(pWhere,EP_FromJoin)==0
|| pWhere->iRightJoinTable!=iCursor)
){
return 0; /* restriction (4) */
}
if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
return 0; /* restriction (5) */
}
if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
nChng++;
while( pSubq ){
SubstContext x;
pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
unsetJoinExpr(pNew, -1);
x.pParse = pParse;
x.iTable = iCursor;
x.iNewTable = iCursor;
x.isLeftJoin = 0;
x.pEList = pSubq->pEList;
pNew = substExpr(&x, pNew);
if( pSubq->selFlags & SF_Aggregate ){
pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
}else{
pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
}
pSubq = pSubq->pPrior;
}
}
return nChng;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
/*
** The pFunc is the only aggregate function in the query. Check to see
** if the query is a candidate for the min/max optimization.
**
** If the query is a candidate for the min/max optimization, then set
** *ppMinMax to be an ORDER BY clause to be used for the optimization
** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
** whether pFunc is a min() or max() function.
**
** If the query is not a candidate for the min/max optimization, return
** WHERE_ORDERBY_NORMAL (which must be zero).
**
** This routine must be called after aggregate functions have been
** located but before their arguments have been subjected to aggregate
** analysis.
*/
static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
const char *zFunc; /* Name of aggregate function pFunc */
ExprList *pOrderBy;
u8 sortFlags;
assert( *ppMinMax==0 );
assert( pFunc->op==TK_AGG_FUNCTION );
assert( !IsWindowFunc(pFunc) );
if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){
return eRet;
}
zFunc = pFunc->u.zToken;
if( sqlite3StrICmp(zFunc, "min")==0 ){
eRet = WHERE_ORDERBY_MIN;
sortFlags = KEYINFO_ORDER_BIGNULL;
}else if( sqlite3StrICmp(zFunc, "max")==0 ){
eRet = WHERE_ORDERBY_MAX;
sortFlags = KEYINFO_ORDER_DESC;
}else{
return eRet;
}
*ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
assert( pOrderBy!=0 || db->mallocFailed );
if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;
return eRet;
}
/*
** The select statement passed as the first argument is an aggregate query.
** The second argument is the associated aggregate-info object. This
** function tests if the SELECT is of the form:
**
** SELECT count(*) FROM <tbl>
**
** where table is a database table, not a sub-select or view. If the query
** does match this pattern, then a pointer to the Table object representing
** <tbl> is returned. Otherwise, 0 is returned.
*/
static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
Table *pTab;
Expr *pExpr;
assert( !p->pGroupBy );
if( p->pWhere || p->pEList->nExpr!=1
|| p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
){
return 0;
}
pTab = p->pSrc->a[0].pTab;
pExpr = p->pEList->a[0].pExpr;
assert( pTab && !pTab->pSelect && pExpr );
if( IsVirtual(pTab) ) return 0;
if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
if( NEVER(pAggInfo->nFunc==0) ) return 0;
if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
return pTab;
}
/*
** If the source-list item passed as an argument was augmented with an
** INDEXED BY clause, then try to locate the specified index. If there
** was such a clause and the named index cannot be found, return
** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
** pFrom->pIndex and return SQLITE_OK.
*/
int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
if( pFrom->pTab && pFrom->fg.isIndexedBy ){
Table *pTab = pFrom->pTab;
char *zIndexedBy = pFrom->u1.zIndexedBy;
Index *pIdx;
for(pIdx=pTab->pIndex;
pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
pIdx=pIdx->pNext
);
if( !pIdx ){
sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
pParse->checkSchema = 1;
return SQLITE_ERROR;
}
pFrom->pIBIndex = pIdx;
}
return SQLITE_OK;
}
/*
** Detect compound SELECT statements that use an ORDER BY clause with
** an alternative collating sequence.
**
** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
**
** These are rewritten as a subquery:
**
** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
** ORDER BY ... COLLATE ...
**
** This transformation is necessary because the multiSelectOrderBy() routine
** above that generates the code for a compound SELECT with an ORDER BY clause
** uses a merge algorithm that requires the same collating sequence on the
** result columns as on the ORDER BY clause. See ticket
** http://www.sqlite.org/src/info/6709574d2a
**
** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
** The UNION ALL operator works fine with multiSelectOrderBy() even when
** there are COLLATE terms in the ORDER BY.
*/
static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
int i;
Select *pNew;
Select *pX;
sqlite3 *db;
struct ExprList_item *a;
SrcList *pNewSrc;
Parse *pParse;
Token dummy;
if( p->pPrior==0 ) return WRC_Continue;
if( p->pOrderBy==0 ) return WRC_Continue;
for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
if( pX==0 ) return WRC_Continue;
a = p->pOrderBy->a;
for(i=p->pOrderBy->nExpr-1; i>=0; i--){
if( a[i].pExpr->flags & EP_Collate ) break;
}
if( i<0 ) return WRC_Continue;
/* If we reach this point, that means the transformation is required. */
pParse = pWalker->pParse;
db = pParse->db;
pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
if( pNew==0 ) return WRC_Abort;
memset(&dummy, 0, sizeof(dummy));
pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
if( pNewSrc==0 ) return WRC_Abort;
*pNew = *p;
p->pSrc = pNewSrc;
p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
p->op = TK_SELECT;
p->pWhere = 0;
pNew->pGroupBy = 0;
pNew->pHaving = 0;
pNew->pOrderBy = 0;
p->pPrior = 0;
p->pNext = 0;
p->pWith = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
p->pWinDefn = 0;
#endif
p->selFlags &= ~SF_Compound;
assert( (p->selFlags & SF_Converted)==0 );
p->selFlags |= SF_Converted;
assert( pNew->pPrior!=0 );
pNew->pPrior->pNext = pNew;
pNew->pLimit = 0;
return WRC_Continue;
}
/*
** Check to see if the FROM clause term pFrom has table-valued function
** arguments. If it does, leave an error message in pParse and return
** non-zero, since pFrom is not allowed to be a table-valued function.
*/
static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
if( pFrom->fg.isTabFunc ){
sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
return 1;
}
return 0;
}
#ifndef SQLITE_OMIT_CTE
/*
** Argument pWith (which may be NULL) points to a linked list of nested
** WITH contexts, from inner to outermost. If the table identified by
** FROM clause element pItem is really a common-table-expression (CTE)
** then return a pointer to the CTE definition for that table. Otherwise
** return NULL.
**
** If a non-NULL value is returned, set *ppContext to point to the With
** object that the returned CTE belongs to.
*/
static struct Cte *searchWith(
With *pWith, /* Current innermost WITH clause */
struct SrcList_item *pItem, /* FROM clause element to resolve */
With **ppContext /* OUT: WITH clause return value belongs to */
){
const char *zName;
if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
With *p;
for(p=pWith; p; p=p->pOuter){
int i;
for(i=0; i<p->nCte; i++){
if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
*ppContext = p;
return &p->a[i];
}
}
}
}
return 0;
}
/* The code generator maintains a stack of active WITH clauses
** with the inner-most WITH clause being at the top of the stack.
**
** This routine pushes the WITH clause passed as the second argument
** onto the top of the stack. If argument bFree is true, then this
** WITH clause will never be popped from the stack. In this case it
** should be freed along with the Parse object. In other cases, when
** bFree==0, the With object will be freed along with the SELECT
** statement with which it is associated.
*/
void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
if( pWith ){
assert( pParse->pWith!=pWith );
pWith->pOuter = pParse->pWith;
pParse->pWith = pWith;
if( bFree ) pParse->pWithToFree = pWith;
}
}
/*
** This function checks if argument pFrom refers to a CTE declared by
** a WITH clause on the stack currently maintained by the parser. And,
** if currently processing a CTE expression, if it is a recursive
** reference to the current CTE.
**
** If pFrom falls into either of the two categories above, pFrom->pTab
** and other fields are populated accordingly. The caller should check
** (pFrom->pTab!=0) to determine whether or not a successful match
** was found.
**
** Whether or not a match is found, SQLITE_OK is returned if no error
** occurs. If an error does occur, an error message is stored in the
** parser and some error code other than SQLITE_OK returned.
*/
static int withExpand(
Walker *pWalker,
struct SrcList_item *pFrom
){
Parse *pParse = pWalker->pParse;
sqlite3 *db = pParse->db;
struct Cte *pCte; /* Matched CTE (or NULL if no match) */
With *pWith; /* WITH clause that pCte belongs to */
assert( pFrom->pTab==0 );
if( pParse->nErr ){
return SQLITE_ERROR;
}
pCte = searchWith(pParse->pWith, pFrom, &pWith);
if( pCte ){
Table *pTab;
ExprList *pEList;
Select *pSel;
Select *pLeft; /* Left-most SELECT statement */
int bMayRecursive; /* True if compound joined by UNION [ALL] */
With *pSavedWith; /* Initial value of pParse->pWith */
/* If pCte->zCteErr is non-NULL at this point, then this is an illegal
** recursive reference to CTE pCte. Leave an error in pParse and return
** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
** In this case, proceed. */
if( pCte->zCteErr ){
sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
return SQLITE_ERROR;
}
if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
assert( pFrom->pTab==0 );
pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
if( pTab==0 ) return WRC_Abort;
pTab->nTabRef = 1;
pTab->zName = sqlite3DbStrDup(db, pCte->zName);
pTab->iPKey = -1;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
assert( pFrom->pSelect );
/* Check if this is a recursive CTE. */
pSel = pFrom->pSelect;
bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
if( bMayRecursive ){
int i;
SrcList *pSrc = pFrom->pSelect->pSrc;
for(i=0; i<pSrc->nSrc; i++){
struct SrcList_item *pItem = &pSrc->a[i];
if( pItem->zDatabase==0
&& pItem->zName!=0
&& 0==sqlite3StrICmp(pItem->zName, pCte->zName)
){
pItem->pTab = pTab;
pItem->fg.isRecursive = 1;
pTab->nTabRef++;
pSel->selFlags |= SF_Recursive;
}
}
}
/* Only one recursive reference is permitted. */
if( pTab->nTabRef>2 ){
sqlite3ErrorMsg(
pParse, "multiple references to recursive table: %s", pCte->zName
);
return SQLITE_ERROR;
}
assert( pTab->nTabRef==1 ||
((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
pCte->zCteErr = "circular reference: %s";
pSavedWith = pParse->pWith;
pParse->pWith = pWith;
if( bMayRecursive ){
Select *pPrior = pSel->pPrior;
assert( pPrior->pWith==0 );
pPrior->pWith = pSel->pWith;
sqlite3WalkSelect(pWalker, pPrior);
pPrior->pWith = 0;
}else{
sqlite3WalkSelect(pWalker, pSel);
}
pParse->pWith = pWith;
for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
pEList = pLeft->pEList;
if( pCte->pCols ){
if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
pCte->zName, pEList->nExpr, pCte->pCols->nExpr
);
pParse->pWith = pSavedWith;
return SQLITE_ERROR;
}
pEList = pCte->pCols;
}
sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
if( bMayRecursive ){
if( pSel->selFlags & SF_Recursive ){
pCte->zCteErr = "multiple recursive references: %s";
}else{
pCte->zCteErr = "recursive reference in a subquery: %s";
}
sqlite3WalkSelect(pWalker, pSel);
}
pCte->zCteErr = 0;
pParse->pWith = pSavedWith;
}
return SQLITE_OK;
}
#endif
#ifndef SQLITE_OMIT_CTE
/*
** If the SELECT passed as the second argument has an associated WITH
** clause, pop it from the stack stored as part of the Parse object.
**
** This function is used as the xSelectCallback2() callback by
** sqlite3SelectExpand() when walking a SELECT tree to resolve table
** names and other FROM clause elements.
*/
static void selectPopWith(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
With *pWith = findRightmost(p)->pWith;
if( pWith!=0 ){
assert( pParse->pWith==pWith );
pParse->pWith = pWith->pOuter;
}
}
}
#else
#define selectPopWith 0
#endif
/*
** The SrcList_item structure passed as the second argument represents a
** sub-query in the FROM clause of a SELECT statement. This function
** allocates and populates the SrcList_item.pTab object. If successful,
** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
** SQLITE_NOMEM.
*/
int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
Select *pSel = pFrom->pSelect;
Table *pTab;
assert( pSel );
pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
if( pTab==0 ) return SQLITE_NOMEM;
pTab->nTabRef = 1;
if( pFrom->zAlias ){
pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
}else{
pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
}
while( pSel->pPrior ){ pSel = pSel->pPrior; }
sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
pTab->iPKey = -1;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
pTab->tabFlags |= TF_Ephemeral;
return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
}
/*
** This routine is a Walker callback for "expanding" a SELECT statement.
** "Expanding" means to do the following:
**
** (1) Make sure VDBE cursor numbers have been assigned to every
** element of the FROM clause.
**
** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
** defines FROM clause. When views appear in the FROM clause,
** fill pTabList->a[].pSelect with a copy of the SELECT statement
** that implements the view. A copy is made of the view's SELECT
** statement so that we can freely modify or delete that statement
** without worrying about messing up the persistent representation
** of the view.
**
** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
** on joins and the ON and USING clause of joins.
**
** (4) Scan the list of columns in the result set (pEList) looking
** for instances of the "*" operator or the TABLE.* operator.
** If found, expand each "*" to be every column in every table
** and TABLE.* to be every column in TABLE.
**
*/
static int selectExpander(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
int i, j, k;
SrcList *pTabList;
ExprList *pEList;
struct SrcList_item *pFrom;
sqlite3 *db = pParse->db;
Expr *pE, *pRight, *pExpr;
u16 selFlags = p->selFlags;
u32 elistFlags = 0;
p->selFlags |= SF_Expanded;
if( db->mallocFailed ){
return WRC_Abort;
}
assert( p->pSrc!=0 );
if( (selFlags & SF_Expanded)!=0 ){
return WRC_Prune;
}
if( pWalker->eCode ){
/* Renumber selId because it has been copied from a view */
p->selId = ++pParse->nSelect;
}
pTabList = p->pSrc;
pEList = p->pEList;
sqlite3WithPush(pParse, p->pWith, 0);
/* Make sure cursor numbers have been assigned to all entries in
** the FROM clause of the SELECT statement.
*/
sqlite3SrcListAssignCursors(pParse, pTabList);
/* Look up every table named in the FROM clause of the select. If
** an entry of the FROM clause is a subquery instead of a table or view,
** then create a transient table structure to describe the subquery.
*/
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab;
assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
if( pFrom->fg.isRecursive ) continue;
assert( pFrom->pTab==0 );
#ifndef SQLITE_OMIT_CTE
if( withExpand(pWalker, pFrom) ) return WRC_Abort;
if( pFrom->pTab ) {} else
#endif
if( pFrom->zName==0 ){
#ifndef SQLITE_OMIT_SUBQUERY
Select *pSel = pFrom->pSelect;
/* A sub-query in the FROM clause of a SELECT */
assert( pSel!=0 );
assert( pFrom->pTab==0 );
if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
#endif
}else{
/* An ordinary table or view name in the FROM clause */
assert( pFrom->pTab==0 );
pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
if( pTab==0 ) return WRC_Abort;
if( pTab->nTabRef>=0xffff ){
sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
pTab->zName);
pFrom->pTab = 0;
return WRC_Abort;
}
pTab->nTabRef++;
if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
return WRC_Abort;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
if( IsVirtual(pTab) || pTab->pSelect ){
i16 nCol;
u8 eCodeOrig = pWalker->eCode;
if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
assert( pFrom->pSelect==0 );
if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
pTab->zName);
}
pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
nCol = pTab->nCol;
pTab->nCol = -1;
pWalker->eCode = 1; /* Turn on Select.selId renumbering */
sqlite3WalkSelect(pWalker, pFrom->pSelect);
pWalker->eCode = eCodeOrig;
pTab->nCol = nCol;
}
#endif
}
/* Locate the index named by the INDEXED BY clause, if any. */
if( sqlite3IndexedByLookup(pParse, pFrom) ){
return WRC_Abort;
}
}
/* Process NATURAL keywords, and ON and USING clauses of joins.
*/
if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){
return WRC_Abort;
}
/* For every "*" that occurs in the column list, insert the names of
** all columns in all tables. And for every TABLE.* insert the names
** of all columns in TABLE. The parser inserted a special expression
** with the TK_ASTERISK operator for each "*" that it found in the column
** list. The following code just has to locate the TK_ASTERISK
** expressions and expand each one to the list of all columns in
** all tables.
**
** The first loop just checks to see if there are any "*" operators
** that need expanding.
*/
for(k=0; k<pEList->nExpr; k++){
pE = pEList->a[k].pExpr;
if( pE->op==TK_ASTERISK ) break;
assert( pE->op!=TK_DOT || pE->pRight!=0 );
assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
elistFlags |= pE->flags;
}
if( k<pEList->nExpr ){
/*
** If we get here it means the result set contains one or more "*"
** operators that need to be expanded. Loop through each expression
** in the result set and expand them one by one.
*/
struct ExprList_item *a = pEList->a;
ExprList *pNew = 0;
int flags = pParse->db->flags;
int longNames = (flags & SQLITE_FullColNames)!=0
&& (flags & SQLITE_ShortColNames)==0;
for(k=0; k<pEList->nExpr; k++){
pE = a[k].pExpr;
elistFlags |= pE->flags;
pRight = pE->pRight;
assert( pE->op!=TK_DOT || pRight!=0 );
if( pE->op!=TK_ASTERISK
&& (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
){
/* This particular expression does not need to be expanded.
*/
pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
if( pNew ){
pNew->a[pNew->nExpr-1].zName = a[k].zName;
pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
a[k].zName = 0;
a[k].zSpan = 0;
}
a[k].pExpr = 0;
}else{
/* This expression is a "*" or a "TABLE.*" and needs to be
** expanded. */
int tableSeen = 0; /* Set to 1 when TABLE matches */
char *zTName = 0; /* text of name of TABLE */
if( pE->op==TK_DOT ){
assert( pE->pLeft!=0 );
assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
zTName = pE->pLeft->u.zToken;
}
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab = pFrom->pTab;
Select *pSub = pFrom->pSelect;
char *zTabName = pFrom->zAlias;
const char *zSchemaName = 0;
int iDb;
if( zTabName==0 ){
zTabName = pTab->zName;
}
if( db->mallocFailed ) break;
if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
pSub = 0;
if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
continue;
}
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
}
for(j=0; j<pTab->nCol; j++){
char *zName = pTab->aCol[j].zName;
char *zColname; /* The computed column name */
char *zToFree; /* Malloced string that needs to be freed */
Token sColname; /* Computed column name as a token */
assert( zName );
if( zTName && pSub
&& sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
){
continue;
}
/* If a column is marked as 'hidden', omit it from the expanded
** result-set list unless the SELECT has the SF_IncludeHidden
** bit set.
*/
if( (p->selFlags & SF_IncludeHidden)==0
&& IsHiddenColumn(&pTab->aCol[j])
){
continue;
}
tableSeen = 1;
if( i>0 && zTName==0 ){
if( (pFrom->fg.jointype & JT_NATURAL)!=0
&& tableAndColumnIndex(pTabList, i, zName, 0, 0)
){
/* In a NATURAL join, omit the join columns from the
** table to the right of the join */
continue;
}
if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
/* In a join with a USING clause, omit columns in the
** using clause from the table on the right. */
continue;
}
}
pRight = sqlite3Expr(db, TK_ID, zName);
zColname = zName;
zToFree = 0;
if( longNames || pTabList->nSrc>1 ){
Expr *pLeft;
pLeft = sqlite3Expr(db, TK_ID, zTabName);
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
if( zSchemaName ){
pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
}
if( longNames ){
zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
zToFree = zColname;
}
}else{
pExpr = pRight;
}
pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
sqlite3TokenInit(&sColname, zColname);
sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
if( pSub ){
pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
testcase( pX->zSpan==0 );
}else{
pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
zSchemaName, zTabName, zColname);
testcase( pX->zSpan==0 );
}
pX->bSpanIsTab = 1;
}
sqlite3DbFree(db, zToFree);
}
}
if( !tableSeen ){
if( zTName ){
sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
}else{
sqlite3ErrorMsg(pParse, "no tables specified");
}
}
}
}
sqlite3ExprListDelete(db, pEList);
p->pEList = pNew;
}
if( p->pEList ){
if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many columns in result set");
return WRC_Abort;
}
if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
p->selFlags |= SF_ComplexResult;
}
}
return WRC_Continue;
}
/*
** No-op routine for the parse-tree walker.
**
** When this routine is the Walker.xExprCallback then expression trees
** are walked without any actions being taken at each node. Presumably,
** when this routine is used for Walker.xExprCallback then
** Walker.xSelectCallback is set to do something useful for every
** subquery in the parser tree.
*/
int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
return WRC_Continue;
}
/*
** No-op routine for the parse-tree walker for SELECT statements.
** subquery in the parser tree.
*/
int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
return WRC_Continue;
}
#if SQLITE_DEBUG
/*
** Always assert. This xSelectCallback2 implementation proves that the
** xSelectCallback2 is never invoked.
*/
void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
assert( 0 );
}
#endif
/*
** This routine "expands" a SELECT statement and all of its subqueries.
** For additional information on what it means to "expand" a SELECT
** statement, see the comment on the selectExpand worker callback above.
**
** Expanding a SELECT statement is the first step in processing a
** SELECT statement. The SELECT statement must be expanded before
** name resolution is performed.
**
** If anything goes wrong, an error message is written into pParse.
** The calling function can detect the problem by looking at pParse->nErr
** and/or pParse->db->mallocFailed.
*/
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
Walker w;
w.xExprCallback = sqlite3ExprWalkNoop;
w.pParse = pParse;
if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
w.xSelectCallback = convertCompoundSelectToSubquery;
w.xSelectCallback2 = 0;
sqlite3WalkSelect(&w, pSelect);
}
w.xSelectCallback = selectExpander;
w.xSelectCallback2 = selectPopWith;
w.eCode = 0;
sqlite3WalkSelect(&w, pSelect);
}
#ifndef SQLITE_OMIT_SUBQUERY
/*
** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
** interface.
**
** For each FROM-clause subquery, add Column.zType and Column.zColl
** information to the Table structure that represents the result set
** of that subquery.
**
** The Table structure that represents the result set was constructed
** by selectExpander() but the type and collation information was omitted
** at that point because identifiers had not yet been resolved. This
** routine is called after identifier resolution.
*/
static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
Parse *pParse;
int i;
SrcList *pTabList;
struct SrcList_item *pFrom;
assert( p->selFlags & SF_Resolved );
if( p->selFlags & SF_HasTypeInfo ) return;
p->selFlags |= SF_HasTypeInfo;
pParse = pWalker->pParse;
pTabList = p->pSrc;
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab = pFrom->pTab;
assert( pTab!=0 );
if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
/* A sub-query in the FROM clause of a SELECT */
Select *pSel = pFrom->pSelect;
if( pSel ){
while( pSel->pPrior ) pSel = pSel->pPrior;
sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
SQLITE_AFF_NONE);
}
}
}
}
#endif
/*
** This routine adds datatype and collating sequence information to
** the Table structures of all FROM-clause subqueries in a
** SELECT statement.
**
** Use this routine after name resolution.
*/
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
#ifndef SQLITE_OMIT_SUBQUERY
Walker w;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.xSelectCallback2 = selectAddSubqueryTypeInfo;
w.xExprCallback = sqlite3ExprWalkNoop;
w.pParse = pParse;
sqlite3WalkSelect(&w, pSelect);
#endif
}
/*
** This routine sets up a SELECT statement for processing. The
** following is accomplished:
**
** * VDBE Cursor numbers are assigned to all FROM-clause terms.
** * Ephemeral Table objects are created for all FROM-clause subqueries.
** * ON and USING clauses are shifted into WHERE statements
** * Wildcards "*" and "TABLE.*" in result sets are expanded.
** * Identifiers in expression are matched to tables.
**
** This routine acts recursively on all subqueries within the SELECT.
*/
void sqlite3SelectPrep(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
NameContext *pOuterNC /* Name context for container */
){
assert( p!=0 || pParse->db->mallocFailed );
if( pParse->db->mallocFailed ) return;
if( p->selFlags & SF_HasTypeInfo ) return;
sqlite3SelectExpand(pParse, p);
if( pParse->nErr || pParse->db->mallocFailed ) return;
sqlite3ResolveSelectNames(pParse, p, pOuterNC);
if( pParse->nErr || pParse->db->mallocFailed ) return;
sqlite3SelectAddTypeInfo(pParse, p);
}
/*
** Reset the aggregate accumulator.
**
** The aggregate accumulator is a set of memory cells that hold
** intermediate results while calculating an aggregate. This
** routine generates code that stores NULLs in all of those memory
** cells.
*/
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
struct AggInfo_func *pFunc;
int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
if( nReg==0 ) return;
#ifdef SQLITE_DEBUG
/* Verify that all AggInfo registers are within the range specified by
** AggInfo.mnReg..AggInfo.mxReg */
assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
for(i=0; i<pAggInfo->nColumn; i++){
assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
&& pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
}
for(i=0; i<pAggInfo->nFunc; i++){
assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
&& pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
}
#endif
sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
if( pFunc->iDistinct>=0 ){
Expr *pE = pFunc->pExpr;
assert( !ExprHasProperty(pE, EP_xIsSelect) );
if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
"argument");
pFunc->iDistinct = -1;
}else{
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
(char*)pKeyInfo, P4_KEYINFO);
}
}
}
}
/*
** Invoke the OP_AggFinalize opcode for every aggregate function
** in the AggInfo structure.
*/
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
struct AggInfo_func *pF;
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
ExprList *pList = pF->pExpr->x.pList;
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
}
}
/*
** Update the accumulator memory cells for an aggregate based on
** the current cursor position.
**
** If regAcc is non-zero and there are no min() or max() aggregates
** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
** registers if register regAcc contains 0. The caller will take care
** of setting and clearing regAcc.
*/
static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
int regHit = 0;
int addrHitTest = 0;
struct AggInfo_func *pF;
struct AggInfo_col *pC;
pAggInfo->directMode = 1;
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
int nArg;
int addrNext = 0;
int regAgg;
ExprList *pList = pF->pExpr->x.pList;
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
assert( !IsWindowFunc(pF->pExpr) );
if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){
Expr *pFilter = pF->pExpr->y.pWin->pFilter;
if( pAggInfo->nAccumulator
&& (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
){
if( regHit==0 ) regHit = ++pParse->nMem;
/* If this is the first row of the group (regAcc==0), clear the
** "magnet" register regHit so that the accumulator registers
** are populated if the FILTER clause jumps over the the
** invocation of min() or max() altogether. Or, if this is not
** the first row (regAcc==1), set the magnet register so that the
** accumulators are not populated unless the min()/max() is invoked and
** indicates that they should be. */
sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
}
addrNext = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
}
if( pList ){
nArg = pList->nExpr;
regAgg = sqlite3GetTempRange(pParse, nArg);
sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
}else{
nArg = 0;
regAgg = 0;
}
if( pF->iDistinct>=0 ){
if( addrNext==0 ){
addrNext = sqlite3VdbeMakeLabel(pParse);
}
testcase( nArg==0 ); /* Error condition */
testcase( nArg>1 ); /* Also an error */
codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
}
if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
CollSeq *pColl = 0;
struct ExprList_item *pItem;
int j;
assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
}
if( !pColl ){
pColl = pParse->db->pDfltColl;
}
if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
}
sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
sqlite3VdbeChangeP5(v, (u8)nArg);
sqlite3ReleaseTempRange(pParse, regAgg, nArg);
if( addrNext ){
sqlite3VdbeResolveLabel(v, addrNext);
}
}
if( regHit==0 && pAggInfo->nAccumulator ){
regHit = regAcc;
}
if( regHit ){
addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
}
for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
}
pAggInfo->directMode = 0;
if( addrHitTest ){
sqlite3VdbeJumpHere(v, addrHitTest);
}
}
/*
** Add a single OP_Explain instruction to the VDBE to explain a simple
** count(*) query ("SELECT count(*) FROM pTab").
*/
#ifndef SQLITE_OMIT_EXPLAIN
static void explainSimpleCount(
Parse *pParse, /* Parse context */
Table *pTab, /* Table being queried */
Index *pIdx /* Index used to optimize scan, or NULL */
){
if( pParse->explain==2 ){
int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
pTab->zName,
bCover ? " USING COVERING INDEX " : "",
bCover ? pIdx->zName : ""
);
}
}
#else
# define explainSimpleCount(a,b,c)
#endif
/*
** sqlite3WalkExpr() callback used by havingToWhere().
**
** If the node passed to the callback is a TK_AND node, return
** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
**
** Otherwise, return WRC_Prune. In this case, also check if the
** sub-expression matches the criteria for being moved to the WHERE
** clause. If so, add it to the WHERE clause and replace the sub-expression
** within the HAVING expression with a constant "1".
*/
static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
if( pExpr->op!=TK_AND ){
Select *pS = pWalker->u.pSelect;
if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
sqlite3 *db = pWalker->pParse->db;
Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
if( pNew ){
Expr *pWhere = pS->pWhere;
SWAP(Expr, *pNew, *pExpr);
pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
pS->pWhere = pNew;
pWalker->eCode = 1;
}
}
return WRC_Prune;
}
return WRC_Continue;
}
/*
** Transfer eligible terms from the HAVING clause of a query, which is
** processed after grouping, to the WHERE clause, which is processed before
** grouping. For example, the query:
**
** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
**
** can be rewritten as:
**
** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
**
** A term of the HAVING expression is eligible for transfer if it consists
** entirely of constants and expressions that are also GROUP BY terms that
** use the "BINARY" collation sequence.
*/
static void havingToWhere(Parse *pParse, Select *p){
Walker sWalker;
memset(&sWalker, 0, sizeof(sWalker));
sWalker.pParse = pParse;
sWalker.xExprCallback = havingToWhereExprCb;
sWalker.u.pSelect = p;
sqlite3WalkExpr(&sWalker, p->pHaving);
#if SELECTTRACE_ENABLED
if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}
/*
** Check to see if the pThis entry of pTabList is a self-join of a prior view.
** If it is, then return the SrcList_item for the prior view. If it is not,
** then return 0.
*/
static struct SrcList_item *isSelfJoinView(
SrcList *pTabList, /* Search for self-joins in this FROM clause */
struct SrcList_item *pThis /* Search for prior reference to this subquery */
){
struct SrcList_item *pItem;
for(pItem = pTabList->a; pItem<pThis; pItem++){
Select *pS1;
if( pItem->pSelect==0 ) continue;
if( pItem->fg.viaCoroutine ) continue;
if( pItem->zName==0 ) continue;
assert( pItem->pTab!=0 );
assert( pThis->pTab!=0 );
if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
pS1 = pItem->pSelect;
if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
/* The query flattener left two different CTE tables with identical
** names in the same FROM clause. */
continue;
}
if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
|| sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
){
/* The view was modified by some other optimization such as
** pushDownWhereTerms() */
continue;
}
return pItem;
}
return 0;
}
#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
/*
** Attempt to transform a query of the form
**
** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
**
** Into this:
**
** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
**
** The transformation only works if all of the following are true:
**
** * The subquery is a UNION ALL of two or more terms
** * The subquery does not have a LIMIT clause
** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
** * The outer query is a simple count(*) with no WHERE clause or other
** extraneous syntax.
**
** Return TRUE if the optimization is undertaken.
*/
static int countOfViewOptimization(Parse *pParse, Select *p){
Select *pSub, *pPrior;
Expr *pExpr;
Expr *pCount;
sqlite3 *db;
if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
if( p->pWhere ) return 0;
if( p->pGroupBy ) return 0;
pExpr = p->pEList->a[0].pExpr;
if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
pSub = p->pSrc->a[0].pSelect;
if( pSub==0 ) return 0; /* The FROM is a subquery */
if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
do{
if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
if( pSub->pWhere ) return 0; /* No WHERE clause */
if( pSub->pLimit ) return 0; /* No LIMIT clause */
if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
pSub = pSub->pPrior; /* Repeat over compound */
}while( pSub );
/* If we reach this point then it is OK to perform the transformation */
db = pParse->db;
pCount = pExpr;
pExpr = 0;
pSub = p->pSrc->a[0].pSelect;
p->pSrc->a[0].pSelect = 0;
sqlite3SrcListDelete(db, p->pSrc);
p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
while( pSub ){
Expr *pTerm;
pPrior = pSub->pPrior;
pSub->pPrior = 0;
pSub->pNext = 0;
pSub->selFlags |= SF_Aggregate;
pSub->selFlags &= ~SF_Compound;
pSub->nSelectRow = 0;
sqlite3ExprListDelete(db, pSub->pEList);
pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
sqlite3PExprAddSelect(pParse, pTerm, pSub);
if( pExpr==0 ){
pExpr = pTerm;
}else{
pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
}
pSub = pPrior;
}
p->pEList->a[0].pExpr = pExpr;
p->selFlags &= ~SF_Aggregate;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
}
#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
/*
** Generate code for the SELECT statement given in the p argument.
**
** The results are returned according to the SelectDest structure.
** See comments in sqliteInt.h for further information.
**
** This routine returns the number of errors. If any errors are
** encountered, then an appropriate error message is left in
** pParse->zErrMsg.
**
** This routine does NOT free the Select structure passed in. The
** calling function needs to do that.
*/
int sqlite3Select(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
SelectDest *pDest /* What to do with the query results */
){
int i, j; /* Loop counters */
WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
Vdbe *v; /* The virtual machine under construction */
int isAgg; /* True for select lists like "count(*)" */
ExprList *pEList = 0; /* List of columns to extract. */
SrcList *pTabList; /* List of tables to select from */
Expr *pWhere; /* The WHERE clause. May be NULL */
ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
Expr *pHaving; /* The HAVING clause. May be NULL */
int rc = 1; /* Value to return from this function */
DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
SortCtx sSort; /* Info on how to code the ORDER BY clause */
AggInfo sAggInfo; /* Information used by aggregate queries */
int iEnd; /* Address of the end of the query */
sqlite3 *db; /* The database connection */
ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
u8 minMaxFlag; /* Flag for min/max queries */
db = pParse->db;
v = sqlite3GetVdbe(pParse);
if( p==0 || db->mallocFailed || pParse->nErr ){
return 1;
}
if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
memset(&sAggInfo, 0, sizeof(sAggInfo));
#if SELECTTRACE_ENABLED
SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
if( sqlite3SelectTrace & 0x100 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
if( IgnorableOrderby(pDest) ){
assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
/* If ORDER BY makes no difference in the output then neither does
** DISTINCT so it can be removed too. */
sqlite3ExprListDelete(db, p->pOrderBy);
p->pOrderBy = 0;
p->selFlags &= ~SF_Distinct;
}
sqlite3SelectPrep(pParse, p, 0);
if( pParse->nErr || db->mallocFailed ){
goto select_end;
}
assert( p->pEList!=0 );
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x104 ){
SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
if( pDest->eDest==SRT_Output ){
generateColumnNames(pParse, p);
}
#ifndef SQLITE_OMIT_WINDOWFUNC
rc = sqlite3WindowRewrite(pParse, p);
if( rc ){
assert( db->mallocFailed || pParse->nErr>0 );
goto select_end;
}
#if SELECTTRACE_ENABLED
if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){
SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
#endif /* SQLITE_OMIT_WINDOWFUNC */
pTabList = p->pSrc;
isAgg = (p->selFlags & SF_Aggregate)!=0;
memset(&sSort, 0, sizeof(sSort));
sSort.pOrderBy = p->pOrderBy;
/* Try to various optimizations (flattening subqueries, and strength
** reduction of join operators) in the FROM clause up into the main query
*/
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
struct SrcList_item *pItem = &pTabList->a[i];
Select *pSub = pItem->pSelect;
Table *pTab = pItem->pTab;
/* Convert LEFT JOIN into JOIN if there are terms of the right table
** of the LEFT JOIN used in the WHERE clause.
*/
if( (pItem->fg.jointype & JT_LEFT)!=0
&& sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
&& OptimizationEnabled(db, SQLITE_SimplifyJoin)
){
SELECTTRACE(0x100,pParse,p,
("LEFT-JOIN simplifies to JOIN on term %d\n",i));
pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
unsetJoinExpr(p->pWhere, pItem->iCursor);
}
/* No futher action if this term of the FROM clause is no a subquery */
if( pSub==0 ) continue;
/* Catch mismatch in the declared columns of a view and the number of
** columns in the SELECT on the RHS */
if( pTab->nCol!=pSub->pEList->nExpr ){
sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
pTab->nCol, pTab->zName, pSub->pEList->nExpr);
goto select_end;
}
/* Do not try to flatten an aggregate subquery.
**
** Flattening an aggregate subquery is only possible if the outer query
** is not a join. But if the outer query is not a join, then the subquery
** will be implemented as a co-routine and there is no advantage to
** flattening in that case.
*/
if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
assert( pSub->pGroupBy==0 );
/* If the outer query contains a "complex" result set (that is,
** if the result set of the outer query uses functions or subqueries)
** and if the subquery contains an ORDER BY clause and if
** it will be implemented as a co-routine, then do not flatten. This
** restriction allows SQL constructs like this:
**
** SELECT expensive_function(x)
** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
**
** The expensive_function() is only computed on the 10 rows that
** are output, rather than every row of the table.
**
** The requirement that the outer query have a complex result set
** means that flattening does occur on simpler SQL constraints without
** the expensive_function() like:
**
** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
*/
if( pSub->pOrderBy!=0
&& i==0
&& (p->selFlags & SF_ComplexResult)!=0
&& (pTabList->nSrc==1
|| (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
){
continue;
}
if( flattenSubquery(pParse, p, i, isAgg) ){
if( pParse->nErr ) goto select_end;
/* This subquery can be absorbed into its parent. */
i = -1;
}
pTabList = p->pSrc;
if( db->mallocFailed ) goto select_end;
if( !IgnorableOrderby(pDest) ){
sSort.pOrderBy = p->pOrderBy;
}
}
#endif
#ifndef SQLITE_OMIT_COMPOUND_SELECT
/* Handle compound SELECT statements using the separate multiSelect()
** procedure.
*/
if( p->pPrior ){
rc = multiSelect(pParse, p, pDest);
#if SELECTTRACE_ENABLED
SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
return rc;
}
#endif
/* Do the WHERE-clause constant propagation optimization if this is
** a join. No need to speed time on this operation for non-join queries
** as the equivalent optimization will be handled by query planner in
** sqlite3WhereBegin().
*/
if( pTabList->nSrc>1
&& OptimizationEnabled(db, SQLITE_PropagateConst)
&& propagateConstants(pParse, p)
){
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}else{
SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
}
#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
&& countOfViewOptimization(pParse, p)
){
if( db->mallocFailed ) goto select_end;
pEList = p->pEList;
pTabList = p->pSrc;
}
#endif
/* For each term in the FROM clause, do two things:
** (1) Authorized unreferenced tables
** (2) Generate code for all sub-queries
*/
for(i=0; i<pTabList->nSrc; i++){
struct SrcList_item *pItem = &pTabList->a[i];
SelectDest dest;
Select *pSub;
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
const char *zSavedAuthContext;
#endif
/* Issue SQLITE_READ authorizations with a fake column name for any
** tables that are referenced but from which no values are extracted.
** Examples of where these kinds of null SQLITE_READ authorizations
** would occur:
**
** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
**
** The fake column name is an empty string. It is possible for a table to
** have a column named by the empty string, in which case there is no way to
** distinguish between an unreferenced table and an actual reference to the
** "" column. The original design was for the fake column name to be a NULL,
** which would be unambiguous. But legacy authorization callbacks might
** assume the column name is non-NULL and segfault. The use of an empty
** string for the fake column name seems safer.
*/
if( pItem->colUsed==0 && pItem->zName!=0 ){
sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
}
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* Generate code for all sub-queries in the FROM clause
*/
pSub = pItem->pSelect;
if( pSub==0 ) continue;
/* The code for a subquery should only be generated once, though it is
** technically harmless for it to be generated multiple times. The
** following assert() will detect if something changes to cause
** the same subquery to be coded multiple times, as a signal to the
** developers to try to optimize the situation.
**
** Update 2019-07-24:
** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.
** The dbsqlfuzz fuzzer found a case where the same subquery gets
** coded twice. So this assert() now becomes a testcase(). It should
** be very rare, though.
*/
testcase( pItem->addrFillSub!=0 );
/* Increment Parse.nHeight by the height of the largest expression
** tree referred to by this, the parent select. The child select
** may contain expression trees of at most
** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
** more conservative than necessary, but much easier than enforcing
** an exact limit.
*/
pParse->nHeight += sqlite3SelectExprHeight(p);
/* Make copies of constant WHERE-clause terms in the outer query down
** inside the subquery. This can help the subquery to run more efficiently.
*/
if( OptimizationEnabled(db, SQLITE_PushDown)
&& pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
(pItem->fg.jointype & JT_OUTER)!=0)
){
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,
("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}else{
SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
}
zSavedAuthContext = pParse->zAuthContext;
pParse->zAuthContext = pItem->zName;
/* Generate code to implement the subquery
**
** The subquery is implemented as a co-routine if the subquery is
** guaranteed to be the outer loop (so that it does not need to be
** computed more than once)
**
** TODO: Are there other reasons beside (1) to use a co-routine
** implementation?
*/
if( i==0
&& (pTabList->nSrc==1
|| (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
){
/* Implement a co-routine that will return a single row of the result
** set on each invocation.
*/
int addrTop = sqlite3VdbeCurrentAddr(v)+1;
pItem->regReturn = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
VdbeComment((v, "%s", pItem->pTab->zName));
pItem->addrFillSub = addrTop;
sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
sqlite3Select(pParse, pSub, &dest);
pItem->pTab->nRowLogEst = pSub->nSelectRow;
pItem->fg.viaCoroutine = 1;
pItem->regResult = dest.iSdst;
sqlite3VdbeEndCoroutine(v, pItem->regReturn);
sqlite3VdbeJumpHere(v, addrTop-1);
sqlite3ClearTempRegCache(pParse);
}else{
/* Generate a subroutine that will fill an ephemeral table with
** the content of this subquery. pItem->addrFillSub will point
** to the address of the generated subroutine. pItem->regReturn
** is a register allocated to hold the subroutine return address
*/
int topAddr;
int onceAddr = 0;
int retAddr;
struct SrcList_item *pPrior;
testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
pItem->regReturn = ++pParse->nMem;
topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
pItem->addrFillSub = topAddr+1;
if( pItem->fg.isCorrelated==0 ){
/* If the subquery is not correlated and if we are not inside of
** a trigger, then we only need to compute the value of the subquery
** once. */
onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
}else{
VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
}
pPrior = isSelfJoinView(pTabList, pItem);
if( pPrior ){
sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
assert( pPrior->pSelect!=0 );
pSub->nSelectRow = pPrior->pSelect->nSelectRow;
}else{
sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
sqlite3Select(pParse, pSub, &dest);
}
pItem->pTab->nRowLogEst = pSub->nSelectRow;
if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
VdbeComment((v, "end %s", pItem->pTab->zName));
sqlite3VdbeChangeP1(v, topAddr, retAddr);
sqlite3ClearTempRegCache(pParse);
}
if( db->mallocFailed ) goto select_end;
pParse->nHeight -= sqlite3SelectExprHeight(p);
pParse->zAuthContext = zSavedAuthContext;
#endif
}
/* Various elements of the SELECT copied into local variables for
** convenience */
pEList = p->pEList;
pWhere = p->pWhere;
pGroupBy = p->pGroupBy;
pHaving = p->pHaving;
sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
/* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
** if the select-list is the same as the ORDER BY list, then this query
** can be rewritten as a GROUP BY. In other words, this:
**
** SELECT DISTINCT xyz FROM ... ORDER BY xyz
**
** is transformed to:
**
** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
**
** The second form is preferred as a single index (or temp-table) may be
** used for both the ORDER BY and DISTINCT processing. As originally
** written the query must use a temp-table for at least one of the ORDER
** BY and DISTINCT, and an index or separate temp-table for the other.
*/
if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
&& sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
&& p->pWin==0
){
p->selFlags &= ~SF_Distinct;
pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
/* Notice that even thought SF_Distinct has been cleared from p->selFlags,
** the sDistinct.isTnct is still set. Hence, isTnct represents the
** original setting of the SF_Distinct flag, not the current setting */
assert( sDistinct.isTnct );
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}
/* If there is an ORDER BY clause, then create an ephemeral index to
** do the sorting. But this sorting ephemeral index might end up
** being unused if the data can be extracted in pre-sorted order.
** If that is the case, then the OP_OpenEphemeral instruction will be
** changed to an OP_Noop once we figure out that the sorting index is
** not needed. The sSort.addrSortIndex variable is used to facilitate
** that change.
*/
if( sSort.pOrderBy ){
KeyInfo *pKeyInfo;
pKeyInfo = sqlite3KeyInfoFromExprList(
pParse, sSort.pOrderBy, 0, pEList->nExpr);
sSort.iECursor = pParse->nTab++;
sSort.addrSortIndex =
sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
(char*)pKeyInfo, P4_KEYINFO
);
}else{
sSort.addrSortIndex = -1;
}
/* If the output is destined for a temporary table, open that table.
*/
if( pDest->eDest==SRT_EphemTab ){
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
}
/* Set the limiter.
*/
iEnd = sqlite3VdbeMakeLabel(pParse);
if( (p->selFlags & SF_FixedLimit)==0 ){
p->nSelectRow = 320; /* 4 billion rows */
}
computeLimitRegisters(pParse, p, iEnd);
if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
sSort.sortFlags |= SORTFLAG_UseSorter;
}
/* Open an ephemeral index to use for the distinct set.
*/
if( p->selFlags & SF_Distinct ){
sDistinct.tabTnct = pParse->nTab++;
sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
sDistinct.tabTnct, 0, 0,
(char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
P4_KEYINFO);
sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
}else{
sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
}
if( !isAgg && pGroupBy==0 ){
/* No aggregate functions and no GROUP BY clause */
u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
| (p->selFlags & SF_FixedLimit);
#ifndef SQLITE_OMIT_WINDOWFUNC
Window *pWin = p->pWin; /* Master window object (or NULL) */
if( pWin ){
sqlite3WindowCodeInit(pParse, pWin);
}
#endif
assert( WHERE_USE_LIMIT==SF_FixedLimit );
/* Begin the database scan. */
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
p->pEList, wctrlFlags, p->nSelectRow);
if( pWInfo==0 ) goto select_end;
if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
}
if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
}
if( sSort.pOrderBy ){
sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
sSort.pOrderBy = 0;
}
}
/* If sorting index that was created by a prior OP_OpenEphemeral
** instruction ended up not being needed, then change the OP_OpenEphemeral
** into an OP_Noop.
*/
if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
}
assert( p->pEList==pEList );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pWin ){
int addrGosub = sqlite3VdbeMakeLabel(pParse);
int iCont = sqlite3VdbeMakeLabel(pParse);
int iBreak = sqlite3VdbeMakeLabel(pParse);
int regGosub = ++pParse->nMem;
sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
sqlite3VdbeResolveLabel(v, addrGosub);
VdbeNoopComment((v, "inner-loop subroutine"));
sSort.labelOBLopt = 0;
selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp1(v, OP_Return, regGosub);
VdbeComment((v, "end inner-loop subroutine"));
sqlite3VdbeResolveLabel(v, iBreak);
}else
#endif /* SQLITE_OMIT_WINDOWFUNC */
{
/* Use the standard inner loop. */
selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
sqlite3WhereContinueLabel(pWInfo),
sqlite3WhereBreakLabel(pWInfo));
/* End the database scan loop.
*/
sqlite3WhereEnd(pWInfo);
}
}else{
/* This case when there exist aggregate functions or a GROUP BY clause
** or both */
NameContext sNC; /* Name context for processing aggregate information */
int iAMem; /* First Mem address for storing current GROUP BY */
int iBMem; /* First Mem address for previous GROUP BY */
int iUseFlag; /* Mem address holding flag indicating that at least
** one row of the input to the aggregator has been
** processed */
int iAbortFlag; /* Mem address which causes query abort if positive */
int groupBySort; /* Rows come from source in GROUP BY order */
int addrEnd; /* End of processing for this SELECT */
int sortPTab = 0; /* Pseudotable used to decode sorting results */
int sortOut = 0; /* Output register from the sorter */
int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
/* Remove any and all aliases between the result set and the
** GROUP BY clause.
*/
if( pGroupBy ){
int k; /* Loop counter */
struct ExprList_item *pItem; /* For looping over expression in a list */
for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
pItem->u.x.iAlias = 0;
}
for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
pItem->u.x.iAlias = 0;
}
assert( 66==sqlite3LogEst(100) );
if( p->nSelectRow>66 ) p->nSelectRow = 66;
/* If there is both a GROUP BY and an ORDER BY clause and they are
** identical, then it may be possible to disable the ORDER BY clause
** on the grounds that the GROUP BY will cause elements to come out
** in the correct order. It also may not - the GROUP BY might use a
** database index that causes rows to be grouped together as required
** but not actually sorted. Either way, record the fact that the
** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
** variable. */
if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
int ii;
/* The GROUP BY processing doesn't care whether rows are delivered in
** ASC or DESC order - only that each group is returned contiguously.
** So set the ASC/DESC flags in the GROUP BY to match those in the
** ORDER BY to maximize the chances of rows being delivered in an
** order that makes the ORDER BY redundant. */
for(ii=0; ii<pGroupBy->nExpr; ii++){
u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
pGroupBy->a[ii].sortFlags = sortFlags;
}
if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
orderByGrp = 1;
}
}
}else{
assert( 0==sqlite3LogEst(1) );
p->nSelectRow = 0;
}
/* Create a label to jump to when we want to abort the query */
addrEnd = sqlite3VdbeMakeLabel(pParse);
/* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
** SELECT statement.
*/
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
sNC.uNC.pAggInfo = &sAggInfo;
VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
sAggInfo.mnReg = pParse->nMem+1;
sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
sAggInfo.pGroupBy = pGroupBy;
sqlite3ExprAnalyzeAggList(&sNC, pEList);
sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
if( pHaving ){
if( pGroupBy ){
assert( pWhere==p->pWhere );
assert( pHaving==p->pHaving );
assert( pGroupBy==p->pGroupBy );
havingToWhere(pParse, p);
pWhere = p->pWhere;
}
sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
}
sAggInfo.nAccumulator = sAggInfo.nColumn;
if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
}else{
minMaxFlag = WHERE_ORDERBY_NORMAL;
}
for(i=0; i<sAggInfo.nFunc; i++){
Expr *pExpr = sAggInfo.aFunc[i].pExpr;
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
sNC.ncFlags |= NC_InAggFunc;
sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( !IsWindowFunc(pExpr) );
if( ExprHasProperty(pExpr, EP_WinFunc) ){
sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
}
#endif
sNC.ncFlags &= ~NC_InAggFunc;
}
sAggInfo.mxReg = pParse->nMem;
if( db->mallocFailed ) goto select_end;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
int ii;
SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
sqlite3TreeViewSelect(0, p, 0);
for(ii=0; ii<sAggInfo.nColumn; ii++){
sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
ii, sAggInfo.aCol[ii].iMem);
sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
}
for(ii=0; ii<sAggInfo.nFunc; ii++){
sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
ii, sAggInfo.aFunc[ii].iMem);
sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
}
}
#endif
/* Processing for aggregates with GROUP BY is very different and
** much more complex than aggregates without a GROUP BY.
*/
if( pGroupBy ){
KeyInfo *pKeyInfo; /* Keying information for the group by clause */
int addr1; /* A-vs-B comparision jump */
int addrOutputRow; /* Start of subroutine that outputs a result row */
int regOutputRow; /* Return address register for output subroutine */
int addrSetAbort; /* Set the abort flag and return */
int addrTopOfLoop; /* Top of the input loop */
int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
int addrReset; /* Subroutine for resetting the accumulator */
int regReset; /* Return address register for reset subroutine */
/* If there is a GROUP BY clause we might need a sorting index to
** implement it. Allocate that sorting index now. If it turns out
** that we do not need it after all, the OP_SorterOpen instruction
** will be converted into a Noop.
*/
sAggInfo.sortingIdx = pParse->nTab++;
pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
0, (char*)pKeyInfo, P4_KEYINFO);
/* Initialize memory locations used by GROUP BY aggregate processing
*/
iUseFlag = ++pParse->nMem;
iAbortFlag = ++pParse->nMem;
regOutputRow = ++pParse->nMem;
addrOutputRow = sqlite3VdbeMakeLabel(pParse);
regReset = ++pParse->nMem;
addrReset = sqlite3VdbeMakeLabel(pParse);
iAMem = pParse->nMem + 1;
pParse->nMem += pGroupBy->nExpr;
iBMem = pParse->nMem + 1;
pParse->nMem += pGroupBy->nExpr;
sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
VdbeComment((v, "clear abort flag"));
sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
/* Begin a loop that will extract all source rows in GROUP BY order.
** This might involve two separate loops with an OP_Sort in between, or
** it might be a single loop that uses an index to extract information
** in the right order to begin with.
*/
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
);
if( pWInfo==0 ) goto select_end;
if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
/* The optimizer is able to deliver rows in group by order so
** we do not have to sort. The OP_OpenEphemeral table will be
** cancelled later because we still need to use the pKeyInfo
*/
groupBySort = 0;
}else{
/* Rows are coming out in undetermined order. We have to push
** each row into a sorting index, terminate the first loop,
** then loop over the sorting index in order to get the output
** in sorted order
*/
int regBase;
int regRecord;
int nCol;
int nGroupBy;
explainTempTable(pParse,
(sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
"DISTINCT" : "GROUP BY");
groupBySort = 1;
nGroupBy = pGroupBy->nExpr;
nCol = nGroupBy;
j = nGroupBy;
for(i=0; i<sAggInfo.nColumn; i++){
if( sAggInfo.aCol[i].iSorterColumn>=j ){
nCol++;
j++;
}
}
regBase = sqlite3GetTempRange(pParse, nCol);
sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
j = nGroupBy;
for(i=0; i<sAggInfo.nColumn; i++){
struct AggInfo_col *pCol = &sAggInfo.aCol[i];
if( pCol->iSorterColumn>=j ){
int r1 = j + regBase;
sqlite3ExprCodeGetColumnOfTable(v,
pCol->pTab, pCol->iTable, pCol->iColumn, r1);
j++;
}
}
regRecord = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
sqlite3ReleaseTempReg(pParse, regRecord);
sqlite3ReleaseTempRange(pParse, regBase, nCol);
sqlite3WhereEnd(pWInfo);
sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
sortOut = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
sAggInfo.useSortingIdx = 1;
}
/* If the index or temporary table used by the GROUP BY sort
** will naturally deliver rows in the order required by the ORDER BY
** clause, cancel the ephemeral table open coded earlier.
**
** This is an optimization - the correct answer should result regardless.
** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
** disable this optimization for testing purposes. */
if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
&& (groupBySort || sqlite3WhereIsSorted(pWInfo))
){
sSort.pOrderBy = 0;
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
}
/* Evaluate the current GROUP BY terms and store in b0, b1, b2...
** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
** Then compare the current GROUP BY terms against the GROUP BY terms
** from the previous row currently stored in a0, a1, a2...
*/
addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
if( groupBySort ){
sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
sortOut, sortPTab);
}
for(j=0; j<pGroupBy->nExpr; j++){
if( groupBySort ){
sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
}else{
sAggInfo.directMode = 1;
sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
}
}
sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
addr1 = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
/* Generate code that runs whenever the GROUP BY changes.
** Changes in the GROUP BY are detected by the previous code
** block. If there were no changes, this block is skipped.
**
** This code copies current group by terms in b0,b1,b2,...
** over to a0,a1,a2. It then calls the output subroutine
** and resets the aggregate accumulator registers in preparation
** for the next GROUP BY batch.
*/
sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
VdbeComment((v, "output one row"));
sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
VdbeComment((v, "check abort flag"));
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
VdbeComment((v, "reset accumulator"));
/* Update the aggregate accumulators based on the content of
** the current row
*/
sqlite3VdbeJumpHere(v, addr1);
updateAccumulator(pParse, iUseFlag, &sAggInfo);
sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
VdbeComment((v, "indicate data in accumulator"));
/* End of the loop
*/
if( groupBySort ){
sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
VdbeCoverage(v);
}else{
sqlite3WhereEnd(pWInfo);
sqlite3VdbeChangeToNoop(v, addrSortingIdx);
}
/* Output the final row of result
*/
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
VdbeComment((v, "output final row"));
/* Jump over the subroutines
*/
sqlite3VdbeGoto(v, addrEnd);
/* Generate a subroutine that outputs a single row of the result
** set. This subroutine first looks at the iUseFlag. If iUseFlag
** is less than or equal to zero, the subroutine is a no-op. If
** the processing calls for the query to abort, this subroutine
** increments the iAbortFlag memory location before returning in
** order to signal the caller to abort.
*/
addrSetAbort = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
VdbeComment((v, "set abort flag"));
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
sqlite3VdbeResolveLabel(v, addrOutputRow);
addrOutputRow = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
VdbeCoverage(v);
VdbeComment((v, "Groupby result generator entry point"));
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
finalizeAggFunctions(pParse, &sAggInfo);
sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
selectInnerLoop(pParse, p, -1, &sSort,
&sDistinct, pDest,
addrOutputRow+1, addrSetAbort);
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
VdbeComment((v, "end groupby result generator"));
/* Generate a subroutine that will reset the group-by accumulator
*/
sqlite3VdbeResolveLabel(v, addrReset);
resetAccumulator(pParse, &sAggInfo);
sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
VdbeComment((v, "indicate accumulator empty"));
sqlite3VdbeAddOp1(v, OP_Return, regReset);
} /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
else {
#ifndef SQLITE_OMIT_BTREECOUNT
Table *pTab;
if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
/* If isSimpleCount() returns a pointer to a Table structure, then
** the SQL statement is of the form:
**
** SELECT count(*) FROM <tbl>
**
** where the Table structure returned represents table <tbl>.
**
** This statement is so common that it is optimized specially. The
** OP_Count instruction is executed either on the intkey table that
** contains the data for table <tbl> or on one of its indexes. It
** is better to execute the op on an index, as indexes are almost
** always spread across less pages than their corresponding tables.
*/
const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
Index *pIdx; /* Iterator variable */
KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
Index *pBest = 0; /* Best index found so far */
int iRoot = pTab->tnum; /* Root page of scanned b-tree */
sqlite3CodeVerifySchema(pParse, iDb);
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
/* Search for the index that has the lowest scan cost.
**
** (2011-04-15) Do not do a full scan of an unordered index.
**
** (2013-10-03) Do not count the entries in a partial index.
**
** In practice the KeyInfo structure will not be used. It is only
** passed to keep OP_OpenRead happy.
*/
if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
if( pIdx->bUnordered==0
&& pIdx->szIdxRow<pTab->szTabRow
&& pIdx->pPartIdxWhere==0
&& (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
){
pBest = pIdx;
}
}
if( pBest ){
iRoot = pBest->tnum;
pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
}
/* Open a read-only cursor, execute the OP_Count, close the cursor. */
sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
if( pKeyInfo ){
sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
}
sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
sqlite3VdbeAddOp1(v, OP_Close, iCsr);
explainSimpleCount(pParse, pTab, pBest);
}else
#endif /* SQLITE_OMIT_BTREECOUNT */
{
int regAcc = 0; /* "populate accumulators" flag */
/* If there are accumulator registers but no min() or max() functions
** without FILTER clauses, allocate register regAcc. Register regAcc
** will contain 0 the first time the inner loop runs, and 1 thereafter.
** The code generated by updateAccumulator() uses this to ensure
** that the accumulator registers are (a) updated only once if
** there are no min() or max functions or (b) always updated for the
** first row visited by the aggregate, so that they are updated at
** least once even if the FILTER clause means the min() or max()
** function visits zero rows. */
if( sAggInfo.nAccumulator ){
for(i=0; i<sAggInfo.nFunc; i++){
if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue;
if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
}
if( i==sAggInfo.nFunc ){
regAcc = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
}
}
/* This case runs if the aggregate has no GROUP BY clause. The
** processing is much simpler since there is only a single row
** of output.
*/
assert( p->pGroupBy==0 );
resetAccumulator(pParse, &sAggInfo);
/* If this query is a candidate for the min/max optimization, then
** minMaxFlag will have been previously set to either
** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
** be an appropriate ORDER BY expression for the optimization.
*/
assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
0, minMaxFlag, 0);
if( pWInfo==0 ){
goto select_end;
}
updateAccumulator(pParse, regAcc, &sAggInfo);
if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
if( sqlite3WhereIsOrdered(pWInfo)>0 ){
sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
VdbeComment((v, "%s() by index",
(minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
}
sqlite3WhereEnd(pWInfo);
finalizeAggFunctions(pParse, &sAggInfo);
}
sSort.pOrderBy = 0;
sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
selectInnerLoop(pParse, p, -1, 0, 0,
pDest, addrEnd, addrEnd);
}
sqlite3VdbeResolveLabel(v, addrEnd);
} /* endif aggregate query */
if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
explainTempTable(pParse, "DISTINCT");
}
/* If there is an ORDER BY clause, then we need to sort the results
** and send them to the callback one by one.
*/
if( sSort.pOrderBy ){
explainTempTable(pParse,
sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
assert( p->pEList==pEList );
generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
}
/* Jump here to skip this query
*/
sqlite3VdbeResolveLabel(v, iEnd);
/* The SELECT has been coded. If there is an error in the Parse structure,
** set the return code to 1. Otherwise 0. */
rc = (pParse->nErr>0);
/* Control jumps to here if an error is encountered above, or upon
** successful coding of the SELECT.
*/
select_end:
sqlite3ExprListDelete(db, pMinMaxOrderBy);
sqlite3DbFree(db, sAggInfo.aCol);
sqlite3DbFree(db, sAggInfo.aFunc);
#if SELECTTRACE_ENABLED
SELECTTRACE(0x1,pParse,p,("end processing\n"));
if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
ExplainQueryPlanPop(pParse);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_1352_2 |
crossvul-cpp_data_bad_1325_4 | /*
** 2018 May 08
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
*/
#include "sqliteInt.h"
#ifndef SQLITE_OMIT_WINDOWFUNC
/*
** SELECT REWRITING
**
** Any SELECT statement that contains one or more window functions in
** either the select list or ORDER BY clause (the only two places window
** functions may be used) is transformed by function sqlite3WindowRewrite()
** in order to support window function processing. For example, with the
** schema:
**
** CREATE TABLE t1(a, b, c, d, e, f, g);
**
** the statement:
**
** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
**
** is transformed to:
**
** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
** ) ORDER BY e;
**
** The flattening optimization is disabled when processing this transformed
** SELECT statement. This allows the implementation of the window function
** (in this case max()) to process rows sorted in order of (c, d), which
** makes things easier for obvious reasons. More generally:
**
** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
** the sub-query.
**
** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
**
** * Terminals from each of the expression trees that make up the
** select-list and ORDER BY expressions in the parent query are
** selected by the sub-query. For the purposes of the transformation,
** terminals are column references and aggregate functions.
**
** If there is more than one window function in the SELECT that uses
** the same window declaration (the OVER bit), then a single scan may
** be used to process more than one window function. For example:
**
** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
** min(e) OVER (PARTITION BY c ORDER BY d)
** FROM t1;
**
** is transformed in the same way as the example above. However:
**
** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
** min(e) OVER (PARTITION BY a ORDER BY b)
** FROM t1;
**
** Must be transformed to:
**
** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
** ) ORDER BY c, d
** ) ORDER BY e;
**
** so that both min() and max() may process rows in the order defined by
** their respective window declarations.
**
** INTERFACE WITH SELECT.C
**
** When processing the rewritten SELECT statement, code in select.c calls
** sqlite3WhereBegin() to begin iterating through the results of the
** sub-query, which is always implemented as a co-routine. It then calls
** sqlite3WindowCodeStep() to process rows and finish the scan by calling
** sqlite3WhereEnd().
**
** sqlite3WindowCodeStep() generates VM code so that, for each row returned
** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
** When the sub-routine is invoked:
**
** * The results of all window-functions for the row are stored
** in the associated Window.regResult registers.
**
** * The required terminal values are stored in the current row of
** temp table Window.iEphCsr.
**
** In some cases, depending on the window frame and the specific window
** functions invoked, sqlite3WindowCodeStep() caches each entire partition
** in a temp table before returning any rows. In other cases it does not.
** This detail is encapsulated within this file, the code generated by
** select.c is the same in either case.
**
** BUILT-IN WINDOW FUNCTIONS
**
** This implementation features the following built-in window functions:
**
** row_number()
** rank()
** dense_rank()
** percent_rank()
** cume_dist()
** ntile(N)
** lead(expr [, offset [, default]])
** lag(expr [, offset [, default]])
** first_value(expr)
** last_value(expr)
** nth_value(expr, N)
**
** These are the same built-in window functions supported by Postgres.
** Although the behaviour of aggregate window functions (functions that
** can be used as either aggregates or window funtions) allows them to
** be implemented using an API, built-in window functions are much more
** esoteric. Additionally, some window functions (e.g. nth_value())
** may only be implemented by caching the entire partition in memory.
** As such, some built-in window functions use the same API as aggregate
** window functions and some are implemented directly using VDBE
** instructions. Additionally, for those functions that use the API, the
** window frame is sometimes modified before the SELECT statement is
** rewritten. For example, regardless of the specified window frame, the
** row_number() function always uses:
**
** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
**
** See sqlite3WindowUpdate() for details.
**
** As well as some of the built-in window functions, aggregate window
** functions min() and max() are implemented using VDBE instructions if
** the start of the window frame is declared as anything other than
** UNBOUNDED PRECEDING.
*/
/*
** Implementation of built-in window function row_number(). Assumes that the
** window frame has been coerced to:
**
** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
*/
static void row_numberStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ) (*p)++;
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void row_numberValueFunc(sqlite3_context *pCtx){
i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
sqlite3_result_int64(pCtx, (p ? *p : 0));
}
/*
** Context object type used by rank(), dense_rank(), percent_rank() and
** cume_dist().
*/
struct CallCount {
i64 nValue;
i64 nStep;
i64 nTotal;
};
/*
** Implementation of built-in window function dense_rank(). Assumes that
** the window frame has been set to:
**
** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
*/
static void dense_rankStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ) p->nStep = 1;
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void dense_rankValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
if( p->nStep ){
p->nValue++;
p->nStep = 0;
}
sqlite3_result_int64(pCtx, p->nValue);
}
}
/*
** Implementation of built-in window function nth_value(). This
** implementation is used in "slow mode" only - when the EXCLUDE clause
** is not set to the default value "NO OTHERS".
*/
struct NthValueCtx {
i64 nStep;
sqlite3_value *pValue;
};
static void nth_valueStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
i64 iVal;
switch( sqlite3_value_numeric_type(apArg[1]) ){
case SQLITE_INTEGER:
iVal = sqlite3_value_int64(apArg[1]);
break;
case SQLITE_FLOAT: {
double fVal = sqlite3_value_double(apArg[1]);
if( ((i64)fVal)!=fVal ) goto error_out;
iVal = (i64)fVal;
break;
}
default:
goto error_out;
}
if( iVal<=0 ) goto error_out;
p->nStep++;
if( iVal==p->nStep ){
p->pValue = sqlite3_value_dup(apArg[0]);
if( !p->pValue ){
sqlite3_result_error_nomem(pCtx);
}
}
}
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
return;
error_out:
sqlite3_result_error(
pCtx, "second argument to nth_value must be a positive integer", -1
);
}
static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
if( p && p->pValue ){
sqlite3_result_value(pCtx, p->pValue);
sqlite3_value_free(p->pValue);
p->pValue = 0;
}
}
#define nth_valueInvFunc noopStepFunc
#define nth_valueValueFunc noopValueFunc
static void first_valueStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->pValue==0 ){
p->pValue = sqlite3_value_dup(apArg[0]);
if( !p->pValue ){
sqlite3_result_error_nomem(pCtx);
}
}
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void first_valueFinalizeFunc(sqlite3_context *pCtx){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->pValue ){
sqlite3_result_value(pCtx, p->pValue);
sqlite3_value_free(p->pValue);
p->pValue = 0;
}
}
#define first_valueInvFunc noopStepFunc
#define first_valueValueFunc noopValueFunc
/*
** Implementation of built-in window function rank(). Assumes that
** the window frame has been set to:
**
** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
*/
static void rankStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nStep++;
if( p->nValue==0 ){
p->nValue = p->nStep;
}
}
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void rankValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
sqlite3_result_int64(pCtx, p->nValue);
p->nValue = 0;
}
}
/*
** Implementation of built-in window function percent_rank(). Assumes that
** the window frame has been set to:
**
** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
*/
static void percent_rankStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nTotal++;
}
}
static void percent_rankInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
p->nStep++;
}
static void percent_rankValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nValue = p->nStep;
if( p->nTotal>1 ){
double r = (double)p->nValue / (double)(p->nTotal-1);
sqlite3_result_double(pCtx, r);
}else{
sqlite3_result_double(pCtx, 0.0);
}
}
}
#define percent_rankFinalizeFunc percent_rankValueFunc
/*
** Implementation of built-in window function cume_dist(). Assumes that
** the window frame has been set to:
**
** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
*/
static void cume_distStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nTotal++;
}
}
static void cume_distInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
p->nStep++;
}
static void cume_distValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
if( p ){
double r = (double)(p->nStep) / (double)(p->nTotal);
sqlite3_result_double(pCtx, r);
}
}
#define cume_distFinalizeFunc cume_distValueFunc
/*
** Context object for ntile() window function.
*/
struct NtileCtx {
i64 nTotal; /* Total rows in partition */
i64 nParam; /* Parameter passed to ntile(N) */
i64 iRow; /* Current row */
};
/*
** Implementation of ntile(). This assumes that the window frame has
** been coerced to:
**
** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
*/
static void ntileStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NtileCtx *p;
assert( nArg==1 ); UNUSED_PARAMETER(nArg);
p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
if( p->nTotal==0 ){
p->nParam = sqlite3_value_int64(apArg[0]);
if( p->nParam<=0 ){
sqlite3_result_error(
pCtx, "argument of ntile must be a positive integer", -1
);
}
}
p->nTotal++;
}
}
static void ntileInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NtileCtx *p;
assert( nArg==1 ); UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
p->iRow++;
}
static void ntileValueFunc(sqlite3_context *pCtx){
struct NtileCtx *p;
p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->nParam>0 ){
int nSize = (p->nTotal / p->nParam);
if( nSize==0 ){
sqlite3_result_int64(pCtx, p->iRow+1);
}else{
i64 nLarge = p->nTotal - p->nParam*nSize;
i64 iSmall = nLarge*(nSize+1);
i64 iRow = p->iRow;
assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
if( iRow<iSmall ){
sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
}else{
sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
}
}
}
}
#define ntileFinalizeFunc ntileValueFunc
/*
** Context object for last_value() window function.
*/
struct LastValueCtx {
sqlite3_value *pVal;
int nVal;
};
/*
** Implementation of last_value().
*/
static void last_valueStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct LastValueCtx *p;
UNUSED_PARAMETER(nArg);
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
sqlite3_value_free(p->pVal);
p->pVal = sqlite3_value_dup(apArg[0]);
if( p->pVal==0 ){
sqlite3_result_error_nomem(pCtx);
}else{
p->nVal++;
}
}
}
static void last_valueInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct LastValueCtx *p;
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( ALWAYS(p) ){
p->nVal--;
if( p->nVal==0 ){
sqlite3_value_free(p->pVal);
p->pVal = 0;
}
}
}
static void last_valueValueFunc(sqlite3_context *pCtx){
struct LastValueCtx *p;
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
if( p && p->pVal ){
sqlite3_result_value(pCtx, p->pVal);
}
}
static void last_valueFinalizeFunc(sqlite3_context *pCtx){
struct LastValueCtx *p;
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->pVal ){
sqlite3_result_value(pCtx, p->pVal);
sqlite3_value_free(p->pVal);
p->pVal = 0;
}
}
/*
** Static names for the built-in window function names. These static
** names are used, rather than string literals, so that FuncDef objects
** can be associated with a particular window function by direct
** comparison of the zName pointer. Example:
**
** if( pFuncDef->zName==row_valueName ){ ... }
*/
static const char row_numberName[] = "row_number";
static const char dense_rankName[] = "dense_rank";
static const char rankName[] = "rank";
static const char percent_rankName[] = "percent_rank";
static const char cume_distName[] = "cume_dist";
static const char ntileName[] = "ntile";
static const char last_valueName[] = "last_value";
static const char nth_valueName[] = "nth_value";
static const char first_valueName[] = "first_value";
static const char leadName[] = "lead";
static const char lagName[] = "lag";
/*
** No-op implementations of xStep() and xFinalize(). Used as place-holders
** for built-in window functions that never call those interfaces.
**
** The noopValueFunc() is called but is expected to do nothing. The
** noopStepFunc() is never called, and so it is marked with NO_TEST to
** let the test coverage routine know not to expect this function to be
** invoked.
*/
static void noopStepFunc( /*NO_TEST*/
sqlite3_context *p, /*NO_TEST*/
int n, /*NO_TEST*/
sqlite3_value **a /*NO_TEST*/
){ /*NO_TEST*/
UNUSED_PARAMETER(p); /*NO_TEST*/
UNUSED_PARAMETER(n); /*NO_TEST*/
UNUSED_PARAMETER(a); /*NO_TEST*/
assert(0); /*NO_TEST*/
} /*NO_TEST*/
static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
/* Window functions that use all window interfaces: xStep, xFinal,
** xValue, and xInverse */
#define WINDOWFUNCALL(name,nArg,extra) { \
nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
name ## InvFunc, name ## Name, {0} \
}
/* Window functions that are implemented using bytecode and thus have
** no-op routines for their methods */
#define WINDOWFUNCNOOP(name,nArg,extra) { \
nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
noopStepFunc, noopValueFunc, noopValueFunc, \
noopStepFunc, name ## Name, {0} \
}
/* Window functions that use all window interfaces: xStep, the
** same routine for xFinalize and xValue and which never call
** xInverse. */
#define WINDOWFUNCX(name,nArg,extra) { \
nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
noopStepFunc, name ## Name, {0} \
}
/*
** Register those built-in window functions that are not also aggregates.
*/
void sqlite3WindowFunctions(void){
static FuncDef aWindowFuncs[] = {
WINDOWFUNCX(row_number, 0, 0),
WINDOWFUNCX(dense_rank, 0, 0),
WINDOWFUNCX(rank, 0, 0),
WINDOWFUNCALL(percent_rank, 0, 0),
WINDOWFUNCALL(cume_dist, 0, 0),
WINDOWFUNCALL(ntile, 1, 0),
WINDOWFUNCALL(last_value, 1, 0),
WINDOWFUNCALL(nth_value, 2, 0),
WINDOWFUNCALL(first_value, 1, 0),
WINDOWFUNCNOOP(lead, 1, 0),
WINDOWFUNCNOOP(lead, 2, 0),
WINDOWFUNCNOOP(lead, 3, 0),
WINDOWFUNCNOOP(lag, 1, 0),
WINDOWFUNCNOOP(lag, 2, 0),
WINDOWFUNCNOOP(lag, 3, 0),
};
sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
}
static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
Window *p;
for(p=pList; p; p=p->pNextWin){
if( sqlite3StrICmp(p->zName, zName)==0 ) break;
}
if( p==0 ){
sqlite3ErrorMsg(pParse, "no such window: %s", zName);
}
return p;
}
/*
** This function is called immediately after resolving the function name
** for a window function within a SELECT statement. Argument pList is a
** linked list of WINDOW definitions for the current SELECT statement.
** Argument pFunc is the function definition just resolved and pWin
** is the Window object representing the associated OVER clause. This
** function updates the contents of pWin as follows:
**
** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
** search list pList for a matching WINDOW definition, and update pWin
** accordingly. If no such WINDOW clause can be found, leave an error
** in pParse.
**
** * If the function is a built-in window function that requires the
** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
** of this file), pWin is updated here.
*/
void sqlite3WindowUpdate(
Parse *pParse,
Window *pList, /* List of named windows for this SELECT */
Window *pWin, /* Window frame to update */
FuncDef *pFunc /* Window function definition */
){
if( pWin->zName && pWin->eFrmType==0 ){
Window *p = windowFind(pParse, pList, pWin->zName);
if( p==0 ) return;
pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
pWin->eStart = p->eStart;
pWin->eEnd = p->eEnd;
pWin->eFrmType = p->eFrmType;
pWin->eExclude = p->eExclude;
}else{
sqlite3WindowChain(pParse, pWin, pList);
}
if( (pWin->eFrmType==TK_RANGE)
&& (pWin->pStart || pWin->pEnd)
&& (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
){
sqlite3ErrorMsg(pParse,
"RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
);
}else
if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
sqlite3 *db = pParse->db;
if( pWin->pFilter ){
sqlite3ErrorMsg(pParse,
"FILTER clause may only be used with aggregate window functions"
);
}else{
struct WindowUpdate {
const char *zFunc;
int eFrmType;
int eStart;
int eEnd;
} aUp[] = {
{ row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
{ dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
{ rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
{ percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
{ cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
{ ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
{ leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
{ lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
};
int i;
for(i=0; i<ArraySize(aUp); i++){
if( pFunc->zName==aUp[i].zFunc ){
sqlite3ExprDelete(db, pWin->pStart);
sqlite3ExprDelete(db, pWin->pEnd);
pWin->pEnd = pWin->pStart = 0;
pWin->eFrmType = aUp[i].eFrmType;
pWin->eStart = aUp[i].eStart;
pWin->eEnd = aUp[i].eEnd;
pWin->eExclude = 0;
if( pWin->eStart==TK_FOLLOWING ){
pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
}
break;
}
}
}
}
pWin->pFunc = pFunc;
}
/*
** Context object passed through sqlite3WalkExprList() to
** selectWindowRewriteExprCb() by selectWindowRewriteEList().
*/
typedef struct WindowRewrite WindowRewrite;
struct WindowRewrite {
Window *pWin;
SrcList *pSrc;
ExprList *pSub;
Table *pTab;
Select *pSubSelect; /* Current sub-select, if any */
};
/*
** Callback function used by selectWindowRewriteEList(). If necessary,
** this function appends to the output expression-list and updates
** expression (*ppExpr) in place.
*/
static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
struct WindowRewrite *p = pWalker->u.pRewrite;
Parse *pParse = pWalker->pParse;
assert( p!=0 );
assert( p->pWin!=0 );
/* If this function is being called from within a scalar sub-select
** that used by the SELECT statement being processed, only process
** TK_COLUMN expressions that refer to it (the outer SELECT). Do
** not process aggregates or window functions at all, as they belong
** to the scalar sub-select. */
if( p->pSubSelect ){
if( pExpr->op!=TK_COLUMN ){
return WRC_Continue;
}else{
int nSrc = p->pSrc->nSrc;
int i;
for(i=0; i<nSrc; i++){
if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
}
if( i==nSrc ) return WRC_Continue;
}
}
switch( pExpr->op ){
case TK_FUNCTION:
if( !ExprHasProperty(pExpr, EP_WinFunc) ){
break;
}else{
Window *pWin;
for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
if( pExpr->y.pWin==pWin ){
assert( pWin->pOwner==pExpr );
return WRC_Prune;
}
}
}
/* Fall through. */
case TK_AGG_FUNCTION:
case TK_COLUMN: {
int iCol = -1;
if( p->pSub ){
int i;
for(i=0; i<p->pSub->nExpr; i++){
if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
iCol = i;
break;
}
}
}
if( iCol<0 ){
Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
}
if( p->pSub ){
assert( ExprHasProperty(pExpr, EP_Static)==0 );
ExprSetProperty(pExpr, EP_Static);
sqlite3ExprDelete(pParse->db, pExpr);
ExprClearProperty(pExpr, EP_Static);
memset(pExpr, 0, sizeof(Expr));
pExpr->op = TK_COLUMN;
pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
pExpr->iTable = p->pWin->iEphCsr;
pExpr->y.pTab = p->pTab;
}
if( pParse->db->mallocFailed ) return WRC_Abort;
break;
}
default: /* no-op */
break;
}
return WRC_Continue;
}
static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
struct WindowRewrite *p = pWalker->u.pRewrite;
Select *pSave = p->pSubSelect;
if( pSave==pSelect ){
return WRC_Continue;
}else{
p->pSubSelect = pSelect;
sqlite3WalkSelect(pWalker, pSelect);
p->pSubSelect = pSave;
}
return WRC_Prune;
}
/*
** Iterate through each expression in expression-list pEList. For each:
**
** * TK_COLUMN,
** * aggregate function, or
** * window function with a Window object that is not a member of the
** Window list passed as the second argument (pWin).
**
** Append the node to output expression-list (*ppSub). And replace it
** with a TK_COLUMN that reads the (N-1)th element of table
** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
** appending the new one.
*/
static void selectWindowRewriteEList(
Parse *pParse,
Window *pWin,
SrcList *pSrc,
ExprList *pEList, /* Rewrite expressions in this list */
Table *pTab,
ExprList **ppSub /* IN/OUT: Sub-select expression-list */
){
Walker sWalker;
WindowRewrite sRewrite;
assert( pWin!=0 );
memset(&sWalker, 0, sizeof(Walker));
memset(&sRewrite, 0, sizeof(WindowRewrite));
sRewrite.pSub = *ppSub;
sRewrite.pWin = pWin;
sRewrite.pSrc = pSrc;
sRewrite.pTab = pTab;
sWalker.pParse = pParse;
sWalker.xExprCallback = selectWindowRewriteExprCb;
sWalker.xSelectCallback = selectWindowRewriteSelectCb;
sWalker.u.pRewrite = &sRewrite;
(void)sqlite3WalkExprList(&sWalker, pEList);
*ppSub = sRewrite.pSub;
}
/*
** Append a copy of each expression in expression-list pAppend to
** expression list pList. Return a pointer to the result list.
*/
static ExprList *exprListAppendList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
ExprList *pAppend, /* List of values to append. Might be NULL */
int bIntToNull
){
if( pAppend ){
int i;
int nInit = pList ? pList->nExpr : 0;
for(i=0; i<pAppend->nExpr; i++){
Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
pDup->op = TK_NULL;
pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
pDup->u.zToken = 0;
}
pList = sqlite3ExprListAppend(pParse, pList, pDup);
if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
}
}
return pList;
}
/*
** If the SELECT statement passed as the second argument does not invoke
** any SQL window functions, this function is a no-op. Otherwise, it
** rewrites the SELECT statement so that window function xStep functions
** are invoked in the correct order as described under "SELECT REWRITING"
** at the top of this file.
*/
int sqlite3WindowRewrite(Parse *pParse, Select *p){
int rc = SQLITE_OK;
if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
Vdbe *v = sqlite3GetVdbe(pParse);
sqlite3 *db = pParse->db;
Select *pSub = 0; /* The subquery */
SrcList *pSrc = p->pSrc;
Expr *pWhere = p->pWhere;
ExprList *pGroupBy = p->pGroupBy;
Expr *pHaving = p->pHaving;
ExprList *pSort = 0;
ExprList *pSublist = 0; /* Expression list for sub-query */
Window *pMWin = p->pWin; /* Master window object */
Window *pWin; /* Window object iterator */
Table *pTab;
pTab = sqlite3DbMallocZero(db, sizeof(Table));
if( pTab==0 ){
return SQLITE_NOMEM;
}
p->pSrc = 0;
p->pWhere = 0;
p->pGroupBy = 0;
p->pHaving = 0;
p->selFlags &= ~SF_Aggregate;
p->selFlags |= SF_WinRewrite;
/* Create the ORDER BY clause for the sub-select. This is the concatenation
** of the window PARTITION and ORDER BY clauses. Then, if this makes it
** redundant, remove the ORDER BY from the parent SELECT. */
pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
int nSave = pSort->nExpr;
pSort->nExpr = p->pOrderBy->nExpr;
if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
sqlite3ExprListDelete(db, p->pOrderBy);
p->pOrderBy = 0;
}
pSort->nExpr = nSave;
}
/* Assign a cursor number for the ephemeral table used to buffer rows.
** The OpenEphemeral instruction is coded later, after it is known how
** many columns the table will have. */
pMWin->iEphCsr = pParse->nTab++;
pParse->nTab += 3;
selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
/* Append the PARTITION BY and ORDER BY expressions to the to the
** sub-select expression list. They are required to figure out where
** boundaries for partitions and sets of peer rows lie. */
pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
/* Append the arguments passed to each window function to the
** sub-select expression list. Also allocate two registers for each
** window function - one for the accumulator, another for interim
** results. */
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
ExprList *pArgs = pWin->pOwner->x.pList;
if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
pWin->bExprArgs = 1;
}else{
pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
}
if( pWin->pFilter ){
Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
}
pWin->regAccum = ++pParse->nMem;
pWin->regResult = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
}
/* If there is no ORDER BY or PARTITION BY clause, and the window
** function accepts zero arguments, and there are no other columns
** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
** that pSublist is still NULL here. Add a constant expression here to
** keep everything legal in this case.
*/
if( pSublist==0 ){
pSublist = sqlite3ExprListAppend(pParse, 0,
sqlite3Expr(db, TK_INTEGER, "0")
);
}
pSub = sqlite3SelectNew(
pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
);
p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( p->pSrc ){
Table *pTab2;
p->pSrc->a[0].pSelect = pSub;
sqlite3SrcListAssignCursors(pParse, p->pSrc);
pSub->selFlags |= SF_Expanded;
pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
if( pTab2==0 ){
rc = SQLITE_NOMEM;
}else{
memcpy(pTab, pTab2, sizeof(Table));
pTab->tabFlags |= TF_Ephemeral;
p->pSrc->a[0].pTab = pTab;
pTab = pTab2;
}
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
}else{
sqlite3SelectDelete(db, pSub);
}
if( db->mallocFailed ) rc = SQLITE_NOMEM;
sqlite3DbFree(db, pTab);
}
return rc;
}
/*
** Unlink the Window object from the Select to which it is attached,
** if it is attached.
*/
void sqlite3WindowUnlinkFromSelect(Window *p){
if( p->ppThis ){
*p->ppThis = p->pNextWin;
if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
p->ppThis = 0;
}
}
/*
** Free the Window object passed as the second argument.
*/
void sqlite3WindowDelete(sqlite3 *db, Window *p){
if( p ){
sqlite3WindowUnlinkFromSelect(p);
sqlite3ExprDelete(db, p->pFilter);
sqlite3ExprListDelete(db, p->pPartition);
sqlite3ExprListDelete(db, p->pOrderBy);
sqlite3ExprDelete(db, p->pEnd);
sqlite3ExprDelete(db, p->pStart);
sqlite3DbFree(db, p->zName);
sqlite3DbFree(db, p->zBase);
sqlite3DbFree(db, p);
}
}
/*
** Free the linked list of Window objects starting at the second argument.
*/
void sqlite3WindowListDelete(sqlite3 *db, Window *p){
while( p ){
Window *pNext = p->pNextWin;
sqlite3WindowDelete(db, p);
p = pNext;
}
}
/*
** The argument expression is an PRECEDING or FOLLOWING offset. The
** value should be a non-negative integer. If the value is not a
** constant, change it to NULL. The fact that it is then a non-negative
** integer will be caught later. But it is important not to leave
** variable values in the expression tree.
*/
static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
if( 0==sqlite3ExprIsConstant(pExpr) ){
if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
sqlite3ExprDelete(pParse->db, pExpr);
pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
}
return pExpr;
}
/*
** Allocate and return a new Window object describing a Window Definition.
*/
Window *sqlite3WindowAlloc(
Parse *pParse, /* Parsing context */
int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
u8 eExclude /* EXCLUDE clause */
){
Window *pWin = 0;
int bImplicitFrame = 0;
/* Parser assures the following: */
assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
|| eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
|| eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
if( eType==0 ){
bImplicitFrame = 1;
eType = TK_RANGE;
}
/* Additionally, the
** starting boundary type may not occur earlier in the following list than
** the ending boundary type:
**
** UNBOUNDED PRECEDING
** <expr> PRECEDING
** CURRENT ROW
** <expr> FOLLOWING
** UNBOUNDED FOLLOWING
**
** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
** frame boundary.
*/
if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
|| (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
){
sqlite3ErrorMsg(pParse, "unsupported frame specification");
goto windowAllocErr;
}
pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
if( pWin==0 ) goto windowAllocErr;
pWin->eFrmType = eType;
pWin->eStart = eStart;
pWin->eEnd = eEnd;
if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
eExclude = TK_NO;
}
pWin->eExclude = eExclude;
pWin->bImplicitFrame = bImplicitFrame;
pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
return pWin;
windowAllocErr:
sqlite3ExprDelete(pParse->db, pEnd);
sqlite3ExprDelete(pParse->db, pStart);
return 0;
}
/*
** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
** equivalent nul-terminated string.
*/
Window *sqlite3WindowAssemble(
Parse *pParse,
Window *pWin,
ExprList *pPartition,
ExprList *pOrderBy,
Token *pBase
){
if( pWin ){
pWin->pPartition = pPartition;
pWin->pOrderBy = pOrderBy;
if( pBase ){
pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
}
}else{
sqlite3ExprListDelete(pParse->db, pPartition);
sqlite3ExprListDelete(pParse->db, pOrderBy);
}
return pWin;
}
/*
** Window *pWin has just been created from a WINDOW clause. Tokne pBase
** is the base window. Earlier windows from the same WINDOW clause are
** stored in the linked list starting at pWin->pNextWin. This function
** either updates *pWin according to the base specification, or else
** leaves an error in pParse.
*/
void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
if( pWin->zBase ){
sqlite3 *db = pParse->db;
Window *pExist = windowFind(pParse, pList, pWin->zBase);
if( pExist ){
const char *zErr = 0;
/* Check for errors */
if( pWin->pPartition ){
zErr = "PARTITION clause";
}else if( pExist->pOrderBy && pWin->pOrderBy ){
zErr = "ORDER BY clause";
}else if( pExist->bImplicitFrame==0 ){
zErr = "frame specification";
}
if( zErr ){
sqlite3ErrorMsg(pParse,
"cannot override %s of window: %s", zErr, pWin->zBase
);
}else{
pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
if( pExist->pOrderBy ){
assert( pWin->pOrderBy==0 );
pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
}
sqlite3DbFree(db, pWin->zBase);
pWin->zBase = 0;
}
}
}
}
/*
** Attach window object pWin to expression p.
*/
void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
if( p ){
assert( p->op==TK_FUNCTION );
assert( pWin );
p->y.pWin = pWin;
ExprSetProperty(p, EP_WinFunc);
pWin->pOwner = p;
if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
sqlite3ErrorMsg(pParse,
"DISTINCT is not supported for window functions"
);
}
}else{
sqlite3WindowDelete(pParse->db, pWin);
}
}
/*
** Possibly link window pWin into the list at pSel->pWin (window functions
** to be processed as part of SELECT statement pSel). The window is linked
** in if either (a) there are no other windows already linked to this
** SELECT, or (b) the windows already linked use a compatible window frame.
*/
void sqlite3WindowLink(Select *pSel, Window *pWin){
if( pSel!=0
&& (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
){
pWin->pNextWin = pSel->pWin;
if( pSel->pWin ){
pSel->pWin->ppThis = &pWin->pNextWin;
}
pSel->pWin = pWin;
pWin->ppThis = &pSel->pWin;
}
}
/*
** Return 0 if the two window objects are identical, or non-zero otherwise.
** Identical window objects can be processed in a single scan.
*/
int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
if( p1->eFrmType!=p2->eFrmType ) return 1;
if( p1->eStart!=p2->eStart ) return 1;
if( p1->eEnd!=p2->eEnd ) return 1;
if( p1->eExclude!=p2->eExclude ) return 1;
if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
if( bFilter ){
if( sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1) ) return 1;
}
return 0;
}
/*
** This is called by code in select.c before it calls sqlite3WhereBegin()
** to begin iterating through the sub-query results. It is used to allocate
** and initialize registers and cursors used by sqlite3WindowCodeStep().
*/
void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
Window *pWin;
Vdbe *v = sqlite3GetVdbe(pParse);
/* Allocate registers to use for PARTITION BY values, if any. Initialize
** said registers to NULL. */
if( pMWin->pPartition ){
int nExpr = pMWin->pPartition->nExpr;
pMWin->regPart = pParse->nMem+1;
pParse->nMem += nExpr;
sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
}
pMWin->regOne = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
if( pMWin->eExclude ){
pMWin->regStartRowid = ++pParse->nMem;
pMWin->regEndRowid = ++pParse->nMem;
pMWin->csrApp = pParse->nTab++;
sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
return;
}
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *p = pWin->pFunc;
if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
/* The inline versions of min() and max() require a single ephemeral
** table and 3 registers. The registers are used as follows:
**
** regApp+0: slot to copy min()/max() argument to for MakeRecord
** regApp+1: integer value used to ensure keys are unique
** regApp+2: output of MakeRecord
*/
ExprList *pList = pWin->pOwner->x.pList;
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
pWin->csrApp = pParse->nTab++;
pWin->regApp = pParse->nMem+1;
pParse->nMem += 3;
if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
assert( pKeyInfo->aSortFlags[0]==0 );
pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
}
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
}
else if( p->zName==nth_valueName || p->zName==first_valueName ){
/* Allocate two registers at pWin->regApp. These will be used to
** store the start and end index of the current frame. */
pWin->regApp = pParse->nMem+1;
pWin->csrApp = pParse->nTab++;
pParse->nMem += 2;
sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
}
else if( p->zName==leadName || p->zName==lagName ){
pWin->csrApp = pParse->nTab++;
sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
}
}
}
#define WINDOW_STARTING_INT 0
#define WINDOW_ENDING_INT 1
#define WINDOW_NTH_VALUE_INT 2
#define WINDOW_STARTING_NUM 3
#define WINDOW_ENDING_NUM 4
/*
** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
** value of the second argument to nth_value() (eCond==2) has just been
** evaluated and the result left in register reg. This function generates VM
** code to check that the value is a non-negative integer and throws an
** exception if it is not.
*/
static void windowCheckValue(Parse *pParse, int reg, int eCond){
static const char *azErr[] = {
"frame starting offset must be a non-negative integer",
"frame ending offset must be a non-negative integer",
"second argument to nth_value must be a positive integer",
"frame starting offset must be a non-negative number",
"frame ending offset must be a non-negative number",
};
static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
Vdbe *v = sqlite3GetVdbe(pParse);
int regZero = sqlite3GetTempReg(pParse);
assert( eCond>=0 && eCond<ArraySize(azErr) );
sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
if( eCond>=WINDOW_STARTING_NUM ){
int regString = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
VdbeCoverage(v);
assert( eCond==3 || eCond==4 );
VdbeCoverageIf(v, eCond==3);
VdbeCoverageIf(v, eCond==4);
}else{
sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
VdbeCoverage(v);
assert( eCond==0 || eCond==1 || eCond==2 );
VdbeCoverageIf(v, eCond==0);
VdbeCoverageIf(v, eCond==1);
VdbeCoverageIf(v, eCond==2);
}
sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
VdbeCoverageNeverNullIf(v, eCond==2);
VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
sqlite3MayAbort(pParse);
sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
sqlite3ReleaseTempReg(pParse, regZero);
}
/*
** Return the number of arguments passed to the window-function associated
** with the object passed as the only argument to this function.
*/
static int windowArgCount(Window *pWin){
ExprList *pList = pWin->pOwner->x.pList;
return (pList ? pList->nExpr : 0);
}
typedef struct WindowCodeArg WindowCodeArg;
typedef struct WindowCsrAndReg WindowCsrAndReg;
/*
** See comments above struct WindowCodeArg.
*/
struct WindowCsrAndReg {
int csr; /* Cursor number */
int reg; /* First in array of peer values */
};
/*
** A single instance of this structure is allocated on the stack by
** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
** routines. This is to reduce the number of arguments required by each
** helper function.
**
** regArg:
** Each window function requires an accumulator register (just as an
** ordinary aggregate function does). This variable is set to the first
** in an array of accumulator registers - one for each window function
** in the WindowCodeArg.pMWin list.
**
** eDelete:
** The window functions implementation sometimes caches the input rows
** that it processes in a temporary table. If it is not zero, this
** variable indicates when rows may be removed from the temp table (in
** order to reduce memory requirements - it would always be safe just
** to leave them there). Possible values for eDelete are:
**
** WINDOW_RETURN_ROW:
** An input row can be discarded after it is returned to the caller.
**
** WINDOW_AGGINVERSE:
** An input row can be discarded after the window functions xInverse()
** callbacks have been invoked in it.
**
** WINDOW_AGGSTEP:
** An input row can be discarded after the window functions xStep()
** callbacks have been invoked in it.
**
** start,current,end
** Consider a window-frame similar to the following:
**
** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
**
** The windows functions implmentation caches the input rows in a temp
** table, sorted by "a, b" (it actually populates the cache lazily, and
** aggressively removes rows once they are no longer required, but that's
** a mere detail). It keeps three cursors open on the temp table. One
** (current) that points to the next row to return to the query engine
** once its window function values have been calculated. Another (end)
** points to the next row to call the xStep() method of each window function
** on (so that it is 2 groups ahead of current). And a third (start) that
** points to the next row to call the xInverse() method of each window
** function on.
**
** Each cursor (start, current and end) consists of a VDBE cursor
** (WindowCsrAndReg.csr) and an array of registers (starting at
** WindowCodeArg.reg) that always contains a copy of the peer values
** read from the corresponding cursor.
**
** Depending on the window-frame in question, all three cursors may not
** be required. In this case both WindowCodeArg.csr and reg are set to
** 0.
*/
struct WindowCodeArg {
Parse *pParse; /* Parse context */
Window *pMWin; /* First in list of functions being processed */
Vdbe *pVdbe; /* VDBE object */
int addrGosub; /* OP_Gosub to this address to return one row */
int regGosub; /* Register used with OP_Gosub(addrGosub) */
int regArg; /* First in array of accumulator registers */
int eDelete; /* See above */
WindowCsrAndReg start;
WindowCsrAndReg current;
WindowCsrAndReg end;
};
/*
** Generate VM code to read the window frames peer values from cursor csr into
** an array of registers starting at reg.
*/
static void windowReadPeerValues(
WindowCodeArg *p,
int csr,
int reg
){
Window *pMWin = p->pMWin;
ExprList *pOrderBy = pMWin->pOrderBy;
if( pOrderBy ){
Vdbe *v = sqlite3GetVdbe(p->pParse);
ExprList *pPart = pMWin->pPartition;
int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
int i;
for(i=0; i<pOrderBy->nExpr; i++){
sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
}
}
}
/*
** Generate VM code to invoke either xStep() (if bInverse is 0) or
** xInverse (if bInverse is non-zero) for each window function in the
** linked list starting at pMWin. Or, for built-in window functions
** that do not use the standard function API, generate the required
** inline VM code.
**
** If argument csr is greater than or equal to 0, then argument reg is
** the first register in an array of registers guaranteed to be large
** enough to hold the array of arguments for each function. In this case
** the arguments are extracted from the current row of csr into the
** array of registers before invoking OP_AggStep or OP_AggInverse
**
** Or, if csr is less than zero, then the array of registers at reg is
** already populated with all columns from the current row of the sub-query.
**
** If argument regPartSize is non-zero, then it is a register containing the
** number of rows in the current partition.
*/
static void windowAggStep(
WindowCodeArg *p,
Window *pMWin, /* Linked list of window functions */
int csr, /* Read arguments from this cursor */
int bInverse, /* True to invoke xInverse instead of xStep */
int reg /* Array of registers */
){
Parse *pParse = p->pParse;
Vdbe *v = sqlite3GetVdbe(pParse);
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
int regArg;
int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
int i;
assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
/* All OVER clauses in the same window function aggregate step must
** be the same. */
assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)==0 );
for(i=0; i<nArg; i++){
if( i!=1 || pFunc->zName!=nth_valueName ){
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
}else{
sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
}
}
regArg = reg;
if( pMWin->regStartRowid==0
&& (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
&& (pWin->eStart!=TK_UNBOUNDED)
){
int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
VdbeCoverage(v);
if( bInverse==0 ){
sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
}else{
sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
VdbeCoverageNeverTaken(v);
sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
}
sqlite3VdbeJumpHere(v, addrIsNull);
}else if( pWin->regApp ){
assert( pFunc->zName==nth_valueName
|| pFunc->zName==first_valueName
);
assert( bInverse==0 || bInverse==1 );
sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
}else if( pFunc->xSFunc!=noopStepFunc ){
int addrIf = 0;
if( pWin->pFilter ){
int regTmp;
assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
regTmp = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, regTmp);
}
if( pWin->bExprArgs ){
int iStart = sqlite3VdbeCurrentAddr(v);
VdbeOp *pOp, *pEnd;
nArg = pWin->pOwner->x.pList->nExpr;
regArg = sqlite3GetTempRange(pParse, nArg);
sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
pEnd = sqlite3VdbeGetOp(v, -1);
for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
pOp->p1 = csr;
}
}
}
if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
CollSeq *pColl;
assert( nArg>0 );
pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
}
sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
bInverse, regArg, pWin->regAccum);
sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
sqlite3VdbeChangeP5(v, (u8)nArg);
if( pWin->bExprArgs ){
sqlite3ReleaseTempRange(pParse, regArg, nArg);
}
if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
}
}
}
/*
** Values that may be passed as the second argument to windowCodeOp().
*/
#define WINDOW_RETURN_ROW 1
#define WINDOW_AGGINVERSE 2
#define WINDOW_AGGSTEP 3
/*
** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
** (bFin==1) for each window function in the linked list starting at
** pMWin. Or, for built-in window-functions that do not use the standard
** API, generate the equivalent VM code.
*/
static void windowAggFinal(WindowCodeArg *p, int bFin){
Parse *pParse = p->pParse;
Window *pMWin = p->pMWin;
Vdbe *v = sqlite3GetVdbe(pParse);
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
if( pMWin->regStartRowid==0
&& (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
&& (pWin->eStart!=TK_UNBOUNDED)
){
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
}else if( pWin->regApp ){
assert( pMWin->regStartRowid==0 );
}else{
int nArg = windowArgCount(pWin);
if( bFin ){
sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
}else{
sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
}
}
}
}
/*
** Generate code to calculate the current values of all window functions in the
** p->pMWin list by doing a full scan of the current window frame. Store the
** results in the Window.regResult registers, ready to return the upper
** layer.
*/
static void windowFullScan(WindowCodeArg *p){
Window *pWin;
Parse *pParse = p->pParse;
Window *pMWin = p->pMWin;
Vdbe *v = p->pVdbe;
int regCRowid = 0; /* Current rowid value */
int regCPeer = 0; /* Current peer values */
int regRowid = 0; /* AggStep rowid value */
int regPeer = 0; /* AggStep peer values */
int nPeer;
int lblNext;
int lblBrk;
int addrNext;
int csr;
VdbeModuleComment((v, "windowFullScan begin"));
assert( pMWin!=0 );
csr = pMWin->csrApp;
nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
lblNext = sqlite3VdbeMakeLabel(pParse);
lblBrk = sqlite3VdbeMakeLabel(pParse);
regCRowid = sqlite3GetTempReg(pParse);
regRowid = sqlite3GetTempReg(pParse);
if( nPeer ){
regCPeer = sqlite3GetTempRange(pParse, nPeer);
regPeer = sqlite3GetTempRange(pParse, nPeer);
}
sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
}
sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
VdbeCoverage(v);
addrNext = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
VdbeCoverageNeverNull(v);
if( pMWin->eExclude==TK_CURRENT ){
sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
VdbeCoverageNeverNull(v);
}else if( pMWin->eExclude!=TK_NO ){
int addr;
int addrEq = 0;
KeyInfo *pKeyInfo = 0;
if( pMWin->pOrderBy ){
pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
}
if( pMWin->eExclude==TK_TIES ){
addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
VdbeCoverageNeverNull(v);
}
if( pKeyInfo ){
windowReadPeerValues(p, csr, regPeer);
sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
addr = sqlite3VdbeCurrentAddr(v)+1;
sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
VdbeCoverageEqNe(v);
}else{
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
}
if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
}
windowAggStep(p, pMWin, csr, 0, p->regArg);
sqlite3VdbeResolveLabel(v, lblNext);
sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addrNext-1);
sqlite3VdbeJumpHere(v, addrNext+1);
sqlite3ReleaseTempReg(pParse, regRowid);
sqlite3ReleaseTempReg(pParse, regCRowid);
if( nPeer ){
sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
}
windowAggFinal(p, 1);
VdbeModuleComment((v, "windowFullScan end"));
}
/*
** Invoke the sub-routine at regGosub (generated by code in select.c) to
** return the current row of Window.iEphCsr. If all window functions are
** aggregate window functions that use the standard API, a single
** OP_Gosub instruction is all that this routine generates. Extra VM code
** for per-row processing is only generated for the following built-in window
** functions:
**
** nth_value()
** first_value()
** lag()
** lead()
*/
static void windowReturnOneRow(WindowCodeArg *p){
Window *pMWin = p->pMWin;
Vdbe *v = p->pVdbe;
if( pMWin->regStartRowid ){
windowFullScan(p);
}else{
Parse *pParse = p->pParse;
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
if( pFunc->zName==nth_valueName
|| pFunc->zName==first_valueName
){
int csr = pWin->csrApp;
int lbl = sqlite3VdbeMakeLabel(pParse);
int tmpReg = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
if( pFunc->zName==nth_valueName ){
sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
windowCheckValue(pParse, tmpReg, 2);
}else{
sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
}
sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
VdbeCoverageNeverNull(v);
sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
VdbeCoverageNeverTaken(v);
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
sqlite3VdbeResolveLabel(v, lbl);
sqlite3ReleaseTempReg(pParse, tmpReg);
}
else if( pFunc->zName==leadName || pFunc->zName==lagName ){
int nArg = pWin->pOwner->x.pList->nExpr;
int csr = pWin->csrApp;
int lbl = sqlite3VdbeMakeLabel(pParse);
int tmpReg = sqlite3GetTempReg(pParse);
int iEph = pMWin->iEphCsr;
if( nArg<3 ){
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
}else{
sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
}
sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
if( nArg<2 ){
int val = (pFunc->zName==leadName ? 1 : -1);
sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
}else{
int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
int tmpReg2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
sqlite3ReleaseTempReg(pParse, tmpReg2);
}
sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
sqlite3VdbeResolveLabel(v, lbl);
sqlite3ReleaseTempReg(pParse, tmpReg);
}
}
}
sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
}
/*
** Generate code to set the accumulator register for each window function
** in the linked list passed as the second argument to NULL. And perform
** any equivalent initialization required by any built-in window functions
** in the list.
*/
static int windowInitAccum(Parse *pParse, Window *pMWin){
Vdbe *v = sqlite3GetVdbe(pParse);
int regArg;
int nArg = 0;
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
nArg = MAX(nArg, windowArgCount(pWin));
if( pMWin->regStartRowid==0 ){
if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
}
if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
assert( pWin->eStart!=TK_UNBOUNDED );
sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
}
}
}
regArg = pParse->nMem+1;
pParse->nMem += nArg;
return regArg;
}
/*
** Return true if the current frame should be cached in the ephemeral table,
** even if there are no xInverse() calls required.
*/
static int windowCacheFrame(Window *pMWin){
Window *pWin;
if( pMWin->regStartRowid ) return 1;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
if( (pFunc->zName==nth_valueName)
|| (pFunc->zName==first_valueName)
|| (pFunc->zName==leadName)
|| (pFunc->zName==lagName)
){
return 1;
}
}
return 0;
}
/*
** regOld and regNew are each the first register in an array of size
** pOrderBy->nExpr. This function generates code to compare the two
** arrays of registers using the collation sequences and other comparison
** parameters specified by pOrderBy.
**
** If the two arrays are not equal, the contents of regNew is copied to
** regOld and control falls through. Otherwise, if the contents of the arrays
** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
*/
static void windowIfNewPeer(
Parse *pParse,
ExprList *pOrderBy,
int regNew, /* First in array of new values */
int regOld, /* First in array of old values */
int addr /* Jump here */
){
Vdbe *v = sqlite3GetVdbe(pParse);
if( pOrderBy ){
int nVal = pOrderBy->nExpr;
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump,
sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
);
VdbeCoverageEqNe(v);
sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
}else{
sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
}
}
/*
** This function is called as part of generating VM programs for RANGE
** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
** code equivalent to:
**
** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
**
** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
**
** If the sort-order for the ORDER BY term in the window is DESC, then the
** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
** is OP_Ge, the generated code is equivalent to:
**
** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
**
** A special type of arithmetic is used such that if csr1.peerVal is not
** a numeric type (real or integer), then the result of the addition addition
** or subtraction is a a copy of csr1.peerVal.
*/
static void windowCodeRangeTest(
WindowCodeArg *p,
int op, /* OP_Ge, OP_Gt, or OP_Le */
int csr1, /* Cursor number for cursor 1 */
int regVal, /* Register containing non-negative number */
int csr2, /* Cursor number for cursor 2 */
int lbl /* Jump destination if condition is true */
){
Parse *pParse = p->pParse;
Vdbe *v = sqlite3GetVdbe(pParse);
ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
int regString = ++pParse->nMem; /* Reg. for constant value '' */
int arith = OP_Add; /* OP_Add or OP_Subtract */
int addrGe; /* Jump destination */
assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
assert( pOrderBy && pOrderBy->nExpr==1 );
if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
switch( op ){
case OP_Ge: op = OP_Le; break;
case OP_Gt: op = OP_Lt; break;
default: assert( op==OP_Le ); op = OP_Ge; break;
}
arith = OP_Subtract;
}
/* Read the peer-value from each cursor into a register */
windowReadPeerValues(p, csr1, reg1);
windowReadPeerValues(p, csr2, reg2);
VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
reg1, (arith==OP_Add ? "+" : "-"), regVal,
((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
));
/* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
** This block adds (or subtracts for DESC) the numeric value in regVal
** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
** then leave reg1 as it is. In pseudo-code, this is implemented as:
**
** if( reg1>='' ) goto addrGe;
** reg1 = reg1 +/- regVal
** addrGe:
**
** Since all strings and blobs are greater-than-or-equal-to an empty string,
** the add/subtract is skipped for these, as required. If reg1 is a NULL,
** then the arithmetic is performed, but since adding or subtracting from
** NULL is always NULL anyway, this case is handled as required too. */
sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
sqlite3VdbeJumpHere(v, addrGe);
/* If the BIGNULL flag is set for the ORDER BY, then it is required to
** consider NULL values to be larger than all other values, instead of
** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
** (and adding that capability causes a performance regression), so
** instead if the BIGNULL flag is set then cases where either reg1 or
** reg2 are NULL are handled separately in the following block. The code
** generated is equivalent to:
**
** if( reg1 IS NULL ){
** if( op==OP_Ge ) goto lbl;
** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
** if( op==OP_Le && reg2 IS NULL ) goto lbl;
** }else if( reg2 IS NULL ){
** if( op==OP_Le ) goto lbl;
** }
**
** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
** not taken, control jumps over the comparison operator coded below this
** block. */
if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
/* This block runs if reg1 contains a NULL. */
int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
switch( op ){
case OP_Ge:
sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
break;
case OP_Gt:
sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
VdbeCoverage(v);
break;
case OP_Le:
sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
VdbeCoverage(v);
break;
default: assert( op==OP_Lt ); /* no-op */ break;
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
/* This block runs if reg1 is not NULL, but reg2 is. */
sqlite3VdbeJumpHere(v, addr);
sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
if( op==OP_Gt || op==OP_Ge ){
sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
}
}
/* Compare registers reg2 and reg1, taking the jump if required. Note that
** control skips over this test if the BIGNULL flag is set and either
** reg1 or reg2 contain a NULL value. */
sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
sqlite3ReleaseTempReg(pParse, reg1);
sqlite3ReleaseTempReg(pParse, reg2);
VdbeModuleComment((v, "CodeRangeTest: end"));
}
/*
** Helper function for sqlite3WindowCodeStep(). Each call to this function
** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
** operation. Refer to the header comment for sqlite3WindowCodeStep() for
** details.
*/
static int windowCodeOp(
WindowCodeArg *p, /* Context object */
int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
int regCountdown, /* Register for OP_IfPos countdown */
int jumpOnEof /* Jump here if stepped cursor reaches EOF */
){
int csr, reg;
Parse *pParse = p->pParse;
Window *pMWin = p->pMWin;
int ret = 0;
Vdbe *v = p->pVdbe;
int addrContinue = 0;
int bPeer = (pMWin->eFrmType!=TK_ROWS);
int lblDone = sqlite3VdbeMakeLabel(pParse);
int addrNextRange = 0;
/* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
** starts with UNBOUNDED PRECEDING. */
if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
assert( regCountdown==0 && jumpOnEof==0 );
return 0;
}
if( regCountdown>0 ){
if( pMWin->eFrmType==TK_RANGE ){
addrNextRange = sqlite3VdbeCurrentAddr(v);
assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
if( op==WINDOW_AGGINVERSE ){
if( pMWin->eStart==TK_FOLLOWING ){
windowCodeRangeTest(
p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
);
}else{
windowCodeRangeTest(
p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
);
}
}else{
windowCodeRangeTest(
p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
);
}
}else{
sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
VdbeCoverage(v);
}
}
if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
windowAggFinal(p, 0);
}
addrContinue = sqlite3VdbeCurrentAddr(v);
/* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
** start cursor does not advance past the end cursor within the
** temporary table. It otherwise might, if (a>b). */
if( pMWin->eStart==pMWin->eEnd && regCountdown
&& pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
){
int regRowid1 = sqlite3GetTempReg(pParse);
int regRowid2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, regRowid1);
sqlite3ReleaseTempReg(pParse, regRowid2);
assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
}
switch( op ){
case WINDOW_RETURN_ROW:
csr = p->current.csr;
reg = p->current.reg;
windowReturnOneRow(p);
break;
case WINDOW_AGGINVERSE:
csr = p->start.csr;
reg = p->start.reg;
if( pMWin->regStartRowid ){
assert( pMWin->regEndRowid );
sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
}else{
windowAggStep(p, pMWin, csr, 1, p->regArg);
}
break;
default:
assert( op==WINDOW_AGGSTEP );
csr = p->end.csr;
reg = p->end.reg;
if( pMWin->regStartRowid ){
assert( pMWin->regEndRowid );
sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
}else{
windowAggStep(p, pMWin, csr, 0, p->regArg);
}
break;
}
if( op==p->eDelete ){
sqlite3VdbeAddOp1(v, OP_Delete, csr);
sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
}
if( jumpOnEof ){
sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
VdbeCoverage(v);
ret = sqlite3VdbeAddOp0(v, OP_Goto);
}else{
sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
VdbeCoverage(v);
if( bPeer ){
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
}
}
if( bPeer ){
int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
windowReadPeerValues(p, csr, regTmp);
windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
sqlite3ReleaseTempRange(pParse, regTmp, nReg);
}
if( addrNextRange ){
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
}
sqlite3VdbeResolveLabel(v, lblDone);
return ret;
}
/*
** Allocate and return a duplicate of the Window object indicated by the
** third argument. Set the Window.pOwner field of the new object to
** pOwner.
*/
Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
Window *pNew = 0;
if( ALWAYS(p) ){
pNew = sqlite3DbMallocZero(db, sizeof(Window));
if( pNew ){
pNew->zName = sqlite3DbStrDup(db, p->zName);
pNew->zBase = sqlite3DbStrDup(db, p->zBase);
pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
pNew->pFunc = p->pFunc;
pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
pNew->eFrmType = p->eFrmType;
pNew->eEnd = p->eEnd;
pNew->eStart = p->eStart;
pNew->eExclude = p->eExclude;
pNew->regResult = p->regResult;
pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
pNew->pOwner = pOwner;
pNew->bImplicitFrame = p->bImplicitFrame;
}
}
return pNew;
}
/*
** Return a copy of the linked list of Window objects passed as the
** second argument.
*/
Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
Window *pWin;
Window *pRet = 0;
Window **pp = &pRet;
for(pWin=p; pWin; pWin=pWin->pNextWin){
*pp = sqlite3WindowDup(db, 0, pWin);
if( *pp==0 ) break;
pp = &((*pp)->pNextWin);
}
return pRet;
}
/*
** Return true if it can be determined at compile time that expression
** pExpr evaluates to a value that, when cast to an integer, is greater
** than zero. False otherwise.
**
** If an OOM error occurs, this function sets the Parse.db.mallocFailed
** flag and returns zero.
*/
static int windowExprGtZero(Parse *pParse, Expr *pExpr){
int ret = 0;
sqlite3 *db = pParse->db;
sqlite3_value *pVal = 0;
sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
if( pVal && sqlite3_value_int(pVal)>0 ){
ret = 1;
}
sqlite3ValueFree(pVal);
return ret;
}
/*
** sqlite3WhereBegin() has already been called for the SELECT statement
** passed as the second argument when this function is invoked. It generates
** code to populate the Window.regResult register for each window function
** and invoke the sub-routine at instruction addrGosub once for each row.
** sqlite3WhereEnd() is always called before returning.
**
** This function handles several different types of window frames, which
** require slightly different processing. The following pseudo code is
** used to implement window frames of the form:
**
** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
**
** Other window frame types use variants of the following:
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
**
** if( first row of partition ){
** // Rewind three cursors, all open on the eph table.
** Rewind(csrEnd);
** Rewind(csrStart);
** Rewind(csrCurrent);
**
** regEnd = <expr2> // FOLLOWING expression
** regStart = <expr1> // PRECEDING expression
** }else{
** // First time this branch is taken, the eph table contains two
** // rows. The first row in the partition, which all three cursors
** // currently point to, and the following row.
** AGGSTEP
** if( (regEnd--)<=0 ){
** RETURN_ROW
** if( (regStart--)<=0 ){
** AGGINVERSE
** }
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** RETURN ROW
** if( csrCurrent is EOF ) break;
** if( (regStart--)<=0 ){
** AggInverse(csrStart)
** Next(csrStart)
** }
** }
**
** The pseudo-code above uses the following shorthand:
**
** AGGSTEP: invoke the aggregate xStep() function for each window function
** with arguments read from the current row of cursor csrEnd, then
** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
**
** RETURN_ROW: return a row to the caller based on the contents of the
** current row of csrCurrent and the current state of all
** aggregates. Then step cursor csrCurrent forward one row.
**
** AGGINVERSE: invoke the aggregate xInverse() function for each window
** functions with arguments read from the current row of cursor
** csrStart. Then step csrStart forward one row.
**
** There are two other ROWS window frames that are handled significantly
** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
** cases because they change the order in which the three cursors (csrStart,
** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
** three.
**
** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** if( (regEnd--)<=0 ){
** AGGSTEP
** }
** RETURN_ROW
** if( (regStart--)<=0 ){
** AGGINVERSE
** }
** }
** }
** flush:
** if( (regEnd--)<=0 ){
** AGGSTEP
** }
** RETURN_ROW
**
**
** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = regEnd - <expr1>
** }else{
** AGGSTEP
** if( (regEnd--)<=0 ){
** RETURN_ROW
** }
** if( (regStart--)<=0 ){
** AGGINVERSE
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** if( (regEnd--)<=0 ){
** RETURN_ROW
** if( eof ) break;
** }
** if( (regStart--)<=0 ){
** AGGINVERSE
** if( eof ) break
** }
** }
** while( !eof csrCurrent ){
** RETURN_ROW
** }
**
** For the most part, the patterns above are adapted to support UNBOUNDED by
** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
** This is optimized of course - branches that will never be taken and
** conditions that are always true are omitted from the VM code. The only
** exceptional case is:
**
** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regStart = <expr1>
** }else{
** AGGSTEP
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** if( (regStart--)<=0 ){
** AGGINVERSE
** if( eof ) break
** }
** RETURN_ROW
** }
** while( !eof csrCurrent ){
** RETURN_ROW
** }
**
** Also requiring special handling are the cases:
**
** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
**
** when (expr1 < expr2). This is detected at runtime, not by this function.
** To handle this case, the pseudo-code programs depicted above are modified
** slightly to be:
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** if( regEnd < regStart ){
** RETURN_ROW
** delete eph table contents
** continue
** }
** ...
**
** The new "continue" statement in the above jumps to the next iteration
** of the outer loop - the one started by sqlite3WhereBegin().
**
** The various GROUPS cases are implemented using the same patterns as
** ROWS. The VM code is modified slightly so that:
**
** 1. The else branch in the main loop is only taken if the row just
** added to the ephemeral table is the start of a new group. In
** other words, it becomes:
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else if( new group ){
** ...
** }
** }
**
** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
** AGGINVERSE step processes the current row of the relevant cursor and
** all subsequent rows belonging to the same group.
**
** RANGE window frames are a little different again. As for GROUPS, the
** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
** deal in groups instead of rows. As for ROWS and GROUPS, there are three
** basic cases:
**
** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** AGGSTEP
** while( (csrCurrent.key + regEnd) < csrEnd.key ){
** RETURN_ROW
** while( csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** RETURN ROW
** if( csrCurrent is EOF ) break;
** while( csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** }
** }
**
** In the above notation, "csr.key" means the current value of the ORDER BY
** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
** or <expr PRECEDING) read from cursor csr.
**
** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
** AGGSTEP
** }
** while( (csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** RETURN_ROW
** }
** }
** flush:
** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
** AGGSTEP
** }
** while( (csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** RETURN_ROW
**
** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** AGGSTEP
** while( (csrCurrent.key + regEnd) < csrEnd.key ){
** while( (csrCurrent.key + regStart) > csrStart.key ){
** AGGINVERSE
** }
** RETURN_ROW
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** while( (csrCurrent.key + regStart) > csrStart.key ){
** AGGINVERSE
** if( eof ) break "while( 1 )" loop.
** }
** RETURN_ROW
** }
** while( !eof csrCurrent ){
** RETURN_ROW
** }
**
** The text above leaves out many details. Refer to the code and comments
** below for a more complete picture.
*/
void sqlite3WindowCodeStep(
Parse *pParse, /* Parse context */
Select *p, /* Rewritten SELECT statement */
WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
int regGosub, /* Register for OP_Gosub */
int addrGosub /* OP_Gosub here to return each row */
){
Window *pMWin = p->pWin;
ExprList *pOrderBy = pMWin->pOrderBy;
Vdbe *v = sqlite3GetVdbe(pParse);
int csrWrite; /* Cursor used to write to eph. table */
int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
int iInput; /* To iterate through sub cols */
int addrNe; /* Address of OP_Ne */
int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
int addrInteger = 0; /* Address of OP_Integer */
int addrEmpty; /* Address of OP_Rewind in flush: */
int regNew; /* Array of registers holding new input row */
int regRecord; /* regNew array in record form */
int regRowid; /* Rowid for regRecord in eph table */
int regNewPeer = 0; /* Peer values for new row (part of regNew) */
int regPeer = 0; /* Peer values for current row */
int regFlushPart = 0; /* Register for "Gosub flush_partition" */
WindowCodeArg s; /* Context object for sub-routines */
int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
int regStart = 0; /* Value of <expr> PRECEDING */
int regEnd = 0; /* Value of <expr> FOLLOWING */
assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
|| pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
);
assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
|| pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
);
assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
|| pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
|| pMWin->eExclude==TK_NO
);
lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
/* Fill in the context object */
memset(&s, 0, sizeof(WindowCodeArg));
s.pParse = pParse;
s.pMWin = pMWin;
s.pVdbe = v;
s.regGosub = regGosub;
s.addrGosub = addrGosub;
s.current.csr = pMWin->iEphCsr;
csrWrite = s.current.csr+1;
s.start.csr = s.current.csr+2;
s.end.csr = s.current.csr+3;
/* Figure out when rows may be deleted from the ephemeral table. There
** are four options - they may never be deleted (eDelete==0), they may
** be deleted as soon as they are no longer part of the window frame
** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
** has been returned to the caller (WINDOW_RETURN_ROW), or they may
** be deleted after they enter the frame (WINDOW_AGGSTEP). */
switch( pMWin->eStart ){
case TK_FOLLOWING:
if( pMWin->eFrmType!=TK_RANGE
&& windowExprGtZero(pParse, pMWin->pStart)
){
s.eDelete = WINDOW_RETURN_ROW;
}
break;
case TK_UNBOUNDED:
if( windowCacheFrame(pMWin)==0 ){
if( pMWin->eEnd==TK_PRECEDING ){
if( pMWin->eFrmType!=TK_RANGE
&& windowExprGtZero(pParse, pMWin->pEnd)
){
s.eDelete = WINDOW_AGGSTEP;
}
}else{
s.eDelete = WINDOW_RETURN_ROW;
}
}
break;
default:
s.eDelete = WINDOW_AGGINVERSE;
break;
}
/* Allocate registers for the array of values from the sub-query, the
** samve values in record form, and the rowid used to insert said record
** into the ephemeral table. */
regNew = pParse->nMem+1;
pParse->nMem += nInput;
regRecord = ++pParse->nMem;
regRowid = ++pParse->nMem;
/* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
** clause, allocate registers to store the results of evaluating each
** <expr>. */
if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
regStart = ++pParse->nMem;
}
if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
regEnd = ++pParse->nMem;
}
/* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
** registers to store copies of the ORDER BY expressions (peer values)
** for the main loop, and for each cursor (start, current and end). */
if( pMWin->eFrmType!=TK_ROWS ){
int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
regNewPeer = regNew + pMWin->nBufferCol;
if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
regPeer = pParse->nMem+1; pParse->nMem += nPeer;
s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
}
/* Load the column values for the row returned by the sub-select
** into an array of registers starting at regNew. Assemble them into
** a record in register regRecord. */
for(iInput=0; iInput<nInput; iInput++){
sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
/* An input row has just been read into an array of registers starting
** at regNew. If the window has a PARTITION clause, this block generates
** VM code to check if the input row is the start of a new partition.
** If so, it does an OP_Gosub to an address to be filled in later. The
** address of the OP_Gosub is stored in local variable addrGosubFlush. */
if( pMWin->pPartition ){
int addr;
ExprList *pPart = pMWin->pPartition;
int nPart = pPart->nExpr;
int regNewPart = regNew + pMWin->nBufferCol;
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
regFlushPart = ++pParse->nMem;
addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
VdbeCoverageEqNe(v);
addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
VdbeComment((v, "call flush_partition"));
sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
}
/* Insert the new row into the ephemeral table */
sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
VdbeCoverageNeverNull(v);
/* This block is run for the first row of each partition */
s.regArg = windowInitAccum(pParse, pMWin);
if( regStart ){
sqlite3ExprCode(pParse, pMWin->pStart, regStart);
windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
}
if( regEnd ){
sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
}
if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
windowAggFinal(&s, 0);
sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
VdbeCoverageNeverTaken(v);
windowReturnOneRow(&s);
sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
sqlite3VdbeJumpHere(v, addrGe);
}
if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
assert( pMWin->eEnd==TK_FOLLOWING );
sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
}
if( pMWin->eStart!=TK_UNBOUNDED ){
sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
VdbeCoverageNeverTaken(v);
}
sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
VdbeCoverageNeverTaken(v);
sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
VdbeCoverageNeverTaken(v);
if( regPeer && pOrderBy ){
sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
sqlite3VdbeJumpHere(v, addrNe);
/* Beginning of the block executed for the second and subsequent rows. */
if( regPeer ){
windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
}
if( pMWin->eStart==TK_FOLLOWING ){
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
if( pMWin->eEnd!=TK_UNBOUNDED ){
if( pMWin->eFrmType==TK_RANGE ){
int lbl = sqlite3VdbeMakeLabel(pParse);
int addrNext = sqlite3VdbeCurrentAddr(v);
windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
sqlite3VdbeResolveLabel(v, lbl);
}else{
windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
}
}
}else
if( pMWin->eEnd==TK_PRECEDING ){
int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
}else{
int addr = 0;
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
if( pMWin->eEnd!=TK_UNBOUNDED ){
if( pMWin->eFrmType==TK_RANGE ){
int lbl = 0;
addr = sqlite3VdbeCurrentAddr(v);
if( regEnd ){
lbl = sqlite3VdbeMakeLabel(pParse);
windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
}
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
if( regEnd ){
sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
sqlite3VdbeResolveLabel(v, lbl);
}
}else{
if( regEnd ){
addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
VdbeCoverage(v);
}
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
if( regEnd ) sqlite3VdbeJumpHere(v, addr);
}
}
}
/* End of the main input loop */
sqlite3VdbeResolveLabel(v, lblWhereEnd);
sqlite3WhereEnd(pWInfo);
/* Fall through */
if( pMWin->pPartition ){
addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
sqlite3VdbeJumpHere(v, addrGosubFlush);
}
addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
VdbeCoverage(v);
if( pMWin->eEnd==TK_PRECEDING ){
int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
}else if( pMWin->eStart==TK_FOLLOWING ){
int addrStart;
int addrBreak1;
int addrBreak2;
int addrBreak3;
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
if( pMWin->eFrmType==TK_RANGE ){
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
}else
if( pMWin->eEnd==TK_UNBOUNDED ){
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
}else{
assert( pMWin->eEnd==TK_FOLLOWING );
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
sqlite3VdbeJumpHere(v, addrBreak2);
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
sqlite3VdbeJumpHere(v, addrBreak1);
sqlite3VdbeJumpHere(v, addrBreak3);
}else{
int addrBreak;
int addrStart;
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
sqlite3VdbeJumpHere(v, addrBreak);
}
sqlite3VdbeJumpHere(v, addrEmpty);
sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
if( pMWin->pPartition ){
if( pMWin->regStartRowid ){
sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
}
sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
}
}
#endif /* SQLITE_OMIT_WINDOWFUNC */
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_1325_4 |
crossvul-cpp_data_good_1325_2 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
*/
#include "sqliteInt.h"
/* Forward declarations */
static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
/*
** Return the affinity character for a single column of a table.
*/
char sqlite3TableColumnAffinity(Table *pTab, int iCol){
assert( iCol<pTab->nCol );
return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
}
/*
** Return the 'affinity' of the expression pExpr if any.
**
** If pExpr is a column, a reference to a column via an 'AS' alias,
** or a sub-select with a column as the return value, then the
** affinity of that column is returned. Otherwise, 0x00 is returned,
** indicating no affinity for the expression.
**
** i.e. the WHERE clause expressions in the following statements all
** have an affinity:
**
** CREATE TABLE t1(a);
** SELECT * FROM t1 WHERE a;
** SELECT a AS b FROM t1 WHERE b;
** SELECT * FROM t1 WHERE (select a from t1);
*/
char sqlite3ExprAffinity(Expr *pExpr){
int op;
while( ExprHasProperty(pExpr, EP_Skip) ){
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
assert( pExpr!=0 );
}
op = pExpr->op;
if( op==TK_SELECT ){
assert( pExpr->flags&EP_xIsSelect );
return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
}
if( op==TK_REGISTER ) op = pExpr->op2;
#ifndef SQLITE_OMIT_CAST
if( op==TK_CAST ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
return sqlite3AffinityType(pExpr->u.zToken, 0);
}
#endif
if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
}
if( op==TK_SELECT_COLUMN ){
assert( pExpr->pLeft->flags&EP_xIsSelect );
return sqlite3ExprAffinity(
pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
);
}
if( op==TK_VECTOR ){
return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
}
return pExpr->affExpr;
}
/*
** Set the collating sequence for expression pExpr to be the collating
** sequence named by pToken. Return a pointer to a new Expr node that
** implements the COLLATE operator.
**
** If a memory allocation error occurs, that fact is recorded in pParse->db
** and the pExpr parameter is returned unchanged.
*/
Expr *sqlite3ExprAddCollateToken(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* Add the "COLLATE" clause to this expression */
const Token *pCollName, /* Name of collating sequence */
int dequote /* True to dequote pCollName */
){
if( pCollName->n>0 ){
Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
if( pNew ){
pNew->pLeft = pExpr;
pNew->flags |= EP_Collate|EP_Skip;
pExpr = pNew;
}
}
return pExpr;
}
Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
Token s;
assert( zC!=0 );
sqlite3TokenInit(&s, (char*)zC);
return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
}
/*
** Skip over any TK_COLLATE operators.
*/
Expr *sqlite3ExprSkipCollate(Expr *pExpr){
while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
}
return pExpr;
}
/*
** Skip over any TK_COLLATE operators and/or any unlikely()
** or likelihood() or likely() functions at the root of an
** expression.
*/
Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
if( ExprHasProperty(pExpr, EP_Unlikely) ){
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
assert( pExpr->x.pList->nExpr>0 );
assert( pExpr->op==TK_FUNCTION );
pExpr = pExpr->x.pList->a[0].pExpr;
}else{
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
}
}
return pExpr;
}
/*
** Return the collation sequence for the expression pExpr. If
** there is no defined collating sequence, return NULL.
**
** See also: sqlite3ExprNNCollSeq()
**
** The sqlite3ExprNNCollSeq() works the same exact that it returns the
** default collation if pExpr has no defined collation.
**
** The collating sequence might be determined by a COLLATE operator
** or by the presence of a column with a defined collating sequence.
** COLLATE operators take first precedence. Left operands take
** precedence over right operands.
*/
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
sqlite3 *db = pParse->db;
CollSeq *pColl = 0;
Expr *p = pExpr;
while( p ){
int op = p->op;
if( op==TK_REGISTER ) op = p->op2;
if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
&& p->y.pTab!=0
){
/* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
** a TK_COLUMN but was previously evaluated and cached in a register */
int j = p->iColumn;
if( j>=0 ){
const char *zColl = p->y.pTab->aCol[j].zColl;
pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
}
break;
}
if( op==TK_CAST || op==TK_UPLUS ){
p = p->pLeft;
continue;
}
if( op==TK_VECTOR ){
p = p->x.pList->a[0].pExpr;
continue;
}
if( op==TK_COLLATE ){
pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
break;
}
if( p->flags & EP_Collate ){
if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
p = p->pLeft;
}else{
Expr *pNext = p->pRight;
/* The Expr.x union is never used at the same time as Expr.pRight */
assert( p->x.pList==0 || p->pRight==0 );
if( p->x.pList!=0
&& !db->mallocFailed
&& ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
pNext = p->x.pList->a[i].pExpr;
break;
}
}
}
p = pNext;
}
}else{
break;
}
}
if( sqlite3CheckCollSeq(pParse, pColl) ){
pColl = 0;
}
return pColl;
}
/*
** Return the collation sequence for the expression pExpr. If
** there is no defined collating sequence, return a pointer to the
** defautl collation sequence.
**
** See also: sqlite3ExprCollSeq()
**
** The sqlite3ExprCollSeq() routine works the same except that it
** returns NULL if there is no defined collation.
*/
CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
if( p==0 ) p = pParse->db->pDfltColl;
assert( p!=0 );
return p;
}
/*
** Return TRUE if the two expressions have equivalent collating sequences.
*/
int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
}
/*
** pExpr is an operand of a comparison operator. aff2 is the
** type affinity of the other operand. This routine returns the
** type affinity that should be used for the comparison operator.
*/
char sqlite3CompareAffinity(Expr *pExpr, char aff2){
char aff1 = sqlite3ExprAffinity(pExpr);
if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
/* Both sides of the comparison are columns. If one has numeric
** affinity, use that. Otherwise use no affinity.
*/
if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
return SQLITE_AFF_NUMERIC;
}else{
return SQLITE_AFF_BLOB;
}
}else{
/* One side is a column, the other is not. Use the columns affinity. */
assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
}
}
/*
** pExpr is a comparison operator. Return the type affinity that should
** be applied to both operands prior to doing the comparison.
*/
static char comparisonAffinity(Expr *pExpr){
char aff;
assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
assert( pExpr->pLeft );
aff = sqlite3ExprAffinity(pExpr->pLeft);
if( pExpr->pRight ){
aff = sqlite3CompareAffinity(pExpr->pRight, aff);
}else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
}else if( aff==0 ){
aff = SQLITE_AFF_BLOB;
}
return aff;
}
/*
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
** idx_affinity is the affinity of an indexed column. Return true
** if the index with affinity idx_affinity may be used to implement
** the comparison in pExpr.
*/
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
char aff = comparisonAffinity(pExpr);
if( aff<SQLITE_AFF_TEXT ){
return 1;
}
if( aff==SQLITE_AFF_TEXT ){
return idx_affinity==SQLITE_AFF_TEXT;
}
return sqlite3IsNumericAffinity(idx_affinity);
}
/*
** Return the P5 value that should be used for a binary comparison
** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
*/
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
u8 aff = (char)sqlite3ExprAffinity(pExpr2);
aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
return aff;
}
/*
** Return a pointer to the collation sequence that should be used by
** a binary comparison operator comparing pLeft and pRight.
**
** If the left hand expression has a collating sequence type, then it is
** used. Otherwise the collation sequence for the right hand expression
** is used, or the default (BINARY) if neither expression has a collating
** type.
**
** Argument pRight (but not pLeft) may be a null pointer. In this case,
** it is not considered.
*/
CollSeq *sqlite3BinaryCompareCollSeq(
Parse *pParse,
Expr *pLeft,
Expr *pRight
){
CollSeq *pColl;
assert( pLeft );
if( pLeft->flags & EP_Collate ){
pColl = sqlite3ExprCollSeq(pParse, pLeft);
}else if( pRight && (pRight->flags & EP_Collate)!=0 ){
pColl = sqlite3ExprCollSeq(pParse, pRight);
}else{
pColl = sqlite3ExprCollSeq(pParse, pLeft);
if( !pColl ){
pColl = sqlite3ExprCollSeq(pParse, pRight);
}
}
return pColl;
}
/* Expresssion p is a comparison operator. Return a collation sequence
** appropriate for the comparison operator.
**
** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
** However, if the OP_Commuted flag is set, then the order of the operands
** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
** correct collating sequence is found.
*/
CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, Expr *p){
if( ExprHasProperty(p, EP_Commuted) ){
return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
}else{
return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
}
}
/*
** Generate code for a comparison operator.
*/
static int codeCompare(
Parse *pParse, /* The parsing (and code generating) context */
Expr *pLeft, /* The left operand */
Expr *pRight, /* The right operand */
int opcode, /* The comparison opcode */
int in1, int in2, /* Register holding operands */
int dest, /* Jump here if true. */
int jumpIfNull, /* If true, jump if either operand is NULL */
int isCommuted /* The comparison has been commuted */
){
int p5;
int addr;
CollSeq *p4;
if( pParse->nErr ) return 0;
if( isCommuted ){
p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
}else{
p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
}
p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
(void*)p4, P4_COLLSEQ);
sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
return addr;
}
/*
** Return true if expression pExpr is a vector, or false otherwise.
**
** A vector is defined as any expression that results in two or more
** columns of result. Every TK_VECTOR node is an vector because the
** parser will not generate a TK_VECTOR with fewer than two entries.
** But a TK_SELECT might be either a vector or a scalar. It is only
** considered a vector if it has two or more result columns.
*/
int sqlite3ExprIsVector(Expr *pExpr){
return sqlite3ExprVectorSize(pExpr)>1;
}
/*
** If the expression passed as the only argument is of type TK_VECTOR
** return the number of expressions in the vector. Or, if the expression
** is a sub-select, return the number of columns in the sub-select. For
** any other type of expression, return 1.
*/
int sqlite3ExprVectorSize(Expr *pExpr){
u8 op = pExpr->op;
if( op==TK_REGISTER ) op = pExpr->op2;
if( op==TK_VECTOR ){
return pExpr->x.pList->nExpr;
}else if( op==TK_SELECT ){
return pExpr->x.pSelect->pEList->nExpr;
}else{
return 1;
}
}
/*
** Return a pointer to a subexpression of pVector that is the i-th
** column of the vector (numbered starting with 0). The caller must
** ensure that i is within range.
**
** If pVector is really a scalar (and "scalar" here includes subqueries
** that return a single column!) then return pVector unmodified.
**
** pVector retains ownership of the returned subexpression.
**
** If the vector is a (SELECT ...) then the expression returned is
** just the expression for the i-th term of the result set, and may
** not be ready for evaluation because the table cursor has not yet
** been positioned.
*/
Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
assert( i<sqlite3ExprVectorSize(pVector) );
if( sqlite3ExprIsVector(pVector) ){
assert( pVector->op2==0 || pVector->op==TK_REGISTER );
if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
return pVector->x.pSelect->pEList->a[i].pExpr;
}else{
return pVector->x.pList->a[i].pExpr;
}
}
return pVector;
}
/*
** Compute and return a new Expr object which when passed to
** sqlite3ExprCode() will generate all necessary code to compute
** the iField-th column of the vector expression pVector.
**
** It is ok for pVector to be a scalar (as long as iField==0).
** In that case, this routine works like sqlite3ExprDup().
**
** The caller owns the returned Expr object and is responsible for
** ensuring that the returned value eventually gets freed.
**
** The caller retains ownership of pVector. If pVector is a TK_SELECT,
** then the returned object will reference pVector and so pVector must remain
** valid for the life of the returned object. If pVector is a TK_VECTOR
** or a scalar expression, then it can be deleted as soon as this routine
** returns.
**
** A trick to cause a TK_SELECT pVector to be deleted together with
** the returned Expr object is to attach the pVector to the pRight field
** of the returned TK_SELECT_COLUMN Expr object.
*/
Expr *sqlite3ExprForVectorField(
Parse *pParse, /* Parsing context */
Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
int iField /* Which column of the vector to return */
){
Expr *pRet;
if( pVector->op==TK_SELECT ){
assert( pVector->flags & EP_xIsSelect );
/* The TK_SELECT_COLUMN Expr node:
**
** pLeft: pVector containing TK_SELECT. Not deleted.
** pRight: not used. But recursively deleted.
** iColumn: Index of a column in pVector
** iTable: 0 or the number of columns on the LHS of an assignment
** pLeft->iTable: First in an array of register holding result, or 0
** if the result is not yet computed.
**
** sqlite3ExprDelete() specifically skips the recursive delete of
** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
** can be attached to pRight to cause this node to take ownership of
** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
** with the same pLeft pointer to the pVector, but only one of them
** will own the pVector.
*/
pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
if( pRet ){
pRet->iColumn = iField;
pRet->pLeft = pVector;
}
assert( pRet==0 || pRet->iTable==0 );
}else{
if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
pRet = sqlite3ExprDup(pParse->db, pVector, 0);
sqlite3RenameTokenRemap(pParse, pRet, pVector);
}
return pRet;
}
/*
** If expression pExpr is of type TK_SELECT, generate code to evaluate
** it. Return the register in which the result is stored (or, if the
** sub-select returns more than one column, the first in an array
** of registers in which the result is stored).
**
** If pExpr is not a TK_SELECT expression, return 0.
*/
static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
int reg = 0;
#ifndef SQLITE_OMIT_SUBQUERY
if( pExpr->op==TK_SELECT ){
reg = sqlite3CodeSubselect(pParse, pExpr);
}
#endif
return reg;
}
/*
** Argument pVector points to a vector expression - either a TK_VECTOR
** or TK_SELECT that returns more than one column. This function returns
** the register number of a register that contains the value of
** element iField of the vector.
**
** If pVector is a TK_SELECT expression, then code for it must have
** already been generated using the exprCodeSubselect() routine. In this
** case parameter regSelect should be the first in an array of registers
** containing the results of the sub-select.
**
** If pVector is of type TK_VECTOR, then code for the requested field
** is generated. In this case (*pRegFree) may be set to the number of
** a temporary register to be freed by the caller before returning.
**
** Before returning, output parameter (*ppExpr) is set to point to the
** Expr object corresponding to element iElem of the vector.
*/
static int exprVectorRegister(
Parse *pParse, /* Parse context */
Expr *pVector, /* Vector to extract element from */
int iField, /* Field to extract from pVector */
int regSelect, /* First in array of registers */
Expr **ppExpr, /* OUT: Expression element */
int *pRegFree /* OUT: Temp register to free */
){
u8 op = pVector->op;
assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
if( op==TK_REGISTER ){
*ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
return pVector->iTable+iField;
}
if( op==TK_SELECT ){
*ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
return regSelect+iField;
}
*ppExpr = pVector->x.pList->a[iField].pExpr;
return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
}
/*
** Expression pExpr is a comparison between two vector values. Compute
** the result of the comparison (1, 0, or NULL) and write that
** result into register dest.
**
** The caller must satisfy the following preconditions:
**
** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
** otherwise: op==pExpr->op and p5==0
*/
static void codeVectorCompare(
Parse *pParse, /* Code generator context */
Expr *pExpr, /* The comparison operation */
int dest, /* Write results into this register */
u8 op, /* Comparison operator */
u8 p5 /* SQLITE_NULLEQ or zero */
){
Vdbe *v = pParse->pVdbe;
Expr *pLeft = pExpr->pLeft;
Expr *pRight = pExpr->pRight;
int nLeft = sqlite3ExprVectorSize(pLeft);
int i;
int regLeft = 0;
int regRight = 0;
u8 opx = op;
int addrDone = sqlite3VdbeMakeLabel(pParse);
int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
if( nLeft!=sqlite3ExprVectorSize(pRight) ){
sqlite3ErrorMsg(pParse, "row value misused");
return;
}
assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
|| pExpr->op==TK_IS || pExpr->op==TK_ISNOT
|| pExpr->op==TK_LT || pExpr->op==TK_GT
|| pExpr->op==TK_LE || pExpr->op==TK_GE
);
assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
|| (pExpr->op==TK_ISNOT && op==TK_NE) );
assert( p5==0 || pExpr->op!=op );
assert( p5==SQLITE_NULLEQ || pExpr->op==op );
p5 |= SQLITE_STOREP2;
if( opx==TK_LE ) opx = TK_LT;
if( opx==TK_GE ) opx = TK_GT;
regLeft = exprCodeSubselect(pParse, pLeft);
regRight = exprCodeSubselect(pParse, pRight);
for(i=0; 1 /*Loop exits by "break"*/; i++){
int regFree1 = 0, regFree2 = 0;
Expr *pL, *pR;
int r1, r2;
assert( i>=0 && i<nLeft );
r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1);
r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2);
codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
if( i==nLeft-1 ){
break;
}
if( opx==TK_EQ ){
sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
p5 |= SQLITE_KEEPNULL;
}else if( opx==TK_NE ){
sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
p5 |= SQLITE_KEEPNULL;
}else{
assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
VdbeCoverageIf(v, op==TK_LT);
VdbeCoverageIf(v, op==TK_GT);
VdbeCoverageIf(v, op==TK_LE);
VdbeCoverageIf(v, op==TK_GE);
if( i==nLeft-2 ) opx = op;
}
}
sqlite3VdbeResolveLabel(v, addrDone);
}
#if SQLITE_MAX_EXPR_DEPTH>0
/*
** Check that argument nHeight is less than or equal to the maximum
** expression depth allowed. If it is not, leave an error message in
** pParse.
*/
int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
int rc = SQLITE_OK;
int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
if( nHeight>mxHeight ){
sqlite3ErrorMsg(pParse,
"Expression tree is too large (maximum depth %d)", mxHeight
);
rc = SQLITE_ERROR;
}
return rc;
}
/* The following three functions, heightOfExpr(), heightOfExprList()
** and heightOfSelect(), are used to determine the maximum height
** of any expression tree referenced by the structure passed as the
** first argument.
**
** If this maximum height is greater than the current value pointed
** to by pnHeight, the second parameter, then set *pnHeight to that
** value.
*/
static void heightOfExpr(Expr *p, int *pnHeight){
if( p ){
if( p->nHeight>*pnHeight ){
*pnHeight = p->nHeight;
}
}
}
static void heightOfExprList(ExprList *p, int *pnHeight){
if( p ){
int i;
for(i=0; i<p->nExpr; i++){
heightOfExpr(p->a[i].pExpr, pnHeight);
}
}
}
static void heightOfSelect(Select *pSelect, int *pnHeight){
Select *p;
for(p=pSelect; p; p=p->pPrior){
heightOfExpr(p->pWhere, pnHeight);
heightOfExpr(p->pHaving, pnHeight);
heightOfExpr(p->pLimit, pnHeight);
heightOfExprList(p->pEList, pnHeight);
heightOfExprList(p->pGroupBy, pnHeight);
heightOfExprList(p->pOrderBy, pnHeight);
}
}
/*
** Set the Expr.nHeight variable in the structure passed as an
** argument. An expression with no children, Expr.pList or
** Expr.pSelect member has a height of 1. Any other expression
** has a height equal to the maximum height of any other
** referenced Expr plus one.
**
** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
** if appropriate.
*/
static void exprSetHeight(Expr *p){
int nHeight = 0;
heightOfExpr(p->pLeft, &nHeight);
heightOfExpr(p->pRight, &nHeight);
if( ExprHasProperty(p, EP_xIsSelect) ){
heightOfSelect(p->x.pSelect, &nHeight);
}else if( p->x.pList ){
heightOfExprList(p->x.pList, &nHeight);
p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
}
p->nHeight = nHeight + 1;
}
/*
** Set the Expr.nHeight variable using the exprSetHeight() function. If
** the height is greater than the maximum allowed expression depth,
** leave an error in pParse.
**
** Also propagate all EP_Propagate flags from the Expr.x.pList into
** Expr.flags.
*/
void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
if( pParse->nErr ) return;
exprSetHeight(p);
sqlite3ExprCheckHeight(pParse, p->nHeight);
}
/*
** Return the maximum height of any expression tree referenced
** by the select statement passed as an argument.
*/
int sqlite3SelectExprHeight(Select *p){
int nHeight = 0;
heightOfSelect(p, &nHeight);
return nHeight;
}
#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
/*
** Propagate all EP_Propagate flags from the Expr.x.pList into
** Expr.flags.
*/
void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
}
}
#define exprSetHeight(y)
#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
/*
** This routine is the core allocator for Expr nodes.
**
** Construct a new expression node and return a pointer to it. Memory
** for this node and for the pToken argument is a single allocation
** obtained from sqlite3DbMalloc(). The calling function
** is responsible for making sure the node eventually gets freed.
**
** If dequote is true, then the token (if it exists) is dequoted.
** If dequote is false, no dequoting is performed. The deQuote
** parameter is ignored if pToken is NULL or if the token does not
** appear to be quoted. If the quotes were of the form "..." (double-quotes)
** then the EP_DblQuoted flag is set on the expression node.
**
** Special case: If op==TK_INTEGER and pToken points to a string that
** can be translated into a 32-bit integer, then the token is not
** stored in u.zToken. Instead, the integer values is written
** into u.iValue and the EP_IntValue flag is set. No extra storage
** is allocated to hold the integer text and the dequote flag is ignored.
*/
Expr *sqlite3ExprAlloc(
sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
int op, /* Expression opcode */
const Token *pToken, /* Token argument. Might be NULL */
int dequote /* True to dequote */
){
Expr *pNew;
int nExtra = 0;
int iValue = 0;
assert( db!=0 );
if( pToken ){
if( op!=TK_INTEGER || pToken->z==0
|| sqlite3GetInt32(pToken->z, &iValue)==0 ){
nExtra = pToken->n+1;
assert( iValue>=0 );
}
}
pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
if( pNew ){
memset(pNew, 0, sizeof(Expr));
pNew->op = (u8)op;
pNew->iAgg = -1;
if( pToken ){
if( nExtra==0 ){
pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
pNew->u.iValue = iValue;
}else{
pNew->u.zToken = (char*)&pNew[1];
assert( pToken->z!=0 || pToken->n==0 );
if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
pNew->u.zToken[pToken->n] = 0;
if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
sqlite3DequoteExpr(pNew);
}
}
}
#if SQLITE_MAX_EXPR_DEPTH>0
pNew->nHeight = 1;
#endif
}
return pNew;
}
/*
** Allocate a new expression node from a zero-terminated token that has
** already been dequoted.
*/
Expr *sqlite3Expr(
sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
int op, /* Expression opcode */
const char *zToken /* Token argument. Might be NULL */
){
Token x;
x.z = zToken;
x.n = sqlite3Strlen30(zToken);
return sqlite3ExprAlloc(db, op, &x, 0);
}
/*
** Attach subtrees pLeft and pRight to the Expr node pRoot.
**
** If pRoot==NULL that means that a memory allocation error has occurred.
** In that case, delete the subtrees pLeft and pRight.
*/
void sqlite3ExprAttachSubtrees(
sqlite3 *db,
Expr *pRoot,
Expr *pLeft,
Expr *pRight
){
if( pRoot==0 ){
assert( db->mallocFailed );
sqlite3ExprDelete(db, pLeft);
sqlite3ExprDelete(db, pRight);
}else{
if( pRight ){
pRoot->pRight = pRight;
pRoot->flags |= EP_Propagate & pRight->flags;
}
if( pLeft ){
pRoot->pLeft = pLeft;
pRoot->flags |= EP_Propagate & pLeft->flags;
}
exprSetHeight(pRoot);
}
}
/*
** Allocate an Expr node which joins as many as two subtrees.
**
** One or both of the subtrees can be NULL. Return a pointer to the new
** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
** free the subtrees and return NULL.
*/
Expr *sqlite3PExpr(
Parse *pParse, /* Parsing context */
int op, /* Expression opcode */
Expr *pLeft, /* Left operand */
Expr *pRight /* Right operand */
){
Expr *p;
p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
if( p ){
memset(p, 0, sizeof(Expr));
p->op = op & 0xff;
p->iAgg = -1;
sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
sqlite3ExprCheckHeight(pParse, p->nHeight);
}else{
sqlite3ExprDelete(pParse->db, pLeft);
sqlite3ExprDelete(pParse->db, pRight);
}
return p;
}
/*
** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
** do a memory allocation failure) then delete the pSelect object.
*/
void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
if( pExpr ){
pExpr->x.pSelect = pSelect;
ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, pExpr);
}else{
assert( pParse->db->mallocFailed );
sqlite3SelectDelete(pParse->db, pSelect);
}
}
/*
** Join two expressions using an AND operator. If either expression is
** NULL, then just return the other expression.
**
** If one side or the other of the AND is known to be false, then instead
** of returning an AND expression, just return a constant expression with
** a value of false.
*/
Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
sqlite3 *db = pParse->db;
if( pLeft==0 ){
return pRight;
}else if( pRight==0 ){
return pLeft;
}else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
sqlite3ExprUnmapAndDelete(pParse, pLeft);
sqlite3ExprUnmapAndDelete(pParse, pRight);
return sqlite3Expr(db, TK_INTEGER, "0");
}else{
return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
}
}
/*
** Construct a new expression node for a function with multiple
** arguments.
*/
Expr *sqlite3ExprFunction(
Parse *pParse, /* Parsing context */
ExprList *pList, /* Argument list */
Token *pToken, /* Name of the function */
int eDistinct /* SF_Distinct or SF_ALL or 0 */
){
Expr *pNew;
sqlite3 *db = pParse->db;
assert( pToken );
pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
if( pNew==0 ){
sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
return 0;
}
if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
}
pNew->x.pList = pList;
ExprSetProperty(pNew, EP_HasFunc);
assert( !ExprHasProperty(pNew, EP_xIsSelect) );
sqlite3ExprSetHeightAndFlags(pParse, pNew);
if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
return pNew;
}
/*
** Assign a variable number to an expression that encodes a wildcard
** in the original SQL statement.
**
** Wildcards consisting of a single "?" are assigned the next sequential
** variable number.
**
** Wildcards of the form "?nnn" are assigned the number "nnn". We make
** sure "nnn" is not too big to avoid a denial of service attack when
** the SQL statement comes from an external source.
**
** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
** as the previous instance of the same wildcard. Or if this is the first
** instance of the wildcard, the next sequential variable number is
** assigned.
*/
void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
sqlite3 *db = pParse->db;
const char *z;
ynVar x;
if( pExpr==0 ) return;
assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
z = pExpr->u.zToken;
assert( z!=0 );
assert( z[0]!=0 );
assert( n==(u32)sqlite3Strlen30(z) );
if( z[1]==0 ){
/* Wildcard of the form "?". Assign the next variable number */
assert( z[0]=='?' );
x = (ynVar)(++pParse->nVar);
}else{
int doAdd = 0;
if( z[0]=='?' ){
/* Wildcard of the form "?nnn". Convert "nnn" to an integer and
** use it as the variable number */
i64 i;
int bOk;
if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
i = z[1]-'0'; /* The common case of ?N for a single digit N */
bOk = 1;
}else{
bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
}
testcase( i==0 );
testcase( i==1 );
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
return;
}
x = (ynVar)i;
if( x>pParse->nVar ){
pParse->nVar = (int)x;
doAdd = 1;
}else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
doAdd = 1;
}
}else{
/* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
** number as the prior appearance of the same name, or if the name
** has never appeared before, reuse the same variable number
*/
x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
if( x==0 ){
x = (ynVar)(++pParse->nVar);
doAdd = 1;
}
}
if( doAdd ){
pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
}
}
pExpr->iColumn = x;
if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
sqlite3ErrorMsg(pParse, "too many SQL variables");
}
}
/*
** Recursively delete an expression tree.
*/
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
assert( p!=0 );
/* Sanity check: Assert that the IntValue is non-negative if it exists */
assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
|| p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
#ifdef SQLITE_DEBUG
if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
assert( p->pLeft==0 );
assert( p->pRight==0 );
assert( p->x.pSelect==0 );
}
#endif
if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
/* The Expr.x union is never used at the same time as Expr.pRight */
assert( p->x.pList==0 || p->pRight==0 );
if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
if( p->pRight ){
assert( !ExprHasProperty(p, EP_WinFunc) );
sqlite3ExprDeleteNN(db, p->pRight);
}else if( ExprHasProperty(p, EP_xIsSelect) ){
assert( !ExprHasProperty(p, EP_WinFunc) );
sqlite3SelectDelete(db, p->x.pSelect);
}else{
sqlite3ExprListDelete(db, p->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(p, EP_WinFunc) ){
sqlite3WindowDelete(db, p->y.pWin);
}
#endif
}
}
if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
if( !ExprHasProperty(p, EP_Static) ){
sqlite3DbFreeNN(db, p);
}
}
void sqlite3ExprDelete(sqlite3 *db, Expr *p){
if( p ) sqlite3ExprDeleteNN(db, p);
}
/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
** expression.
*/
void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
if( p ){
if( IN_RENAME_OBJECT ){
sqlite3RenameExprUnmap(pParse, p);
}
sqlite3ExprDeleteNN(pParse->db, p);
}
}
/*
** Return the number of bytes allocated for the expression structure
** passed as the first argument. This is always one of EXPR_FULLSIZE,
** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
*/
static int exprStructSize(Expr *p){
if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
return EXPR_FULLSIZE;
}
/*
** The dupedExpr*Size() routines each return the number of bytes required
** to store a copy of an expression or expression tree. They differ in
** how much of the tree is measured.
**
** dupedExprStructSize() Size of only the Expr structure
** dupedExprNodeSize() Size of Expr + space for token
** dupedExprSize() Expr + token + subtree components
**
***************************************************************************
**
** The dupedExprStructSize() function returns two values OR-ed together:
** (1) the space required for a copy of the Expr structure only and
** (2) the EP_xxx flags that indicate what the structure size should be.
** The return values is always one of:
**
** EXPR_FULLSIZE
** EXPR_REDUCEDSIZE | EP_Reduced
** EXPR_TOKENONLYSIZE | EP_TokenOnly
**
** The size of the structure can be found by masking the return value
** of this routine with 0xfff. The flags can be found by masking the
** return value with EP_Reduced|EP_TokenOnly.
**
** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
** (unreduced) Expr objects as they or originally constructed by the parser.
** During expression analysis, extra information is computed and moved into
** later parts of the Expr object and that extra information might get chopped
** off if the expression is reduced. Note also that it does not work to
** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
** to reduce a pristine expression tree from the parser. The implementation
** of dupedExprStructSize() contain multiple assert() statements that attempt
** to enforce this constraint.
*/
static int dupedExprStructSize(Expr *p, int flags){
int nSize;
assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
assert( EXPR_FULLSIZE<=0xfff );
assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
if( 0==flags || p->op==TK_SELECT_COLUMN
#ifndef SQLITE_OMIT_WINDOWFUNC
|| ExprHasProperty(p, EP_WinFunc)
#endif
){
nSize = EXPR_FULLSIZE;
}else{
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
assert( !ExprHasProperty(p, EP_FromJoin) );
assert( !ExprHasProperty(p, EP_MemToken) );
assert( !ExprHasProperty(p, EP_NoReduce) );
if( p->pLeft || p->x.pList ){
nSize = EXPR_REDUCEDSIZE | EP_Reduced;
}else{
assert( p->pRight==0 );
nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
}
}
return nSize;
}
/*
** This function returns the space in bytes required to store the copy
** of the Expr structure and a copy of the Expr.u.zToken string (if that
** string is defined.)
*/
static int dupedExprNodeSize(Expr *p, int flags){
int nByte = dupedExprStructSize(p, flags) & 0xfff;
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
nByte += sqlite3Strlen30NN(p->u.zToken)+1;
}
return ROUND8(nByte);
}
/*
** Return the number of bytes required to create a duplicate of the
** expression passed as the first argument. The second argument is a
** mask containing EXPRDUP_XXX flags.
**
** The value returned includes space to create a copy of the Expr struct
** itself and the buffer referred to by Expr.u.zToken, if any.
**
** If the EXPRDUP_REDUCE flag is set, then the return value includes
** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
** and Expr.pRight variables (but not for any structures pointed to or
** descended from the Expr.x.pList or Expr.x.pSelect variables).
*/
static int dupedExprSize(Expr *p, int flags){
int nByte = 0;
if( p ){
nByte = dupedExprNodeSize(p, flags);
if( flags&EXPRDUP_REDUCE ){
nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
}
}
return nByte;
}
/*
** This function is similar to sqlite3ExprDup(), except that if pzBuffer
** is not NULL then *pzBuffer is assumed to point to a buffer large enough
** to store the copy of expression p, the copies of p->u.zToken
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
** if any. Before returning, *pzBuffer is set to the first byte past the
** portion of the buffer copied into by this function.
*/
static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
Expr *pNew; /* Value to return */
u8 *zAlloc; /* Memory space from which to build Expr object */
u32 staticFlag; /* EP_Static if space not obtained from malloc */
assert( db!=0 );
assert( p );
assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
/* Figure out where to write the new Expr structure. */
if( pzBuffer ){
zAlloc = *pzBuffer;
staticFlag = EP_Static;
}else{
zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
staticFlag = 0;
}
pNew = (Expr *)zAlloc;
if( pNew ){
/* Set nNewSize to the size allocated for the structure pointed to
** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
** by the copy of the p->u.zToken string (if any).
*/
const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
const int nNewSize = nStructSize & 0xfff;
int nToken;
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
nToken = sqlite3Strlen30(p->u.zToken) + 1;
}else{
nToken = 0;
}
if( dupFlags ){
assert( ExprHasProperty(p, EP_Reduced)==0 );
memcpy(zAlloc, p, nNewSize);
}else{
u32 nSize = (u32)exprStructSize(p);
memcpy(zAlloc, p, nSize);
if( nSize<EXPR_FULLSIZE ){
memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
}
}
/* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
pNew->flags |= staticFlag;
/* Copy the p->u.zToken string, if any. */
if( nToken ){
char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
memcpy(zToken, p->u.zToken, nToken);
}
if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
/* Fill in the pNew->x.pSelect or pNew->x.pList member. */
if( ExprHasProperty(p, EP_xIsSelect) ){
pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
}else{
pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
}
}
/* Fill in pNew->pLeft and pNew->pRight. */
if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
zAlloc += dupedExprNodeSize(p, dupFlags);
if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
pNew->pLeft = p->pLeft ?
exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
pNew->pRight = p->pRight ?
exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(p, EP_WinFunc) ){
pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
assert( ExprHasProperty(pNew, EP_WinFunc) );
}
#endif /* SQLITE_OMIT_WINDOWFUNC */
if( pzBuffer ){
*pzBuffer = zAlloc;
}
}else{
if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
if( pNew->op==TK_SELECT_COLUMN ){
pNew->pLeft = p->pLeft;
assert( p->iColumn==0 || p->pRight==0 );
assert( p->pRight==0 || p->pRight==p->pLeft );
}else{
pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
}
pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
}
}
}
return pNew;
}
/*
** Create and return a deep copy of the object passed as the second
** argument. If an OOM condition is encountered, NULL is returned
** and the db->mallocFailed flag set.
*/
#ifndef SQLITE_OMIT_CTE
static With *withDup(sqlite3 *db, With *p){
With *pRet = 0;
if( p ){
sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
pRet = sqlite3DbMallocZero(db, nByte);
if( pRet ){
int i;
pRet->nCte = p->nCte;
for(i=0; i<p->nCte; i++){
pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
}
}
}
return pRet;
}
#else
# define withDup(x,y) 0
#endif
#ifndef SQLITE_OMIT_WINDOWFUNC
/*
** The gatherSelectWindows() procedure and its helper routine
** gatherSelectWindowsCallback() are used to scan all the expressions
** an a newly duplicated SELECT statement and gather all of the Window
** objects found there, assembling them onto the linked list at Select->pWin.
*/
static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
Select *pSelect = pWalker->u.pSelect;
Window *pWin = pExpr->y.pWin;
assert( pWin );
assert( IsWindowFunc(pExpr) );
assert( pWin->ppThis==0 );
sqlite3WindowLink(pSelect, pWin);
}
return WRC_Continue;
}
static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
}
static void gatherSelectWindows(Select *p){
Walker w;
w.xExprCallback = gatherSelectWindowsCallback;
w.xSelectCallback = gatherSelectWindowsSelectCallback;
w.xSelectCallback2 = 0;
w.pParse = 0;
w.u.pSelect = p;
sqlite3WalkSelect(&w, p);
}
#endif
/*
** The following group of routines make deep copies of expressions,
** expression lists, ID lists, and select statements. The copies can
** be deleted (by being passed to their respective ...Delete() routines)
** without effecting the originals.
**
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
** by subsequent calls to sqlite*ListAppend() routines.
**
** Any tables that the SrcList might point to are not duplicated.
**
** The flags parameter contains a combination of the EXPRDUP_XXX flags.
** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
** truncated version of the usual Expr structure that will be stored as
** part of the in-memory representation of the database schema.
*/
Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
assert( flags==0 || flags==EXPRDUP_REDUCE );
return p ? exprDup(db, p, flags, 0) : 0;
}
ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
ExprList *pNew;
struct ExprList_item *pItem, *pOldItem;
int i;
Expr *pPriorSelectCol = 0;
assert( db!=0 );
if( p==0 ) return 0;
pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
if( pNew==0 ) return 0;
pNew->nExpr = p->nExpr;
pItem = pNew->a;
pOldItem = p->a;
for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
Expr *pOldExpr = pOldItem->pExpr;
Expr *pNewExpr;
pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
if( pOldExpr
&& pOldExpr->op==TK_SELECT_COLUMN
&& (pNewExpr = pItem->pExpr)!=0
){
assert( pNewExpr->iColumn==0 || i>0 );
if( pNewExpr->iColumn==0 ){
assert( pOldExpr->pLeft==pOldExpr->pRight );
pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
}else{
assert( i>0 );
assert( pItem[-1].pExpr!=0 );
assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
pNewExpr->pLeft = pPriorSelectCol;
}
}
pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
pItem->sortFlags = pOldItem->sortFlags;
pItem->done = 0;
pItem->bNulls = pOldItem->bNulls;
pItem->bSpanIsTab = pOldItem->bSpanIsTab;
pItem->bSorterRef = pOldItem->bSorterRef;
pItem->u = pOldItem->u;
}
return pNew;
}
/*
** If cursors, triggers, views and subqueries are all omitted from
** the build, then none of the following routines, except for
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
** called with a NULL argument.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
|| !defined(SQLITE_OMIT_SUBQUERY)
SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
SrcList *pNew;
int i;
int nByte;
assert( db!=0 );
if( p==0 ) return 0;
nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
pNew = sqlite3DbMallocRawNN(db, nByte );
if( pNew==0 ) return 0;
pNew->nSrc = pNew->nAlloc = p->nSrc;
for(i=0; i<p->nSrc; i++){
struct SrcList_item *pNewItem = &pNew->a[i];
struct SrcList_item *pOldItem = &p->a[i];
Table *pTab;
pNewItem->pSchema = pOldItem->pSchema;
pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
pNewItem->fg = pOldItem->fg;
pNewItem->iCursor = pOldItem->iCursor;
pNewItem->addrFillSub = pOldItem->addrFillSub;
pNewItem->regReturn = pOldItem->regReturn;
if( pNewItem->fg.isIndexedBy ){
pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
}
pNewItem->pIBIndex = pOldItem->pIBIndex;
if( pNewItem->fg.isTabFunc ){
pNewItem->u1.pFuncArg =
sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
}
pTab = pNewItem->pTab = pOldItem->pTab;
if( pTab ){
pTab->nTabRef++;
}
pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
pNewItem->colUsed = pOldItem->colUsed;
}
return pNew;
}
IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
IdList *pNew;
int i;
assert( db!=0 );
if( p==0 ) return 0;
pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
if( pNew==0 ) return 0;
pNew->nId = p->nId;
pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
if( pNew->a==0 ){
sqlite3DbFreeNN(db, pNew);
return 0;
}
/* Note that because the size of the allocation for p->a[] is not
** necessarily a power of two, sqlite3IdListAppend() may not be called
** on the duplicate created by this function. */
for(i=0; i<p->nId; i++){
struct IdList_item *pNewItem = &pNew->a[i];
struct IdList_item *pOldItem = &p->a[i];
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pNewItem->idx = pOldItem->idx;
}
return pNew;
}
Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
Select *pRet = 0;
Select *pNext = 0;
Select **pp = &pRet;
Select *p;
assert( db!=0 );
for(p=pDup; p; p=p->pPrior){
Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
if( pNew==0 ) break;
pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
pNew->op = p->op;
pNew->pNext = pNext;
pNew->pPrior = 0;
pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
pNew->iLimit = 0;
pNew->iOffset = 0;
pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
pNew->addrOpenEphm[0] = -1;
pNew->addrOpenEphm[1] = -1;
pNew->nSelectRow = p->nSelectRow;
pNew->pWith = withDup(db, p->pWith);
#ifndef SQLITE_OMIT_WINDOWFUNC
pNew->pWin = 0;
pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
#endif
pNew->selId = p->selId;
*pp = pNew;
pp = &pNew->pPrior;
pNext = pNew;
}
return pRet;
}
#else
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
assert( p==0 );
return 0;
}
#endif
/*
** Add a new element to the end of an expression list. If pList is
** initially NULL, then create a new expression list.
**
** The pList argument must be either NULL or a pointer to an ExprList
** obtained from a prior call to sqlite3ExprListAppend(). This routine
** may not be used with an ExprList obtained from sqlite3ExprListDup().
** Reason: This routine assumes that the number of slots in pList->a[]
** is a power of two. That is true for sqlite3ExprListAppend() returns
** but is not necessarily true from the return value of sqlite3ExprListDup().
**
** If a memory allocation error occurs, the entire list is freed and
** NULL is returned. If non-NULL is returned, then it is guaranteed
** that the new entry was successfully appended.
*/
ExprList *sqlite3ExprListAppend(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
Expr *pExpr /* Expression to be appended. Might be NULL */
){
struct ExprList_item *pItem;
sqlite3 *db = pParse->db;
assert( db!=0 );
if( pList==0 ){
pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
if( pList==0 ){
goto no_mem;
}
pList->nExpr = 0;
}else if( (pList->nExpr & (pList->nExpr-1))==0 ){
ExprList *pNew;
pNew = sqlite3DbRealloc(db, pList,
sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
if( pNew==0 ){
goto no_mem;
}
pList = pNew;
}
pItem = &pList->a[pList->nExpr++];
assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
assert( offsetof(struct ExprList_item,pExpr)==0 );
memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
pItem->pExpr = pExpr;
return pList;
no_mem:
/* Avoid leaking memory if malloc has failed. */
sqlite3ExprDelete(db, pExpr);
sqlite3ExprListDelete(db, pList);
return 0;
}
/*
** pColumns and pExpr form a vector assignment which is part of the SET
** clause of an UPDATE statement. Like this:
**
** (a,b,c) = (expr1,expr2,expr3)
** Or: (a,b,c) = (SELECT x,y,z FROM ....)
**
** For each term of the vector assignment, append new entries to the
** expression list pList. In the case of a subquery on the RHS, append
** TK_SELECT_COLUMN expressions.
*/
ExprList *sqlite3ExprListAppendVector(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
IdList *pColumns, /* List of names of LHS of the assignment */
Expr *pExpr /* Vector expression to be appended. Might be NULL */
){
sqlite3 *db = pParse->db;
int n;
int i;
int iFirst = pList ? pList->nExpr : 0;
/* pColumns can only be NULL due to an OOM but an OOM will cause an
** exit prior to this routine being invoked */
if( NEVER(pColumns==0) ) goto vector_append_error;
if( pExpr==0 ) goto vector_append_error;
/* If the RHS is a vector, then we can immediately check to see that
** the size of the RHS and LHS match. But if the RHS is a SELECT,
** wildcards ("*") in the result set of the SELECT must be expanded before
** we can do the size check, so defer the size check until code generation.
*/
if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
pColumns->nId, n);
goto vector_append_error;
}
for(i=0; i<pColumns->nId; i++){
Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
assert( pSubExpr!=0 || db->mallocFailed );
assert( pSubExpr==0 || pSubExpr->iTable==0 );
if( pSubExpr==0 ) continue;
pSubExpr->iTable = pColumns->nId;
pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
if( pList ){
assert( pList->nExpr==iFirst+i+1 );
pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
pColumns->a[i].zName = 0;
}
}
if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
Expr *pFirst = pList->a[iFirst].pExpr;
assert( pFirst!=0 );
assert( pFirst->op==TK_SELECT_COLUMN );
/* Store the SELECT statement in pRight so it will be deleted when
** sqlite3ExprListDelete() is called */
pFirst->pRight = pExpr;
pExpr = 0;
/* Remember the size of the LHS in iTable so that we can check that
** the RHS and LHS sizes match during code generation. */
pFirst->iTable = pColumns->nId;
}
vector_append_error:
sqlite3ExprUnmapAndDelete(pParse, pExpr);
sqlite3IdListDelete(db, pColumns);
return pList;
}
/*
** Set the sort order for the last element on the given ExprList.
*/
void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
struct ExprList_item *pItem;
if( p==0 ) return;
assert( p->nExpr>0 );
assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
assert( iSortOrder==SQLITE_SO_UNDEFINED
|| iSortOrder==SQLITE_SO_ASC
|| iSortOrder==SQLITE_SO_DESC
);
assert( eNulls==SQLITE_SO_UNDEFINED
|| eNulls==SQLITE_SO_ASC
|| eNulls==SQLITE_SO_DESC
);
pItem = &p->a[p->nExpr-1];
assert( pItem->bNulls==0 );
if( iSortOrder==SQLITE_SO_UNDEFINED ){
iSortOrder = SQLITE_SO_ASC;
}
pItem->sortFlags = (u8)iSortOrder;
if( eNulls!=SQLITE_SO_UNDEFINED ){
pItem->bNulls = 1;
if( iSortOrder!=eNulls ){
pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
}
}
}
/*
** Set the ExprList.a[].zName element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error. But pName should never be
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetName(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to add the span. */
Token *pName, /* Name to be added */
int dequote /* True to cause the name to be dequoted */
){
assert( pList!=0 || pParse->db->mallocFailed!=0 );
if( pList ){
struct ExprList_item *pItem;
assert( pList->nExpr>0 );
pItem = &pList->a[pList->nExpr-1];
assert( pItem->zName==0 );
pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
if( dequote ) sqlite3Dequote(pItem->zName);
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
}
}
}
/*
** Set the ExprList.a[].zSpan element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error. But pSpan should never be
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetSpan(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to add the span. */
const char *zStart, /* Start of the span */
const char *zEnd /* End of the span */
){
sqlite3 *db = pParse->db;
assert( pList!=0 || db->mallocFailed!=0 );
if( pList ){
struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
assert( pList->nExpr>0 );
sqlite3DbFree(db, pItem->zSpan);
pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
}
}
/*
** If the expression list pEList contains more than iLimit elements,
** leave an error message in pParse.
*/
void sqlite3ExprListCheckLength(
Parse *pParse,
ExprList *pEList,
const char *zObject
){
int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
testcase( pEList && pEList->nExpr==mx );
testcase( pEList && pEList->nExpr==mx+1 );
if( pEList && pEList->nExpr>mx ){
sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
}
}
/*
** Delete an entire expression list.
*/
static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
int i = pList->nExpr;
struct ExprList_item *pItem = pList->a;
assert( pList->nExpr>0 );
do{
sqlite3ExprDelete(db, pItem->pExpr);
sqlite3DbFree(db, pItem->zName);
sqlite3DbFree(db, pItem->zSpan);
pItem++;
}while( --i>0 );
sqlite3DbFreeNN(db, pList);
}
void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
if( pList ) exprListDeleteNN(db, pList);
}
/*
** Return the bitwise-OR of all Expr.flags fields in the given
** ExprList.
*/
u32 sqlite3ExprListFlags(const ExprList *pList){
int i;
u32 m = 0;
assert( pList!=0 );
for(i=0; i<pList->nExpr; i++){
Expr *pExpr = pList->a[i].pExpr;
assert( pExpr!=0 );
m |= pExpr->flags;
}
return m;
}
/*
** This is a SELECT-node callback for the expression walker that
** always "fails". By "fail" in this case, we mean set
** pWalker->eCode to zero and abort.
**
** This callback is used by multiple expression walkers.
*/
int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
UNUSED_PARAMETER(NotUsed);
pWalker->eCode = 0;
return WRC_Abort;
}
/*
** If the input expression is an ID with the name "true" or "false"
** then convert it into an TK_TRUEFALSE term. Return non-zero if
** the conversion happened, and zero if the expression is unaltered.
*/
int sqlite3ExprIdToTrueFalse(Expr *pExpr){
assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
if( !ExprHasProperty(pExpr, EP_Quoted)
&& (sqlite3StrICmp(pExpr->u.zToken, "true")==0
|| sqlite3StrICmp(pExpr->u.zToken, "false")==0)
){
pExpr->op = TK_TRUEFALSE;
ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
return 1;
}
return 0;
}
/*
** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
** and 0 if it is FALSE.
*/
int sqlite3ExprTruthValue(const Expr *pExpr){
pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
assert( pExpr->op==TK_TRUEFALSE );
assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
|| sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
return pExpr->u.zToken[4]==0;
}
/*
** If pExpr is an AND or OR expression, try to simplify it by eliminating
** terms that are always true or false. Return the simplified expression.
** Or return the original expression if no simplification is possible.
**
** Examples:
**
** (x<10) AND true => (x<10)
** (x<10) AND false => false
** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
** (x<10) AND (y=22 OR true) => (x<10)
** (y=22) OR true => true
*/
Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
assert( pExpr!=0 );
if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
pExpr = pExpr->op==TK_AND ? pRight : pLeft;
}else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
pExpr = pExpr->op==TK_AND ? pLeft : pRight;
}
}
return pExpr;
}
/*
** These routines are Walker callbacks used to check expressions to
** see if they are "constant" for some definition of constant. The
** Walker.eCode value determines the type of "constant" we are looking
** for.
**
** These callback routines are used to implement the following:
**
** sqlite3ExprIsConstant() pWalker->eCode==1
** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
** sqlite3ExprIsTableConstant() pWalker->eCode==3
** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
**
** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
** is found to not be a constant.
**
** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
** an existing schema and 4 when processing a new statement. A bound
** parameter raises an error for new statements, but is silently converted
** to NULL for existing schemas. This allows sqlite_master tables that
** contain a bound parameter because they were generated by older versions
** of SQLite to be parsed by newer versions of SQLite without raising a
** malformed schema error.
*/
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
/* If pWalker->eCode is 2 then any term of the expression that comes from
** the ON or USING clauses of a left join disqualifies the expression
** from being considered constant. */
if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
pWalker->eCode = 0;
return WRC_Abort;
}
switch( pExpr->op ){
/* Consider functions to be constant if all their arguments are constant
** and either pWalker->eCode==4 or 5 or the function has the
** SQLITE_FUNC_CONST flag. */
case TK_FUNCTION:
if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
&& !ExprHasProperty(pExpr, EP_WinFunc)
){
return WRC_Continue;
}else{
pWalker->eCode = 0;
return WRC_Abort;
}
case TK_ID:
/* Convert "true" or "false" in a DEFAULT clause into the
** appropriate TK_TRUEFALSE operator */
if( sqlite3ExprIdToTrueFalse(pExpr) ){
return WRC_Prune;
}
/* Fall thru */
case TK_COLUMN:
case TK_AGG_FUNCTION:
case TK_AGG_COLUMN:
testcase( pExpr->op==TK_ID );
testcase( pExpr->op==TK_COLUMN );
testcase( pExpr->op==TK_AGG_FUNCTION );
testcase( pExpr->op==TK_AGG_COLUMN );
if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
return WRC_Continue;
}
if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
return WRC_Continue;
}
/* Fall through */
case TK_IF_NULL_ROW:
case TK_REGISTER:
testcase( pExpr->op==TK_REGISTER );
testcase( pExpr->op==TK_IF_NULL_ROW );
pWalker->eCode = 0;
return WRC_Abort;
case TK_VARIABLE:
if( pWalker->eCode==5 ){
/* Silently convert bound parameters that appear inside of CREATE
** statements into a NULL when parsing the CREATE statement text out
** of the sqlite_master table */
pExpr->op = TK_NULL;
}else if( pWalker->eCode==4 ){
/* A bound parameter in a CREATE statement that originates from
** sqlite3_prepare() causes an error */
pWalker->eCode = 0;
return WRC_Abort;
}
/* Fall through */
default:
testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
return WRC_Continue;
}
}
static int exprIsConst(Expr *p, int initFlag, int iCur){
Walker w;
w.eCode = initFlag;
w.xExprCallback = exprNodeIsConstant;
w.xSelectCallback = sqlite3SelectWalkFail;
#ifdef SQLITE_DEBUG
w.xSelectCallback2 = sqlite3SelectWalkAssert2;
#endif
w.u.iCur = iCur;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** and 0 if it involves variables or function calls.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstant(Expr *p){
return exprIsConst(p, 1, 0);
}
/*
** Walk an expression tree. Return non-zero if
**
** (1) the expression is constant, and
** (2) the expression does originate in the ON or USING clause
** of a LEFT JOIN, and
** (3) the expression does not contain any EP_FixedCol TK_COLUMN
** operands created by the constant propagation optimization.
**
** When this routine returns true, it indicates that the expression
** can be added to the pParse->pConstExpr list and evaluated once when
** the prepared statement starts up. See sqlite3ExprCodeAtInit().
*/
int sqlite3ExprIsConstantNotJoin(Expr *p){
return exprIsConst(p, 2, 0);
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** for any single row of the table with cursor iCur. In other words, the
** expression must not refer to any non-deterministic function nor any
** table other than iCur.
*/
int sqlite3ExprIsTableConstant(Expr *p, int iCur){
return exprIsConst(p, 3, iCur);
}
/*
** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
*/
static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
ExprList *pGroupBy = pWalker->u.pGroupBy;
int i;
/* Check if pExpr is identical to any GROUP BY term. If so, consider
** it constant. */
for(i=0; i<pGroupBy->nExpr; i++){
Expr *p = pGroupBy->a[i].pExpr;
if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
if( sqlite3IsBinary(pColl) ){
return WRC_Prune;
}
}
}
/* Check if pExpr is a sub-select. If so, consider it variable. */
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
pWalker->eCode = 0;
return WRC_Abort;
}
return exprNodeIsConstant(pWalker, pExpr);
}
/*
** Walk the expression tree passed as the first argument. Return non-zero
** if the expression consists entirely of constants or copies of terms
** in pGroupBy that sort with the BINARY collation sequence.
**
** This routine is used to determine if a term of the HAVING clause can
** be promoted into the WHERE clause. In order for such a promotion to work,
** the value of the HAVING clause term must be the same for all members of
** a "group". The requirement that the GROUP BY term must be BINARY
** assumes that no other collating sequence will have a finer-grained
** grouping than binary. In other words (A=B COLLATE binary) implies
** A=B in every other collating sequence. The requirement that the
** GROUP BY be BINARY is stricter than necessary. It would also work
** to promote HAVING clauses that use the same alternative collating
** sequence as the GROUP BY term, but that is much harder to check,
** alternative collating sequences are uncommon, and this is only an
** optimization, so we take the easy way out and simply require the
** GROUP BY to use the BINARY collating sequence.
*/
int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
Walker w;
w.eCode = 1;
w.xExprCallback = exprNodeIsConstantOrGroupBy;
w.xSelectCallback = 0;
w.u.pGroupBy = pGroupBy;
w.pParse = pParse;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** or a function call with constant arguments. Return and 0 if there
** are any variables.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
assert( isInit==0 || isInit==1 );
return exprIsConst(p, 4+isInit, 0);
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
/*
** Walk an expression tree. Return 1 if the expression contains a
** subquery of some kind. Return 0 if there are no subqueries.
*/
int sqlite3ExprContainsSubquery(Expr *p){
Walker w;
w.eCode = 1;
w.xExprCallback = sqlite3ExprWalkNoop;
w.xSelectCallback = sqlite3SelectWalkFail;
#ifdef SQLITE_DEBUG
w.xSelectCallback2 = sqlite3SelectWalkAssert2;
#endif
sqlite3WalkExpr(&w, p);
return w.eCode==0;
}
#endif
/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue. If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
*/
int sqlite3ExprIsInteger(Expr *p, int *pValue){
int rc = 0;
if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
/* If an expression is an integer literal that fits in a signed 32-bit
** integer, then the EP_IntValue flag will have already been set */
assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
|| sqlite3GetInt32(p->u.zToken, &rc)==0 );
if( p->flags & EP_IntValue ){
*pValue = p->u.iValue;
return 1;
}
switch( p->op ){
case TK_UPLUS: {
rc = sqlite3ExprIsInteger(p->pLeft, pValue);
break;
}
case TK_UMINUS: {
int v;
if( sqlite3ExprIsInteger(p->pLeft, &v) ){
assert( v!=(-2147483647-1) );
*pValue = -v;
rc = 1;
}
break;
}
default: break;
}
return rc;
}
/*
** Return FALSE if there is no chance that the expression can be NULL.
**
** If the expression might be NULL or if the expression is too complex
** to tell return TRUE.
**
** This routine is used as an optimization, to skip OP_IsNull opcodes
** when we know that a value cannot be NULL. Hence, a false positive
** (returning TRUE when in fact the expression can never be NULL) might
** be a small performance hit but is otherwise harmless. On the other
** hand, a false negative (returning FALSE when the result could be NULL)
** will likely result in an incorrect answer. So when in doubt, return
** TRUE.
*/
int sqlite3ExprCanBeNull(const Expr *p){
u8 op;
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
p = p->pLeft;
}
op = p->op;
if( op==TK_REGISTER ) op = p->op2;
switch( op ){
case TK_INTEGER:
case TK_STRING:
case TK_FLOAT:
case TK_BLOB:
return 0;
case TK_COLUMN:
return ExprHasProperty(p, EP_CanBeNull) ||
p->y.pTab==0 || /* Reference to column of index on expression */
(p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
default:
return 1;
}
}
/*
** Return TRUE if the given expression is a constant which would be
** unchanged by OP_Affinity with the affinity given in the second
** argument.
**
** This routine is used to determine if the OP_Affinity operation
** can be omitted. When in doubt return FALSE. A false negative
** is harmless. A false positive, however, can result in the wrong
** answer.
*/
int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
u8 op;
int unaryMinus = 0;
if( aff==SQLITE_AFF_BLOB ) return 1;
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
if( p->op==TK_UMINUS ) unaryMinus = 1;
p = p->pLeft;
}
op = p->op;
if( op==TK_REGISTER ) op = p->op2;
switch( op ){
case TK_INTEGER: {
return aff>=SQLITE_AFF_NUMERIC;
}
case TK_FLOAT: {
return aff>=SQLITE_AFF_NUMERIC;
}
case TK_STRING: {
return !unaryMinus && aff==SQLITE_AFF_TEXT;
}
case TK_BLOB: {
return !unaryMinus;
}
case TK_COLUMN: {
assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
}
default: {
return 0;
}
}
}
/*
** Return TRUE if the given string is a row-id column name.
*/
int sqlite3IsRowid(const char *z){
if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
if( sqlite3StrICmp(z, "OID")==0 ) return 1;
return 0;
}
/*
** pX is the RHS of an IN operator. If pX is a SELECT statement
** that can be simplified to a direct table access, then return
** a pointer to the SELECT statement. If pX is not a SELECT statement,
** or if the SELECT statement needs to be manifested into a transient
** table, then return NULL.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static Select *isCandidateForInOpt(Expr *pX){
Select *p;
SrcList *pSrc;
ExprList *pEList;
Table *pTab;
int i;
if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
p = pX->x.pSelect;
if( p->pPrior ) return 0; /* Not a compound SELECT */
if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
return 0; /* No DISTINCT keyword and no aggregate functions */
}
assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
if( p->pLimit ) return 0; /* Has no LIMIT clause */
if( p->pWhere ) return 0; /* Has no WHERE clause */
pSrc = p->pSrc;
assert( pSrc!=0 );
if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
pTab = pSrc->a[0].pTab;
assert( pTab!=0 );
assert( pTab->pSelect==0 ); /* FROM clause is not a view */
if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
pEList = p->pEList;
assert( pEList!=0 );
/* All SELECT results must be columns. */
for(i=0; i<pEList->nExpr; i++){
Expr *pRes = pEList->a[i].pExpr;
if( pRes->op!=TK_COLUMN ) return 0;
assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
}
return p;
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code that checks the left-most column of index table iCur to see if
** it contains any NULL entries. Cause the register at regHasNull to be set
** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
** to be set to NULL if iCur contains one or more NULL values.
*/
static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
int addr1;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
VdbeComment((v, "first_entry_in(%d)", iCur));
sqlite3VdbeJumpHere(v, addr1);
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** The argument is an IN operator with a list (not a subquery) on the
** right-hand side. Return TRUE if that list is constant.
*/
static int sqlite3InRhsIsConstant(Expr *pIn){
Expr *pLHS;
int res;
assert( !ExprHasProperty(pIn, EP_xIsSelect) );
pLHS = pIn->pLeft;
pIn->pLeft = 0;
res = sqlite3ExprIsConstant(pIn);
pIn->pLeft = pLHS;
return res;
}
#endif
/*
** This function is used by the implementation of the IN (...) operator.
** The pX parameter is the expression on the RHS of the IN operator, which
** might be either a list of expressions or a subquery.
**
** The job of this routine is to find or create a b-tree object that can
** be used either to test for membership in the RHS set or to iterate through
** all members of the RHS set, skipping duplicates.
**
** A cursor is opened on the b-tree object that is the RHS of the IN operator
** and pX->iTable is set to the index of that cursor.
**
** The returned value of this function indicates the b-tree type, as follows:
**
** IN_INDEX_ROWID - The cursor was opened on a database table.
** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
** IN_INDEX_EPH - The cursor was opened on a specially created and
** populated epheremal table.
** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
** implemented as a sequence of comparisons.
**
** An existing b-tree might be used if the RHS expression pX is a simple
** subquery such as:
**
** SELECT <column1>, <column2>... FROM <table>
**
** If the RHS of the IN operator is a list or a more complex subquery, then
** an ephemeral table might need to be generated from the RHS and then
** pX->iTable made to point to the ephemeral table instead of an
** existing table.
**
** The inFlags parameter must contain, at a minimum, one of the bits
** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
** be used to loop over all values of the RHS of the IN operator.
**
** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
** through the set members) then the b-tree must not contain duplicates.
** An epheremal table will be created unless the selected columns are guaranteed
** to be unique - either because it is an INTEGER PRIMARY KEY or due to
** a UNIQUE constraint or index.
**
** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
** for fast set membership tests) then an epheremal table must
** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
** index can be found with the specified <columns> as its left-most.
**
** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
** if the RHS of the IN operator is a list (not a subquery) then this
** routine might decide that creating an ephemeral b-tree for membership
** testing is too expensive and return IN_INDEX_NOOP. In that case, the
** calling routine should implement the IN operator using a sequence
** of Eq or Ne comparison operations.
**
** When the b-tree is being used for membership tests, the calling function
** might need to know whether or not the RHS side of the IN operator
** contains a NULL. If prRhsHasNull is not a NULL pointer and
** if there is any chance that the (...) might contain a NULL value at
** runtime, then a register is allocated and the register number written
** to *prRhsHasNull. If there is no chance that the (...) contains a
** NULL value, then *prRhsHasNull is left unchanged.
**
** If a register is allocated and its location stored in *prRhsHasNull, then
** the value in that register will be NULL if the b-tree contains one or more
** NULL values, and it will be some non-NULL value if the b-tree contains no
** NULL values.
**
** If the aiMap parameter is not NULL, it must point to an array containing
** one element for each column returned by the SELECT statement on the RHS
** of the IN(...) operator. The i'th entry of the array is populated with the
** offset of the index column that matches the i'th column returned by the
** SELECT. For example, if the expression and selected index are:
**
** (?,?,?) IN (SELECT a, b, c FROM t1)
** CREATE INDEX i1 ON t1(b, c, a);
**
** then aiMap[] is populated with {2, 0, 1}.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3FindInIndex(
Parse *pParse, /* Parsing context */
Expr *pX, /* The IN expression */
u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
int *prRhsHasNull, /* Register holding NULL status. See notes */
int *aiMap, /* Mapping from Index fields to RHS fields */
int *piTab /* OUT: index to use */
){
Select *p; /* SELECT to the right of IN operator */
int eType = 0; /* Type of RHS table. IN_INDEX_* */
int iTab = pParse->nTab++; /* Cursor of the RHS table */
int mustBeUnique; /* True if RHS must be unique */
Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
assert( pX->op==TK_IN );
mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
/* If the RHS of this IN(...) operator is a SELECT, and if it matters
** whether or not the SELECT result contains NULL values, check whether
** or not NULL is actually possible (it may not be, for example, due
** to NOT NULL constraints in the schema). If no NULL values are possible,
** set prRhsHasNull to 0 before continuing. */
if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
int i;
ExprList *pEList = pX->x.pSelect->pEList;
for(i=0; i<pEList->nExpr; i++){
if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
}
if( i==pEList->nExpr ){
prRhsHasNull = 0;
}
}
/* Check to see if an existing table or index can be used to
** satisfy the query. This is preferable to generating a new
** ephemeral table. */
if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
sqlite3 *db = pParse->db; /* Database connection */
Table *pTab; /* Table <table>. */
i16 iDb; /* Database idx for pTab */
ExprList *pEList = p->pEList;
int nExpr = pEList->nExpr;
assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
pTab = p->pSrc->a[0].pTab;
/* Code an OP_Transaction and OP_TableLock for <table>. */
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
sqlite3CodeVerifySchema(pParse, iDb);
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
assert(v); /* sqlite3GetVdbe() has always been previously called */
if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
/* The "x IN (SELECT rowid FROM table)" case */
int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
VdbeCoverage(v);
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
eType = IN_INDEX_ROWID;
ExplainQueryPlan((pParse, 0,
"USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
sqlite3VdbeJumpHere(v, iAddr);
}else{
Index *pIdx; /* Iterator variable */
int affinity_ok = 1;
int i;
/* Check that the affinity that will be used to perform each
** comparison is the same as the affinity of each column in table
** on the RHS of the IN operator. If it not, it is not possible to
** use any index of the RHS table. */
for(i=0; i<nExpr && affinity_ok; i++){
Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
int iCol = pEList->a[i].pExpr->iColumn;
char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
testcase( cmpaff==SQLITE_AFF_BLOB );
testcase( cmpaff==SQLITE_AFF_TEXT );
switch( cmpaff ){
case SQLITE_AFF_BLOB:
break;
case SQLITE_AFF_TEXT:
/* sqlite3CompareAffinity() only returns TEXT if one side or the
** other has no affinity and the other side is TEXT. Hence,
** the only way for cmpaff to be TEXT is for idxaff to be TEXT
** and for the term on the LHS of the IN to have no affinity. */
assert( idxaff==SQLITE_AFF_TEXT );
break;
default:
affinity_ok = sqlite3IsNumericAffinity(idxaff);
}
}
if( affinity_ok ){
/* Search for an existing index that will work for this IN operator */
for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
Bitmask colUsed; /* Columns of the index used */
Bitmask mCol; /* Mask for the current column */
if( pIdx->nColumn<nExpr ) continue;
if( pIdx->pPartIdxWhere!=0 ) continue;
/* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
** BITMASK(nExpr) without overflowing */
testcase( pIdx->nColumn==BMS-2 );
testcase( pIdx->nColumn==BMS-1 );
if( pIdx->nColumn>=BMS-1 ) continue;
if( mustBeUnique ){
if( pIdx->nKeyCol>nExpr
||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
){
continue; /* This index is not unique over the IN RHS columns */
}
}
colUsed = 0; /* Columns of index used so far */
for(i=0; i<nExpr; i++){
Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
Expr *pRhs = pEList->a[i].pExpr;
CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
int j;
assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
for(j=0; j<nExpr; j++){
if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
assert( pIdx->azColl[j] );
if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
continue;
}
break;
}
if( j==nExpr ) break;
mCol = MASKBIT(j);
if( mCol & colUsed ) break; /* Each column used only once */
colUsed |= mCol;
if( aiMap ) aiMap[i] = j;
}
assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
if( colUsed==(MASKBIT(nExpr)-1) ){
/* If we reach this point, that means the index pIdx is usable */
int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
ExplainQueryPlan((pParse, 0,
"USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
VdbeComment((v, "%s", pIdx->zName));
assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
if( prRhsHasNull ){
#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
i64 mask = (1<<nExpr)-1;
sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
iTab, 0, 0, (u8*)&mask, P4_INT64);
#endif
*prRhsHasNull = ++pParse->nMem;
if( nExpr==1 ){
sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
}
}
sqlite3VdbeJumpHere(v, iAddr);
}
} /* End loop over indexes */
} /* End if( affinity_ok ) */
} /* End if not an rowid index */
} /* End attempt to optimize using an index */
/* If no preexisting index is available for the IN clause
** and IN_INDEX_NOOP is an allowed reply
** and the RHS of the IN operator is a list, not a subquery
** and the RHS is not constant or has two or fewer terms,
** then it is not worth creating an ephemeral table to evaluate
** the IN operator so return IN_INDEX_NOOP.
*/
if( eType==0
&& (inFlags & IN_INDEX_NOOP_OK)
&& !ExprHasProperty(pX, EP_xIsSelect)
&& (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
){
eType = IN_INDEX_NOOP;
}
if( eType==0 ){
/* Could not find an existing table or index to use as the RHS b-tree.
** We will have to generate an ephemeral table to do the job.
*/
u32 savedNQueryLoop = pParse->nQueryLoop;
int rMayHaveNull = 0;
eType = IN_INDEX_EPH;
if( inFlags & IN_INDEX_LOOP ){
pParse->nQueryLoop = 0;
}else if( prRhsHasNull ){
*prRhsHasNull = rMayHaveNull = ++pParse->nMem;
}
assert( pX->op==TK_IN );
sqlite3CodeRhsOfIN(pParse, pX, iTab);
if( rMayHaveNull ){
sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
}
pParse->nQueryLoop = savedNQueryLoop;
}
if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
int i, n;
n = sqlite3ExprVectorSize(pX->pLeft);
for(i=0; i<n; i++) aiMap[i] = i;
}
*piTab = iTab;
return eType;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Argument pExpr is an (?, ?...) IN(...) expression. This
** function allocates and returns a nul-terminated string containing
** the affinities to be used for each column of the comparison.
**
** It is the responsibility of the caller to ensure that the returned
** string is eventually freed using sqlite3DbFree().
*/
static char *exprINAffinity(Parse *pParse, Expr *pExpr){
Expr *pLeft = pExpr->pLeft;
int nVal = sqlite3ExprVectorSize(pLeft);
Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
char *zRet;
assert( pExpr->op==TK_IN );
zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
if( zRet ){
int i;
for(i=0; i<nVal; i++){
Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
char a = sqlite3ExprAffinity(pA);
if( pSelect ){
zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
}else{
zRet[i] = a;
}
}
zRet[nVal] = '\0';
}
return zRet;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Load the Parse object passed as the first argument with an error
** message of the form:
**
** "sub-select returns N columns - expected M"
*/
void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
const char *zFmt = "sub-select returns %d columns - expected %d";
sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
}
#endif
/*
** Expression pExpr is a vector that has been used in a context where
** it is not permitted. If pExpr is a sub-select vector, this routine
** loads the Parse object with a message of the form:
**
** "sub-select returns N columns - expected 1"
**
** Or, if it is a regular scalar vector:
**
** "row value misused"
*/
void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
#ifndef SQLITE_OMIT_SUBQUERY
if( pExpr->flags & EP_xIsSelect ){
sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
}else
#endif
{
sqlite3ErrorMsg(pParse, "row value misused");
}
}
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code that will construct an ephemeral table containing all terms
** in the RHS of an IN operator. The IN operator can be in either of two
** forms:
**
** x IN (4,5,11) -- IN operator with list on right-hand side
** x IN (SELECT a FROM b) -- IN operator with subquery on the right
**
** The pExpr parameter is the IN operator. The cursor number for the
** constructed ephermeral table is returned. The first time the ephemeral
** table is computed, the cursor number is also stored in pExpr->iTable,
** however the cursor number returned might not be the same, as it might
** have been duplicated using OP_OpenDup.
**
** If the LHS expression ("x" in the examples) is a column value, or
** the SELECT statement returns a column value, then the affinity of that
** column is used to build the index keys. If both 'x' and the
** SELECT... statement are columns, then numeric affinity is used
** if either column has NUMERIC or INTEGER affinity. If neither
** 'x' nor the SELECT... statement are columns, then numeric affinity
** is used.
*/
void sqlite3CodeRhsOfIN(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The IN operator */
int iTab /* Use this cursor number */
){
int addrOnce = 0; /* Address of the OP_Once instruction at top */
int addr; /* Address of OP_OpenEphemeral instruction */
Expr *pLeft; /* the LHS of the IN operator */
KeyInfo *pKeyInfo = 0; /* Key information */
int nVal; /* Size of vector pLeft */
Vdbe *v; /* The prepared statement under construction */
v = pParse->pVdbe;
assert( v!=0 );
/* The evaluation of the IN must be repeated every time it
** is encountered if any of the following is true:
**
** * The right-hand side is a correlated subquery
** * The right-hand side is an expression list containing variables
** * We are inside a trigger
**
** If all of the above are false, then we can compute the RHS just once
** and reuse it many names.
*/
if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
/* Reuse of the RHS is allowed */
/* If this routine has already been coded, but the previous code
** might not have been invoked yet, so invoke it now as a subroutine.
*/
if( ExprHasProperty(pExpr, EP_Subrtn) ){
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
pExpr->x.pSelect->selId));
}
sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
pExpr->y.sub.iAddr);
sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
sqlite3VdbeJumpHere(v, addrOnce);
return;
}
/* Begin coding the subroutine */
ExprSetProperty(pExpr, EP_Subrtn);
pExpr->y.sub.regReturn = ++pParse->nMem;
pExpr->y.sub.iAddr =
sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
VdbeComment((v, "return address"));
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
/* Check to see if this is a vector IN operator */
pLeft = pExpr->pLeft;
nVal = sqlite3ExprVectorSize(pLeft);
/* Construct the ephemeral table that will contain the content of
** RHS of the IN operator.
*/
pExpr->iTable = iTab;
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
}else{
VdbeComment((v, "RHS of IN operator"));
}
#endif
pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
/* Case 1: expr IN (SELECT ...)
**
** Generate code to write the results of the select into the temporary
** table allocated and opened above.
*/
Select *pSelect = pExpr->x.pSelect;
ExprList *pEList = pSelect->pEList;
ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
addrOnce?"":"CORRELATED ", pSelect->selId
));
/* If the LHS and RHS of the IN operator do not match, that
** error will have been caught long before we reach this point. */
if( ALWAYS(pEList->nExpr==nVal) ){
SelectDest dest;
int i;
sqlite3SelectDestInit(&dest, SRT_Set, iTab);
dest.zAffSdst = exprINAffinity(pParse, pExpr);
pSelect->iLimit = 0;
testcase( pSelect->selFlags & SF_Distinct );
testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
if( sqlite3Select(pParse, pSelect, &dest) ){
sqlite3DbFree(pParse->db, dest.zAffSdst);
sqlite3KeyInfoUnref(pKeyInfo);
return;
}
sqlite3DbFree(pParse->db, dest.zAffSdst);
assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
assert( pEList!=0 );
assert( pEList->nExpr>0 );
assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
for(i=0; i<nVal; i++){
Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
pParse, p, pEList->a[i].pExpr
);
}
}
}else if( ALWAYS(pExpr->x.pList!=0) ){
/* Case 2: expr IN (exprlist)
**
** For each expression, build an index key from the evaluation and
** store it in the temporary table. If <expr> is a column, then use
** that columns affinity when building index keys. If <expr> is not
** a column, use numeric affinity.
*/
char affinity; /* Affinity of the LHS of the IN */
int i;
ExprList *pList = pExpr->x.pList;
struct ExprList_item *pItem;
int r1, r2;
affinity = sqlite3ExprAffinity(pLeft);
if( affinity<=SQLITE_AFF_NONE ){
affinity = SQLITE_AFF_BLOB;
}
if( pKeyInfo ){
assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
}
/* Loop through each expression in <exprlist>. */
r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3GetTempReg(pParse);
for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
Expr *pE2 = pItem->pExpr;
/* If the expression is not constant then we will need to
** disable the test that was generated above that makes sure
** this code only executes once. Because for a non-constant
** expression we need to rerun this code each time.
*/
if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
sqlite3VdbeChangeToNoop(v, addrOnce);
ExprClearProperty(pExpr, EP_Subrtn);
addrOnce = 0;
}
/* Evaluate the expression and insert it into the temp table */
sqlite3ExprCode(pParse, pE2, r1);
sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
}
sqlite3ReleaseTempReg(pParse, r1);
sqlite3ReleaseTempReg(pParse, r2);
}
if( pKeyInfo ){
sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
}
if( addrOnce ){
sqlite3VdbeJumpHere(v, addrOnce);
/* Subroutine return */
sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
sqlite3ClearTempRegCache(pParse);
}
}
#endif /* SQLITE_OMIT_SUBQUERY */
/*
** Generate code for scalar subqueries used as a subquery expression
** or EXISTS operator:
**
** (SELECT a FROM b) -- subquery
** EXISTS (SELECT a FROM b) -- EXISTS subquery
**
** The pExpr parameter is the SELECT or EXISTS operator to be coded.
**
** Return the register that holds the result. For a multi-column SELECT,
** the result is stored in a contiguous array of registers and the
** return value is the register of the left-most result column.
** Return 0 if an error occurs.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
int addrOnce = 0; /* Address of OP_Once at top of subroutine */
int rReg = 0; /* Register storing resulting */
Select *pSel; /* SELECT statement to encode */
SelectDest dest; /* How to deal with SELECT result */
int nReg; /* Registers to allocate */
Expr *pLimit; /* New limit expression */
Vdbe *v = pParse->pVdbe;
assert( v!=0 );
testcase( pExpr->op==TK_EXISTS );
testcase( pExpr->op==TK_SELECT );
assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
pSel = pExpr->x.pSelect;
/* The evaluation of the EXISTS/SELECT must be repeated every time it
** is encountered if any of the following is true:
**
** * The right-hand side is a correlated subquery
** * The right-hand side is an expression list containing variables
** * We are inside a trigger
**
** If all of the above are false, then we can run this code just once
** save the results, and reuse the same result on subsequent invocations.
*/
if( !ExprHasProperty(pExpr, EP_VarSelect) ){
/* If this routine has already been coded, then invoke it as a
** subroutine. */
if( ExprHasProperty(pExpr, EP_Subrtn) ){
ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
pExpr->y.sub.iAddr);
return pExpr->iTable;
}
/* Begin coding the subroutine */
ExprSetProperty(pExpr, EP_Subrtn);
pExpr->y.sub.regReturn = ++pParse->nMem;
pExpr->y.sub.iAddr =
sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
VdbeComment((v, "return address"));
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
/* For a SELECT, generate code to put the values for all columns of
** the first row into an array of registers and return the index of
** the first register.
**
** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
** into a register and return that register number.
**
** In both cases, the query is augmented with "LIMIT 1". Any
** preexisting limit is discarded in place of the new LIMIT 1.
*/
ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
addrOnce?"":"CORRELATED ", pSel->selId));
nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
pParse->nMem += nReg;
if( pExpr->op==TK_SELECT ){
dest.eDest = SRT_Mem;
dest.iSdst = dest.iSDParm;
dest.nSdst = nReg;
sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
VdbeComment((v, "Init subquery result"));
}else{
dest.eDest = SRT_Exists;
sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
VdbeComment((v, "Init EXISTS result"));
}
if( pSel->pLimit ){
/* The subquery already has a limit. If the pre-existing limit is X
** then make the new limit X<>0 so that the new limit is either 1 or 0 */
sqlite3 *db = pParse->db;
pLimit = sqlite3Expr(db, TK_INTEGER, "0");
if( pLimit ){
pLimit->affExpr = SQLITE_AFF_NUMERIC;
pLimit = sqlite3PExpr(pParse, TK_NE,
sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
}
sqlite3ExprDelete(db, pSel->pLimit->pLeft);
pSel->pLimit->pLeft = pLimit;
}else{
/* If there is no pre-existing limit add a limit of 1 */
pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
}
pSel->iLimit = 0;
if( sqlite3Select(pParse, pSel, &dest) ){
return 0;
}
pExpr->iTable = rReg = dest.iSDParm;
ExprSetVVAProperty(pExpr, EP_NoReduce);
if( addrOnce ){
sqlite3VdbeJumpHere(v, addrOnce);
/* Subroutine return */
sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
sqlite3ClearTempRegCache(pParse);
}
return rReg;
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Expr pIn is an IN(...) expression. This function checks that the
** sub-select on the RHS of the IN() operator has the same number of
** columns as the vector on the LHS. Or, if the RHS of the IN() is not
** a sub-query, that the LHS is a vector of size 1.
*/
int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
int nVector = sqlite3ExprVectorSize(pIn->pLeft);
if( (pIn->flags & EP_xIsSelect) ){
if( nVector!=pIn->x.pSelect->pEList->nExpr ){
sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
return 1;
}
}else if( nVector!=1 ){
sqlite3VectorErrorMsg(pParse, pIn->pLeft);
return 1;
}
return 0;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code for an IN expression.
**
** x IN (SELECT ...)
** x IN (value, value, ...)
**
** The left-hand side (LHS) is a scalar or vector expression. The
** right-hand side (RHS) is an array of zero or more scalar values, or a
** subquery. If the RHS is a subquery, the number of result columns must
** match the number of columns in the vector on the LHS. If the RHS is
** a list of values, the LHS must be a scalar.
**
** The IN operator is true if the LHS value is contained within the RHS.
** The result is false if the LHS is definitely not in the RHS. The
** result is NULL if the presence of the LHS in the RHS cannot be
** determined due to NULLs.
**
** This routine generates code that jumps to destIfFalse if the LHS is not
** contained within the RHS. If due to NULLs we cannot determine if the LHS
** is contained in the RHS then jump to destIfNull. If the LHS is contained
** within the RHS then fall through.
**
** See the separate in-operator.md documentation file in the canonical
** SQLite source tree for additional information.
*/
static void sqlite3ExprCodeIN(
Parse *pParse, /* Parsing and code generating context */
Expr *pExpr, /* The IN expression */
int destIfFalse, /* Jump here if LHS is not contained in the RHS */
int destIfNull /* Jump here if the results are unknown due to NULLs */
){
int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
int eType; /* Type of the RHS */
int rLhs; /* Register(s) holding the LHS values */
int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
Vdbe *v; /* Statement under construction */
int *aiMap = 0; /* Map from vector field to index column */
char *zAff = 0; /* Affinity string for comparisons */
int nVector; /* Size of vectors for this IN operator */
int iDummy; /* Dummy parameter to exprCodeVector() */
Expr *pLeft; /* The LHS of the IN operator */
int i; /* loop counter */
int destStep2; /* Where to jump when NULLs seen in step 2 */
int destStep6 = 0; /* Start of code for Step 6 */
int addrTruthOp; /* Address of opcode that determines the IN is true */
int destNotNull; /* Jump here if a comparison is not true in step 6 */
int addrTop; /* Top of the step-6 loop */
int iTab = 0; /* Index to use */
pLeft = pExpr->pLeft;
if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
zAff = exprINAffinity(pParse, pExpr);
nVector = sqlite3ExprVectorSize(pExpr->pLeft);
aiMap = (int*)sqlite3DbMallocZero(
pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
);
if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
/* Attempt to compute the RHS. After this step, if anything other than
** IN_INDEX_NOOP is returned, the table opened with cursor iTab
** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
** the RHS has not yet been coded. */
v = pParse->pVdbe;
assert( v!=0 ); /* OOM detected prior to this routine */
VdbeNoopComment((v, "begin IN expr"));
eType = sqlite3FindInIndex(pParse, pExpr,
IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
destIfFalse==destIfNull ? 0 : &rRhsHasNull,
aiMap, &iTab);
assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
|| eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
);
#ifdef SQLITE_DEBUG
/* Confirm that aiMap[] contains nVector integer values between 0 and
** nVector-1. */
for(i=0; i<nVector; i++){
int j, cnt;
for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
assert( cnt==1 );
}
#endif
/* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
** vector, then it is stored in an array of nVector registers starting
** at r1.
**
** sqlite3FindInIndex() might have reordered the fields of the LHS vector
** so that the fields are in the same order as an existing index. The
** aiMap[] array contains a mapping from the original LHS field order to
** the field order that matches the RHS index.
*/
rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
if( i==nVector ){
/* LHS fields are not reordered */
rLhs = rLhsOrig;
}else{
/* Need to reorder the LHS fields according to aiMap */
rLhs = sqlite3GetTempRange(pParse, nVector);
for(i=0; i<nVector; i++){
sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
}
}
/* If sqlite3FindInIndex() did not find or create an index that is
** suitable for evaluating the IN operator, then evaluate using a
** sequence of comparisons.
**
** This is step (1) in the in-operator.md optimized algorithm.
*/
if( eType==IN_INDEX_NOOP ){
ExprList *pList = pExpr->x.pList;
CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
int labelOk = sqlite3VdbeMakeLabel(pParse);
int r2, regToFree;
int regCkNull = 0;
int ii;
int bLhsReal; /* True if the LHS of the IN has REAL affinity */
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
if( destIfNull!=destIfFalse ){
regCkNull = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
}
bLhsReal = sqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL;
for(ii=0; ii<pList->nExpr; ii++){
if( bLhsReal ){
r2 = regToFree = sqlite3GetTempReg(pParse);
sqlite3ExprCode(pParse, pList->a[ii].pExpr, r2);
sqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC);
}else{
r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree);
}
if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
}
if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
(void*)pColl, P4_COLLSEQ);
VdbeCoverageIf(v, ii<pList->nExpr-1);
VdbeCoverageIf(v, ii==pList->nExpr-1);
sqlite3VdbeChangeP5(v, zAff[0]);
}else{
assert( destIfNull==destIfFalse );
sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
(void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
}
sqlite3ReleaseTempReg(pParse, regToFree);
}
if( regCkNull ){
sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
sqlite3VdbeGoto(v, destIfFalse);
}
sqlite3VdbeResolveLabel(v, labelOk);
sqlite3ReleaseTempReg(pParse, regCkNull);
goto sqlite3ExprCodeIN_finished;
}
/* Step 2: Check to see if the LHS contains any NULL columns. If the
** LHS does contain NULLs then the result must be either FALSE or NULL.
** We will then skip the binary search of the RHS.
*/
if( destIfNull==destIfFalse ){
destStep2 = destIfFalse;
}else{
destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
}
for(i=0; i<nVector; i++){
Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
if( sqlite3ExprCanBeNull(p) ){
sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
VdbeCoverage(v);
}
}
/* Step 3. The LHS is now known to be non-NULL. Do the binary search
** of the RHS using the LHS as a probe. If found, the result is
** true.
*/
if( eType==IN_INDEX_ROWID ){
/* In this case, the RHS is the ROWID of table b-tree and so we also
** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
** into a single opcode. */
sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
VdbeCoverage(v);
addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
}else{
sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
if( destIfFalse==destIfNull ){
/* Combine Step 3 and Step 5 into a single opcode */
sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
rLhs, nVector); VdbeCoverage(v);
goto sqlite3ExprCodeIN_finished;
}
/* Ordinary Step 3, for the case where FALSE and NULL are distinct */
addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
rLhs, nVector); VdbeCoverage(v);
}
/* Step 4. If the RHS is known to be non-NULL and we did not find
** an match on the search above, then the result must be FALSE.
*/
if( rRhsHasNull && nVector==1 ){
sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
VdbeCoverage(v);
}
/* Step 5. If we do not care about the difference between NULL and
** FALSE, then just return false.
*/
if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
/* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
** If any comparison is NULL, then the result is NULL. If all
** comparisons are FALSE then the final result is FALSE.
**
** For a scalar LHS, it is sufficient to check just the first row
** of the RHS.
*/
if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
VdbeCoverage(v);
if( nVector>1 ){
destNotNull = sqlite3VdbeMakeLabel(pParse);
}else{
/* For nVector==1, combine steps 6 and 7 by immediately returning
** FALSE if the first comparison is not NULL */
destNotNull = destIfFalse;
}
for(i=0; i<nVector; i++){
Expr *p;
CollSeq *pColl;
int r3 = sqlite3GetTempReg(pParse);
p = sqlite3VectorFieldSubexpr(pLeft, i);
pColl = sqlite3ExprCollSeq(pParse, p);
sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
(void*)pColl, P4_COLLSEQ);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r3);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
if( nVector>1 ){
sqlite3VdbeResolveLabel(v, destNotNull);
sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
VdbeCoverage(v);
/* Step 7: If we reach this point, we know that the result must
** be false. */
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
}
/* Jumps here in order to return true. */
sqlite3VdbeJumpHere(v, addrTruthOp);
sqlite3ExprCodeIN_finished:
if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
VdbeComment((v, "end IN expr"));
sqlite3ExprCodeIN_oom_error:
sqlite3DbFree(pParse->db, aiMap);
sqlite3DbFree(pParse->db, zAff);
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_FLOATING_POINT
/*
** Generate an instruction that will put the floating point
** value described by z[0..n-1] into register iMem.
**
** The z[] string will probably not be zero-terminated. But the
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
if( ALWAYS(z!=0) ){
double value;
sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
if( negateFlag ) value = -value;
sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
}
}
#endif
/*
** Generate an instruction that will put the integer describe by
** text z[0..n-1] into register iMem.
**
** Expr.u.zToken is always UTF8 and zero-terminated.
*/
static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
Vdbe *v = pParse->pVdbe;
if( pExpr->flags & EP_IntValue ){
int i = pExpr->u.iValue;
assert( i>=0 );
if( negFlag ) i = -i;
sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
}else{
int c;
i64 value;
const char *z = pExpr->u.zToken;
assert( z!=0 );
c = sqlite3DecOrHexToI64(z, &value);
if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
#ifdef SQLITE_OMIT_FLOATING_POINT
sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
#else
#ifndef SQLITE_OMIT_HEX_INTEGER
if( sqlite3_strnicmp(z,"0x",2)==0 ){
sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
}else
#endif
{
codeReal(v, z, negFlag, iMem);
}
#endif
}else{
if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
}
}
}
/* Generate code that will load into register regOut a value that is
** appropriate for the iIdxCol-th column of index pIdx.
*/
void sqlite3ExprCodeLoadIndexColumn(
Parse *pParse, /* The parsing context */
Index *pIdx, /* The index whose column is to be loaded */
int iTabCur, /* Cursor pointing to a table row */
int iIdxCol, /* The column of the index to be loaded */
int regOut /* Store the index column value in this register */
){
i16 iTabCol = pIdx->aiColumn[iIdxCol];
if( iTabCol==XN_EXPR ){
assert( pIdx->aColExpr );
assert( pIdx->aColExpr->nExpr>iIdxCol );
pParse->iSelfTab = iTabCur + 1;
sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
pParse->iSelfTab = 0;
}else{
sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
iTabCol, regOut);
}
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/*
** Generate code that will compute the value of generated column pCol
** and store the result in register regOut
*/
void sqlite3ExprCodeGeneratedColumn(
Parse *pParse,
Column *pCol,
int regOut
){
int iAddr;
Vdbe *v = pParse->pVdbe;
assert( v!=0 );
assert( pParse->iSelfTab!=0 );
if( pParse->iSelfTab>0 ){
iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
}else{
iAddr = 0;
}
sqlite3ExprCode(pParse, pCol->pDflt, regOut);
if( pCol->affinity>=SQLITE_AFF_TEXT ){
sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
}
if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
}
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
/*
** Generate code to extract the value of the iCol-th column of a table.
*/
void sqlite3ExprCodeGetColumnOfTable(
Vdbe *v, /* Parsing context */
Table *pTab, /* The table containing the value */
int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
int iCol, /* Index of the column to extract */
int regOut /* Extract the value into this register */
){
Column *pCol;
assert( v!=0 );
if( pTab==0 ){
sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
return;
}
if( iCol<0 || iCol==pTab->iPKey ){
sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
}else{
int op;
int x;
if( IsVirtual(pTab) ){
op = OP_VColumn;
x = iCol;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
}else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
Parse *pParse = sqlite3VdbeParser(v);
if( pCol->colFlags & COLFLAG_BUSY ){
sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
}else{
int savedSelfTab = pParse->iSelfTab;
pCol->colFlags |= COLFLAG_BUSY;
pParse->iSelfTab = iTabCur+1;
sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
pParse->iSelfTab = savedSelfTab;
pCol->colFlags &= ~COLFLAG_BUSY;
}
return;
#endif
}else if( !HasRowid(pTab) ){
testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
op = OP_Column;
}else{
x = sqlite3TableColumnToStorage(pTab,iCol);
testcase( x!=iCol );
op = OP_Column;
}
sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
sqlite3ColumnDefault(v, pTab, iCol, regOut);
}
}
/*
** Generate code that will extract the iColumn-th column from
** table pTab and store the column value in register iReg.
**
** There must be an open cursor to pTab in iTable when this routine
** is called. If iColumn<0 then code is generated that extracts the rowid.
*/
int sqlite3ExprCodeGetColumn(
Parse *pParse, /* Parsing and code generating context */
Table *pTab, /* Description of the table we are reading from */
int iColumn, /* Index of the table column */
int iTable, /* The cursor pointing to the table */
int iReg, /* Store results here */
u8 p5 /* P5 value for OP_Column + FLAGS */
){
assert( pParse->pVdbe!=0 );
sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
if( p5 ){
VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
if( pOp->opcode==OP_Column ) pOp->p5 = p5;
}
return iReg;
}
/*
** Generate code to move content from registers iFrom...iFrom+nReg-1
** over to iTo..iTo+nReg-1.
*/
void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
}
/*
** Convert a scalar expression node to a TK_REGISTER referencing
** register iReg. The caller must ensure that iReg already contains
** the correct value for the expression.
*/
static void exprToRegister(Expr *pExpr, int iReg){
Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
p->op2 = p->op;
p->op = TK_REGISTER;
p->iTable = iReg;
ExprClearProperty(p, EP_Skip);
}
/*
** Evaluate an expression (either a vector or a scalar expression) and store
** the result in continguous temporary registers. Return the index of
** the first register used to store the result.
**
** If the returned result register is a temporary scalar, then also write
** that register number into *piFreeable. If the returned result register
** is not a temporary or if the expression is a vector set *piFreeable
** to 0.
*/
static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
int iResult;
int nResult = sqlite3ExprVectorSize(p);
if( nResult==1 ){
iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
}else{
*piFreeable = 0;
if( p->op==TK_SELECT ){
#if SQLITE_OMIT_SUBQUERY
iResult = 0;
#else
iResult = sqlite3CodeSubselect(pParse, p);
#endif
}else{
int i;
iResult = pParse->nMem+1;
pParse->nMem += nResult;
for(i=0; i<nResult; i++){
sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
}
}
}
return iResult;
}
/*
** Generate code into the current Vdbe to evaluate the given
** expression. Attempt to store the results in register "target".
** Return the register where results are stored.
**
** With this routine, there is no guarantee that results will
** be stored in target. The result might be stored in some other
** register if it is convenient to do so. The calling function
** must check the return code and move the results to the desired
** register.
*/
int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
Vdbe *v = pParse->pVdbe; /* The VM under construction */
int op; /* The opcode being coded */
int inReg = target; /* Results stored in register inReg */
int regFree1 = 0; /* If non-zero free this temporary register */
int regFree2 = 0; /* If non-zero free this temporary register */
int r1, r2; /* Various register numbers */
Expr tempX; /* Temporary expression node */
int p5 = 0;
assert( target>0 && target<=pParse->nMem );
if( v==0 ){
assert( pParse->db->mallocFailed );
return 0;
}
expr_code_doover:
if( pExpr==0 ){
op = TK_NULL;
}else{
op = pExpr->op;
}
switch( op ){
case TK_AGG_COLUMN: {
AggInfo *pAggInfo = pExpr->pAggInfo;
struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
if( !pAggInfo->directMode ){
assert( pCol->iMem>0 );
return pCol->iMem;
}else if( pAggInfo->useSortingIdx ){
sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
pCol->iSorterColumn, target);
return target;
}
/* Otherwise, fall thru into the TK_COLUMN case */
}
case TK_COLUMN: {
int iTab = pExpr->iTable;
if( ExprHasProperty(pExpr, EP_FixedCol) ){
/* This COLUMN expression is really a constant due to WHERE clause
** constraints, and that constant is coded by the pExpr->pLeft
** expresssion. However, make sure the constant has the correct
** datatype by applying the Affinity of the table column to the
** constant.
*/
int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
int aff;
if( pExpr->y.pTab ){
aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
}else{
aff = pExpr->affExpr;
}
if( aff>SQLITE_AFF_BLOB ){
static const char zAff[] = "B\000C\000D\000E";
assert( SQLITE_AFF_BLOB=='A' );
assert( SQLITE_AFF_TEXT=='B' );
if( iReg!=target ){
sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
iReg = target;
}
sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
&zAff[(aff-'B')*2], P4_STATIC);
}
return iReg;
}
if( iTab<0 ){
if( pParse->iSelfTab<0 ){
/* Other columns in the same row for CHECK constraints or
** generated columns or for inserting into partial index.
** The row is unpacked into registers beginning at
** 0-(pParse->iSelfTab). The rowid (if any) is in a register
** immediately prior to the first column.
*/
Column *pCol;
Table *pTab = pExpr->y.pTab;
int iSrc;
int iCol = pExpr->iColumn;
assert( pTab!=0 );
assert( iCol>=XN_ROWID );
assert( iCol<pExpr->y.pTab->nCol );
if( iCol<0 ){
return -1-pParse->iSelfTab;
}
pCol = pTab->aCol + iCol;
testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( pCol->colFlags & COLFLAG_GENERATED ){
if( pCol->colFlags & COLFLAG_BUSY ){
sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
pCol->zName);
return 0;
}
pCol->colFlags |= COLFLAG_BUSY;
if( pCol->colFlags & COLFLAG_NOTAVAIL ){
sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
}
pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
return iSrc;
}else
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
if( pCol->affinity==SQLITE_AFF_REAL ){
sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
return target;
}else{
return iSrc;
}
}else{
/* Coding an expression that is part of an index where column names
** in the index refer to the table to which the index belongs */
iTab = pParse->iSelfTab - 1;
}
}
return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
pExpr->iColumn, iTab, target,
pExpr->op2);
}
case TK_INTEGER: {
codeInteger(pParse, pExpr, 0, target);
return target;
}
case TK_TRUEFALSE: {
sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
return target;
}
#ifndef SQLITE_OMIT_FLOATING_POINT
case TK_FLOAT: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
codeReal(v, pExpr->u.zToken, 0, target);
return target;
}
#endif
case TK_STRING: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
return target;
}
default: {
/* Make NULL the default case so that if a bug causes an illegal
** Expr node to be passed into this function, it will be handled
** sanely and not crash. But keep an assert() to bring the problem
** to the attention of the developers. */
assert( op==TK_NULL );
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
return target;
}
#ifndef SQLITE_OMIT_BLOB_LITERAL
case TK_BLOB: {
int n;
const char *z;
char *zBlob;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
assert( pExpr->u.zToken[1]=='\'' );
z = &pExpr->u.zToken[2];
n = sqlite3Strlen30(z) - 1;
assert( z[n]=='\'' );
zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
return target;
}
#endif
case TK_VARIABLE: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
assert( pExpr->u.zToken!=0 );
assert( pExpr->u.zToken[0]!=0 );
sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
if( pExpr->u.zToken[1]!=0 ){
const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
}
return target;
}
case TK_REGISTER: {
return pExpr->iTable;
}
#ifndef SQLITE_OMIT_CAST
case TK_CAST: {
/* Expressions of the form: CAST(pLeft AS token) */
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
if( inReg!=target ){
sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
inReg = target;
}
sqlite3VdbeAddOp2(v, OP_Cast, target,
sqlite3AffinityType(pExpr->u.zToken, 0));
return inReg;
}
#endif /* SQLITE_OMIT_CAST */
case TK_IS:
case TK_ISNOT:
op = (op==TK_IS) ? TK_EQ : TK_NE;
p5 = SQLITE_NULLEQ;
/* fall-through */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
Expr *pLeft = pExpr->pLeft;
if( sqlite3ExprIsVector(pLeft) ){
codeVectorCompare(pParse, pExpr, target, op, p5);
}else{
r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pLeft, pExpr->pRight, op,
r1, r2, inReg, SQLITE_STOREP2 | p5,
ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
testcase( regFree1==0 );
testcase( regFree2==0 );
}
break;
}
case TK_AND:
case TK_OR:
case TK_PLUS:
case TK_STAR:
case TK_MINUS:
case TK_REM:
case TK_BITAND:
case TK_BITOR:
case TK_SLASH:
case TK_LSHIFT:
case TK_RSHIFT:
case TK_CONCAT: {
assert( TK_AND==OP_And ); testcase( op==TK_AND );
assert( TK_OR==OP_Or ); testcase( op==TK_OR );
assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
sqlite3VdbeAddOp3(v, op, r2, r1, target);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_UMINUS: {
Expr *pLeft = pExpr->pLeft;
assert( pLeft );
if( pLeft->op==TK_INTEGER ){
codeInteger(pParse, pLeft, 1, target);
return target;
#ifndef SQLITE_OMIT_FLOATING_POINT
}else if( pLeft->op==TK_FLOAT ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
codeReal(v, pLeft->u.zToken, 1, target);
return target;
#endif
}else{
tempX.op = TK_INTEGER;
tempX.flags = EP_IntValue|EP_TokenOnly;
tempX.u.iValue = 0;
r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2);
sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
testcase( regFree2==0 );
}
break;
}
case TK_BITNOT:
case TK_NOT: {
assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
sqlite3VdbeAddOp2(v, op, r1, inReg);
break;
}
case TK_TRUTH: {
int isTrue; /* IS TRUE or IS NOT TRUE */
int bNormal; /* IS TRUE or IS FALSE */
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
bNormal = pExpr->op2==TK_IS;
testcase( isTrue && bNormal);
testcase( !isTrue && bNormal);
sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
int addr;
assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
addr = sqlite3VdbeAddOp1(v, op, r1);
VdbeCoverageIf(v, op==TK_ISNULL);
VdbeCoverageIf(v, op==TK_NOTNULL);
sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
sqlite3VdbeJumpHere(v, addr);
break;
}
case TK_AGG_FUNCTION: {
AggInfo *pInfo = pExpr->pAggInfo;
if( pInfo==0 ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
}else{
return pInfo->aFunc[pExpr->iAgg].iMem;
}
break;
}
case TK_FUNCTION: {
ExprList *pFarg; /* List of function arguments */
int nFarg; /* Number of function arguments */
FuncDef *pDef; /* The function definition object */
const char *zId; /* The function name */
u32 constMask = 0; /* Mask of function arguments that are constant */
int i; /* Loop counter */
sqlite3 *db = pParse->db; /* The database connection */
u8 enc = ENC(db); /* The text encoding used by this database */
CollSeq *pColl = 0; /* A collating sequence */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
return pExpr->y.pWin->regResult;
}
#endif
if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
/* SQL functions can be expensive. So try to move constant functions
** out of the inner loop, even if that means an extra OP_Copy. */
return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
}
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
if( ExprHasProperty(pExpr, EP_TokenOnly) ){
pFarg = 0;
}else{
pFarg = pExpr->x.pList;
}
nFarg = pFarg ? pFarg->nExpr : 0;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
zId = pExpr->u.zToken;
pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
if( pDef==0 && pParse->explain ){
pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
}
#endif
if( pDef==0 || pDef->xFinalize!=0 ){
sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
break;
}
/* Attempt a direct implementation of the built-in COALESCE() and
** IFNULL() functions. This avoids unnecessary evaluation of
** arguments past the first non-NULL argument.
*/
if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
int endCoalesce = sqlite3VdbeMakeLabel(pParse);
assert( nFarg>=2 );
sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
for(i=1; i<nFarg; i++){
sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
VdbeCoverage(v);
sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
}
sqlite3VdbeResolveLabel(v, endCoalesce);
break;
}
/* The UNLIKELY() function is a no-op. The result is the value
** of the first argument.
*/
if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
assert( nFarg>=1 );
return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
}
#ifdef SQLITE_DEBUG
/* The AFFINITY() function evaluates to a string that describes
** the type affinity of the argument. This is used for testing of
** the SQLite type logic.
*/
if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
char aff;
assert( nFarg==1 );
aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
sqlite3VdbeLoadString(v, target,
(aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
return target;
}
#endif
for(i=0; i<nFarg; i++){
if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
testcase( i==31 );
constMask |= MASKBIT32(i);
}
if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
}
}
if( pFarg ){
if( constMask ){
r1 = pParse->nMem+1;
pParse->nMem += nFarg;
}else{
r1 = sqlite3GetTempRange(pParse, nFarg);
}
/* For length() and typeof() functions with a column argument,
** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
** loading.
*/
if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
u8 exprOp;
assert( nFarg==1 );
assert( pFarg->a[0].pExpr!=0 );
exprOp = pFarg->a[0].pExpr->op;
if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
pFarg->a[0].pExpr->op2 =
pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
}
}
sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
}else{
r1 = 0;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Possibly overload the function if the first argument is
** a virtual table column.
**
** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
** second argument, not the first, as the argument to test to
** see if it is a column in a virtual table. This is done because
** the left operand of infix functions (the operand we want to
** control overloading) ends up as the second argument to the
** function. The expression "A glob B" is equivalent to
** "glob(B,A). We want to use the A in "A glob B" to test
** for function overloading. But we use the B term in "glob(B,A)".
*/
if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
}else if( nFarg>0 ){
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
}
#endif
if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
if( !pColl ) pColl = db->pDfltColl;
sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
}
#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
Expr *pArg = pFarg->a[0].pExpr;
if( pArg->op==TK_COLUMN ){
sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
}else{
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
}
}else
#endif
{
sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
pDef, pExpr->op2);
}
if( nFarg && constMask==0 ){
sqlite3ReleaseTempRange(pParse, r1, nFarg);
}
return target;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_EXISTS:
case TK_SELECT: {
int nCol;
testcase( op==TK_EXISTS );
testcase( op==TK_SELECT );
if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
sqlite3SubselectError(pParse, nCol, 1);
}else{
return sqlite3CodeSubselect(pParse, pExpr);
}
break;
}
case TK_SELECT_COLUMN: {
int n;
if( pExpr->pLeft->iTable==0 ){
pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
}
assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
if( pExpr->iTable!=0
&& pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
){
sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
pExpr->iTable, n);
}
return pExpr->pLeft->iTable + pExpr->iColumn;
}
case TK_IN: {
int destIfFalse = sqlite3VdbeMakeLabel(pParse);
int destIfNull = sqlite3VdbeMakeLabel(pParse);
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
sqlite3VdbeResolveLabel(v, destIfFalse);
sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
sqlite3VdbeResolveLabel(v, destIfNull);
return target;
}
#endif /* SQLITE_OMIT_SUBQUERY */
/*
** x BETWEEN y AND z
**
** This is equivalent to
**
** x>=y AND x<=z
**
** X is stored in pExpr->pLeft.
** Y is stored in pExpr->pList->a[0].pExpr.
** Z is stored in pExpr->pList->a[1].pExpr.
*/
case TK_BETWEEN: {
exprCodeBetween(pParse, pExpr, target, 0, 0);
return target;
}
case TK_SPAN:
case TK_COLLATE:
case TK_UPLUS: {
pExpr = pExpr->pLeft;
goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
}
case TK_TRIGGER: {
/* If the opcode is TK_TRIGGER, then the expression is a reference
** to a column in the new.* or old.* pseudo-tables available to
** trigger programs. In this case Expr.iTable is set to 1 for the
** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
** is set to the column of the pseudo-table to read, or to -1 to
** read the rowid field.
**
** The expression is implemented using an OP_Param opcode. The p1
** parameter is set to 0 for an old.rowid reference, or to (i+1)
** to reference another column of the old.* pseudo-table, where
** i is the index of the column. For a new.rowid reference, p1 is
** set to (n+1), where n is the number of columns in each pseudo-table.
** For a reference to any other column in the new.* pseudo-table, p1
** is set to (n+2+i), where n and i are as defined previously. For
** example, if the table on which triggers are being fired is
** declared as:
**
** CREATE TABLE t1(a, b);
**
** Then p1 is interpreted as follows:
**
** p1==0 -> old.rowid p1==3 -> new.rowid
** p1==1 -> old.a p1==4 -> new.a
** p1==2 -> old.b p1==5 -> new.b
*/
Table *pTab = pExpr->y.pTab;
int iCol = pExpr->iColumn;
int p1 = pExpr->iTable * (pTab->nCol+1) + 1
+ sqlite3TableColumnToStorage(pTab, iCol);
assert( pExpr->iTable==0 || pExpr->iTable==1 );
assert( iCol>=-1 && iCol<pTab->nCol );
assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
assert( p1>=0 && p1<(pTab->nCol*2+2) );
sqlite3VdbeAddOp2(v, OP_Param, p1, target);
VdbeComment((v, "r[%d]=%s.%s", target,
(pExpr->iTable ? "new" : "old"),
(pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
));
#ifndef SQLITE_OMIT_FLOATING_POINT
/* If the column has REAL affinity, it may currently be stored as an
** integer. Use OP_RealAffinity to make sure it is really real.
**
** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
** floating point when extracting it from the record. */
if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
}
#endif
break;
}
case TK_VECTOR: {
sqlite3ErrorMsg(pParse, "row value misused");
break;
}
/* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
** that derive from the right-hand table of a LEFT JOIN. The
** Expr.iTable value is the table number for the right-hand table.
** The expression is only evaluated if that table is not currently
** on a LEFT JOIN NULL row.
*/
case TK_IF_NULL_ROW: {
int addrINR;
u8 okConstFactor = pParse->okConstFactor;
addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
/* Temporarily disable factoring of constant expressions, since
** even though expressions may appear to be constant, they are not
** really constant because they originate from the right-hand side
** of a LEFT JOIN. */
pParse->okConstFactor = 0;
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
pParse->okConstFactor = okConstFactor;
sqlite3VdbeJumpHere(v, addrINR);
sqlite3VdbeChangeP3(v, addrINR, inReg);
break;
}
/*
** Form A:
** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
**
** Form B:
** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
**
** Form A is can be transformed into the equivalent form B as follows:
** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
** WHEN x=eN THEN rN ELSE y END
**
** X (if it exists) is in pExpr->pLeft.
** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
** odd. The Y is also optional. If the number of elements in x.pList
** is even, then Y is omitted and the "otherwise" result is NULL.
** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
**
** The result of the expression is the Ri for the first matching Ei,
** or if there is no matching Ei, the ELSE term Y, or if there is
** no ELSE term, NULL.
*/
case TK_CASE: {
int endLabel; /* GOTO label for end of CASE stmt */
int nextCase; /* GOTO label for next WHEN clause */
int nExpr; /* 2x number of WHEN terms */
int i; /* Loop counter */
ExprList *pEList; /* List of WHEN terms */
struct ExprList_item *aListelem; /* Array of WHEN terms */
Expr opCompare; /* The X==Ei expression */
Expr *pX; /* The X expression */
Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
Expr *pDel = 0;
sqlite3 *db = pParse->db;
assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
assert(pExpr->x.pList->nExpr > 0);
pEList = pExpr->x.pList;
aListelem = pEList->a;
nExpr = pEList->nExpr;
endLabel = sqlite3VdbeMakeLabel(pParse);
if( (pX = pExpr->pLeft)!=0 ){
pDel = sqlite3ExprDup(db, pX, 0);
if( db->mallocFailed ){
sqlite3ExprDelete(db, pDel);
break;
}
testcase( pX->op==TK_COLUMN );
exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1));
testcase( regFree1==0 );
memset(&opCompare, 0, sizeof(opCompare));
opCompare.op = TK_EQ;
opCompare.pLeft = pDel;
pTest = &opCompare;
/* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
** The value in regFree1 might get SCopy-ed into the file result.
** So make sure that the regFree1 register is not reused for other
** purposes and possibly overwritten. */
regFree1 = 0;
}
for(i=0; i<nExpr-1; i=i+2){
if( pX ){
assert( pTest!=0 );
opCompare.pRight = aListelem[i].pExpr;
}else{
pTest = aListelem[i].pExpr;
}
nextCase = sqlite3VdbeMakeLabel(pParse);
testcase( pTest->op==TK_COLUMN );
sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
sqlite3VdbeGoto(v, endLabel);
sqlite3VdbeResolveLabel(v, nextCase);
}
if( (nExpr&1)!=0 ){
sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
}else{
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
}
sqlite3ExprDelete(db, pDel);
sqlite3VdbeResolveLabel(v, endLabel);
break;
}
#ifndef SQLITE_OMIT_TRIGGER
case TK_RAISE: {
assert( pExpr->affExpr==OE_Rollback
|| pExpr->affExpr==OE_Abort
|| pExpr->affExpr==OE_Fail
|| pExpr->affExpr==OE_Ignore
);
if( !pParse->pTriggerTab ){
sqlite3ErrorMsg(pParse,
"RAISE() may only be used within a trigger-program");
return 0;
}
if( pExpr->affExpr==OE_Abort ){
sqlite3MayAbort(pParse);
}
assert( !ExprHasProperty(pExpr, EP_IntValue) );
if( pExpr->affExpr==OE_Ignore ){
sqlite3VdbeAddOp4(
v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
VdbeCoverage(v);
}else{
sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
pExpr->affExpr, pExpr->u.zToken, 0, 0);
}
break;
}
#endif
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
return inReg;
}
/*
** Factor out the code of the given expression to initialization time.
**
** If regDest>=0 then the result is always stored in that register and the
** result is not reusable. If regDest<0 then this routine is free to
** store the value whereever it wants. The register where the expression
** is stored is returned. When regDest<0, two identical expressions will
** code to the same register.
*/
int sqlite3ExprCodeAtInit(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The expression to code when the VDBE initializes */
int regDest /* Store the value in this register */
){
ExprList *p;
assert( ConstFactorOk(pParse) );
p = pParse->pConstExpr;
if( regDest<0 && p ){
struct ExprList_item *pItem;
int i;
for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
return pItem->u.iConstExprReg;
}
}
}
pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
p = sqlite3ExprListAppend(pParse, p, pExpr);
if( p ){
struct ExprList_item *pItem = &p->a[p->nExpr-1];
pItem->reusable = regDest<0;
if( regDest<0 ) regDest = ++pParse->nMem;
pItem->u.iConstExprReg = regDest;
}
pParse->pConstExpr = p;
return regDest;
}
/*
** Generate code to evaluate an expression and store the results
** into a register. Return the register number where the results
** are stored.
**
** If the register is a temporary register that can be deallocated,
** then write its number into *pReg. If the result register is not
** a temporary, then set *pReg to zero.
**
** If pExpr is a constant, then this routine might generate this
** code to fill the register in the initialization section of the
** VDBE program, in order to factor it out of the evaluation loop.
*/
int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
int r2;
pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
if( ConstFactorOk(pParse)
&& pExpr->op!=TK_REGISTER
&& sqlite3ExprIsConstantNotJoin(pExpr)
){
*pReg = 0;
r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
}else{
int r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
if( r2==r1 ){
*pReg = r1;
}else{
sqlite3ReleaseTempReg(pParse, r1);
*pReg = 0;
}
}
return r2;
}
/*
** Generate code that will evaluate expression pExpr and store the
** results in register target. The results are guaranteed to appear
** in register target.
*/
void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
int inReg;
assert( target>0 && target<=pParse->nMem );
inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
if( inReg!=target && pParse->pVdbe ){
sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
}
}
/*
** Make a transient copy of expression pExpr and then code it using
** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
** except that the input expression is guaranteed to be unchanged.
*/
void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
sqlite3 *db = pParse->db;
pExpr = sqlite3ExprDup(db, pExpr, 0);
if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
sqlite3ExprDelete(db, pExpr);
}
/*
** Generate code that will evaluate expression pExpr and store the
** results in register target. The results are guaranteed to appear
** in register target. If the expression is constant, then this routine
** might choose to code the expression at initialization time.
*/
void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
sqlite3ExprCodeAtInit(pParse, pExpr, target);
}else{
sqlite3ExprCode(pParse, pExpr, target);
}
}
/*
** Generate code that pushes the value of every element of the given
** expression list into a sequence of registers beginning at target.
**
** Return the number of elements evaluated. The number returned will
** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
** is defined.
**
** The SQLITE_ECEL_DUP flag prevents the arguments from being
** filled using OP_SCopy. OP_Copy must be used instead.
**
** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
** factored out into initialization code.
**
** The SQLITE_ECEL_REF flag means that expressions in the list with
** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
** in registers at srcReg, and so the value can be copied from there.
** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
** are simply omitted rather than being copied from srcReg.
*/
int sqlite3ExprCodeExprList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* The expression list to be coded */
int target, /* Where to write results */
int srcReg, /* Source registers if SQLITE_ECEL_REF */
u8 flags /* SQLITE_ECEL_* flags */
){
struct ExprList_item *pItem;
int i, j, n;
u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
Vdbe *v = pParse->pVdbe;
assert( pList!=0 );
assert( target>0 );
assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
n = pList->nExpr;
if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
for(pItem=pList->a, i=0; i<n; i++, pItem++){
Expr *pExpr = pItem->pExpr;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pItem->bSorterRef ){
i--;
n--;
}else
#endif
if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
if( flags & SQLITE_ECEL_OMITREF ){
i--;
n--;
}else{
sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
}
}else if( (flags & SQLITE_ECEL_FACTOR)!=0
&& sqlite3ExprIsConstantNotJoin(pExpr)
){
sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
}else{
int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
if( inReg!=target+i ){
VdbeOp *pOp;
if( copyOp==OP_Copy
&& (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
&& pOp->p1+pOp->p3+1==inReg
&& pOp->p2+pOp->p3+1==target+i
){
pOp->p3++;
}else{
sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
}
}
}
}
return n;
}
/*
** Generate code for a BETWEEN operator.
**
** x BETWEEN y AND z
**
** The above is equivalent to
**
** x>=y AND x<=z
**
** Code it as such, taking care to do the common subexpression
** elimination of x.
**
** The xJumpIf parameter determines details:
**
** NULL: Store the boolean result in reg[dest]
** sqlite3ExprIfTrue: Jump to dest if true
** sqlite3ExprIfFalse: Jump to dest if false
**
** The jumpIfNull parameter is ignored if xJumpIf is NULL.
*/
static void exprCodeBetween(
Parse *pParse, /* Parsing and code generating context */
Expr *pExpr, /* The BETWEEN expression */
int dest, /* Jump destination or storage location */
void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
int jumpIfNull /* Take the jump if the BETWEEN is NULL */
){
Expr exprAnd; /* The AND operator in x>=y AND x<=z */
Expr compLeft; /* The x>=y term */
Expr compRight; /* The x<=z term */
int regFree1 = 0; /* Temporary use register */
Expr *pDel = 0;
sqlite3 *db = pParse->db;
memset(&compLeft, 0, sizeof(Expr));
memset(&compRight, 0, sizeof(Expr));
memset(&exprAnd, 0, sizeof(Expr));
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
if( db->mallocFailed==0 ){
exprAnd.op = TK_AND;
exprAnd.pLeft = &compLeft;
exprAnd.pRight = &compRight;
compLeft.op = TK_GE;
compLeft.pLeft = pDel;
compLeft.pRight = pExpr->x.pList->a[0].pExpr;
compRight.op = TK_LE;
compRight.pLeft = pDel;
compRight.pRight = pExpr->x.pList->a[1].pExpr;
exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1));
if( xJump ){
xJump(pParse, &exprAnd, dest, jumpIfNull);
}else{
/* Mark the expression is being from the ON or USING clause of a join
** so that the sqlite3ExprCodeTarget() routine will not attempt to move
** it into the Parse.pConstExpr list. We should use a new bit for this,
** for clarity, but we are out of bits in the Expr.flags field so we
** have to reuse the EP_FromJoin bit. Bummer. */
pDel->flags |= EP_FromJoin;
sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
}
sqlite3ReleaseTempReg(pParse, regFree1);
}
sqlite3ExprDelete(db, pDel);
/* Ensure adequate test coverage */
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
testcase( xJump==0 );
}
/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is true but execution
** continues straight thru if the expression is false.
**
** If the expression evaluates to NULL (neither true nor false), then
** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
**
** This code depends on the fact that certain token values (ex: TK_EQ)
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
** the make process cause these values to align. Assert()s in the code
** below verify that the numbers are aligned correctly.
*/
void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
Vdbe *v = pParse->pVdbe;
int op = 0;
int regFree1 = 0;
int regFree2 = 0;
int r1, r2;
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
if( NEVER(pExpr==0) ) return; /* No way this can happen */
op = pExpr->op;
switch( op ){
case TK_AND:
case TK_OR: {
Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
if( pAlt!=pExpr ){
sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
}else if( op==TK_AND ){
int d2 = sqlite3VdbeMakeLabel(pParse);
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
jumpIfNull^SQLITE_JUMPIFNULL);
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
sqlite3VdbeResolveLabel(v, d2);
}else{
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
}
break;
}
case TK_NOT: {
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
break;
}
case TK_TRUTH: {
int isNot; /* IS NOT TRUE or IS NOT FALSE */
int isTrue; /* IS TRUE or IS NOT TRUE */
testcase( jumpIfNull==0 );
isNot = pExpr->op2==TK_ISNOT;
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
testcase( isTrue && isNot );
testcase( !isTrue && isNot );
if( isTrue ^ isNot ){
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
isNot ? SQLITE_JUMPIFNULL : 0);
}else{
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
isNot ? SQLITE_JUMPIFNULL : 0);
}
break;
}
case TK_IS:
case TK_ISNOT:
testcase( op==TK_IS );
testcase( op==TK_ISNOT );
op = (op==TK_IS) ? TK_EQ : TK_NE;
jumpIfNull = SQLITE_NULLEQ;
/* Fall thru */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
testcase( jumpIfNull==0 );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
sqlite3VdbeAddOp2(v, op, r1, dest);
VdbeCoverageIf(v, op==TK_ISNULL);
VdbeCoverageIf(v, op==TK_NOTNULL);
testcase( regFree1==0 );
break;
}
case TK_BETWEEN: {
testcase( jumpIfNull==0 );
exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_IN: {
int destIfFalse = sqlite3VdbeMakeLabel(pParse);
int destIfNull = jumpIfNull ? dest : destIfFalse;
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
sqlite3VdbeGoto(v, dest);
sqlite3VdbeResolveLabel(v, destIfFalse);
break;
}
#endif
default: {
default_expr:
if( ExprAlwaysTrue(pExpr) ){
sqlite3VdbeGoto(v, dest);
}else if( ExprAlwaysFalse(pExpr) ){
/* No-op */
}else{
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
VdbeCoverage(v);
testcase( regFree1==0 );
testcase( jumpIfNull==0 );
}
break;
}
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
}
/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is false but execution
** continues straight thru if the expression is true.
**
** If the expression evaluates to NULL (neither true nor false) then
** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
** is 0.
*/
void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
Vdbe *v = pParse->pVdbe;
int op = 0;
int regFree1 = 0;
int regFree2 = 0;
int r1, r2;
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
if( pExpr==0 ) return;
/* The value of pExpr->op and op are related as follows:
**
** pExpr->op op
** --------- ----------
** TK_ISNULL OP_NotNull
** TK_NOTNULL OP_IsNull
** TK_NE OP_Eq
** TK_EQ OP_Ne
** TK_GT OP_Le
** TK_LE OP_Gt
** TK_GE OP_Lt
** TK_LT OP_Ge
**
** For other values of pExpr->op, op is undefined and unused.
** The value of TK_ and OP_ constants are arranged such that we
** can compute the mapping above using the following expression.
** Assert()s verify that the computation is correct.
*/
op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
/* Verify correct alignment of TK_ and OP_ constants
*/
assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
assert( pExpr->op!=TK_NE || op==OP_Eq );
assert( pExpr->op!=TK_EQ || op==OP_Ne );
assert( pExpr->op!=TK_LT || op==OP_Ge );
assert( pExpr->op!=TK_LE || op==OP_Gt );
assert( pExpr->op!=TK_GT || op==OP_Le );
assert( pExpr->op!=TK_GE || op==OP_Lt );
switch( pExpr->op ){
case TK_AND:
case TK_OR: {
Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
if( pAlt!=pExpr ){
sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
}else if( pExpr->op==TK_AND ){
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
}else{
int d2 = sqlite3VdbeMakeLabel(pParse);
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
jumpIfNull^SQLITE_JUMPIFNULL);
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
sqlite3VdbeResolveLabel(v, d2);
}
break;
}
case TK_NOT: {
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
break;
}
case TK_TRUTH: {
int isNot; /* IS NOT TRUE or IS NOT FALSE */
int isTrue; /* IS TRUE or IS NOT TRUE */
testcase( jumpIfNull==0 );
isNot = pExpr->op2==TK_ISNOT;
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
testcase( isTrue && isNot );
testcase( !isTrue && isNot );
if( isTrue ^ isNot ){
/* IS TRUE and IS NOT FALSE */
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
isNot ? 0 : SQLITE_JUMPIFNULL);
}else{
/* IS FALSE and IS NOT TRUE */
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
isNot ? 0 : SQLITE_JUMPIFNULL);
}
break;
}
case TK_IS:
case TK_ISNOT:
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_ISNOT );
op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
jumpIfNull = SQLITE_NULLEQ;
/* Fall thru */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
testcase( jumpIfNull==0 );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
sqlite3VdbeAddOp2(v, op, r1, dest);
testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
testcase( regFree1==0 );
break;
}
case TK_BETWEEN: {
testcase( jumpIfNull==0 );
exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_IN: {
if( jumpIfNull ){
sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
}else{
int destIfNull = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
sqlite3VdbeResolveLabel(v, destIfNull);
}
break;
}
#endif
default: {
default_expr:
if( ExprAlwaysFalse(pExpr) ){
sqlite3VdbeGoto(v, dest);
}else if( ExprAlwaysTrue(pExpr) ){
/* no-op */
}else{
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
VdbeCoverage(v);
testcase( regFree1==0 );
testcase( jumpIfNull==0 );
}
break;
}
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
}
/*
** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
** code generation, and that copy is deleted after code generation. This
** ensures that the original pExpr is unchanged.
*/
void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
sqlite3 *db = pParse->db;
Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
if( db->mallocFailed==0 ){
sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
}
sqlite3ExprDelete(db, pCopy);
}
/*
** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
** type of expression.
**
** If pExpr is a simple SQL value - an integer, real, string, blob
** or NULL value - then the VDBE currently being prepared is configured
** to re-prepare each time a new value is bound to variable pVar.
**
** Additionally, if pExpr is a simple SQL value and the value is the
** same as that currently bound to variable pVar, non-zero is returned.
** Otherwise, if the values are not the same or if pExpr is not a simple
** SQL value, zero is returned.
*/
static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
int res = 0;
int iVar;
sqlite3_value *pL, *pR = 0;
sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
if( pR ){
iVar = pVar->iColumn;
sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
if( pL ){
if( sqlite3_value_type(pL)==SQLITE_TEXT ){
sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
}
res = 0==sqlite3MemCompare(pL, pR, 0);
}
sqlite3ValueFree(pR);
sqlite3ValueFree(pL);
}
return res;
}
/*
** Do a deep comparison of two expression trees. Return 0 if the two
** expressions are completely identical. Return 1 if they differ only
** by a COLLATE operator at the top level. Return 2 if there are differences
** other than the top-level COLLATE operator.
**
** If any subelement of pB has Expr.iTable==(-1) then it is allowed
** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
**
** The pA side might be using TK_REGISTER. If that is the case and pB is
** not using TK_REGISTER but is otherwise equivalent, then still return 0.
**
** Sometimes this routine will return 2 even if the two expressions
** really are equivalent. If we cannot prove that the expressions are
** identical, we return 2 just to be safe. So if this routine
** returns 2, then you do not really know for certain if the two
** expressions are the same. But if you get a 0 or 1 return, then you
** can be sure the expressions are the same. In the places where
** this routine is used, it does not hurt to get an extra 2 - that
** just might result in some slightly slower code. But returning
** an incorrect 0 or 1 could lead to a malfunction.
**
** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
** pParse->pReprepare can be matched against literals in pB. The
** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
** If pParse is NULL (the normal case) then any TK_VARIABLE term in
** Argument pParse should normally be NULL. If it is not NULL and pA or
** pB causes a return value of 2.
*/
int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
u32 combinedFlags;
if( pA==0 || pB==0 ){
return pB==pA ? 0 : 2;
}
if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
return 0;
}
combinedFlags = pA->flags | pB->flags;
if( combinedFlags & EP_IntValue ){
if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
return 0;
}
return 2;
}
if( pA->op!=pB->op || pA->op==TK_RAISE ){
if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
return 1;
}
if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
return 1;
}
return 2;
}
if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( pA->op==pB->op );
if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
return 2;
}
if( ExprHasProperty(pA,EP_WinFunc) ){
if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
return 2;
}
}
#endif
}else if( pA->op==TK_NULL ){
return 0;
}else if( pA->op==TK_COLLATE ){
if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
}else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
return 2;
}
}
if( (pA->flags & (EP_Distinct|EP_Commuted))
!= (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
if( (combinedFlags & EP_TokenOnly)==0 ){
if( combinedFlags & EP_xIsSelect ) return 2;
if( (combinedFlags & EP_FixedCol)==0
&& sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
if( pA->op!=TK_STRING
&& pA->op!=TK_TRUEFALSE
&& (combinedFlags & EP_Reduced)==0
){
if( pA->iColumn!=pB->iColumn ) return 2;
if( pA->op2!=pB->op2 ){
if( pA->op==TK_TRUTH ) return 2;
if( pA->op==TK_FUNCTION && iTab<0 ){
/* Ex: CREATE TABLE t1(a CHECK( a<julianday('now') ));
** INSERT INTO t1(a) VALUES(julianday('now')+10);
** Without this test, sqlite3ExprCodeAtInit() will run on the
** the julianday() of INSERT first, and remember that expression.
** Then sqlite3ExprCodeInit() will see the julianday() in the CHECK
** constraint as redundant, reusing the one from the INSERT, even
** though the julianday() in INSERT lacks the critical NC_IsCheck
** flag. See ticket [830277d9db6c3ba1] (2019-10-30)
*/
return 2;
}
}
if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
return 2;
}
}
}
return 0;
}
/*
** Compare two ExprList objects. Return 0 if they are identical and
** non-zero if they differ in any way.
**
** If any subelement of pB has Expr.iTable==(-1) then it is allowed
** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
**
** This routine might return non-zero for equivalent ExprLists. The
** only consequence will be disabled optimizations. But this routine
** must never return 0 if the two ExprList objects are different, or
** a malfunction will result.
**
** Two NULL pointers are considered to be the same. But a NULL pointer
** always differs from a non-NULL pointer.
*/
int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
int i;
if( pA==0 && pB==0 ) return 0;
if( pA==0 || pB==0 ) return 1;
if( pA->nExpr!=pB->nExpr ) return 1;
for(i=0; i<pA->nExpr; i++){
Expr *pExprA = pA->a[i].pExpr;
Expr *pExprB = pB->a[i].pExpr;
if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
}
return 0;
}
/*
** Like sqlite3ExprCompare() except COLLATE operators at the top-level
** are ignored.
*/
int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
return sqlite3ExprCompare(0,
sqlite3ExprSkipCollateAndLikely(pA),
sqlite3ExprSkipCollateAndLikely(pB),
iTab);
}
/*
** Return non-zero if Expr p can only be true if pNN is not NULL.
**
** Or if seenNot is true, return non-zero if Expr p can only be
** non-NULL if pNN is not NULL
*/
static int exprImpliesNotNull(
Parse *pParse, /* Parsing context */
Expr *p, /* The expression to be checked */
Expr *pNN, /* The expression that is NOT NULL */
int iTab, /* Table being evaluated */
int seenNot /* Return true only if p can be any non-NULL value */
){
assert( p );
assert( pNN );
if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
return pNN->op!=TK_NULL;
}
switch( p->op ){
case TK_IN: {
if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
assert( ExprHasProperty(p,EP_xIsSelect)
|| (p->x.pList!=0 && p->x.pList->nExpr>0) );
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_BETWEEN: {
ExprList *pList = p->x.pList;
assert( pList!=0 );
assert( pList->nExpr==2 );
if( seenNot ) return 0;
if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
|| exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
){
return 1;
}
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_PLUS:
case TK_MINUS:
case TK_BITOR:
case TK_LSHIFT:
case TK_RSHIFT:
case TK_CONCAT:
seenNot = 1;
/* Fall thru */
case TK_STAR:
case TK_REM:
case TK_BITAND:
case TK_SLASH: {
if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
/* Fall thru into the next case */
}
case TK_SPAN:
case TK_COLLATE:
case TK_UPLUS:
case TK_UMINUS: {
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
}
case TK_TRUTH: {
if( seenNot ) return 0;
if( p->op2!=TK_IS ) return 0;
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_BITNOT:
case TK_NOT: {
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
}
return 0;
}
/*
** Return true if we can prove the pE2 will always be true if pE1 is
** true. Return false if we cannot complete the proof or if pE2 might
** be false. Examples:
**
** pE1: x==5 pE2: x==5 Result: true
** pE1: x>0 pE2: x==5 Result: false
** pE1: x=21 pE2: x=21 OR y=43 Result: true
** pE1: x!=123 pE2: x IS NOT NULL Result: true
** pE1: x!=?1 pE2: x IS NOT NULL Result: true
** pE1: x IS NULL pE2: x IS NOT NULL Result: false
** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
**
** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
** Expr.iTable<0 then assume a table number given by iTab.
**
** If pParse is not NULL, then the values of bound variables in pE1 are
** compared against literal values in pE2 and pParse->pVdbe->expmask is
** modified to record which bound variables are referenced. If pParse
** is NULL, then false will be returned if pE1 contains any bound variables.
**
** When in doubt, return false. Returning true might give a performance
** improvement. Returning false might cause a performance reduction, but
** it will always give the correct answer and is hence always safe.
*/
int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
return 1;
}
if( pE2->op==TK_OR
&& (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
|| sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
){
return 1;
}
if( pE2->op==TK_NOTNULL
&& exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
){
return 1;
}
return 0;
}
/*
** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
** If the expression node requires that the table at pWalker->iCur
** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
**
** This routine controls an optimization. False positives (setting
** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
** (never setting pWalker->eCode) is a harmless missed optimization.
*/
static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
testcase( pExpr->op==TK_AGG_COLUMN );
testcase( pExpr->op==TK_AGG_FUNCTION );
if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
switch( pExpr->op ){
case TK_ISNOT:
case TK_ISNULL:
case TK_NOTNULL:
case TK_IS:
case TK_OR:
case TK_VECTOR:
case TK_CASE:
case TK_IN:
case TK_FUNCTION:
case TK_TRUTH:
testcase( pExpr->op==TK_ISNOT );
testcase( pExpr->op==TK_ISNULL );
testcase( pExpr->op==TK_NOTNULL );
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_OR );
testcase( pExpr->op==TK_VECTOR );
testcase( pExpr->op==TK_CASE );
testcase( pExpr->op==TK_IN );
testcase( pExpr->op==TK_FUNCTION );
testcase( pExpr->op==TK_TRUTH );
return WRC_Prune;
case TK_COLUMN:
if( pWalker->u.iCur==pExpr->iTable ){
pWalker->eCode = 1;
return WRC_Abort;
}
return WRC_Prune;
case TK_AND:
assert( pWalker->eCode==0 );
sqlite3WalkExpr(pWalker, pExpr->pLeft);
if( pWalker->eCode ){
pWalker->eCode = 0;
sqlite3WalkExpr(pWalker, pExpr->pRight);
}
return WRC_Prune;
case TK_BETWEEN:
sqlite3WalkExpr(pWalker, pExpr->pLeft);
return WRC_Prune;
/* Virtual tables are allowed to use constraints like x=NULL. So
** a term of the form x=y does not prove that y is not null if x
** is the column of a virtual table */
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
testcase( pExpr->op==TK_EQ );
testcase( pExpr->op==TK_NE );
testcase( pExpr->op==TK_LT );
testcase( pExpr->op==TK_LE );
testcase( pExpr->op==TK_GT );
testcase( pExpr->op==TK_GE );
if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
|| (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
){
return WRC_Prune;
}
default:
return WRC_Continue;
}
}
/*
** Return true (non-zero) if expression p can only be true if at least
** one column of table iTab is non-null. In other words, return true
** if expression p will always be NULL or false if every column of iTab
** is NULL.
**
** False negatives are acceptable. In other words, it is ok to return
** zero even if expression p will never be true of every column of iTab
** is NULL. A false negative is merely a missed optimization opportunity.
**
** False positives are not allowed, however. A false positive may result
** in an incorrect answer.
**
** Terms of p that are marked with EP_FromJoin (and hence that come from
** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
**
** This routine is used to check if a LEFT JOIN can be converted into
** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
** clause requires that some column of the right table of the LEFT JOIN
** be non-NULL, then the LEFT JOIN can be safely converted into an
** ordinary join.
*/
int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
Walker w;
p = sqlite3ExprSkipCollateAndLikely(p);
if( p==0 ) return 0;
if( p->op==TK_NOTNULL ){
p = p->pLeft;
}else{
while( p->op==TK_AND ){
if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
p = p->pRight;
}
}
w.xExprCallback = impliesNotNullRow;
w.xSelectCallback = 0;
w.xSelectCallback2 = 0;
w.eCode = 0;
w.u.iCur = iTab;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** An instance of the following structure is used by the tree walker
** to determine if an expression can be evaluated by reference to the
** index only, without having to do a search for the corresponding
** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
** is the cursor for the table.
*/
struct IdxCover {
Index *pIdx; /* The index to be tested for coverage */
int iCur; /* Cursor number for the table corresponding to the index */
};
/*
** Check to see if there are references to columns in table
** pWalker->u.pIdxCover->iCur can be satisfied using the index
** pWalker->u.pIdxCover->pIdx.
*/
static int exprIdxCover(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_COLUMN
&& pExpr->iTable==pWalker->u.pIdxCover->iCur
&& sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
){
pWalker->eCode = 1;
return WRC_Abort;
}
return WRC_Continue;
}
/*
** Determine if an index pIdx on table with cursor iCur contains will
** the expression pExpr. Return true if the index does cover the
** expression and false if the pExpr expression references table columns
** that are not found in the index pIdx.
**
** An index covering an expression means that the expression can be
** evaluated using only the index and without having to lookup the
** corresponding table entry.
*/
int sqlite3ExprCoveredByIndex(
Expr *pExpr, /* The index to be tested */
int iCur, /* The cursor number for the corresponding table */
Index *pIdx /* The index that might be used for coverage */
){
Walker w;
struct IdxCover xcov;
memset(&w, 0, sizeof(w));
xcov.iCur = iCur;
xcov.pIdx = pIdx;
w.xExprCallback = exprIdxCover;
w.u.pIdxCover = &xcov;
sqlite3WalkExpr(&w, pExpr);
return !w.eCode;
}
/*
** An instance of the following structure is used by the tree walker
** to count references to table columns in the arguments of an
** aggregate function, in order to implement the
** sqlite3FunctionThisSrc() routine.
*/
struct SrcCount {
SrcList *pSrc; /* One particular FROM clause in a nested query */
int nThis; /* Number of references to columns in pSrcList */
int nOther; /* Number of references to columns in other FROM clauses */
};
/*
** Count the number of references to columns.
*/
static int exprSrcCount(Walker *pWalker, Expr *pExpr){
/* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
** is always called before sqlite3ExprAnalyzeAggregates() and so the
** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
** sqlite3FunctionUsesThisSrc() is used differently in the future, the
** NEVER() will need to be removed. */
if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
int i;
struct SrcCount *p = pWalker->u.pSrcCount;
SrcList *pSrc = p->pSrc;
int nSrc = pSrc ? pSrc->nSrc : 0;
for(i=0; i<nSrc; i++){
if( pExpr->iTable==pSrc->a[i].iCursor ) break;
}
if( i<nSrc ){
p->nThis++;
}else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
/* In a well-formed parse tree (no name resolution errors),
** TK_COLUMN nodes with smaller Expr.iTable values are in an
** outer context. Those are the only ones to count as "other" */
p->nOther++;
}
}
return WRC_Continue;
}
/*
** Determine if any of the arguments to the pExpr Function reference
** pSrcList. Return true if they do. Also return true if the function
** has no arguments or has only constant arguments. Return false if pExpr
** references columns but not columns of tables found in pSrcList.
*/
int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
Walker w;
struct SrcCount cnt;
assert( pExpr->op==TK_AGG_FUNCTION );
memset(&w, 0, sizeof(w));
w.xExprCallback = exprSrcCount;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.u.pSrcCount = &cnt;
cnt.pSrc = pSrcList;
cnt.nThis = 0;
cnt.nOther = 0;
sqlite3WalkExprList(&w, pExpr->x.pList);
return cnt.nThis>0 || cnt.nOther==0;
}
/*
** Add a new element to the pAggInfo->aCol[] array. Return the index of
** the new element. Return a negative number if malloc fails.
*/
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
int i;
pInfo->aCol = sqlite3ArrayAllocate(
db,
pInfo->aCol,
sizeof(pInfo->aCol[0]),
&pInfo->nColumn,
&i
);
return i;
}
/*
** Add a new element to the pAggInfo->aFunc[] array. Return the index of
** the new element. Return a negative number if malloc fails.
*/
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
int i;
pInfo->aFunc = sqlite3ArrayAllocate(
db,
pInfo->aFunc,
sizeof(pInfo->aFunc[0]),
&pInfo->nFunc,
&i
);
return i;
}
/*
** This is the xExprCallback for a tree walker. It is used to
** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
** for additional information.
*/
static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
int i;
NameContext *pNC = pWalker->u.pNC;
Parse *pParse = pNC->pParse;
SrcList *pSrcList = pNC->pSrcList;
AggInfo *pAggInfo = pNC->uNC.pAggInfo;
assert( pNC->ncFlags & NC_UAggInfo );
switch( pExpr->op ){
case TK_AGG_COLUMN:
case TK_COLUMN: {
testcase( pExpr->op==TK_AGG_COLUMN );
testcase( pExpr->op==TK_COLUMN );
/* Check to see if the column is in one of the tables in the FROM
** clause of the aggregate query */
if( ALWAYS(pSrcList!=0) ){
struct SrcList_item *pItem = pSrcList->a;
for(i=0; i<pSrcList->nSrc; i++, pItem++){
struct AggInfo_col *pCol;
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
if( pExpr->iTable==pItem->iCursor ){
/* If we reach this point, it means that pExpr refers to a table
** that is in the FROM clause of the aggregate query.
**
** Make an entry for the column in pAggInfo->aCol[] if there
** is not an entry there already.
*/
int k;
pCol = pAggInfo->aCol;
for(k=0; k<pAggInfo->nColumn; k++, pCol++){
if( pCol->iTable==pExpr->iTable &&
pCol->iColumn==pExpr->iColumn ){
break;
}
}
if( (k>=pAggInfo->nColumn)
&& (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
){
pCol = &pAggInfo->aCol[k];
pCol->pTab = pExpr->y.pTab;
pCol->iTable = pExpr->iTable;
pCol->iColumn = pExpr->iColumn;
pCol->iMem = ++pParse->nMem;
pCol->iSorterColumn = -1;
pCol->pExpr = pExpr;
if( pAggInfo->pGroupBy ){
int j, n;
ExprList *pGB = pAggInfo->pGroupBy;
struct ExprList_item *pTerm = pGB->a;
n = pGB->nExpr;
for(j=0; j<n; j++, pTerm++){
Expr *pE = pTerm->pExpr;
if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
pE->iColumn==pExpr->iColumn ){
pCol->iSorterColumn = j;
break;
}
}
}
if( pCol->iSorterColumn<0 ){
pCol->iSorterColumn = pAggInfo->nSortingColumn++;
}
}
/* There is now an entry for pExpr in pAggInfo->aCol[] (either
** because it was there before or because we just created it).
** Convert the pExpr to be a TK_AGG_COLUMN referring to that
** pAggInfo->aCol[] entry.
*/
ExprSetVVAProperty(pExpr, EP_NoReduce);
pExpr->pAggInfo = pAggInfo;
pExpr->op = TK_AGG_COLUMN;
pExpr->iAgg = (i16)k;
break;
} /* endif pExpr->iTable==pItem->iCursor */
} /* end loop over pSrcList */
}
return WRC_Prune;
}
case TK_AGG_FUNCTION: {
if( (pNC->ncFlags & NC_InAggFunc)==0
&& pWalker->walkerDepth==pExpr->op2
){
/* Check to see if pExpr is a duplicate of another aggregate
** function that is already in the pAggInfo structure
*/
struct AggInfo_func *pItem = pAggInfo->aFunc;
for(i=0; i<pAggInfo->nFunc; i++, pItem++){
if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
break;
}
}
if( i>=pAggInfo->nFunc ){
/* pExpr is original. Make a new entry in pAggInfo->aFunc[]
*/
u8 enc = ENC(pParse->db);
i = addAggInfoFunc(pParse->db, pAggInfo);
if( i>=0 ){
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
pItem = &pAggInfo->aFunc[i];
pItem->pExpr = pExpr;
pItem->iMem = ++pParse->nMem;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
pItem->pFunc = sqlite3FindFunction(pParse->db,
pExpr->u.zToken,
pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
if( pExpr->flags & EP_Distinct ){
pItem->iDistinct = pParse->nTab++;
}else{
pItem->iDistinct = -1;
}
}
}
/* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
*/
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(pExpr, EP_NoReduce);
pExpr->iAgg = (i16)i;
pExpr->pAggInfo = pAggInfo;
return WRC_Prune;
}else{
return WRC_Continue;
}
}
}
return WRC_Continue;
}
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
UNUSED_PARAMETER(pSelect);
pWalker->walkerDepth++;
return WRC_Continue;
}
static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
UNUSED_PARAMETER(pSelect);
pWalker->walkerDepth--;
}
/*
** Analyze the pExpr expression looking for aggregate functions and
** for variables that need to be added to AggInfo object that pNC->pAggInfo
** points to. Additional entries are made on the AggInfo object as
** necessary.
**
** This routine should only be called after the expression has been
** analyzed by sqlite3ResolveExprNames().
*/
void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
Walker w;
w.xExprCallback = analyzeAggregate;
w.xSelectCallback = analyzeAggregatesInSelect;
w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
w.walkerDepth = 0;
w.u.pNC = pNC;
w.pParse = 0;
assert( pNC->pSrcList!=0 );
sqlite3WalkExpr(&w, pExpr);
}
/*
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
** expression list. Return the number of errors.
**
** If an error is found, the analysis is cut short.
*/
void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
struct ExprList_item *pItem;
int i;
if( pList ){
for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
}
}
}
/*
** Allocate a single new register for use to hold some intermediate result.
*/
int sqlite3GetTempReg(Parse *pParse){
if( pParse->nTempReg==0 ){
return ++pParse->nMem;
}
return pParse->aTempReg[--pParse->nTempReg];
}
/*
** Deallocate a register, making available for reuse for some other
** purpose.
*/
void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
pParse->aTempReg[pParse->nTempReg++] = iReg;
}
}
/*
** Allocate or deallocate a block of nReg consecutive registers.
*/
int sqlite3GetTempRange(Parse *pParse, int nReg){
int i, n;
if( nReg==1 ) return sqlite3GetTempReg(pParse);
i = pParse->iRangeReg;
n = pParse->nRangeReg;
if( nReg<=n ){
pParse->iRangeReg += nReg;
pParse->nRangeReg -= nReg;
}else{
i = pParse->nMem+1;
pParse->nMem += nReg;
}
return i;
}
void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
if( nReg==1 ){
sqlite3ReleaseTempReg(pParse, iReg);
return;
}
if( nReg>pParse->nRangeReg ){
pParse->nRangeReg = nReg;
pParse->iRangeReg = iReg;
}
}
/*
** Mark all temporary registers as being unavailable for reuse.
**
** Always invoke this procedure after coding a subroutine or co-routine
** that might be invoked from other parts of the code, to ensure that
** the sub/co-routine does not use registers in common with the code that
** invokes the sub/co-routine.
*/
void sqlite3ClearTempRegCache(Parse *pParse){
pParse->nTempReg = 0;
pParse->nRangeReg = 0;
}
/*
** Validate that no temporary register falls within the range of
** iFirst..iLast, inclusive. This routine is only call from within assert()
** statements.
*/
#ifdef SQLITE_DEBUG
int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
int i;
if( pParse->nRangeReg>0
&& pParse->iRangeReg+pParse->nRangeReg > iFirst
&& pParse->iRangeReg <= iLast
){
return 0;
}
for(i=0; i<pParse->nTempReg; i++){
if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
return 0;
}
}
return 1;
}
#endif /* SQLITE_DEBUG */
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_1325_2 |
crossvul-cpp_data_good_1368_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Linux INET6 implementation
* Forwarding Information Database
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Changes:
* Yuji SEKIYA @USAGI: Support default route on router node;
* remove ip6_null_entry from the top of
* routing table.
* Ville Nuorvala: Fixed routing subtrees.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/lwtunnel.h>
#include <net/fib_notifier.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
static struct kmem_cache *fib6_node_kmem __read_mostly;
struct fib6_cleaner {
struct fib6_walker w;
struct net *net;
int (*func)(struct fib6_info *, void *arg);
int sernum;
void *arg;
bool skip_notify;
};
#ifdef CONFIG_IPV6_SUBTREES
#define FWS_INIT FWS_S
#else
#define FWS_INIT FWS_L
#endif
static struct fib6_info *fib6_find_prefix(struct net *net,
struct fib6_table *table,
struct fib6_node *fn);
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_table *table,
struct fib6_node *fn);
static int fib6_walk(struct net *net, struct fib6_walker *w);
static int fib6_walk_continue(struct fib6_walker *w);
/*
* A routing update causes an increase of the serial number on the
* affected subtree. This allows for cached routes to be asynchronously
* tested when modifications are made to the destination cache as a
* result of redirects, path MTU changes, etc.
*/
static void fib6_gc_timer_cb(struct timer_list *t);
#define FOR_WALKERS(net, w) \
list_for_each_entry(w, &(net)->ipv6.fib6_walkers, lh)
static void fib6_walker_link(struct net *net, struct fib6_walker *w)
{
write_lock_bh(&net->ipv6.fib6_walker_lock);
list_add(&w->lh, &net->ipv6.fib6_walkers);
write_unlock_bh(&net->ipv6.fib6_walker_lock);
}
static void fib6_walker_unlink(struct net *net, struct fib6_walker *w)
{
write_lock_bh(&net->ipv6.fib6_walker_lock);
list_del(&w->lh);
write_unlock_bh(&net->ipv6.fib6_walker_lock);
}
static int fib6_new_sernum(struct net *net)
{
int new, old;
do {
old = atomic_read(&net->ipv6.fib6_sernum);
new = old < INT_MAX ? old + 1 : 1;
} while (atomic_cmpxchg(&net->ipv6.fib6_sernum,
old, new) != old);
return new;
}
enum {
FIB6_NO_SERNUM_CHANGE = 0,
};
void fib6_update_sernum(struct net *net, struct fib6_info *f6i)
{
struct fib6_node *fn;
fn = rcu_dereference_protected(f6i->fib6_node,
lockdep_is_held(&f6i->fib6_table->tb6_lock));
if (fn)
fn->fn_sernum = fib6_new_sernum(net);
}
/*
* Auxiliary address test functions for the radix tree.
*
* These assume a 32bit processor (although it will work on
* 64bit processors)
*/
/*
* test bit
*/
#if defined(__LITTLE_ENDIAN)
# define BITOP_BE32_SWIZZLE (0x1F & ~7)
#else
# define BITOP_BE32_SWIZZLE 0
#endif
static __be32 addr_bit_set(const void *token, int fn_bit)
{
const __be32 *addr = token;
/*
* Here,
* 1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)
* is optimized version of
* htonl(1 << ((~fn_bit)&0x1F))
* See include/asm-generic/bitops/le.h.
*/
return (__force __be32)(1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)) &
addr[fn_bit >> 5];
}
struct fib6_info *fib6_info_alloc(gfp_t gfp_flags, bool with_fib6_nh)
{
struct fib6_info *f6i;
size_t sz = sizeof(*f6i);
if (with_fib6_nh)
sz += sizeof(struct fib6_nh);
f6i = kzalloc(sz, gfp_flags);
if (!f6i)
return NULL;
/* fib6_siblings is a union with nh_list, so this initializes both */
INIT_LIST_HEAD(&f6i->fib6_siblings);
refcount_set(&f6i->fib6_ref, 1);
return f6i;
}
void fib6_info_destroy_rcu(struct rcu_head *head)
{
struct fib6_info *f6i = container_of(head, struct fib6_info, rcu);
WARN_ON(f6i->fib6_node);
if (f6i->nh)
nexthop_put(f6i->nh);
else
fib6_nh_release(f6i->fib6_nh);
ip_fib_metrics_put(f6i->fib6_metrics);
kfree(f6i);
}
EXPORT_SYMBOL_GPL(fib6_info_destroy_rcu);
static struct fib6_node *node_alloc(struct net *net)
{
struct fib6_node *fn;
fn = kmem_cache_zalloc(fib6_node_kmem, GFP_ATOMIC);
if (fn)
net->ipv6.rt6_stats->fib_nodes++;
return fn;
}
static void node_free_immediate(struct net *net, struct fib6_node *fn)
{
kmem_cache_free(fib6_node_kmem, fn);
net->ipv6.rt6_stats->fib_nodes--;
}
static void node_free_rcu(struct rcu_head *head)
{
struct fib6_node *fn = container_of(head, struct fib6_node, rcu);
kmem_cache_free(fib6_node_kmem, fn);
}
static void node_free(struct net *net, struct fib6_node *fn)
{
call_rcu(&fn->rcu, node_free_rcu);
net->ipv6.rt6_stats->fib_nodes--;
}
static void fib6_free_table(struct fib6_table *table)
{
inetpeer_invalidate_tree(&table->tb6_peers);
kfree(table);
}
static void fib6_link_table(struct net *net, struct fib6_table *tb)
{
unsigned int h;
/*
* Initialize table lock at a single place to give lockdep a key,
* tables aren't visible prior to being linked to the list.
*/
spin_lock_init(&tb->tb6_lock);
h = tb->tb6_id & (FIB6_TABLE_HASHSZ - 1);
/*
* No protection necessary, this is the only list mutatation
* operation, tables never disappear once they exist.
*/
hlist_add_head_rcu(&tb->tb6_hlist, &net->ipv6.fib_table_hash[h]);
}
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static struct fib6_table *fib6_alloc_table(struct net *net, u32 id)
{
struct fib6_table *table;
table = kzalloc(sizeof(*table), GFP_ATOMIC);
if (table) {
table->tb6_id = id;
rcu_assign_pointer(table->tb6_root.leaf,
net->ipv6.fib6_null_entry);
table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&table->tb6_peers);
}
return table;
}
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
struct fib6_table *tb;
if (id == 0)
id = RT6_TABLE_MAIN;
tb = fib6_get_table(net, id);
if (tb)
return tb;
tb = fib6_alloc_table(net, id);
if (tb)
fib6_link_table(net, tb);
return tb;
}
EXPORT_SYMBOL_GPL(fib6_new_table);
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
struct fib6_table *tb;
struct hlist_head *head;
unsigned int h;
if (id == 0)
id = RT6_TABLE_MAIN;
h = id & (FIB6_TABLE_HASHSZ - 1);
rcu_read_lock();
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
if (tb->tb6_id == id) {
rcu_read_unlock();
return tb;
}
}
rcu_read_unlock();
return NULL;
}
EXPORT_SYMBOL_GPL(fib6_get_table);
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
fib6_link_table(net, net->ipv6.fib6_local_tbl);
}
#else
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
return fib6_get_table(net, id);
}
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
return net->ipv6.fib6_main_tbl;
}
struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
const struct sk_buff *skb,
int flags, pol_lookup_t lookup)
{
struct rt6_info *rt;
rt = lookup(net, net->ipv6.fib6_main_tbl, fl6, skb, flags);
if (rt->dst.error == -EAGAIN) {
ip6_rt_put_flags(rt, flags);
rt = net->ipv6.ip6_null_entry;
if (!(flags & RT6_LOOKUP_F_DST_NOREF))
dst_hold(&rt->dst);
}
return &rt->dst;
}
/* called with rcu lock held; no reference taken on fib6_info */
int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6,
struct fib6_result *res, int flags)
{
return fib6_table_lookup(net, net->ipv6.fib6_main_tbl, oif, fl6,
res, flags);
}
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
}
#endif
unsigned int fib6_tables_seq_read(struct net *net)
{
unsigned int h, fib_seq = 0;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[h];
struct fib6_table *tb;
hlist_for_each_entry_rcu(tb, head, tb6_hlist)
fib_seq += tb->fib_seq;
}
rcu_read_unlock();
return fib_seq;
}
static int call_fib6_entry_notifier(struct notifier_block *nb, struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt)
{
struct fib6_entry_notifier_info info = {
.rt = rt,
};
return call_fib6_notifier(nb, net, event_type, &info.info);
}
int call_fib6_entry_notifiers(struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, event_type, &info.info);
}
int call_fib6_multipath_entry_notifiers(struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt,
unsigned int nsiblings,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
.nsiblings = nsiblings,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, event_type, &info.info);
}
struct fib6_dump_arg {
struct net *net;
struct notifier_block *nb;
};
static void fib6_rt_dump(struct fib6_info *rt, struct fib6_dump_arg *arg)
{
if (rt == arg->net->ipv6.fib6_null_entry)
return;
call_fib6_entry_notifier(arg->nb, arg->net, FIB_EVENT_ENTRY_ADD, rt);
}
static int fib6_node_dump(struct fib6_walker *w)
{
struct fib6_info *rt;
for_each_fib6_walker_rt(w)
fib6_rt_dump(rt, w->args);
w->leaf = NULL;
return 0;
}
static void fib6_table_dump(struct net *net, struct fib6_table *tb,
struct fib6_walker *w)
{
w->root = &tb->tb6_root;
spin_lock_bh(&tb->tb6_lock);
fib6_walk(net, w);
spin_unlock_bh(&tb->tb6_lock);
}
/* Called with rcu_read_lock() */
int fib6_tables_dump(struct net *net, struct notifier_block *nb)
{
struct fib6_dump_arg arg;
struct fib6_walker *w;
unsigned int h;
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_node_dump;
arg.net = net;
arg.nb = nb;
w->args = &arg;
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[h];
struct fib6_table *tb;
hlist_for_each_entry_rcu(tb, head, tb6_hlist)
fib6_table_dump(net, tb, w);
}
kfree(w);
return 0;
}
static int fib6_dump_node(struct fib6_walker *w)
{
int res;
struct fib6_info *rt;
for_each_fib6_walker_rt(w) {
res = rt6_dump_route(rt, w->args, w->skip_in_node);
if (res >= 0) {
/* Frame is full, suspend walking */
w->leaf = rt;
/* We'll restart from this node, so if some routes were
* already dumped, skip them next time.
*/
w->skip_in_node += res;
return 1;
}
w->skip_in_node = 0;
/* Multipath routes are dumped in one route with the
* RTA_MULTIPATH attribute. Jump 'rt' to point to the
* last sibling of this route (no need to dump the
* sibling routes again)
*/
if (rt->fib6_nsiblings)
rt = list_last_entry(&rt->fib6_siblings,
struct fib6_info,
fib6_siblings);
}
w->leaf = NULL;
return 0;
}
static void fib6_dump_end(struct netlink_callback *cb)
{
struct net *net = sock_net(cb->skb->sk);
struct fib6_walker *w = (void *)cb->args[2];
if (w) {
if (cb->args[4]) {
cb->args[4] = 0;
fib6_walker_unlink(net, w);
}
cb->args[2] = 0;
kfree(w);
}
cb->done = (void *)cb->args[3];
cb->args[1] = 3;
}
static int fib6_dump_done(struct netlink_callback *cb)
{
fib6_dump_end(cb);
return cb->done ? cb->done(cb) : 0;
}
static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct fib6_walker *w;
int res;
w = (void *)cb->args[2];
w->root = &table->tb6_root;
if (cb->args[4] == 0) {
w->count = 0;
w->skip = 0;
w->skip_in_node = 0;
spin_lock_bh(&table->tb6_lock);
res = fib6_walk(net, w);
spin_unlock_bh(&table->tb6_lock);
if (res > 0) {
cb->args[4] = 1;
cb->args[5] = w->root->fn_sernum;
}
} else {
if (cb->args[5] != w->root->fn_sernum) {
/* Begin at the root if the tree changed */
cb->args[5] = w->root->fn_sernum;
w->state = FWS_INIT;
w->node = w->root;
w->skip = w->count;
w->skip_in_node = 0;
} else
w->skip = 0;
spin_lock_bh(&table->tb6_lock);
res = fib6_walk_continue(w);
spin_unlock_bh(&table->tb6_lock);
if (res <= 0) {
fib6_walker_unlink(net, w);
cb->args[4] = 0;
}
}
return res;
}
static int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
{
struct rt6_rtnl_dump_arg arg = { .filter.dump_exceptions = true,
.filter.dump_routes = true };
const struct nlmsghdr *nlh = cb->nlh;
struct net *net = sock_net(skb->sk);
unsigned int h, s_h;
unsigned int e = 0, s_e;
struct fib6_walker *w;
struct fib6_table *tb;
struct hlist_head *head;
int res = 0;
if (cb->strict_check) {
int err;
err = ip_valid_fib_dump_req(net, nlh, &arg.filter, cb);
if (err < 0)
return err;
} else if (nlmsg_len(nlh) >= sizeof(struct rtmsg)) {
struct rtmsg *rtm = nlmsg_data(nlh);
if (rtm->rtm_flags & RTM_F_PREFIX)
arg.filter.flags = RTM_F_PREFIX;
}
w = (void *)cb->args[2];
if (!w) {
/* New dump:
*
* 1. hook callback destructor.
*/
cb->args[3] = (long)cb->done;
cb->done = fib6_dump_done;
/*
* 2. allocate and initialize walker.
*/
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_dump_node;
cb->args[2] = (long)w;
}
arg.skb = skb;
arg.cb = cb;
arg.net = net;
w->args = &arg;
if (arg.filter.table_id) {
tb = fib6_get_table(net, arg.filter.table_id);
if (!tb) {
if (arg.filter.dump_all_families)
goto out;
NL_SET_ERR_MSG_MOD(cb->extack, "FIB table does not exist");
return -ENOENT;
}
if (!cb->args[0]) {
res = fib6_dump_table(tb, skb, cb);
if (!res)
cb->args[0] = 1;
}
goto out;
}
s_h = cb->args[0];
s_e = cb->args[1];
rcu_read_lock();
for (h = s_h; h < FIB6_TABLE_HASHSZ; h++, s_e = 0) {
e = 0;
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
if (e < s_e)
goto next;
res = fib6_dump_table(tb, skb, cb);
if (res != 0)
goto out_unlock;
next:
e++;
}
}
out_unlock:
rcu_read_unlock();
cb->args[1] = e;
cb->args[0] = h;
out:
res = res < 0 ? res : skb->len;
if (res <= 0)
fib6_dump_end(cb);
return res;
}
void fib6_metric_set(struct fib6_info *f6i, int metric, u32 val)
{
if (!f6i)
return;
if (f6i->fib6_metrics == &dst_default_metrics) {
struct dst_metrics *p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (!p)
return;
refcount_set(&p->refcnt, 1);
f6i->fib6_metrics = p;
}
f6i->fib6_metrics->metrics[metric - 1] = val;
}
/*
* Routing Table
*
* return the appropriate node for a routing tree "add" operation
* by either creating and inserting or by returning an existing
* node.
*/
static struct fib6_node *fib6_add_1(struct net *net,
struct fib6_table *table,
struct fib6_node *root,
struct in6_addr *addr, int plen,
int offset, int allow_create,
int replace_required,
struct netlink_ext_ack *extack)
{
struct fib6_node *fn, *in, *ln;
struct fib6_node *pn = NULL;
struct rt6key *key;
int bit;
__be32 dir = 0;
RT6_TRACE("fib6_add_1\n");
/* insert node in tree */
fn = root;
do {
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
key = (struct rt6key *)((u8 *)leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit)) {
if (!allow_create) {
if (replace_required) {
NL_SET_ERR_MSG(extack,
"Can not replace route - no match found");
pr_warn("Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("NLM_F_CREATE should be set when creating new route\n");
}
goto insert_above;
}
/*
* Exact match ?
*/
if (plen == fn->fn_bit) {
/* clean up an intermediate node */
if (!(fn->fn_flags & RTN_RTINFO)) {
RCU_INIT_POINTER(fn->leaf, NULL);
fib6_info_release(leaf);
/* remove null_entry in the root node */
} else if (fn->fn_flags & RTN_TL_ROOT &&
rcu_access_pointer(fn->leaf) ==
net->ipv6.fib6_null_entry) {
RCU_INIT_POINTER(fn->leaf, NULL);
}
return fn;
}
/*
* We have more bits to go
*/
/* Try to walk down on tree. */
dir = addr_bit_set(addr, fn->fn_bit);
pn = fn;
fn = dir ?
rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock)) :
rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
} while (fn);
if (!allow_create) {
/* We should not create new node because
* NLM_F_REPLACE was specified without NLM_F_CREATE
* I assume it is safe to require NLM_F_CREATE when
* REPLACE flag is used! Later we may want to remove the
* check for replace_required, because according
* to netlink specification, NLM_F_CREATE
* MUST be specified if new route is created.
* That would keep IPv6 consistent with IPv4
*/
if (replace_required) {
NL_SET_ERR_MSG(extack,
"Can not replace route - no match found");
pr_warn("Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("NLM_F_CREATE should be set when creating new route\n");
}
/*
* We walked to the bottom of tree.
* Create new leaf node without children.
*/
ln = node_alloc(net);
if (!ln)
return ERR_PTR(-ENOMEM);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, pn);
if (dir)
rcu_assign_pointer(pn->right, ln);
else
rcu_assign_pointer(pn->left, ln);
return ln;
insert_above:
/*
* split since we don't have a common prefix anymore or
* we have a less significant route.
* we've to insert an intermediate node on the list
* this new node will point to the one we need to create
* and the current
*/
pn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
/* find 1st bit in difference between the 2 addrs.
See comment in __ipv6_addr_diff: bit may be an invalid value,
but if it is >= plen, the value is ignored in any case.
*/
bit = __ipv6_addr_diff(addr, &key->addr, sizeof(*addr));
/*
* (intermediate)[in]
* / \
* (new leaf node)[ln] (old node)[fn]
*/
if (plen > bit) {
in = node_alloc(net);
ln = node_alloc(net);
if (!in || !ln) {
if (in)
node_free_immediate(net, in);
if (ln)
node_free_immediate(net, ln);
return ERR_PTR(-ENOMEM);
}
/*
* new intermediate node.
* RTN_RTINFO will
* be off since that an address that chooses one of
* the branches would not match less specific routes
* in the other branch
*/
in->fn_bit = bit;
RCU_INIT_POINTER(in->parent, pn);
in->leaf = fn->leaf;
fib6_info_hold(rcu_dereference_protected(in->leaf,
lockdep_is_held(&table->tb6_lock)));
/* update parent pointer */
if (dir)
rcu_assign_pointer(pn->right, in);
else
rcu_assign_pointer(pn->left, in);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, in);
rcu_assign_pointer(fn->parent, in);
if (addr_bit_set(addr, bit)) {
rcu_assign_pointer(in->right, ln);
rcu_assign_pointer(in->left, fn);
} else {
rcu_assign_pointer(in->left, ln);
rcu_assign_pointer(in->right, fn);
}
} else { /* plen <= bit */
/*
* (new leaf node)[ln]
* / \
* (old node)[fn] NULL
*/
ln = node_alloc(net);
if (!ln)
return ERR_PTR(-ENOMEM);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, pn);
if (addr_bit_set(&key->addr, plen))
RCU_INIT_POINTER(ln->right, fn);
else
RCU_INIT_POINTER(ln->left, fn);
rcu_assign_pointer(fn->parent, ln);
if (dir)
rcu_assign_pointer(pn->right, ln);
else
rcu_assign_pointer(pn->left, ln);
}
return ln;
}
static void __fib6_drop_pcpu_from(struct fib6_nh *fib6_nh,
const struct fib6_info *match,
const struct fib6_table *table)
{
int cpu;
if (!fib6_nh->rt6i_pcpu)
return;
/* release the reference to this fib entry from
* all of its cached pcpu routes
*/
for_each_possible_cpu(cpu) {
struct rt6_info **ppcpu_rt;
struct rt6_info *pcpu_rt;
ppcpu_rt = per_cpu_ptr(fib6_nh->rt6i_pcpu, cpu);
pcpu_rt = *ppcpu_rt;
/* only dropping the 'from' reference if the cached route
* is using 'match'. The cached pcpu_rt->from only changes
* from a fib6_info to NULL (ip6_dst_destroy); it can never
* change from one fib6_info reference to another
*/
if (pcpu_rt && rcu_access_pointer(pcpu_rt->from) == match) {
struct fib6_info *from;
from = xchg((__force struct fib6_info **)&pcpu_rt->from, NULL);
fib6_info_release(from);
}
}
}
struct fib6_nh_pcpu_arg {
struct fib6_info *from;
const struct fib6_table *table;
};
static int fib6_nh_drop_pcpu_from(struct fib6_nh *nh, void *_arg)
{
struct fib6_nh_pcpu_arg *arg = _arg;
__fib6_drop_pcpu_from(nh, arg->from, arg->table);
return 0;
}
static void fib6_drop_pcpu_from(struct fib6_info *f6i,
const struct fib6_table *table)
{
/* Make sure rt6_make_pcpu_route() wont add other percpu routes
* while we are cleaning them here.
*/
f6i->fib6_destroying = 1;
mb(); /* paired with the cmpxchg() in rt6_make_pcpu_route() */
if (f6i->nh) {
struct fib6_nh_pcpu_arg arg = {
.from = f6i,
.table = table
};
nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_drop_pcpu_from,
&arg);
} else {
struct fib6_nh *fib6_nh;
fib6_nh = f6i->fib6_nh;
__fib6_drop_pcpu_from(fib6_nh, f6i, table);
}
}
static void fib6_purge_rt(struct fib6_info *rt, struct fib6_node *fn,
struct net *net)
{
struct fib6_table *table = rt->fib6_table;
fib6_drop_pcpu_from(rt, table);
if (rt->nh && !list_empty(&rt->nh_list))
list_del_init(&rt->nh_list);
if (refcount_read(&rt->fib6_ref) != 1) {
/* This route is used as dummy address holder in some split
* nodes. It is not leaked, but it still holds other resources,
* which must be released in time. So, scan ascendant nodes
* and replace dummy references to this route with references
* to still alive ones.
*/
while (fn) {
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *new_leaf;
if (!(fn->fn_flags & RTN_RTINFO) && leaf == rt) {
new_leaf = fib6_find_prefix(net, table, fn);
fib6_info_hold(new_leaf);
rcu_assign_pointer(fn->leaf, new_leaf);
fib6_info_release(rt);
}
fn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
}
}
}
/*
* Insert routing information in a node.
*/
static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
struct nl_info *info,
struct netlink_ext_ack *extack)
{
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&rt->fib6_table->tb6_lock));
struct fib6_info *iter = NULL;
struct fib6_info __rcu **ins;
struct fib6_info __rcu **fallback_ins = NULL;
int replace = (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_REPLACE));
int add = (!info->nlh ||
(info->nlh->nlmsg_flags & NLM_F_CREATE));
int found = 0;
bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
u16 nlflags = NLM_F_EXCL;
int err;
if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_APPEND))
nlflags |= NLM_F_APPEND;
ins = &fn->leaf;
for (iter = leaf; iter;
iter = rcu_dereference_protected(iter->fib6_next,
lockdep_is_held(&rt->fib6_table->tb6_lock))) {
/*
* Search for duplicates
*/
if (iter->fib6_metric == rt->fib6_metric) {
/*
* Same priority level
*/
if (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_EXCL))
return -EEXIST;
nlflags &= ~NLM_F_EXCL;
if (replace) {
if (rt_can_ecmp == rt6_qualify_for_ecmp(iter)) {
found++;
break;
}
if (rt_can_ecmp)
fallback_ins = fallback_ins ?: ins;
goto next_iter;
}
if (rt6_duplicate_nexthop(iter, rt)) {
if (rt->fib6_nsiblings)
rt->fib6_nsiblings = 0;
if (!(iter->fib6_flags & RTF_EXPIRES))
return -EEXIST;
if (!(rt->fib6_flags & RTF_EXPIRES))
fib6_clean_expires(iter);
else
fib6_set_expires(iter, rt->expires);
if (rt->fib6_pmtu)
fib6_metric_set(iter, RTAX_MTU,
rt->fib6_pmtu);
return -EEXIST;
}
/* If we have the same destination and the same metric,
* but not the same gateway, then the route we try to
* add is sibling to this route, increment our counter
* of siblings, and later we will add our route to the
* list.
* Only static routes (which don't have flag
* RTF_EXPIRES) are used for ECMPv6.
*
* To avoid long list, we only had siblings if the
* route have a gateway.
*/
if (rt_can_ecmp &&
rt6_qualify_for_ecmp(iter))
rt->fib6_nsiblings++;
}
if (iter->fib6_metric > rt->fib6_metric)
break;
next_iter:
ins = &iter->fib6_next;
}
if (fallback_ins && !found) {
/* No ECMP-able route found, replace first non-ECMP one */
ins = fallback_ins;
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
found++;
}
/* Reset round-robin state, if necessary */
if (ins == &fn->leaf)
fn->rr_ptr = NULL;
/* Link this route to others same route. */
if (rt->fib6_nsiblings) {
unsigned int fib6_nsiblings;
struct fib6_info *sibling, *temp_sibling;
/* Find the first route that have the same metric */
sibling = leaf;
while (sibling) {
if (sibling->fib6_metric == rt->fib6_metric &&
rt6_qualify_for_ecmp(sibling)) {
list_add_tail(&rt->fib6_siblings,
&sibling->fib6_siblings);
break;
}
sibling = rcu_dereference_protected(sibling->fib6_next,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
/* For each sibling in the list, increment the counter of
* siblings. BUG() if counters does not match, list of siblings
* is broken!
*/
fib6_nsiblings = 0;
list_for_each_entry_safe(sibling, temp_sibling,
&rt->fib6_siblings, fib6_siblings) {
sibling->fib6_nsiblings++;
BUG_ON(sibling->fib6_nsiblings != rt->fib6_nsiblings);
fib6_nsiblings++;
}
BUG_ON(fib6_nsiblings != rt->fib6_nsiblings);
rt6_multipath_rebalance(temp_sibling);
}
/*
* insert node
*/
if (!replace) {
if (!add)
pr_warn("NLM_F_CREATE should be set when creating new route\n");
add:
nlflags |= NLM_F_CREATE;
if (!info->skip_notify_kernel) {
err = call_fib6_entry_notifiers(info->nl_net,
FIB_EVENT_ENTRY_ADD,
rt, extack);
if (err) {
struct fib6_info *sibling, *next_sibling;
/* If the route has siblings, then it first
* needs to be unlinked from them.
*/
if (!rt->fib6_nsiblings)
return err;
list_for_each_entry_safe(sibling, next_sibling,
&rt->fib6_siblings,
fib6_siblings)
sibling->fib6_nsiblings--;
rt->fib6_nsiblings = 0;
list_del_init(&rt->fib6_siblings);
rt6_multipath_rebalance(next_sibling);
return err;
}
}
rcu_assign_pointer(rt->fib6_next, iter);
fib6_info_hold(rt);
rcu_assign_pointer(rt->fib6_node, fn);
rcu_assign_pointer(*ins, rt);
if (!info->skip_notify)
inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
} else {
int nsiblings;
if (!found) {
if (add)
goto add;
pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
return -ENOENT;
}
if (!info->skip_notify_kernel) {
err = call_fib6_entry_notifiers(info->nl_net,
FIB_EVENT_ENTRY_REPLACE,
rt, extack);
if (err)
return err;
}
fib6_info_hold(rt);
rcu_assign_pointer(rt->fib6_node, fn);
rt->fib6_next = iter->fib6_next;
rcu_assign_pointer(*ins, rt);
if (!info->skip_notify)
inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE);
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
nsiblings = iter->fib6_nsiblings;
iter->fib6_node = NULL;
fib6_purge_rt(iter, fn, info->nl_net);
if (rcu_access_pointer(fn->rr_ptr) == iter)
fn->rr_ptr = NULL;
fib6_info_release(iter);
if (nsiblings) {
/* Replacing an ECMP route, remove all siblings */
ins = &rt->fib6_next;
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
while (iter) {
if (iter->fib6_metric > rt->fib6_metric)
break;
if (rt6_qualify_for_ecmp(iter)) {
*ins = iter->fib6_next;
iter->fib6_node = NULL;
fib6_purge_rt(iter, fn, info->nl_net);
if (rcu_access_pointer(fn->rr_ptr) == iter)
fn->rr_ptr = NULL;
fib6_info_release(iter);
nsiblings--;
info->nl_net->ipv6.rt6_stats->fib_rt_entries--;
} else {
ins = &iter->fib6_next;
}
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
WARN_ON(nsiblings != 0);
}
}
return 0;
}
static void fib6_start_gc(struct net *net, struct fib6_info *rt)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer) &&
(rt->fib6_flags & RTF_EXPIRES))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
void fib6_force_start_gc(struct net *net)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
static void __fib6_update_sernum_upto_root(struct fib6_info *rt,
int sernum)
{
struct fib6_node *fn = rcu_dereference_protected(rt->fib6_node,
lockdep_is_held(&rt->fib6_table->tb6_lock));
/* paired with smp_rmb() in rt6_get_cookie_safe() */
smp_wmb();
while (fn) {
fn->fn_sernum = sernum;
fn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
}
void fib6_update_sernum_upto_root(struct net *net, struct fib6_info *rt)
{
__fib6_update_sernum_upto_root(rt, fib6_new_sernum(net));
}
/* allow ipv4 to update sernum via ipv6_stub */
void fib6_update_sernum_stub(struct net *net, struct fib6_info *f6i)
{
spin_lock_bh(&f6i->fib6_table->tb6_lock);
fib6_update_sernum_upto_root(net, f6i);
spin_unlock_bh(&f6i->fib6_table->tb6_lock);
}
/*
* Add routing information to the routing tree.
* <destination addr>/<source addr>
* with source addr info in sub-trees
* Need to own table->tb6_lock
*/
int fib6_add(struct fib6_node *root, struct fib6_info *rt,
struct nl_info *info, struct netlink_ext_ack *extack)
{
struct fib6_table *table = rt->fib6_table;
struct fib6_node *fn, *pn = NULL;
int err = -ENOMEM;
int allow_create = 1;
int replace_required = 0;
int sernum = fib6_new_sernum(info->nl_net);
if (info->nlh) {
if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
allow_create = 0;
if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
replace_required = 1;
}
if (!allow_create && !replace_required)
pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
fn = fib6_add_1(info->nl_net, table, root,
&rt->fib6_dst.addr, rt->fib6_dst.plen,
offsetof(struct fib6_info, fib6_dst), allow_create,
replace_required, extack);
if (IS_ERR(fn)) {
err = PTR_ERR(fn);
fn = NULL;
goto out;
}
pn = fn;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->fib6_src.plen) {
struct fib6_node *sn;
if (!rcu_access_pointer(fn->subtree)) {
struct fib6_node *sfn;
/*
* Create subtree.
*
* fn[main tree]
* |
* sfn[subtree root]
* \
* sn[new leaf node]
*/
/* Create subtree root node */
sfn = node_alloc(info->nl_net);
if (!sfn)
goto failure;
fib6_info_hold(info->nl_net->ipv6.fib6_null_entry);
rcu_assign_pointer(sfn->leaf,
info->nl_net->ipv6.fib6_null_entry);
sfn->fn_flags = RTN_ROOT;
/* Now add the first leaf node to new subtree */
sn = fib6_add_1(info->nl_net, table, sfn,
&rt->fib6_src.addr, rt->fib6_src.plen,
offsetof(struct fib6_info, fib6_src),
allow_create, replace_required, extack);
if (IS_ERR(sn)) {
/* If it is failed, discard just allocated
root, and then (in failure) stale node
in main tree.
*/
node_free_immediate(info->nl_net, sfn);
err = PTR_ERR(sn);
goto failure;
}
/* Now link new subtree to main tree */
rcu_assign_pointer(sfn->parent, fn);
rcu_assign_pointer(fn->subtree, sfn);
} else {
sn = fib6_add_1(info->nl_net, table, FIB6_SUBTREE(fn),
&rt->fib6_src.addr, rt->fib6_src.plen,
offsetof(struct fib6_info, fib6_src),
allow_create, replace_required, extack);
if (IS_ERR(sn)) {
err = PTR_ERR(sn);
goto failure;
}
}
if (!rcu_access_pointer(fn->leaf)) {
if (fn->fn_flags & RTN_TL_ROOT) {
/* put back null_entry for root node */
rcu_assign_pointer(fn->leaf,
info->nl_net->ipv6.fib6_null_entry);
} else {
fib6_info_hold(rt);
rcu_assign_pointer(fn->leaf, rt);
}
}
fn = sn;
}
#endif
err = fib6_add_rt2node(fn, rt, info, extack);
if (!err) {
if (rt->nh)
list_add(&rt->nh_list, &rt->nh->f6i_list);
__fib6_update_sernum_upto_root(rt, sernum);
fib6_start_gc(info->nl_net, rt);
}
out:
if (err) {
#ifdef CONFIG_IPV6_SUBTREES
/*
* If fib6_add_1 has cleared the old leaf pointer in the
* super-tree leaf node we have to find a new one for it.
*/
if (pn != fn) {
struct fib6_info *pn_leaf =
rcu_dereference_protected(pn->leaf,
lockdep_is_held(&table->tb6_lock));
if (pn_leaf == rt) {
pn_leaf = NULL;
RCU_INIT_POINTER(pn->leaf, NULL);
fib6_info_release(rt);
}
if (!pn_leaf && !(pn->fn_flags & RTN_RTINFO)) {
pn_leaf = fib6_find_prefix(info->nl_net, table,
pn);
#if RT6_DEBUG >= 2
if (!pn_leaf) {
WARN_ON(!pn_leaf);
pn_leaf =
info->nl_net->ipv6.fib6_null_entry;
}
#endif
fib6_info_hold(pn_leaf);
rcu_assign_pointer(pn->leaf, pn_leaf);
}
}
#endif
goto failure;
}
return err;
failure:
/* fn->leaf could be NULL and fib6_repair_tree() needs to be called if:
* 1. fn is an intermediate node and we failed to add the new
* route to it in both subtree creation failure and fib6_add_rt2node()
* failure case.
* 2. fn is the root node in the table and we fail to add the first
* default route to it.
*/
if (fn &&
(!(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)) ||
(fn->fn_flags & RTN_TL_ROOT &&
!rcu_access_pointer(fn->leaf))))
fib6_repair_tree(info->nl_net, table, fn);
return err;
}
/*
* Routing tree lookup
*
*/
struct lookup_args {
int offset; /* key offset on fib6_info */
const struct in6_addr *addr; /* search key */
};
static struct fib6_node *fib6_node_lookup_1(struct fib6_node *root,
struct lookup_args *args)
{
struct fib6_node *fn;
__be32 dir;
if (unlikely(args->offset == 0))
return NULL;
/*
* Descend on a tree
*/
fn = root;
for (;;) {
struct fib6_node *next;
dir = addr_bit_set(args->addr, fn->fn_bit);
next = dir ? rcu_dereference(fn->right) :
rcu_dereference(fn->left);
if (next) {
fn = next;
continue;
}
break;
}
while (fn) {
struct fib6_node *subtree = FIB6_SUBTREE(fn);
if (subtree || fn->fn_flags & RTN_RTINFO) {
struct fib6_info *leaf = rcu_dereference(fn->leaf);
struct rt6key *key;
if (!leaf)
goto backtrack;
key = (struct rt6key *) ((u8 *)leaf + args->offset);
if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
#ifdef CONFIG_IPV6_SUBTREES
if (subtree) {
struct fib6_node *sfn;
sfn = fib6_node_lookup_1(subtree,
args + 1);
if (!sfn)
goto backtrack;
fn = sfn;
}
#endif
if (fn->fn_flags & RTN_RTINFO)
return fn;
}
}
backtrack:
if (fn->fn_flags & RTN_ROOT)
break;
fn = rcu_dereference(fn->parent);
}
return NULL;
}
/* called with rcu_read_lock() held
*/
struct fib6_node *fib6_node_lookup(struct fib6_node *root,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct fib6_node *fn;
struct lookup_args args[] = {
{
.offset = offsetof(struct fib6_info, fib6_dst),
.addr = daddr,
},
#ifdef CONFIG_IPV6_SUBTREES
{
.offset = offsetof(struct fib6_info, fib6_src),
.addr = saddr,
},
#endif
{
.offset = 0, /* sentinel */
}
};
fn = fib6_node_lookup_1(root, daddr ? args : args + 1);
if (!fn || fn->fn_flags & RTN_TL_ROOT)
fn = root;
return fn;
}
/*
* Get node with specified destination prefix (and source prefix,
* if subtrees are used)
* exact_match == true means we try to find fn with exact match of
* the passed in prefix addr
* exact_match == false means we try to find fn with longest prefix
* match of the passed in prefix addr. This is useful for finding fn
* for cached route as it will be stored in the exception table under
* the node with longest prefix length.
*/
static struct fib6_node *fib6_locate_1(struct fib6_node *root,
const struct in6_addr *addr,
int plen, int offset,
bool exact_match)
{
struct fib6_node *fn, *prev = NULL;
for (fn = root; fn ; ) {
struct fib6_info *leaf = rcu_dereference(fn->leaf);
struct rt6key *key;
/* This node is being deleted */
if (!leaf) {
if (plen <= fn->fn_bit)
goto out;
else
goto next;
}
key = (struct rt6key *)((u8 *)leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
goto out;
if (plen == fn->fn_bit)
return fn;
if (fn->fn_flags & RTN_RTINFO)
prev = fn;
next:
/*
* We have more bits to go
*/
if (addr_bit_set(addr, fn->fn_bit))
fn = rcu_dereference(fn->right);
else
fn = rcu_dereference(fn->left);
}
out:
if (exact_match)
return NULL;
else
return prev;
}
struct fib6_node *fib6_locate(struct fib6_node *root,
const struct in6_addr *daddr, int dst_len,
const struct in6_addr *saddr, int src_len,
bool exact_match)
{
struct fib6_node *fn;
fn = fib6_locate_1(root, daddr, dst_len,
offsetof(struct fib6_info, fib6_dst),
exact_match);
#ifdef CONFIG_IPV6_SUBTREES
if (src_len) {
WARN_ON(saddr == NULL);
if (fn) {
struct fib6_node *subtree = FIB6_SUBTREE(fn);
if (subtree) {
fn = fib6_locate_1(subtree, saddr, src_len,
offsetof(struct fib6_info, fib6_src),
exact_match);
}
}
}
#endif
if (fn && fn->fn_flags & RTN_RTINFO)
return fn;
return NULL;
}
/*
* Deletion
*
*/
static struct fib6_info *fib6_find_prefix(struct net *net,
struct fib6_table *table,
struct fib6_node *fn)
{
struct fib6_node *child_left, *child_right;
if (fn->fn_flags & RTN_ROOT)
return net->ipv6.fib6_null_entry;
while (fn) {
child_left = rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
child_right = rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock));
if (child_left)
return rcu_dereference_protected(child_left->leaf,
lockdep_is_held(&table->tb6_lock));
if (child_right)
return rcu_dereference_protected(child_right->leaf,
lockdep_is_held(&table->tb6_lock));
fn = FIB6_SUBTREE(fn);
}
return NULL;
}
/*
* Called to trim the tree of intermediate nodes when possible. "fn"
* is the node we want to try and remove.
* Need to own table->tb6_lock
*/
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_table *table,
struct fib6_node *fn)
{
int children;
int nstate;
struct fib6_node *child;
struct fib6_walker *w;
int iter = 0;
/* Set fn->leaf to null_entry for root node. */
if (fn->fn_flags & RTN_TL_ROOT) {
rcu_assign_pointer(fn->leaf, net->ipv6.fib6_null_entry);
return fn;
}
for (;;) {
struct fib6_node *fn_r = rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *fn_l = rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn_r = rcu_dereference_protected(pn->right,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn_l = rcu_dereference_protected(pn->left,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *fn_leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *pn_leaf = rcu_dereference_protected(pn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *new_fn_leaf;
RT6_TRACE("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
iter++;
WARN_ON(fn->fn_flags & RTN_RTINFO);
WARN_ON(fn->fn_flags & RTN_TL_ROOT);
WARN_ON(fn_leaf);
children = 0;
child = NULL;
if (fn_r)
child = fn_r, children |= 1;
if (fn_l)
child = fn_l, children |= 2;
if (children == 3 || FIB6_SUBTREE(fn)
#ifdef CONFIG_IPV6_SUBTREES
/* Subtree root (i.e. fn) may have one child */
|| (children && fn->fn_flags & RTN_ROOT)
#endif
) {
new_fn_leaf = fib6_find_prefix(net, table, fn);
#if RT6_DEBUG >= 2
if (!new_fn_leaf) {
WARN_ON(!new_fn_leaf);
new_fn_leaf = net->ipv6.fib6_null_entry;
}
#endif
fib6_info_hold(new_fn_leaf);
rcu_assign_pointer(fn->leaf, new_fn_leaf);
return pn;
}
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
RCU_INIT_POINTER(pn->subtree, NULL);
nstate = FWS_L;
} else {
WARN_ON(fn->fn_flags & RTN_ROOT);
#endif
if (pn_r == fn)
rcu_assign_pointer(pn->right, child);
else if (pn_l == fn)
rcu_assign_pointer(pn->left, child);
#if RT6_DEBUG >= 2
else
WARN_ON(1);
#endif
if (child)
rcu_assign_pointer(child->parent, pn);
nstate = FWS_R;
#ifdef CONFIG_IPV6_SUBTREES
}
#endif
read_lock(&net->ipv6.fib6_walker_lock);
FOR_WALKERS(net, w) {
if (!child) {
if (w->node == fn) {
RT6_TRACE("W %p adjusted by delnode 1, s=%d/%d\n", w, w->state, nstate);
w->node = pn;
w->state = nstate;
}
} else {
if (w->node == fn) {
w->node = child;
if (children&2) {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state >= FWS_R ? FWS_U : FWS_INIT;
} else {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state >= FWS_C ? FWS_U : FWS_INIT;
}
}
}
}
read_unlock(&net->ipv6.fib6_walker_lock);
node_free(net, fn);
if (pn->fn_flags & RTN_RTINFO || FIB6_SUBTREE(pn))
return pn;
RCU_INIT_POINTER(pn->leaf, NULL);
fib6_info_release(pn_leaf);
fn = pn;
}
}
static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,
struct fib6_info __rcu **rtp, struct nl_info *info)
{
struct fib6_walker *w;
struct fib6_info *rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&table->tb6_lock));
struct net *net = info->nl_net;
RT6_TRACE("fib6_del_route\n");
/* Unlink it */
*rtp = rt->fib6_next;
rt->fib6_node = NULL;
net->ipv6.rt6_stats->fib_rt_entries--;
net->ipv6.rt6_stats->fib_discarded_routes++;
/* Flush all cached dst in exception table */
rt6_flush_exceptions(rt);
/* Reset round-robin state, if necessary */
if (rcu_access_pointer(fn->rr_ptr) == rt)
fn->rr_ptr = NULL;
/* Remove this entry from other siblings */
if (rt->fib6_nsiblings) {
struct fib6_info *sibling, *next_sibling;
list_for_each_entry_safe(sibling, next_sibling,
&rt->fib6_siblings, fib6_siblings)
sibling->fib6_nsiblings--;
rt->fib6_nsiblings = 0;
list_del_init(&rt->fib6_siblings);
rt6_multipath_rebalance(next_sibling);
}
/* Adjust walkers */
read_lock(&net->ipv6.fib6_walker_lock);
FOR_WALKERS(net, w) {
if (w->state == FWS_C && w->leaf == rt) {
RT6_TRACE("walker %p adjusted by delroute\n", w);
w->leaf = rcu_dereference_protected(rt->fib6_next,
lockdep_is_held(&table->tb6_lock));
if (!w->leaf)
w->state = FWS_U;
}
}
read_unlock(&net->ipv6.fib6_walker_lock);
/* If it was last route, call fib6_repair_tree() to:
* 1. For root node, put back null_entry as how the table was created.
* 2. For other nodes, expunge its radix tree node.
*/
if (!rcu_access_pointer(fn->leaf)) {
if (!(fn->fn_flags & RTN_TL_ROOT)) {
fn->fn_flags &= ~RTN_RTINFO;
net->ipv6.rt6_stats->fib_route_nodes--;
}
fn = fib6_repair_tree(net, table, fn);
}
fib6_purge_rt(rt, fn, net);
if (!info->skip_notify_kernel)
call_fib6_entry_notifiers(net, FIB_EVENT_ENTRY_DEL, rt, NULL);
if (!info->skip_notify)
inet6_rt_notify(RTM_DELROUTE, rt, info, 0);
fib6_info_release(rt);
}
/* Need to own table->tb6_lock */
int fib6_del(struct fib6_info *rt, struct nl_info *info)
{
struct fib6_node *fn = rcu_dereference_protected(rt->fib6_node,
lockdep_is_held(&rt->fib6_table->tb6_lock));
struct fib6_table *table = rt->fib6_table;
struct net *net = info->nl_net;
struct fib6_info __rcu **rtp;
struct fib6_info __rcu **rtp_next;
if (!fn || rt == net->ipv6.fib6_null_entry)
return -ENOENT;
WARN_ON(!(fn->fn_flags & RTN_RTINFO));
/*
* Walk the leaf entries looking for ourself
*/
for (rtp = &fn->leaf; *rtp; rtp = rtp_next) {
struct fib6_info *cur = rcu_dereference_protected(*rtp,
lockdep_is_held(&table->tb6_lock));
if (rt == cur) {
fib6_del_route(table, fn, rtp, info);
return 0;
}
rtp_next = &cur->fib6_next;
}
return -ENOENT;
}
/*
* Tree traversal function.
*
* Certainly, it is not interrupt safe.
* However, it is internally reenterable wrt itself and fib6_add/fib6_del.
* It means, that we can modify tree during walking
* and use this function for garbage collection, clone pruning,
* cleaning tree when a device goes down etc. etc.
*
* It guarantees that every node will be traversed,
* and that it will be traversed only once.
*
* Callback function w->func may return:
* 0 -> continue walking.
* positive value -> walking is suspended (used by tree dumps,
* and probably by gc, if it will be split to several slices)
* negative value -> terminate walking.
*
* The function itself returns:
* 0 -> walk is complete.
* >0 -> walk is incomplete (i.e. suspended)
* <0 -> walk is terminated by an error.
*
* This function is called with tb6_lock held.
*/
static int fib6_walk_continue(struct fib6_walker *w)
{
struct fib6_node *fn, *pn, *left, *right;
/* w->root should always be table->tb6_root */
WARN_ON_ONCE(!(w->root->fn_flags & RTN_TL_ROOT));
for (;;) {
fn = w->node;
if (!fn)
return 0;
switch (w->state) {
#ifdef CONFIG_IPV6_SUBTREES
case FWS_S:
if (FIB6_SUBTREE(fn)) {
w->node = FIB6_SUBTREE(fn);
continue;
}
w->state = FWS_L;
#endif
/* fall through */
case FWS_L:
left = rcu_dereference_protected(fn->left, 1);
if (left) {
w->node = left;
w->state = FWS_INIT;
continue;
}
w->state = FWS_R;
/* fall through */
case FWS_R:
right = rcu_dereference_protected(fn->right, 1);
if (right) {
w->node = right;
w->state = FWS_INIT;
continue;
}
w->state = FWS_C;
w->leaf = rcu_dereference_protected(fn->leaf, 1);
/* fall through */
case FWS_C:
if (w->leaf && fn->fn_flags & RTN_RTINFO) {
int err;
if (w->skip) {
w->skip--;
goto skip;
}
err = w->func(w);
if (err)
return err;
w->count++;
continue;
}
skip:
w->state = FWS_U;
/* fall through */
case FWS_U:
if (fn == w->root)
return 0;
pn = rcu_dereference_protected(fn->parent, 1);
left = rcu_dereference_protected(pn->left, 1);
right = rcu_dereference_protected(pn->right, 1);
w->node = pn;
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
w->state = FWS_L;
continue;
}
#endif
if (left == fn) {
w->state = FWS_R;
continue;
}
if (right == fn) {
w->state = FWS_C;
w->leaf = rcu_dereference_protected(w->node->leaf, 1);
continue;
}
#if RT6_DEBUG >= 2
WARN_ON(1);
#endif
}
}
}
static int fib6_walk(struct net *net, struct fib6_walker *w)
{
int res;
w->state = FWS_INIT;
w->node = w->root;
fib6_walker_link(net, w);
res = fib6_walk_continue(w);
if (res <= 0)
fib6_walker_unlink(net, w);
return res;
}
static int fib6_clean_node(struct fib6_walker *w)
{
int res;
struct fib6_info *rt;
struct fib6_cleaner *c = container_of(w, struct fib6_cleaner, w);
struct nl_info info = {
.nl_net = c->net,
.skip_notify = c->skip_notify,
};
if (c->sernum != FIB6_NO_SERNUM_CHANGE &&
w->node->fn_sernum != c->sernum)
w->node->fn_sernum = c->sernum;
if (!c->func) {
WARN_ON_ONCE(c->sernum == FIB6_NO_SERNUM_CHANGE);
w->leaf = NULL;
return 0;
}
for_each_fib6_walker_rt(w) {
res = c->func(rt, c->arg);
if (res == -1) {
w->leaf = rt;
res = fib6_del(rt, &info);
if (res) {
#if RT6_DEBUG >= 2
pr_debug("%s: del failed: rt=%p@%p err=%d\n",
__func__, rt,
rcu_access_pointer(rt->fib6_node),
res);
#endif
continue;
}
return 0;
} else if (res == -2) {
if (WARN_ON(!rt->fib6_nsiblings))
continue;
rt = list_last_entry(&rt->fib6_siblings,
struct fib6_info, fib6_siblings);
continue;
}
WARN_ON(res != 0);
}
w->leaf = rt;
return 0;
}
/*
* Convenient frontend to tree walker.
*
* func is called on each route.
* It may return -2 -> skip multipath route.
* -1 -> delete this route.
* 0 -> continue walking
*/
static void fib6_clean_tree(struct net *net, struct fib6_node *root,
int (*func)(struct fib6_info *, void *arg),
int sernum, void *arg, bool skip_notify)
{
struct fib6_cleaner c;
c.w.root = root;
c.w.func = fib6_clean_node;
c.w.count = 0;
c.w.skip = 0;
c.w.skip_in_node = 0;
c.func = func;
c.sernum = sernum;
c.arg = arg;
c.net = net;
c.skip_notify = skip_notify;
fib6_walk(net, &c.w);
}
static void __fib6_clean_all(struct net *net,
int (*func)(struct fib6_info *, void *),
int sernum, void *arg, bool skip_notify)
{
struct fib6_table *table;
struct hlist_head *head;
unsigned int h;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(table, head, tb6_hlist) {
spin_lock_bh(&table->tb6_lock);
fib6_clean_tree(net, &table->tb6_root,
func, sernum, arg, skip_notify);
spin_unlock_bh(&table->tb6_lock);
}
}
rcu_read_unlock();
}
void fib6_clean_all(struct net *net, int (*func)(struct fib6_info *, void *),
void *arg)
{
__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, false);
}
void fib6_clean_all_skip_notify(struct net *net,
int (*func)(struct fib6_info *, void *),
void *arg)
{
__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, true);
}
static void fib6_flush_trees(struct net *net)
{
int new_sernum = fib6_new_sernum(net);
__fib6_clean_all(net, NULL, new_sernum, NULL, false);
}
/*
* Garbage collection
*/
static int fib6_age(struct fib6_info *rt, void *arg)
{
struct fib6_gc_args *gc_args = arg;
unsigned long now = jiffies;
/*
* check addrconf expiration here.
* Routes are expired even if they are in use.
*/
if (rt->fib6_flags & RTF_EXPIRES && rt->expires) {
if (time_after(now, rt->expires)) {
RT6_TRACE("expiring %p\n", rt);
return -1;
}
gc_args->more++;
}
/* Also age clones in the exception table.
* Note, that clones are aged out
* only if they are not in use now.
*/
rt6_age_exceptions(rt, gc_args, now);
return 0;
}
void fib6_run_gc(unsigned long expires, struct net *net, bool force)
{
struct fib6_gc_args gc_args;
unsigned long now;
if (force) {
spin_lock_bh(&net->ipv6.fib6_gc_lock);
} else if (!spin_trylock_bh(&net->ipv6.fib6_gc_lock)) {
mod_timer(&net->ipv6.ip6_fib_timer, jiffies + HZ);
return;
}
gc_args.timeout = expires ? (int)expires :
net->ipv6.sysctl.ip6_rt_gc_interval;
gc_args.more = 0;
fib6_clean_all(net, fib6_age, &gc_args);
now = jiffies;
net->ipv6.ip6_rt_last_gc = now;
if (gc_args.more)
mod_timer(&net->ipv6.ip6_fib_timer,
round_jiffies(now
+ net->ipv6.sysctl.ip6_rt_gc_interval));
else
del_timer(&net->ipv6.ip6_fib_timer);
spin_unlock_bh(&net->ipv6.fib6_gc_lock);
}
static void fib6_gc_timer_cb(struct timer_list *t)
{
struct net *arg = from_timer(arg, t, ipv6.ip6_fib_timer);
fib6_run_gc(0, arg, true);
}
static int __net_init fib6_net_init(struct net *net)
{
size_t size = sizeof(struct hlist_head) * FIB6_TABLE_HASHSZ;
int err;
err = fib6_notifier_init(net);
if (err)
return err;
spin_lock_init(&net->ipv6.fib6_gc_lock);
rwlock_init(&net->ipv6.fib6_walker_lock);
INIT_LIST_HEAD(&net->ipv6.fib6_walkers);
timer_setup(&net->ipv6.ip6_fib_timer, fib6_gc_timer_cb, 0);
net->ipv6.rt6_stats = kzalloc(sizeof(*net->ipv6.rt6_stats), GFP_KERNEL);
if (!net->ipv6.rt6_stats)
goto out_timer;
/* Avoid false sharing : Use at least a full cache line */
size = max_t(size_t, size, L1_CACHE_BYTES);
net->ipv6.fib_table_hash = kzalloc(size, GFP_KERNEL);
if (!net->ipv6.fib_table_hash)
goto out_rt6_stats;
net->ipv6.fib6_main_tbl = kzalloc(sizeof(*net->ipv6.fib6_main_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_main_tbl)
goto out_fib_table_hash;
net->ipv6.fib6_main_tbl->tb6_id = RT6_TABLE_MAIN;
rcu_assign_pointer(net->ipv6.fib6_main_tbl->tb6_root.leaf,
net->ipv6.fib6_null_entry);
net->ipv6.fib6_main_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&net->ipv6.fib6_main_tbl->tb6_peers);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.fib6_local_tbl = kzalloc(sizeof(*net->ipv6.fib6_local_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_local_tbl)
goto out_fib6_main_tbl;
net->ipv6.fib6_local_tbl->tb6_id = RT6_TABLE_LOCAL;
rcu_assign_pointer(net->ipv6.fib6_local_tbl->tb6_root.leaf,
net->ipv6.fib6_null_entry);
net->ipv6.fib6_local_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&net->ipv6.fib6_local_tbl->tb6_peers);
#endif
fib6_tables_init(net);
return 0;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_fib6_main_tbl:
kfree(net->ipv6.fib6_main_tbl);
#endif
out_fib_table_hash:
kfree(net->ipv6.fib_table_hash);
out_rt6_stats:
kfree(net->ipv6.rt6_stats);
out_timer:
fib6_notifier_exit(net);
return -ENOMEM;
}
static void fib6_net_exit(struct net *net)
{
unsigned int i;
del_timer_sync(&net->ipv6.ip6_fib_timer);
for (i = 0; i < FIB6_TABLE_HASHSZ; i++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[i];
struct hlist_node *tmp;
struct fib6_table *tb;
hlist_for_each_entry_safe(tb, tmp, head, tb6_hlist) {
hlist_del(&tb->tb6_hlist);
fib6_free_table(tb);
}
}
kfree(net->ipv6.fib_table_hash);
kfree(net->ipv6.rt6_stats);
fib6_notifier_exit(net);
}
static struct pernet_operations fib6_net_ops = {
.init = fib6_net_init,
.exit = fib6_net_exit,
};
int __init fib6_init(void)
{
int ret = -ENOMEM;
fib6_node_kmem = kmem_cache_create("fib6_nodes",
sizeof(struct fib6_node),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!fib6_node_kmem)
goto out;
ret = register_pernet_subsys(&fib6_net_ops);
if (ret)
goto out_kmem_cache_create;
ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETROUTE, NULL,
inet6_dump_fib, 0);
if (ret)
goto out_unregister_subsys;
__fib6_flush_trees = fib6_flush_trees;
out:
return ret;
out_unregister_subsys:
unregister_pernet_subsys(&fib6_net_ops);
out_kmem_cache_create:
kmem_cache_destroy(fib6_node_kmem);
goto out;
}
void fib6_gc_cleanup(void)
{
unregister_pernet_subsys(&fib6_net_ops);
kmem_cache_destroy(fib6_node_kmem);
}
#ifdef CONFIG_PROC_FS
static int ipv6_route_seq_show(struct seq_file *seq, void *v)
{
struct fib6_info *rt = v;
struct ipv6_route_iter *iter = seq->private;
struct fib6_nh *fib6_nh = rt->fib6_nh;
unsigned int flags = rt->fib6_flags;
const struct net_device *dev;
if (rt->nh)
fib6_nh = nexthop_fib6_nh(rt->nh);
seq_printf(seq, "%pi6 %02x ", &rt->fib6_dst.addr, rt->fib6_dst.plen);
#ifdef CONFIG_IPV6_SUBTREES
seq_printf(seq, "%pi6 %02x ", &rt->fib6_src.addr, rt->fib6_src.plen);
#else
seq_puts(seq, "00000000000000000000000000000000 00 ");
#endif
if (fib6_nh->fib_nh_gw_family) {
flags |= RTF_GATEWAY;
seq_printf(seq, "%pi6", &fib6_nh->fib_nh_gw6);
} else {
seq_puts(seq, "00000000000000000000000000000000");
}
dev = fib6_nh->fib_nh_dev;
seq_printf(seq, " %08x %08x %08x %08x %8s\n",
rt->fib6_metric, refcount_read(&rt->fib6_ref), 0,
flags, dev ? dev->name : "");
iter->w.leaf = NULL;
return 0;
}
static int ipv6_route_yield(struct fib6_walker *w)
{
struct ipv6_route_iter *iter = w->args;
if (!iter->skip)
return 1;
do {
iter->w.leaf = rcu_dereference_protected(
iter->w.leaf->fib6_next,
lockdep_is_held(&iter->tbl->tb6_lock));
iter->skip--;
if (!iter->skip && iter->w.leaf)
return 1;
} while (iter->w.leaf);
return 0;
}
static void ipv6_route_seq_setup_walk(struct ipv6_route_iter *iter,
struct net *net)
{
memset(&iter->w, 0, sizeof(iter->w));
iter->w.func = ipv6_route_yield;
iter->w.root = &iter->tbl->tb6_root;
iter->w.state = FWS_INIT;
iter->w.node = iter->w.root;
iter->w.args = iter;
iter->sernum = iter->w.root->fn_sernum;
INIT_LIST_HEAD(&iter->w.lh);
fib6_walker_link(net, &iter->w);
}
static struct fib6_table *ipv6_route_seq_next_table(struct fib6_table *tbl,
struct net *net)
{
unsigned int h;
struct hlist_node *node;
if (tbl) {
h = (tbl->tb6_id & (FIB6_TABLE_HASHSZ - 1)) + 1;
node = rcu_dereference_bh(hlist_next_rcu(&tbl->tb6_hlist));
} else {
h = 0;
node = NULL;
}
while (!node && h < FIB6_TABLE_HASHSZ) {
node = rcu_dereference_bh(
hlist_first_rcu(&net->ipv6.fib_table_hash[h++]));
}
return hlist_entry_safe(node, struct fib6_table, tb6_hlist);
}
static void ipv6_route_check_sernum(struct ipv6_route_iter *iter)
{
if (iter->sernum != iter->w.root->fn_sernum) {
iter->sernum = iter->w.root->fn_sernum;
iter->w.state = FWS_INIT;
iter->w.node = iter->w.root;
WARN_ON(iter->w.skip);
iter->w.skip = iter->w.count;
}
}
static void *ipv6_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
int r;
struct fib6_info *n;
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
if (!v)
goto iter_table;
n = rcu_dereference_bh(((struct fib6_info *)v)->fib6_next);
if (n) {
++*pos;
return n;
}
iter_table:
ipv6_route_check_sernum(iter);
spin_lock_bh(&iter->tbl->tb6_lock);
r = fib6_walk_continue(&iter->w);
spin_unlock_bh(&iter->tbl->tb6_lock);
if (r > 0) {
if (v)
++*pos;
return iter->w.leaf;
} else if (r < 0) {
fib6_walker_unlink(net, &iter->w);
return NULL;
}
fib6_walker_unlink(net, &iter->w);
iter->tbl = ipv6_route_seq_next_table(iter->tbl, net);
if (!iter->tbl)
return NULL;
ipv6_route_seq_setup_walk(iter, net);
goto iter_table;
}
static void *ipv6_route_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU_BH)
{
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
rcu_read_lock_bh();
iter->tbl = ipv6_route_seq_next_table(NULL, net);
iter->skip = *pos;
if (iter->tbl) {
ipv6_route_seq_setup_walk(iter, net);
return ipv6_route_seq_next(seq, NULL, pos);
} else {
return NULL;
}
}
static bool ipv6_route_iter_active(struct ipv6_route_iter *iter)
{
struct fib6_walker *w = &iter->w;
return w->node && !(w->state == FWS_U && w->node == w->root);
}
static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
__releases(RCU_BH)
{
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
if (ipv6_route_iter_active(iter))
fib6_walker_unlink(net, &iter->w);
rcu_read_unlock_bh();
}
const struct seq_operations ipv6_route_seq_ops = {
.start = ipv6_route_seq_start,
.next = ipv6_route_seq_next,
.stop = ipv6_route_seq_stop,
.show = ipv6_route_seq_show
};
#endif /* CONFIG_PROC_FS */
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_1368_0 |
crossvul-cpp_data_good_2581_0 | /******************************************************************************
*
* Module Name: nsutils - Utilities for accessing ACPI namespace, accessing
* parents and siblings and Scope manipulation
*
*****************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2017, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#include "acpi.h"
#include "accommon.h"
#include "acnamesp.h"
#include "amlcode.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME ("nsutils")
/* Local prototypes */
#ifdef ACPI_OBSOLETE_FUNCTIONS
ACPI_NAME
AcpiNsFindParentName (
ACPI_NAMESPACE_NODE *NodeToSearch);
#endif
/*******************************************************************************
*
* FUNCTION: AcpiNsPrintNodePathname
*
* PARAMETERS: Node - Object
* Message - Prefix message
*
* DESCRIPTION: Print an object's full namespace pathname
* Manages allocation/freeing of a pathname buffer
*
******************************************************************************/
void
AcpiNsPrintNodePathname (
ACPI_NAMESPACE_NODE *Node,
const char *Message)
{
ACPI_BUFFER Buffer;
ACPI_STATUS Status;
if (!Node)
{
AcpiOsPrintf ("[NULL NAME]");
return;
}
/* Convert handle to full pathname and print it (with supplied message) */
Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
Status = AcpiNsHandleToPathname (Node, &Buffer, TRUE);
if (ACPI_SUCCESS (Status))
{
if (Message)
{
AcpiOsPrintf ("%s ", Message);
}
AcpiOsPrintf ("[%s] (Node %p)", (char *) Buffer.Pointer, Node);
ACPI_FREE (Buffer.Pointer);
}
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetType
*
* PARAMETERS: Node - Parent Node to be examined
*
* RETURN: Type field from Node whose handle is passed
*
* DESCRIPTION: Return the type of a Namespace node
*
******************************************************************************/
ACPI_OBJECT_TYPE
AcpiNsGetType (
ACPI_NAMESPACE_NODE *Node)
{
ACPI_FUNCTION_TRACE (NsGetType);
if (!Node)
{
ACPI_WARNING ((AE_INFO, "Null Node parameter"));
return_UINT8 (ACPI_TYPE_ANY);
}
return_UINT8 (Node->Type);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsLocal
*
* PARAMETERS: Type - A namespace object type
*
* RETURN: LOCAL if names must be found locally in objects of the
* passed type, 0 if enclosing scopes should be searched
*
* DESCRIPTION: Returns scope rule for the given object type.
*
******************************************************************************/
UINT32
AcpiNsLocal (
ACPI_OBJECT_TYPE Type)
{
ACPI_FUNCTION_TRACE (NsLocal);
if (!AcpiUtValidObjectType (Type))
{
/* Type code out of range */
ACPI_WARNING ((AE_INFO, "Invalid Object Type 0x%X", Type));
return_UINT32 (ACPI_NS_NORMAL);
}
return_UINT32 (AcpiGbl_NsProperties[Type] & ACPI_NS_LOCAL);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetInternalNameLength
*
* PARAMETERS: Info - Info struct initialized with the
* external name pointer.
*
* RETURN: None
*
* DESCRIPTION: Calculate the length of the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
void
AcpiNsGetInternalNameLength (
ACPI_NAMESTRING_INFO *Info)
{
const char *NextExternalChar;
UINT32 i;
ACPI_FUNCTION_ENTRY ();
NextExternalChar = Info->ExternalName;
Info->NumCarats = 0;
Info->NumSegments = 0;
Info->FullyQualified = FALSE;
/*
* For the internal name, the required length is 4 bytes per segment,
* plus 1 each for RootPrefix, MultiNamePrefixOp, segment count,
* trailing null (which is not really needed, but no there's harm in
* putting it there)
*
* strlen() + 1 covers the first NameSeg, which has no path separator
*/
if (ACPI_IS_ROOT_PREFIX (*NextExternalChar))
{
Info->FullyQualified = TRUE;
NextExternalChar++;
/* Skip redundant RootPrefix, like \\_SB.PCI0.SBRG.EC0 */
while (ACPI_IS_ROOT_PREFIX (*NextExternalChar))
{
NextExternalChar++;
}
}
else
{
/* Handle Carat prefixes */
while (ACPI_IS_PARENT_PREFIX (*NextExternalChar))
{
Info->NumCarats++;
NextExternalChar++;
}
}
/*
* Determine the number of ACPI name "segments" by counting the number of
* path separators within the string. Start with one segment since the
* segment count is [(# separators) + 1], and zero separators is ok.
*/
if (*NextExternalChar)
{
Info->NumSegments = 1;
for (i = 0; NextExternalChar[i]; i++)
{
if (ACPI_IS_PATH_SEPARATOR (NextExternalChar[i]))
{
Info->NumSegments++;
}
}
}
Info->Length = (ACPI_NAME_SIZE * Info->NumSegments) +
4 + Info->NumCarats;
Info->NextExternalChar = NextExternalChar;
}
/*******************************************************************************
*
* FUNCTION: AcpiNsBuildInternalName
*
* PARAMETERS: Info - Info struct fully initialized
*
* RETURN: Status
*
* DESCRIPTION: Construct the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
ACPI_STATUS
AcpiNsBuildInternalName (
ACPI_NAMESTRING_INFO *Info)
{
UINT32 NumSegments = Info->NumSegments;
char *InternalName = Info->InternalName;
const char *ExternalName = Info->NextExternalChar;
char *Result = NULL;
UINT32 i;
ACPI_FUNCTION_TRACE (NsBuildInternalName);
/* Setup the correct prefixes, counts, and pointers */
if (Info->FullyQualified)
{
InternalName[0] = AML_ROOT_PREFIX;
if (NumSegments <= 1)
{
Result = &InternalName[1];
}
else if (NumSegments == 2)
{
InternalName[1] = AML_DUAL_NAME_PREFIX;
Result = &InternalName[2];
}
else
{
InternalName[1] = AML_MULTI_NAME_PREFIX_OP;
InternalName[2] = (char) NumSegments;
Result = &InternalName[3];
}
}
else
{
/*
* Not fully qualified.
* Handle Carats first, then append the name segments
*/
i = 0;
if (Info->NumCarats)
{
for (i = 0; i < Info->NumCarats; i++)
{
InternalName[i] = AML_PARENT_PREFIX;
}
}
if (NumSegments <= 1)
{
Result = &InternalName[i];
}
else if (NumSegments == 2)
{
InternalName[i] = AML_DUAL_NAME_PREFIX;
Result = &InternalName[(ACPI_SIZE) i+1];
}
else
{
InternalName[i] = AML_MULTI_NAME_PREFIX_OP;
InternalName[(ACPI_SIZE) i+1] = (char) NumSegments;
Result = &InternalName[(ACPI_SIZE) i+2];
}
}
/* Build the name (minus path separators) */
for (; NumSegments; NumSegments--)
{
for (i = 0; i < ACPI_NAME_SIZE; i++)
{
if (ACPI_IS_PATH_SEPARATOR (*ExternalName) ||
(*ExternalName == 0))
{
/* Pad the segment with underscore(s) if segment is short */
Result[i] = '_';
}
else
{
/* Convert the character to uppercase and save it */
Result[i] = (char) toupper ((int) *ExternalName);
ExternalName++;
}
}
/* Now we must have a path separator, or the pathname is bad */
if (!ACPI_IS_PATH_SEPARATOR (*ExternalName) &&
(*ExternalName != 0))
{
return_ACPI_STATUS (AE_BAD_PATHNAME);
}
/* Move on the next segment */
ExternalName++;
Result += ACPI_NAME_SIZE;
}
/* Terminate the string */
*Result = 0;
if (Info->FullyQualified)
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Returning [%p] (abs) \"\\%s\"\n",
InternalName, InternalName));
}
else
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Returning [%p] (rel) \"%s\"\n",
InternalName, InternalName));
}
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsInternalizeName
*
* PARAMETERS: *ExternalName - External representation of name
* **Converted Name - Where to return the resulting
* internal represention of the name
*
* RETURN: Status
*
* DESCRIPTION: Convert an external representation (e.g. "\_PR_.CPU0")
* to internal form (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
*
*******************************************************************************/
ACPI_STATUS
AcpiNsInternalizeName (
const char *ExternalName,
char **ConvertedName)
{
char *InternalName;
ACPI_NAMESTRING_INFO Info;
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsInternalizeName);
if ((!ExternalName) ||
(*ExternalName == 0) ||
(!ConvertedName))
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
/* Get the length of the new internal name */
Info.ExternalName = ExternalName;
AcpiNsGetInternalNameLength (&Info);
/* We need a segment to store the internal name */
InternalName = ACPI_ALLOCATE_ZEROED (Info.Length);
if (!InternalName)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Build the name */
Info.InternalName = InternalName;
Status = AcpiNsBuildInternalName (&Info);
if (ACPI_FAILURE (Status))
{
ACPI_FREE (InternalName);
return_ACPI_STATUS (Status);
}
*ConvertedName = InternalName;
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsExternalizeName
*
* PARAMETERS: InternalNameLength - Lenth of the internal name below
* InternalName - Internal representation of name
* ConvertedNameLength - Where the length is returned
* ConvertedName - Where the resulting external name
* is returned
*
* RETURN: Status
*
* DESCRIPTION: Convert internal name (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
* to its external (printable) form (e.g. "\_PR_.CPU0")
*
******************************************************************************/
ACPI_STATUS
AcpiNsExternalizeName (
UINT32 InternalNameLength,
const char *InternalName,
UINT32 *ConvertedNameLength,
char **ConvertedName)
{
UINT32 NamesIndex = 0;
UINT32 NumSegments = 0;
UINT32 RequiredLength;
UINT32 PrefixLength = 0;
UINT32 i = 0;
UINT32 j = 0;
ACPI_FUNCTION_TRACE (NsExternalizeName);
if (!InternalNameLength ||
!InternalName ||
!ConvertedName)
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
/* Check for a prefix (one '\' | one or more '^') */
switch (InternalName[0])
{
case AML_ROOT_PREFIX:
PrefixLength = 1;
break;
case AML_PARENT_PREFIX:
for (i = 0; i < InternalNameLength; i++)
{
if (ACPI_IS_PARENT_PREFIX (InternalName[i]))
{
PrefixLength = i + 1;
}
else
{
break;
}
}
if (i == InternalNameLength)
{
PrefixLength = i;
}
break;
default:
break;
}
/*
* Check for object names. Note that there could be 0-255 of these
* 4-byte elements.
*/
if (PrefixLength < InternalNameLength)
{
switch (InternalName[PrefixLength])
{
case AML_MULTI_NAME_PREFIX_OP:
/* <count> 4-byte names */
NamesIndex = PrefixLength + 2;
NumSegments = (UINT8)
InternalName[(ACPI_SIZE) PrefixLength + 1];
break;
case AML_DUAL_NAME_PREFIX:
/* Two 4-byte names */
NamesIndex = PrefixLength + 1;
NumSegments = 2;
break;
case 0:
/* NullName */
NamesIndex = 0;
NumSegments = 0;
break;
default:
/* one 4-byte name */
NamesIndex = PrefixLength;
NumSegments = 1;
break;
}
}
/*
* Calculate the length of ConvertedName, which equals the length
* of the prefix, length of all object names, length of any required
* punctuation ('.') between object names, plus the NULL terminator.
*/
RequiredLength = PrefixLength + (4 * NumSegments) +
((NumSegments > 0) ? (NumSegments - 1) : 0) + 1;
/*
* Check to see if we're still in bounds. If not, there's a problem
* with InternalName (invalid format).
*/
if (RequiredLength > InternalNameLength)
{
ACPI_ERROR ((AE_INFO, "Invalid internal name"));
return_ACPI_STATUS (AE_BAD_PATHNAME);
}
/* Build the ConvertedName */
*ConvertedName = ACPI_ALLOCATE_ZEROED (RequiredLength);
if (!(*ConvertedName))
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
j = 0;
for (i = 0; i < PrefixLength; i++)
{
(*ConvertedName)[j++] = InternalName[i];
}
if (NumSegments > 0)
{
for (i = 0; i < NumSegments; i++)
{
if (i > 0)
{
(*ConvertedName)[j++] = '.';
}
/* Copy and validate the 4-char name segment */
ACPI_MOVE_NAME (&(*ConvertedName)[j],
&InternalName[NamesIndex]);
AcpiUtRepairName (&(*ConvertedName)[j]);
j += ACPI_NAME_SIZE;
NamesIndex += ACPI_NAME_SIZE;
}
}
if (ConvertedNameLength)
{
*ConvertedNameLength = (UINT32) RequiredLength;
}
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsValidateHandle
*
* PARAMETERS: Handle - Handle to be validated and typecast to a
* namespace node.
*
* RETURN: A pointer to a namespace node
*
* DESCRIPTION: Convert a namespace handle to a namespace node. Handles special
* cases for the root node.
*
* NOTE: Real integer handles would allow for more verification
* and keep all pointers within this subsystem - however this introduces
* more overhead and has not been necessary to this point. Drivers
* holding handles are typically notified before a node becomes invalid
* due to a table unload.
*
******************************************************************************/
ACPI_NAMESPACE_NODE *
AcpiNsValidateHandle (
ACPI_HANDLE Handle)
{
ACPI_FUNCTION_ENTRY ();
/* Parameter validation */
if ((!Handle) || (Handle == ACPI_ROOT_OBJECT))
{
return (AcpiGbl_RootNode);
}
/* We can at least attempt to verify the handle */
if (ACPI_GET_DESCRIPTOR_TYPE (Handle) != ACPI_DESC_TYPE_NAMED)
{
return (NULL);
}
return (ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Handle));
}
/*******************************************************************************
*
* FUNCTION: AcpiNsTerminate
*
* PARAMETERS: none
*
* RETURN: none
*
* DESCRIPTION: free memory allocated for namespace and ACPI table storage.
*
******************************************************************************/
void
AcpiNsTerminate (
void)
{
ACPI_STATUS Status;
ACPI_OPERAND_OBJECT *Prev;
ACPI_OPERAND_OBJECT *Next;
ACPI_FUNCTION_TRACE (NsTerminate);
/* Delete any module-level code blocks */
Next = AcpiGbl_ModuleCodeList;
while (Next)
{
Prev = Next;
Next = Next->Method.Mutex;
Prev->Method.Mutex = NULL; /* Clear the Mutex (cheated) field */
AcpiUtRemoveReference (Prev);
}
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode);
/* Delete any objects attached to the root node */
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_VOID;
}
AcpiNsDeleteNode (AcpiGbl_RootNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: AcpiNsOpensScope
*
* PARAMETERS: Type - A valid namespace type
*
* RETURN: NEWSCOPE if the passed type "opens a name scope" according
* to the ACPI specification, else 0
*
******************************************************************************/
UINT32
AcpiNsOpensScope (
ACPI_OBJECT_TYPE Type)
{
ACPI_FUNCTION_ENTRY ();
if (Type > ACPI_TYPE_LOCAL_MAX)
{
/* type code out of range */
ACPI_WARNING ((AE_INFO, "Invalid Object Type 0x%X", Type));
return (ACPI_NS_NORMAL);
}
return (((UINT32) AcpiGbl_NsProperties[Type]) & ACPI_NS_NEWSCOPE);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetNodeUnlocked
*
* PARAMETERS: *Pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* PrefixNode - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first INT8 is '\'), the passed value
* of Scope will not be accessed.
* Flags - Used to indicate whether to perform upsearch or
* not.
* ReturnNode - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Doesn't locks namespace
*
******************************************************************************/
ACPI_STATUS
AcpiNsGetNodeUnlocked (
ACPI_NAMESPACE_NODE *PrefixNode,
const char *Pathname,
UINT32 Flags,
ACPI_NAMESPACE_NODE **ReturnNode)
{
ACPI_GENERIC_STATE ScopeInfo;
ACPI_STATUS Status;
char *InternalPath;
ACPI_FUNCTION_TRACE_PTR (NsGetNodeUnlocked, ACPI_CAST_PTR (char, Pathname));
/* Simplest case is a null pathname */
if (!Pathname)
{
*ReturnNode = PrefixNode;
if (!PrefixNode)
{
*ReturnNode = AcpiGbl_RootNode;
}
return_ACPI_STATUS (AE_OK);
}
/* Quick check for a reference to the root */
if (ACPI_IS_ROOT_PREFIX (Pathname[0]) && (!Pathname[1]))
{
*ReturnNode = AcpiGbl_RootNode;
return_ACPI_STATUS (AE_OK);
}
/* Convert path to internal representation */
Status = AcpiNsInternalizeName (Pathname, &InternalPath);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
/* Setup lookup scope (search starting point) */
ScopeInfo.Scope.Node = PrefixNode;
/* Lookup the name in the namespace */
Status = AcpiNsLookup (&ScopeInfo, InternalPath, ACPI_TYPE_ANY,
ACPI_IMODE_EXECUTE, (Flags | ACPI_NS_DONT_OPEN_SCOPE),
NULL, ReturnNode);
if (ACPI_FAILURE (Status))
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%s, %s\n",
Pathname, AcpiFormatException (Status)));
}
ACPI_FREE (InternalPath);
return_ACPI_STATUS (Status);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetNode
*
* PARAMETERS: *Pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* PrefixNode - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first INT8 is '\'), the passed value
* of Scope will not be accessed.
* Flags - Used to indicate whether to perform upsearch or
* not.
* ReturnNode - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Locks namespace
*
******************************************************************************/
ACPI_STATUS
AcpiNsGetNode (
ACPI_NAMESPACE_NODE *PrefixNode,
const char *Pathname,
UINT32 Flags,
ACPI_NAMESPACE_NODE **ReturnNode)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE_PTR (NsGetNode, ACPI_CAST_PTR (char, Pathname));
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
Status = AcpiNsGetNodeUnlocked (PrefixNode, Pathname,
Flags, ReturnNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
return_ACPI_STATUS (Status);
}
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_2581_0 |
crossvul-cpp_data_good_1325_3 | /*
** 2003 September 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used for creating, destroying, and populating
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
*/
#include "sqliteInt.h"
#include "vdbeInt.h"
/* Forward references */
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
static void vdbeFreeOpArray(sqlite3 *, Op *, int);
/*
** Create a new virtual database engine.
*/
Vdbe *sqlite3VdbeCreate(Parse *pParse){
sqlite3 *db = pParse->db;
Vdbe *p;
p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
if( p==0 ) return 0;
memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
p->db = db;
if( db->pVdbe ){
db->pVdbe->pPrev = p;
}
p->pNext = db->pVdbe;
p->pPrev = 0;
db->pVdbe = p;
p->magic = VDBE_MAGIC_INIT;
p->pParse = pParse;
pParse->pVdbe = p;
assert( pParse->aLabel==0 );
assert( pParse->nLabel==0 );
assert( p->nOpAlloc==0 );
assert( pParse->szOpAlloc==0 );
sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
return p;
}
/*
** Return the Parse object that owns a Vdbe object.
*/
Parse *sqlite3VdbeParser(Vdbe *p){
return p->pParse;
}
/*
** Change the error string stored in Vdbe.zErrMsg
*/
void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
va_list ap;
sqlite3DbFree(p->db, p->zErrMsg);
va_start(ap, zFormat);
p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
va_end(ap);
}
/*
** Remember the SQL string for a prepared statement.
*/
void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
if( p==0 ) return;
p->prepFlags = prepFlags;
if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
p->expmask = 0;
}
assert( p->zSql==0 );
p->zSql = sqlite3DbStrNDup(p->db, z, n);
}
#ifdef SQLITE_ENABLE_NORMALIZE
/*
** Add a new element to the Vdbe->pDblStr list.
*/
void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
if( p ){
int n = sqlite3Strlen30(z);
DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
sizeof(*pStr)+n+1-sizeof(pStr->z));
if( pStr ){
pStr->pNextStr = p->pDblStr;
p->pDblStr = pStr;
memcpy(pStr->z, z, n+1);
}
}
}
#endif
#ifdef SQLITE_ENABLE_NORMALIZE
/*
** zId of length nId is a double-quoted identifier. Check to see if
** that identifier is really used as a string literal.
*/
int sqlite3VdbeUsesDoubleQuotedString(
Vdbe *pVdbe, /* The prepared statement */
const char *zId /* The double-quoted identifier, already dequoted */
){
DblquoteStr *pStr;
assert( zId!=0 );
if( pVdbe->pDblStr==0 ) return 0;
for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
if( strcmp(zId, pStr->z)==0 ) return 1;
}
return 0;
}
#endif
/*
** Swap all content between two VDBE structures.
*/
void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
Vdbe tmp, *pTmp;
char *zTmp;
assert( pA->db==pB->db );
tmp = *pA;
*pA = *pB;
*pB = tmp;
pTmp = pA->pNext;
pA->pNext = pB->pNext;
pB->pNext = pTmp;
pTmp = pA->pPrev;
pA->pPrev = pB->pPrev;
pB->pPrev = pTmp;
zTmp = pA->zSql;
pA->zSql = pB->zSql;
pB->zSql = zTmp;
#ifdef SQLITE_ENABLE_NORMALIZE
zTmp = pA->zNormSql;
pA->zNormSql = pB->zNormSql;
pB->zNormSql = zTmp;
#endif
pB->expmask = pA->expmask;
pB->prepFlags = pA->prepFlags;
memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
}
/*
** Resize the Vdbe.aOp array so that it is at least nOp elements larger
** than its current size. nOp is guaranteed to be less than or equal
** to 1024/sizeof(Op).
**
** If an out-of-memory error occurs while resizing the array, return
** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
** unchanged (this is so that any opcodes already allocated can be
** correctly deallocated along with the rest of the Vdbe).
*/
static int growOpArray(Vdbe *v, int nOp){
VdbeOp *pNew;
Parse *p = v->pParse;
/* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
** more frequent reallocs and hence provide more opportunities for
** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
** by the minimum* amount required until the size reaches 512. Normal
** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
** size of the op array or add 1KB of space, whichever is smaller. */
#ifdef SQLITE_TEST_REALLOC_STRESS
sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
: (sqlite3_int64)v->nOpAlloc+nOp);
#else
sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
: (sqlite3_int64)(1024/sizeof(Op)));
UNUSED_PARAMETER(nOp);
#endif
/* Ensure that the size of a VDBE does not grow too large */
if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
sqlite3OomFault(p->db);
return SQLITE_NOMEM;
}
assert( nOp<=(1024/sizeof(Op)) );
assert( nNew>=(v->nOpAlloc+nOp) );
pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
if( pNew ){
p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
v->nOpAlloc = p->szOpAlloc/sizeof(Op);
v->aOp = pNew;
}
return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
}
#ifdef SQLITE_DEBUG
/* This routine is just a convenient place to set a breakpoint that will
** fire after each opcode is inserted and displayed using
** "PRAGMA vdbe_addoptrace=on".
*/
static void test_addop_breakpoint(void){
static int n = 0;
n++;
}
#endif
/*
** Add a new instruction to the list of instructions current in the
** VDBE. Return the address of the new instruction.
**
** Parameters:
**
** p Pointer to the VDBE
**
** op The opcode for this instruction
**
** p1, p2, p3 Operands
**
** Use the sqlite3VdbeResolveLabel() function to fix an address and
** the sqlite3VdbeChangeP4() function to change the value of the P4
** operand.
*/
static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
assert( p->nOpAlloc<=p->nOp );
if( growOpArray(p, 1) ) return 1;
assert( p->nOpAlloc>p->nOp );
return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
}
int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
int i;
VdbeOp *pOp;
i = p->nOp;
assert( p->magic==VDBE_MAGIC_INIT );
assert( op>=0 && op<0xff );
if( p->nOpAlloc<=i ){
return growOp3(p, op, p1, p2, p3);
}
p->nOp++;
pOp = &p->aOp[i];
pOp->opcode = (u8)op;
pOp->p5 = 0;
pOp->p1 = p1;
pOp->p2 = p2;
pOp->p3 = p3;
pOp->p4.p = 0;
pOp->p4type = P4_NOTUSED;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
pOp->zComment = 0;
#endif
#ifdef SQLITE_DEBUG
if( p->db->flags & SQLITE_VdbeAddopTrace ){
sqlite3VdbePrintOp(0, i, &p->aOp[i]);
test_addop_breakpoint();
}
#endif
#ifdef VDBE_PROFILE
pOp->cycles = 0;
pOp->cnt = 0;
#endif
#ifdef SQLITE_VDBE_COVERAGE
pOp->iSrcLine = 0;
#endif
return i;
}
int sqlite3VdbeAddOp0(Vdbe *p, int op){
return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
}
int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
}
int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
}
/* Generate code for an unconditional jump to instruction iDest
*/
int sqlite3VdbeGoto(Vdbe *p, int iDest){
return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
}
/* Generate code to cause the string zStr to be loaded into
** register iDest
*/
int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
}
/*
** Generate code that initializes multiple registers to string or integer
** constants. The registers begin with iDest and increase consecutively.
** One register is initialized for each characgter in zTypes[]. For each
** "s" character in zTypes[], the register is a string if the argument is
** not NULL, or OP_Null if the value is a null pointer. For each "i" character
** in zTypes[], the register is initialized to an integer.
**
** If the input string does not end with "X" then an OP_ResultRow instruction
** is generated for the values inserted.
*/
void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
va_list ap;
int i;
char c;
va_start(ap, zTypes);
for(i=0; (c = zTypes[i])!=0; i++){
if( c=='s' ){
const char *z = va_arg(ap, const char*);
sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
}else if( c=='i' ){
sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
}else{
goto skip_op_resultrow;
}
}
sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
skip_op_resultrow:
va_end(ap);
}
/*
** Add an opcode that includes the p4 value as a pointer.
*/
int sqlite3VdbeAddOp4(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
const char *zP4, /* The P4 operand */
int p4type /* P4 operand type */
){
int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
sqlite3VdbeChangeP4(p, addr, zP4, p4type);
return addr;
}
/*
** Add an OP_Function or OP_PureFunc opcode.
**
** The eCallCtx argument is information (typically taken from Expr.op2)
** that describes the calling context of the function. 0 means a general
** function call. NC_IsCheck means called by a check constraint,
** NC_IdxExpr means called as part of an index expression. NC_PartIdx
** means in the WHERE clause of a partial index. NC_GenCol means called
** while computing a generated column value. 0 is the usual case.
*/
int sqlite3VdbeAddFunctionCall(
Parse *pParse, /* Parsing context */
int p1, /* Constant argument mask */
int p2, /* First argument register */
int p3, /* Register into which results are written */
int nArg, /* Number of argument */
const FuncDef *pFunc, /* The function to be invoked */
int eCallCtx /* Calling context */
){
Vdbe *v = pParse->pVdbe;
int nByte;
int addr;
sqlite3_context *pCtx;
assert( v );
nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
if( pCtx==0 ){
assert( pParse->db->mallocFailed );
freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
return 0;
}
pCtx->pOut = 0;
pCtx->pFunc = (FuncDef*)pFunc;
pCtx->pVdbe = 0;
pCtx->isError = 0;
pCtx->argc = nArg;
pCtx->iOp = sqlite3VdbeCurrentAddr(v);
addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
return addr;
}
/*
** Add an opcode that includes the p4 value with a P4_INT64 or
** P4_REAL type.
*/
int sqlite3VdbeAddOp4Dup8(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
const u8 *zP4, /* The P4 operand */
int p4type /* P4 operand type */
){
char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
if( p4copy ) memcpy(p4copy, zP4, 8);
return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Return the address of the current EXPLAIN QUERY PLAN baseline.
** 0 means "none".
*/
int sqlite3VdbeExplainParent(Parse *pParse){
VdbeOp *pOp;
if( pParse->addrExplain==0 ) return 0;
pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
return pOp->p2;
}
/*
** Set a debugger breakpoint on the following routine in order to
** monitor the EXPLAIN QUERY PLAN code generation.
*/
#if defined(SQLITE_DEBUG)
void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
(void)z1;
(void)z2;
}
#endif
/*
** Add a new OP_ opcode.
**
** If the bPush flag is true, then make this opcode the parent for
** subsequent Explains until sqlite3VdbeExplainPop() is called.
*/
void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
#ifndef SQLITE_DEBUG
/* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
** But omit them (for performance) during production builds */
if( pParse->explain==2 )
#endif
{
char *zMsg;
Vdbe *v;
va_list ap;
int iThis;
va_start(ap, zFmt);
zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
va_end(ap);
v = pParse->pVdbe;
iThis = v->nOp;
sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
zMsg, P4_DYNAMIC);
sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
if( bPush){
pParse->addrExplain = iThis;
}
}
}
/*
** Pop the EXPLAIN QUERY PLAN stack one level.
*/
void sqlite3VdbeExplainPop(Parse *pParse){
sqlite3ExplainBreakpoint("POP", 0);
pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
}
#endif /* SQLITE_OMIT_EXPLAIN */
/*
** Add an OP_ParseSchema opcode. This routine is broken out from
** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
** as having been used.
**
** The zWhere string must have been obtained from sqlite3_malloc().
** This routine will take ownership of the allocated memory.
*/
void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
int j;
sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
}
/*
** Add an opcode that includes the p4 value as an integer.
*/
int sqlite3VdbeAddOp4Int(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
int p4 /* The P4 operand as an integer */
){
int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
if( p->db->mallocFailed==0 ){
VdbeOp *pOp = &p->aOp[addr];
pOp->p4type = P4_INT32;
pOp->p4.i = p4;
}
return addr;
}
/* Insert the end of a co-routine
*/
void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
/* Clear the temporary register cache, thereby ensuring that each
** co-routine has its own independent set of registers, because co-routines
** might expect their registers to be preserved across an OP_Yield, and
** that could cause problems if two or more co-routines are using the same
** temporary register.
*/
v->pParse->nTempReg = 0;
v->pParse->nRangeReg = 0;
}
/*
** Create a new symbolic label for an instruction that has yet to be
** coded. The symbolic label is really just a negative number. The
** label can be used as the P2 value of an operation. Later, when
** the label is resolved to a specific address, the VDBE will scan
** through its operation list and change all values of P2 which match
** the label into the resolved address.
**
** The VDBE knows that a P2 value is a label because labels are
** always negative and P2 values are suppose to be non-negative.
** Hence, a negative P2 value is a label that has yet to be resolved.
** (Later:) This is only true for opcodes that have the OPFLG_JUMP
** property.
**
** Variable usage notes:
**
** Parse.aLabel[x] Stores the address that the x-th label resolves
** into. For testing (SQLITE_DEBUG), unresolved
** labels stores -1, but that is not required.
** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
** Parse.nLabel The *negative* of the number of labels that have
** been issued. The negative is stored because
** that gives a performance improvement over storing
** the equivalent positive value.
*/
int sqlite3VdbeMakeLabel(Parse *pParse){
return --pParse->nLabel;
}
/*
** Resolve label "x" to be the address of the next instruction to
** be inserted. The parameter "x" must have been obtained from
** a prior call to sqlite3VdbeMakeLabel().
*/
static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
int nNewSize = 10 - p->nLabel;
p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
nNewSize*sizeof(p->aLabel[0]));
if( p->aLabel==0 ){
p->nLabelAlloc = 0;
}else{
#ifdef SQLITE_DEBUG
int i;
for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
#endif
p->nLabelAlloc = nNewSize;
p->aLabel[j] = v->nOp;
}
}
void sqlite3VdbeResolveLabel(Vdbe *v, int x){
Parse *p = v->pParse;
int j = ADDR(x);
assert( v->magic==VDBE_MAGIC_INIT );
assert( j<-p->nLabel );
assert( j>=0 );
#ifdef SQLITE_DEBUG
if( p->db->flags & SQLITE_VdbeAddopTrace ){
printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
}
#endif
if( p->nLabelAlloc + p->nLabel < 0 ){
resizeResolveLabel(p,v,j);
}else{
assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
p->aLabel[j] = v->nOp;
}
}
/*
** Mark the VDBE as one that can only be run one time.
*/
void sqlite3VdbeRunOnlyOnce(Vdbe *p){
p->runOnlyOnce = 1;
}
/*
** Mark the VDBE as one that can only be run multiple times.
*/
void sqlite3VdbeReusable(Vdbe *p){
p->runOnlyOnce = 0;
}
#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
/*
** The following type and function are used to iterate through all opcodes
** in a Vdbe main program and each of the sub-programs (triggers) it may
** invoke directly or indirectly. It should be used as follows:
**
** Op *pOp;
** VdbeOpIter sIter;
**
** memset(&sIter, 0, sizeof(sIter));
** sIter.v = v; // v is of type Vdbe*
** while( (pOp = opIterNext(&sIter)) ){
** // Do something with pOp
** }
** sqlite3DbFree(v->db, sIter.apSub);
**
*/
typedef struct VdbeOpIter VdbeOpIter;
struct VdbeOpIter {
Vdbe *v; /* Vdbe to iterate through the opcodes of */
SubProgram **apSub; /* Array of subprograms */
int nSub; /* Number of entries in apSub */
int iAddr; /* Address of next instruction to return */
int iSub; /* 0 = main program, 1 = first sub-program etc. */
};
static Op *opIterNext(VdbeOpIter *p){
Vdbe *v = p->v;
Op *pRet = 0;
Op *aOp;
int nOp;
if( p->iSub<=p->nSub ){
if( p->iSub==0 ){
aOp = v->aOp;
nOp = v->nOp;
}else{
aOp = p->apSub[p->iSub-1]->aOp;
nOp = p->apSub[p->iSub-1]->nOp;
}
assert( p->iAddr<nOp );
pRet = &aOp[p->iAddr];
p->iAddr++;
if( p->iAddr==nOp ){
p->iSub++;
p->iAddr = 0;
}
if( pRet->p4type==P4_SUBPROGRAM ){
int nByte = (p->nSub+1)*sizeof(SubProgram*);
int j;
for(j=0; j<p->nSub; j++){
if( p->apSub[j]==pRet->p4.pProgram ) break;
}
if( j==p->nSub ){
p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
if( !p->apSub ){
pRet = 0;
}else{
p->apSub[p->nSub++] = pRet->p4.pProgram;
}
}
}
}
return pRet;
}
/*
** Check if the program stored in the VM associated with pParse may
** throw an ABORT exception (causing the statement, but not entire transaction
** to be rolled back). This condition is true if the main program or any
** sub-programs contains any of the following:
**
** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
** * OP_Destroy
** * OP_VUpdate
** * OP_VCreate
** * OP_VRename
** * OP_FkCounter with P2==0 (immediate foreign key constraint)
** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
** (for CREATE TABLE AS SELECT ...)
**
** Then check that the value of Parse.mayAbort is true if an
** ABORT may be thrown, or false otherwise. Return true if it does
** match, or false otherwise. This function is intended to be used as
** part of an assert statement in the compiler. Similar to:
**
** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
*/
int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
int hasAbort = 0;
int hasFkCounter = 0;
int hasCreateTable = 0;
int hasCreateIndex = 0;
int hasInitCoroutine = 0;
Op *pOp;
VdbeOpIter sIter;
memset(&sIter, 0, sizeof(sIter));
sIter.v = v;
while( (pOp = opIterNext(&sIter))!=0 ){
int opcode = pOp->opcode;
if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
|| opcode==OP_VDestroy
|| opcode==OP_VCreate
|| (opcode==OP_ParseSchema && pOp->p4.z==0)
|| ((opcode==OP_Halt || opcode==OP_HaltIfNull)
&& ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
){
hasAbort = 1;
break;
}
if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
if( mayAbort ){
/* hasCreateIndex may also be set for some DELETE statements that use
** OP_Clear. So this routine may end up returning true in the case
** where a "DELETE FROM tbl" has a statement-journal but does not
** require one. This is not so bad - it is an inefficiency, not a bug. */
if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
if( opcode==OP_Clear ) hasCreateIndex = 1;
}
if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
#ifndef SQLITE_OMIT_FOREIGN_KEY
if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
hasFkCounter = 1;
}
#endif
}
sqlite3DbFree(v->db, sIter.apSub);
/* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
** If malloc failed, then the while() loop above may not have iterated
** through all opcodes and hasAbort may be set incorrectly. Return
** true for this case to prevent the assert() in the callers frame
** from failing. */
return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
|| (hasCreateTable && hasInitCoroutine) || hasCreateIndex
);
}
#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
#ifdef SQLITE_DEBUG
/*
** Increment the nWrite counter in the VDBE if the cursor is not an
** ephemeral cursor, or if the cursor argument is NULL.
*/
void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
if( pC==0
|| (pC->eCurType!=CURTYPE_SORTER
&& pC->eCurType!=CURTYPE_PSEUDO
&& !pC->isEphemeral)
){
p->nWrite++;
}
}
#endif
#ifdef SQLITE_DEBUG
/*
** Assert if an Abort at this point in time might result in a corrupt
** database.
*/
void sqlite3VdbeAssertAbortable(Vdbe *p){
assert( p->nWrite==0 || p->usesStmtJournal );
}
#endif
/*
** This routine is called after all opcodes have been inserted. It loops
** through all the opcodes and fixes up some details.
**
** (1) For each jump instruction with a negative P2 value (a label)
** resolve the P2 value to an actual address.
**
** (2) Compute the maximum number of arguments used by any SQL function
** and store that value in *pMaxFuncArgs.
**
** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
** indicate what the prepared statement actually does.
**
** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
**
** (5) Reclaim the memory allocated for storing labels.
**
** This routine will only function correctly if the mkopcodeh.tcl generator
** script numbers the opcodes correctly. Changes to this routine must be
** coordinated with changes to mkopcodeh.tcl.
*/
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
int nMaxArgs = *pMaxFuncArgs;
Op *pOp;
Parse *pParse = p->pParse;
int *aLabel = pParse->aLabel;
p->readOnly = 1;
p->bIsReader = 0;
pOp = &p->aOp[p->nOp-1];
while(1){
/* Only JUMP opcodes and the short list of special opcodes in the switch
** below need to be considered. The mkopcodeh.tcl generator script groups
** all these opcodes together near the front of the opcode list. Skip
** any opcode that does not need processing by virtual of the fact that
** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
*/
if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
/* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
** cases from this switch! */
switch( pOp->opcode ){
case OP_Transaction: {
if( pOp->p2!=0 ) p->readOnly = 0;
/* fall thru */
}
case OP_AutoCommit:
case OP_Savepoint: {
p->bIsReader = 1;
break;
}
#ifndef SQLITE_OMIT_WAL
case OP_Checkpoint:
#endif
case OP_Vacuum:
case OP_JournalMode: {
p->readOnly = 0;
p->bIsReader = 1;
break;
}
case OP_Next:
case OP_SorterNext: {
pOp->p4.xAdvance = sqlite3BtreeNext;
pOp->p4type = P4_ADVANCE;
/* The code generator never codes any of these opcodes as a jump
** to a label. They are always coded as a jump backwards to a
** known address */
assert( pOp->p2>=0 );
break;
}
case OP_Prev: {
pOp->p4.xAdvance = sqlite3BtreePrevious;
pOp->p4type = P4_ADVANCE;
/* The code generator never codes any of these opcodes as a jump
** to a label. They are always coded as a jump backwards to a
** known address */
assert( pOp->p2>=0 );
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case OP_VUpdate: {
if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
break;
}
case OP_VFilter: {
int n;
assert( (pOp - p->aOp) >= 3 );
assert( pOp[-1].opcode==OP_Integer );
n = pOp[-1].p1;
if( n>nMaxArgs ) nMaxArgs = n;
/* Fall through into the default case */
}
#endif
default: {
if( pOp->p2<0 ){
/* The mkopcodeh.tcl script has so arranged things that the only
** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
** have non-negative values for P2. */
assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
assert( ADDR(pOp->p2)<-pParse->nLabel );
pOp->p2 = aLabel[ADDR(pOp->p2)];
}
break;
}
}
/* The mkopcodeh.tcl script has so arranged things that the only
** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
** have non-negative values for P2. */
assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
}
if( pOp==p->aOp ) break;
pOp--;
}
sqlite3DbFree(p->db, pParse->aLabel);
pParse->aLabel = 0;
pParse->nLabel = 0;
*pMaxFuncArgs = nMaxArgs;
assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
}
/*
** Return the address of the next instruction to be inserted.
*/
int sqlite3VdbeCurrentAddr(Vdbe *p){
assert( p->magic==VDBE_MAGIC_INIT );
return p->nOp;
}
/*
** Verify that at least N opcode slots are available in p without
** having to malloc for more space (except when compiled using
** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
** to verify that certain calls to sqlite3VdbeAddOpList() can never
** fail due to a OOM fault and hence that the return value from
** sqlite3VdbeAddOpList() will always be non-NULL.
*/
#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
assert( p->nOp + N <= p->nOpAlloc );
}
#endif
/*
** Verify that the VM passed as the only argument does not contain
** an OP_ResultRow opcode. Fail an assert() if it does. This is used
** by code in pragma.c to ensure that the implementation of certain
** pragmas comports with the flags specified in the mkpragmatab.tcl
** script.
*/
#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
int i;
for(i=0; i<p->nOp; i++){
assert( p->aOp[i].opcode!=OP_ResultRow );
}
}
#endif
/*
** Generate code (a single OP_Abortable opcode) that will
** verify that the VDBE program can safely call Abort in the current
** context.
*/
#if defined(SQLITE_DEBUG)
void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
}
#endif
/*
** This function returns a pointer to the array of opcodes associated with
** the Vdbe passed as the first argument. It is the callers responsibility
** to arrange for the returned array to be eventually freed using the
** vdbeFreeOpArray() function.
**
** Before returning, *pnOp is set to the number of entries in the returned
** array. Also, *pnMaxArg is set to the larger of its current value and
** the number of entries in the Vdbe.apArg[] array required to execute the
** returned program.
*/
VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
VdbeOp *aOp = p->aOp;
assert( aOp && !p->db->mallocFailed );
/* Check that sqlite3VdbeUsesBtree() was not called on this VM */
assert( DbMaskAllZero(p->btreeMask) );
resolveP2Values(p, pnMaxArg);
*pnOp = p->nOp;
p->aOp = 0;
return aOp;
}
/*
** Add a whole list of operations to the operation stack. Return a
** pointer to the first operation inserted.
**
** Non-zero P2 arguments to jump instructions are automatically adjusted
** so that the jump target is relative to the first operation inserted.
*/
VdbeOp *sqlite3VdbeAddOpList(
Vdbe *p, /* Add opcodes to the prepared statement */
int nOp, /* Number of opcodes to add */
VdbeOpList const *aOp, /* The opcodes to be added */
int iLineno /* Source-file line number of first opcode */
){
int i;
VdbeOp *pOut, *pFirst;
assert( nOp>0 );
assert( p->magic==VDBE_MAGIC_INIT );
if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
return 0;
}
pFirst = pOut = &p->aOp[p->nOp];
for(i=0; i<nOp; i++, aOp++, pOut++){
pOut->opcode = aOp->opcode;
pOut->p1 = aOp->p1;
pOut->p2 = aOp->p2;
assert( aOp->p2>=0 );
if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
pOut->p2 += p->nOp;
}
pOut->p3 = aOp->p3;
pOut->p4type = P4_NOTUSED;
pOut->p4.p = 0;
pOut->p5 = 0;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
pOut->zComment = 0;
#endif
#ifdef SQLITE_VDBE_COVERAGE
pOut->iSrcLine = iLineno+i;
#else
(void)iLineno;
#endif
#ifdef SQLITE_DEBUG
if( p->db->flags & SQLITE_VdbeAddopTrace ){
sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
}
#endif
}
p->nOp += nOp;
return pFirst;
}
#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
/*
** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
*/
void sqlite3VdbeScanStatus(
Vdbe *p, /* VM to add scanstatus() to */
int addrExplain, /* Address of OP_Explain (or 0) */
int addrLoop, /* Address of loop counter */
int addrVisit, /* Address of rows visited counter */
LogEst nEst, /* Estimated number of output rows */
const char *zName /* Name of table or index being scanned */
){
sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
ScanStatus *aNew;
aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
if( aNew ){
ScanStatus *pNew = &aNew[p->nScan++];
pNew->addrExplain = addrExplain;
pNew->addrLoop = addrLoop;
pNew->addrVisit = addrVisit;
pNew->nEst = nEst;
pNew->zName = sqlite3DbStrDup(p->db, zName);
p->aScan = aNew;
}
}
#endif
/*
** Change the value of the opcode, or P1, P2, P3, or P5 operands
** for a specific instruction.
*/
void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
}
void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
sqlite3VdbeGetOp(p,addr)->p1 = val;
}
void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
sqlite3VdbeGetOp(p,addr)->p2 = val;
}
void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
sqlite3VdbeGetOp(p,addr)->p3 = val;
}
void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
assert( p->nOp>0 || p->db->mallocFailed );
if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
}
/*
** Change the P2 operand of instruction addr so that it points to
** the address of the next instruction to be coded.
*/
void sqlite3VdbeJumpHere(Vdbe *p, int addr){
sqlite3VdbeChangeP2(p, addr, p->nOp);
}
/*
** If the input FuncDef structure is ephemeral, then free it. If
** the FuncDef is not ephermal, then do nothing.
*/
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
sqlite3DbFreeNN(db, pDef);
}
}
/*
** Delete a P4 value if necessary.
*/
static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
sqlite3DbFreeNN(db, p);
}
static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
freeEphemeralFunction(db, p->pFunc);
sqlite3DbFreeNN(db, p);
}
static void freeP4(sqlite3 *db, int p4type, void *p4){
assert( db );
switch( p4type ){
case P4_FUNCCTX: {
freeP4FuncCtx(db, (sqlite3_context*)p4);
break;
}
case P4_REAL:
case P4_INT64:
case P4_DYNAMIC:
case P4_DYNBLOB:
case P4_INTARRAY: {
sqlite3DbFree(db, p4);
break;
}
case P4_KEYINFO: {
if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
break;
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
case P4_EXPR: {
sqlite3ExprDelete(db, (Expr*)p4);
break;
}
#endif
case P4_FUNCDEF: {
freeEphemeralFunction(db, (FuncDef*)p4);
break;
}
case P4_MEM: {
if( db->pnBytesFreed==0 ){
sqlite3ValueFree((sqlite3_value*)p4);
}else{
freeP4Mem(db, (Mem*)p4);
}
break;
}
case P4_VTAB : {
if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
break;
}
}
}
/*
** Free the space allocated for aOp and any p4 values allocated for the
** opcodes contained within. If aOp is not NULL it is assumed to contain
** nOp entries.
*/
static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
if( aOp ){
Op *pOp;
for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
sqlite3DbFree(db, pOp->zComment);
#endif
}
sqlite3DbFreeNN(db, aOp);
}
}
/*
** Link the SubProgram object passed as the second argument into the linked
** list at Vdbe.pSubProgram. This list is used to delete all sub-program
** objects when the VM is no longer required.
*/
void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
p->pNext = pVdbe->pProgram;
pVdbe->pProgram = p;
}
/*
** Return true if the given Vdbe has any SubPrograms.
*/
int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
return pVdbe->pProgram!=0;
}
/*
** Change the opcode at addr into OP_Noop
*/
int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
VdbeOp *pOp;
if( p->db->mallocFailed ) return 0;
assert( addr>=0 && addr<p->nOp );
pOp = &p->aOp[addr];
freeP4(p->db, pOp->p4type, pOp->p4.p);
pOp->p4type = P4_NOTUSED;
pOp->p4.z = 0;
pOp->opcode = OP_Noop;
return 1;
}
/*
** If the last opcode is "op" and it is not a jump destination,
** then remove it. Return true if and only if an opcode was removed.
*/
int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
return sqlite3VdbeChangeToNoop(p, p->nOp-1);
}else{
return 0;
}
}
/*
** Change the value of the P4 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
**
** If n>=0 then the P4 operand is dynamic, meaning that a copy of
** the string is made into memory obtained from sqlite3_malloc().
** A value of n==0 means copy bytes of zP4 up to and including the
** first null byte. If n>0 then copy n+1 bytes of zP4.
**
** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
** to a string or structure that is guaranteed to exist for the lifetime of
** the Vdbe. In these cases we can just copy the pointer.
**
** If addr<0 then change P4 on the most recently inserted instruction.
*/
static void SQLITE_NOINLINE vdbeChangeP4Full(
Vdbe *p,
Op *pOp,
const char *zP4,
int n
){
if( pOp->p4type ){
freeP4(p->db, pOp->p4type, pOp->p4.p);
pOp->p4type = 0;
pOp->p4.p = 0;
}
if( n<0 ){
sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
}else{
if( n==0 ) n = sqlite3Strlen30(zP4);
pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
pOp->p4type = P4_DYNAMIC;
}
}
void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
Op *pOp;
sqlite3 *db;
assert( p!=0 );
db = p->db;
assert( p->magic==VDBE_MAGIC_INIT );
assert( p->aOp!=0 || db->mallocFailed );
if( db->mallocFailed ){
if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
return;
}
assert( p->nOp>0 );
assert( addr<p->nOp );
if( addr<0 ){
addr = p->nOp - 1;
}
pOp = &p->aOp[addr];
if( n>=0 || pOp->p4type ){
vdbeChangeP4Full(p, pOp, zP4, n);
return;
}
if( n==P4_INT32 ){
/* Note: this cast is safe, because the origin data point was an int
** that was cast to a (const char *). */
pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
pOp->p4type = P4_INT32;
}else if( zP4!=0 ){
assert( n<0 );
pOp->p4.p = (void*)zP4;
pOp->p4type = (signed char)n;
if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
}
}
/*
** Change the P4 operand of the most recently coded instruction
** to the value defined by the arguments. This is a high-speed
** version of sqlite3VdbeChangeP4().
**
** The P4 operand must not have been previously defined. And the new
** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
** those cases.
*/
void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
VdbeOp *pOp;
assert( n!=P4_INT32 && n!=P4_VTAB );
assert( n<=0 );
if( p->db->mallocFailed ){
freeP4(p->db, n, pP4);
}else{
assert( pP4!=0 );
assert( p->nOp>0 );
pOp = &p->aOp[p->nOp-1];
assert( pOp->p4type==P4_NOTUSED );
pOp->p4type = n;
pOp->p4.p = pP4;
}
}
/*
** Set the P4 on the most recently added opcode to the KeyInfo for the
** index given.
*/
void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
Vdbe *v = pParse->pVdbe;
KeyInfo *pKeyInfo;
assert( v!=0 );
assert( pIdx!=0 );
pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
}
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
/*
** Change the comment on the most recently coded instruction. Or
** insert a No-op and add the comment to that new instruction. This
** makes the code easier to read during debugging. None of this happens
** in a production build.
*/
static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
assert( p->nOp>0 || p->aOp==0 );
assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed
|| p->pParse->nErr>0 );
if( p->nOp ){
assert( p->aOp );
sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
}
}
void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
va_list ap;
if( p ){
va_start(ap, zFormat);
vdbeVComment(p, zFormat, ap);
va_end(ap);
}
}
void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
va_list ap;
if( p ){
sqlite3VdbeAddOp0(p, OP_Noop);
va_start(ap, zFormat);
vdbeVComment(p, zFormat, ap);
va_end(ap);
}
}
#endif /* NDEBUG */
#ifdef SQLITE_VDBE_COVERAGE
/*
** Set the value if the iSrcLine field for the previously coded instruction.
*/
void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
}
#endif /* SQLITE_VDBE_COVERAGE */
/*
** Return the opcode for a given address. If the address is -1, then
** return the most recently inserted opcode.
**
** If a memory allocation error has occurred prior to the calling of this
** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
** is readable but not writable, though it is cast to a writable value.
** The return of a dummy opcode allows the call to continue functioning
** after an OOM fault without having to check to see if the return from
** this routine is a valid pointer. But because the dummy.opcode is 0,
** dummy will never be written to. This is verified by code inspection and
** by running with Valgrind.
*/
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
/* C89 specifies that the constant "dummy" will be initialized to all
** zeros, which is correct. MSVC generates a warning, nevertheless. */
static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
assert( p->magic==VDBE_MAGIC_INIT );
if( addr<0 ){
addr = p->nOp - 1;
}
assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
if( p->db->mallocFailed ){
return (VdbeOp*)&dummy;
}else{
return &p->aOp[addr];
}
}
#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
/*
** Return an integer value for one of the parameters to the opcode pOp
** determined by character c.
*/
static int translateP(char c, const Op *pOp){
if( c=='1' ) return pOp->p1;
if( c=='2' ) return pOp->p2;
if( c=='3' ) return pOp->p3;
if( c=='4' ) return pOp->p4.i;
return pOp->p5;
}
/*
** Compute a string for the "comment" field of a VDBE opcode listing.
**
** The Synopsis: field in comments in the vdbe.c source file gets converted
** to an extra string that is appended to the sqlite3OpcodeName(). In the
** absence of other comments, this synopsis becomes the comment on the opcode.
** Some translation occurs:
**
** "PX" -> "r[X]"
** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
*/
static int displayComment(
const Op *pOp, /* The opcode to be commented */
const char *zP4, /* Previously obtained value for P4 */
char *zTemp, /* Write result here */
int nTemp /* Space available in zTemp[] */
){
const char *zOpName;
const char *zSynopsis;
int nOpName;
int ii, jj;
char zAlt[50];
zOpName = sqlite3OpcodeName(pOp->opcode);
nOpName = sqlite3Strlen30(zOpName);
if( zOpName[nOpName+1] ){
int seenCom = 0;
char c;
zSynopsis = zOpName += nOpName + 1;
if( strncmp(zSynopsis,"IF ",3)==0 ){
if( pOp->p5 & SQLITE_STOREP2 ){
sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
}else{
sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
}
zSynopsis = zAlt;
}
for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
if( c=='P' ){
c = zSynopsis[++ii];
if( c=='4' ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
}else if( c=='X' ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
seenCom = 1;
}else{
int v1 = translateP(c, pOp);
int v2;
sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
ii += 3;
jj += sqlite3Strlen30(zTemp+jj);
v2 = translateP(zSynopsis[ii], pOp);
if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
ii += 2;
v2++;
}
if( v2>1 ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
}
}else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
ii += 4;
}
}
jj += sqlite3Strlen30(zTemp+jj);
}else{
zTemp[jj++] = c;
}
}
if( !seenCom && jj<nTemp-5 && pOp->zComment ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
jj += sqlite3Strlen30(zTemp+jj);
}
if( jj<nTemp ) zTemp[jj] = 0;
}else if( pOp->zComment ){
sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
jj = sqlite3Strlen30(zTemp);
}else{
zTemp[0] = 0;
jj = 0;
}
return jj;
}
#endif /* SQLITE_DEBUG */
#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
/*
** Translate the P4.pExpr value for an OP_CursorHint opcode into text
** that can be displayed in the P4 column of EXPLAIN output.
*/
static void displayP4Expr(StrAccum *p, Expr *pExpr){
const char *zOp = 0;
switch( pExpr->op ){
case TK_STRING:
sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
break;
case TK_INTEGER:
sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
break;
case TK_NULL:
sqlite3_str_appendf(p, "NULL");
break;
case TK_REGISTER: {
sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
break;
}
case TK_COLUMN: {
if( pExpr->iColumn<0 ){
sqlite3_str_appendf(p, "rowid");
}else{
sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
}
break;
}
case TK_LT: zOp = "LT"; break;
case TK_LE: zOp = "LE"; break;
case TK_GT: zOp = "GT"; break;
case TK_GE: zOp = "GE"; break;
case TK_NE: zOp = "NE"; break;
case TK_EQ: zOp = "EQ"; break;
case TK_IS: zOp = "IS"; break;
case TK_ISNOT: zOp = "ISNOT"; break;
case TK_AND: zOp = "AND"; break;
case TK_OR: zOp = "OR"; break;
case TK_PLUS: zOp = "ADD"; break;
case TK_STAR: zOp = "MUL"; break;
case TK_MINUS: zOp = "SUB"; break;
case TK_REM: zOp = "REM"; break;
case TK_BITAND: zOp = "BITAND"; break;
case TK_BITOR: zOp = "BITOR"; break;
case TK_SLASH: zOp = "DIV"; break;
case TK_LSHIFT: zOp = "LSHIFT"; break;
case TK_RSHIFT: zOp = "RSHIFT"; break;
case TK_CONCAT: zOp = "CONCAT"; break;
case TK_UMINUS: zOp = "MINUS"; break;
case TK_UPLUS: zOp = "PLUS"; break;
case TK_BITNOT: zOp = "BITNOT"; break;
case TK_NOT: zOp = "NOT"; break;
case TK_ISNULL: zOp = "ISNULL"; break;
case TK_NOTNULL: zOp = "NOTNULL"; break;
default:
sqlite3_str_appendf(p, "%s", "expr");
break;
}
if( zOp ){
sqlite3_str_appendf(p, "%s(", zOp);
displayP4Expr(p, pExpr->pLeft);
if( pExpr->pRight ){
sqlite3_str_append(p, ",", 1);
displayP4Expr(p, pExpr->pRight);
}
sqlite3_str_append(p, ")", 1);
}
}
#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
#if VDBE_DISPLAY_P4
/*
** Compute a string that describes the P4 parameter for an opcode.
** Use zTemp for any required temporary buffer space.
*/
static char *displayP4(Op *pOp, char *zTemp, int nTemp){
char *zP4 = zTemp;
StrAccum x;
assert( nTemp>=20 );
sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
switch( pOp->p4type ){
case P4_KEYINFO: {
int j;
KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
assert( pKeyInfo->aSortFlags!=0 );
sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
for(j=0; j<pKeyInfo->nKeyField; j++){
CollSeq *pColl = pKeyInfo->aColl[j];
const char *zColl = pColl ? pColl->zName : "";
if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
sqlite3_str_appendf(&x, ",%s%s%s",
(pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
(pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
zColl);
}
sqlite3_str_append(&x, ")", 1);
break;
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
case P4_EXPR: {
displayP4Expr(&x, pOp->p4.pExpr);
break;
}
#endif
case P4_COLLSEQ: {
CollSeq *pColl = pOp->p4.pColl;
sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
break;
}
case P4_FUNCDEF: {
FuncDef *pDef = pOp->p4.pFunc;
sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
break;
}
case P4_FUNCCTX: {
FuncDef *pDef = pOp->p4.pCtx->pFunc;
sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
break;
}
case P4_INT64: {
sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
break;
}
case P4_INT32: {
sqlite3_str_appendf(&x, "%d", pOp->p4.i);
break;
}
case P4_REAL: {
sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
break;
}
case P4_MEM: {
Mem *pMem = pOp->p4.pMem;
if( pMem->flags & MEM_Str ){
zP4 = pMem->z;
}else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
sqlite3_str_appendf(&x, "%lld", pMem->u.i);
}else if( pMem->flags & MEM_Real ){
sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
}else if( pMem->flags & MEM_Null ){
zP4 = "NULL";
}else{
assert( pMem->flags & MEM_Blob );
zP4 = "(blob)";
}
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case P4_VTAB: {
sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
sqlite3_str_appendf(&x, "vtab:%p", pVtab);
break;
}
#endif
case P4_INTARRAY: {
int i;
int *ai = pOp->p4.ai;
int n = ai[0]; /* The first element of an INTARRAY is always the
** count of the number of elements to follow */
for(i=1; i<=n; i++){
sqlite3_str_appendf(&x, ",%d", ai[i]);
}
zTemp[0] = '[';
sqlite3_str_append(&x, "]", 1);
break;
}
case P4_SUBPROGRAM: {
sqlite3_str_appendf(&x, "program");
break;
}
case P4_DYNBLOB:
case P4_ADVANCE: {
zTemp[0] = 0;
break;
}
case P4_TABLE: {
sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
break;
}
default: {
zP4 = pOp->p4.z;
if( zP4==0 ){
zP4 = zTemp;
zTemp[0] = 0;
}
}
}
sqlite3StrAccumFinish(&x);
assert( zP4!=0 );
return zP4;
}
#endif /* VDBE_DISPLAY_P4 */
/*
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
**
** The prepared statements need to know in advance the complete set of
** attached databases that will be use. A mask of these databases
** is maintained in p->btreeMask. The p->lockMask value is the subset of
** p->btreeMask of databases that will require a lock.
*/
void sqlite3VdbeUsesBtree(Vdbe *p, int i){
assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
assert( i<(int)sizeof(p->btreeMask)*8 );
DbMaskSet(p->btreeMask, i);
if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
DbMaskSet(p->lockMask, i);
}
}
#if !defined(SQLITE_OMIT_SHARED_CACHE)
/*
** If SQLite is compiled to support shared-cache mode and to be threadsafe,
** this routine obtains the mutex associated with each BtShared structure
** that may be accessed by the VM passed as an argument. In doing so it also
** sets the BtShared.db member of each of the BtShared structures, ensuring
** that the correct busy-handler callback is invoked if required.
**
** If SQLite is not threadsafe but does support shared-cache mode, then
** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
** of all of BtShared structures accessible via the database handle
** associated with the VM.
**
** If SQLite is not threadsafe and does not support shared-cache mode, this
** function is a no-op.
**
** The p->btreeMask field is a bitmask of all btrees that the prepared
** statement p will ever use. Let N be the number of bits in p->btreeMask
** corresponding to btrees that use shared cache. Then the runtime of
** this routine is N*N. But as N is rarely more than 1, this should not
** be a problem.
*/
void sqlite3VdbeEnter(Vdbe *p){
int i;
sqlite3 *db;
Db *aDb;
int nDb;
if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
db = p->db;
aDb = db->aDb;
nDb = db->nDb;
for(i=0; i<nDb; i++){
if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
sqlite3BtreeEnter(aDb[i].pBt);
}
}
}
#endif
#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
/*
** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
*/
static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
int i;
sqlite3 *db;
Db *aDb;
int nDb;
db = p->db;
aDb = db->aDb;
nDb = db->nDb;
for(i=0; i<nDb; i++){
if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
sqlite3BtreeLeave(aDb[i].pBt);
}
}
}
void sqlite3VdbeLeave(Vdbe *p){
if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
vdbeLeave(p);
}
#endif
#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Print a single opcode. This routine is used for debugging only.
*/
void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
char *zP4;
char zPtr[50];
char zCom[100];
static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
if( pOut==0 ) pOut = stdout;
zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
displayComment(pOp, zP4, zCom, sizeof(zCom));
#else
zCom[0] = 0;
#endif
/* NB: The sqlite3OpcodeName() function is implemented by code created
** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
** information from the vdbe.c source text */
fprintf(pOut, zFormat1, pc,
sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
zCom
);
fflush(pOut);
}
#endif
/*
** Initialize an array of N Mem element.
*/
static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
while( (N--)>0 ){
p->db = db;
p->flags = flags;
p->szMalloc = 0;
#ifdef SQLITE_DEBUG
p->pScopyFrom = 0;
#endif
p++;
}
}
/*
** Release an array of N Mem elements
*/
static void releaseMemArray(Mem *p, int N){
if( p && N ){
Mem *pEnd = &p[N];
sqlite3 *db = p->db;
if( db->pnBytesFreed ){
do{
if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
}while( (++p)<pEnd );
return;
}
do{
assert( (&p[1])==pEnd || p[0].db==p[1].db );
assert( sqlite3VdbeCheckMemInvariants(p) );
/* This block is really an inlined version of sqlite3VdbeMemRelease()
** that takes advantage of the fact that the memory cell value is
** being set to NULL after releasing any dynamic resources.
**
** The justification for duplicating code is that according to
** callgrind, this causes a certain test case to hit the CPU 4.7
** percent less (x86 linux, gcc version 4.1.2, -O6) than if
** sqlite3MemRelease() were called from here. With -O2, this jumps
** to 6.6 percent. The test case is inserting 1000 rows into a table
** with no indexes using a single prepared INSERT statement, bind()
** and reset(). Inserts are grouped into a transaction.
*/
testcase( p->flags & MEM_Agg );
testcase( p->flags & MEM_Dyn );
testcase( p->xDel==sqlite3VdbeFrameMemDel );
if( p->flags&(MEM_Agg|MEM_Dyn) ){
sqlite3VdbeMemRelease(p);
}else if( p->szMalloc ){
sqlite3DbFreeNN(db, p->zMalloc);
p->szMalloc = 0;
}
p->flags = MEM_Undefined;
}while( (++p)<pEnd );
}
}
#ifdef SQLITE_DEBUG
/*
** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
** and false if something is wrong.
**
** This routine is intended for use inside of assert() statements only.
*/
int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
return 1;
}
#endif
/*
** This is a destructor on a Mem object (which is really an sqlite3_value)
** that deletes the Frame object that is attached to it as a blob.
**
** This routine does not delete the Frame right away. It merely adds the
** frame to a list of frames to be deleted when the Vdbe halts.
*/
void sqlite3VdbeFrameMemDel(void *pArg){
VdbeFrame *pFrame = (VdbeFrame*)pArg;
assert( sqlite3VdbeFrameIsValid(pFrame) );
pFrame->pParent = pFrame->v->pDelFrame;
pFrame->v->pDelFrame = pFrame;
}
/*
** Delete a VdbeFrame object and its contents. VdbeFrame objects are
** allocated by the OP_Program opcode in sqlite3VdbeExec().
*/
void sqlite3VdbeFrameDelete(VdbeFrame *p){
int i;
Mem *aMem = VdbeFrameMem(p);
VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
assert( sqlite3VdbeFrameIsValid(p) );
for(i=0; i<p->nChildCsr; i++){
sqlite3VdbeFreeCursor(p->v, apCsr[i]);
}
releaseMemArray(aMem, p->nChildMem);
sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
sqlite3DbFree(p->v->db, p);
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Give a listing of the program in the virtual machine.
**
** The interface is the same as sqlite3VdbeExec(). But instead of
** running the code, it invokes the callback once for each instruction.
** This feature is used to implement "EXPLAIN".
**
** When p->explain==1, each instruction is listed. When
** p->explain==2, only OP_Explain instructions are listed and these
** are shown in a different format. p->explain==2 is used to implement
** EXPLAIN QUERY PLAN.
** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
** are also shown, so that the boundaries between the main program and
** each trigger are clear.
**
** When p->explain==1, first the main program is listed, then each of
** the trigger subprograms are listed one by one.
*/
int sqlite3VdbeList(
Vdbe *p /* The VDBE */
){
int nRow; /* Stop when row count reaches this */
int nSub = 0; /* Number of sub-vdbes seen so far */
SubProgram **apSub = 0; /* Array of sub-vdbes */
Mem *pSub = 0; /* Memory cell hold array of subprogs */
sqlite3 *db = p->db; /* The database connection */
int i; /* Loop counter */
int rc = SQLITE_OK; /* Return code */
Mem *pMem = &p->aMem[1]; /* First Mem of result set */
int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
Op *pOp = 0;
assert( p->explain );
assert( p->magic==VDBE_MAGIC_RUN );
assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
/* Even though this opcode does not use dynamic strings for
** the result, result columns may become dynamic if the user calls
** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
*/
releaseMemArray(pMem, 8);
p->pResultSet = 0;
if( p->rc==SQLITE_NOMEM ){
/* This happens if a malloc() inside a call to sqlite3_column_text() or
** sqlite3_column_text16() failed. */
sqlite3OomFault(db);
return SQLITE_ERROR;
}
/* When the number of output rows reaches nRow, that means the
** listing has finished and sqlite3_step() should return SQLITE_DONE.
** nRow is the sum of the number of rows in the main program, plus
** the sum of the number of rows in all trigger subprograms encountered
** so far. The nRow value will increase as new trigger subprograms are
** encountered, but p->pc will eventually catch up to nRow.
*/
nRow = p->nOp;
if( bListSubprogs ){
/* The first 8 memory cells are used for the result set. So we will
** commandeer the 9th cell to use as storage for an array of pointers
** to trigger subprograms. The VDBE is guaranteed to have at least 9
** cells. */
assert( p->nMem>9 );
pSub = &p->aMem[9];
if( pSub->flags&MEM_Blob ){
/* On the first call to sqlite3_step(), pSub will hold a NULL. It is
** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
nSub = pSub->n/sizeof(Vdbe*);
apSub = (SubProgram **)pSub->z;
}
for(i=0; i<nSub; i++){
nRow += apSub[i]->nOp;
}
}
while(1){ /* Loop exits via break */
i = p->pc++;
if( i>=nRow ){
p->rc = SQLITE_OK;
rc = SQLITE_DONE;
break;
}
if( i<p->nOp ){
/* The output line number is small enough that we are still in the
** main program. */
pOp = &p->aOp[i];
}else{
/* We are currently listing subprograms. Figure out which one and
** pick up the appropriate opcode. */
int j;
i -= p->nOp;
assert( apSub!=0 );
assert( nSub>0 );
for(j=0; i>=apSub[j]->nOp; j++){
i -= apSub[j]->nOp;
assert( i<apSub[j]->nOp || j+1<nSub );
}
pOp = &apSub[j]->aOp[i];
}
/* When an OP_Program opcode is encounter (the only opcode that has
** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
** kept in p->aMem[9].z to hold the new program - assuming this subprogram
** has not already been seen.
*/
if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
int nByte = (nSub+1)*sizeof(SubProgram*);
int j;
for(j=0; j<nSub; j++){
if( apSub[j]==pOp->p4.pProgram ) break;
}
if( j==nSub ){
p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
if( p->rc!=SQLITE_OK ){
rc = SQLITE_ERROR;
break;
}
apSub = (SubProgram **)pSub->z;
apSub[nSub++] = pOp->p4.pProgram;
pSub->flags |= MEM_Blob;
pSub->n = nSub*sizeof(SubProgram*);
nRow += pOp->p4.pProgram->nOp;
}
}
if( p->explain<2 ) break;
if( pOp->opcode==OP_Explain ) break;
if( pOp->opcode==OP_Init && p->pc>1 ) break;
}
if( rc==SQLITE_OK ){
if( db->u1.isInterrupted ){
p->rc = SQLITE_INTERRUPT;
rc = SQLITE_ERROR;
sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
}else{
char *zP4;
if( p->explain==1 ){
pMem->flags = MEM_Int;
pMem->u.i = i; /* Program counter */
pMem++;
pMem->flags = MEM_Static|MEM_Str|MEM_Term;
pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
assert( pMem->z!=0 );
pMem->n = sqlite3Strlen30(pMem->z);
pMem->enc = SQLITE_UTF8;
pMem++;
}
pMem->flags = MEM_Int;
pMem->u.i = pOp->p1; /* P1 */
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p2; /* P2 */
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p3; /* P3 */
pMem++;
if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
if( zP4!=pMem->z ){
pMem->n = 0;
sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
}else{
assert( pMem->z!=0 );
pMem->n = sqlite3Strlen30(pMem->z);
pMem->enc = SQLITE_UTF8;
}
pMem++;
if( p->explain==1 ){
if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
pMem->n = 2;
sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
pMem->enc = SQLITE_UTF8;
pMem++;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
pMem->n = displayComment(pOp, zP4, pMem->z, 500);
pMem->enc = SQLITE_UTF8;
#else
pMem->flags = MEM_Null; /* Comment */
#endif
}
p->nResColumn = 8 - 4*(p->explain-1);
p->pResultSet = &p->aMem[1];
p->rc = SQLITE_OK;
rc = SQLITE_ROW;
}
}
return rc;
}
#endif /* SQLITE_OMIT_EXPLAIN */
#ifdef SQLITE_DEBUG
/*
** Print the SQL that was used to generate a VDBE program.
*/
void sqlite3VdbePrintSql(Vdbe *p){
const char *z = 0;
if( p->zSql ){
z = p->zSql;
}else if( p->nOp>=1 ){
const VdbeOp *pOp = &p->aOp[0];
if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
z = pOp->p4.z;
while( sqlite3Isspace(*z) ) z++;
}
}
if( z ) printf("SQL: [%s]\n", z);
}
#endif
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** Print an IOTRACE message showing SQL content.
*/
void sqlite3VdbeIOTraceSql(Vdbe *p){
int nOp = p->nOp;
VdbeOp *pOp;
if( sqlite3IoTrace==0 ) return;
if( nOp<1 ) return;
pOp = &p->aOp[0];
if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
int i, j;
char z[1000];
sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
for(i=0; sqlite3Isspace(z[i]); i++){}
for(j=0; z[i]; i++){
if( sqlite3Isspace(z[i]) ){
if( z[i-1]!=' ' ){
z[j++] = ' ';
}
}else{
z[j++] = z[i];
}
}
z[j] = 0;
sqlite3IoTrace("SQL %s\n", z);
}
}
#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
/* An instance of this object describes bulk memory available for use
** by subcomponents of a prepared statement. Space is allocated out
** of a ReusableSpace object by the allocSpace() routine below.
*/
struct ReusableSpace {
u8 *pSpace; /* Available memory */
sqlite3_int64 nFree; /* Bytes of available memory */
sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
};
/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
** from the ReusableSpace object. Return a pointer to the allocated
** memory on success. If insufficient memory is available in the
** ReusableSpace object, increase the ReusableSpace.nNeeded
** value by the amount needed and return NULL.
**
** If pBuf is not initially NULL, that means that the memory has already
** been allocated by a prior call to this routine, so just return a copy
** of pBuf and leave ReusableSpace unchanged.
**
** This allocator is employed to repurpose unused slots at the end of the
** opcode array of prepared state for other memory needs of the prepared
** statement.
*/
static void *allocSpace(
struct ReusableSpace *p, /* Bulk memory available for allocation */
void *pBuf, /* Pointer to a prior allocation */
sqlite3_int64 nByte /* Bytes of memory needed */
){
assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
if( pBuf==0 ){
nByte = ROUND8(nByte);
if( nByte <= p->nFree ){
p->nFree -= nByte;
pBuf = &p->pSpace[p->nFree];
}else{
p->nNeeded += nByte;
}
}
assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
return pBuf;
}
/*
** Rewind the VDBE back to the beginning in preparation for
** running it.
*/
void sqlite3VdbeRewind(Vdbe *p){
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
int i;
#endif
assert( p!=0 );
assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
/* There should be at least one opcode.
*/
assert( p->nOp>0 );
/* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
p->magic = VDBE_MAGIC_RUN;
#ifdef SQLITE_DEBUG
for(i=0; i<p->nMem; i++){
assert( p->aMem[i].db==p->db );
}
#endif
p->pc = -1;
p->rc = SQLITE_OK;
p->errorAction = OE_Abort;
p->nChange = 0;
p->cacheCtr = 1;
p->minWriteFileFormat = 255;
p->iStatement = 0;
p->nFkConstraint = 0;
#ifdef VDBE_PROFILE
for(i=0; i<p->nOp; i++){
p->aOp[i].cnt = 0;
p->aOp[i].cycles = 0;
}
#endif
}
/*
** Prepare a virtual machine for execution for the first time after
** creating the virtual machine. This involves things such
** as allocating registers and initializing the program counter.
** After the VDBE has be prepped, it can be executed by one or more
** calls to sqlite3VdbeExec().
**
** This function may be called exactly once on each virtual machine.
** After this routine is called the VM has been "packaged" and is ready
** to run. After this routine is called, further calls to
** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
** the Vdbe from the Parse object that helped generate it so that the
** the Vdbe becomes an independent entity and the Parse object can be
** destroyed.
**
** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
** to its initial state after it has been run.
*/
void sqlite3VdbeMakeReady(
Vdbe *p, /* The VDBE */
Parse *pParse /* Parsing context */
){
sqlite3 *db; /* The database connection */
int nVar; /* Number of parameters */
int nMem; /* Number of VM memory registers */
int nCursor; /* Number of cursors required */
int nArg; /* Number of arguments in subprograms */
int n; /* Loop counter */
struct ReusableSpace x; /* Reusable bulk memory */
assert( p!=0 );
assert( p->nOp>0 );
assert( pParse!=0 );
assert( p->magic==VDBE_MAGIC_INIT );
assert( pParse==p->pParse );
db = p->db;
assert( db->mallocFailed==0 );
nVar = pParse->nVar;
nMem = pParse->nMem;
nCursor = pParse->nTab;
nArg = pParse->nMaxArg;
/* Each cursor uses a memory cell. The first cursor (cursor 0) can
** use aMem[0] which is not otherwise used by the VDBE program. Allocate
** space at the end of aMem[] for cursors 1 and greater.
** See also: allocateCursor().
*/
nMem += nCursor;
if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
/* Figure out how much reusable memory is available at the end of the
** opcode array. This extra memory will be reallocated for other elements
** of the prepared statement.
*/
n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
assert( x.nFree>=0 );
assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
resolveP2Values(p, &nArg);
p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
if( pParse->explain ){
static const char * const azColName[] = {
"addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
"id", "parent", "notused", "detail"
};
int iFirst, mx, i;
if( nMem<10 ) nMem = 10;
if( pParse->explain==2 ){
sqlite3VdbeSetNumCols(p, 4);
iFirst = 8;
mx = 12;
}else{
sqlite3VdbeSetNumCols(p, 8);
iFirst = 0;
mx = 8;
}
for(i=iFirst; i<mx; i++){
sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
azColName[i], SQLITE_STATIC);
}
}
p->expired = 0;
/* Memory for registers, parameters, cursor, etc, is allocated in one or two
** passes. On the first pass, we try to reuse unused memory at the
** end of the opcode array. If we are unable to satisfy all memory
** requirements by reusing the opcode array tail, then the second
** pass will fill in the remainder using a fresh memory allocation.
**
** This two-pass approach that reuses as much memory as possible from
** the leftover memory at the end of the opcode array. This can significantly
** reduce the amount of memory held by a prepared statement.
*/
x.nNeeded = 0;
p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
#endif
if( x.nNeeded ){
x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
x.nFree = x.nNeeded;
if( !db->mallocFailed ){
p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
#endif
}
}
p->pVList = pParse->pVList;
pParse->pVList = 0;
p->explain = pParse->explain;
if( db->mallocFailed ){
p->nVar = 0;
p->nCursor = 0;
p->nMem = 0;
}else{
p->nCursor = nCursor;
p->nVar = (ynVar)nVar;
initMemArray(p->aVar, nVar, db, MEM_Null);
p->nMem = nMem;
initMemArray(p->aMem, nMem, db, MEM_Undefined);
memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
memset(p->anExec, 0, p->nOp*sizeof(i64));
#endif
}
sqlite3VdbeRewind(p);
}
/*
** Close a VDBE cursor and release all the resources that cursor
** happens to hold.
*/
void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
if( pCx==0 ){
return;
}
assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
switch( pCx->eCurType ){
case CURTYPE_SORTER: {
sqlite3VdbeSorterClose(p->db, pCx);
break;
}
case CURTYPE_BTREE: {
if( pCx->isEphemeral ){
if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
/* The pCx->pCursor will be close automatically, if it exists, by
** the call above. */
}else{
assert( pCx->uc.pCursor!=0 );
sqlite3BtreeCloseCursor(pCx->uc.pCursor);
}
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case CURTYPE_VTAB: {
sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
const sqlite3_module *pModule = pVCur->pVtab->pModule;
assert( pVCur->pVtab->nRef>0 );
pVCur->pVtab->nRef--;
pModule->xClose(pVCur);
break;
}
#endif
}
}
/*
** Close all cursors in the current frame.
*/
static void closeCursorsInFrame(Vdbe *p){
if( p->apCsr ){
int i;
for(i=0; i<p->nCursor; i++){
VdbeCursor *pC = p->apCsr[i];
if( pC ){
sqlite3VdbeFreeCursor(p, pC);
p->apCsr[i] = 0;
}
}
}
}
/*
** Copy the values stored in the VdbeFrame structure to its Vdbe. This
** is used, for example, when a trigger sub-program is halted to restore
** control to the main program.
*/
int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
Vdbe *v = pFrame->v;
closeCursorsInFrame(v);
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
v->anExec = pFrame->anExec;
#endif
v->aOp = pFrame->aOp;
v->nOp = pFrame->nOp;
v->aMem = pFrame->aMem;
v->nMem = pFrame->nMem;
v->apCsr = pFrame->apCsr;
v->nCursor = pFrame->nCursor;
v->db->lastRowid = pFrame->lastRowid;
v->nChange = pFrame->nChange;
v->db->nChange = pFrame->nDbChange;
sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
v->pAuxData = pFrame->pAuxData;
pFrame->pAuxData = 0;
return pFrame->pc;
}
/*
** Close all cursors.
**
** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
** cell array. This is necessary as the memory cell array may contain
** pointers to VdbeFrame objects, which may in turn contain pointers to
** open cursors.
*/
static void closeAllCursors(Vdbe *p){
if( p->pFrame ){
VdbeFrame *pFrame;
for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
sqlite3VdbeFrameRestore(pFrame);
p->pFrame = 0;
p->nFrame = 0;
}
assert( p->nFrame==0 );
closeCursorsInFrame(p);
if( p->aMem ){
releaseMemArray(p->aMem, p->nMem);
}
while( p->pDelFrame ){
VdbeFrame *pDel = p->pDelFrame;
p->pDelFrame = pDel->pParent;
sqlite3VdbeFrameDelete(pDel);
}
/* Delete any auxdata allocations made by the VM */
if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
assert( p->pAuxData==0 );
}
/*
** Set the number of result columns that will be returned by this SQL
** statement. This is now set at compile time, rather than during
** execution of the vdbe program so that sqlite3_column_count() can
** be called on an SQL statement before sqlite3_step().
*/
void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
int n;
sqlite3 *db = p->db;
if( p->nResColumn ){
releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
sqlite3DbFree(db, p->aColName);
}
n = nResColumn*COLNAME_N;
p->nResColumn = (u16)nResColumn;
p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
if( p->aColName==0 ) return;
initMemArray(p->aColName, n, db, MEM_Null);
}
/*
** Set the name of the idx'th column to be returned by the SQL statement.
** zName must be a pointer to a nul terminated string.
**
** This call must be made after a call to sqlite3VdbeSetNumCols().
**
** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
*/
int sqlite3VdbeSetColName(
Vdbe *p, /* Vdbe being configured */
int idx, /* Index of column zName applies to */
int var, /* One of the COLNAME_* constants */
const char *zName, /* Pointer to buffer containing name */
void (*xDel)(void*) /* Memory management strategy for zName */
){
int rc;
Mem *pColName;
assert( idx<p->nResColumn );
assert( var<COLNAME_N );
if( p->db->mallocFailed ){
assert( !zName || xDel!=SQLITE_DYNAMIC );
return SQLITE_NOMEM_BKPT;
}
assert( p->aColName!=0 );
pColName = &(p->aColName[idx+var*p->nResColumn]);
rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
return rc;
}
/*
** A read or write transaction may or may not be active on database handle
** db. If a transaction is active, commit it. If there is a
** write-transaction spanning more than one database file, this routine
** takes care of the master journal trickery.
*/
static int vdbeCommit(sqlite3 *db, Vdbe *p){
int i;
int nTrans = 0; /* Number of databases with an active write-transaction
** that are candidates for a two-phase commit using a
** master-journal */
int rc = SQLITE_OK;
int needXcommit = 0;
#ifdef SQLITE_OMIT_VIRTUALTABLE
/* With this option, sqlite3VtabSync() is defined to be simply
** SQLITE_OK so p is not used.
*/
UNUSED_PARAMETER(p);
#endif
/* Before doing anything else, call the xSync() callback for any
** virtual module tables written in this transaction. This has to
** be done before determining whether a master journal file is
** required, as an xSync() callback may add an attached database
** to the transaction.
*/
rc = sqlite3VtabSync(db, p);
/* This loop determines (a) if the commit hook should be invoked and
** (b) how many database files have open write transactions, not
** including the temp database. (b) is important because if more than
** one database file has an open write transaction, a master journal
** file is required for an atomic commit.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( sqlite3BtreeIsInTrans(pBt) ){
/* Whether or not a database might need a master journal depends upon
** its journal mode (among other things). This matrix determines which
** journal modes use a master journal and which do not */
static const u8 aMJNeeded[] = {
/* DELETE */ 1,
/* PERSIST */ 1,
/* OFF */ 0,
/* TRUNCATE */ 1,
/* MEMORY */ 0,
/* WAL */ 0
};
Pager *pPager; /* Pager associated with pBt */
needXcommit = 1;
sqlite3BtreeEnter(pBt);
pPager = sqlite3BtreePager(pBt);
if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
&& aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
&& sqlite3PagerIsMemdb(pPager)==0
){
assert( i!=1 );
nTrans++;
}
rc = sqlite3PagerExclusiveLock(pPager);
sqlite3BtreeLeave(pBt);
}
}
if( rc!=SQLITE_OK ){
return rc;
}
/* If there are any write-transactions at all, invoke the commit hook */
if( needXcommit && db->xCommitCallback ){
rc = db->xCommitCallback(db->pCommitArg);
if( rc ){
return SQLITE_CONSTRAINT_COMMITHOOK;
}
}
/* The simple case - no more than one database file (not counting the
** TEMP database) has a transaction active. There is no need for the
** master-journal.
**
** If the return value of sqlite3BtreeGetFilename() is a zero length
** string, it means the main database is :memory: or a temp file. In
** that case we do not support atomic multi-file commits, so use the
** simple case then too.
*/
if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
|| nTrans<=1
){
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
}
}
/* Do the commit only if all databases successfully complete phase 1.
** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
** IO error while deleting or truncating a journal file. It is unlikely,
** but could happen. In this case abandon processing and return the error.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
}
}
if( rc==SQLITE_OK ){
sqlite3VtabCommit(db);
}
}
/* The complex case - There is a multi-file write-transaction active.
** This requires a master journal file to ensure the transaction is
** committed atomically.
*/
#ifndef SQLITE_OMIT_DISKIO
else{
sqlite3_vfs *pVfs = db->pVfs;
char *zMaster = 0; /* File-name for the master journal */
char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
sqlite3_file *pMaster = 0;
i64 offset = 0;
int res;
int retryCount = 0;
int nMainFile;
/* Select a master journal file name */
nMainFile = sqlite3Strlen30(zMainFile);
zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz%c%c", zMainFile, 0, 0);
if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
do {
u32 iRandom;
if( retryCount ){
if( retryCount>100 ){
sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
break;
}else if( retryCount==1 ){
sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
}
}
retryCount++;
sqlite3_randomness(sizeof(iRandom), &iRandom);
sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
(iRandom>>8)&0xffffff, iRandom&0xff);
/* The antipenultimate character of the master journal name must
** be "9" to avoid name collisions when using 8+3 filenames. */
assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
sqlite3FileSuffix3(zMainFile, zMaster);
rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
}while( rc==SQLITE_OK && res );
if( rc==SQLITE_OK ){
/* Open the master journal. */
rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
);
}
if( rc!=SQLITE_OK ){
sqlite3DbFree(db, zMaster);
return rc;
}
/* Write the name of each database file in the transaction into the new
** master journal file. If an error occurs at this point close
** and delete the master journal file. All the individual journal files
** still have 'null' as the master journal pointer, so they will roll
** back independently if a failure occurs.
*/
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( sqlite3BtreeIsInTrans(pBt) ){
char const *zFile = sqlite3BtreeGetJournalname(pBt);
if( zFile==0 ){
continue; /* Ignore TEMP and :memory: databases */
}
assert( zFile[0]!=0 );
rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
offset += sqlite3Strlen30(zFile)+1;
if( rc!=SQLITE_OK ){
sqlite3OsCloseFree(pMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
sqlite3DbFree(db, zMaster);
return rc;
}
}
}
/* Sync the master journal file. If the IOCAP_SEQUENTIAL device
** flag is set this is not required.
*/
if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
&& SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
){
sqlite3OsCloseFree(pMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
sqlite3DbFree(db, zMaster);
return rc;
}
/* Sync all the db files involved in the transaction. The same call
** sets the master journal pointer in each individual journal. If
** an error occurs here, do not delete the master journal file.
**
** If the error occurs during the first call to
** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
** master journal file will be orphaned. But we cannot delete it,
** in case the master journal file name was written into the journal
** file before the failure occurred.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
}
}
sqlite3OsCloseFree(pMaster);
assert( rc!=SQLITE_BUSY );
if( rc!=SQLITE_OK ){
sqlite3DbFree(db, zMaster);
return rc;
}
/* Delete the master journal file. This commits the transaction. After
** doing this the directory is synced again before any individual
** transaction files are deleted.
*/
rc = sqlite3OsDelete(pVfs, zMaster, 1);
sqlite3DbFree(db, zMaster);
zMaster = 0;
if( rc ){
return rc;
}
/* All files and directories have already been synced, so the following
** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
** deleting or truncating journals. If something goes wrong while
** this is happening we don't really care. The integrity of the
** transaction is already guaranteed, but some stray 'cold' journals
** may be lying around. Returning an error code won't help matters.
*/
disable_simulated_io_errors();
sqlite3BeginBenignMalloc();
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
sqlite3BtreeCommitPhaseTwo(pBt, 1);
}
}
sqlite3EndBenignMalloc();
enable_simulated_io_errors();
sqlite3VtabCommit(db);
}
#endif
return rc;
}
/*
** This routine checks that the sqlite3.nVdbeActive count variable
** matches the number of vdbe's in the list sqlite3.pVdbe that are
** currently active. An assertion fails if the two counts do not match.
** This is an internal self-check only - it is not an essential processing
** step.
**
** This is a no-op if NDEBUG is defined.
*/
#ifndef NDEBUG
static void checkActiveVdbeCnt(sqlite3 *db){
Vdbe *p;
int cnt = 0;
int nWrite = 0;
int nRead = 0;
p = db->pVdbe;
while( p ){
if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
cnt++;
if( p->readOnly==0 ) nWrite++;
if( p->bIsReader ) nRead++;
}
p = p->pNext;
}
assert( cnt==db->nVdbeActive );
assert( nWrite==db->nVdbeWrite );
assert( nRead==db->nVdbeRead );
}
#else
#define checkActiveVdbeCnt(x)
#endif
/*
** If the Vdbe passed as the first argument opened a statement-transaction,
** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
** statement transaction is committed.
**
** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
** Otherwise SQLITE_OK.
*/
static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
sqlite3 *const db = p->db;
int rc = SQLITE_OK;
int i;
const int iSavepoint = p->iStatement-1;
assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
assert( db->nStatement>0 );
assert( p->iStatement==(db->nStatement+db->nSavepoint) );
for(i=0; i<db->nDb; i++){
int rc2 = SQLITE_OK;
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
if( eOp==SAVEPOINT_ROLLBACK ){
rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
}
if( rc2==SQLITE_OK ){
rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
}
if( rc==SQLITE_OK ){
rc = rc2;
}
}
}
db->nStatement--;
p->iStatement = 0;
if( rc==SQLITE_OK ){
if( eOp==SAVEPOINT_ROLLBACK ){
rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
}
if( rc==SQLITE_OK ){
rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
}
}
/* If the statement transaction is being rolled back, also restore the
** database handles deferred constraint counter to the value it had when
** the statement transaction was opened. */
if( eOp==SAVEPOINT_ROLLBACK ){
db->nDeferredCons = p->nStmtDefCons;
db->nDeferredImmCons = p->nStmtDefImmCons;
}
return rc;
}
int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
if( p->db->nStatement && p->iStatement ){
return vdbeCloseStatement(p, eOp);
}
return SQLITE_OK;
}
/*
** This function is called when a transaction opened by the database
** handle associated with the VM passed as an argument is about to be
** committed. If there are outstanding deferred foreign key constraint
** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
**
** If there are outstanding FK violations and this function returns
** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
** and write an error message to it. Then return SQLITE_ERROR.
*/
#ifndef SQLITE_OMIT_FOREIGN_KEY
int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
sqlite3 *db = p->db;
if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
|| (!deferred && p->nFkConstraint>0)
){
p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
p->errorAction = OE_Abort;
sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
return SQLITE_ERROR;
}
return SQLITE_OK;
}
#endif
/*
** This routine is called the when a VDBE tries to halt. If the VDBE
** has made changes and is in autocommit mode, then commit those
** changes. If a rollback is needed, then do the rollback.
**
** This routine is the only way to move the state of a VM from
** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
** call this on a VM that is in the SQLITE_MAGIC_HALT state.
**
** Return an error code. If the commit could not complete because of
** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
** means the close did not happen and needs to be repeated.
*/
int sqlite3VdbeHalt(Vdbe *p){
int rc; /* Used to store transient return codes */
sqlite3 *db = p->db;
/* This function contains the logic that determines if a statement or
** transaction will be committed or rolled back as a result of the
** execution of this virtual machine.
**
** If any of the following errors occur:
**
** SQLITE_NOMEM
** SQLITE_IOERR
** SQLITE_FULL
** SQLITE_INTERRUPT
**
** Then the internal cache might have been left in an inconsistent
** state. We need to rollback the statement transaction, if there is
** one, or the complete transaction if there is no statement transaction.
*/
if( p->magic!=VDBE_MAGIC_RUN ){
return SQLITE_OK;
}
if( db->mallocFailed ){
p->rc = SQLITE_NOMEM_BKPT;
}
closeAllCursors(p);
checkActiveVdbeCnt(db);
/* No commit or rollback needed if the program never started or if the
** SQL statement does not read or write a database file. */
if( p->pc>=0 && p->bIsReader ){
int mrc; /* Primary error code from p->rc */
int eStatementOp = 0;
int isSpecialError; /* Set to true if a 'special' error */
/* Lock all btrees used by the statement */
sqlite3VdbeEnter(p);
/* Check for one of the special errors */
mrc = p->rc & 0xff;
isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
|| mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
if( isSpecialError ){
/* If the query was read-only and the error code is SQLITE_INTERRUPT,
** no rollback is necessary. Otherwise, at least a savepoint
** transaction must be rolled back to restore the database to a
** consistent state.
**
** Even if the statement is read-only, it is important to perform
** a statement or transaction rollback operation. If the error
** occurred while writing to the journal, sub-journal or database
** file as part of an effort to free up cache space (see function
** pagerStress() in pager.c), the rollback is required to restore
** the pager to a consistent state.
*/
if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
eStatementOp = SAVEPOINT_ROLLBACK;
}else{
/* We are forced to roll back the active transaction. Before doing
** so, abort any other statements this handle currently has active.
*/
sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
sqlite3CloseSavepoints(db);
db->autoCommit = 1;
p->nChange = 0;
}
}
}
/* Check for immediate foreign key violations. */
if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
sqlite3VdbeCheckFk(p, 0);
}
/* If the auto-commit flag is set and this is the only active writer
** VM, then we do either a commit or rollback of the current transaction.
**
** Note: This block also runs if one of the special errors handled
** above has occurred.
*/
if( !sqlite3VtabInSync(db)
&& db->autoCommit
&& db->nVdbeWrite==(p->readOnly==0)
){
if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
rc = sqlite3VdbeCheckFk(p, 1);
if( rc!=SQLITE_OK ){
if( NEVER(p->readOnly) ){
sqlite3VdbeLeave(p);
return SQLITE_ERROR;
}
rc = SQLITE_CONSTRAINT_FOREIGNKEY;
}else{
/* The auto-commit flag is true, the vdbe program was successful
** or hit an 'OR FAIL' constraint and there are no deferred foreign
** key constraints to hold up the transaction. This means a commit
** is required. */
rc = vdbeCommit(db, p);
}
if( rc==SQLITE_BUSY && p->readOnly ){
sqlite3VdbeLeave(p);
return SQLITE_BUSY;
}else if( rc!=SQLITE_OK ){
p->rc = rc;
sqlite3RollbackAll(db, SQLITE_OK);
p->nChange = 0;
}else{
db->nDeferredCons = 0;
db->nDeferredImmCons = 0;
db->flags &= ~(u64)SQLITE_DeferFKs;
sqlite3CommitInternalChanges(db);
}
}else{
sqlite3RollbackAll(db, SQLITE_OK);
p->nChange = 0;
}
db->nStatement = 0;
}else if( eStatementOp==0 ){
if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
eStatementOp = SAVEPOINT_RELEASE;
}else if( p->errorAction==OE_Abort ){
eStatementOp = SAVEPOINT_ROLLBACK;
}else{
sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
sqlite3CloseSavepoints(db);
db->autoCommit = 1;
p->nChange = 0;
}
}
/* If eStatementOp is non-zero, then a statement transaction needs to
** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
** do so. If this operation returns an error, and the current statement
** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
** current statement error code.
*/
if( eStatementOp ){
rc = sqlite3VdbeCloseStatement(p, eStatementOp);
if( rc ){
if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
p->rc = rc;
sqlite3DbFree(db, p->zErrMsg);
p->zErrMsg = 0;
}
sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
sqlite3CloseSavepoints(db);
db->autoCommit = 1;
p->nChange = 0;
}
}
/* If this was an INSERT, UPDATE or DELETE and no statement transaction
** has been rolled back, update the database connection change-counter.
*/
if( p->changeCntOn ){
if( eStatementOp!=SAVEPOINT_ROLLBACK ){
sqlite3VdbeSetChanges(db, p->nChange);
}else{
sqlite3VdbeSetChanges(db, 0);
}
p->nChange = 0;
}
/* Release the locks */
sqlite3VdbeLeave(p);
}
/* We have successfully halted and closed the VM. Record this fact. */
if( p->pc>=0 ){
db->nVdbeActive--;
if( !p->readOnly ) db->nVdbeWrite--;
if( p->bIsReader ) db->nVdbeRead--;
assert( db->nVdbeActive>=db->nVdbeRead );
assert( db->nVdbeRead>=db->nVdbeWrite );
assert( db->nVdbeWrite>=0 );
}
p->magic = VDBE_MAGIC_HALT;
checkActiveVdbeCnt(db);
if( db->mallocFailed ){
p->rc = SQLITE_NOMEM_BKPT;
}
/* If the auto-commit flag is set to true, then any locks that were held
** by connection db have now been released. Call sqlite3ConnectionUnlocked()
** to invoke any required unlock-notify callbacks.
*/
if( db->autoCommit ){
sqlite3ConnectionUnlocked(db);
}
assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
}
/*
** Each VDBE holds the result of the most recent sqlite3_step() call
** in p->rc. This routine sets that result back to SQLITE_OK.
*/
void sqlite3VdbeResetStepResult(Vdbe *p){
p->rc = SQLITE_OK;
}
/*
** Copy the error code and error message belonging to the VDBE passed
** as the first argument to its database handle (so that they will be
** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
**
** This function does not clear the VDBE error code or message, just
** copies them to the database handle.
*/
int sqlite3VdbeTransferError(Vdbe *p){
sqlite3 *db = p->db;
int rc = p->rc;
if( p->zErrMsg ){
db->bBenignMalloc++;
sqlite3BeginBenignMalloc();
if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
sqlite3EndBenignMalloc();
db->bBenignMalloc--;
}else if( db->pErr ){
sqlite3ValueSetNull(db->pErr);
}
db->errCode = rc;
return rc;
}
#ifdef SQLITE_ENABLE_SQLLOG
/*
** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
** invoke it.
*/
static void vdbeInvokeSqllog(Vdbe *v){
if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
assert( v->db->init.busy==0 );
if( zExpanded ){
sqlite3GlobalConfig.xSqllog(
sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
);
sqlite3DbFree(v->db, zExpanded);
}
}
}
#else
# define vdbeInvokeSqllog(x)
#endif
/*
** Clean up a VDBE after execution but do not delete the VDBE just yet.
** Write any error messages into *pzErrMsg. Return the result code.
**
** After this routine is run, the VDBE should be ready to be executed
** again.
**
** To look at it another way, this routine resets the state of the
** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
** VDBE_MAGIC_INIT.
*/
int sqlite3VdbeReset(Vdbe *p){
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
int i;
#endif
sqlite3 *db;
db = p->db;
/* If the VM did not run to completion or if it encountered an
** error, then it might not have been halted properly. So halt
** it now.
*/
sqlite3VdbeHalt(p);
/* If the VDBE has been run even partially, then transfer the error code
** and error message from the VDBE into the main database structure. But
** if the VDBE has just been set to run but has not actually executed any
** instructions yet, leave the main database error information unchanged.
*/
if( p->pc>=0 ){
vdbeInvokeSqllog(p);
sqlite3VdbeTransferError(p);
if( p->runOnlyOnce ) p->expired = 1;
}else if( p->rc && p->expired ){
/* The expired flag was set on the VDBE before the first call
** to sqlite3_step(). For consistency (since sqlite3_step() was
** called), set the database error in this case as well.
*/
sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
}
/* Reset register contents and reclaim error message memory.
*/
#ifdef SQLITE_DEBUG
/* Execute assert() statements to ensure that the Vdbe.apCsr[] and
** Vdbe.aMem[] arrays have already been cleaned up. */
if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
if( p->aMem ){
for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
}
#endif
sqlite3DbFree(db, p->zErrMsg);
p->zErrMsg = 0;
p->pResultSet = 0;
#ifdef SQLITE_DEBUG
p->nWrite = 0;
#endif
/* Save profiling information from this VDBE run.
*/
#ifdef VDBE_PROFILE
{
FILE *out = fopen("vdbe_profile.out", "a");
if( out ){
fprintf(out, "---- ");
for(i=0; i<p->nOp; i++){
fprintf(out, "%02x", p->aOp[i].opcode);
}
fprintf(out, "\n");
if( p->zSql ){
char c, pc = 0;
fprintf(out, "-- ");
for(i=0; (c = p->zSql[i])!=0; i++){
if( pc=='\n' ) fprintf(out, "-- ");
putc(c, out);
pc = c;
}
if( pc!='\n' ) fprintf(out, "\n");
}
for(i=0; i<p->nOp; i++){
char zHdr[100];
sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
p->aOp[i].cnt,
p->aOp[i].cycles,
p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
);
fprintf(out, "%s", zHdr);
sqlite3VdbePrintOp(out, i, &p->aOp[i]);
}
fclose(out);
}
}
#endif
p->magic = VDBE_MAGIC_RESET;
return p->rc & db->errMask;
}
/*
** Clean up and delete a VDBE after execution. Return an integer which is
** the result code. Write any error message text into *pzErrMsg.
*/
int sqlite3VdbeFinalize(Vdbe *p){
int rc = SQLITE_OK;
if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
rc = sqlite3VdbeReset(p);
assert( (rc & p->db->errMask)==rc );
}
sqlite3VdbeDelete(p);
return rc;
}
/*
** If parameter iOp is less than zero, then invoke the destructor for
** all auxiliary data pointers currently cached by the VM passed as
** the first argument.
**
** Or, if iOp is greater than or equal to zero, then the destructor is
** only invoked for those auxiliary data pointers created by the user
** function invoked by the OP_Function opcode at instruction iOp of
** VM pVdbe, and only then if:
**
** * the associated function parameter is the 32nd or later (counting
** from left to right), or
**
** * the corresponding bit in argument mask is clear (where the first
** function parameter corresponds to bit 0 etc.).
*/
void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
while( *pp ){
AuxData *pAux = *pp;
if( (iOp<0)
|| (pAux->iAuxOp==iOp
&& pAux->iAuxArg>=0
&& (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
){
testcase( pAux->iAuxArg==31 );
if( pAux->xDeleteAux ){
pAux->xDeleteAux(pAux->pAux);
}
*pp = pAux->pNextAux;
sqlite3DbFree(db, pAux);
}else{
pp= &pAux->pNextAux;
}
}
}
/*
** Free all memory associated with the Vdbe passed as the second argument,
** except for object itself, which is preserved.
**
** The difference between this function and sqlite3VdbeDelete() is that
** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
** the database connection and frees the object itself.
*/
void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
SubProgram *pSub, *pNext;
assert( p->db==0 || p->db==db );
releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
for(pSub=p->pProgram; pSub; pSub=pNext){
pNext = pSub->pNext;
vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
sqlite3DbFree(db, pSub);
}
if( p->magic!=VDBE_MAGIC_INIT ){
releaseMemArray(p->aVar, p->nVar);
sqlite3DbFree(db, p->pVList);
sqlite3DbFree(db, p->pFree);
}
vdbeFreeOpArray(db, p->aOp, p->nOp);
sqlite3DbFree(db, p->aColName);
sqlite3DbFree(db, p->zSql);
#ifdef SQLITE_ENABLE_NORMALIZE
sqlite3DbFree(db, p->zNormSql);
{
DblquoteStr *pThis, *pNext;
for(pThis=p->pDblStr; pThis; pThis=pNext){
pNext = pThis->pNextStr;
sqlite3DbFree(db, pThis);
}
}
#endif
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
{
int i;
for(i=0; i<p->nScan; i++){
sqlite3DbFree(db, p->aScan[i].zName);
}
sqlite3DbFree(db, p->aScan);
}
#endif
}
/*
** Delete an entire VDBE.
*/
void sqlite3VdbeDelete(Vdbe *p){
sqlite3 *db;
assert( p!=0 );
db = p->db;
assert( sqlite3_mutex_held(db->mutex) );
sqlite3VdbeClearObject(db, p);
if( p->pPrev ){
p->pPrev->pNext = p->pNext;
}else{
assert( db->pVdbe==p );
db->pVdbe = p->pNext;
}
if( p->pNext ){
p->pNext->pPrev = p->pPrev;
}
p->magic = VDBE_MAGIC_DEAD;
p->db = 0;
sqlite3DbFreeNN(db, p);
}
/*
** The cursor "p" has a pending seek operation that has not yet been
** carried out. Seek the cursor now. If an error occurs, return
** the appropriate error code.
*/
static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
int res, rc;
#ifdef SQLITE_TEST
extern int sqlite3_search_count;
#endif
assert( p->deferredMoveto );
assert( p->isTable );
assert( p->eCurType==CURTYPE_BTREE );
rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
if( rc ) return rc;
if( res!=0 ) return SQLITE_CORRUPT_BKPT;
#ifdef SQLITE_TEST
sqlite3_search_count++;
#endif
p->deferredMoveto = 0;
p->cacheStatus = CACHE_STALE;
return SQLITE_OK;
}
/*
** Something has moved cursor "p" out of place. Maybe the row it was
** pointed to was deleted out from under it. Or maybe the btree was
** rebalanced. Whatever the cause, try to restore "p" to the place it
** is supposed to be pointing. If the row was deleted out from under the
** cursor, set the cursor to point to a NULL row.
*/
static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
int isDifferentRow, rc;
assert( p->eCurType==CURTYPE_BTREE );
assert( p->uc.pCursor!=0 );
assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
p->cacheStatus = CACHE_STALE;
if( isDifferentRow ) p->nullRow = 1;
return rc;
}
/*
** Check to ensure that the cursor is valid. Restore the cursor
** if need be. Return any I/O error from the restore operation.
*/
int sqlite3VdbeCursorRestore(VdbeCursor *p){
assert( p->eCurType==CURTYPE_BTREE );
if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
return handleMovedCursor(p);
}
return SQLITE_OK;
}
/*
** Make sure the cursor p is ready to read or write the row to which it
** was last positioned. Return an error code if an OOM fault or I/O error
** prevents us from positioning the cursor to its correct position.
**
** If a MoveTo operation is pending on the given cursor, then do that
** MoveTo now. If no move is pending, check to see if the row has been
** deleted out from under the cursor and if it has, mark the row as
** a NULL row.
**
** If the cursor is already pointing to the correct row and that row has
** not been deleted out from under the cursor, then this routine is a no-op.
*/
int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
VdbeCursor *p = *pp;
assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
if( p->deferredMoveto ){
int iMap;
if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
*pp = p->pAltCursor;
*piCol = iMap - 1;
return SQLITE_OK;
}
return handleDeferredMoveto(p);
}
if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
return handleMovedCursor(p);
}
return SQLITE_OK;
}
/*
** The following functions:
**
** sqlite3VdbeSerialType()
** sqlite3VdbeSerialTypeLen()
** sqlite3VdbeSerialLen()
** sqlite3VdbeSerialPut()
** sqlite3VdbeSerialGet()
**
** encapsulate the code that serializes values for storage in SQLite
** data and index records. Each serialized value consists of a
** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
** integer, stored as a varint.
**
** In an SQLite index record, the serial type is stored directly before
** the blob of data that it corresponds to. In a table record, all serial
** types are stored at the start of the record, and the blobs of data at
** the end. Hence these functions allow the caller to handle the
** serial-type and data blob separately.
**
** The following table describes the various storage classes for data:
**
** serial type bytes of data type
** -------------- --------------- ---------------
** 0 0 NULL
** 1 1 signed integer
** 2 2 signed integer
** 3 3 signed integer
** 4 4 signed integer
** 5 6 signed integer
** 6 8 signed integer
** 7 8 IEEE float
** 8 0 Integer constant 0
** 9 0 Integer constant 1
** 10,11 reserved for expansion
** N>=12 and even (N-12)/2 BLOB
** N>=13 and odd (N-13)/2 text
**
** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
** of SQLite will not understand those serial types.
*/
#if 0 /* Inlined into the OP_MakeRecord opcode */
/*
** Return the serial-type for the value stored in pMem.
**
** This routine might convert a large MEM_IntReal value into MEM_Real.
**
** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
** opcode in the byte-code engine. But by moving this routine in-line, we
** can omit some redundant tests and make that opcode a lot faster. So
** this routine is now only used by the STAT3 logic and STAT3 support has
** ended. The code is kept here for historical reference only.
*/
u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
int flags = pMem->flags;
u32 n;
assert( pLen!=0 );
if( flags&MEM_Null ){
*pLen = 0;
return 0;
}
if( flags&(MEM_Int|MEM_IntReal) ){
/* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
i64 i = pMem->u.i;
u64 u;
testcase( flags & MEM_Int );
testcase( flags & MEM_IntReal );
if( i<0 ){
u = ~i;
}else{
u = i;
}
if( u<=127 ){
if( (i&1)==i && file_format>=4 ){
*pLen = 0;
return 8+(u32)u;
}else{
*pLen = 1;
return 1;
}
}
if( u<=32767 ){ *pLen = 2; return 2; }
if( u<=8388607 ){ *pLen = 3; return 3; }
if( u<=2147483647 ){ *pLen = 4; return 4; }
if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
*pLen = 8;
if( flags&MEM_IntReal ){
/* If the value is IntReal and is going to take up 8 bytes to store
** as an integer, then we might as well make it an 8-byte floating
** point value */
pMem->u.r = (double)pMem->u.i;
pMem->flags &= ~MEM_IntReal;
pMem->flags |= MEM_Real;
return 7;
}
return 6;
}
if( flags&MEM_Real ){
*pLen = 8;
return 7;
}
assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
assert( pMem->n>=0 );
n = (u32)pMem->n;
if( flags & MEM_Zero ){
n += pMem->u.nZero;
}
*pLen = n;
return ((n*2) + 12 + ((flags&MEM_Str)!=0));
}
#endif /* inlined into OP_MakeRecord */
/*
** The sizes for serial types less than 128
*/
static const u8 sqlite3SmallTypeSizes[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
/* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
/* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
/* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
/* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
/* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
/* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
/* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
/* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
/* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
/* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
/* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
/* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
};
/*
** Return the length of the data corresponding to the supplied serial-type.
*/
u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
if( serial_type>=128 ){
return (serial_type-12)/2;
}else{
assert( serial_type<12
|| sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
return sqlite3SmallTypeSizes[serial_type];
}
}
u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
assert( serial_type<128 );
return sqlite3SmallTypeSizes[serial_type];
}
/*
** If we are on an architecture with mixed-endian floating
** points (ex: ARM7) then swap the lower 4 bytes with the
** upper 4 bytes. Return the result.
**
** For most architectures, this is a no-op.
**
** (later): It is reported to me that the mixed-endian problem
** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
** that early versions of GCC stored the two words of a 64-bit
** float in the wrong order. And that error has been propagated
** ever since. The blame is not necessarily with GCC, though.
** GCC might have just copying the problem from a prior compiler.
** I am also told that newer versions of GCC that follow a different
** ABI get the byte order right.
**
** Developers using SQLite on an ARM7 should compile and run their
** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
** enabled, some asserts below will ensure that the byte order of
** floating point values is correct.
**
** (2007-08-30) Frank van Vugt has studied this problem closely
** and has send his findings to the SQLite developers. Frank
** writes that some Linux kernels offer floating point hardware
** emulation that uses only 32-bit mantissas instead of a full
** 48-bits as required by the IEEE standard. (This is the
** CONFIG_FPE_FASTFPE option.) On such systems, floating point
** byte swapping becomes very complicated. To avoid problems,
** the necessary byte swapping is carried out using a 64-bit integer
** rather than a 64-bit float. Frank assures us that the code here
** works for him. We, the developers, have no way to independently
** verify this, but Frank seems to know what he is talking about
** so we trust him.
*/
#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
static u64 floatSwap(u64 in){
union {
u64 r;
u32 i[2];
} u;
u32 t;
u.r = in;
t = u.i[0];
u.i[0] = u.i[1];
u.i[1] = t;
return u.r;
}
# define swapMixedEndianFloat(X) X = floatSwap(X)
#else
# define swapMixedEndianFloat(X)
#endif
/*
** Write the serialized data blob for the value stored in pMem into
** buf. It is assumed that the caller has allocated sufficient space.
** Return the number of bytes written.
**
** nBuf is the amount of space left in buf[]. The caller is responsible
** for allocating enough space to buf[] to hold the entire field, exclusive
** of the pMem->u.nZero bytes for a MEM_Zero value.
**
** Return the number of bytes actually written into buf[]. The number
** of bytes in the zero-filled tail is included in the return value only
** if those bytes were zeroed in buf[].
*/
u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
u32 len;
/* Integer and Real */
if( serial_type<=7 && serial_type>0 ){
u64 v;
u32 i;
if( serial_type==7 ){
assert( sizeof(v)==sizeof(pMem->u.r) );
memcpy(&v, &pMem->u.r, sizeof(v));
swapMixedEndianFloat(v);
}else{
v = pMem->u.i;
}
len = i = sqlite3SmallTypeSizes[serial_type];
assert( i>0 );
do{
buf[--i] = (u8)(v&0xFF);
v >>= 8;
}while( i );
return len;
}
/* String or blob */
if( serial_type>=12 ){
assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
== (int)sqlite3VdbeSerialTypeLen(serial_type) );
len = pMem->n;
if( len>0 ) memcpy(buf, pMem->z, len);
return len;
}
/* NULL or constants 0 or 1 */
return 0;
}
/* Input "x" is a sequence of unsigned characters that represent a
** big-endian integer. Return the equivalent native integer
*/
#define ONE_BYTE_INT(x) ((i8)(x)[0])
#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
/*
** Deserialize the data blob pointed to by buf as serial type serial_type
** and store the result in pMem. Return the number of bytes read.
**
** This function is implemented as two separate routines for performance.
** The few cases that require local variables are broken out into a separate
** routine so that in most cases the overhead of moving the stack pointer
** is avoided.
*/
static u32 serialGet(
const unsigned char *buf, /* Buffer to deserialize from */
u32 serial_type, /* Serial type to deserialize */
Mem *pMem /* Memory cell to write value into */
){
u64 x = FOUR_BYTE_UINT(buf);
u32 y = FOUR_BYTE_UINT(buf+4);
x = (x<<32) + y;
if( serial_type==6 ){
/* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
** twos-complement integer. */
pMem->u.i = *(i64*)&x;
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
}else{
/* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
** floating point number. */
#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
/* Verify that integers and floating point values use the same
** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
** defined that 64-bit floating point values really are mixed
** endian.
*/
static const u64 t1 = ((u64)0x3ff00000)<<32;
static const double r1 = 1.0;
u64 t2 = t1;
swapMixedEndianFloat(t2);
assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
#endif
assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
swapMixedEndianFloat(x);
memcpy(&pMem->u.r, &x, sizeof(x));
pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
}
return 8;
}
u32 sqlite3VdbeSerialGet(
const unsigned char *buf, /* Buffer to deserialize from */
u32 serial_type, /* Serial type to deserialize */
Mem *pMem /* Memory cell to write value into */
){
switch( serial_type ){
case 10: { /* Internal use only: NULL with virtual table
** UPDATE no-change flag set */
pMem->flags = MEM_Null|MEM_Zero;
pMem->n = 0;
pMem->u.nZero = 0;
break;
}
case 11: /* Reserved for future use */
case 0: { /* Null */
/* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
pMem->flags = MEM_Null;
break;
}
case 1: {
/* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
** integer. */
pMem->u.i = ONE_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 1;
}
case 2: { /* 2-byte signed integer */
/* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
** twos-complement integer. */
pMem->u.i = TWO_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 2;
}
case 3: { /* 3-byte signed integer */
/* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
** twos-complement integer. */
pMem->u.i = THREE_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 3;
}
case 4: { /* 4-byte signed integer */
/* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
** twos-complement integer. */
pMem->u.i = FOUR_BYTE_INT(buf);
#ifdef __HP_cc
/* Work around a sign-extension bug in the HP compiler for HP/UX */
if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
#endif
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 4;
}
case 5: { /* 6-byte signed integer */
/* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
** twos-complement integer. */
pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 6;
}
case 6: /* 8-byte signed integer */
case 7: { /* IEEE floating point */
/* These use local variables, so do them in a separate routine
** to avoid having to move the frame pointer in the common case */
return serialGet(buf,serial_type,pMem);
}
case 8: /* Integer 0 */
case 9: { /* Integer 1 */
/* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
/* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
pMem->u.i = serial_type-8;
pMem->flags = MEM_Int;
return 0;
}
default: {
/* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
** length.
** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
** (N-13)/2 bytes in length. */
static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
pMem->z = (char *)buf;
pMem->n = (serial_type-12)/2;
pMem->flags = aFlag[serial_type&1];
return pMem->n;
}
}
return 0;
}
/*
** This routine is used to allocate sufficient space for an UnpackedRecord
** structure large enough to be used with sqlite3VdbeRecordUnpack() if
** the first argument is a pointer to KeyInfo structure pKeyInfo.
**
** The space is either allocated using sqlite3DbMallocRaw() or from within
** the unaligned buffer passed via the second and third arguments (presumably
** stack space). If the former, then *ppFree is set to a pointer that should
** be eventually freed by the caller using sqlite3DbFree(). Or, if the
** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
** before returning.
**
** If an OOM error occurs, NULL is returned.
*/
UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
KeyInfo *pKeyInfo /* Description of the record */
){
UnpackedRecord *p; /* Unpacked record to return */
int nByte; /* Number of bytes required for *p */
nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
if( !p ) return 0;
p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
assert( pKeyInfo->aSortFlags!=0 );
p->pKeyInfo = pKeyInfo;
p->nField = pKeyInfo->nKeyField + 1;
return p;
}
/*
** Given the nKey-byte encoding of a record in pKey[], populate the
** UnpackedRecord structure indicated by the fourth argument with the
** contents of the decoded record.
*/
void sqlite3VdbeRecordUnpack(
KeyInfo *pKeyInfo, /* Information about the record format */
int nKey, /* Size of the binary record */
const void *pKey, /* The binary record */
UnpackedRecord *p /* Populate this structure before returning. */
){
const unsigned char *aKey = (const unsigned char *)pKey;
u32 d;
u32 idx; /* Offset in aKey[] to read from */
u16 u; /* Unsigned loop counter */
u32 szHdr;
Mem *pMem = p->aMem;
p->default_rc = 0;
assert( EIGHT_BYTE_ALIGNMENT(pMem) );
idx = getVarint32(aKey, szHdr);
d = szHdr;
u = 0;
while( idx<szHdr && d<=(u32)nKey ){
u32 serial_type;
idx += getVarint32(&aKey[idx], serial_type);
pMem->enc = pKeyInfo->enc;
pMem->db = pKeyInfo->db;
/* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
pMem->szMalloc = 0;
pMem->z = 0;
d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
pMem++;
if( (++u)>=p->nField ) break;
}
if( d>(u32)nKey && u ){
assert( CORRUPT_DB );
/* In a corrupt record entry, the last pMem might have been set up using
** uninitialized memory. Overwrite its value with NULL, to prevent
** warnings from MSAN. */
sqlite3VdbeMemSetNull(pMem-1);
}
assert( u<=pKeyInfo->nKeyField + 1 );
p->nField = u;
}
#ifdef SQLITE_DEBUG
/*
** This function compares two index or table record keys in the same way
** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
** this function deserializes and compares values using the
** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
** in assert() statements to ensure that the optimized code in
** sqlite3VdbeRecordCompare() returns results with these two primitives.
**
** Return true if the result of comparison is equivalent to desiredResult.
** Return false if there is a disagreement.
*/
static int vdbeRecordCompareDebug(
int nKey1, const void *pKey1, /* Left key */
const UnpackedRecord *pPKey2, /* Right key */
int desiredResult /* Correct answer */
){
u32 d1; /* Offset into aKey[] of next data element */
u32 idx1; /* Offset into aKey[] of next header element */
u32 szHdr1; /* Number of bytes in header */
int i = 0;
int rc = 0;
const unsigned char *aKey1 = (const unsigned char *)pKey1;
KeyInfo *pKeyInfo;
Mem mem1;
pKeyInfo = pPKey2->pKeyInfo;
if( pKeyInfo->db==0 ) return 1;
mem1.enc = pKeyInfo->enc;
mem1.db = pKeyInfo->db;
/* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
/* Compilers may complain that mem1.u.i is potentially uninitialized.
** We could initialize it, as shown here, to silence those complaints.
** But in fact, mem1.u.i will never actually be used uninitialized, and doing
** the unnecessary initialization has a measurable negative performance
** impact, since this routine is a very high runner. And so, we choose
** to ignore the compiler warnings and leave this variable uninitialized.
*/
/* mem1.u.i = 0; // not needed, here to silence compiler warning */
idx1 = getVarint32(aKey1, szHdr1);
if( szHdr1>98307 ) return SQLITE_CORRUPT;
d1 = szHdr1;
assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
assert( pKeyInfo->aSortFlags!=0 );
assert( pKeyInfo->nKeyField>0 );
assert( idx1<=szHdr1 || CORRUPT_DB );
do{
u32 serial_type1;
/* Read the serial types for the next element in each key. */
idx1 += getVarint32( aKey1+idx1, serial_type1 );
/* Verify that there is enough key space remaining to avoid
** a buffer overread. The "d1+serial_type1+2" subexpression will
** always be greater than or equal to the amount of required key space.
** Use that approximation to avoid the more expensive call to
** sqlite3VdbeSerialTypeLen() in the common case.
*/
if( d1+(u64)serial_type1+2>(u64)nKey1
&& d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
){
break;
}
/* Extract the values to be compared.
*/
d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
/* Do the comparison
*/
rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
if( rc!=0 ){
assert( mem1.szMalloc==0 ); /* See comment below */
if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
&& ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
){
rc = -rc;
}
if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
rc = -rc; /* Invert the result for DESC sort order. */
}
goto debugCompareEnd;
}
i++;
}while( idx1<szHdr1 && i<pPKey2->nField );
/* No memory allocation is ever used on mem1. Prove this using
** the following assert(). If the assert() fails, it indicates a
** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
*/
assert( mem1.szMalloc==0 );
/* rc==0 here means that one of the keys ran out of fields and
** all the fields up to that point were equal. Return the default_rc
** value. */
rc = pPKey2->default_rc;
debugCompareEnd:
if( desiredResult==0 && rc==0 ) return 1;
if( desiredResult<0 && rc<0 ) return 1;
if( desiredResult>0 && rc>0 ) return 1;
if( CORRUPT_DB ) return 1;
if( pKeyInfo->db->mallocFailed ) return 1;
return 0;
}
#endif
#ifdef SQLITE_DEBUG
/*
** Count the number of fields (a.k.a. columns) in the record given by
** pKey,nKey. The verify that this count is less than or equal to the
** limit given by pKeyInfo->nAllField.
**
** If this constraint is not satisfied, it means that the high-speed
** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
** not work correctly. If this assert() ever fires, it probably means
** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
** incorrectly.
*/
static void vdbeAssertFieldCountWithinLimits(
int nKey, const void *pKey, /* The record to verify */
const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
){
int nField = 0;
u32 szHdr;
u32 idx;
u32 notUsed;
const unsigned char *aKey = (const unsigned char*)pKey;
if( CORRUPT_DB ) return;
idx = getVarint32(aKey, szHdr);
assert( nKey>=0 );
assert( szHdr<=(u32)nKey );
while( idx<szHdr ){
idx += getVarint32(aKey+idx, notUsed);
nField++;
}
assert( nField <= pKeyInfo->nAllField );
}
#else
# define vdbeAssertFieldCountWithinLimits(A,B,C)
#endif
/*
** Both *pMem1 and *pMem2 contain string values. Compare the two values
** using the collation sequence pColl. As usual, return a negative , zero
** or positive value if *pMem1 is less than, equal to or greater than
** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
*/
static int vdbeCompareMemString(
const Mem *pMem1,
const Mem *pMem2,
const CollSeq *pColl,
u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
){
if( pMem1->enc==pColl->enc ){
/* The strings are already in the correct encoding. Call the
** comparison function directly */
return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
}else{
int rc;
const void *v1, *v2;
Mem c1;
Mem c2;
sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
if( (v1==0 || v2==0) ){
if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
rc = 0;
}else{
rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
}
sqlite3VdbeMemRelease(&c1);
sqlite3VdbeMemRelease(&c2);
return rc;
}
}
/*
** The input pBlob is guaranteed to be a Blob that is not marked
** with MEM_Zero. Return true if it could be a zero-blob.
*/
static int isAllZero(const char *z, int n){
int i;
for(i=0; i<n; i++){
if( z[i] ) return 0;
}
return 1;
}
/*
** Compare two blobs. Return negative, zero, or positive if the first
** is less than, equal to, or greater than the second, respectively.
** If one blob is a prefix of the other, then the shorter is the lessor.
*/
SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
int c;
int n1 = pB1->n;
int n2 = pB2->n;
/* It is possible to have a Blob value that has some non-zero content
** followed by zero content. But that only comes up for Blobs formed
** by the OP_MakeRecord opcode, and such Blobs never get passed into
** sqlite3MemCompare(). */
assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
if( (pB1->flags|pB2->flags) & MEM_Zero ){
if( pB1->flags & pB2->flags & MEM_Zero ){
return pB1->u.nZero - pB2->u.nZero;
}else if( pB1->flags & MEM_Zero ){
if( !isAllZero(pB2->z, pB2->n) ) return -1;
return pB1->u.nZero - n2;
}else{
if( !isAllZero(pB1->z, pB1->n) ) return +1;
return n1 - pB2->u.nZero;
}
}
c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
if( c ) return c;
return n1 - n2;
}
/*
** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
** number. Return negative, zero, or positive if the first (i64) is less than,
** equal to, or greater than the second (double).
*/
static int sqlite3IntFloatCompare(i64 i, double r){
if( sizeof(LONGDOUBLE_TYPE)>8 ){
LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
if( x<r ) return -1;
if( x>r ) return +1;
return 0;
}else{
i64 y;
double s;
if( r<-9223372036854775808.0 ) return +1;
if( r>=9223372036854775808.0 ) return -1;
y = (i64)r;
if( i<y ) return -1;
if( i>y ) return +1;
s = (double)i;
if( s<r ) return -1;
if( s>r ) return +1;
return 0;
}
}
/*
** Compare the values contained by the two memory cells, returning
** negative, zero or positive if pMem1 is less than, equal to, or greater
** than pMem2. Sorting order is NULL's first, followed by numbers (integers
** and reals) sorted numerically, followed by text ordered by the collating
** sequence pColl and finally blob's ordered by memcmp().
**
** Two NULL values are considered equal by this function.
*/
int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
int f1, f2;
int combined_flags;
f1 = pMem1->flags;
f2 = pMem2->flags;
combined_flags = f1|f2;
assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
/* If one value is NULL, it is less than the other. If both values
** are NULL, return 0.
*/
if( combined_flags&MEM_Null ){
return (f2&MEM_Null) - (f1&MEM_Null);
}
/* At least one of the two values is a number
*/
if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
testcase( combined_flags & MEM_Int );
testcase( combined_flags & MEM_Real );
testcase( combined_flags & MEM_IntReal );
if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
testcase( f1 & f2 & MEM_Int );
testcase( f1 & f2 & MEM_IntReal );
if( pMem1->u.i < pMem2->u.i ) return -1;
if( pMem1->u.i > pMem2->u.i ) return +1;
return 0;
}
if( (f1 & f2 & MEM_Real)!=0 ){
if( pMem1->u.r < pMem2->u.r ) return -1;
if( pMem1->u.r > pMem2->u.r ) return +1;
return 0;
}
if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
testcase( f1 & MEM_Int );
testcase( f1 & MEM_IntReal );
if( (f2&MEM_Real)!=0 ){
return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
}else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
if( pMem1->u.i < pMem2->u.i ) return -1;
if( pMem1->u.i > pMem2->u.i ) return +1;
return 0;
}else{
return -1;
}
}
if( (f1&MEM_Real)!=0 ){
if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
testcase( f2 & MEM_Int );
testcase( f2 & MEM_IntReal );
return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
}else{
return -1;
}
}
return +1;
}
/* If one value is a string and the other is a blob, the string is less.
** If both are strings, compare using the collating functions.
*/
if( combined_flags&MEM_Str ){
if( (f1 & MEM_Str)==0 ){
return 1;
}
if( (f2 & MEM_Str)==0 ){
return -1;
}
assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
assert( pMem1->enc==SQLITE_UTF8 ||
pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
/* The collation sequence must be defined at this point, even if
** the user deletes the collation sequence after the vdbe program is
** compiled (this was not always the case).
*/
assert( !pColl || pColl->xCmp );
if( pColl ){
return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
}
/* If a NULL pointer was passed as the collate function, fall through
** to the blob case and use memcmp(). */
}
/* Both values must be blobs. Compare using memcmp(). */
return sqlite3BlobCompare(pMem1, pMem2);
}
/*
** The first argument passed to this function is a serial-type that
** corresponds to an integer - all values between 1 and 9 inclusive
** except 7. The second points to a buffer containing an integer value
** serialized according to serial_type. This function deserializes
** and returns the value.
*/
static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
u32 y;
assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
switch( serial_type ){
case 0:
case 1:
testcase( aKey[0]&0x80 );
return ONE_BYTE_INT(aKey);
case 2:
testcase( aKey[0]&0x80 );
return TWO_BYTE_INT(aKey);
case 3:
testcase( aKey[0]&0x80 );
return THREE_BYTE_INT(aKey);
case 4: {
testcase( aKey[0]&0x80 );
y = FOUR_BYTE_UINT(aKey);
return (i64)*(int*)&y;
}
case 5: {
testcase( aKey[0]&0x80 );
return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
}
case 6: {
u64 x = FOUR_BYTE_UINT(aKey);
testcase( aKey[0]&0x80 );
x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
return (i64)*(i64*)&x;
}
}
return (serial_type - 8);
}
/*
** This function compares the two table rows or index records
** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
** or positive integer if key1 is less than, equal to or
** greater than key2. The {nKey1, pKey1} key must be a blob
** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
** key must be a parsed key such as obtained from
** sqlite3VdbeParseRecord.
**
** If argument bSkip is non-zero, it is assumed that the caller has already
** determined that the first fields of the keys are equal.
**
** Key1 and Key2 do not have to contain the same number of fields. If all
** fields that appear in both keys are equal, then pPKey2->default_rc is
** returned.
**
** If database corruption is discovered, set pPKey2->errCode to
** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
*/
int sqlite3VdbeRecordCompareWithSkip(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2, /* Right key */
int bSkip /* If true, skip the first field */
){
u32 d1; /* Offset into aKey[] of next data element */
int i; /* Index of next field to compare */
u32 szHdr1; /* Size of record header in bytes */
u32 idx1; /* Offset of first type in header */
int rc = 0; /* Return value */
Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
KeyInfo *pKeyInfo;
const unsigned char *aKey1 = (const unsigned char *)pKey1;
Mem mem1;
/* If bSkip is true, then the caller has already determined that the first
** two elements in the keys are equal. Fix the various stack variables so
** that this routine begins comparing at the second field. */
if( bSkip ){
u32 s1;
idx1 = 1 + getVarint32(&aKey1[1], s1);
szHdr1 = aKey1[0];
d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
i = 1;
pRhs++;
}else{
idx1 = getVarint32(aKey1, szHdr1);
d1 = szHdr1;
i = 0;
}
if( d1>(unsigned)nKey1 ){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}
VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
|| CORRUPT_DB );
assert( pPKey2->pKeyInfo->aSortFlags!=0 );
assert( pPKey2->pKeyInfo->nKeyField>0 );
assert( idx1<=szHdr1 || CORRUPT_DB );
do{
u32 serial_type;
/* RHS is an integer */
if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
testcase( pRhs->flags & MEM_Int );
testcase( pRhs->flags & MEM_IntReal );
serial_type = aKey1[idx1];
testcase( serial_type==12 );
if( serial_type>=10 ){
rc = +1;
}else if( serial_type==0 ){
rc = -1;
}else if( serial_type==7 ){
sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
}else{
i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
i64 rhs = pRhs->u.i;
if( lhs<rhs ){
rc = -1;
}else if( lhs>rhs ){
rc = +1;
}
}
}
/* RHS is real */
else if( pRhs->flags & MEM_Real ){
serial_type = aKey1[idx1];
if( serial_type>=10 ){
/* Serial types 12 or greater are strings and blobs (greater than
** numbers). Types 10 and 11 are currently "reserved for future
** use", so it doesn't really matter what the results of comparing
** them to numberic values are. */
rc = +1;
}else if( serial_type==0 ){
rc = -1;
}else{
sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
if( serial_type==7 ){
if( mem1.u.r<pRhs->u.r ){
rc = -1;
}else if( mem1.u.r>pRhs->u.r ){
rc = +1;
}
}else{
rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
}
}
}
/* RHS is a string */
else if( pRhs->flags & MEM_Str ){
getVarint32(&aKey1[idx1], serial_type);
testcase( serial_type==12 );
if( serial_type<12 ){
rc = -1;
}else if( !(serial_type & 0x01) ){
rc = +1;
}else{
mem1.n = (serial_type - 12) / 2;
testcase( (d1+mem1.n)==(unsigned)nKey1 );
testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
if( (d1+mem1.n) > (unsigned)nKey1
|| (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}else if( pKeyInfo->aColl[i] ){
mem1.enc = pKeyInfo->enc;
mem1.db = pKeyInfo->db;
mem1.flags = MEM_Str;
mem1.z = (char*)&aKey1[d1];
rc = vdbeCompareMemString(
&mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
);
}else{
int nCmp = MIN(mem1.n, pRhs->n);
rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
if( rc==0 ) rc = mem1.n - pRhs->n;
}
}
}
/* RHS is a blob */
else if( pRhs->flags & MEM_Blob ){
assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
getVarint32(&aKey1[idx1], serial_type);
testcase( serial_type==12 );
if( serial_type<12 || (serial_type & 0x01) ){
rc = -1;
}else{
int nStr = (serial_type - 12) / 2;
testcase( (d1+nStr)==(unsigned)nKey1 );
testcase( (d1+nStr+1)==(unsigned)nKey1 );
if( (d1+nStr) > (unsigned)nKey1 ){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}else if( pRhs->flags & MEM_Zero ){
if( !isAllZero((const char*)&aKey1[d1],nStr) ){
rc = 1;
}else{
rc = nStr - pRhs->u.nZero;
}
}else{
int nCmp = MIN(nStr, pRhs->n);
rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
if( rc==0 ) rc = nStr - pRhs->n;
}
}
}
/* RHS is null */
else{
serial_type = aKey1[idx1];
rc = (serial_type!=0);
}
if( rc!=0 ){
int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
if( sortFlags ){
if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
|| ((sortFlags & KEYINFO_ORDER_DESC)
!=(serial_type==0 || (pRhs->flags&MEM_Null)))
){
rc = -rc;
}
}
assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
assert( mem1.szMalloc==0 ); /* See comment below */
return rc;
}
i++;
if( i==pPKey2->nField ) break;
pRhs++;
d1 += sqlite3VdbeSerialTypeLen(serial_type);
idx1 += sqlite3VarintLen(serial_type);
}while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
/* No memory allocation is ever used on mem1. Prove this using
** the following assert(). If the assert() fails, it indicates a
** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
assert( mem1.szMalloc==0 );
/* rc==0 here means that one or both of the keys ran out of fields and
** all the fields up to that point were equal. Return the default_rc
** value. */
assert( CORRUPT_DB
|| vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
|| pPKey2->pKeyInfo->db->mallocFailed
);
pPKey2->eqSeen = 1;
return pPKey2->default_rc;
}
int sqlite3VdbeRecordCompare(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2 /* Right key */
){
return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
}
/*
** This function is an optimized version of sqlite3VdbeRecordCompare()
** that (a) the first field of pPKey2 is an integer, and (b) the
** size-of-header varint at the start of (pKey1/nKey1) fits in a single
** byte (i.e. is less than 128).
**
** To avoid concerns about buffer overreads, this routine is only used
** on schemas where the maximum valid header size is 63 bytes or less.
*/
static int vdbeRecordCompareInt(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2 /* Right key */
){
const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
int serial_type = ((const u8*)pKey1)[1];
int res;
u32 y;
u64 x;
i64 v;
i64 lhs;
vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
switch( serial_type ){
case 1: { /* 1-byte signed integer */
lhs = ONE_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 2: { /* 2-byte signed integer */
lhs = TWO_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 3: { /* 3-byte signed integer */
lhs = THREE_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 4: { /* 4-byte signed integer */
y = FOUR_BYTE_UINT(aKey);
lhs = (i64)*(int*)&y;
testcase( lhs<0 );
break;
}
case 5: { /* 6-byte signed integer */
lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 6: { /* 8-byte signed integer */
x = FOUR_BYTE_UINT(aKey);
x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
lhs = *(i64*)&x;
testcase( lhs<0 );
break;
}
case 8:
lhs = 0;
break;
case 9:
lhs = 1;
break;
/* This case could be removed without changing the results of running
** this code. Including it causes gcc to generate a faster switch
** statement (since the range of switch targets now starts at zero and
** is contiguous) but does not cause any duplicate code to be generated
** (as gcc is clever enough to combine the two like cases). Other
** compilers might be similar. */
case 0: case 7:
return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
default:
return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
}
v = pPKey2->aMem[0].u.i;
if( v>lhs ){
res = pPKey2->r1;
}else if( v<lhs ){
res = pPKey2->r2;
}else if( pPKey2->nField>1 ){
/* The first fields of the two keys are equal. Compare the trailing
** fields. */
res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
}else{
/* The first fields of the two keys are equal and there are no trailing
** fields. Return pPKey2->default_rc in this case. */
res = pPKey2->default_rc;
pPKey2->eqSeen = 1;
}
assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
return res;
}
/*
** This function is an optimized version of sqlite3VdbeRecordCompare()
** that (a) the first field of pPKey2 is a string, that (b) the first field
** uses the collation sequence BINARY and (c) that the size-of-header varint
** at the start of (pKey1/nKey1) fits in a single byte.
*/
static int vdbeRecordCompareString(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2 /* Right key */
){
const u8 *aKey1 = (const u8*)pKey1;
int serial_type;
int res;
assert( pPKey2->aMem[0].flags & MEM_Str );
vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
getVarint32(&aKey1[1], serial_type);
if( serial_type<12 ){
res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
}else if( !(serial_type & 0x01) ){
res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
}else{
int nCmp;
int nStr;
int szHdr = aKey1[0];
nStr = (serial_type-12) / 2;
if( (szHdr + nStr) > nKey1 ){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}
nCmp = MIN( pPKey2->aMem[0].n, nStr );
res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
if( res>0 ){
res = pPKey2->r2;
}else if( res<0 ){
res = pPKey2->r1;
}else{
res = nStr - pPKey2->aMem[0].n;
if( res==0 ){
if( pPKey2->nField>1 ){
res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
}else{
res = pPKey2->default_rc;
pPKey2->eqSeen = 1;
}
}else if( res>0 ){
res = pPKey2->r2;
}else{
res = pPKey2->r1;
}
}
}
assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
|| CORRUPT_DB
|| pPKey2->pKeyInfo->db->mallocFailed
);
return res;
}
/*
** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
** suitable for comparing serialized records to the unpacked record passed
** as the only argument.
*/
RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
/* varintRecordCompareInt() and varintRecordCompareString() both assume
** that the size-of-header varint that occurs at the start of each record
** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
** also assumes that it is safe to overread a buffer by at least the
** maximum possible legal header size plus 8 bytes. Because there is
** guaranteed to be at least 74 (but not 136) bytes of padding following each
** buffer passed to varintRecordCompareInt() this makes it convenient to
** limit the size of the header to 64 bytes in cases where the first field
** is an integer.
**
** The easiest way to enforce this limit is to consider only records with
** 13 fields or less. If the first field is an integer, the maximum legal
** header size is (12*5 + 1 + 1) bytes. */
if( p->pKeyInfo->nAllField<=13 ){
int flags = p->aMem[0].flags;
if( p->pKeyInfo->aSortFlags[0] ){
if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
return sqlite3VdbeRecordCompare;
}
p->r1 = 1;
p->r2 = -1;
}else{
p->r1 = -1;
p->r2 = 1;
}
if( (flags & MEM_Int) ){
return vdbeRecordCompareInt;
}
testcase( flags & MEM_Real );
testcase( flags & MEM_Null );
testcase( flags & MEM_Blob );
if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
&& p->pKeyInfo->aColl[0]==0
){
assert( flags & MEM_Str );
return vdbeRecordCompareString;
}
}
return sqlite3VdbeRecordCompare;
}
/*
** pCur points at an index entry created using the OP_MakeRecord opcode.
** Read the rowid (the last field in the record) and store it in *rowid.
** Return SQLITE_OK if everything works, or an error code otherwise.
**
** pCur might be pointing to text obtained from a corrupt database file.
** So the content cannot be trusted. Do appropriate checks on the content.
*/
int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
i64 nCellKey = 0;
int rc;
u32 szHdr; /* Size of the header */
u32 typeRowid; /* Serial type of the rowid */
u32 lenRowid; /* Size of the rowid */
Mem m, v;
/* Get the size of the index entry. Only indices entries of less
** than 2GiB are support - anything large must be database corruption.
** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
** this code can safely assume that nCellKey is 32-bits
*/
assert( sqlite3BtreeCursorIsValid(pCur) );
nCellKey = sqlite3BtreePayloadSize(pCur);
assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
/* Read in the complete content of the index entry */
sqlite3VdbeMemInit(&m, db, 0);
rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
if( rc ){
return rc;
}
/* The index entry must begin with a header size */
(void)getVarint32((u8*)m.z, szHdr);
testcase( szHdr==3 );
testcase( szHdr==m.n );
testcase( szHdr>0x7fffffff );
assert( m.n>=0 );
if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
goto idx_rowid_corruption;
}
/* The last field of the index should be an integer - the ROWID.
** Verify that the last entry really is an integer. */
(void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
testcase( typeRowid==1 );
testcase( typeRowid==2 );
testcase( typeRowid==3 );
testcase( typeRowid==4 );
testcase( typeRowid==5 );
testcase( typeRowid==6 );
testcase( typeRowid==8 );
testcase( typeRowid==9 );
if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
goto idx_rowid_corruption;
}
lenRowid = sqlite3SmallTypeSizes[typeRowid];
testcase( (u32)m.n==szHdr+lenRowid );
if( unlikely((u32)m.n<szHdr+lenRowid) ){
goto idx_rowid_corruption;
}
/* Fetch the integer off the end of the index record */
sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
*rowid = v.u.i;
sqlite3VdbeMemRelease(&m);
return SQLITE_OK;
/* Jump here if database corruption is detected after m has been
** allocated. Free the m object and return SQLITE_CORRUPT. */
idx_rowid_corruption:
testcase( m.szMalloc!=0 );
sqlite3VdbeMemRelease(&m);
return SQLITE_CORRUPT_BKPT;
}
/*
** Compare the key of the index entry that cursor pC is pointing to against
** the key string in pUnpacked. Write into *pRes a number
** that is negative, zero, or positive if pC is less than, equal to,
** or greater than pUnpacked. Return SQLITE_OK on success.
**
** pUnpacked is either created without a rowid or is truncated so that it
** omits the rowid at the end. The rowid at the end of the index entry
** is ignored as well. Hence, this routine only compares the prefixes
** of the keys prior to the final rowid, not the entire key.
*/
int sqlite3VdbeIdxKeyCompare(
sqlite3 *db, /* Database connection */
VdbeCursor *pC, /* The cursor to compare against */
UnpackedRecord *pUnpacked, /* Unpacked version of key */
int *res /* Write the comparison result here */
){
i64 nCellKey = 0;
int rc;
BtCursor *pCur;
Mem m;
assert( pC->eCurType==CURTYPE_BTREE );
pCur = pC->uc.pCursor;
assert( sqlite3BtreeCursorIsValid(pCur) );
nCellKey = sqlite3BtreePayloadSize(pCur);
/* nCellKey will always be between 0 and 0xffffffff because of the way
** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
if( nCellKey<=0 || nCellKey>0x7fffffff ){
*res = 0;
return SQLITE_CORRUPT_BKPT;
}
sqlite3VdbeMemInit(&m, db, 0);
rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
if( rc ){
return rc;
}
*res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
sqlite3VdbeMemRelease(&m);
return SQLITE_OK;
}
/*
** This routine sets the value to be returned by subsequent calls to
** sqlite3_changes() on the database handle 'db'.
*/
void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
assert( sqlite3_mutex_held(db->mutex) );
db->nChange = nChange;
db->nTotalChange += nChange;
}
/*
** Set a flag in the vdbe to update the change counter when it is finalised
** or reset.
*/
void sqlite3VdbeCountChanges(Vdbe *v){
v->changeCntOn = 1;
}
/*
** Mark every prepared statement associated with a database connection
** as expired.
**
** An expired statement means that recompilation of the statement is
** recommend. Statements expire when things happen that make their
** programs obsolete. Removing user-defined functions or collating
** sequences, or changing an authorization function are the types of
** things that make prepared statements obsolete.
**
** If iCode is 1, then expiration is advisory. The statement should
** be reprepared before being restarted, but if it is already running
** it is allowed to run to completion.
**
** Internally, this function just sets the Vdbe.expired flag on all
** prepared statements. The flag is set to 1 for an immediate expiration
** and set to 2 for an advisory expiration.
*/
void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
Vdbe *p;
for(p = db->pVdbe; p; p=p->pNext){
p->expired = iCode+1;
}
}
/*
** Return the database associated with the Vdbe.
*/
sqlite3 *sqlite3VdbeDb(Vdbe *v){
return v->db;
}
/*
** Return the SQLITE_PREPARE flags for a Vdbe.
*/
u8 sqlite3VdbePrepareFlags(Vdbe *v){
return v->prepFlags;
}
/*
** Return a pointer to an sqlite3_value structure containing the value bound
** parameter iVar of VM v. Except, if the value is an SQL NULL, return
** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
** constants) to the value before returning it.
**
** The returned value must be freed by the caller using sqlite3ValueFree().
*/
sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
assert( iVar>0 );
if( v ){
Mem *pMem = &v->aVar[iVar-1];
assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
if( 0==(pMem->flags & MEM_Null) ){
sqlite3_value *pRet = sqlite3ValueNew(v->db);
if( pRet ){
sqlite3VdbeMemCopy((Mem *)pRet, pMem);
sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
}
return pRet;
}
}
return 0;
}
/*
** Configure SQL variable iVar so that binding a new value to it signals
** to sqlite3_reoptimize() that re-preparing the statement may result
** in a better query plan.
*/
void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
assert( iVar>0 );
assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
if( iVar>=32 ){
v->expmask |= 0x80000000;
}else{
v->expmask |= ((u32)1 << (iVar-1));
}
}
/*
** Cause a function to throw an error if it was call from OP_PureFunc
** rather than OP_Function.
**
** OP_PureFunc means that the function must be deterministic, and should
** throw an error if it is given inputs that would make it non-deterministic.
** This routine is invoked by date/time functions that use non-deterministic
** features such as 'now'.
*/
int sqlite3NotPureFunc(sqlite3_context *pCtx){
const VdbeOp *pOp;
#ifdef SQLITE_ENABLE_STAT4
if( pCtx->pVdbe==0 ) return 1;
#endif
pOp = pCtx->pVdbe->aOp + pCtx->iOp;
if( pOp->opcode==OP_PureFunc ){
const char *zContext;
char *zMsg;
if( pOp->p5 & NC_IsCheck ){
zContext = "a CHECK constraint";
}else if( pOp->p5 & NC_GenCol ){
zContext = "a generated column";
}else{
zContext = "an index";
}
zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
pCtx->pFunc->zName, zContext);
sqlite3_result_error(pCtx, zMsg, -1);
sqlite3_free(zMsg);
return 0;
}
return 1;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
** in memory obtained from sqlite3DbMalloc).
*/
void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
if( pVtab->zErrMsg ){
sqlite3 *db = p->db;
sqlite3DbFree(db, p->zErrMsg);
p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
sqlite3_free(pVtab->zErrMsg);
pVtab->zErrMsg = 0;
}
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** If the second argument is not NULL, release any allocations associated
** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
** structure itself, using sqlite3DbFree().
**
** This function is used to free UnpackedRecord structures allocated by
** the vdbeUnpackRecord() function found in vdbeapi.c.
*/
static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
if( p ){
int i;
for(i=0; i<nField; i++){
Mem *pMem = &p->aMem[i];
if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
}
sqlite3DbFreeNN(db, p);
}
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
** then cursor passed as the second argument should point to the row about
** to be update or deleted. If the application calls sqlite3_preupdate_old(),
** the required value will be read from the row the cursor points to.
*/
void sqlite3VdbePreUpdateHook(
Vdbe *v, /* Vdbe pre-update hook is invoked by */
VdbeCursor *pCsr, /* Cursor to grab old.* values from */
int op, /* SQLITE_INSERT, UPDATE or DELETE */
const char *zDb, /* Database name */
Table *pTab, /* Modified table */
i64 iKey1, /* Initial key value */
int iReg /* Register for new.* record */
){
sqlite3 *db = v->db;
i64 iKey2;
PreUpdate preupdate;
const char *zTbl = pTab->zName;
static const u8 fakeSortOrder = 0;
assert( db->pPreUpdate==0 );
memset(&preupdate, 0, sizeof(PreUpdate));
if( HasRowid(pTab)==0 ){
iKey1 = iKey2 = 0;
preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
}else{
if( op==SQLITE_UPDATE ){
iKey2 = v->aMem[iReg].u.i;
}else{
iKey2 = iKey1;
}
}
assert( pCsr->nField==pTab->nCol
|| (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
);
preupdate.v = v;
preupdate.pCsr = pCsr;
preupdate.op = op;
preupdate.iNewReg = iReg;
preupdate.keyinfo.db = db;
preupdate.keyinfo.enc = ENC(db);
preupdate.keyinfo.nKeyField = pTab->nCol;
preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
preupdate.iKey1 = iKey1;
preupdate.iKey2 = iKey2;
preupdate.pTab = pTab;
db->pPreUpdate = &preupdate;
db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
db->pPreUpdate = 0;
sqlite3DbFree(db, preupdate.aRecord);
vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
if( preupdate.aNew ){
int i;
for(i=0; i<pCsr->nField; i++){
sqlite3VdbeMemRelease(&preupdate.aNew[i]);
}
sqlite3DbFreeNN(db, preupdate.aNew);
}
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_1325_3 |
crossvul-cpp_data_bad_1325_2 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
*/
#include "sqliteInt.h"
/* Forward declarations */
static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
/*
** Return the affinity character for a single column of a table.
*/
char sqlite3TableColumnAffinity(Table *pTab, int iCol){
assert( iCol<pTab->nCol );
return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
}
/*
** Return the 'affinity' of the expression pExpr if any.
**
** If pExpr is a column, a reference to a column via an 'AS' alias,
** or a sub-select with a column as the return value, then the
** affinity of that column is returned. Otherwise, 0x00 is returned,
** indicating no affinity for the expression.
**
** i.e. the WHERE clause expressions in the following statements all
** have an affinity:
**
** CREATE TABLE t1(a);
** SELECT * FROM t1 WHERE a;
** SELECT a AS b FROM t1 WHERE b;
** SELECT * FROM t1 WHERE (select a from t1);
*/
char sqlite3ExprAffinity(Expr *pExpr){
int op;
while( ExprHasProperty(pExpr, EP_Skip) ){
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
assert( pExpr!=0 );
}
op = pExpr->op;
if( op==TK_SELECT ){
assert( pExpr->flags&EP_xIsSelect );
return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
}
if( op==TK_REGISTER ) op = pExpr->op2;
#ifndef SQLITE_OMIT_CAST
if( op==TK_CAST ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
return sqlite3AffinityType(pExpr->u.zToken, 0);
}
#endif
if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
}
if( op==TK_SELECT_COLUMN ){
assert( pExpr->pLeft->flags&EP_xIsSelect );
return sqlite3ExprAffinity(
pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
);
}
if( op==TK_VECTOR ){
return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
}
return pExpr->affExpr;
}
/*
** Set the collating sequence for expression pExpr to be the collating
** sequence named by pToken. Return a pointer to a new Expr node that
** implements the COLLATE operator.
**
** If a memory allocation error occurs, that fact is recorded in pParse->db
** and the pExpr parameter is returned unchanged.
*/
Expr *sqlite3ExprAddCollateToken(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* Add the "COLLATE" clause to this expression */
const Token *pCollName, /* Name of collating sequence */
int dequote /* True to dequote pCollName */
){
if( pCollName->n>0 ){
Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
if( pNew ){
pNew->pLeft = pExpr;
pNew->flags |= EP_Collate|EP_Skip;
pExpr = pNew;
}
}
return pExpr;
}
Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
Token s;
assert( zC!=0 );
sqlite3TokenInit(&s, (char*)zC);
return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
}
/*
** Skip over any TK_COLLATE operators.
*/
Expr *sqlite3ExprSkipCollate(Expr *pExpr){
while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
}
return pExpr;
}
/*
** Skip over any TK_COLLATE operators and/or any unlikely()
** or likelihood() or likely() functions at the root of an
** expression.
*/
Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
if( ExprHasProperty(pExpr, EP_Unlikely) ){
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
assert( pExpr->x.pList->nExpr>0 );
assert( pExpr->op==TK_FUNCTION );
pExpr = pExpr->x.pList->a[0].pExpr;
}else{
assert( pExpr->op==TK_COLLATE );
pExpr = pExpr->pLeft;
}
}
return pExpr;
}
/*
** Return the collation sequence for the expression pExpr. If
** there is no defined collating sequence, return NULL.
**
** See also: sqlite3ExprNNCollSeq()
**
** The sqlite3ExprNNCollSeq() works the same exact that it returns the
** default collation if pExpr has no defined collation.
**
** The collating sequence might be determined by a COLLATE operator
** or by the presence of a column with a defined collating sequence.
** COLLATE operators take first precedence. Left operands take
** precedence over right operands.
*/
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
sqlite3 *db = pParse->db;
CollSeq *pColl = 0;
Expr *p = pExpr;
while( p ){
int op = p->op;
if( op==TK_REGISTER ) op = p->op2;
if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
&& p->y.pTab!=0
){
/* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
** a TK_COLUMN but was previously evaluated and cached in a register */
int j = p->iColumn;
if( j>=0 ){
const char *zColl = p->y.pTab->aCol[j].zColl;
pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
}
break;
}
if( op==TK_CAST || op==TK_UPLUS ){
p = p->pLeft;
continue;
}
if( op==TK_VECTOR ){
p = p->x.pList->a[0].pExpr;
continue;
}
if( op==TK_COLLATE ){
pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
break;
}
if( p->flags & EP_Collate ){
if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
p = p->pLeft;
}else{
Expr *pNext = p->pRight;
/* The Expr.x union is never used at the same time as Expr.pRight */
assert( p->x.pList==0 || p->pRight==0 );
if( p->x.pList!=0
&& !db->mallocFailed
&& ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
pNext = p->x.pList->a[i].pExpr;
break;
}
}
}
p = pNext;
}
}else{
break;
}
}
if( sqlite3CheckCollSeq(pParse, pColl) ){
pColl = 0;
}
return pColl;
}
/*
** Return the collation sequence for the expression pExpr. If
** there is no defined collating sequence, return a pointer to the
** defautl collation sequence.
**
** See also: sqlite3ExprCollSeq()
**
** The sqlite3ExprCollSeq() routine works the same except that it
** returns NULL if there is no defined collation.
*/
CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
if( p==0 ) p = pParse->db->pDfltColl;
assert( p!=0 );
return p;
}
/*
** Return TRUE if the two expressions have equivalent collating sequences.
*/
int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
}
/*
** pExpr is an operand of a comparison operator. aff2 is the
** type affinity of the other operand. This routine returns the
** type affinity that should be used for the comparison operator.
*/
char sqlite3CompareAffinity(Expr *pExpr, char aff2){
char aff1 = sqlite3ExprAffinity(pExpr);
if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
/* Both sides of the comparison are columns. If one has numeric
** affinity, use that. Otherwise use no affinity.
*/
if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
return SQLITE_AFF_NUMERIC;
}else{
return SQLITE_AFF_BLOB;
}
}else{
/* One side is a column, the other is not. Use the columns affinity. */
assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
}
}
/*
** pExpr is a comparison operator. Return the type affinity that should
** be applied to both operands prior to doing the comparison.
*/
static char comparisonAffinity(Expr *pExpr){
char aff;
assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
assert( pExpr->pLeft );
aff = sqlite3ExprAffinity(pExpr->pLeft);
if( pExpr->pRight ){
aff = sqlite3CompareAffinity(pExpr->pRight, aff);
}else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
}else if( aff==0 ){
aff = SQLITE_AFF_BLOB;
}
return aff;
}
/*
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
** idx_affinity is the affinity of an indexed column. Return true
** if the index with affinity idx_affinity may be used to implement
** the comparison in pExpr.
*/
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
char aff = comparisonAffinity(pExpr);
if( aff<SQLITE_AFF_TEXT ){
return 1;
}
if( aff==SQLITE_AFF_TEXT ){
return idx_affinity==SQLITE_AFF_TEXT;
}
return sqlite3IsNumericAffinity(idx_affinity);
}
/*
** Return the P5 value that should be used for a binary comparison
** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
*/
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
u8 aff = (char)sqlite3ExprAffinity(pExpr2);
aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
return aff;
}
/*
** Return a pointer to the collation sequence that should be used by
** a binary comparison operator comparing pLeft and pRight.
**
** If the left hand expression has a collating sequence type, then it is
** used. Otherwise the collation sequence for the right hand expression
** is used, or the default (BINARY) if neither expression has a collating
** type.
**
** Argument pRight (but not pLeft) may be a null pointer. In this case,
** it is not considered.
*/
CollSeq *sqlite3BinaryCompareCollSeq(
Parse *pParse,
Expr *pLeft,
Expr *pRight
){
CollSeq *pColl;
assert( pLeft );
if( pLeft->flags & EP_Collate ){
pColl = sqlite3ExprCollSeq(pParse, pLeft);
}else if( pRight && (pRight->flags & EP_Collate)!=0 ){
pColl = sqlite3ExprCollSeq(pParse, pRight);
}else{
pColl = sqlite3ExprCollSeq(pParse, pLeft);
if( !pColl ){
pColl = sqlite3ExprCollSeq(pParse, pRight);
}
}
return pColl;
}
/* Expresssion p is a comparison operator. Return a collation sequence
** appropriate for the comparison operator.
**
** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
** However, if the OP_Commuted flag is set, then the order of the operands
** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
** correct collating sequence is found.
*/
CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, Expr *p){
if( ExprHasProperty(p, EP_Commuted) ){
return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
}else{
return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
}
}
/*
** Generate code for a comparison operator.
*/
static int codeCompare(
Parse *pParse, /* The parsing (and code generating) context */
Expr *pLeft, /* The left operand */
Expr *pRight, /* The right operand */
int opcode, /* The comparison opcode */
int in1, int in2, /* Register holding operands */
int dest, /* Jump here if true. */
int jumpIfNull, /* If true, jump if either operand is NULL */
int isCommuted /* The comparison has been commuted */
){
int p5;
int addr;
CollSeq *p4;
if( isCommuted ){
p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
}else{
p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
}
p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
(void*)p4, P4_COLLSEQ);
sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
return addr;
}
/*
** Return true if expression pExpr is a vector, or false otherwise.
**
** A vector is defined as any expression that results in two or more
** columns of result. Every TK_VECTOR node is an vector because the
** parser will not generate a TK_VECTOR with fewer than two entries.
** But a TK_SELECT might be either a vector or a scalar. It is only
** considered a vector if it has two or more result columns.
*/
int sqlite3ExprIsVector(Expr *pExpr){
return sqlite3ExprVectorSize(pExpr)>1;
}
/*
** If the expression passed as the only argument is of type TK_VECTOR
** return the number of expressions in the vector. Or, if the expression
** is a sub-select, return the number of columns in the sub-select. For
** any other type of expression, return 1.
*/
int sqlite3ExprVectorSize(Expr *pExpr){
u8 op = pExpr->op;
if( op==TK_REGISTER ) op = pExpr->op2;
if( op==TK_VECTOR ){
return pExpr->x.pList->nExpr;
}else if( op==TK_SELECT ){
return pExpr->x.pSelect->pEList->nExpr;
}else{
return 1;
}
}
/*
** Return a pointer to a subexpression of pVector that is the i-th
** column of the vector (numbered starting with 0). The caller must
** ensure that i is within range.
**
** If pVector is really a scalar (and "scalar" here includes subqueries
** that return a single column!) then return pVector unmodified.
**
** pVector retains ownership of the returned subexpression.
**
** If the vector is a (SELECT ...) then the expression returned is
** just the expression for the i-th term of the result set, and may
** not be ready for evaluation because the table cursor has not yet
** been positioned.
*/
Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
assert( i<sqlite3ExprVectorSize(pVector) );
if( sqlite3ExprIsVector(pVector) ){
assert( pVector->op2==0 || pVector->op==TK_REGISTER );
if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
return pVector->x.pSelect->pEList->a[i].pExpr;
}else{
return pVector->x.pList->a[i].pExpr;
}
}
return pVector;
}
/*
** Compute and return a new Expr object which when passed to
** sqlite3ExprCode() will generate all necessary code to compute
** the iField-th column of the vector expression pVector.
**
** It is ok for pVector to be a scalar (as long as iField==0).
** In that case, this routine works like sqlite3ExprDup().
**
** The caller owns the returned Expr object and is responsible for
** ensuring that the returned value eventually gets freed.
**
** The caller retains ownership of pVector. If pVector is a TK_SELECT,
** then the returned object will reference pVector and so pVector must remain
** valid for the life of the returned object. If pVector is a TK_VECTOR
** or a scalar expression, then it can be deleted as soon as this routine
** returns.
**
** A trick to cause a TK_SELECT pVector to be deleted together with
** the returned Expr object is to attach the pVector to the pRight field
** of the returned TK_SELECT_COLUMN Expr object.
*/
Expr *sqlite3ExprForVectorField(
Parse *pParse, /* Parsing context */
Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
int iField /* Which column of the vector to return */
){
Expr *pRet;
if( pVector->op==TK_SELECT ){
assert( pVector->flags & EP_xIsSelect );
/* The TK_SELECT_COLUMN Expr node:
**
** pLeft: pVector containing TK_SELECT. Not deleted.
** pRight: not used. But recursively deleted.
** iColumn: Index of a column in pVector
** iTable: 0 or the number of columns on the LHS of an assignment
** pLeft->iTable: First in an array of register holding result, or 0
** if the result is not yet computed.
**
** sqlite3ExprDelete() specifically skips the recursive delete of
** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
** can be attached to pRight to cause this node to take ownership of
** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
** with the same pLeft pointer to the pVector, but only one of them
** will own the pVector.
*/
pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
if( pRet ){
pRet->iColumn = iField;
pRet->pLeft = pVector;
}
assert( pRet==0 || pRet->iTable==0 );
}else{
if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
pRet = sqlite3ExprDup(pParse->db, pVector, 0);
sqlite3RenameTokenRemap(pParse, pRet, pVector);
}
return pRet;
}
/*
** If expression pExpr is of type TK_SELECT, generate code to evaluate
** it. Return the register in which the result is stored (or, if the
** sub-select returns more than one column, the first in an array
** of registers in which the result is stored).
**
** If pExpr is not a TK_SELECT expression, return 0.
*/
static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
int reg = 0;
#ifndef SQLITE_OMIT_SUBQUERY
if( pExpr->op==TK_SELECT ){
reg = sqlite3CodeSubselect(pParse, pExpr);
}
#endif
return reg;
}
/*
** Argument pVector points to a vector expression - either a TK_VECTOR
** or TK_SELECT that returns more than one column. This function returns
** the register number of a register that contains the value of
** element iField of the vector.
**
** If pVector is a TK_SELECT expression, then code for it must have
** already been generated using the exprCodeSubselect() routine. In this
** case parameter regSelect should be the first in an array of registers
** containing the results of the sub-select.
**
** If pVector is of type TK_VECTOR, then code for the requested field
** is generated. In this case (*pRegFree) may be set to the number of
** a temporary register to be freed by the caller before returning.
**
** Before returning, output parameter (*ppExpr) is set to point to the
** Expr object corresponding to element iElem of the vector.
*/
static int exprVectorRegister(
Parse *pParse, /* Parse context */
Expr *pVector, /* Vector to extract element from */
int iField, /* Field to extract from pVector */
int regSelect, /* First in array of registers */
Expr **ppExpr, /* OUT: Expression element */
int *pRegFree /* OUT: Temp register to free */
){
u8 op = pVector->op;
assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
if( op==TK_REGISTER ){
*ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
return pVector->iTable+iField;
}
if( op==TK_SELECT ){
*ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
return regSelect+iField;
}
*ppExpr = pVector->x.pList->a[iField].pExpr;
return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
}
/*
** Expression pExpr is a comparison between two vector values. Compute
** the result of the comparison (1, 0, or NULL) and write that
** result into register dest.
**
** The caller must satisfy the following preconditions:
**
** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
** otherwise: op==pExpr->op and p5==0
*/
static void codeVectorCompare(
Parse *pParse, /* Code generator context */
Expr *pExpr, /* The comparison operation */
int dest, /* Write results into this register */
u8 op, /* Comparison operator */
u8 p5 /* SQLITE_NULLEQ or zero */
){
Vdbe *v = pParse->pVdbe;
Expr *pLeft = pExpr->pLeft;
Expr *pRight = pExpr->pRight;
int nLeft = sqlite3ExprVectorSize(pLeft);
int i;
int regLeft = 0;
int regRight = 0;
u8 opx = op;
int addrDone = sqlite3VdbeMakeLabel(pParse);
int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
if( nLeft!=sqlite3ExprVectorSize(pRight) ){
sqlite3ErrorMsg(pParse, "row value misused");
return;
}
assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
|| pExpr->op==TK_IS || pExpr->op==TK_ISNOT
|| pExpr->op==TK_LT || pExpr->op==TK_GT
|| pExpr->op==TK_LE || pExpr->op==TK_GE
);
assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
|| (pExpr->op==TK_ISNOT && op==TK_NE) );
assert( p5==0 || pExpr->op!=op );
assert( p5==SQLITE_NULLEQ || pExpr->op==op );
p5 |= SQLITE_STOREP2;
if( opx==TK_LE ) opx = TK_LT;
if( opx==TK_GE ) opx = TK_GT;
regLeft = exprCodeSubselect(pParse, pLeft);
regRight = exprCodeSubselect(pParse, pRight);
for(i=0; 1 /*Loop exits by "break"*/; i++){
int regFree1 = 0, regFree2 = 0;
Expr *pL, *pR;
int r1, r2;
assert( i>=0 && i<nLeft );
r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1);
r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2);
codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
if( i==nLeft-1 ){
break;
}
if( opx==TK_EQ ){
sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
p5 |= SQLITE_KEEPNULL;
}else if( opx==TK_NE ){
sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
p5 |= SQLITE_KEEPNULL;
}else{
assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
VdbeCoverageIf(v, op==TK_LT);
VdbeCoverageIf(v, op==TK_GT);
VdbeCoverageIf(v, op==TK_LE);
VdbeCoverageIf(v, op==TK_GE);
if( i==nLeft-2 ) opx = op;
}
}
sqlite3VdbeResolveLabel(v, addrDone);
}
#if SQLITE_MAX_EXPR_DEPTH>0
/*
** Check that argument nHeight is less than or equal to the maximum
** expression depth allowed. If it is not, leave an error message in
** pParse.
*/
int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
int rc = SQLITE_OK;
int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
if( nHeight>mxHeight ){
sqlite3ErrorMsg(pParse,
"Expression tree is too large (maximum depth %d)", mxHeight
);
rc = SQLITE_ERROR;
}
return rc;
}
/* The following three functions, heightOfExpr(), heightOfExprList()
** and heightOfSelect(), are used to determine the maximum height
** of any expression tree referenced by the structure passed as the
** first argument.
**
** If this maximum height is greater than the current value pointed
** to by pnHeight, the second parameter, then set *pnHeight to that
** value.
*/
static void heightOfExpr(Expr *p, int *pnHeight){
if( p ){
if( p->nHeight>*pnHeight ){
*pnHeight = p->nHeight;
}
}
}
static void heightOfExprList(ExprList *p, int *pnHeight){
if( p ){
int i;
for(i=0; i<p->nExpr; i++){
heightOfExpr(p->a[i].pExpr, pnHeight);
}
}
}
static void heightOfSelect(Select *pSelect, int *pnHeight){
Select *p;
for(p=pSelect; p; p=p->pPrior){
heightOfExpr(p->pWhere, pnHeight);
heightOfExpr(p->pHaving, pnHeight);
heightOfExpr(p->pLimit, pnHeight);
heightOfExprList(p->pEList, pnHeight);
heightOfExprList(p->pGroupBy, pnHeight);
heightOfExprList(p->pOrderBy, pnHeight);
}
}
/*
** Set the Expr.nHeight variable in the structure passed as an
** argument. An expression with no children, Expr.pList or
** Expr.pSelect member has a height of 1. Any other expression
** has a height equal to the maximum height of any other
** referenced Expr plus one.
**
** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
** if appropriate.
*/
static void exprSetHeight(Expr *p){
int nHeight = 0;
heightOfExpr(p->pLeft, &nHeight);
heightOfExpr(p->pRight, &nHeight);
if( ExprHasProperty(p, EP_xIsSelect) ){
heightOfSelect(p->x.pSelect, &nHeight);
}else if( p->x.pList ){
heightOfExprList(p->x.pList, &nHeight);
p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
}
p->nHeight = nHeight + 1;
}
/*
** Set the Expr.nHeight variable using the exprSetHeight() function. If
** the height is greater than the maximum allowed expression depth,
** leave an error in pParse.
**
** Also propagate all EP_Propagate flags from the Expr.x.pList into
** Expr.flags.
*/
void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
if( pParse->nErr ) return;
exprSetHeight(p);
sqlite3ExprCheckHeight(pParse, p->nHeight);
}
/*
** Return the maximum height of any expression tree referenced
** by the select statement passed as an argument.
*/
int sqlite3SelectExprHeight(Select *p){
int nHeight = 0;
heightOfSelect(p, &nHeight);
return nHeight;
}
#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
/*
** Propagate all EP_Propagate flags from the Expr.x.pList into
** Expr.flags.
*/
void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
}
}
#define exprSetHeight(y)
#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
/*
** This routine is the core allocator for Expr nodes.
**
** Construct a new expression node and return a pointer to it. Memory
** for this node and for the pToken argument is a single allocation
** obtained from sqlite3DbMalloc(). The calling function
** is responsible for making sure the node eventually gets freed.
**
** If dequote is true, then the token (if it exists) is dequoted.
** If dequote is false, no dequoting is performed. The deQuote
** parameter is ignored if pToken is NULL or if the token does not
** appear to be quoted. If the quotes were of the form "..." (double-quotes)
** then the EP_DblQuoted flag is set on the expression node.
**
** Special case: If op==TK_INTEGER and pToken points to a string that
** can be translated into a 32-bit integer, then the token is not
** stored in u.zToken. Instead, the integer values is written
** into u.iValue and the EP_IntValue flag is set. No extra storage
** is allocated to hold the integer text and the dequote flag is ignored.
*/
Expr *sqlite3ExprAlloc(
sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
int op, /* Expression opcode */
const Token *pToken, /* Token argument. Might be NULL */
int dequote /* True to dequote */
){
Expr *pNew;
int nExtra = 0;
int iValue = 0;
assert( db!=0 );
if( pToken ){
if( op!=TK_INTEGER || pToken->z==0
|| sqlite3GetInt32(pToken->z, &iValue)==0 ){
nExtra = pToken->n+1;
assert( iValue>=0 );
}
}
pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
if( pNew ){
memset(pNew, 0, sizeof(Expr));
pNew->op = (u8)op;
pNew->iAgg = -1;
if( pToken ){
if( nExtra==0 ){
pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
pNew->u.iValue = iValue;
}else{
pNew->u.zToken = (char*)&pNew[1];
assert( pToken->z!=0 || pToken->n==0 );
if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
pNew->u.zToken[pToken->n] = 0;
if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
sqlite3DequoteExpr(pNew);
}
}
}
#if SQLITE_MAX_EXPR_DEPTH>0
pNew->nHeight = 1;
#endif
}
return pNew;
}
/*
** Allocate a new expression node from a zero-terminated token that has
** already been dequoted.
*/
Expr *sqlite3Expr(
sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
int op, /* Expression opcode */
const char *zToken /* Token argument. Might be NULL */
){
Token x;
x.z = zToken;
x.n = sqlite3Strlen30(zToken);
return sqlite3ExprAlloc(db, op, &x, 0);
}
/*
** Attach subtrees pLeft and pRight to the Expr node pRoot.
**
** If pRoot==NULL that means that a memory allocation error has occurred.
** In that case, delete the subtrees pLeft and pRight.
*/
void sqlite3ExprAttachSubtrees(
sqlite3 *db,
Expr *pRoot,
Expr *pLeft,
Expr *pRight
){
if( pRoot==0 ){
assert( db->mallocFailed );
sqlite3ExprDelete(db, pLeft);
sqlite3ExprDelete(db, pRight);
}else{
if( pRight ){
pRoot->pRight = pRight;
pRoot->flags |= EP_Propagate & pRight->flags;
}
if( pLeft ){
pRoot->pLeft = pLeft;
pRoot->flags |= EP_Propagate & pLeft->flags;
}
exprSetHeight(pRoot);
}
}
/*
** Allocate an Expr node which joins as many as two subtrees.
**
** One or both of the subtrees can be NULL. Return a pointer to the new
** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
** free the subtrees and return NULL.
*/
Expr *sqlite3PExpr(
Parse *pParse, /* Parsing context */
int op, /* Expression opcode */
Expr *pLeft, /* Left operand */
Expr *pRight /* Right operand */
){
Expr *p;
p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
if( p ){
memset(p, 0, sizeof(Expr));
p->op = op & 0xff;
p->iAgg = -1;
sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
sqlite3ExprCheckHeight(pParse, p->nHeight);
}else{
sqlite3ExprDelete(pParse->db, pLeft);
sqlite3ExprDelete(pParse->db, pRight);
}
return p;
}
/*
** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
** do a memory allocation failure) then delete the pSelect object.
*/
void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
if( pExpr ){
pExpr->x.pSelect = pSelect;
ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
sqlite3ExprSetHeightAndFlags(pParse, pExpr);
}else{
assert( pParse->db->mallocFailed );
sqlite3SelectDelete(pParse->db, pSelect);
}
}
/*
** Join two expressions using an AND operator. If either expression is
** NULL, then just return the other expression.
**
** If one side or the other of the AND is known to be false, then instead
** of returning an AND expression, just return a constant expression with
** a value of false.
*/
Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
sqlite3 *db = pParse->db;
if( pLeft==0 ){
return pRight;
}else if( pRight==0 ){
return pLeft;
}else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
sqlite3ExprUnmapAndDelete(pParse, pLeft);
sqlite3ExprUnmapAndDelete(pParse, pRight);
return sqlite3Expr(db, TK_INTEGER, "0");
}else{
return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
}
}
/*
** Construct a new expression node for a function with multiple
** arguments.
*/
Expr *sqlite3ExprFunction(
Parse *pParse, /* Parsing context */
ExprList *pList, /* Argument list */
Token *pToken, /* Name of the function */
int eDistinct /* SF_Distinct or SF_ALL or 0 */
){
Expr *pNew;
sqlite3 *db = pParse->db;
assert( pToken );
pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
if( pNew==0 ){
sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
return 0;
}
if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
}
pNew->x.pList = pList;
ExprSetProperty(pNew, EP_HasFunc);
assert( !ExprHasProperty(pNew, EP_xIsSelect) );
sqlite3ExprSetHeightAndFlags(pParse, pNew);
if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
return pNew;
}
/*
** Assign a variable number to an expression that encodes a wildcard
** in the original SQL statement.
**
** Wildcards consisting of a single "?" are assigned the next sequential
** variable number.
**
** Wildcards of the form "?nnn" are assigned the number "nnn". We make
** sure "nnn" is not too big to avoid a denial of service attack when
** the SQL statement comes from an external source.
**
** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
** as the previous instance of the same wildcard. Or if this is the first
** instance of the wildcard, the next sequential variable number is
** assigned.
*/
void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
sqlite3 *db = pParse->db;
const char *z;
ynVar x;
if( pExpr==0 ) return;
assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
z = pExpr->u.zToken;
assert( z!=0 );
assert( z[0]!=0 );
assert( n==(u32)sqlite3Strlen30(z) );
if( z[1]==0 ){
/* Wildcard of the form "?". Assign the next variable number */
assert( z[0]=='?' );
x = (ynVar)(++pParse->nVar);
}else{
int doAdd = 0;
if( z[0]=='?' ){
/* Wildcard of the form "?nnn". Convert "nnn" to an integer and
** use it as the variable number */
i64 i;
int bOk;
if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
i = z[1]-'0'; /* The common case of ?N for a single digit N */
bOk = 1;
}else{
bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
}
testcase( i==0 );
testcase( i==1 );
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
return;
}
x = (ynVar)i;
if( x>pParse->nVar ){
pParse->nVar = (int)x;
doAdd = 1;
}else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
doAdd = 1;
}
}else{
/* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
** number as the prior appearance of the same name, or if the name
** has never appeared before, reuse the same variable number
*/
x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
if( x==0 ){
x = (ynVar)(++pParse->nVar);
doAdd = 1;
}
}
if( doAdd ){
pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
}
}
pExpr->iColumn = x;
if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
sqlite3ErrorMsg(pParse, "too many SQL variables");
}
}
/*
** Recursively delete an expression tree.
*/
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
assert( p!=0 );
/* Sanity check: Assert that the IntValue is non-negative if it exists */
assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
|| p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
#ifdef SQLITE_DEBUG
if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
assert( p->pLeft==0 );
assert( p->pRight==0 );
assert( p->x.pSelect==0 );
}
#endif
if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
/* The Expr.x union is never used at the same time as Expr.pRight */
assert( p->x.pList==0 || p->pRight==0 );
if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
if( p->pRight ){
assert( !ExprHasProperty(p, EP_WinFunc) );
sqlite3ExprDeleteNN(db, p->pRight);
}else if( ExprHasProperty(p, EP_xIsSelect) ){
assert( !ExprHasProperty(p, EP_WinFunc) );
sqlite3SelectDelete(db, p->x.pSelect);
}else{
sqlite3ExprListDelete(db, p->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(p, EP_WinFunc) ){
sqlite3WindowDelete(db, p->y.pWin);
}
#endif
}
}
if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
if( !ExprHasProperty(p, EP_Static) ){
sqlite3DbFreeNN(db, p);
}
}
void sqlite3ExprDelete(sqlite3 *db, Expr *p){
if( p ) sqlite3ExprDeleteNN(db, p);
}
/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
** expression.
*/
void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
if( p ){
if( IN_RENAME_OBJECT ){
sqlite3RenameExprUnmap(pParse, p);
}
sqlite3ExprDeleteNN(pParse->db, p);
}
}
/*
** Return the number of bytes allocated for the expression structure
** passed as the first argument. This is always one of EXPR_FULLSIZE,
** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
*/
static int exprStructSize(Expr *p){
if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
return EXPR_FULLSIZE;
}
/*
** The dupedExpr*Size() routines each return the number of bytes required
** to store a copy of an expression or expression tree. They differ in
** how much of the tree is measured.
**
** dupedExprStructSize() Size of only the Expr structure
** dupedExprNodeSize() Size of Expr + space for token
** dupedExprSize() Expr + token + subtree components
**
***************************************************************************
**
** The dupedExprStructSize() function returns two values OR-ed together:
** (1) the space required for a copy of the Expr structure only and
** (2) the EP_xxx flags that indicate what the structure size should be.
** The return values is always one of:
**
** EXPR_FULLSIZE
** EXPR_REDUCEDSIZE | EP_Reduced
** EXPR_TOKENONLYSIZE | EP_TokenOnly
**
** The size of the structure can be found by masking the return value
** of this routine with 0xfff. The flags can be found by masking the
** return value with EP_Reduced|EP_TokenOnly.
**
** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
** (unreduced) Expr objects as they or originally constructed by the parser.
** During expression analysis, extra information is computed and moved into
** later parts of the Expr object and that extra information might get chopped
** off if the expression is reduced. Note also that it does not work to
** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
** to reduce a pristine expression tree from the parser. The implementation
** of dupedExprStructSize() contain multiple assert() statements that attempt
** to enforce this constraint.
*/
static int dupedExprStructSize(Expr *p, int flags){
int nSize;
assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
assert( EXPR_FULLSIZE<=0xfff );
assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
if( 0==flags || p->op==TK_SELECT_COLUMN
#ifndef SQLITE_OMIT_WINDOWFUNC
|| ExprHasProperty(p, EP_WinFunc)
#endif
){
nSize = EXPR_FULLSIZE;
}else{
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
assert( !ExprHasProperty(p, EP_FromJoin) );
assert( !ExprHasProperty(p, EP_MemToken) );
assert( !ExprHasProperty(p, EP_NoReduce) );
if( p->pLeft || p->x.pList ){
nSize = EXPR_REDUCEDSIZE | EP_Reduced;
}else{
assert( p->pRight==0 );
nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
}
}
return nSize;
}
/*
** This function returns the space in bytes required to store the copy
** of the Expr structure and a copy of the Expr.u.zToken string (if that
** string is defined.)
*/
static int dupedExprNodeSize(Expr *p, int flags){
int nByte = dupedExprStructSize(p, flags) & 0xfff;
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
nByte += sqlite3Strlen30NN(p->u.zToken)+1;
}
return ROUND8(nByte);
}
/*
** Return the number of bytes required to create a duplicate of the
** expression passed as the first argument. The second argument is a
** mask containing EXPRDUP_XXX flags.
**
** The value returned includes space to create a copy of the Expr struct
** itself and the buffer referred to by Expr.u.zToken, if any.
**
** If the EXPRDUP_REDUCE flag is set, then the return value includes
** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
** and Expr.pRight variables (but not for any structures pointed to or
** descended from the Expr.x.pList or Expr.x.pSelect variables).
*/
static int dupedExprSize(Expr *p, int flags){
int nByte = 0;
if( p ){
nByte = dupedExprNodeSize(p, flags);
if( flags&EXPRDUP_REDUCE ){
nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
}
}
return nByte;
}
/*
** This function is similar to sqlite3ExprDup(), except that if pzBuffer
** is not NULL then *pzBuffer is assumed to point to a buffer large enough
** to store the copy of expression p, the copies of p->u.zToken
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
** if any. Before returning, *pzBuffer is set to the first byte past the
** portion of the buffer copied into by this function.
*/
static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
Expr *pNew; /* Value to return */
u8 *zAlloc; /* Memory space from which to build Expr object */
u32 staticFlag; /* EP_Static if space not obtained from malloc */
assert( db!=0 );
assert( p );
assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
/* Figure out where to write the new Expr structure. */
if( pzBuffer ){
zAlloc = *pzBuffer;
staticFlag = EP_Static;
}else{
zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
staticFlag = 0;
}
pNew = (Expr *)zAlloc;
if( pNew ){
/* Set nNewSize to the size allocated for the structure pointed to
** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
** by the copy of the p->u.zToken string (if any).
*/
const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
const int nNewSize = nStructSize & 0xfff;
int nToken;
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
nToken = sqlite3Strlen30(p->u.zToken) + 1;
}else{
nToken = 0;
}
if( dupFlags ){
assert( ExprHasProperty(p, EP_Reduced)==0 );
memcpy(zAlloc, p, nNewSize);
}else{
u32 nSize = (u32)exprStructSize(p);
memcpy(zAlloc, p, nSize);
if( nSize<EXPR_FULLSIZE ){
memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
}
}
/* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
pNew->flags |= staticFlag;
/* Copy the p->u.zToken string, if any. */
if( nToken ){
char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
memcpy(zToken, p->u.zToken, nToken);
}
if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
/* Fill in the pNew->x.pSelect or pNew->x.pList member. */
if( ExprHasProperty(p, EP_xIsSelect) ){
pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
}else{
pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
}
}
/* Fill in pNew->pLeft and pNew->pRight. */
if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
zAlloc += dupedExprNodeSize(p, dupFlags);
if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
pNew->pLeft = p->pLeft ?
exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
pNew->pRight = p->pRight ?
exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(p, EP_WinFunc) ){
pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
assert( ExprHasProperty(pNew, EP_WinFunc) );
}
#endif /* SQLITE_OMIT_WINDOWFUNC */
if( pzBuffer ){
*pzBuffer = zAlloc;
}
}else{
if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
if( pNew->op==TK_SELECT_COLUMN ){
pNew->pLeft = p->pLeft;
assert( p->iColumn==0 || p->pRight==0 );
assert( p->pRight==0 || p->pRight==p->pLeft );
}else{
pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
}
pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
}
}
}
return pNew;
}
/*
** Create and return a deep copy of the object passed as the second
** argument. If an OOM condition is encountered, NULL is returned
** and the db->mallocFailed flag set.
*/
#ifndef SQLITE_OMIT_CTE
static With *withDup(sqlite3 *db, With *p){
With *pRet = 0;
if( p ){
sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
pRet = sqlite3DbMallocZero(db, nByte);
if( pRet ){
int i;
pRet->nCte = p->nCte;
for(i=0; i<p->nCte; i++){
pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
}
}
}
return pRet;
}
#else
# define withDup(x,y) 0
#endif
#ifndef SQLITE_OMIT_WINDOWFUNC
/*
** The gatherSelectWindows() procedure and its helper routine
** gatherSelectWindowsCallback() are used to scan all the expressions
** an a newly duplicated SELECT statement and gather all of the Window
** objects found there, assembling them onto the linked list at Select->pWin.
*/
static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
Select *pSelect = pWalker->u.pSelect;
Window *pWin = pExpr->y.pWin;
assert( pWin );
assert( IsWindowFunc(pExpr) );
assert( pWin->ppThis==0 );
sqlite3WindowLink(pSelect, pWin);
}
return WRC_Continue;
}
static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
}
static void gatherSelectWindows(Select *p){
Walker w;
w.xExprCallback = gatherSelectWindowsCallback;
w.xSelectCallback = gatherSelectWindowsSelectCallback;
w.xSelectCallback2 = 0;
w.pParse = 0;
w.u.pSelect = p;
sqlite3WalkSelect(&w, p);
}
#endif
/*
** The following group of routines make deep copies of expressions,
** expression lists, ID lists, and select statements. The copies can
** be deleted (by being passed to their respective ...Delete() routines)
** without effecting the originals.
**
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
** by subsequent calls to sqlite*ListAppend() routines.
**
** Any tables that the SrcList might point to are not duplicated.
**
** The flags parameter contains a combination of the EXPRDUP_XXX flags.
** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
** truncated version of the usual Expr structure that will be stored as
** part of the in-memory representation of the database schema.
*/
Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
assert( flags==0 || flags==EXPRDUP_REDUCE );
return p ? exprDup(db, p, flags, 0) : 0;
}
ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
ExprList *pNew;
struct ExprList_item *pItem, *pOldItem;
int i;
Expr *pPriorSelectCol = 0;
assert( db!=0 );
if( p==0 ) return 0;
pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
if( pNew==0 ) return 0;
pNew->nExpr = p->nExpr;
pItem = pNew->a;
pOldItem = p->a;
for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
Expr *pOldExpr = pOldItem->pExpr;
Expr *pNewExpr;
pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
if( pOldExpr
&& pOldExpr->op==TK_SELECT_COLUMN
&& (pNewExpr = pItem->pExpr)!=0
){
assert( pNewExpr->iColumn==0 || i>0 );
if( pNewExpr->iColumn==0 ){
assert( pOldExpr->pLeft==pOldExpr->pRight );
pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
}else{
assert( i>0 );
assert( pItem[-1].pExpr!=0 );
assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
pNewExpr->pLeft = pPriorSelectCol;
}
}
pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
pItem->sortFlags = pOldItem->sortFlags;
pItem->done = 0;
pItem->bNulls = pOldItem->bNulls;
pItem->bSpanIsTab = pOldItem->bSpanIsTab;
pItem->bSorterRef = pOldItem->bSorterRef;
pItem->u = pOldItem->u;
}
return pNew;
}
/*
** If cursors, triggers, views and subqueries are all omitted from
** the build, then none of the following routines, except for
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
** called with a NULL argument.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
|| !defined(SQLITE_OMIT_SUBQUERY)
SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
SrcList *pNew;
int i;
int nByte;
assert( db!=0 );
if( p==0 ) return 0;
nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
pNew = sqlite3DbMallocRawNN(db, nByte );
if( pNew==0 ) return 0;
pNew->nSrc = pNew->nAlloc = p->nSrc;
for(i=0; i<p->nSrc; i++){
struct SrcList_item *pNewItem = &pNew->a[i];
struct SrcList_item *pOldItem = &p->a[i];
Table *pTab;
pNewItem->pSchema = pOldItem->pSchema;
pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
pNewItem->fg = pOldItem->fg;
pNewItem->iCursor = pOldItem->iCursor;
pNewItem->addrFillSub = pOldItem->addrFillSub;
pNewItem->regReturn = pOldItem->regReturn;
if( pNewItem->fg.isIndexedBy ){
pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
}
pNewItem->pIBIndex = pOldItem->pIBIndex;
if( pNewItem->fg.isTabFunc ){
pNewItem->u1.pFuncArg =
sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
}
pTab = pNewItem->pTab = pOldItem->pTab;
if( pTab ){
pTab->nTabRef++;
}
pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
pNewItem->colUsed = pOldItem->colUsed;
}
return pNew;
}
IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
IdList *pNew;
int i;
assert( db!=0 );
if( p==0 ) return 0;
pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
if( pNew==0 ) return 0;
pNew->nId = p->nId;
pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
if( pNew->a==0 ){
sqlite3DbFreeNN(db, pNew);
return 0;
}
/* Note that because the size of the allocation for p->a[] is not
** necessarily a power of two, sqlite3IdListAppend() may not be called
** on the duplicate created by this function. */
for(i=0; i<p->nId; i++){
struct IdList_item *pNewItem = &pNew->a[i];
struct IdList_item *pOldItem = &p->a[i];
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
pNewItem->idx = pOldItem->idx;
}
return pNew;
}
Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
Select *pRet = 0;
Select *pNext = 0;
Select **pp = &pRet;
Select *p;
assert( db!=0 );
for(p=pDup; p; p=p->pPrior){
Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
if( pNew==0 ) break;
pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
pNew->op = p->op;
pNew->pNext = pNext;
pNew->pPrior = 0;
pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
pNew->iLimit = 0;
pNew->iOffset = 0;
pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
pNew->addrOpenEphm[0] = -1;
pNew->addrOpenEphm[1] = -1;
pNew->nSelectRow = p->nSelectRow;
pNew->pWith = withDup(db, p->pWith);
#ifndef SQLITE_OMIT_WINDOWFUNC
pNew->pWin = 0;
pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
#endif
pNew->selId = p->selId;
*pp = pNew;
pp = &pNew->pPrior;
pNext = pNew;
}
return pRet;
}
#else
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
assert( p==0 );
return 0;
}
#endif
/*
** Add a new element to the end of an expression list. If pList is
** initially NULL, then create a new expression list.
**
** The pList argument must be either NULL or a pointer to an ExprList
** obtained from a prior call to sqlite3ExprListAppend(). This routine
** may not be used with an ExprList obtained from sqlite3ExprListDup().
** Reason: This routine assumes that the number of slots in pList->a[]
** is a power of two. That is true for sqlite3ExprListAppend() returns
** but is not necessarily true from the return value of sqlite3ExprListDup().
**
** If a memory allocation error occurs, the entire list is freed and
** NULL is returned. If non-NULL is returned, then it is guaranteed
** that the new entry was successfully appended.
*/
ExprList *sqlite3ExprListAppend(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
Expr *pExpr /* Expression to be appended. Might be NULL */
){
struct ExprList_item *pItem;
sqlite3 *db = pParse->db;
assert( db!=0 );
if( pList==0 ){
pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
if( pList==0 ){
goto no_mem;
}
pList->nExpr = 0;
}else if( (pList->nExpr & (pList->nExpr-1))==0 ){
ExprList *pNew;
pNew = sqlite3DbRealloc(db, pList,
sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
if( pNew==0 ){
goto no_mem;
}
pList = pNew;
}
pItem = &pList->a[pList->nExpr++];
assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
assert( offsetof(struct ExprList_item,pExpr)==0 );
memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
pItem->pExpr = pExpr;
return pList;
no_mem:
/* Avoid leaking memory if malloc has failed. */
sqlite3ExprDelete(db, pExpr);
sqlite3ExprListDelete(db, pList);
return 0;
}
/*
** pColumns and pExpr form a vector assignment which is part of the SET
** clause of an UPDATE statement. Like this:
**
** (a,b,c) = (expr1,expr2,expr3)
** Or: (a,b,c) = (SELECT x,y,z FROM ....)
**
** For each term of the vector assignment, append new entries to the
** expression list pList. In the case of a subquery on the RHS, append
** TK_SELECT_COLUMN expressions.
*/
ExprList *sqlite3ExprListAppendVector(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
IdList *pColumns, /* List of names of LHS of the assignment */
Expr *pExpr /* Vector expression to be appended. Might be NULL */
){
sqlite3 *db = pParse->db;
int n;
int i;
int iFirst = pList ? pList->nExpr : 0;
/* pColumns can only be NULL due to an OOM but an OOM will cause an
** exit prior to this routine being invoked */
if( NEVER(pColumns==0) ) goto vector_append_error;
if( pExpr==0 ) goto vector_append_error;
/* If the RHS is a vector, then we can immediately check to see that
** the size of the RHS and LHS match. But if the RHS is a SELECT,
** wildcards ("*") in the result set of the SELECT must be expanded before
** we can do the size check, so defer the size check until code generation.
*/
if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
pColumns->nId, n);
goto vector_append_error;
}
for(i=0; i<pColumns->nId; i++){
Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
assert( pSubExpr!=0 || db->mallocFailed );
assert( pSubExpr==0 || pSubExpr->iTable==0 );
if( pSubExpr==0 ) continue;
pSubExpr->iTable = pColumns->nId;
pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
if( pList ){
assert( pList->nExpr==iFirst+i+1 );
pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
pColumns->a[i].zName = 0;
}
}
if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
Expr *pFirst = pList->a[iFirst].pExpr;
assert( pFirst!=0 );
assert( pFirst->op==TK_SELECT_COLUMN );
/* Store the SELECT statement in pRight so it will be deleted when
** sqlite3ExprListDelete() is called */
pFirst->pRight = pExpr;
pExpr = 0;
/* Remember the size of the LHS in iTable so that we can check that
** the RHS and LHS sizes match during code generation. */
pFirst->iTable = pColumns->nId;
}
vector_append_error:
sqlite3ExprUnmapAndDelete(pParse, pExpr);
sqlite3IdListDelete(db, pColumns);
return pList;
}
/*
** Set the sort order for the last element on the given ExprList.
*/
void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
struct ExprList_item *pItem;
if( p==0 ) return;
assert( p->nExpr>0 );
assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
assert( iSortOrder==SQLITE_SO_UNDEFINED
|| iSortOrder==SQLITE_SO_ASC
|| iSortOrder==SQLITE_SO_DESC
);
assert( eNulls==SQLITE_SO_UNDEFINED
|| eNulls==SQLITE_SO_ASC
|| eNulls==SQLITE_SO_DESC
);
pItem = &p->a[p->nExpr-1];
assert( pItem->bNulls==0 );
if( iSortOrder==SQLITE_SO_UNDEFINED ){
iSortOrder = SQLITE_SO_ASC;
}
pItem->sortFlags = (u8)iSortOrder;
if( eNulls!=SQLITE_SO_UNDEFINED ){
pItem->bNulls = 1;
if( iSortOrder!=eNulls ){
pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
}
}
}
/*
** Set the ExprList.a[].zName element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error. But pName should never be
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetName(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to add the span. */
Token *pName, /* Name to be added */
int dequote /* True to cause the name to be dequoted */
){
assert( pList!=0 || pParse->db->mallocFailed!=0 );
if( pList ){
struct ExprList_item *pItem;
assert( pList->nExpr>0 );
pItem = &pList->a[pList->nExpr-1];
assert( pItem->zName==0 );
pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
if( dequote ) sqlite3Dequote(pItem->zName);
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
}
}
}
/*
** Set the ExprList.a[].zSpan element of the most recently added item
** on the expression list.
**
** pList might be NULL following an OOM error. But pSpan should never be
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
** is set.
*/
void sqlite3ExprListSetSpan(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to add the span. */
const char *zStart, /* Start of the span */
const char *zEnd /* End of the span */
){
sqlite3 *db = pParse->db;
assert( pList!=0 || db->mallocFailed!=0 );
if( pList ){
struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
assert( pList->nExpr>0 );
sqlite3DbFree(db, pItem->zSpan);
pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
}
}
/*
** If the expression list pEList contains more than iLimit elements,
** leave an error message in pParse.
*/
void sqlite3ExprListCheckLength(
Parse *pParse,
ExprList *pEList,
const char *zObject
){
int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
testcase( pEList && pEList->nExpr==mx );
testcase( pEList && pEList->nExpr==mx+1 );
if( pEList && pEList->nExpr>mx ){
sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
}
}
/*
** Delete an entire expression list.
*/
static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
int i = pList->nExpr;
struct ExprList_item *pItem = pList->a;
assert( pList->nExpr>0 );
do{
sqlite3ExprDelete(db, pItem->pExpr);
sqlite3DbFree(db, pItem->zName);
sqlite3DbFree(db, pItem->zSpan);
pItem++;
}while( --i>0 );
sqlite3DbFreeNN(db, pList);
}
void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
if( pList ) exprListDeleteNN(db, pList);
}
/*
** Return the bitwise-OR of all Expr.flags fields in the given
** ExprList.
*/
u32 sqlite3ExprListFlags(const ExprList *pList){
int i;
u32 m = 0;
assert( pList!=0 );
for(i=0; i<pList->nExpr; i++){
Expr *pExpr = pList->a[i].pExpr;
assert( pExpr!=0 );
m |= pExpr->flags;
}
return m;
}
/*
** This is a SELECT-node callback for the expression walker that
** always "fails". By "fail" in this case, we mean set
** pWalker->eCode to zero and abort.
**
** This callback is used by multiple expression walkers.
*/
int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
UNUSED_PARAMETER(NotUsed);
pWalker->eCode = 0;
return WRC_Abort;
}
/*
** If the input expression is an ID with the name "true" or "false"
** then convert it into an TK_TRUEFALSE term. Return non-zero if
** the conversion happened, and zero if the expression is unaltered.
*/
int sqlite3ExprIdToTrueFalse(Expr *pExpr){
assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
if( !ExprHasProperty(pExpr, EP_Quoted)
&& (sqlite3StrICmp(pExpr->u.zToken, "true")==0
|| sqlite3StrICmp(pExpr->u.zToken, "false")==0)
){
pExpr->op = TK_TRUEFALSE;
ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
return 1;
}
return 0;
}
/*
** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
** and 0 if it is FALSE.
*/
int sqlite3ExprTruthValue(const Expr *pExpr){
pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
assert( pExpr->op==TK_TRUEFALSE );
assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
|| sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
return pExpr->u.zToken[4]==0;
}
/*
** If pExpr is an AND or OR expression, try to simplify it by eliminating
** terms that are always true or false. Return the simplified expression.
** Or return the original expression if no simplification is possible.
**
** Examples:
**
** (x<10) AND true => (x<10)
** (x<10) AND false => false
** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
** (x<10) AND (y=22 OR true) => (x<10)
** (y=22) OR true => true
*/
Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
assert( pExpr!=0 );
if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
pExpr = pExpr->op==TK_AND ? pRight : pLeft;
}else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
pExpr = pExpr->op==TK_AND ? pLeft : pRight;
}
}
return pExpr;
}
/*
** These routines are Walker callbacks used to check expressions to
** see if they are "constant" for some definition of constant. The
** Walker.eCode value determines the type of "constant" we are looking
** for.
**
** These callback routines are used to implement the following:
**
** sqlite3ExprIsConstant() pWalker->eCode==1
** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
** sqlite3ExprIsTableConstant() pWalker->eCode==3
** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
**
** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
** is found to not be a constant.
**
** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
** an existing schema and 4 when processing a new statement. A bound
** parameter raises an error for new statements, but is silently converted
** to NULL for existing schemas. This allows sqlite_master tables that
** contain a bound parameter because they were generated by older versions
** of SQLite to be parsed by newer versions of SQLite without raising a
** malformed schema error.
*/
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
/* If pWalker->eCode is 2 then any term of the expression that comes from
** the ON or USING clauses of a left join disqualifies the expression
** from being considered constant. */
if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
pWalker->eCode = 0;
return WRC_Abort;
}
switch( pExpr->op ){
/* Consider functions to be constant if all their arguments are constant
** and either pWalker->eCode==4 or 5 or the function has the
** SQLITE_FUNC_CONST flag. */
case TK_FUNCTION:
if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
&& !ExprHasProperty(pExpr, EP_WinFunc)
){
return WRC_Continue;
}else{
pWalker->eCode = 0;
return WRC_Abort;
}
case TK_ID:
/* Convert "true" or "false" in a DEFAULT clause into the
** appropriate TK_TRUEFALSE operator */
if( sqlite3ExprIdToTrueFalse(pExpr) ){
return WRC_Prune;
}
/* Fall thru */
case TK_COLUMN:
case TK_AGG_FUNCTION:
case TK_AGG_COLUMN:
testcase( pExpr->op==TK_ID );
testcase( pExpr->op==TK_COLUMN );
testcase( pExpr->op==TK_AGG_FUNCTION );
testcase( pExpr->op==TK_AGG_COLUMN );
if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
return WRC_Continue;
}
if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
return WRC_Continue;
}
/* Fall through */
case TK_IF_NULL_ROW:
case TK_REGISTER:
testcase( pExpr->op==TK_REGISTER );
testcase( pExpr->op==TK_IF_NULL_ROW );
pWalker->eCode = 0;
return WRC_Abort;
case TK_VARIABLE:
if( pWalker->eCode==5 ){
/* Silently convert bound parameters that appear inside of CREATE
** statements into a NULL when parsing the CREATE statement text out
** of the sqlite_master table */
pExpr->op = TK_NULL;
}else if( pWalker->eCode==4 ){
/* A bound parameter in a CREATE statement that originates from
** sqlite3_prepare() causes an error */
pWalker->eCode = 0;
return WRC_Abort;
}
/* Fall through */
default:
testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
return WRC_Continue;
}
}
static int exprIsConst(Expr *p, int initFlag, int iCur){
Walker w;
w.eCode = initFlag;
w.xExprCallback = exprNodeIsConstant;
w.xSelectCallback = sqlite3SelectWalkFail;
#ifdef SQLITE_DEBUG
w.xSelectCallback2 = sqlite3SelectWalkAssert2;
#endif
w.u.iCur = iCur;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** and 0 if it involves variables or function calls.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstant(Expr *p){
return exprIsConst(p, 1, 0);
}
/*
** Walk an expression tree. Return non-zero if
**
** (1) the expression is constant, and
** (2) the expression does originate in the ON or USING clause
** of a LEFT JOIN, and
** (3) the expression does not contain any EP_FixedCol TK_COLUMN
** operands created by the constant propagation optimization.
**
** When this routine returns true, it indicates that the expression
** can be added to the pParse->pConstExpr list and evaluated once when
** the prepared statement starts up. See sqlite3ExprCodeAtInit().
*/
int sqlite3ExprIsConstantNotJoin(Expr *p){
return exprIsConst(p, 2, 0);
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** for any single row of the table with cursor iCur. In other words, the
** expression must not refer to any non-deterministic function nor any
** table other than iCur.
*/
int sqlite3ExprIsTableConstant(Expr *p, int iCur){
return exprIsConst(p, 3, iCur);
}
/*
** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
*/
static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
ExprList *pGroupBy = pWalker->u.pGroupBy;
int i;
/* Check if pExpr is identical to any GROUP BY term. If so, consider
** it constant. */
for(i=0; i<pGroupBy->nExpr; i++){
Expr *p = pGroupBy->a[i].pExpr;
if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
if( sqlite3IsBinary(pColl) ){
return WRC_Prune;
}
}
}
/* Check if pExpr is a sub-select. If so, consider it variable. */
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
pWalker->eCode = 0;
return WRC_Abort;
}
return exprNodeIsConstant(pWalker, pExpr);
}
/*
** Walk the expression tree passed as the first argument. Return non-zero
** if the expression consists entirely of constants or copies of terms
** in pGroupBy that sort with the BINARY collation sequence.
**
** This routine is used to determine if a term of the HAVING clause can
** be promoted into the WHERE clause. In order for such a promotion to work,
** the value of the HAVING clause term must be the same for all members of
** a "group". The requirement that the GROUP BY term must be BINARY
** assumes that no other collating sequence will have a finer-grained
** grouping than binary. In other words (A=B COLLATE binary) implies
** A=B in every other collating sequence. The requirement that the
** GROUP BY be BINARY is stricter than necessary. It would also work
** to promote HAVING clauses that use the same alternative collating
** sequence as the GROUP BY term, but that is much harder to check,
** alternative collating sequences are uncommon, and this is only an
** optimization, so we take the easy way out and simply require the
** GROUP BY to use the BINARY collating sequence.
*/
int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
Walker w;
w.eCode = 1;
w.xExprCallback = exprNodeIsConstantOrGroupBy;
w.xSelectCallback = 0;
w.u.pGroupBy = pGroupBy;
w.pParse = pParse;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** Walk an expression tree. Return non-zero if the expression is constant
** or a function call with constant arguments. Return and 0 if there
** are any variables.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
assert( isInit==0 || isInit==1 );
return exprIsConst(p, 4+isInit, 0);
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
/*
** Walk an expression tree. Return 1 if the expression contains a
** subquery of some kind. Return 0 if there are no subqueries.
*/
int sqlite3ExprContainsSubquery(Expr *p){
Walker w;
w.eCode = 1;
w.xExprCallback = sqlite3ExprWalkNoop;
w.xSelectCallback = sqlite3SelectWalkFail;
#ifdef SQLITE_DEBUG
w.xSelectCallback2 = sqlite3SelectWalkAssert2;
#endif
sqlite3WalkExpr(&w, p);
return w.eCode==0;
}
#endif
/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue. If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
*/
int sqlite3ExprIsInteger(Expr *p, int *pValue){
int rc = 0;
if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
/* If an expression is an integer literal that fits in a signed 32-bit
** integer, then the EP_IntValue flag will have already been set */
assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
|| sqlite3GetInt32(p->u.zToken, &rc)==0 );
if( p->flags & EP_IntValue ){
*pValue = p->u.iValue;
return 1;
}
switch( p->op ){
case TK_UPLUS: {
rc = sqlite3ExprIsInteger(p->pLeft, pValue);
break;
}
case TK_UMINUS: {
int v;
if( sqlite3ExprIsInteger(p->pLeft, &v) ){
assert( v!=(-2147483647-1) );
*pValue = -v;
rc = 1;
}
break;
}
default: break;
}
return rc;
}
/*
** Return FALSE if there is no chance that the expression can be NULL.
**
** If the expression might be NULL or if the expression is too complex
** to tell return TRUE.
**
** This routine is used as an optimization, to skip OP_IsNull opcodes
** when we know that a value cannot be NULL. Hence, a false positive
** (returning TRUE when in fact the expression can never be NULL) might
** be a small performance hit but is otherwise harmless. On the other
** hand, a false negative (returning FALSE when the result could be NULL)
** will likely result in an incorrect answer. So when in doubt, return
** TRUE.
*/
int sqlite3ExprCanBeNull(const Expr *p){
u8 op;
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
p = p->pLeft;
}
op = p->op;
if( op==TK_REGISTER ) op = p->op2;
switch( op ){
case TK_INTEGER:
case TK_STRING:
case TK_FLOAT:
case TK_BLOB:
return 0;
case TK_COLUMN:
return ExprHasProperty(p, EP_CanBeNull) ||
p->y.pTab==0 || /* Reference to column of index on expression */
(p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
default:
return 1;
}
}
/*
** Return TRUE if the given expression is a constant which would be
** unchanged by OP_Affinity with the affinity given in the second
** argument.
**
** This routine is used to determine if the OP_Affinity operation
** can be omitted. When in doubt return FALSE. A false negative
** is harmless. A false positive, however, can result in the wrong
** answer.
*/
int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
u8 op;
int unaryMinus = 0;
if( aff==SQLITE_AFF_BLOB ) return 1;
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
if( p->op==TK_UMINUS ) unaryMinus = 1;
p = p->pLeft;
}
op = p->op;
if( op==TK_REGISTER ) op = p->op2;
switch( op ){
case TK_INTEGER: {
return aff>=SQLITE_AFF_NUMERIC;
}
case TK_FLOAT: {
return aff>=SQLITE_AFF_NUMERIC;
}
case TK_STRING: {
return !unaryMinus && aff==SQLITE_AFF_TEXT;
}
case TK_BLOB: {
return !unaryMinus;
}
case TK_COLUMN: {
assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
}
default: {
return 0;
}
}
}
/*
** Return TRUE if the given string is a row-id column name.
*/
int sqlite3IsRowid(const char *z){
if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
if( sqlite3StrICmp(z, "OID")==0 ) return 1;
return 0;
}
/*
** pX is the RHS of an IN operator. If pX is a SELECT statement
** that can be simplified to a direct table access, then return
** a pointer to the SELECT statement. If pX is not a SELECT statement,
** or if the SELECT statement needs to be manifested into a transient
** table, then return NULL.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static Select *isCandidateForInOpt(Expr *pX){
Select *p;
SrcList *pSrc;
ExprList *pEList;
Table *pTab;
int i;
if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
p = pX->x.pSelect;
if( p->pPrior ) return 0; /* Not a compound SELECT */
if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
return 0; /* No DISTINCT keyword and no aggregate functions */
}
assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
if( p->pLimit ) return 0; /* Has no LIMIT clause */
if( p->pWhere ) return 0; /* Has no WHERE clause */
pSrc = p->pSrc;
assert( pSrc!=0 );
if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
pTab = pSrc->a[0].pTab;
assert( pTab!=0 );
assert( pTab->pSelect==0 ); /* FROM clause is not a view */
if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
pEList = p->pEList;
assert( pEList!=0 );
/* All SELECT results must be columns. */
for(i=0; i<pEList->nExpr; i++){
Expr *pRes = pEList->a[i].pExpr;
if( pRes->op!=TK_COLUMN ) return 0;
assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
}
return p;
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code that checks the left-most column of index table iCur to see if
** it contains any NULL entries. Cause the register at regHasNull to be set
** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
** to be set to NULL if iCur contains one or more NULL values.
*/
static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
int addr1;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
VdbeComment((v, "first_entry_in(%d)", iCur));
sqlite3VdbeJumpHere(v, addr1);
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** The argument is an IN operator with a list (not a subquery) on the
** right-hand side. Return TRUE if that list is constant.
*/
static int sqlite3InRhsIsConstant(Expr *pIn){
Expr *pLHS;
int res;
assert( !ExprHasProperty(pIn, EP_xIsSelect) );
pLHS = pIn->pLeft;
pIn->pLeft = 0;
res = sqlite3ExprIsConstant(pIn);
pIn->pLeft = pLHS;
return res;
}
#endif
/*
** This function is used by the implementation of the IN (...) operator.
** The pX parameter is the expression on the RHS of the IN operator, which
** might be either a list of expressions or a subquery.
**
** The job of this routine is to find or create a b-tree object that can
** be used either to test for membership in the RHS set or to iterate through
** all members of the RHS set, skipping duplicates.
**
** A cursor is opened on the b-tree object that is the RHS of the IN operator
** and pX->iTable is set to the index of that cursor.
**
** The returned value of this function indicates the b-tree type, as follows:
**
** IN_INDEX_ROWID - The cursor was opened on a database table.
** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
** IN_INDEX_EPH - The cursor was opened on a specially created and
** populated epheremal table.
** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
** implemented as a sequence of comparisons.
**
** An existing b-tree might be used if the RHS expression pX is a simple
** subquery such as:
**
** SELECT <column1>, <column2>... FROM <table>
**
** If the RHS of the IN operator is a list or a more complex subquery, then
** an ephemeral table might need to be generated from the RHS and then
** pX->iTable made to point to the ephemeral table instead of an
** existing table.
**
** The inFlags parameter must contain, at a minimum, one of the bits
** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
** be used to loop over all values of the RHS of the IN operator.
**
** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
** through the set members) then the b-tree must not contain duplicates.
** An epheremal table will be created unless the selected columns are guaranteed
** to be unique - either because it is an INTEGER PRIMARY KEY or due to
** a UNIQUE constraint or index.
**
** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
** for fast set membership tests) then an epheremal table must
** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
** index can be found with the specified <columns> as its left-most.
**
** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
** if the RHS of the IN operator is a list (not a subquery) then this
** routine might decide that creating an ephemeral b-tree for membership
** testing is too expensive and return IN_INDEX_NOOP. In that case, the
** calling routine should implement the IN operator using a sequence
** of Eq or Ne comparison operations.
**
** When the b-tree is being used for membership tests, the calling function
** might need to know whether or not the RHS side of the IN operator
** contains a NULL. If prRhsHasNull is not a NULL pointer and
** if there is any chance that the (...) might contain a NULL value at
** runtime, then a register is allocated and the register number written
** to *prRhsHasNull. If there is no chance that the (...) contains a
** NULL value, then *prRhsHasNull is left unchanged.
**
** If a register is allocated and its location stored in *prRhsHasNull, then
** the value in that register will be NULL if the b-tree contains one or more
** NULL values, and it will be some non-NULL value if the b-tree contains no
** NULL values.
**
** If the aiMap parameter is not NULL, it must point to an array containing
** one element for each column returned by the SELECT statement on the RHS
** of the IN(...) operator. The i'th entry of the array is populated with the
** offset of the index column that matches the i'th column returned by the
** SELECT. For example, if the expression and selected index are:
**
** (?,?,?) IN (SELECT a, b, c FROM t1)
** CREATE INDEX i1 ON t1(b, c, a);
**
** then aiMap[] is populated with {2, 0, 1}.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3FindInIndex(
Parse *pParse, /* Parsing context */
Expr *pX, /* The IN expression */
u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
int *prRhsHasNull, /* Register holding NULL status. See notes */
int *aiMap, /* Mapping from Index fields to RHS fields */
int *piTab /* OUT: index to use */
){
Select *p; /* SELECT to the right of IN operator */
int eType = 0; /* Type of RHS table. IN_INDEX_* */
int iTab = pParse->nTab++; /* Cursor of the RHS table */
int mustBeUnique; /* True if RHS must be unique */
Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
assert( pX->op==TK_IN );
mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
/* If the RHS of this IN(...) operator is a SELECT, and if it matters
** whether or not the SELECT result contains NULL values, check whether
** or not NULL is actually possible (it may not be, for example, due
** to NOT NULL constraints in the schema). If no NULL values are possible,
** set prRhsHasNull to 0 before continuing. */
if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
int i;
ExprList *pEList = pX->x.pSelect->pEList;
for(i=0; i<pEList->nExpr; i++){
if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
}
if( i==pEList->nExpr ){
prRhsHasNull = 0;
}
}
/* Check to see if an existing table or index can be used to
** satisfy the query. This is preferable to generating a new
** ephemeral table. */
if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
sqlite3 *db = pParse->db; /* Database connection */
Table *pTab; /* Table <table>. */
i16 iDb; /* Database idx for pTab */
ExprList *pEList = p->pEList;
int nExpr = pEList->nExpr;
assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
pTab = p->pSrc->a[0].pTab;
/* Code an OP_Transaction and OP_TableLock for <table>. */
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
sqlite3CodeVerifySchema(pParse, iDb);
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
assert(v); /* sqlite3GetVdbe() has always been previously called */
if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
/* The "x IN (SELECT rowid FROM table)" case */
int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
VdbeCoverage(v);
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
eType = IN_INDEX_ROWID;
ExplainQueryPlan((pParse, 0,
"USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
sqlite3VdbeJumpHere(v, iAddr);
}else{
Index *pIdx; /* Iterator variable */
int affinity_ok = 1;
int i;
/* Check that the affinity that will be used to perform each
** comparison is the same as the affinity of each column in table
** on the RHS of the IN operator. If it not, it is not possible to
** use any index of the RHS table. */
for(i=0; i<nExpr && affinity_ok; i++){
Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
int iCol = pEList->a[i].pExpr->iColumn;
char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
testcase( cmpaff==SQLITE_AFF_BLOB );
testcase( cmpaff==SQLITE_AFF_TEXT );
switch( cmpaff ){
case SQLITE_AFF_BLOB:
break;
case SQLITE_AFF_TEXT:
/* sqlite3CompareAffinity() only returns TEXT if one side or the
** other has no affinity and the other side is TEXT. Hence,
** the only way for cmpaff to be TEXT is for idxaff to be TEXT
** and for the term on the LHS of the IN to have no affinity. */
assert( idxaff==SQLITE_AFF_TEXT );
break;
default:
affinity_ok = sqlite3IsNumericAffinity(idxaff);
}
}
if( affinity_ok ){
/* Search for an existing index that will work for this IN operator */
for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
Bitmask colUsed; /* Columns of the index used */
Bitmask mCol; /* Mask for the current column */
if( pIdx->nColumn<nExpr ) continue;
if( pIdx->pPartIdxWhere!=0 ) continue;
/* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
** BITMASK(nExpr) without overflowing */
testcase( pIdx->nColumn==BMS-2 );
testcase( pIdx->nColumn==BMS-1 );
if( pIdx->nColumn>=BMS-1 ) continue;
if( mustBeUnique ){
if( pIdx->nKeyCol>nExpr
||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
){
continue; /* This index is not unique over the IN RHS columns */
}
}
colUsed = 0; /* Columns of index used so far */
for(i=0; i<nExpr; i++){
Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
Expr *pRhs = pEList->a[i].pExpr;
CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
int j;
assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
for(j=0; j<nExpr; j++){
if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
assert( pIdx->azColl[j] );
if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
continue;
}
break;
}
if( j==nExpr ) break;
mCol = MASKBIT(j);
if( mCol & colUsed ) break; /* Each column used only once */
colUsed |= mCol;
if( aiMap ) aiMap[i] = j;
}
assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
if( colUsed==(MASKBIT(nExpr)-1) ){
/* If we reach this point, that means the index pIdx is usable */
int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
ExplainQueryPlan((pParse, 0,
"USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
VdbeComment((v, "%s", pIdx->zName));
assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
if( prRhsHasNull ){
#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
i64 mask = (1<<nExpr)-1;
sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
iTab, 0, 0, (u8*)&mask, P4_INT64);
#endif
*prRhsHasNull = ++pParse->nMem;
if( nExpr==1 ){
sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
}
}
sqlite3VdbeJumpHere(v, iAddr);
}
} /* End loop over indexes */
} /* End if( affinity_ok ) */
} /* End if not an rowid index */
} /* End attempt to optimize using an index */
/* If no preexisting index is available for the IN clause
** and IN_INDEX_NOOP is an allowed reply
** and the RHS of the IN operator is a list, not a subquery
** and the RHS is not constant or has two or fewer terms,
** then it is not worth creating an ephemeral table to evaluate
** the IN operator so return IN_INDEX_NOOP.
*/
if( eType==0
&& (inFlags & IN_INDEX_NOOP_OK)
&& !ExprHasProperty(pX, EP_xIsSelect)
&& (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
){
eType = IN_INDEX_NOOP;
}
if( eType==0 ){
/* Could not find an existing table or index to use as the RHS b-tree.
** We will have to generate an ephemeral table to do the job.
*/
u32 savedNQueryLoop = pParse->nQueryLoop;
int rMayHaveNull = 0;
eType = IN_INDEX_EPH;
if( inFlags & IN_INDEX_LOOP ){
pParse->nQueryLoop = 0;
}else if( prRhsHasNull ){
*prRhsHasNull = rMayHaveNull = ++pParse->nMem;
}
assert( pX->op==TK_IN );
sqlite3CodeRhsOfIN(pParse, pX, iTab);
if( rMayHaveNull ){
sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
}
pParse->nQueryLoop = savedNQueryLoop;
}
if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
int i, n;
n = sqlite3ExprVectorSize(pX->pLeft);
for(i=0; i<n; i++) aiMap[i] = i;
}
*piTab = iTab;
return eType;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Argument pExpr is an (?, ?...) IN(...) expression. This
** function allocates and returns a nul-terminated string containing
** the affinities to be used for each column of the comparison.
**
** It is the responsibility of the caller to ensure that the returned
** string is eventually freed using sqlite3DbFree().
*/
static char *exprINAffinity(Parse *pParse, Expr *pExpr){
Expr *pLeft = pExpr->pLeft;
int nVal = sqlite3ExprVectorSize(pLeft);
Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
char *zRet;
assert( pExpr->op==TK_IN );
zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
if( zRet ){
int i;
for(i=0; i<nVal; i++){
Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
char a = sqlite3ExprAffinity(pA);
if( pSelect ){
zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
}else{
zRet[i] = a;
}
}
zRet[nVal] = '\0';
}
return zRet;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Load the Parse object passed as the first argument with an error
** message of the form:
**
** "sub-select returns N columns - expected M"
*/
void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
const char *zFmt = "sub-select returns %d columns - expected %d";
sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
}
#endif
/*
** Expression pExpr is a vector that has been used in a context where
** it is not permitted. If pExpr is a sub-select vector, this routine
** loads the Parse object with a message of the form:
**
** "sub-select returns N columns - expected 1"
**
** Or, if it is a regular scalar vector:
**
** "row value misused"
*/
void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
#ifndef SQLITE_OMIT_SUBQUERY
if( pExpr->flags & EP_xIsSelect ){
sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
}else
#endif
{
sqlite3ErrorMsg(pParse, "row value misused");
}
}
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code that will construct an ephemeral table containing all terms
** in the RHS of an IN operator. The IN operator can be in either of two
** forms:
**
** x IN (4,5,11) -- IN operator with list on right-hand side
** x IN (SELECT a FROM b) -- IN operator with subquery on the right
**
** The pExpr parameter is the IN operator. The cursor number for the
** constructed ephermeral table is returned. The first time the ephemeral
** table is computed, the cursor number is also stored in pExpr->iTable,
** however the cursor number returned might not be the same, as it might
** have been duplicated using OP_OpenDup.
**
** If the LHS expression ("x" in the examples) is a column value, or
** the SELECT statement returns a column value, then the affinity of that
** column is used to build the index keys. If both 'x' and the
** SELECT... statement are columns, then numeric affinity is used
** if either column has NUMERIC or INTEGER affinity. If neither
** 'x' nor the SELECT... statement are columns, then numeric affinity
** is used.
*/
void sqlite3CodeRhsOfIN(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The IN operator */
int iTab /* Use this cursor number */
){
int addrOnce = 0; /* Address of the OP_Once instruction at top */
int addr; /* Address of OP_OpenEphemeral instruction */
Expr *pLeft; /* the LHS of the IN operator */
KeyInfo *pKeyInfo = 0; /* Key information */
int nVal; /* Size of vector pLeft */
Vdbe *v; /* The prepared statement under construction */
v = pParse->pVdbe;
assert( v!=0 );
/* The evaluation of the IN must be repeated every time it
** is encountered if any of the following is true:
**
** * The right-hand side is a correlated subquery
** * The right-hand side is an expression list containing variables
** * We are inside a trigger
**
** If all of the above are false, then we can compute the RHS just once
** and reuse it many names.
*/
if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
/* Reuse of the RHS is allowed */
/* If this routine has already been coded, but the previous code
** might not have been invoked yet, so invoke it now as a subroutine.
*/
if( ExprHasProperty(pExpr, EP_Subrtn) ){
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
pExpr->x.pSelect->selId));
}
sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
pExpr->y.sub.iAddr);
sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
sqlite3VdbeJumpHere(v, addrOnce);
return;
}
/* Begin coding the subroutine */
ExprSetProperty(pExpr, EP_Subrtn);
pExpr->y.sub.regReturn = ++pParse->nMem;
pExpr->y.sub.iAddr =
sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
VdbeComment((v, "return address"));
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
/* Check to see if this is a vector IN operator */
pLeft = pExpr->pLeft;
nVal = sqlite3ExprVectorSize(pLeft);
/* Construct the ephemeral table that will contain the content of
** RHS of the IN operator.
*/
pExpr->iTable = iTab;
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
}else{
VdbeComment((v, "RHS of IN operator"));
}
#endif
pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
/* Case 1: expr IN (SELECT ...)
**
** Generate code to write the results of the select into the temporary
** table allocated and opened above.
*/
Select *pSelect = pExpr->x.pSelect;
ExprList *pEList = pSelect->pEList;
ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
addrOnce?"":"CORRELATED ", pSelect->selId
));
/* If the LHS and RHS of the IN operator do not match, that
** error will have been caught long before we reach this point. */
if( ALWAYS(pEList->nExpr==nVal) ){
SelectDest dest;
int i;
sqlite3SelectDestInit(&dest, SRT_Set, iTab);
dest.zAffSdst = exprINAffinity(pParse, pExpr);
pSelect->iLimit = 0;
testcase( pSelect->selFlags & SF_Distinct );
testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
if( sqlite3Select(pParse, pSelect, &dest) ){
sqlite3DbFree(pParse->db, dest.zAffSdst);
sqlite3KeyInfoUnref(pKeyInfo);
return;
}
sqlite3DbFree(pParse->db, dest.zAffSdst);
assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
assert( pEList!=0 );
assert( pEList->nExpr>0 );
assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
for(i=0; i<nVal; i++){
Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
pParse, p, pEList->a[i].pExpr
);
}
}
}else if( ALWAYS(pExpr->x.pList!=0) ){
/* Case 2: expr IN (exprlist)
**
** For each expression, build an index key from the evaluation and
** store it in the temporary table. If <expr> is a column, then use
** that columns affinity when building index keys. If <expr> is not
** a column, use numeric affinity.
*/
char affinity; /* Affinity of the LHS of the IN */
int i;
ExprList *pList = pExpr->x.pList;
struct ExprList_item *pItem;
int r1, r2;
affinity = sqlite3ExprAffinity(pLeft);
if( affinity<=SQLITE_AFF_NONE ){
affinity = SQLITE_AFF_BLOB;
}
if( pKeyInfo ){
assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
}
/* Loop through each expression in <exprlist>. */
r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3GetTempReg(pParse);
for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
Expr *pE2 = pItem->pExpr;
/* If the expression is not constant then we will need to
** disable the test that was generated above that makes sure
** this code only executes once. Because for a non-constant
** expression we need to rerun this code each time.
*/
if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
sqlite3VdbeChangeToNoop(v, addrOnce);
ExprClearProperty(pExpr, EP_Subrtn);
addrOnce = 0;
}
/* Evaluate the expression and insert it into the temp table */
sqlite3ExprCode(pParse, pE2, r1);
sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
}
sqlite3ReleaseTempReg(pParse, r1);
sqlite3ReleaseTempReg(pParse, r2);
}
if( pKeyInfo ){
sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
}
if( addrOnce ){
sqlite3VdbeJumpHere(v, addrOnce);
/* Subroutine return */
sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
sqlite3ClearTempRegCache(pParse);
}
}
#endif /* SQLITE_OMIT_SUBQUERY */
/*
** Generate code for scalar subqueries used as a subquery expression
** or EXISTS operator:
**
** (SELECT a FROM b) -- subquery
** EXISTS (SELECT a FROM b) -- EXISTS subquery
**
** The pExpr parameter is the SELECT or EXISTS operator to be coded.
**
** Return the register that holds the result. For a multi-column SELECT,
** the result is stored in a contiguous array of registers and the
** return value is the register of the left-most result column.
** Return 0 if an error occurs.
*/
#ifndef SQLITE_OMIT_SUBQUERY
int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
int addrOnce = 0; /* Address of OP_Once at top of subroutine */
int rReg = 0; /* Register storing resulting */
Select *pSel; /* SELECT statement to encode */
SelectDest dest; /* How to deal with SELECT result */
int nReg; /* Registers to allocate */
Expr *pLimit; /* New limit expression */
Vdbe *v = pParse->pVdbe;
assert( v!=0 );
testcase( pExpr->op==TK_EXISTS );
testcase( pExpr->op==TK_SELECT );
assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
pSel = pExpr->x.pSelect;
/* The evaluation of the EXISTS/SELECT must be repeated every time it
** is encountered if any of the following is true:
**
** * The right-hand side is a correlated subquery
** * The right-hand side is an expression list containing variables
** * We are inside a trigger
**
** If all of the above are false, then we can run this code just once
** save the results, and reuse the same result on subsequent invocations.
*/
if( !ExprHasProperty(pExpr, EP_VarSelect) ){
/* If this routine has already been coded, then invoke it as a
** subroutine. */
if( ExprHasProperty(pExpr, EP_Subrtn) ){
ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
pExpr->y.sub.iAddr);
return pExpr->iTable;
}
/* Begin coding the subroutine */
ExprSetProperty(pExpr, EP_Subrtn);
pExpr->y.sub.regReturn = ++pParse->nMem;
pExpr->y.sub.iAddr =
sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
VdbeComment((v, "return address"));
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
/* For a SELECT, generate code to put the values for all columns of
** the first row into an array of registers and return the index of
** the first register.
**
** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
** into a register and return that register number.
**
** In both cases, the query is augmented with "LIMIT 1". Any
** preexisting limit is discarded in place of the new LIMIT 1.
*/
ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
addrOnce?"":"CORRELATED ", pSel->selId));
nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
pParse->nMem += nReg;
if( pExpr->op==TK_SELECT ){
dest.eDest = SRT_Mem;
dest.iSdst = dest.iSDParm;
dest.nSdst = nReg;
sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
VdbeComment((v, "Init subquery result"));
}else{
dest.eDest = SRT_Exists;
sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
VdbeComment((v, "Init EXISTS result"));
}
if( pSel->pLimit ){
/* The subquery already has a limit. If the pre-existing limit is X
** then make the new limit X<>0 so that the new limit is either 1 or 0 */
sqlite3 *db = pParse->db;
pLimit = sqlite3Expr(db, TK_INTEGER, "0");
if( pLimit ){
pLimit->affExpr = SQLITE_AFF_NUMERIC;
pLimit = sqlite3PExpr(pParse, TK_NE,
sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
}
sqlite3ExprDelete(db, pSel->pLimit->pLeft);
pSel->pLimit->pLeft = pLimit;
}else{
/* If there is no pre-existing limit add a limit of 1 */
pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
}
pSel->iLimit = 0;
if( sqlite3Select(pParse, pSel, &dest) ){
return 0;
}
pExpr->iTable = rReg = dest.iSDParm;
ExprSetVVAProperty(pExpr, EP_NoReduce);
if( addrOnce ){
sqlite3VdbeJumpHere(v, addrOnce);
/* Subroutine return */
sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
sqlite3ClearTempRegCache(pParse);
}
return rReg;
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Expr pIn is an IN(...) expression. This function checks that the
** sub-select on the RHS of the IN() operator has the same number of
** columns as the vector on the LHS. Or, if the RHS of the IN() is not
** a sub-query, that the LHS is a vector of size 1.
*/
int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
int nVector = sqlite3ExprVectorSize(pIn->pLeft);
if( (pIn->flags & EP_xIsSelect) ){
if( nVector!=pIn->x.pSelect->pEList->nExpr ){
sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
return 1;
}
}else if( nVector!=1 ){
sqlite3VectorErrorMsg(pParse, pIn->pLeft);
return 1;
}
return 0;
}
#endif
#ifndef SQLITE_OMIT_SUBQUERY
/*
** Generate code for an IN expression.
**
** x IN (SELECT ...)
** x IN (value, value, ...)
**
** The left-hand side (LHS) is a scalar or vector expression. The
** right-hand side (RHS) is an array of zero or more scalar values, or a
** subquery. If the RHS is a subquery, the number of result columns must
** match the number of columns in the vector on the LHS. If the RHS is
** a list of values, the LHS must be a scalar.
**
** The IN operator is true if the LHS value is contained within the RHS.
** The result is false if the LHS is definitely not in the RHS. The
** result is NULL if the presence of the LHS in the RHS cannot be
** determined due to NULLs.
**
** This routine generates code that jumps to destIfFalse if the LHS is not
** contained within the RHS. If due to NULLs we cannot determine if the LHS
** is contained in the RHS then jump to destIfNull. If the LHS is contained
** within the RHS then fall through.
**
** See the separate in-operator.md documentation file in the canonical
** SQLite source tree for additional information.
*/
static void sqlite3ExprCodeIN(
Parse *pParse, /* Parsing and code generating context */
Expr *pExpr, /* The IN expression */
int destIfFalse, /* Jump here if LHS is not contained in the RHS */
int destIfNull /* Jump here if the results are unknown due to NULLs */
){
int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
int eType; /* Type of the RHS */
int rLhs; /* Register(s) holding the LHS values */
int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
Vdbe *v; /* Statement under construction */
int *aiMap = 0; /* Map from vector field to index column */
char *zAff = 0; /* Affinity string for comparisons */
int nVector; /* Size of vectors for this IN operator */
int iDummy; /* Dummy parameter to exprCodeVector() */
Expr *pLeft; /* The LHS of the IN operator */
int i; /* loop counter */
int destStep2; /* Where to jump when NULLs seen in step 2 */
int destStep6 = 0; /* Start of code for Step 6 */
int addrTruthOp; /* Address of opcode that determines the IN is true */
int destNotNull; /* Jump here if a comparison is not true in step 6 */
int addrTop; /* Top of the step-6 loop */
int iTab = 0; /* Index to use */
pLeft = pExpr->pLeft;
if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
zAff = exprINAffinity(pParse, pExpr);
nVector = sqlite3ExprVectorSize(pExpr->pLeft);
aiMap = (int*)sqlite3DbMallocZero(
pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
);
if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
/* Attempt to compute the RHS. After this step, if anything other than
** IN_INDEX_NOOP is returned, the table opened with cursor iTab
** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
** the RHS has not yet been coded. */
v = pParse->pVdbe;
assert( v!=0 ); /* OOM detected prior to this routine */
VdbeNoopComment((v, "begin IN expr"));
eType = sqlite3FindInIndex(pParse, pExpr,
IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
destIfFalse==destIfNull ? 0 : &rRhsHasNull,
aiMap, &iTab);
assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
|| eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
);
#ifdef SQLITE_DEBUG
/* Confirm that aiMap[] contains nVector integer values between 0 and
** nVector-1. */
for(i=0; i<nVector; i++){
int j, cnt;
for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
assert( cnt==1 );
}
#endif
/* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
** vector, then it is stored in an array of nVector registers starting
** at r1.
**
** sqlite3FindInIndex() might have reordered the fields of the LHS vector
** so that the fields are in the same order as an existing index. The
** aiMap[] array contains a mapping from the original LHS field order to
** the field order that matches the RHS index.
*/
rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
if( i==nVector ){
/* LHS fields are not reordered */
rLhs = rLhsOrig;
}else{
/* Need to reorder the LHS fields according to aiMap */
rLhs = sqlite3GetTempRange(pParse, nVector);
for(i=0; i<nVector; i++){
sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
}
}
/* If sqlite3FindInIndex() did not find or create an index that is
** suitable for evaluating the IN operator, then evaluate using a
** sequence of comparisons.
**
** This is step (1) in the in-operator.md optimized algorithm.
*/
if( eType==IN_INDEX_NOOP ){
ExprList *pList = pExpr->x.pList;
CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
int labelOk = sqlite3VdbeMakeLabel(pParse);
int r2, regToFree;
int regCkNull = 0;
int ii;
int bLhsReal; /* True if the LHS of the IN has REAL affinity */
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
if( destIfNull!=destIfFalse ){
regCkNull = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
}
bLhsReal = sqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL;
for(ii=0; ii<pList->nExpr; ii++){
if( bLhsReal ){
r2 = regToFree = sqlite3GetTempReg(pParse);
sqlite3ExprCode(pParse, pList->a[ii].pExpr, r2);
sqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC);
}else{
r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree);
}
if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
}
if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
(void*)pColl, P4_COLLSEQ);
VdbeCoverageIf(v, ii<pList->nExpr-1);
VdbeCoverageIf(v, ii==pList->nExpr-1);
sqlite3VdbeChangeP5(v, zAff[0]);
}else{
assert( destIfNull==destIfFalse );
sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
(void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
}
sqlite3ReleaseTempReg(pParse, regToFree);
}
if( regCkNull ){
sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
sqlite3VdbeGoto(v, destIfFalse);
}
sqlite3VdbeResolveLabel(v, labelOk);
sqlite3ReleaseTempReg(pParse, regCkNull);
goto sqlite3ExprCodeIN_finished;
}
/* Step 2: Check to see if the LHS contains any NULL columns. If the
** LHS does contain NULLs then the result must be either FALSE or NULL.
** We will then skip the binary search of the RHS.
*/
if( destIfNull==destIfFalse ){
destStep2 = destIfFalse;
}else{
destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
}
for(i=0; i<nVector; i++){
Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
if( sqlite3ExprCanBeNull(p) ){
sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
VdbeCoverage(v);
}
}
/* Step 3. The LHS is now known to be non-NULL. Do the binary search
** of the RHS using the LHS as a probe. If found, the result is
** true.
*/
if( eType==IN_INDEX_ROWID ){
/* In this case, the RHS is the ROWID of table b-tree and so we also
** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
** into a single opcode. */
sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
VdbeCoverage(v);
addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
}else{
sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
if( destIfFalse==destIfNull ){
/* Combine Step 3 and Step 5 into a single opcode */
sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
rLhs, nVector); VdbeCoverage(v);
goto sqlite3ExprCodeIN_finished;
}
/* Ordinary Step 3, for the case where FALSE and NULL are distinct */
addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
rLhs, nVector); VdbeCoverage(v);
}
/* Step 4. If the RHS is known to be non-NULL and we did not find
** an match on the search above, then the result must be FALSE.
*/
if( rRhsHasNull && nVector==1 ){
sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
VdbeCoverage(v);
}
/* Step 5. If we do not care about the difference between NULL and
** FALSE, then just return false.
*/
if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
/* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
** If any comparison is NULL, then the result is NULL. If all
** comparisons are FALSE then the final result is FALSE.
**
** For a scalar LHS, it is sufficient to check just the first row
** of the RHS.
*/
if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
VdbeCoverage(v);
if( nVector>1 ){
destNotNull = sqlite3VdbeMakeLabel(pParse);
}else{
/* For nVector==1, combine steps 6 and 7 by immediately returning
** FALSE if the first comparison is not NULL */
destNotNull = destIfFalse;
}
for(i=0; i<nVector; i++){
Expr *p;
CollSeq *pColl;
int r3 = sqlite3GetTempReg(pParse);
p = sqlite3VectorFieldSubexpr(pLeft, i);
pColl = sqlite3ExprCollSeq(pParse, p);
sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
(void*)pColl, P4_COLLSEQ);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r3);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
if( nVector>1 ){
sqlite3VdbeResolveLabel(v, destNotNull);
sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
VdbeCoverage(v);
/* Step 7: If we reach this point, we know that the result must
** be false. */
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
}
/* Jumps here in order to return true. */
sqlite3VdbeJumpHere(v, addrTruthOp);
sqlite3ExprCodeIN_finished:
if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
VdbeComment((v, "end IN expr"));
sqlite3ExprCodeIN_oom_error:
sqlite3DbFree(pParse->db, aiMap);
sqlite3DbFree(pParse->db, zAff);
}
#endif /* SQLITE_OMIT_SUBQUERY */
#ifndef SQLITE_OMIT_FLOATING_POINT
/*
** Generate an instruction that will put the floating point
** value described by z[0..n-1] into register iMem.
**
** The z[] string will probably not be zero-terminated. But the
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
if( ALWAYS(z!=0) ){
double value;
sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
if( negateFlag ) value = -value;
sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
}
}
#endif
/*
** Generate an instruction that will put the integer describe by
** text z[0..n-1] into register iMem.
**
** Expr.u.zToken is always UTF8 and zero-terminated.
*/
static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
Vdbe *v = pParse->pVdbe;
if( pExpr->flags & EP_IntValue ){
int i = pExpr->u.iValue;
assert( i>=0 );
if( negFlag ) i = -i;
sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
}else{
int c;
i64 value;
const char *z = pExpr->u.zToken;
assert( z!=0 );
c = sqlite3DecOrHexToI64(z, &value);
if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
#ifdef SQLITE_OMIT_FLOATING_POINT
sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
#else
#ifndef SQLITE_OMIT_HEX_INTEGER
if( sqlite3_strnicmp(z,"0x",2)==0 ){
sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
}else
#endif
{
codeReal(v, z, negFlag, iMem);
}
#endif
}else{
if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
}
}
}
/* Generate code that will load into register regOut a value that is
** appropriate for the iIdxCol-th column of index pIdx.
*/
void sqlite3ExprCodeLoadIndexColumn(
Parse *pParse, /* The parsing context */
Index *pIdx, /* The index whose column is to be loaded */
int iTabCur, /* Cursor pointing to a table row */
int iIdxCol, /* The column of the index to be loaded */
int regOut /* Store the index column value in this register */
){
i16 iTabCol = pIdx->aiColumn[iIdxCol];
if( iTabCol==XN_EXPR ){
assert( pIdx->aColExpr );
assert( pIdx->aColExpr->nExpr>iIdxCol );
pParse->iSelfTab = iTabCur + 1;
sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
pParse->iSelfTab = 0;
}else{
sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
iTabCol, regOut);
}
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/*
** Generate code that will compute the value of generated column pCol
** and store the result in register regOut
*/
void sqlite3ExprCodeGeneratedColumn(
Parse *pParse,
Column *pCol,
int regOut
){
int iAddr;
Vdbe *v = pParse->pVdbe;
assert( v!=0 );
assert( pParse->iSelfTab!=0 );
if( pParse->iSelfTab>0 ){
iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
}else{
iAddr = 0;
}
sqlite3ExprCode(pParse, pCol->pDflt, regOut);
if( pCol->affinity>=SQLITE_AFF_TEXT ){
sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
}
if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
}
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
/*
** Generate code to extract the value of the iCol-th column of a table.
*/
void sqlite3ExprCodeGetColumnOfTable(
Vdbe *v, /* Parsing context */
Table *pTab, /* The table containing the value */
int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
int iCol, /* Index of the column to extract */
int regOut /* Extract the value into this register */
){
Column *pCol;
assert( v!=0 );
if( pTab==0 ){
sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
return;
}
if( iCol<0 || iCol==pTab->iPKey ){
sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
}else{
int op;
int x;
if( IsVirtual(pTab) ){
op = OP_VColumn;
x = iCol;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
}else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
Parse *pParse = sqlite3VdbeParser(v);
if( pCol->colFlags & COLFLAG_BUSY ){
sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
}else{
int savedSelfTab = pParse->iSelfTab;
pCol->colFlags |= COLFLAG_BUSY;
pParse->iSelfTab = iTabCur+1;
sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
pParse->iSelfTab = savedSelfTab;
pCol->colFlags &= ~COLFLAG_BUSY;
}
return;
#endif
}else if( !HasRowid(pTab) ){
testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
op = OP_Column;
}else{
x = sqlite3TableColumnToStorage(pTab,iCol);
testcase( x!=iCol );
op = OP_Column;
}
sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
sqlite3ColumnDefault(v, pTab, iCol, regOut);
}
}
/*
** Generate code that will extract the iColumn-th column from
** table pTab and store the column value in register iReg.
**
** There must be an open cursor to pTab in iTable when this routine
** is called. If iColumn<0 then code is generated that extracts the rowid.
*/
int sqlite3ExprCodeGetColumn(
Parse *pParse, /* Parsing and code generating context */
Table *pTab, /* Description of the table we are reading from */
int iColumn, /* Index of the table column */
int iTable, /* The cursor pointing to the table */
int iReg, /* Store results here */
u8 p5 /* P5 value for OP_Column + FLAGS */
){
assert( pParse->pVdbe!=0 );
sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
if( p5 ){
VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
if( pOp->opcode==OP_Column ) pOp->p5 = p5;
}
return iReg;
}
/*
** Generate code to move content from registers iFrom...iFrom+nReg-1
** over to iTo..iTo+nReg-1.
*/
void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
}
/*
** Convert a scalar expression node to a TK_REGISTER referencing
** register iReg. The caller must ensure that iReg already contains
** the correct value for the expression.
*/
static void exprToRegister(Expr *pExpr, int iReg){
Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
p->op2 = p->op;
p->op = TK_REGISTER;
p->iTable = iReg;
ExprClearProperty(p, EP_Skip);
}
/*
** Evaluate an expression (either a vector or a scalar expression) and store
** the result in continguous temporary registers. Return the index of
** the first register used to store the result.
**
** If the returned result register is a temporary scalar, then also write
** that register number into *piFreeable. If the returned result register
** is not a temporary or if the expression is a vector set *piFreeable
** to 0.
*/
static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
int iResult;
int nResult = sqlite3ExprVectorSize(p);
if( nResult==1 ){
iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
}else{
*piFreeable = 0;
if( p->op==TK_SELECT ){
#if SQLITE_OMIT_SUBQUERY
iResult = 0;
#else
iResult = sqlite3CodeSubselect(pParse, p);
#endif
}else{
int i;
iResult = pParse->nMem+1;
pParse->nMem += nResult;
for(i=0; i<nResult; i++){
sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
}
}
}
return iResult;
}
/*
** Generate code into the current Vdbe to evaluate the given
** expression. Attempt to store the results in register "target".
** Return the register where results are stored.
**
** With this routine, there is no guarantee that results will
** be stored in target. The result might be stored in some other
** register if it is convenient to do so. The calling function
** must check the return code and move the results to the desired
** register.
*/
int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
Vdbe *v = pParse->pVdbe; /* The VM under construction */
int op; /* The opcode being coded */
int inReg = target; /* Results stored in register inReg */
int regFree1 = 0; /* If non-zero free this temporary register */
int regFree2 = 0; /* If non-zero free this temporary register */
int r1, r2; /* Various register numbers */
Expr tempX; /* Temporary expression node */
int p5 = 0;
assert( target>0 && target<=pParse->nMem );
if( v==0 ){
assert( pParse->db->mallocFailed );
return 0;
}
expr_code_doover:
if( pExpr==0 ){
op = TK_NULL;
}else{
op = pExpr->op;
}
switch( op ){
case TK_AGG_COLUMN: {
AggInfo *pAggInfo = pExpr->pAggInfo;
struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
if( !pAggInfo->directMode ){
assert( pCol->iMem>0 );
return pCol->iMem;
}else if( pAggInfo->useSortingIdx ){
sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
pCol->iSorterColumn, target);
return target;
}
/* Otherwise, fall thru into the TK_COLUMN case */
}
case TK_COLUMN: {
int iTab = pExpr->iTable;
if( ExprHasProperty(pExpr, EP_FixedCol) ){
/* This COLUMN expression is really a constant due to WHERE clause
** constraints, and that constant is coded by the pExpr->pLeft
** expresssion. However, make sure the constant has the correct
** datatype by applying the Affinity of the table column to the
** constant.
*/
int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
int aff;
if( pExpr->y.pTab ){
aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
}else{
aff = pExpr->affExpr;
}
if( aff>SQLITE_AFF_BLOB ){
static const char zAff[] = "B\000C\000D\000E";
assert( SQLITE_AFF_BLOB=='A' );
assert( SQLITE_AFF_TEXT=='B' );
if( iReg!=target ){
sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
iReg = target;
}
sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
&zAff[(aff-'B')*2], P4_STATIC);
}
return iReg;
}
if( iTab<0 ){
if( pParse->iSelfTab<0 ){
/* Other columns in the same row for CHECK constraints or
** generated columns or for inserting into partial index.
** The row is unpacked into registers beginning at
** 0-(pParse->iSelfTab). The rowid (if any) is in a register
** immediately prior to the first column.
*/
Column *pCol;
Table *pTab = pExpr->y.pTab;
int iSrc;
int iCol = pExpr->iColumn;
assert( pTab!=0 );
assert( iCol>=XN_ROWID );
assert( iCol<pExpr->y.pTab->nCol );
if( iCol<0 ){
return -1-pParse->iSelfTab;
}
pCol = pTab->aCol + iCol;
testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( pCol->colFlags & COLFLAG_GENERATED ){
if( pCol->colFlags & COLFLAG_BUSY ){
sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
pCol->zName);
return 0;
}
pCol->colFlags |= COLFLAG_BUSY;
if( pCol->colFlags & COLFLAG_NOTAVAIL ){
sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
}
pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
return iSrc;
}else
#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
if( pCol->affinity==SQLITE_AFF_REAL ){
sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
return target;
}else{
return iSrc;
}
}else{
/* Coding an expression that is part of an index where column names
** in the index refer to the table to which the index belongs */
iTab = pParse->iSelfTab - 1;
}
}
return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
pExpr->iColumn, iTab, target,
pExpr->op2);
}
case TK_INTEGER: {
codeInteger(pParse, pExpr, 0, target);
return target;
}
case TK_TRUEFALSE: {
sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
return target;
}
#ifndef SQLITE_OMIT_FLOATING_POINT
case TK_FLOAT: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
codeReal(v, pExpr->u.zToken, 0, target);
return target;
}
#endif
case TK_STRING: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
return target;
}
default: {
/* Make NULL the default case so that if a bug causes an illegal
** Expr node to be passed into this function, it will be handled
** sanely and not crash. But keep an assert() to bring the problem
** to the attention of the developers. */
assert( op==TK_NULL );
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
return target;
}
#ifndef SQLITE_OMIT_BLOB_LITERAL
case TK_BLOB: {
int n;
const char *z;
char *zBlob;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
assert( pExpr->u.zToken[1]=='\'' );
z = &pExpr->u.zToken[2];
n = sqlite3Strlen30(z) - 1;
assert( z[n]=='\'' );
zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
return target;
}
#endif
case TK_VARIABLE: {
assert( !ExprHasProperty(pExpr, EP_IntValue) );
assert( pExpr->u.zToken!=0 );
assert( pExpr->u.zToken[0]!=0 );
sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
if( pExpr->u.zToken[1]!=0 ){
const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
}
return target;
}
case TK_REGISTER: {
return pExpr->iTable;
}
#ifndef SQLITE_OMIT_CAST
case TK_CAST: {
/* Expressions of the form: CAST(pLeft AS token) */
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
if( inReg!=target ){
sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
inReg = target;
}
sqlite3VdbeAddOp2(v, OP_Cast, target,
sqlite3AffinityType(pExpr->u.zToken, 0));
return inReg;
}
#endif /* SQLITE_OMIT_CAST */
case TK_IS:
case TK_ISNOT:
op = (op==TK_IS) ? TK_EQ : TK_NE;
p5 = SQLITE_NULLEQ;
/* fall-through */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
Expr *pLeft = pExpr->pLeft;
if( sqlite3ExprIsVector(pLeft) ){
codeVectorCompare(pParse, pExpr, target, op, p5);
}else{
r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pLeft, pExpr->pRight, op,
r1, r2, inReg, SQLITE_STOREP2 | p5,
ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
testcase( regFree1==0 );
testcase( regFree2==0 );
}
break;
}
case TK_AND:
case TK_OR:
case TK_PLUS:
case TK_STAR:
case TK_MINUS:
case TK_REM:
case TK_BITAND:
case TK_BITOR:
case TK_SLASH:
case TK_LSHIFT:
case TK_RSHIFT:
case TK_CONCAT: {
assert( TK_AND==OP_And ); testcase( op==TK_AND );
assert( TK_OR==OP_Or ); testcase( op==TK_OR );
assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
sqlite3VdbeAddOp3(v, op, r2, r1, target);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_UMINUS: {
Expr *pLeft = pExpr->pLeft;
assert( pLeft );
if( pLeft->op==TK_INTEGER ){
codeInteger(pParse, pLeft, 1, target);
return target;
#ifndef SQLITE_OMIT_FLOATING_POINT
}else if( pLeft->op==TK_FLOAT ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
codeReal(v, pLeft->u.zToken, 1, target);
return target;
#endif
}else{
tempX.op = TK_INTEGER;
tempX.flags = EP_IntValue|EP_TokenOnly;
tempX.u.iValue = 0;
r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2);
sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
testcase( regFree2==0 );
}
break;
}
case TK_BITNOT:
case TK_NOT: {
assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
sqlite3VdbeAddOp2(v, op, r1, inReg);
break;
}
case TK_TRUTH: {
int isTrue; /* IS TRUE or IS NOT TRUE */
int bNormal; /* IS TRUE or IS FALSE */
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
bNormal = pExpr->op2==TK_IS;
testcase( isTrue && bNormal);
testcase( !isTrue && bNormal);
sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
int addr;
assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
testcase( regFree1==0 );
addr = sqlite3VdbeAddOp1(v, op, r1);
VdbeCoverageIf(v, op==TK_ISNULL);
VdbeCoverageIf(v, op==TK_NOTNULL);
sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
sqlite3VdbeJumpHere(v, addr);
break;
}
case TK_AGG_FUNCTION: {
AggInfo *pInfo = pExpr->pAggInfo;
if( pInfo==0 ){
assert( !ExprHasProperty(pExpr, EP_IntValue) );
sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
}else{
return pInfo->aFunc[pExpr->iAgg].iMem;
}
break;
}
case TK_FUNCTION: {
ExprList *pFarg; /* List of function arguments */
int nFarg; /* Number of function arguments */
FuncDef *pDef; /* The function definition object */
const char *zId; /* The function name */
u32 constMask = 0; /* Mask of function arguments that are constant */
int i; /* Loop counter */
sqlite3 *db = pParse->db; /* The database connection */
u8 enc = ENC(db); /* The text encoding used by this database */
CollSeq *pColl = 0; /* A collating sequence */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
return pExpr->y.pWin->regResult;
}
#endif
if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
/* SQL functions can be expensive. So try to move constant functions
** out of the inner loop, even if that means an extra OP_Copy. */
return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
}
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
if( ExprHasProperty(pExpr, EP_TokenOnly) ){
pFarg = 0;
}else{
pFarg = pExpr->x.pList;
}
nFarg = pFarg ? pFarg->nExpr : 0;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
zId = pExpr->u.zToken;
pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
if( pDef==0 && pParse->explain ){
pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
}
#endif
if( pDef==0 || pDef->xFinalize!=0 ){
sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
break;
}
/* Attempt a direct implementation of the built-in COALESCE() and
** IFNULL() functions. This avoids unnecessary evaluation of
** arguments past the first non-NULL argument.
*/
if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
int endCoalesce = sqlite3VdbeMakeLabel(pParse);
assert( nFarg>=2 );
sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
for(i=1; i<nFarg; i++){
sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
VdbeCoverage(v);
sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
}
sqlite3VdbeResolveLabel(v, endCoalesce);
break;
}
/* The UNLIKELY() function is a no-op. The result is the value
** of the first argument.
*/
if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
assert( nFarg>=1 );
return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
}
#ifdef SQLITE_DEBUG
/* The AFFINITY() function evaluates to a string that describes
** the type affinity of the argument. This is used for testing of
** the SQLite type logic.
*/
if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
char aff;
assert( nFarg==1 );
aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
sqlite3VdbeLoadString(v, target,
(aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
return target;
}
#endif
for(i=0; i<nFarg; i++){
if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
testcase( i==31 );
constMask |= MASKBIT32(i);
}
if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
}
}
if( pFarg ){
if( constMask ){
r1 = pParse->nMem+1;
pParse->nMem += nFarg;
}else{
r1 = sqlite3GetTempRange(pParse, nFarg);
}
/* For length() and typeof() functions with a column argument,
** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
** loading.
*/
if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
u8 exprOp;
assert( nFarg==1 );
assert( pFarg->a[0].pExpr!=0 );
exprOp = pFarg->a[0].pExpr->op;
if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
pFarg->a[0].pExpr->op2 =
pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
}
}
sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
}else{
r1 = 0;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Possibly overload the function if the first argument is
** a virtual table column.
**
** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
** second argument, not the first, as the argument to test to
** see if it is a column in a virtual table. This is done because
** the left operand of infix functions (the operand we want to
** control overloading) ends up as the second argument to the
** function. The expression "A glob B" is equivalent to
** "glob(B,A). We want to use the A in "A glob B" to test
** for function overloading. But we use the B term in "glob(B,A)".
*/
if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
}else if( nFarg>0 ){
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
}
#endif
if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
if( !pColl ) pColl = db->pDfltColl;
sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
}
#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
Expr *pArg = pFarg->a[0].pExpr;
if( pArg->op==TK_COLUMN ){
sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
}else{
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
}
}else
#endif
{
sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
pDef, pExpr->op2);
}
if( nFarg && constMask==0 ){
sqlite3ReleaseTempRange(pParse, r1, nFarg);
}
return target;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_EXISTS:
case TK_SELECT: {
int nCol;
testcase( op==TK_EXISTS );
testcase( op==TK_SELECT );
if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
sqlite3SubselectError(pParse, nCol, 1);
}else{
return sqlite3CodeSubselect(pParse, pExpr);
}
break;
}
case TK_SELECT_COLUMN: {
int n;
if( pExpr->pLeft->iTable==0 ){
pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
}
assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
if( pExpr->iTable!=0
&& pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
){
sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
pExpr->iTable, n);
}
return pExpr->pLeft->iTable + pExpr->iColumn;
}
case TK_IN: {
int destIfFalse = sqlite3VdbeMakeLabel(pParse);
int destIfNull = sqlite3VdbeMakeLabel(pParse);
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
sqlite3VdbeResolveLabel(v, destIfFalse);
sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
sqlite3VdbeResolveLabel(v, destIfNull);
return target;
}
#endif /* SQLITE_OMIT_SUBQUERY */
/*
** x BETWEEN y AND z
**
** This is equivalent to
**
** x>=y AND x<=z
**
** X is stored in pExpr->pLeft.
** Y is stored in pExpr->pList->a[0].pExpr.
** Z is stored in pExpr->pList->a[1].pExpr.
*/
case TK_BETWEEN: {
exprCodeBetween(pParse, pExpr, target, 0, 0);
return target;
}
case TK_SPAN:
case TK_COLLATE:
case TK_UPLUS: {
pExpr = pExpr->pLeft;
goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
}
case TK_TRIGGER: {
/* If the opcode is TK_TRIGGER, then the expression is a reference
** to a column in the new.* or old.* pseudo-tables available to
** trigger programs. In this case Expr.iTable is set to 1 for the
** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
** is set to the column of the pseudo-table to read, or to -1 to
** read the rowid field.
**
** The expression is implemented using an OP_Param opcode. The p1
** parameter is set to 0 for an old.rowid reference, or to (i+1)
** to reference another column of the old.* pseudo-table, where
** i is the index of the column. For a new.rowid reference, p1 is
** set to (n+1), where n is the number of columns in each pseudo-table.
** For a reference to any other column in the new.* pseudo-table, p1
** is set to (n+2+i), where n and i are as defined previously. For
** example, if the table on which triggers are being fired is
** declared as:
**
** CREATE TABLE t1(a, b);
**
** Then p1 is interpreted as follows:
**
** p1==0 -> old.rowid p1==3 -> new.rowid
** p1==1 -> old.a p1==4 -> new.a
** p1==2 -> old.b p1==5 -> new.b
*/
Table *pTab = pExpr->y.pTab;
int iCol = pExpr->iColumn;
int p1 = pExpr->iTable * (pTab->nCol+1) + 1
+ sqlite3TableColumnToStorage(pTab, iCol);
assert( pExpr->iTable==0 || pExpr->iTable==1 );
assert( iCol>=-1 && iCol<pTab->nCol );
assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
assert( p1>=0 && p1<(pTab->nCol*2+2) );
sqlite3VdbeAddOp2(v, OP_Param, p1, target);
VdbeComment((v, "r[%d]=%s.%s", target,
(pExpr->iTable ? "new" : "old"),
(pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
));
#ifndef SQLITE_OMIT_FLOATING_POINT
/* If the column has REAL affinity, it may currently be stored as an
** integer. Use OP_RealAffinity to make sure it is really real.
**
** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
** floating point when extracting it from the record. */
if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
}
#endif
break;
}
case TK_VECTOR: {
sqlite3ErrorMsg(pParse, "row value misused");
break;
}
/* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
** that derive from the right-hand table of a LEFT JOIN. The
** Expr.iTable value is the table number for the right-hand table.
** The expression is only evaluated if that table is not currently
** on a LEFT JOIN NULL row.
*/
case TK_IF_NULL_ROW: {
int addrINR;
u8 okConstFactor = pParse->okConstFactor;
addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
/* Temporarily disable factoring of constant expressions, since
** even though expressions may appear to be constant, they are not
** really constant because they originate from the right-hand side
** of a LEFT JOIN. */
pParse->okConstFactor = 0;
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
pParse->okConstFactor = okConstFactor;
sqlite3VdbeJumpHere(v, addrINR);
sqlite3VdbeChangeP3(v, addrINR, inReg);
break;
}
/*
** Form A:
** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
**
** Form B:
** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
**
** Form A is can be transformed into the equivalent form B as follows:
** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
** WHEN x=eN THEN rN ELSE y END
**
** X (if it exists) is in pExpr->pLeft.
** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
** odd. The Y is also optional. If the number of elements in x.pList
** is even, then Y is omitted and the "otherwise" result is NULL.
** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
**
** The result of the expression is the Ri for the first matching Ei,
** or if there is no matching Ei, the ELSE term Y, or if there is
** no ELSE term, NULL.
*/
case TK_CASE: {
int endLabel; /* GOTO label for end of CASE stmt */
int nextCase; /* GOTO label for next WHEN clause */
int nExpr; /* 2x number of WHEN terms */
int i; /* Loop counter */
ExprList *pEList; /* List of WHEN terms */
struct ExprList_item *aListelem; /* Array of WHEN terms */
Expr opCompare; /* The X==Ei expression */
Expr *pX; /* The X expression */
Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
Expr *pDel = 0;
sqlite3 *db = pParse->db;
assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
assert(pExpr->x.pList->nExpr > 0);
pEList = pExpr->x.pList;
aListelem = pEList->a;
nExpr = pEList->nExpr;
endLabel = sqlite3VdbeMakeLabel(pParse);
if( (pX = pExpr->pLeft)!=0 ){
pDel = sqlite3ExprDup(db, pX, 0);
if( db->mallocFailed ){
sqlite3ExprDelete(db, pDel);
break;
}
testcase( pX->op==TK_COLUMN );
exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1));
testcase( regFree1==0 );
memset(&opCompare, 0, sizeof(opCompare));
opCompare.op = TK_EQ;
opCompare.pLeft = pDel;
pTest = &opCompare;
/* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
** The value in regFree1 might get SCopy-ed into the file result.
** So make sure that the regFree1 register is not reused for other
** purposes and possibly overwritten. */
regFree1 = 0;
}
for(i=0; i<nExpr-1; i=i+2){
if( pX ){
assert( pTest!=0 );
opCompare.pRight = aListelem[i].pExpr;
}else{
pTest = aListelem[i].pExpr;
}
nextCase = sqlite3VdbeMakeLabel(pParse);
testcase( pTest->op==TK_COLUMN );
sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
sqlite3VdbeGoto(v, endLabel);
sqlite3VdbeResolveLabel(v, nextCase);
}
if( (nExpr&1)!=0 ){
sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
}else{
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
}
sqlite3ExprDelete(db, pDel);
sqlite3VdbeResolveLabel(v, endLabel);
break;
}
#ifndef SQLITE_OMIT_TRIGGER
case TK_RAISE: {
assert( pExpr->affExpr==OE_Rollback
|| pExpr->affExpr==OE_Abort
|| pExpr->affExpr==OE_Fail
|| pExpr->affExpr==OE_Ignore
);
if( !pParse->pTriggerTab ){
sqlite3ErrorMsg(pParse,
"RAISE() may only be used within a trigger-program");
return 0;
}
if( pExpr->affExpr==OE_Abort ){
sqlite3MayAbort(pParse);
}
assert( !ExprHasProperty(pExpr, EP_IntValue) );
if( pExpr->affExpr==OE_Ignore ){
sqlite3VdbeAddOp4(
v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
VdbeCoverage(v);
}else{
sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
pExpr->affExpr, pExpr->u.zToken, 0, 0);
}
break;
}
#endif
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
return inReg;
}
/*
** Factor out the code of the given expression to initialization time.
**
** If regDest>=0 then the result is always stored in that register and the
** result is not reusable. If regDest<0 then this routine is free to
** store the value whereever it wants. The register where the expression
** is stored is returned. When regDest<0, two identical expressions will
** code to the same register.
*/
int sqlite3ExprCodeAtInit(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The expression to code when the VDBE initializes */
int regDest /* Store the value in this register */
){
ExprList *p;
assert( ConstFactorOk(pParse) );
p = pParse->pConstExpr;
if( regDest<0 && p ){
struct ExprList_item *pItem;
int i;
for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
return pItem->u.iConstExprReg;
}
}
}
pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
p = sqlite3ExprListAppend(pParse, p, pExpr);
if( p ){
struct ExprList_item *pItem = &p->a[p->nExpr-1];
pItem->reusable = regDest<0;
if( regDest<0 ) regDest = ++pParse->nMem;
pItem->u.iConstExprReg = regDest;
}
pParse->pConstExpr = p;
return regDest;
}
/*
** Generate code to evaluate an expression and store the results
** into a register. Return the register number where the results
** are stored.
**
** If the register is a temporary register that can be deallocated,
** then write its number into *pReg. If the result register is not
** a temporary, then set *pReg to zero.
**
** If pExpr is a constant, then this routine might generate this
** code to fill the register in the initialization section of the
** VDBE program, in order to factor it out of the evaluation loop.
*/
int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
int r2;
pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
if( ConstFactorOk(pParse)
&& pExpr->op!=TK_REGISTER
&& sqlite3ExprIsConstantNotJoin(pExpr)
){
*pReg = 0;
r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
}else{
int r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
if( r2==r1 ){
*pReg = r1;
}else{
sqlite3ReleaseTempReg(pParse, r1);
*pReg = 0;
}
}
return r2;
}
/*
** Generate code that will evaluate expression pExpr and store the
** results in register target. The results are guaranteed to appear
** in register target.
*/
void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
int inReg;
assert( target>0 && target<=pParse->nMem );
inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
if( inReg!=target && pParse->pVdbe ){
sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
}
}
/*
** Make a transient copy of expression pExpr and then code it using
** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
** except that the input expression is guaranteed to be unchanged.
*/
void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
sqlite3 *db = pParse->db;
pExpr = sqlite3ExprDup(db, pExpr, 0);
if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
sqlite3ExprDelete(db, pExpr);
}
/*
** Generate code that will evaluate expression pExpr and store the
** results in register target. The results are guaranteed to appear
** in register target. If the expression is constant, then this routine
** might choose to code the expression at initialization time.
*/
void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
sqlite3ExprCodeAtInit(pParse, pExpr, target);
}else{
sqlite3ExprCode(pParse, pExpr, target);
}
}
/*
** Generate code that pushes the value of every element of the given
** expression list into a sequence of registers beginning at target.
**
** Return the number of elements evaluated. The number returned will
** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
** is defined.
**
** The SQLITE_ECEL_DUP flag prevents the arguments from being
** filled using OP_SCopy. OP_Copy must be used instead.
**
** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
** factored out into initialization code.
**
** The SQLITE_ECEL_REF flag means that expressions in the list with
** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
** in registers at srcReg, and so the value can be copied from there.
** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
** are simply omitted rather than being copied from srcReg.
*/
int sqlite3ExprCodeExprList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* The expression list to be coded */
int target, /* Where to write results */
int srcReg, /* Source registers if SQLITE_ECEL_REF */
u8 flags /* SQLITE_ECEL_* flags */
){
struct ExprList_item *pItem;
int i, j, n;
u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
Vdbe *v = pParse->pVdbe;
assert( pList!=0 );
assert( target>0 );
assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
n = pList->nExpr;
if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
for(pItem=pList->a, i=0; i<n; i++, pItem++){
Expr *pExpr = pItem->pExpr;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pItem->bSorterRef ){
i--;
n--;
}else
#endif
if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
if( flags & SQLITE_ECEL_OMITREF ){
i--;
n--;
}else{
sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
}
}else if( (flags & SQLITE_ECEL_FACTOR)!=0
&& sqlite3ExprIsConstantNotJoin(pExpr)
){
sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
}else{
int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
if( inReg!=target+i ){
VdbeOp *pOp;
if( copyOp==OP_Copy
&& (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
&& pOp->p1+pOp->p3+1==inReg
&& pOp->p2+pOp->p3+1==target+i
){
pOp->p3++;
}else{
sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
}
}
}
}
return n;
}
/*
** Generate code for a BETWEEN operator.
**
** x BETWEEN y AND z
**
** The above is equivalent to
**
** x>=y AND x<=z
**
** Code it as such, taking care to do the common subexpression
** elimination of x.
**
** The xJumpIf parameter determines details:
**
** NULL: Store the boolean result in reg[dest]
** sqlite3ExprIfTrue: Jump to dest if true
** sqlite3ExprIfFalse: Jump to dest if false
**
** The jumpIfNull parameter is ignored if xJumpIf is NULL.
*/
static void exprCodeBetween(
Parse *pParse, /* Parsing and code generating context */
Expr *pExpr, /* The BETWEEN expression */
int dest, /* Jump destination or storage location */
void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
int jumpIfNull /* Take the jump if the BETWEEN is NULL */
){
Expr exprAnd; /* The AND operator in x>=y AND x<=z */
Expr compLeft; /* The x>=y term */
Expr compRight; /* The x<=z term */
int regFree1 = 0; /* Temporary use register */
Expr *pDel = 0;
sqlite3 *db = pParse->db;
memset(&compLeft, 0, sizeof(Expr));
memset(&compRight, 0, sizeof(Expr));
memset(&exprAnd, 0, sizeof(Expr));
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
if( db->mallocFailed==0 ){
exprAnd.op = TK_AND;
exprAnd.pLeft = &compLeft;
exprAnd.pRight = &compRight;
compLeft.op = TK_GE;
compLeft.pLeft = pDel;
compLeft.pRight = pExpr->x.pList->a[0].pExpr;
compRight.op = TK_LE;
compRight.pLeft = pDel;
compRight.pRight = pExpr->x.pList->a[1].pExpr;
exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1));
if( xJump ){
xJump(pParse, &exprAnd, dest, jumpIfNull);
}else{
/* Mark the expression is being from the ON or USING clause of a join
** so that the sqlite3ExprCodeTarget() routine will not attempt to move
** it into the Parse.pConstExpr list. We should use a new bit for this,
** for clarity, but we are out of bits in the Expr.flags field so we
** have to reuse the EP_FromJoin bit. Bummer. */
pDel->flags |= EP_FromJoin;
sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
}
sqlite3ReleaseTempReg(pParse, regFree1);
}
sqlite3ExprDelete(db, pDel);
/* Ensure adequate test coverage */
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
testcase( xJump==0 );
}
/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is true but execution
** continues straight thru if the expression is false.
**
** If the expression evaluates to NULL (neither true nor false), then
** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
**
** This code depends on the fact that certain token values (ex: TK_EQ)
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
** the make process cause these values to align. Assert()s in the code
** below verify that the numbers are aligned correctly.
*/
void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
Vdbe *v = pParse->pVdbe;
int op = 0;
int regFree1 = 0;
int regFree2 = 0;
int r1, r2;
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
if( NEVER(pExpr==0) ) return; /* No way this can happen */
op = pExpr->op;
switch( op ){
case TK_AND:
case TK_OR: {
Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
if( pAlt!=pExpr ){
sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
}else if( op==TK_AND ){
int d2 = sqlite3VdbeMakeLabel(pParse);
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
jumpIfNull^SQLITE_JUMPIFNULL);
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
sqlite3VdbeResolveLabel(v, d2);
}else{
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
}
break;
}
case TK_NOT: {
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
break;
}
case TK_TRUTH: {
int isNot; /* IS NOT TRUE or IS NOT FALSE */
int isTrue; /* IS TRUE or IS NOT TRUE */
testcase( jumpIfNull==0 );
isNot = pExpr->op2==TK_ISNOT;
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
testcase( isTrue && isNot );
testcase( !isTrue && isNot );
if( isTrue ^ isNot ){
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
isNot ? SQLITE_JUMPIFNULL : 0);
}else{
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
isNot ? SQLITE_JUMPIFNULL : 0);
}
break;
}
case TK_IS:
case TK_ISNOT:
testcase( op==TK_IS );
testcase( op==TK_ISNOT );
op = (op==TK_IS) ? TK_EQ : TK_NE;
jumpIfNull = SQLITE_NULLEQ;
/* Fall thru */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
testcase( jumpIfNull==0 );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
sqlite3VdbeAddOp2(v, op, r1, dest);
VdbeCoverageIf(v, op==TK_ISNULL);
VdbeCoverageIf(v, op==TK_NOTNULL);
testcase( regFree1==0 );
break;
}
case TK_BETWEEN: {
testcase( jumpIfNull==0 );
exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_IN: {
int destIfFalse = sqlite3VdbeMakeLabel(pParse);
int destIfNull = jumpIfNull ? dest : destIfFalse;
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
sqlite3VdbeGoto(v, dest);
sqlite3VdbeResolveLabel(v, destIfFalse);
break;
}
#endif
default: {
default_expr:
if( ExprAlwaysTrue(pExpr) ){
sqlite3VdbeGoto(v, dest);
}else if( ExprAlwaysFalse(pExpr) ){
/* No-op */
}else{
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
VdbeCoverage(v);
testcase( regFree1==0 );
testcase( jumpIfNull==0 );
}
break;
}
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
}
/*
** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is false but execution
** continues straight thru if the expression is true.
**
** If the expression evaluates to NULL (neither true nor false) then
** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
** is 0.
*/
void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
Vdbe *v = pParse->pVdbe;
int op = 0;
int regFree1 = 0;
int regFree2 = 0;
int r1, r2;
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
if( pExpr==0 ) return;
/* The value of pExpr->op and op are related as follows:
**
** pExpr->op op
** --------- ----------
** TK_ISNULL OP_NotNull
** TK_NOTNULL OP_IsNull
** TK_NE OP_Eq
** TK_EQ OP_Ne
** TK_GT OP_Le
** TK_LE OP_Gt
** TK_GE OP_Lt
** TK_LT OP_Ge
**
** For other values of pExpr->op, op is undefined and unused.
** The value of TK_ and OP_ constants are arranged such that we
** can compute the mapping above using the following expression.
** Assert()s verify that the computation is correct.
*/
op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
/* Verify correct alignment of TK_ and OP_ constants
*/
assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
assert( pExpr->op!=TK_NE || op==OP_Eq );
assert( pExpr->op!=TK_EQ || op==OP_Ne );
assert( pExpr->op!=TK_LT || op==OP_Ge );
assert( pExpr->op!=TK_LE || op==OP_Gt );
assert( pExpr->op!=TK_GT || op==OP_Le );
assert( pExpr->op!=TK_GE || op==OP_Lt );
switch( pExpr->op ){
case TK_AND:
case TK_OR: {
Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
if( pAlt!=pExpr ){
sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
}else if( pExpr->op==TK_AND ){
testcase( jumpIfNull==0 );
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
}else{
int d2 = sqlite3VdbeMakeLabel(pParse);
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
jumpIfNull^SQLITE_JUMPIFNULL);
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
sqlite3VdbeResolveLabel(v, d2);
}
break;
}
case TK_NOT: {
testcase( jumpIfNull==0 );
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
break;
}
case TK_TRUTH: {
int isNot; /* IS NOT TRUE or IS NOT FALSE */
int isTrue; /* IS TRUE or IS NOT TRUE */
testcase( jumpIfNull==0 );
isNot = pExpr->op2==TK_ISNOT;
isTrue = sqlite3ExprTruthValue(pExpr->pRight);
testcase( isTrue && isNot );
testcase( !isTrue && isNot );
if( isTrue ^ isNot ){
/* IS TRUE and IS NOT FALSE */
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
isNot ? 0 : SQLITE_JUMPIFNULL);
}else{
/* IS FALSE and IS NOT TRUE */
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
isNot ? 0 : SQLITE_JUMPIFNULL);
}
break;
}
case TK_IS:
case TK_ISNOT:
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_ISNOT );
op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
jumpIfNull = SQLITE_NULLEQ;
/* Fall thru */
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_NE:
case TK_EQ: {
if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
testcase( jumpIfNull==0 );
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
testcase( regFree1==0 );
testcase( regFree2==0 );
break;
}
case TK_ISNULL:
case TK_NOTNULL: {
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
sqlite3VdbeAddOp2(v, op, r1, dest);
testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
testcase( regFree1==0 );
break;
}
case TK_BETWEEN: {
testcase( jumpIfNull==0 );
exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_IN: {
if( jumpIfNull ){
sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
}else{
int destIfNull = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
sqlite3VdbeResolveLabel(v, destIfNull);
}
break;
}
#endif
default: {
default_expr:
if( ExprAlwaysFalse(pExpr) ){
sqlite3VdbeGoto(v, dest);
}else if( ExprAlwaysTrue(pExpr) ){
/* no-op */
}else{
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
VdbeCoverage(v);
testcase( regFree1==0 );
testcase( jumpIfNull==0 );
}
break;
}
}
sqlite3ReleaseTempReg(pParse, regFree1);
sqlite3ReleaseTempReg(pParse, regFree2);
}
/*
** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
** code generation, and that copy is deleted after code generation. This
** ensures that the original pExpr is unchanged.
*/
void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
sqlite3 *db = pParse->db;
Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
if( db->mallocFailed==0 ){
sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
}
sqlite3ExprDelete(db, pCopy);
}
/*
** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
** type of expression.
**
** If pExpr is a simple SQL value - an integer, real, string, blob
** or NULL value - then the VDBE currently being prepared is configured
** to re-prepare each time a new value is bound to variable pVar.
**
** Additionally, if pExpr is a simple SQL value and the value is the
** same as that currently bound to variable pVar, non-zero is returned.
** Otherwise, if the values are not the same or if pExpr is not a simple
** SQL value, zero is returned.
*/
static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
int res = 0;
int iVar;
sqlite3_value *pL, *pR = 0;
sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
if( pR ){
iVar = pVar->iColumn;
sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
if( pL ){
if( sqlite3_value_type(pL)==SQLITE_TEXT ){
sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
}
res = 0==sqlite3MemCompare(pL, pR, 0);
}
sqlite3ValueFree(pR);
sqlite3ValueFree(pL);
}
return res;
}
/*
** Do a deep comparison of two expression trees. Return 0 if the two
** expressions are completely identical. Return 1 if they differ only
** by a COLLATE operator at the top level. Return 2 if there are differences
** other than the top-level COLLATE operator.
**
** If any subelement of pB has Expr.iTable==(-1) then it is allowed
** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
**
** The pA side might be using TK_REGISTER. If that is the case and pB is
** not using TK_REGISTER but is otherwise equivalent, then still return 0.
**
** Sometimes this routine will return 2 even if the two expressions
** really are equivalent. If we cannot prove that the expressions are
** identical, we return 2 just to be safe. So if this routine
** returns 2, then you do not really know for certain if the two
** expressions are the same. But if you get a 0 or 1 return, then you
** can be sure the expressions are the same. In the places where
** this routine is used, it does not hurt to get an extra 2 - that
** just might result in some slightly slower code. But returning
** an incorrect 0 or 1 could lead to a malfunction.
**
** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
** pParse->pReprepare can be matched against literals in pB. The
** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
** If pParse is NULL (the normal case) then any TK_VARIABLE term in
** Argument pParse should normally be NULL. If it is not NULL and pA or
** pB causes a return value of 2.
*/
int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
u32 combinedFlags;
if( pA==0 || pB==0 ){
return pB==pA ? 0 : 2;
}
if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
return 0;
}
combinedFlags = pA->flags | pB->flags;
if( combinedFlags & EP_IntValue ){
if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
return 0;
}
return 2;
}
if( pA->op!=pB->op || pA->op==TK_RAISE ){
if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
return 1;
}
if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
return 1;
}
return 2;
}
if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( pA->op==pB->op );
if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
return 2;
}
if( ExprHasProperty(pA,EP_WinFunc) ){
if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
return 2;
}
}
#endif
}else if( pA->op==TK_NULL ){
return 0;
}else if( pA->op==TK_COLLATE ){
if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
}else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
return 2;
}
}
if( (pA->flags & (EP_Distinct|EP_Commuted))
!= (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
if( (combinedFlags & EP_TokenOnly)==0 ){
if( combinedFlags & EP_xIsSelect ) return 2;
if( (combinedFlags & EP_FixedCol)==0
&& sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
if( pA->op!=TK_STRING
&& pA->op!=TK_TRUEFALSE
&& (combinedFlags & EP_Reduced)==0
){
if( pA->iColumn!=pB->iColumn ) return 2;
if( pA->op2!=pB->op2 ){
if( pA->op==TK_TRUTH ) return 2;
if( pA->op==TK_FUNCTION && iTab<0 ){
/* Ex: CREATE TABLE t1(a CHECK( a<julianday('now') ));
** INSERT INTO t1(a) VALUES(julianday('now')+10);
** Without this test, sqlite3ExprCodeAtInit() will run on the
** the julianday() of INSERT first, and remember that expression.
** Then sqlite3ExprCodeInit() will see the julianday() in the CHECK
** constraint as redundant, reusing the one from the INSERT, even
** though the julianday() in INSERT lacks the critical NC_IsCheck
** flag. See ticket [830277d9db6c3ba1] (2019-10-30)
*/
return 2;
}
}
if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
return 2;
}
}
}
return 0;
}
/*
** Compare two ExprList objects. Return 0 if they are identical and
** non-zero if they differ in any way.
**
** If any subelement of pB has Expr.iTable==(-1) then it is allowed
** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
**
** This routine might return non-zero for equivalent ExprLists. The
** only consequence will be disabled optimizations. But this routine
** must never return 0 if the two ExprList objects are different, or
** a malfunction will result.
**
** Two NULL pointers are considered to be the same. But a NULL pointer
** always differs from a non-NULL pointer.
*/
int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
int i;
if( pA==0 && pB==0 ) return 0;
if( pA==0 || pB==0 ) return 1;
if( pA->nExpr!=pB->nExpr ) return 1;
for(i=0; i<pA->nExpr; i++){
Expr *pExprA = pA->a[i].pExpr;
Expr *pExprB = pB->a[i].pExpr;
if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
}
return 0;
}
/*
** Like sqlite3ExprCompare() except COLLATE operators at the top-level
** are ignored.
*/
int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
return sqlite3ExprCompare(0,
sqlite3ExprSkipCollateAndLikely(pA),
sqlite3ExprSkipCollateAndLikely(pB),
iTab);
}
/*
** Return non-zero if Expr p can only be true if pNN is not NULL.
**
** Or if seenNot is true, return non-zero if Expr p can only be
** non-NULL if pNN is not NULL
*/
static int exprImpliesNotNull(
Parse *pParse, /* Parsing context */
Expr *p, /* The expression to be checked */
Expr *pNN, /* The expression that is NOT NULL */
int iTab, /* Table being evaluated */
int seenNot /* Return true only if p can be any non-NULL value */
){
assert( p );
assert( pNN );
if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
return pNN->op!=TK_NULL;
}
switch( p->op ){
case TK_IN: {
if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
assert( ExprHasProperty(p,EP_xIsSelect)
|| (p->x.pList!=0 && p->x.pList->nExpr>0) );
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_BETWEEN: {
ExprList *pList = p->x.pList;
assert( pList!=0 );
assert( pList->nExpr==2 );
if( seenNot ) return 0;
if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
|| exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
){
return 1;
}
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
case TK_PLUS:
case TK_MINUS:
case TK_BITOR:
case TK_LSHIFT:
case TK_RSHIFT:
case TK_CONCAT:
seenNot = 1;
/* Fall thru */
case TK_STAR:
case TK_REM:
case TK_BITAND:
case TK_SLASH: {
if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
/* Fall thru into the next case */
}
case TK_SPAN:
case TK_COLLATE:
case TK_UPLUS:
case TK_UMINUS: {
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
}
case TK_TRUTH: {
if( seenNot ) return 0;
if( p->op2!=TK_IS ) return 0;
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
case TK_BITNOT:
case TK_NOT: {
return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
}
}
return 0;
}
/*
** Return true if we can prove the pE2 will always be true if pE1 is
** true. Return false if we cannot complete the proof or if pE2 might
** be false. Examples:
**
** pE1: x==5 pE2: x==5 Result: true
** pE1: x>0 pE2: x==5 Result: false
** pE1: x=21 pE2: x=21 OR y=43 Result: true
** pE1: x!=123 pE2: x IS NOT NULL Result: true
** pE1: x!=?1 pE2: x IS NOT NULL Result: true
** pE1: x IS NULL pE2: x IS NOT NULL Result: false
** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
**
** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
** Expr.iTable<0 then assume a table number given by iTab.
**
** If pParse is not NULL, then the values of bound variables in pE1 are
** compared against literal values in pE2 and pParse->pVdbe->expmask is
** modified to record which bound variables are referenced. If pParse
** is NULL, then false will be returned if pE1 contains any bound variables.
**
** When in doubt, return false. Returning true might give a performance
** improvement. Returning false might cause a performance reduction, but
** it will always give the correct answer and is hence always safe.
*/
int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
return 1;
}
if( pE2->op==TK_OR
&& (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
|| sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
){
return 1;
}
if( pE2->op==TK_NOTNULL
&& exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
){
return 1;
}
return 0;
}
/*
** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
** If the expression node requires that the table at pWalker->iCur
** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
**
** This routine controls an optimization. False positives (setting
** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
** (never setting pWalker->eCode) is a harmless missed optimization.
*/
static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
testcase( pExpr->op==TK_AGG_COLUMN );
testcase( pExpr->op==TK_AGG_FUNCTION );
if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
switch( pExpr->op ){
case TK_ISNOT:
case TK_ISNULL:
case TK_NOTNULL:
case TK_IS:
case TK_OR:
case TK_VECTOR:
case TK_CASE:
case TK_IN:
case TK_FUNCTION:
case TK_TRUTH:
testcase( pExpr->op==TK_ISNOT );
testcase( pExpr->op==TK_ISNULL );
testcase( pExpr->op==TK_NOTNULL );
testcase( pExpr->op==TK_IS );
testcase( pExpr->op==TK_OR );
testcase( pExpr->op==TK_VECTOR );
testcase( pExpr->op==TK_CASE );
testcase( pExpr->op==TK_IN );
testcase( pExpr->op==TK_FUNCTION );
testcase( pExpr->op==TK_TRUTH );
return WRC_Prune;
case TK_COLUMN:
if( pWalker->u.iCur==pExpr->iTable ){
pWalker->eCode = 1;
return WRC_Abort;
}
return WRC_Prune;
case TK_AND:
assert( pWalker->eCode==0 );
sqlite3WalkExpr(pWalker, pExpr->pLeft);
if( pWalker->eCode ){
pWalker->eCode = 0;
sqlite3WalkExpr(pWalker, pExpr->pRight);
}
return WRC_Prune;
case TK_BETWEEN:
sqlite3WalkExpr(pWalker, pExpr->pLeft);
return WRC_Prune;
/* Virtual tables are allowed to use constraints like x=NULL. So
** a term of the form x=y does not prove that y is not null if x
** is the column of a virtual table */
case TK_EQ:
case TK_NE:
case TK_LT:
case TK_LE:
case TK_GT:
case TK_GE:
testcase( pExpr->op==TK_EQ );
testcase( pExpr->op==TK_NE );
testcase( pExpr->op==TK_LT );
testcase( pExpr->op==TK_LE );
testcase( pExpr->op==TK_GT );
testcase( pExpr->op==TK_GE );
if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
|| (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
){
return WRC_Prune;
}
default:
return WRC_Continue;
}
}
/*
** Return true (non-zero) if expression p can only be true if at least
** one column of table iTab is non-null. In other words, return true
** if expression p will always be NULL or false if every column of iTab
** is NULL.
**
** False negatives are acceptable. In other words, it is ok to return
** zero even if expression p will never be true of every column of iTab
** is NULL. A false negative is merely a missed optimization opportunity.
**
** False positives are not allowed, however. A false positive may result
** in an incorrect answer.
**
** Terms of p that are marked with EP_FromJoin (and hence that come from
** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
**
** This routine is used to check if a LEFT JOIN can be converted into
** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
** clause requires that some column of the right table of the LEFT JOIN
** be non-NULL, then the LEFT JOIN can be safely converted into an
** ordinary join.
*/
int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
Walker w;
p = sqlite3ExprSkipCollateAndLikely(p);
if( p==0 ) return 0;
if( p->op==TK_NOTNULL ){
p = p->pLeft;
}else{
while( p->op==TK_AND ){
if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
p = p->pRight;
}
}
w.xExprCallback = impliesNotNullRow;
w.xSelectCallback = 0;
w.xSelectCallback2 = 0;
w.eCode = 0;
w.u.iCur = iTab;
sqlite3WalkExpr(&w, p);
return w.eCode;
}
/*
** An instance of the following structure is used by the tree walker
** to determine if an expression can be evaluated by reference to the
** index only, without having to do a search for the corresponding
** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
** is the cursor for the table.
*/
struct IdxCover {
Index *pIdx; /* The index to be tested for coverage */
int iCur; /* Cursor number for the table corresponding to the index */
};
/*
** Check to see if there are references to columns in table
** pWalker->u.pIdxCover->iCur can be satisfied using the index
** pWalker->u.pIdxCover->pIdx.
*/
static int exprIdxCover(Walker *pWalker, Expr *pExpr){
if( pExpr->op==TK_COLUMN
&& pExpr->iTable==pWalker->u.pIdxCover->iCur
&& sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
){
pWalker->eCode = 1;
return WRC_Abort;
}
return WRC_Continue;
}
/*
** Determine if an index pIdx on table with cursor iCur contains will
** the expression pExpr. Return true if the index does cover the
** expression and false if the pExpr expression references table columns
** that are not found in the index pIdx.
**
** An index covering an expression means that the expression can be
** evaluated using only the index and without having to lookup the
** corresponding table entry.
*/
int sqlite3ExprCoveredByIndex(
Expr *pExpr, /* The index to be tested */
int iCur, /* The cursor number for the corresponding table */
Index *pIdx /* The index that might be used for coverage */
){
Walker w;
struct IdxCover xcov;
memset(&w, 0, sizeof(w));
xcov.iCur = iCur;
xcov.pIdx = pIdx;
w.xExprCallback = exprIdxCover;
w.u.pIdxCover = &xcov;
sqlite3WalkExpr(&w, pExpr);
return !w.eCode;
}
/*
** An instance of the following structure is used by the tree walker
** to count references to table columns in the arguments of an
** aggregate function, in order to implement the
** sqlite3FunctionThisSrc() routine.
*/
struct SrcCount {
SrcList *pSrc; /* One particular FROM clause in a nested query */
int nThis; /* Number of references to columns in pSrcList */
int nOther; /* Number of references to columns in other FROM clauses */
};
/*
** Count the number of references to columns.
*/
static int exprSrcCount(Walker *pWalker, Expr *pExpr){
/* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
** is always called before sqlite3ExprAnalyzeAggregates() and so the
** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
** sqlite3FunctionUsesThisSrc() is used differently in the future, the
** NEVER() will need to be removed. */
if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
int i;
struct SrcCount *p = pWalker->u.pSrcCount;
SrcList *pSrc = p->pSrc;
int nSrc = pSrc ? pSrc->nSrc : 0;
for(i=0; i<nSrc; i++){
if( pExpr->iTable==pSrc->a[i].iCursor ) break;
}
if( i<nSrc ){
p->nThis++;
}else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
/* In a well-formed parse tree (no name resolution errors),
** TK_COLUMN nodes with smaller Expr.iTable values are in an
** outer context. Those are the only ones to count as "other" */
p->nOther++;
}
}
return WRC_Continue;
}
/*
** Determine if any of the arguments to the pExpr Function reference
** pSrcList. Return true if they do. Also return true if the function
** has no arguments or has only constant arguments. Return false if pExpr
** references columns but not columns of tables found in pSrcList.
*/
int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
Walker w;
struct SrcCount cnt;
assert( pExpr->op==TK_AGG_FUNCTION );
memset(&w, 0, sizeof(w));
w.xExprCallback = exprSrcCount;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.u.pSrcCount = &cnt;
cnt.pSrc = pSrcList;
cnt.nThis = 0;
cnt.nOther = 0;
sqlite3WalkExprList(&w, pExpr->x.pList);
return cnt.nThis>0 || cnt.nOther==0;
}
/*
** Add a new element to the pAggInfo->aCol[] array. Return the index of
** the new element. Return a negative number if malloc fails.
*/
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
int i;
pInfo->aCol = sqlite3ArrayAllocate(
db,
pInfo->aCol,
sizeof(pInfo->aCol[0]),
&pInfo->nColumn,
&i
);
return i;
}
/*
** Add a new element to the pAggInfo->aFunc[] array. Return the index of
** the new element. Return a negative number if malloc fails.
*/
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
int i;
pInfo->aFunc = sqlite3ArrayAllocate(
db,
pInfo->aFunc,
sizeof(pInfo->aFunc[0]),
&pInfo->nFunc,
&i
);
return i;
}
/*
** This is the xExprCallback for a tree walker. It is used to
** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
** for additional information.
*/
static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
int i;
NameContext *pNC = pWalker->u.pNC;
Parse *pParse = pNC->pParse;
SrcList *pSrcList = pNC->pSrcList;
AggInfo *pAggInfo = pNC->uNC.pAggInfo;
assert( pNC->ncFlags & NC_UAggInfo );
switch( pExpr->op ){
case TK_AGG_COLUMN:
case TK_COLUMN: {
testcase( pExpr->op==TK_AGG_COLUMN );
testcase( pExpr->op==TK_COLUMN );
/* Check to see if the column is in one of the tables in the FROM
** clause of the aggregate query */
if( ALWAYS(pSrcList!=0) ){
struct SrcList_item *pItem = pSrcList->a;
for(i=0; i<pSrcList->nSrc; i++, pItem++){
struct AggInfo_col *pCol;
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
if( pExpr->iTable==pItem->iCursor ){
/* If we reach this point, it means that pExpr refers to a table
** that is in the FROM clause of the aggregate query.
**
** Make an entry for the column in pAggInfo->aCol[] if there
** is not an entry there already.
*/
int k;
pCol = pAggInfo->aCol;
for(k=0; k<pAggInfo->nColumn; k++, pCol++){
if( pCol->iTable==pExpr->iTable &&
pCol->iColumn==pExpr->iColumn ){
break;
}
}
if( (k>=pAggInfo->nColumn)
&& (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
){
pCol = &pAggInfo->aCol[k];
pCol->pTab = pExpr->y.pTab;
pCol->iTable = pExpr->iTable;
pCol->iColumn = pExpr->iColumn;
pCol->iMem = ++pParse->nMem;
pCol->iSorterColumn = -1;
pCol->pExpr = pExpr;
if( pAggInfo->pGroupBy ){
int j, n;
ExprList *pGB = pAggInfo->pGroupBy;
struct ExprList_item *pTerm = pGB->a;
n = pGB->nExpr;
for(j=0; j<n; j++, pTerm++){
Expr *pE = pTerm->pExpr;
if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
pE->iColumn==pExpr->iColumn ){
pCol->iSorterColumn = j;
break;
}
}
}
if( pCol->iSorterColumn<0 ){
pCol->iSorterColumn = pAggInfo->nSortingColumn++;
}
}
/* There is now an entry for pExpr in pAggInfo->aCol[] (either
** because it was there before or because we just created it).
** Convert the pExpr to be a TK_AGG_COLUMN referring to that
** pAggInfo->aCol[] entry.
*/
ExprSetVVAProperty(pExpr, EP_NoReduce);
pExpr->pAggInfo = pAggInfo;
pExpr->op = TK_AGG_COLUMN;
pExpr->iAgg = (i16)k;
break;
} /* endif pExpr->iTable==pItem->iCursor */
} /* end loop over pSrcList */
}
return WRC_Prune;
}
case TK_AGG_FUNCTION: {
if( (pNC->ncFlags & NC_InAggFunc)==0
&& pWalker->walkerDepth==pExpr->op2
){
/* Check to see if pExpr is a duplicate of another aggregate
** function that is already in the pAggInfo structure
*/
struct AggInfo_func *pItem = pAggInfo->aFunc;
for(i=0; i<pAggInfo->nFunc; i++, pItem++){
if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
break;
}
}
if( i>=pAggInfo->nFunc ){
/* pExpr is original. Make a new entry in pAggInfo->aFunc[]
*/
u8 enc = ENC(pParse->db);
i = addAggInfoFunc(pParse->db, pAggInfo);
if( i>=0 ){
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
pItem = &pAggInfo->aFunc[i];
pItem->pExpr = pExpr;
pItem->iMem = ++pParse->nMem;
assert( !ExprHasProperty(pExpr, EP_IntValue) );
pItem->pFunc = sqlite3FindFunction(pParse->db,
pExpr->u.zToken,
pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
if( pExpr->flags & EP_Distinct ){
pItem->iDistinct = pParse->nTab++;
}else{
pItem->iDistinct = -1;
}
}
}
/* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
*/
assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(pExpr, EP_NoReduce);
pExpr->iAgg = (i16)i;
pExpr->pAggInfo = pAggInfo;
return WRC_Prune;
}else{
return WRC_Continue;
}
}
}
return WRC_Continue;
}
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
UNUSED_PARAMETER(pSelect);
pWalker->walkerDepth++;
return WRC_Continue;
}
static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
UNUSED_PARAMETER(pSelect);
pWalker->walkerDepth--;
}
/*
** Analyze the pExpr expression looking for aggregate functions and
** for variables that need to be added to AggInfo object that pNC->pAggInfo
** points to. Additional entries are made on the AggInfo object as
** necessary.
**
** This routine should only be called after the expression has been
** analyzed by sqlite3ResolveExprNames().
*/
void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
Walker w;
w.xExprCallback = analyzeAggregate;
w.xSelectCallback = analyzeAggregatesInSelect;
w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
w.walkerDepth = 0;
w.u.pNC = pNC;
w.pParse = 0;
assert( pNC->pSrcList!=0 );
sqlite3WalkExpr(&w, pExpr);
}
/*
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
** expression list. Return the number of errors.
**
** If an error is found, the analysis is cut short.
*/
void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
struct ExprList_item *pItem;
int i;
if( pList ){
for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
}
}
}
/*
** Allocate a single new register for use to hold some intermediate result.
*/
int sqlite3GetTempReg(Parse *pParse){
if( pParse->nTempReg==0 ){
return ++pParse->nMem;
}
return pParse->aTempReg[--pParse->nTempReg];
}
/*
** Deallocate a register, making available for reuse for some other
** purpose.
*/
void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
pParse->aTempReg[pParse->nTempReg++] = iReg;
}
}
/*
** Allocate or deallocate a block of nReg consecutive registers.
*/
int sqlite3GetTempRange(Parse *pParse, int nReg){
int i, n;
if( nReg==1 ) return sqlite3GetTempReg(pParse);
i = pParse->iRangeReg;
n = pParse->nRangeReg;
if( nReg<=n ){
pParse->iRangeReg += nReg;
pParse->nRangeReg -= nReg;
}else{
i = pParse->nMem+1;
pParse->nMem += nReg;
}
return i;
}
void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
if( nReg==1 ){
sqlite3ReleaseTempReg(pParse, iReg);
return;
}
if( nReg>pParse->nRangeReg ){
pParse->nRangeReg = nReg;
pParse->iRangeReg = iReg;
}
}
/*
** Mark all temporary registers as being unavailable for reuse.
**
** Always invoke this procedure after coding a subroutine or co-routine
** that might be invoked from other parts of the code, to ensure that
** the sub/co-routine does not use registers in common with the code that
** invokes the sub/co-routine.
*/
void sqlite3ClearTempRegCache(Parse *pParse){
pParse->nTempReg = 0;
pParse->nRangeReg = 0;
}
/*
** Validate that no temporary register falls within the range of
** iFirst..iLast, inclusive. This routine is only call from within assert()
** statements.
*/
#ifdef SQLITE_DEBUG
int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
int i;
if( pParse->nRangeReg>0
&& pParse->iRangeReg+pParse->nRangeReg > iFirst
&& pParse->iRangeReg <= iLast
){
return 0;
}
for(i=0; i<pParse->nTempReg; i++){
if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
return 0;
}
}
return 1;
}
#endif /* SQLITE_DEBUG */
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_1325_2 |
crossvul-cpp_data_bad_1368_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Linux INET6 implementation
* Forwarding Information Database
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Changes:
* Yuji SEKIYA @USAGI: Support default route on router node;
* remove ip6_null_entry from the top of
* routing table.
* Ville Nuorvala: Fixed routing subtrees.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/lwtunnel.h>
#include <net/fib_notifier.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
static struct kmem_cache *fib6_node_kmem __read_mostly;
struct fib6_cleaner {
struct fib6_walker w;
struct net *net;
int (*func)(struct fib6_info *, void *arg);
int sernum;
void *arg;
bool skip_notify;
};
#ifdef CONFIG_IPV6_SUBTREES
#define FWS_INIT FWS_S
#else
#define FWS_INIT FWS_L
#endif
static struct fib6_info *fib6_find_prefix(struct net *net,
struct fib6_table *table,
struct fib6_node *fn);
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_table *table,
struct fib6_node *fn);
static int fib6_walk(struct net *net, struct fib6_walker *w);
static int fib6_walk_continue(struct fib6_walker *w);
/*
* A routing update causes an increase of the serial number on the
* affected subtree. This allows for cached routes to be asynchronously
* tested when modifications are made to the destination cache as a
* result of redirects, path MTU changes, etc.
*/
static void fib6_gc_timer_cb(struct timer_list *t);
#define FOR_WALKERS(net, w) \
list_for_each_entry(w, &(net)->ipv6.fib6_walkers, lh)
static void fib6_walker_link(struct net *net, struct fib6_walker *w)
{
write_lock_bh(&net->ipv6.fib6_walker_lock);
list_add(&w->lh, &net->ipv6.fib6_walkers);
write_unlock_bh(&net->ipv6.fib6_walker_lock);
}
static void fib6_walker_unlink(struct net *net, struct fib6_walker *w)
{
write_lock_bh(&net->ipv6.fib6_walker_lock);
list_del(&w->lh);
write_unlock_bh(&net->ipv6.fib6_walker_lock);
}
static int fib6_new_sernum(struct net *net)
{
int new, old;
do {
old = atomic_read(&net->ipv6.fib6_sernum);
new = old < INT_MAX ? old + 1 : 1;
} while (atomic_cmpxchg(&net->ipv6.fib6_sernum,
old, new) != old);
return new;
}
enum {
FIB6_NO_SERNUM_CHANGE = 0,
};
void fib6_update_sernum(struct net *net, struct fib6_info *f6i)
{
struct fib6_node *fn;
fn = rcu_dereference_protected(f6i->fib6_node,
lockdep_is_held(&f6i->fib6_table->tb6_lock));
if (fn)
fn->fn_sernum = fib6_new_sernum(net);
}
/*
* Auxiliary address test functions for the radix tree.
*
* These assume a 32bit processor (although it will work on
* 64bit processors)
*/
/*
* test bit
*/
#if defined(__LITTLE_ENDIAN)
# define BITOP_BE32_SWIZZLE (0x1F & ~7)
#else
# define BITOP_BE32_SWIZZLE 0
#endif
static __be32 addr_bit_set(const void *token, int fn_bit)
{
const __be32 *addr = token;
/*
* Here,
* 1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)
* is optimized version of
* htonl(1 << ((~fn_bit)&0x1F))
* See include/asm-generic/bitops/le.h.
*/
return (__force __be32)(1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)) &
addr[fn_bit >> 5];
}
struct fib6_info *fib6_info_alloc(gfp_t gfp_flags, bool with_fib6_nh)
{
struct fib6_info *f6i;
size_t sz = sizeof(*f6i);
if (with_fib6_nh)
sz += sizeof(struct fib6_nh);
f6i = kzalloc(sz, gfp_flags);
if (!f6i)
return NULL;
/* fib6_siblings is a union with nh_list, so this initializes both */
INIT_LIST_HEAD(&f6i->fib6_siblings);
refcount_set(&f6i->fib6_ref, 1);
return f6i;
}
void fib6_info_destroy_rcu(struct rcu_head *head)
{
struct fib6_info *f6i = container_of(head, struct fib6_info, rcu);
WARN_ON(f6i->fib6_node);
if (f6i->nh)
nexthop_put(f6i->nh);
else
fib6_nh_release(f6i->fib6_nh);
ip_fib_metrics_put(f6i->fib6_metrics);
kfree(f6i);
}
EXPORT_SYMBOL_GPL(fib6_info_destroy_rcu);
static struct fib6_node *node_alloc(struct net *net)
{
struct fib6_node *fn;
fn = kmem_cache_zalloc(fib6_node_kmem, GFP_ATOMIC);
if (fn)
net->ipv6.rt6_stats->fib_nodes++;
return fn;
}
static void node_free_immediate(struct net *net, struct fib6_node *fn)
{
kmem_cache_free(fib6_node_kmem, fn);
net->ipv6.rt6_stats->fib_nodes--;
}
static void node_free_rcu(struct rcu_head *head)
{
struct fib6_node *fn = container_of(head, struct fib6_node, rcu);
kmem_cache_free(fib6_node_kmem, fn);
}
static void node_free(struct net *net, struct fib6_node *fn)
{
call_rcu(&fn->rcu, node_free_rcu);
net->ipv6.rt6_stats->fib_nodes--;
}
static void fib6_free_table(struct fib6_table *table)
{
inetpeer_invalidate_tree(&table->tb6_peers);
kfree(table);
}
static void fib6_link_table(struct net *net, struct fib6_table *tb)
{
unsigned int h;
/*
* Initialize table lock at a single place to give lockdep a key,
* tables aren't visible prior to being linked to the list.
*/
spin_lock_init(&tb->tb6_lock);
h = tb->tb6_id & (FIB6_TABLE_HASHSZ - 1);
/*
* No protection necessary, this is the only list mutatation
* operation, tables never disappear once they exist.
*/
hlist_add_head_rcu(&tb->tb6_hlist, &net->ipv6.fib_table_hash[h]);
}
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static struct fib6_table *fib6_alloc_table(struct net *net, u32 id)
{
struct fib6_table *table;
table = kzalloc(sizeof(*table), GFP_ATOMIC);
if (table) {
table->tb6_id = id;
rcu_assign_pointer(table->tb6_root.leaf,
net->ipv6.fib6_null_entry);
table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&table->tb6_peers);
}
return table;
}
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
struct fib6_table *tb;
if (id == 0)
id = RT6_TABLE_MAIN;
tb = fib6_get_table(net, id);
if (tb)
return tb;
tb = fib6_alloc_table(net, id);
if (tb)
fib6_link_table(net, tb);
return tb;
}
EXPORT_SYMBOL_GPL(fib6_new_table);
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
struct fib6_table *tb;
struct hlist_head *head;
unsigned int h;
if (id == 0)
id = RT6_TABLE_MAIN;
h = id & (FIB6_TABLE_HASHSZ - 1);
rcu_read_lock();
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
if (tb->tb6_id == id) {
rcu_read_unlock();
return tb;
}
}
rcu_read_unlock();
return NULL;
}
EXPORT_SYMBOL_GPL(fib6_get_table);
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
fib6_link_table(net, net->ipv6.fib6_local_tbl);
}
#else
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
return fib6_get_table(net, id);
}
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
return net->ipv6.fib6_main_tbl;
}
struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
const struct sk_buff *skb,
int flags, pol_lookup_t lookup)
{
struct rt6_info *rt;
rt = lookup(net, net->ipv6.fib6_main_tbl, fl6, skb, flags);
if (rt->dst.error == -EAGAIN) {
ip6_rt_put_flags(rt, flags);
rt = net->ipv6.ip6_null_entry;
if (!(flags | RT6_LOOKUP_F_DST_NOREF))
dst_hold(&rt->dst);
}
return &rt->dst;
}
/* called with rcu lock held; no reference taken on fib6_info */
int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6,
struct fib6_result *res, int flags)
{
return fib6_table_lookup(net, net->ipv6.fib6_main_tbl, oif, fl6,
res, flags);
}
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
}
#endif
unsigned int fib6_tables_seq_read(struct net *net)
{
unsigned int h, fib_seq = 0;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[h];
struct fib6_table *tb;
hlist_for_each_entry_rcu(tb, head, tb6_hlist)
fib_seq += tb->fib_seq;
}
rcu_read_unlock();
return fib_seq;
}
static int call_fib6_entry_notifier(struct notifier_block *nb, struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt)
{
struct fib6_entry_notifier_info info = {
.rt = rt,
};
return call_fib6_notifier(nb, net, event_type, &info.info);
}
int call_fib6_entry_notifiers(struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, event_type, &info.info);
}
int call_fib6_multipath_entry_notifiers(struct net *net,
enum fib_event_type event_type,
struct fib6_info *rt,
unsigned int nsiblings,
struct netlink_ext_ack *extack)
{
struct fib6_entry_notifier_info info = {
.info.extack = extack,
.rt = rt,
.nsiblings = nsiblings,
};
rt->fib6_table->fib_seq++;
return call_fib6_notifiers(net, event_type, &info.info);
}
struct fib6_dump_arg {
struct net *net;
struct notifier_block *nb;
};
static void fib6_rt_dump(struct fib6_info *rt, struct fib6_dump_arg *arg)
{
if (rt == arg->net->ipv6.fib6_null_entry)
return;
call_fib6_entry_notifier(arg->nb, arg->net, FIB_EVENT_ENTRY_ADD, rt);
}
static int fib6_node_dump(struct fib6_walker *w)
{
struct fib6_info *rt;
for_each_fib6_walker_rt(w)
fib6_rt_dump(rt, w->args);
w->leaf = NULL;
return 0;
}
static void fib6_table_dump(struct net *net, struct fib6_table *tb,
struct fib6_walker *w)
{
w->root = &tb->tb6_root;
spin_lock_bh(&tb->tb6_lock);
fib6_walk(net, w);
spin_unlock_bh(&tb->tb6_lock);
}
/* Called with rcu_read_lock() */
int fib6_tables_dump(struct net *net, struct notifier_block *nb)
{
struct fib6_dump_arg arg;
struct fib6_walker *w;
unsigned int h;
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_node_dump;
arg.net = net;
arg.nb = nb;
w->args = &arg;
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[h];
struct fib6_table *tb;
hlist_for_each_entry_rcu(tb, head, tb6_hlist)
fib6_table_dump(net, tb, w);
}
kfree(w);
return 0;
}
static int fib6_dump_node(struct fib6_walker *w)
{
int res;
struct fib6_info *rt;
for_each_fib6_walker_rt(w) {
res = rt6_dump_route(rt, w->args, w->skip_in_node);
if (res >= 0) {
/* Frame is full, suspend walking */
w->leaf = rt;
/* We'll restart from this node, so if some routes were
* already dumped, skip them next time.
*/
w->skip_in_node += res;
return 1;
}
w->skip_in_node = 0;
/* Multipath routes are dumped in one route with the
* RTA_MULTIPATH attribute. Jump 'rt' to point to the
* last sibling of this route (no need to dump the
* sibling routes again)
*/
if (rt->fib6_nsiblings)
rt = list_last_entry(&rt->fib6_siblings,
struct fib6_info,
fib6_siblings);
}
w->leaf = NULL;
return 0;
}
static void fib6_dump_end(struct netlink_callback *cb)
{
struct net *net = sock_net(cb->skb->sk);
struct fib6_walker *w = (void *)cb->args[2];
if (w) {
if (cb->args[4]) {
cb->args[4] = 0;
fib6_walker_unlink(net, w);
}
cb->args[2] = 0;
kfree(w);
}
cb->done = (void *)cb->args[3];
cb->args[1] = 3;
}
static int fib6_dump_done(struct netlink_callback *cb)
{
fib6_dump_end(cb);
return cb->done ? cb->done(cb) : 0;
}
static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct fib6_walker *w;
int res;
w = (void *)cb->args[2];
w->root = &table->tb6_root;
if (cb->args[4] == 0) {
w->count = 0;
w->skip = 0;
w->skip_in_node = 0;
spin_lock_bh(&table->tb6_lock);
res = fib6_walk(net, w);
spin_unlock_bh(&table->tb6_lock);
if (res > 0) {
cb->args[4] = 1;
cb->args[5] = w->root->fn_sernum;
}
} else {
if (cb->args[5] != w->root->fn_sernum) {
/* Begin at the root if the tree changed */
cb->args[5] = w->root->fn_sernum;
w->state = FWS_INIT;
w->node = w->root;
w->skip = w->count;
w->skip_in_node = 0;
} else
w->skip = 0;
spin_lock_bh(&table->tb6_lock);
res = fib6_walk_continue(w);
spin_unlock_bh(&table->tb6_lock);
if (res <= 0) {
fib6_walker_unlink(net, w);
cb->args[4] = 0;
}
}
return res;
}
static int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
{
struct rt6_rtnl_dump_arg arg = { .filter.dump_exceptions = true,
.filter.dump_routes = true };
const struct nlmsghdr *nlh = cb->nlh;
struct net *net = sock_net(skb->sk);
unsigned int h, s_h;
unsigned int e = 0, s_e;
struct fib6_walker *w;
struct fib6_table *tb;
struct hlist_head *head;
int res = 0;
if (cb->strict_check) {
int err;
err = ip_valid_fib_dump_req(net, nlh, &arg.filter, cb);
if (err < 0)
return err;
} else if (nlmsg_len(nlh) >= sizeof(struct rtmsg)) {
struct rtmsg *rtm = nlmsg_data(nlh);
if (rtm->rtm_flags & RTM_F_PREFIX)
arg.filter.flags = RTM_F_PREFIX;
}
w = (void *)cb->args[2];
if (!w) {
/* New dump:
*
* 1. hook callback destructor.
*/
cb->args[3] = (long)cb->done;
cb->done = fib6_dump_done;
/*
* 2. allocate and initialize walker.
*/
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_dump_node;
cb->args[2] = (long)w;
}
arg.skb = skb;
arg.cb = cb;
arg.net = net;
w->args = &arg;
if (arg.filter.table_id) {
tb = fib6_get_table(net, arg.filter.table_id);
if (!tb) {
if (arg.filter.dump_all_families)
goto out;
NL_SET_ERR_MSG_MOD(cb->extack, "FIB table does not exist");
return -ENOENT;
}
if (!cb->args[0]) {
res = fib6_dump_table(tb, skb, cb);
if (!res)
cb->args[0] = 1;
}
goto out;
}
s_h = cb->args[0];
s_e = cb->args[1];
rcu_read_lock();
for (h = s_h; h < FIB6_TABLE_HASHSZ; h++, s_e = 0) {
e = 0;
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
if (e < s_e)
goto next;
res = fib6_dump_table(tb, skb, cb);
if (res != 0)
goto out_unlock;
next:
e++;
}
}
out_unlock:
rcu_read_unlock();
cb->args[1] = e;
cb->args[0] = h;
out:
res = res < 0 ? res : skb->len;
if (res <= 0)
fib6_dump_end(cb);
return res;
}
void fib6_metric_set(struct fib6_info *f6i, int metric, u32 val)
{
if (!f6i)
return;
if (f6i->fib6_metrics == &dst_default_metrics) {
struct dst_metrics *p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (!p)
return;
refcount_set(&p->refcnt, 1);
f6i->fib6_metrics = p;
}
f6i->fib6_metrics->metrics[metric - 1] = val;
}
/*
* Routing Table
*
* return the appropriate node for a routing tree "add" operation
* by either creating and inserting or by returning an existing
* node.
*/
static struct fib6_node *fib6_add_1(struct net *net,
struct fib6_table *table,
struct fib6_node *root,
struct in6_addr *addr, int plen,
int offset, int allow_create,
int replace_required,
struct netlink_ext_ack *extack)
{
struct fib6_node *fn, *in, *ln;
struct fib6_node *pn = NULL;
struct rt6key *key;
int bit;
__be32 dir = 0;
RT6_TRACE("fib6_add_1\n");
/* insert node in tree */
fn = root;
do {
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
key = (struct rt6key *)((u8 *)leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit)) {
if (!allow_create) {
if (replace_required) {
NL_SET_ERR_MSG(extack,
"Can not replace route - no match found");
pr_warn("Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("NLM_F_CREATE should be set when creating new route\n");
}
goto insert_above;
}
/*
* Exact match ?
*/
if (plen == fn->fn_bit) {
/* clean up an intermediate node */
if (!(fn->fn_flags & RTN_RTINFO)) {
RCU_INIT_POINTER(fn->leaf, NULL);
fib6_info_release(leaf);
/* remove null_entry in the root node */
} else if (fn->fn_flags & RTN_TL_ROOT &&
rcu_access_pointer(fn->leaf) ==
net->ipv6.fib6_null_entry) {
RCU_INIT_POINTER(fn->leaf, NULL);
}
return fn;
}
/*
* We have more bits to go
*/
/* Try to walk down on tree. */
dir = addr_bit_set(addr, fn->fn_bit);
pn = fn;
fn = dir ?
rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock)) :
rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
} while (fn);
if (!allow_create) {
/* We should not create new node because
* NLM_F_REPLACE was specified without NLM_F_CREATE
* I assume it is safe to require NLM_F_CREATE when
* REPLACE flag is used! Later we may want to remove the
* check for replace_required, because according
* to netlink specification, NLM_F_CREATE
* MUST be specified if new route is created.
* That would keep IPv6 consistent with IPv4
*/
if (replace_required) {
NL_SET_ERR_MSG(extack,
"Can not replace route - no match found");
pr_warn("Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("NLM_F_CREATE should be set when creating new route\n");
}
/*
* We walked to the bottom of tree.
* Create new leaf node without children.
*/
ln = node_alloc(net);
if (!ln)
return ERR_PTR(-ENOMEM);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, pn);
if (dir)
rcu_assign_pointer(pn->right, ln);
else
rcu_assign_pointer(pn->left, ln);
return ln;
insert_above:
/*
* split since we don't have a common prefix anymore or
* we have a less significant route.
* we've to insert an intermediate node on the list
* this new node will point to the one we need to create
* and the current
*/
pn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
/* find 1st bit in difference between the 2 addrs.
See comment in __ipv6_addr_diff: bit may be an invalid value,
but if it is >= plen, the value is ignored in any case.
*/
bit = __ipv6_addr_diff(addr, &key->addr, sizeof(*addr));
/*
* (intermediate)[in]
* / \
* (new leaf node)[ln] (old node)[fn]
*/
if (plen > bit) {
in = node_alloc(net);
ln = node_alloc(net);
if (!in || !ln) {
if (in)
node_free_immediate(net, in);
if (ln)
node_free_immediate(net, ln);
return ERR_PTR(-ENOMEM);
}
/*
* new intermediate node.
* RTN_RTINFO will
* be off since that an address that chooses one of
* the branches would not match less specific routes
* in the other branch
*/
in->fn_bit = bit;
RCU_INIT_POINTER(in->parent, pn);
in->leaf = fn->leaf;
fib6_info_hold(rcu_dereference_protected(in->leaf,
lockdep_is_held(&table->tb6_lock)));
/* update parent pointer */
if (dir)
rcu_assign_pointer(pn->right, in);
else
rcu_assign_pointer(pn->left, in);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, in);
rcu_assign_pointer(fn->parent, in);
if (addr_bit_set(addr, bit)) {
rcu_assign_pointer(in->right, ln);
rcu_assign_pointer(in->left, fn);
} else {
rcu_assign_pointer(in->left, ln);
rcu_assign_pointer(in->right, fn);
}
} else { /* plen <= bit */
/*
* (new leaf node)[ln]
* / \
* (old node)[fn] NULL
*/
ln = node_alloc(net);
if (!ln)
return ERR_PTR(-ENOMEM);
ln->fn_bit = plen;
RCU_INIT_POINTER(ln->parent, pn);
if (addr_bit_set(&key->addr, plen))
RCU_INIT_POINTER(ln->right, fn);
else
RCU_INIT_POINTER(ln->left, fn);
rcu_assign_pointer(fn->parent, ln);
if (dir)
rcu_assign_pointer(pn->right, ln);
else
rcu_assign_pointer(pn->left, ln);
}
return ln;
}
static void __fib6_drop_pcpu_from(struct fib6_nh *fib6_nh,
const struct fib6_info *match,
const struct fib6_table *table)
{
int cpu;
if (!fib6_nh->rt6i_pcpu)
return;
/* release the reference to this fib entry from
* all of its cached pcpu routes
*/
for_each_possible_cpu(cpu) {
struct rt6_info **ppcpu_rt;
struct rt6_info *pcpu_rt;
ppcpu_rt = per_cpu_ptr(fib6_nh->rt6i_pcpu, cpu);
pcpu_rt = *ppcpu_rt;
/* only dropping the 'from' reference if the cached route
* is using 'match'. The cached pcpu_rt->from only changes
* from a fib6_info to NULL (ip6_dst_destroy); it can never
* change from one fib6_info reference to another
*/
if (pcpu_rt && rcu_access_pointer(pcpu_rt->from) == match) {
struct fib6_info *from;
from = xchg((__force struct fib6_info **)&pcpu_rt->from, NULL);
fib6_info_release(from);
}
}
}
struct fib6_nh_pcpu_arg {
struct fib6_info *from;
const struct fib6_table *table;
};
static int fib6_nh_drop_pcpu_from(struct fib6_nh *nh, void *_arg)
{
struct fib6_nh_pcpu_arg *arg = _arg;
__fib6_drop_pcpu_from(nh, arg->from, arg->table);
return 0;
}
static void fib6_drop_pcpu_from(struct fib6_info *f6i,
const struct fib6_table *table)
{
/* Make sure rt6_make_pcpu_route() wont add other percpu routes
* while we are cleaning them here.
*/
f6i->fib6_destroying = 1;
mb(); /* paired with the cmpxchg() in rt6_make_pcpu_route() */
if (f6i->nh) {
struct fib6_nh_pcpu_arg arg = {
.from = f6i,
.table = table
};
nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_drop_pcpu_from,
&arg);
} else {
struct fib6_nh *fib6_nh;
fib6_nh = f6i->fib6_nh;
__fib6_drop_pcpu_from(fib6_nh, f6i, table);
}
}
static void fib6_purge_rt(struct fib6_info *rt, struct fib6_node *fn,
struct net *net)
{
struct fib6_table *table = rt->fib6_table;
fib6_drop_pcpu_from(rt, table);
if (rt->nh && !list_empty(&rt->nh_list))
list_del_init(&rt->nh_list);
if (refcount_read(&rt->fib6_ref) != 1) {
/* This route is used as dummy address holder in some split
* nodes. It is not leaked, but it still holds other resources,
* which must be released in time. So, scan ascendant nodes
* and replace dummy references to this route with references
* to still alive ones.
*/
while (fn) {
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *new_leaf;
if (!(fn->fn_flags & RTN_RTINFO) && leaf == rt) {
new_leaf = fib6_find_prefix(net, table, fn);
fib6_info_hold(new_leaf);
rcu_assign_pointer(fn->leaf, new_leaf);
fib6_info_release(rt);
}
fn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
}
}
}
/*
* Insert routing information in a node.
*/
static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
struct nl_info *info,
struct netlink_ext_ack *extack)
{
struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&rt->fib6_table->tb6_lock));
struct fib6_info *iter = NULL;
struct fib6_info __rcu **ins;
struct fib6_info __rcu **fallback_ins = NULL;
int replace = (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_REPLACE));
int add = (!info->nlh ||
(info->nlh->nlmsg_flags & NLM_F_CREATE));
int found = 0;
bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
u16 nlflags = NLM_F_EXCL;
int err;
if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_APPEND))
nlflags |= NLM_F_APPEND;
ins = &fn->leaf;
for (iter = leaf; iter;
iter = rcu_dereference_protected(iter->fib6_next,
lockdep_is_held(&rt->fib6_table->tb6_lock))) {
/*
* Search for duplicates
*/
if (iter->fib6_metric == rt->fib6_metric) {
/*
* Same priority level
*/
if (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_EXCL))
return -EEXIST;
nlflags &= ~NLM_F_EXCL;
if (replace) {
if (rt_can_ecmp == rt6_qualify_for_ecmp(iter)) {
found++;
break;
}
if (rt_can_ecmp)
fallback_ins = fallback_ins ?: ins;
goto next_iter;
}
if (rt6_duplicate_nexthop(iter, rt)) {
if (rt->fib6_nsiblings)
rt->fib6_nsiblings = 0;
if (!(iter->fib6_flags & RTF_EXPIRES))
return -EEXIST;
if (!(rt->fib6_flags & RTF_EXPIRES))
fib6_clean_expires(iter);
else
fib6_set_expires(iter, rt->expires);
if (rt->fib6_pmtu)
fib6_metric_set(iter, RTAX_MTU,
rt->fib6_pmtu);
return -EEXIST;
}
/* If we have the same destination and the same metric,
* but not the same gateway, then the route we try to
* add is sibling to this route, increment our counter
* of siblings, and later we will add our route to the
* list.
* Only static routes (which don't have flag
* RTF_EXPIRES) are used for ECMPv6.
*
* To avoid long list, we only had siblings if the
* route have a gateway.
*/
if (rt_can_ecmp &&
rt6_qualify_for_ecmp(iter))
rt->fib6_nsiblings++;
}
if (iter->fib6_metric > rt->fib6_metric)
break;
next_iter:
ins = &iter->fib6_next;
}
if (fallback_ins && !found) {
/* No ECMP-able route found, replace first non-ECMP one */
ins = fallback_ins;
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
found++;
}
/* Reset round-robin state, if necessary */
if (ins == &fn->leaf)
fn->rr_ptr = NULL;
/* Link this route to others same route. */
if (rt->fib6_nsiblings) {
unsigned int fib6_nsiblings;
struct fib6_info *sibling, *temp_sibling;
/* Find the first route that have the same metric */
sibling = leaf;
while (sibling) {
if (sibling->fib6_metric == rt->fib6_metric &&
rt6_qualify_for_ecmp(sibling)) {
list_add_tail(&rt->fib6_siblings,
&sibling->fib6_siblings);
break;
}
sibling = rcu_dereference_protected(sibling->fib6_next,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
/* For each sibling in the list, increment the counter of
* siblings. BUG() if counters does not match, list of siblings
* is broken!
*/
fib6_nsiblings = 0;
list_for_each_entry_safe(sibling, temp_sibling,
&rt->fib6_siblings, fib6_siblings) {
sibling->fib6_nsiblings++;
BUG_ON(sibling->fib6_nsiblings != rt->fib6_nsiblings);
fib6_nsiblings++;
}
BUG_ON(fib6_nsiblings != rt->fib6_nsiblings);
rt6_multipath_rebalance(temp_sibling);
}
/*
* insert node
*/
if (!replace) {
if (!add)
pr_warn("NLM_F_CREATE should be set when creating new route\n");
add:
nlflags |= NLM_F_CREATE;
if (!info->skip_notify_kernel) {
err = call_fib6_entry_notifiers(info->nl_net,
FIB_EVENT_ENTRY_ADD,
rt, extack);
if (err) {
struct fib6_info *sibling, *next_sibling;
/* If the route has siblings, then it first
* needs to be unlinked from them.
*/
if (!rt->fib6_nsiblings)
return err;
list_for_each_entry_safe(sibling, next_sibling,
&rt->fib6_siblings,
fib6_siblings)
sibling->fib6_nsiblings--;
rt->fib6_nsiblings = 0;
list_del_init(&rt->fib6_siblings);
rt6_multipath_rebalance(next_sibling);
return err;
}
}
rcu_assign_pointer(rt->fib6_next, iter);
fib6_info_hold(rt);
rcu_assign_pointer(rt->fib6_node, fn);
rcu_assign_pointer(*ins, rt);
if (!info->skip_notify)
inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
} else {
int nsiblings;
if (!found) {
if (add)
goto add;
pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
return -ENOENT;
}
if (!info->skip_notify_kernel) {
err = call_fib6_entry_notifiers(info->nl_net,
FIB_EVENT_ENTRY_REPLACE,
rt, extack);
if (err)
return err;
}
fib6_info_hold(rt);
rcu_assign_pointer(rt->fib6_node, fn);
rt->fib6_next = iter->fib6_next;
rcu_assign_pointer(*ins, rt);
if (!info->skip_notify)
inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE);
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
nsiblings = iter->fib6_nsiblings;
iter->fib6_node = NULL;
fib6_purge_rt(iter, fn, info->nl_net);
if (rcu_access_pointer(fn->rr_ptr) == iter)
fn->rr_ptr = NULL;
fib6_info_release(iter);
if (nsiblings) {
/* Replacing an ECMP route, remove all siblings */
ins = &rt->fib6_next;
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
while (iter) {
if (iter->fib6_metric > rt->fib6_metric)
break;
if (rt6_qualify_for_ecmp(iter)) {
*ins = iter->fib6_next;
iter->fib6_node = NULL;
fib6_purge_rt(iter, fn, info->nl_net);
if (rcu_access_pointer(fn->rr_ptr) == iter)
fn->rr_ptr = NULL;
fib6_info_release(iter);
nsiblings--;
info->nl_net->ipv6.rt6_stats->fib_rt_entries--;
} else {
ins = &iter->fib6_next;
}
iter = rcu_dereference_protected(*ins,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
WARN_ON(nsiblings != 0);
}
}
return 0;
}
static void fib6_start_gc(struct net *net, struct fib6_info *rt)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer) &&
(rt->fib6_flags & RTF_EXPIRES))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
void fib6_force_start_gc(struct net *net)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
static void __fib6_update_sernum_upto_root(struct fib6_info *rt,
int sernum)
{
struct fib6_node *fn = rcu_dereference_protected(rt->fib6_node,
lockdep_is_held(&rt->fib6_table->tb6_lock));
/* paired with smp_rmb() in rt6_get_cookie_safe() */
smp_wmb();
while (fn) {
fn->fn_sernum = sernum;
fn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&rt->fib6_table->tb6_lock));
}
}
void fib6_update_sernum_upto_root(struct net *net, struct fib6_info *rt)
{
__fib6_update_sernum_upto_root(rt, fib6_new_sernum(net));
}
/* allow ipv4 to update sernum via ipv6_stub */
void fib6_update_sernum_stub(struct net *net, struct fib6_info *f6i)
{
spin_lock_bh(&f6i->fib6_table->tb6_lock);
fib6_update_sernum_upto_root(net, f6i);
spin_unlock_bh(&f6i->fib6_table->tb6_lock);
}
/*
* Add routing information to the routing tree.
* <destination addr>/<source addr>
* with source addr info in sub-trees
* Need to own table->tb6_lock
*/
int fib6_add(struct fib6_node *root, struct fib6_info *rt,
struct nl_info *info, struct netlink_ext_ack *extack)
{
struct fib6_table *table = rt->fib6_table;
struct fib6_node *fn, *pn = NULL;
int err = -ENOMEM;
int allow_create = 1;
int replace_required = 0;
int sernum = fib6_new_sernum(info->nl_net);
if (info->nlh) {
if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
allow_create = 0;
if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
replace_required = 1;
}
if (!allow_create && !replace_required)
pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
fn = fib6_add_1(info->nl_net, table, root,
&rt->fib6_dst.addr, rt->fib6_dst.plen,
offsetof(struct fib6_info, fib6_dst), allow_create,
replace_required, extack);
if (IS_ERR(fn)) {
err = PTR_ERR(fn);
fn = NULL;
goto out;
}
pn = fn;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->fib6_src.plen) {
struct fib6_node *sn;
if (!rcu_access_pointer(fn->subtree)) {
struct fib6_node *sfn;
/*
* Create subtree.
*
* fn[main tree]
* |
* sfn[subtree root]
* \
* sn[new leaf node]
*/
/* Create subtree root node */
sfn = node_alloc(info->nl_net);
if (!sfn)
goto failure;
fib6_info_hold(info->nl_net->ipv6.fib6_null_entry);
rcu_assign_pointer(sfn->leaf,
info->nl_net->ipv6.fib6_null_entry);
sfn->fn_flags = RTN_ROOT;
/* Now add the first leaf node to new subtree */
sn = fib6_add_1(info->nl_net, table, sfn,
&rt->fib6_src.addr, rt->fib6_src.plen,
offsetof(struct fib6_info, fib6_src),
allow_create, replace_required, extack);
if (IS_ERR(sn)) {
/* If it is failed, discard just allocated
root, and then (in failure) stale node
in main tree.
*/
node_free_immediate(info->nl_net, sfn);
err = PTR_ERR(sn);
goto failure;
}
/* Now link new subtree to main tree */
rcu_assign_pointer(sfn->parent, fn);
rcu_assign_pointer(fn->subtree, sfn);
} else {
sn = fib6_add_1(info->nl_net, table, FIB6_SUBTREE(fn),
&rt->fib6_src.addr, rt->fib6_src.plen,
offsetof(struct fib6_info, fib6_src),
allow_create, replace_required, extack);
if (IS_ERR(sn)) {
err = PTR_ERR(sn);
goto failure;
}
}
if (!rcu_access_pointer(fn->leaf)) {
if (fn->fn_flags & RTN_TL_ROOT) {
/* put back null_entry for root node */
rcu_assign_pointer(fn->leaf,
info->nl_net->ipv6.fib6_null_entry);
} else {
fib6_info_hold(rt);
rcu_assign_pointer(fn->leaf, rt);
}
}
fn = sn;
}
#endif
err = fib6_add_rt2node(fn, rt, info, extack);
if (!err) {
if (rt->nh)
list_add(&rt->nh_list, &rt->nh->f6i_list);
__fib6_update_sernum_upto_root(rt, sernum);
fib6_start_gc(info->nl_net, rt);
}
out:
if (err) {
#ifdef CONFIG_IPV6_SUBTREES
/*
* If fib6_add_1 has cleared the old leaf pointer in the
* super-tree leaf node we have to find a new one for it.
*/
if (pn != fn) {
struct fib6_info *pn_leaf =
rcu_dereference_protected(pn->leaf,
lockdep_is_held(&table->tb6_lock));
if (pn_leaf == rt) {
pn_leaf = NULL;
RCU_INIT_POINTER(pn->leaf, NULL);
fib6_info_release(rt);
}
if (!pn_leaf && !(pn->fn_flags & RTN_RTINFO)) {
pn_leaf = fib6_find_prefix(info->nl_net, table,
pn);
#if RT6_DEBUG >= 2
if (!pn_leaf) {
WARN_ON(!pn_leaf);
pn_leaf =
info->nl_net->ipv6.fib6_null_entry;
}
#endif
fib6_info_hold(pn_leaf);
rcu_assign_pointer(pn->leaf, pn_leaf);
}
}
#endif
goto failure;
}
return err;
failure:
/* fn->leaf could be NULL and fib6_repair_tree() needs to be called if:
* 1. fn is an intermediate node and we failed to add the new
* route to it in both subtree creation failure and fib6_add_rt2node()
* failure case.
* 2. fn is the root node in the table and we fail to add the first
* default route to it.
*/
if (fn &&
(!(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)) ||
(fn->fn_flags & RTN_TL_ROOT &&
!rcu_access_pointer(fn->leaf))))
fib6_repair_tree(info->nl_net, table, fn);
return err;
}
/*
* Routing tree lookup
*
*/
struct lookup_args {
int offset; /* key offset on fib6_info */
const struct in6_addr *addr; /* search key */
};
static struct fib6_node *fib6_node_lookup_1(struct fib6_node *root,
struct lookup_args *args)
{
struct fib6_node *fn;
__be32 dir;
if (unlikely(args->offset == 0))
return NULL;
/*
* Descend on a tree
*/
fn = root;
for (;;) {
struct fib6_node *next;
dir = addr_bit_set(args->addr, fn->fn_bit);
next = dir ? rcu_dereference(fn->right) :
rcu_dereference(fn->left);
if (next) {
fn = next;
continue;
}
break;
}
while (fn) {
struct fib6_node *subtree = FIB6_SUBTREE(fn);
if (subtree || fn->fn_flags & RTN_RTINFO) {
struct fib6_info *leaf = rcu_dereference(fn->leaf);
struct rt6key *key;
if (!leaf)
goto backtrack;
key = (struct rt6key *) ((u8 *)leaf + args->offset);
if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
#ifdef CONFIG_IPV6_SUBTREES
if (subtree) {
struct fib6_node *sfn;
sfn = fib6_node_lookup_1(subtree,
args + 1);
if (!sfn)
goto backtrack;
fn = sfn;
}
#endif
if (fn->fn_flags & RTN_RTINFO)
return fn;
}
}
backtrack:
if (fn->fn_flags & RTN_ROOT)
break;
fn = rcu_dereference(fn->parent);
}
return NULL;
}
/* called with rcu_read_lock() held
*/
struct fib6_node *fib6_node_lookup(struct fib6_node *root,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct fib6_node *fn;
struct lookup_args args[] = {
{
.offset = offsetof(struct fib6_info, fib6_dst),
.addr = daddr,
},
#ifdef CONFIG_IPV6_SUBTREES
{
.offset = offsetof(struct fib6_info, fib6_src),
.addr = saddr,
},
#endif
{
.offset = 0, /* sentinel */
}
};
fn = fib6_node_lookup_1(root, daddr ? args : args + 1);
if (!fn || fn->fn_flags & RTN_TL_ROOT)
fn = root;
return fn;
}
/*
* Get node with specified destination prefix (and source prefix,
* if subtrees are used)
* exact_match == true means we try to find fn with exact match of
* the passed in prefix addr
* exact_match == false means we try to find fn with longest prefix
* match of the passed in prefix addr. This is useful for finding fn
* for cached route as it will be stored in the exception table under
* the node with longest prefix length.
*/
static struct fib6_node *fib6_locate_1(struct fib6_node *root,
const struct in6_addr *addr,
int plen, int offset,
bool exact_match)
{
struct fib6_node *fn, *prev = NULL;
for (fn = root; fn ; ) {
struct fib6_info *leaf = rcu_dereference(fn->leaf);
struct rt6key *key;
/* This node is being deleted */
if (!leaf) {
if (plen <= fn->fn_bit)
goto out;
else
goto next;
}
key = (struct rt6key *)((u8 *)leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
goto out;
if (plen == fn->fn_bit)
return fn;
if (fn->fn_flags & RTN_RTINFO)
prev = fn;
next:
/*
* We have more bits to go
*/
if (addr_bit_set(addr, fn->fn_bit))
fn = rcu_dereference(fn->right);
else
fn = rcu_dereference(fn->left);
}
out:
if (exact_match)
return NULL;
else
return prev;
}
struct fib6_node *fib6_locate(struct fib6_node *root,
const struct in6_addr *daddr, int dst_len,
const struct in6_addr *saddr, int src_len,
bool exact_match)
{
struct fib6_node *fn;
fn = fib6_locate_1(root, daddr, dst_len,
offsetof(struct fib6_info, fib6_dst),
exact_match);
#ifdef CONFIG_IPV6_SUBTREES
if (src_len) {
WARN_ON(saddr == NULL);
if (fn) {
struct fib6_node *subtree = FIB6_SUBTREE(fn);
if (subtree) {
fn = fib6_locate_1(subtree, saddr, src_len,
offsetof(struct fib6_info, fib6_src),
exact_match);
}
}
}
#endif
if (fn && fn->fn_flags & RTN_RTINFO)
return fn;
return NULL;
}
/*
* Deletion
*
*/
static struct fib6_info *fib6_find_prefix(struct net *net,
struct fib6_table *table,
struct fib6_node *fn)
{
struct fib6_node *child_left, *child_right;
if (fn->fn_flags & RTN_ROOT)
return net->ipv6.fib6_null_entry;
while (fn) {
child_left = rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
child_right = rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock));
if (child_left)
return rcu_dereference_protected(child_left->leaf,
lockdep_is_held(&table->tb6_lock));
if (child_right)
return rcu_dereference_protected(child_right->leaf,
lockdep_is_held(&table->tb6_lock));
fn = FIB6_SUBTREE(fn);
}
return NULL;
}
/*
* Called to trim the tree of intermediate nodes when possible. "fn"
* is the node we want to try and remove.
* Need to own table->tb6_lock
*/
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_table *table,
struct fib6_node *fn)
{
int children;
int nstate;
struct fib6_node *child;
struct fib6_walker *w;
int iter = 0;
/* Set fn->leaf to null_entry for root node. */
if (fn->fn_flags & RTN_TL_ROOT) {
rcu_assign_pointer(fn->leaf, net->ipv6.fib6_null_entry);
return fn;
}
for (;;) {
struct fib6_node *fn_r = rcu_dereference_protected(fn->right,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *fn_l = rcu_dereference_protected(fn->left,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn = rcu_dereference_protected(fn->parent,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn_r = rcu_dereference_protected(pn->right,
lockdep_is_held(&table->tb6_lock));
struct fib6_node *pn_l = rcu_dereference_protected(pn->left,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *fn_leaf = rcu_dereference_protected(fn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *pn_leaf = rcu_dereference_protected(pn->leaf,
lockdep_is_held(&table->tb6_lock));
struct fib6_info *new_fn_leaf;
RT6_TRACE("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
iter++;
WARN_ON(fn->fn_flags & RTN_RTINFO);
WARN_ON(fn->fn_flags & RTN_TL_ROOT);
WARN_ON(fn_leaf);
children = 0;
child = NULL;
if (fn_r)
child = fn_r, children |= 1;
if (fn_l)
child = fn_l, children |= 2;
if (children == 3 || FIB6_SUBTREE(fn)
#ifdef CONFIG_IPV6_SUBTREES
/* Subtree root (i.e. fn) may have one child */
|| (children && fn->fn_flags & RTN_ROOT)
#endif
) {
new_fn_leaf = fib6_find_prefix(net, table, fn);
#if RT6_DEBUG >= 2
if (!new_fn_leaf) {
WARN_ON(!new_fn_leaf);
new_fn_leaf = net->ipv6.fib6_null_entry;
}
#endif
fib6_info_hold(new_fn_leaf);
rcu_assign_pointer(fn->leaf, new_fn_leaf);
return pn;
}
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
RCU_INIT_POINTER(pn->subtree, NULL);
nstate = FWS_L;
} else {
WARN_ON(fn->fn_flags & RTN_ROOT);
#endif
if (pn_r == fn)
rcu_assign_pointer(pn->right, child);
else if (pn_l == fn)
rcu_assign_pointer(pn->left, child);
#if RT6_DEBUG >= 2
else
WARN_ON(1);
#endif
if (child)
rcu_assign_pointer(child->parent, pn);
nstate = FWS_R;
#ifdef CONFIG_IPV6_SUBTREES
}
#endif
read_lock(&net->ipv6.fib6_walker_lock);
FOR_WALKERS(net, w) {
if (!child) {
if (w->node == fn) {
RT6_TRACE("W %p adjusted by delnode 1, s=%d/%d\n", w, w->state, nstate);
w->node = pn;
w->state = nstate;
}
} else {
if (w->node == fn) {
w->node = child;
if (children&2) {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state >= FWS_R ? FWS_U : FWS_INIT;
} else {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state >= FWS_C ? FWS_U : FWS_INIT;
}
}
}
}
read_unlock(&net->ipv6.fib6_walker_lock);
node_free(net, fn);
if (pn->fn_flags & RTN_RTINFO || FIB6_SUBTREE(pn))
return pn;
RCU_INIT_POINTER(pn->leaf, NULL);
fib6_info_release(pn_leaf);
fn = pn;
}
}
static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,
struct fib6_info __rcu **rtp, struct nl_info *info)
{
struct fib6_walker *w;
struct fib6_info *rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&table->tb6_lock));
struct net *net = info->nl_net;
RT6_TRACE("fib6_del_route\n");
/* Unlink it */
*rtp = rt->fib6_next;
rt->fib6_node = NULL;
net->ipv6.rt6_stats->fib_rt_entries--;
net->ipv6.rt6_stats->fib_discarded_routes++;
/* Flush all cached dst in exception table */
rt6_flush_exceptions(rt);
/* Reset round-robin state, if necessary */
if (rcu_access_pointer(fn->rr_ptr) == rt)
fn->rr_ptr = NULL;
/* Remove this entry from other siblings */
if (rt->fib6_nsiblings) {
struct fib6_info *sibling, *next_sibling;
list_for_each_entry_safe(sibling, next_sibling,
&rt->fib6_siblings, fib6_siblings)
sibling->fib6_nsiblings--;
rt->fib6_nsiblings = 0;
list_del_init(&rt->fib6_siblings);
rt6_multipath_rebalance(next_sibling);
}
/* Adjust walkers */
read_lock(&net->ipv6.fib6_walker_lock);
FOR_WALKERS(net, w) {
if (w->state == FWS_C && w->leaf == rt) {
RT6_TRACE("walker %p adjusted by delroute\n", w);
w->leaf = rcu_dereference_protected(rt->fib6_next,
lockdep_is_held(&table->tb6_lock));
if (!w->leaf)
w->state = FWS_U;
}
}
read_unlock(&net->ipv6.fib6_walker_lock);
/* If it was last route, call fib6_repair_tree() to:
* 1. For root node, put back null_entry as how the table was created.
* 2. For other nodes, expunge its radix tree node.
*/
if (!rcu_access_pointer(fn->leaf)) {
if (!(fn->fn_flags & RTN_TL_ROOT)) {
fn->fn_flags &= ~RTN_RTINFO;
net->ipv6.rt6_stats->fib_route_nodes--;
}
fn = fib6_repair_tree(net, table, fn);
}
fib6_purge_rt(rt, fn, net);
if (!info->skip_notify_kernel)
call_fib6_entry_notifiers(net, FIB_EVENT_ENTRY_DEL, rt, NULL);
if (!info->skip_notify)
inet6_rt_notify(RTM_DELROUTE, rt, info, 0);
fib6_info_release(rt);
}
/* Need to own table->tb6_lock */
int fib6_del(struct fib6_info *rt, struct nl_info *info)
{
struct fib6_node *fn = rcu_dereference_protected(rt->fib6_node,
lockdep_is_held(&rt->fib6_table->tb6_lock));
struct fib6_table *table = rt->fib6_table;
struct net *net = info->nl_net;
struct fib6_info __rcu **rtp;
struct fib6_info __rcu **rtp_next;
if (!fn || rt == net->ipv6.fib6_null_entry)
return -ENOENT;
WARN_ON(!(fn->fn_flags & RTN_RTINFO));
/*
* Walk the leaf entries looking for ourself
*/
for (rtp = &fn->leaf; *rtp; rtp = rtp_next) {
struct fib6_info *cur = rcu_dereference_protected(*rtp,
lockdep_is_held(&table->tb6_lock));
if (rt == cur) {
fib6_del_route(table, fn, rtp, info);
return 0;
}
rtp_next = &cur->fib6_next;
}
return -ENOENT;
}
/*
* Tree traversal function.
*
* Certainly, it is not interrupt safe.
* However, it is internally reenterable wrt itself and fib6_add/fib6_del.
* It means, that we can modify tree during walking
* and use this function for garbage collection, clone pruning,
* cleaning tree when a device goes down etc. etc.
*
* It guarantees that every node will be traversed,
* and that it will be traversed only once.
*
* Callback function w->func may return:
* 0 -> continue walking.
* positive value -> walking is suspended (used by tree dumps,
* and probably by gc, if it will be split to several slices)
* negative value -> terminate walking.
*
* The function itself returns:
* 0 -> walk is complete.
* >0 -> walk is incomplete (i.e. suspended)
* <0 -> walk is terminated by an error.
*
* This function is called with tb6_lock held.
*/
static int fib6_walk_continue(struct fib6_walker *w)
{
struct fib6_node *fn, *pn, *left, *right;
/* w->root should always be table->tb6_root */
WARN_ON_ONCE(!(w->root->fn_flags & RTN_TL_ROOT));
for (;;) {
fn = w->node;
if (!fn)
return 0;
switch (w->state) {
#ifdef CONFIG_IPV6_SUBTREES
case FWS_S:
if (FIB6_SUBTREE(fn)) {
w->node = FIB6_SUBTREE(fn);
continue;
}
w->state = FWS_L;
#endif
/* fall through */
case FWS_L:
left = rcu_dereference_protected(fn->left, 1);
if (left) {
w->node = left;
w->state = FWS_INIT;
continue;
}
w->state = FWS_R;
/* fall through */
case FWS_R:
right = rcu_dereference_protected(fn->right, 1);
if (right) {
w->node = right;
w->state = FWS_INIT;
continue;
}
w->state = FWS_C;
w->leaf = rcu_dereference_protected(fn->leaf, 1);
/* fall through */
case FWS_C:
if (w->leaf && fn->fn_flags & RTN_RTINFO) {
int err;
if (w->skip) {
w->skip--;
goto skip;
}
err = w->func(w);
if (err)
return err;
w->count++;
continue;
}
skip:
w->state = FWS_U;
/* fall through */
case FWS_U:
if (fn == w->root)
return 0;
pn = rcu_dereference_protected(fn->parent, 1);
left = rcu_dereference_protected(pn->left, 1);
right = rcu_dereference_protected(pn->right, 1);
w->node = pn;
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
w->state = FWS_L;
continue;
}
#endif
if (left == fn) {
w->state = FWS_R;
continue;
}
if (right == fn) {
w->state = FWS_C;
w->leaf = rcu_dereference_protected(w->node->leaf, 1);
continue;
}
#if RT6_DEBUG >= 2
WARN_ON(1);
#endif
}
}
}
static int fib6_walk(struct net *net, struct fib6_walker *w)
{
int res;
w->state = FWS_INIT;
w->node = w->root;
fib6_walker_link(net, w);
res = fib6_walk_continue(w);
if (res <= 0)
fib6_walker_unlink(net, w);
return res;
}
static int fib6_clean_node(struct fib6_walker *w)
{
int res;
struct fib6_info *rt;
struct fib6_cleaner *c = container_of(w, struct fib6_cleaner, w);
struct nl_info info = {
.nl_net = c->net,
.skip_notify = c->skip_notify,
};
if (c->sernum != FIB6_NO_SERNUM_CHANGE &&
w->node->fn_sernum != c->sernum)
w->node->fn_sernum = c->sernum;
if (!c->func) {
WARN_ON_ONCE(c->sernum == FIB6_NO_SERNUM_CHANGE);
w->leaf = NULL;
return 0;
}
for_each_fib6_walker_rt(w) {
res = c->func(rt, c->arg);
if (res == -1) {
w->leaf = rt;
res = fib6_del(rt, &info);
if (res) {
#if RT6_DEBUG >= 2
pr_debug("%s: del failed: rt=%p@%p err=%d\n",
__func__, rt,
rcu_access_pointer(rt->fib6_node),
res);
#endif
continue;
}
return 0;
} else if (res == -2) {
if (WARN_ON(!rt->fib6_nsiblings))
continue;
rt = list_last_entry(&rt->fib6_siblings,
struct fib6_info, fib6_siblings);
continue;
}
WARN_ON(res != 0);
}
w->leaf = rt;
return 0;
}
/*
* Convenient frontend to tree walker.
*
* func is called on each route.
* It may return -2 -> skip multipath route.
* -1 -> delete this route.
* 0 -> continue walking
*/
static void fib6_clean_tree(struct net *net, struct fib6_node *root,
int (*func)(struct fib6_info *, void *arg),
int sernum, void *arg, bool skip_notify)
{
struct fib6_cleaner c;
c.w.root = root;
c.w.func = fib6_clean_node;
c.w.count = 0;
c.w.skip = 0;
c.w.skip_in_node = 0;
c.func = func;
c.sernum = sernum;
c.arg = arg;
c.net = net;
c.skip_notify = skip_notify;
fib6_walk(net, &c.w);
}
static void __fib6_clean_all(struct net *net,
int (*func)(struct fib6_info *, void *),
int sernum, void *arg, bool skip_notify)
{
struct fib6_table *table;
struct hlist_head *head;
unsigned int h;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(table, head, tb6_hlist) {
spin_lock_bh(&table->tb6_lock);
fib6_clean_tree(net, &table->tb6_root,
func, sernum, arg, skip_notify);
spin_unlock_bh(&table->tb6_lock);
}
}
rcu_read_unlock();
}
void fib6_clean_all(struct net *net, int (*func)(struct fib6_info *, void *),
void *arg)
{
__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, false);
}
void fib6_clean_all_skip_notify(struct net *net,
int (*func)(struct fib6_info *, void *),
void *arg)
{
__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, true);
}
static void fib6_flush_trees(struct net *net)
{
int new_sernum = fib6_new_sernum(net);
__fib6_clean_all(net, NULL, new_sernum, NULL, false);
}
/*
* Garbage collection
*/
static int fib6_age(struct fib6_info *rt, void *arg)
{
struct fib6_gc_args *gc_args = arg;
unsigned long now = jiffies;
/*
* check addrconf expiration here.
* Routes are expired even if they are in use.
*/
if (rt->fib6_flags & RTF_EXPIRES && rt->expires) {
if (time_after(now, rt->expires)) {
RT6_TRACE("expiring %p\n", rt);
return -1;
}
gc_args->more++;
}
/* Also age clones in the exception table.
* Note, that clones are aged out
* only if they are not in use now.
*/
rt6_age_exceptions(rt, gc_args, now);
return 0;
}
void fib6_run_gc(unsigned long expires, struct net *net, bool force)
{
struct fib6_gc_args gc_args;
unsigned long now;
if (force) {
spin_lock_bh(&net->ipv6.fib6_gc_lock);
} else if (!spin_trylock_bh(&net->ipv6.fib6_gc_lock)) {
mod_timer(&net->ipv6.ip6_fib_timer, jiffies + HZ);
return;
}
gc_args.timeout = expires ? (int)expires :
net->ipv6.sysctl.ip6_rt_gc_interval;
gc_args.more = 0;
fib6_clean_all(net, fib6_age, &gc_args);
now = jiffies;
net->ipv6.ip6_rt_last_gc = now;
if (gc_args.more)
mod_timer(&net->ipv6.ip6_fib_timer,
round_jiffies(now
+ net->ipv6.sysctl.ip6_rt_gc_interval));
else
del_timer(&net->ipv6.ip6_fib_timer);
spin_unlock_bh(&net->ipv6.fib6_gc_lock);
}
static void fib6_gc_timer_cb(struct timer_list *t)
{
struct net *arg = from_timer(arg, t, ipv6.ip6_fib_timer);
fib6_run_gc(0, arg, true);
}
static int __net_init fib6_net_init(struct net *net)
{
size_t size = sizeof(struct hlist_head) * FIB6_TABLE_HASHSZ;
int err;
err = fib6_notifier_init(net);
if (err)
return err;
spin_lock_init(&net->ipv6.fib6_gc_lock);
rwlock_init(&net->ipv6.fib6_walker_lock);
INIT_LIST_HEAD(&net->ipv6.fib6_walkers);
timer_setup(&net->ipv6.ip6_fib_timer, fib6_gc_timer_cb, 0);
net->ipv6.rt6_stats = kzalloc(sizeof(*net->ipv6.rt6_stats), GFP_KERNEL);
if (!net->ipv6.rt6_stats)
goto out_timer;
/* Avoid false sharing : Use at least a full cache line */
size = max_t(size_t, size, L1_CACHE_BYTES);
net->ipv6.fib_table_hash = kzalloc(size, GFP_KERNEL);
if (!net->ipv6.fib_table_hash)
goto out_rt6_stats;
net->ipv6.fib6_main_tbl = kzalloc(sizeof(*net->ipv6.fib6_main_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_main_tbl)
goto out_fib_table_hash;
net->ipv6.fib6_main_tbl->tb6_id = RT6_TABLE_MAIN;
rcu_assign_pointer(net->ipv6.fib6_main_tbl->tb6_root.leaf,
net->ipv6.fib6_null_entry);
net->ipv6.fib6_main_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&net->ipv6.fib6_main_tbl->tb6_peers);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.fib6_local_tbl = kzalloc(sizeof(*net->ipv6.fib6_local_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_local_tbl)
goto out_fib6_main_tbl;
net->ipv6.fib6_local_tbl->tb6_id = RT6_TABLE_LOCAL;
rcu_assign_pointer(net->ipv6.fib6_local_tbl->tb6_root.leaf,
net->ipv6.fib6_null_entry);
net->ipv6.fib6_local_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
inet_peer_base_init(&net->ipv6.fib6_local_tbl->tb6_peers);
#endif
fib6_tables_init(net);
return 0;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_fib6_main_tbl:
kfree(net->ipv6.fib6_main_tbl);
#endif
out_fib_table_hash:
kfree(net->ipv6.fib_table_hash);
out_rt6_stats:
kfree(net->ipv6.rt6_stats);
out_timer:
fib6_notifier_exit(net);
return -ENOMEM;
}
static void fib6_net_exit(struct net *net)
{
unsigned int i;
del_timer_sync(&net->ipv6.ip6_fib_timer);
for (i = 0; i < FIB6_TABLE_HASHSZ; i++) {
struct hlist_head *head = &net->ipv6.fib_table_hash[i];
struct hlist_node *tmp;
struct fib6_table *tb;
hlist_for_each_entry_safe(tb, tmp, head, tb6_hlist) {
hlist_del(&tb->tb6_hlist);
fib6_free_table(tb);
}
}
kfree(net->ipv6.fib_table_hash);
kfree(net->ipv6.rt6_stats);
fib6_notifier_exit(net);
}
static struct pernet_operations fib6_net_ops = {
.init = fib6_net_init,
.exit = fib6_net_exit,
};
int __init fib6_init(void)
{
int ret = -ENOMEM;
fib6_node_kmem = kmem_cache_create("fib6_nodes",
sizeof(struct fib6_node),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!fib6_node_kmem)
goto out;
ret = register_pernet_subsys(&fib6_net_ops);
if (ret)
goto out_kmem_cache_create;
ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETROUTE, NULL,
inet6_dump_fib, 0);
if (ret)
goto out_unregister_subsys;
__fib6_flush_trees = fib6_flush_trees;
out:
return ret;
out_unregister_subsys:
unregister_pernet_subsys(&fib6_net_ops);
out_kmem_cache_create:
kmem_cache_destroy(fib6_node_kmem);
goto out;
}
void fib6_gc_cleanup(void)
{
unregister_pernet_subsys(&fib6_net_ops);
kmem_cache_destroy(fib6_node_kmem);
}
#ifdef CONFIG_PROC_FS
static int ipv6_route_seq_show(struct seq_file *seq, void *v)
{
struct fib6_info *rt = v;
struct ipv6_route_iter *iter = seq->private;
struct fib6_nh *fib6_nh = rt->fib6_nh;
unsigned int flags = rt->fib6_flags;
const struct net_device *dev;
if (rt->nh)
fib6_nh = nexthop_fib6_nh(rt->nh);
seq_printf(seq, "%pi6 %02x ", &rt->fib6_dst.addr, rt->fib6_dst.plen);
#ifdef CONFIG_IPV6_SUBTREES
seq_printf(seq, "%pi6 %02x ", &rt->fib6_src.addr, rt->fib6_src.plen);
#else
seq_puts(seq, "00000000000000000000000000000000 00 ");
#endif
if (fib6_nh->fib_nh_gw_family) {
flags |= RTF_GATEWAY;
seq_printf(seq, "%pi6", &fib6_nh->fib_nh_gw6);
} else {
seq_puts(seq, "00000000000000000000000000000000");
}
dev = fib6_nh->fib_nh_dev;
seq_printf(seq, " %08x %08x %08x %08x %8s\n",
rt->fib6_metric, refcount_read(&rt->fib6_ref), 0,
flags, dev ? dev->name : "");
iter->w.leaf = NULL;
return 0;
}
static int ipv6_route_yield(struct fib6_walker *w)
{
struct ipv6_route_iter *iter = w->args;
if (!iter->skip)
return 1;
do {
iter->w.leaf = rcu_dereference_protected(
iter->w.leaf->fib6_next,
lockdep_is_held(&iter->tbl->tb6_lock));
iter->skip--;
if (!iter->skip && iter->w.leaf)
return 1;
} while (iter->w.leaf);
return 0;
}
static void ipv6_route_seq_setup_walk(struct ipv6_route_iter *iter,
struct net *net)
{
memset(&iter->w, 0, sizeof(iter->w));
iter->w.func = ipv6_route_yield;
iter->w.root = &iter->tbl->tb6_root;
iter->w.state = FWS_INIT;
iter->w.node = iter->w.root;
iter->w.args = iter;
iter->sernum = iter->w.root->fn_sernum;
INIT_LIST_HEAD(&iter->w.lh);
fib6_walker_link(net, &iter->w);
}
static struct fib6_table *ipv6_route_seq_next_table(struct fib6_table *tbl,
struct net *net)
{
unsigned int h;
struct hlist_node *node;
if (tbl) {
h = (tbl->tb6_id & (FIB6_TABLE_HASHSZ - 1)) + 1;
node = rcu_dereference_bh(hlist_next_rcu(&tbl->tb6_hlist));
} else {
h = 0;
node = NULL;
}
while (!node && h < FIB6_TABLE_HASHSZ) {
node = rcu_dereference_bh(
hlist_first_rcu(&net->ipv6.fib_table_hash[h++]));
}
return hlist_entry_safe(node, struct fib6_table, tb6_hlist);
}
static void ipv6_route_check_sernum(struct ipv6_route_iter *iter)
{
if (iter->sernum != iter->w.root->fn_sernum) {
iter->sernum = iter->w.root->fn_sernum;
iter->w.state = FWS_INIT;
iter->w.node = iter->w.root;
WARN_ON(iter->w.skip);
iter->w.skip = iter->w.count;
}
}
static void *ipv6_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
int r;
struct fib6_info *n;
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
if (!v)
goto iter_table;
n = rcu_dereference_bh(((struct fib6_info *)v)->fib6_next);
if (n) {
++*pos;
return n;
}
iter_table:
ipv6_route_check_sernum(iter);
spin_lock_bh(&iter->tbl->tb6_lock);
r = fib6_walk_continue(&iter->w);
spin_unlock_bh(&iter->tbl->tb6_lock);
if (r > 0) {
if (v)
++*pos;
return iter->w.leaf;
} else if (r < 0) {
fib6_walker_unlink(net, &iter->w);
return NULL;
}
fib6_walker_unlink(net, &iter->w);
iter->tbl = ipv6_route_seq_next_table(iter->tbl, net);
if (!iter->tbl)
return NULL;
ipv6_route_seq_setup_walk(iter, net);
goto iter_table;
}
static void *ipv6_route_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU_BH)
{
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
rcu_read_lock_bh();
iter->tbl = ipv6_route_seq_next_table(NULL, net);
iter->skip = *pos;
if (iter->tbl) {
ipv6_route_seq_setup_walk(iter, net);
return ipv6_route_seq_next(seq, NULL, pos);
} else {
return NULL;
}
}
static bool ipv6_route_iter_active(struct ipv6_route_iter *iter)
{
struct fib6_walker *w = &iter->w;
return w->node && !(w->state == FWS_U && w->node == w->root);
}
static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
__releases(RCU_BH)
{
struct net *net = seq_file_net(seq);
struct ipv6_route_iter *iter = seq->private;
if (ipv6_route_iter_active(iter))
fib6_walker_unlink(net, &iter->w);
rcu_read_unlock_bh();
}
const struct seq_operations ipv6_route_seq_ops = {
.start = ipv6_route_seq_start,
.next = ipv6_route_seq_next,
.stop = ipv6_route_seq_stop,
.show = ipv6_route_seq_show
};
#endif /* CONFIG_PROC_FS */
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_1368_0 |
crossvul-cpp_data_bad_1325_3 | /*
** 2003 September 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used for creating, destroying, and populating
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
*/
#include "sqliteInt.h"
#include "vdbeInt.h"
/* Forward references */
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
static void vdbeFreeOpArray(sqlite3 *, Op *, int);
/*
** Create a new virtual database engine.
*/
Vdbe *sqlite3VdbeCreate(Parse *pParse){
sqlite3 *db = pParse->db;
Vdbe *p;
p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
if( p==0 ) return 0;
memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
p->db = db;
if( db->pVdbe ){
db->pVdbe->pPrev = p;
}
p->pNext = db->pVdbe;
p->pPrev = 0;
db->pVdbe = p;
p->magic = VDBE_MAGIC_INIT;
p->pParse = pParse;
pParse->pVdbe = p;
assert( pParse->aLabel==0 );
assert( pParse->nLabel==0 );
assert( p->nOpAlloc==0 );
assert( pParse->szOpAlloc==0 );
sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
return p;
}
/*
** Return the Parse object that owns a Vdbe object.
*/
Parse *sqlite3VdbeParser(Vdbe *p){
return p->pParse;
}
/*
** Change the error string stored in Vdbe.zErrMsg
*/
void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
va_list ap;
sqlite3DbFree(p->db, p->zErrMsg);
va_start(ap, zFormat);
p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
va_end(ap);
}
/*
** Remember the SQL string for a prepared statement.
*/
void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
if( p==0 ) return;
p->prepFlags = prepFlags;
if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
p->expmask = 0;
}
assert( p->zSql==0 );
p->zSql = sqlite3DbStrNDup(p->db, z, n);
}
#ifdef SQLITE_ENABLE_NORMALIZE
/*
** Add a new element to the Vdbe->pDblStr list.
*/
void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
if( p ){
int n = sqlite3Strlen30(z);
DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
sizeof(*pStr)+n+1-sizeof(pStr->z));
if( pStr ){
pStr->pNextStr = p->pDblStr;
p->pDblStr = pStr;
memcpy(pStr->z, z, n+1);
}
}
}
#endif
#ifdef SQLITE_ENABLE_NORMALIZE
/*
** zId of length nId is a double-quoted identifier. Check to see if
** that identifier is really used as a string literal.
*/
int sqlite3VdbeUsesDoubleQuotedString(
Vdbe *pVdbe, /* The prepared statement */
const char *zId /* The double-quoted identifier, already dequoted */
){
DblquoteStr *pStr;
assert( zId!=0 );
if( pVdbe->pDblStr==0 ) return 0;
for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
if( strcmp(zId, pStr->z)==0 ) return 1;
}
return 0;
}
#endif
/*
** Swap all content between two VDBE structures.
*/
void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
Vdbe tmp, *pTmp;
char *zTmp;
assert( pA->db==pB->db );
tmp = *pA;
*pA = *pB;
*pB = tmp;
pTmp = pA->pNext;
pA->pNext = pB->pNext;
pB->pNext = pTmp;
pTmp = pA->pPrev;
pA->pPrev = pB->pPrev;
pB->pPrev = pTmp;
zTmp = pA->zSql;
pA->zSql = pB->zSql;
pB->zSql = zTmp;
#ifdef SQLITE_ENABLE_NORMALIZE
zTmp = pA->zNormSql;
pA->zNormSql = pB->zNormSql;
pB->zNormSql = zTmp;
#endif
pB->expmask = pA->expmask;
pB->prepFlags = pA->prepFlags;
memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
}
/*
** Resize the Vdbe.aOp array so that it is at least nOp elements larger
** than its current size. nOp is guaranteed to be less than or equal
** to 1024/sizeof(Op).
**
** If an out-of-memory error occurs while resizing the array, return
** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
** unchanged (this is so that any opcodes already allocated can be
** correctly deallocated along with the rest of the Vdbe).
*/
static int growOpArray(Vdbe *v, int nOp){
VdbeOp *pNew;
Parse *p = v->pParse;
/* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
** more frequent reallocs and hence provide more opportunities for
** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
** by the minimum* amount required until the size reaches 512. Normal
** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
** size of the op array or add 1KB of space, whichever is smaller. */
#ifdef SQLITE_TEST_REALLOC_STRESS
sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
: (sqlite3_int64)v->nOpAlloc+nOp);
#else
sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
: (sqlite3_int64)(1024/sizeof(Op)));
UNUSED_PARAMETER(nOp);
#endif
/* Ensure that the size of a VDBE does not grow too large */
if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
sqlite3OomFault(p->db);
return SQLITE_NOMEM;
}
assert( nOp<=(1024/sizeof(Op)) );
assert( nNew>=(v->nOpAlloc+nOp) );
pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
if( pNew ){
p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
v->nOpAlloc = p->szOpAlloc/sizeof(Op);
v->aOp = pNew;
}
return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
}
#ifdef SQLITE_DEBUG
/* This routine is just a convenient place to set a breakpoint that will
** fire after each opcode is inserted and displayed using
** "PRAGMA vdbe_addoptrace=on".
*/
static void test_addop_breakpoint(void){
static int n = 0;
n++;
}
#endif
/*
** Add a new instruction to the list of instructions current in the
** VDBE. Return the address of the new instruction.
**
** Parameters:
**
** p Pointer to the VDBE
**
** op The opcode for this instruction
**
** p1, p2, p3 Operands
**
** Use the sqlite3VdbeResolveLabel() function to fix an address and
** the sqlite3VdbeChangeP4() function to change the value of the P4
** operand.
*/
static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
assert( p->nOpAlloc<=p->nOp );
if( growOpArray(p, 1) ) return 1;
assert( p->nOpAlloc>p->nOp );
return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
}
int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
int i;
VdbeOp *pOp;
i = p->nOp;
assert( p->magic==VDBE_MAGIC_INIT );
assert( op>=0 && op<0xff );
if( p->nOpAlloc<=i ){
return growOp3(p, op, p1, p2, p3);
}
p->nOp++;
pOp = &p->aOp[i];
pOp->opcode = (u8)op;
pOp->p5 = 0;
pOp->p1 = p1;
pOp->p2 = p2;
pOp->p3 = p3;
pOp->p4.p = 0;
pOp->p4type = P4_NOTUSED;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
pOp->zComment = 0;
#endif
#ifdef SQLITE_DEBUG
if( p->db->flags & SQLITE_VdbeAddopTrace ){
sqlite3VdbePrintOp(0, i, &p->aOp[i]);
test_addop_breakpoint();
}
#endif
#ifdef VDBE_PROFILE
pOp->cycles = 0;
pOp->cnt = 0;
#endif
#ifdef SQLITE_VDBE_COVERAGE
pOp->iSrcLine = 0;
#endif
return i;
}
int sqlite3VdbeAddOp0(Vdbe *p, int op){
return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
}
int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
}
int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
}
/* Generate code for an unconditional jump to instruction iDest
*/
int sqlite3VdbeGoto(Vdbe *p, int iDest){
return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
}
/* Generate code to cause the string zStr to be loaded into
** register iDest
*/
int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
}
/*
** Generate code that initializes multiple registers to string or integer
** constants. The registers begin with iDest and increase consecutively.
** One register is initialized for each characgter in zTypes[]. For each
** "s" character in zTypes[], the register is a string if the argument is
** not NULL, or OP_Null if the value is a null pointer. For each "i" character
** in zTypes[], the register is initialized to an integer.
**
** If the input string does not end with "X" then an OP_ResultRow instruction
** is generated for the values inserted.
*/
void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
va_list ap;
int i;
char c;
va_start(ap, zTypes);
for(i=0; (c = zTypes[i])!=0; i++){
if( c=='s' ){
const char *z = va_arg(ap, const char*);
sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
}else if( c=='i' ){
sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
}else{
goto skip_op_resultrow;
}
}
sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
skip_op_resultrow:
va_end(ap);
}
/*
** Add an opcode that includes the p4 value as a pointer.
*/
int sqlite3VdbeAddOp4(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
const char *zP4, /* The P4 operand */
int p4type /* P4 operand type */
){
int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
sqlite3VdbeChangeP4(p, addr, zP4, p4type);
return addr;
}
/*
** Add an OP_Function or OP_PureFunc opcode.
**
** The eCallCtx argument is information (typically taken from Expr.op2)
** that describes the calling context of the function. 0 means a general
** function call. NC_IsCheck means called by a check constraint,
** NC_IdxExpr means called as part of an index expression. NC_PartIdx
** means in the WHERE clause of a partial index. NC_GenCol means called
** while computing a generated column value. 0 is the usual case.
*/
int sqlite3VdbeAddFunctionCall(
Parse *pParse, /* Parsing context */
int p1, /* Constant argument mask */
int p2, /* First argument register */
int p3, /* Register into which results are written */
int nArg, /* Number of argument */
const FuncDef *pFunc, /* The function to be invoked */
int eCallCtx /* Calling context */
){
Vdbe *v = pParse->pVdbe;
int nByte;
int addr;
sqlite3_context *pCtx;
assert( v );
nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
if( pCtx==0 ){
assert( pParse->db->mallocFailed );
freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
return 0;
}
pCtx->pOut = 0;
pCtx->pFunc = (FuncDef*)pFunc;
pCtx->pVdbe = 0;
pCtx->isError = 0;
pCtx->argc = nArg;
pCtx->iOp = sqlite3VdbeCurrentAddr(v);
addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
return addr;
}
/*
** Add an opcode that includes the p4 value with a P4_INT64 or
** P4_REAL type.
*/
int sqlite3VdbeAddOp4Dup8(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
const u8 *zP4, /* The P4 operand */
int p4type /* P4 operand type */
){
char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
if( p4copy ) memcpy(p4copy, zP4, 8);
return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Return the address of the current EXPLAIN QUERY PLAN baseline.
** 0 means "none".
*/
int sqlite3VdbeExplainParent(Parse *pParse){
VdbeOp *pOp;
if( pParse->addrExplain==0 ) return 0;
pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
return pOp->p2;
}
/*
** Set a debugger breakpoint on the following routine in order to
** monitor the EXPLAIN QUERY PLAN code generation.
*/
#if defined(SQLITE_DEBUG)
void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
(void)z1;
(void)z2;
}
#endif
/*
** Add a new OP_ opcode.
**
** If the bPush flag is true, then make this opcode the parent for
** subsequent Explains until sqlite3VdbeExplainPop() is called.
*/
void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
#ifndef SQLITE_DEBUG
/* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
** But omit them (for performance) during production builds */
if( pParse->explain==2 )
#endif
{
char *zMsg;
Vdbe *v;
va_list ap;
int iThis;
va_start(ap, zFmt);
zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
va_end(ap);
v = pParse->pVdbe;
iThis = v->nOp;
sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
zMsg, P4_DYNAMIC);
sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
if( bPush){
pParse->addrExplain = iThis;
}
}
}
/*
** Pop the EXPLAIN QUERY PLAN stack one level.
*/
void sqlite3VdbeExplainPop(Parse *pParse){
sqlite3ExplainBreakpoint("POP", 0);
pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
}
#endif /* SQLITE_OMIT_EXPLAIN */
/*
** Add an OP_ParseSchema opcode. This routine is broken out from
** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
** as having been used.
**
** The zWhere string must have been obtained from sqlite3_malloc().
** This routine will take ownership of the allocated memory.
*/
void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
int j;
sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
}
/*
** Add an opcode that includes the p4 value as an integer.
*/
int sqlite3VdbeAddOp4Int(
Vdbe *p, /* Add the opcode to this VM */
int op, /* The new opcode */
int p1, /* The P1 operand */
int p2, /* The P2 operand */
int p3, /* The P3 operand */
int p4 /* The P4 operand as an integer */
){
int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
if( p->db->mallocFailed==0 ){
VdbeOp *pOp = &p->aOp[addr];
pOp->p4type = P4_INT32;
pOp->p4.i = p4;
}
return addr;
}
/* Insert the end of a co-routine
*/
void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
/* Clear the temporary register cache, thereby ensuring that each
** co-routine has its own independent set of registers, because co-routines
** might expect their registers to be preserved across an OP_Yield, and
** that could cause problems if two or more co-routines are using the same
** temporary register.
*/
v->pParse->nTempReg = 0;
v->pParse->nRangeReg = 0;
}
/*
** Create a new symbolic label for an instruction that has yet to be
** coded. The symbolic label is really just a negative number. The
** label can be used as the P2 value of an operation. Later, when
** the label is resolved to a specific address, the VDBE will scan
** through its operation list and change all values of P2 which match
** the label into the resolved address.
**
** The VDBE knows that a P2 value is a label because labels are
** always negative and P2 values are suppose to be non-negative.
** Hence, a negative P2 value is a label that has yet to be resolved.
** (Later:) This is only true for opcodes that have the OPFLG_JUMP
** property.
**
** Variable usage notes:
**
** Parse.aLabel[x] Stores the address that the x-th label resolves
** into. For testing (SQLITE_DEBUG), unresolved
** labels stores -1, but that is not required.
** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
** Parse.nLabel The *negative* of the number of labels that have
** been issued. The negative is stored because
** that gives a performance improvement over storing
** the equivalent positive value.
*/
int sqlite3VdbeMakeLabel(Parse *pParse){
return --pParse->nLabel;
}
/*
** Resolve label "x" to be the address of the next instruction to
** be inserted. The parameter "x" must have been obtained from
** a prior call to sqlite3VdbeMakeLabel().
*/
static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
int nNewSize = 10 - p->nLabel;
p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
nNewSize*sizeof(p->aLabel[0]));
if( p->aLabel==0 ){
p->nLabelAlloc = 0;
}else{
#ifdef SQLITE_DEBUG
int i;
for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
#endif
p->nLabelAlloc = nNewSize;
p->aLabel[j] = v->nOp;
}
}
void sqlite3VdbeResolveLabel(Vdbe *v, int x){
Parse *p = v->pParse;
int j = ADDR(x);
assert( v->magic==VDBE_MAGIC_INIT );
assert( j<-p->nLabel );
assert( j>=0 );
#ifdef SQLITE_DEBUG
if( p->db->flags & SQLITE_VdbeAddopTrace ){
printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
}
#endif
if( p->nLabelAlloc + p->nLabel < 0 ){
resizeResolveLabel(p,v,j);
}else{
assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
p->aLabel[j] = v->nOp;
}
}
/*
** Mark the VDBE as one that can only be run one time.
*/
void sqlite3VdbeRunOnlyOnce(Vdbe *p){
p->runOnlyOnce = 1;
}
/*
** Mark the VDBE as one that can only be run multiple times.
*/
void sqlite3VdbeReusable(Vdbe *p){
p->runOnlyOnce = 0;
}
#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
/*
** The following type and function are used to iterate through all opcodes
** in a Vdbe main program and each of the sub-programs (triggers) it may
** invoke directly or indirectly. It should be used as follows:
**
** Op *pOp;
** VdbeOpIter sIter;
**
** memset(&sIter, 0, sizeof(sIter));
** sIter.v = v; // v is of type Vdbe*
** while( (pOp = opIterNext(&sIter)) ){
** // Do something with pOp
** }
** sqlite3DbFree(v->db, sIter.apSub);
**
*/
typedef struct VdbeOpIter VdbeOpIter;
struct VdbeOpIter {
Vdbe *v; /* Vdbe to iterate through the opcodes of */
SubProgram **apSub; /* Array of subprograms */
int nSub; /* Number of entries in apSub */
int iAddr; /* Address of next instruction to return */
int iSub; /* 0 = main program, 1 = first sub-program etc. */
};
static Op *opIterNext(VdbeOpIter *p){
Vdbe *v = p->v;
Op *pRet = 0;
Op *aOp;
int nOp;
if( p->iSub<=p->nSub ){
if( p->iSub==0 ){
aOp = v->aOp;
nOp = v->nOp;
}else{
aOp = p->apSub[p->iSub-1]->aOp;
nOp = p->apSub[p->iSub-1]->nOp;
}
assert( p->iAddr<nOp );
pRet = &aOp[p->iAddr];
p->iAddr++;
if( p->iAddr==nOp ){
p->iSub++;
p->iAddr = 0;
}
if( pRet->p4type==P4_SUBPROGRAM ){
int nByte = (p->nSub+1)*sizeof(SubProgram*);
int j;
for(j=0; j<p->nSub; j++){
if( p->apSub[j]==pRet->p4.pProgram ) break;
}
if( j==p->nSub ){
p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
if( !p->apSub ){
pRet = 0;
}else{
p->apSub[p->nSub++] = pRet->p4.pProgram;
}
}
}
}
return pRet;
}
/*
** Check if the program stored in the VM associated with pParse may
** throw an ABORT exception (causing the statement, but not entire transaction
** to be rolled back). This condition is true if the main program or any
** sub-programs contains any of the following:
**
** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
** * OP_Destroy
** * OP_VUpdate
** * OP_VCreate
** * OP_VRename
** * OP_FkCounter with P2==0 (immediate foreign key constraint)
** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
** (for CREATE TABLE AS SELECT ...)
**
** Then check that the value of Parse.mayAbort is true if an
** ABORT may be thrown, or false otherwise. Return true if it does
** match, or false otherwise. This function is intended to be used as
** part of an assert statement in the compiler. Similar to:
**
** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
*/
int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
int hasAbort = 0;
int hasFkCounter = 0;
int hasCreateTable = 0;
int hasCreateIndex = 0;
int hasInitCoroutine = 0;
Op *pOp;
VdbeOpIter sIter;
memset(&sIter, 0, sizeof(sIter));
sIter.v = v;
while( (pOp = opIterNext(&sIter))!=0 ){
int opcode = pOp->opcode;
if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
|| opcode==OP_VDestroy
|| opcode==OP_VCreate
|| (opcode==OP_ParseSchema && pOp->p4.z==0)
|| ((opcode==OP_Halt || opcode==OP_HaltIfNull)
&& ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
){
hasAbort = 1;
break;
}
if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
if( mayAbort ){
/* hasCreateIndex may also be set for some DELETE statements that use
** OP_Clear. So this routine may end up returning true in the case
** where a "DELETE FROM tbl" has a statement-journal but does not
** require one. This is not so bad - it is an inefficiency, not a bug. */
if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
if( opcode==OP_Clear ) hasCreateIndex = 1;
}
if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
#ifndef SQLITE_OMIT_FOREIGN_KEY
if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
hasFkCounter = 1;
}
#endif
}
sqlite3DbFree(v->db, sIter.apSub);
/* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
** If malloc failed, then the while() loop above may not have iterated
** through all opcodes and hasAbort may be set incorrectly. Return
** true for this case to prevent the assert() in the callers frame
** from failing. */
return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
|| (hasCreateTable && hasInitCoroutine) || hasCreateIndex
);
}
#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
#ifdef SQLITE_DEBUG
/*
** Increment the nWrite counter in the VDBE if the cursor is not an
** ephemeral cursor, or if the cursor argument is NULL.
*/
void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
if( pC==0
|| (pC->eCurType!=CURTYPE_SORTER
&& pC->eCurType!=CURTYPE_PSEUDO
&& !pC->isEphemeral)
){
p->nWrite++;
}
}
#endif
#ifdef SQLITE_DEBUG
/*
** Assert if an Abort at this point in time might result in a corrupt
** database.
*/
void sqlite3VdbeAssertAbortable(Vdbe *p){
assert( p->nWrite==0 || p->usesStmtJournal );
}
#endif
/*
** This routine is called after all opcodes have been inserted. It loops
** through all the opcodes and fixes up some details.
**
** (1) For each jump instruction with a negative P2 value (a label)
** resolve the P2 value to an actual address.
**
** (2) Compute the maximum number of arguments used by any SQL function
** and store that value in *pMaxFuncArgs.
**
** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
** indicate what the prepared statement actually does.
**
** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
**
** (5) Reclaim the memory allocated for storing labels.
**
** This routine will only function correctly if the mkopcodeh.tcl generator
** script numbers the opcodes correctly. Changes to this routine must be
** coordinated with changes to mkopcodeh.tcl.
*/
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
int nMaxArgs = *pMaxFuncArgs;
Op *pOp;
Parse *pParse = p->pParse;
int *aLabel = pParse->aLabel;
p->readOnly = 1;
p->bIsReader = 0;
pOp = &p->aOp[p->nOp-1];
while(1){
/* Only JUMP opcodes and the short list of special opcodes in the switch
** below need to be considered. The mkopcodeh.tcl generator script groups
** all these opcodes together near the front of the opcode list. Skip
** any opcode that does not need processing by virtual of the fact that
** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
*/
if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
/* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
** cases from this switch! */
switch( pOp->opcode ){
case OP_Transaction: {
if( pOp->p2!=0 ) p->readOnly = 0;
/* fall thru */
}
case OP_AutoCommit:
case OP_Savepoint: {
p->bIsReader = 1;
break;
}
#ifndef SQLITE_OMIT_WAL
case OP_Checkpoint:
#endif
case OP_Vacuum:
case OP_JournalMode: {
p->readOnly = 0;
p->bIsReader = 1;
break;
}
case OP_Next:
case OP_SorterNext: {
pOp->p4.xAdvance = sqlite3BtreeNext;
pOp->p4type = P4_ADVANCE;
/* The code generator never codes any of these opcodes as a jump
** to a label. They are always coded as a jump backwards to a
** known address */
assert( pOp->p2>=0 );
break;
}
case OP_Prev: {
pOp->p4.xAdvance = sqlite3BtreePrevious;
pOp->p4type = P4_ADVANCE;
/* The code generator never codes any of these opcodes as a jump
** to a label. They are always coded as a jump backwards to a
** known address */
assert( pOp->p2>=0 );
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case OP_VUpdate: {
if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
break;
}
case OP_VFilter: {
int n;
assert( (pOp - p->aOp) >= 3 );
assert( pOp[-1].opcode==OP_Integer );
n = pOp[-1].p1;
if( n>nMaxArgs ) nMaxArgs = n;
/* Fall through into the default case */
}
#endif
default: {
if( pOp->p2<0 ){
/* The mkopcodeh.tcl script has so arranged things that the only
** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
** have non-negative values for P2. */
assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
assert( ADDR(pOp->p2)<-pParse->nLabel );
pOp->p2 = aLabel[ADDR(pOp->p2)];
}
break;
}
}
/* The mkopcodeh.tcl script has so arranged things that the only
** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
** have non-negative values for P2. */
assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
}
if( pOp==p->aOp ) break;
pOp--;
}
sqlite3DbFree(p->db, pParse->aLabel);
pParse->aLabel = 0;
pParse->nLabel = 0;
*pMaxFuncArgs = nMaxArgs;
assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
}
/*
** Return the address of the next instruction to be inserted.
*/
int sqlite3VdbeCurrentAddr(Vdbe *p){
assert( p->magic==VDBE_MAGIC_INIT );
return p->nOp;
}
/*
** Verify that at least N opcode slots are available in p without
** having to malloc for more space (except when compiled using
** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
** to verify that certain calls to sqlite3VdbeAddOpList() can never
** fail due to a OOM fault and hence that the return value from
** sqlite3VdbeAddOpList() will always be non-NULL.
*/
#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
assert( p->nOp + N <= p->nOpAlloc );
}
#endif
/*
** Verify that the VM passed as the only argument does not contain
** an OP_ResultRow opcode. Fail an assert() if it does. This is used
** by code in pragma.c to ensure that the implementation of certain
** pragmas comports with the flags specified in the mkpragmatab.tcl
** script.
*/
#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
int i;
for(i=0; i<p->nOp; i++){
assert( p->aOp[i].opcode!=OP_ResultRow );
}
}
#endif
/*
** Generate code (a single OP_Abortable opcode) that will
** verify that the VDBE program can safely call Abort in the current
** context.
*/
#if defined(SQLITE_DEBUG)
void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
}
#endif
/*
** This function returns a pointer to the array of opcodes associated with
** the Vdbe passed as the first argument. It is the callers responsibility
** to arrange for the returned array to be eventually freed using the
** vdbeFreeOpArray() function.
**
** Before returning, *pnOp is set to the number of entries in the returned
** array. Also, *pnMaxArg is set to the larger of its current value and
** the number of entries in the Vdbe.apArg[] array required to execute the
** returned program.
*/
VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
VdbeOp *aOp = p->aOp;
assert( aOp && !p->db->mallocFailed );
/* Check that sqlite3VdbeUsesBtree() was not called on this VM */
assert( DbMaskAllZero(p->btreeMask) );
resolveP2Values(p, pnMaxArg);
*pnOp = p->nOp;
p->aOp = 0;
return aOp;
}
/*
** Add a whole list of operations to the operation stack. Return a
** pointer to the first operation inserted.
**
** Non-zero P2 arguments to jump instructions are automatically adjusted
** so that the jump target is relative to the first operation inserted.
*/
VdbeOp *sqlite3VdbeAddOpList(
Vdbe *p, /* Add opcodes to the prepared statement */
int nOp, /* Number of opcodes to add */
VdbeOpList const *aOp, /* The opcodes to be added */
int iLineno /* Source-file line number of first opcode */
){
int i;
VdbeOp *pOut, *pFirst;
assert( nOp>0 );
assert( p->magic==VDBE_MAGIC_INIT );
if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
return 0;
}
pFirst = pOut = &p->aOp[p->nOp];
for(i=0; i<nOp; i++, aOp++, pOut++){
pOut->opcode = aOp->opcode;
pOut->p1 = aOp->p1;
pOut->p2 = aOp->p2;
assert( aOp->p2>=0 );
if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
pOut->p2 += p->nOp;
}
pOut->p3 = aOp->p3;
pOut->p4type = P4_NOTUSED;
pOut->p4.p = 0;
pOut->p5 = 0;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
pOut->zComment = 0;
#endif
#ifdef SQLITE_VDBE_COVERAGE
pOut->iSrcLine = iLineno+i;
#else
(void)iLineno;
#endif
#ifdef SQLITE_DEBUG
if( p->db->flags & SQLITE_VdbeAddopTrace ){
sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
}
#endif
}
p->nOp += nOp;
return pFirst;
}
#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
/*
** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
*/
void sqlite3VdbeScanStatus(
Vdbe *p, /* VM to add scanstatus() to */
int addrExplain, /* Address of OP_Explain (or 0) */
int addrLoop, /* Address of loop counter */
int addrVisit, /* Address of rows visited counter */
LogEst nEst, /* Estimated number of output rows */
const char *zName /* Name of table or index being scanned */
){
sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
ScanStatus *aNew;
aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
if( aNew ){
ScanStatus *pNew = &aNew[p->nScan++];
pNew->addrExplain = addrExplain;
pNew->addrLoop = addrLoop;
pNew->addrVisit = addrVisit;
pNew->nEst = nEst;
pNew->zName = sqlite3DbStrDup(p->db, zName);
p->aScan = aNew;
}
}
#endif
/*
** Change the value of the opcode, or P1, P2, P3, or P5 operands
** for a specific instruction.
*/
void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
}
void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
sqlite3VdbeGetOp(p,addr)->p1 = val;
}
void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
sqlite3VdbeGetOp(p,addr)->p2 = val;
}
void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
sqlite3VdbeGetOp(p,addr)->p3 = val;
}
void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
assert( p->nOp>0 || p->db->mallocFailed );
if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
}
/*
** Change the P2 operand of instruction addr so that it points to
** the address of the next instruction to be coded.
*/
void sqlite3VdbeJumpHere(Vdbe *p, int addr){
sqlite3VdbeChangeP2(p, addr, p->nOp);
}
/*
** If the input FuncDef structure is ephemeral, then free it. If
** the FuncDef is not ephermal, then do nothing.
*/
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
sqlite3DbFreeNN(db, pDef);
}
}
/*
** Delete a P4 value if necessary.
*/
static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
sqlite3DbFreeNN(db, p);
}
static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
freeEphemeralFunction(db, p->pFunc);
sqlite3DbFreeNN(db, p);
}
static void freeP4(sqlite3 *db, int p4type, void *p4){
assert( db );
switch( p4type ){
case P4_FUNCCTX: {
freeP4FuncCtx(db, (sqlite3_context*)p4);
break;
}
case P4_REAL:
case P4_INT64:
case P4_DYNAMIC:
case P4_DYNBLOB:
case P4_INTARRAY: {
sqlite3DbFree(db, p4);
break;
}
case P4_KEYINFO: {
if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
break;
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
case P4_EXPR: {
sqlite3ExprDelete(db, (Expr*)p4);
break;
}
#endif
case P4_FUNCDEF: {
freeEphemeralFunction(db, (FuncDef*)p4);
break;
}
case P4_MEM: {
if( db->pnBytesFreed==0 ){
sqlite3ValueFree((sqlite3_value*)p4);
}else{
freeP4Mem(db, (Mem*)p4);
}
break;
}
case P4_VTAB : {
if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
break;
}
}
}
/*
** Free the space allocated for aOp and any p4 values allocated for the
** opcodes contained within. If aOp is not NULL it is assumed to contain
** nOp entries.
*/
static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
if( aOp ){
Op *pOp;
for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
sqlite3DbFree(db, pOp->zComment);
#endif
}
sqlite3DbFreeNN(db, aOp);
}
}
/*
** Link the SubProgram object passed as the second argument into the linked
** list at Vdbe.pSubProgram. This list is used to delete all sub-program
** objects when the VM is no longer required.
*/
void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
p->pNext = pVdbe->pProgram;
pVdbe->pProgram = p;
}
/*
** Return true if the given Vdbe has any SubPrograms.
*/
int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
return pVdbe->pProgram!=0;
}
/*
** Change the opcode at addr into OP_Noop
*/
int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
VdbeOp *pOp;
if( p->db->mallocFailed ) return 0;
assert( addr>=0 && addr<p->nOp );
pOp = &p->aOp[addr];
freeP4(p->db, pOp->p4type, pOp->p4.p);
pOp->p4type = P4_NOTUSED;
pOp->p4.z = 0;
pOp->opcode = OP_Noop;
return 1;
}
/*
** If the last opcode is "op" and it is not a jump destination,
** then remove it. Return true if and only if an opcode was removed.
*/
int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
return sqlite3VdbeChangeToNoop(p, p->nOp-1);
}else{
return 0;
}
}
/*
** Change the value of the P4 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
**
** If n>=0 then the P4 operand is dynamic, meaning that a copy of
** the string is made into memory obtained from sqlite3_malloc().
** A value of n==0 means copy bytes of zP4 up to and including the
** first null byte. If n>0 then copy n+1 bytes of zP4.
**
** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
** to a string or structure that is guaranteed to exist for the lifetime of
** the Vdbe. In these cases we can just copy the pointer.
**
** If addr<0 then change P4 on the most recently inserted instruction.
*/
static void SQLITE_NOINLINE vdbeChangeP4Full(
Vdbe *p,
Op *pOp,
const char *zP4,
int n
){
if( pOp->p4type ){
freeP4(p->db, pOp->p4type, pOp->p4.p);
pOp->p4type = 0;
pOp->p4.p = 0;
}
if( n<0 ){
sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
}else{
if( n==0 ) n = sqlite3Strlen30(zP4);
pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
pOp->p4type = P4_DYNAMIC;
}
}
void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
Op *pOp;
sqlite3 *db;
assert( p!=0 );
db = p->db;
assert( p->magic==VDBE_MAGIC_INIT );
assert( p->aOp!=0 || db->mallocFailed );
if( db->mallocFailed ){
if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
return;
}
assert( p->nOp>0 );
assert( addr<p->nOp );
if( addr<0 ){
addr = p->nOp - 1;
}
pOp = &p->aOp[addr];
if( n>=0 || pOp->p4type ){
vdbeChangeP4Full(p, pOp, zP4, n);
return;
}
if( n==P4_INT32 ){
/* Note: this cast is safe, because the origin data point was an int
** that was cast to a (const char *). */
pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
pOp->p4type = P4_INT32;
}else if( zP4!=0 ){
assert( n<0 );
pOp->p4.p = (void*)zP4;
pOp->p4type = (signed char)n;
if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
}
}
/*
** Change the P4 operand of the most recently coded instruction
** to the value defined by the arguments. This is a high-speed
** version of sqlite3VdbeChangeP4().
**
** The P4 operand must not have been previously defined. And the new
** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
** those cases.
*/
void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
VdbeOp *pOp;
assert( n!=P4_INT32 && n!=P4_VTAB );
assert( n<=0 );
if( p->db->mallocFailed ){
freeP4(p->db, n, pP4);
}else{
assert( pP4!=0 );
assert( p->nOp>0 );
pOp = &p->aOp[p->nOp-1];
assert( pOp->p4type==P4_NOTUSED );
pOp->p4type = n;
pOp->p4.p = pP4;
}
}
/*
** Set the P4 on the most recently added opcode to the KeyInfo for the
** index given.
*/
void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
Vdbe *v = pParse->pVdbe;
KeyInfo *pKeyInfo;
assert( v!=0 );
assert( pIdx!=0 );
pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
}
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
/*
** Change the comment on the most recently coded instruction. Or
** insert a No-op and add the comment to that new instruction. This
** makes the code easier to read during debugging. None of this happens
** in a production build.
*/
static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
assert( p->nOp>0 || p->aOp==0 );
assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
if( p->nOp ){
assert( p->aOp );
sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
}
}
void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
va_list ap;
if( p ){
va_start(ap, zFormat);
vdbeVComment(p, zFormat, ap);
va_end(ap);
}
}
void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
va_list ap;
if( p ){
sqlite3VdbeAddOp0(p, OP_Noop);
va_start(ap, zFormat);
vdbeVComment(p, zFormat, ap);
va_end(ap);
}
}
#endif /* NDEBUG */
#ifdef SQLITE_VDBE_COVERAGE
/*
** Set the value if the iSrcLine field for the previously coded instruction.
*/
void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
}
#endif /* SQLITE_VDBE_COVERAGE */
/*
** Return the opcode for a given address. If the address is -1, then
** return the most recently inserted opcode.
**
** If a memory allocation error has occurred prior to the calling of this
** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
** is readable but not writable, though it is cast to a writable value.
** The return of a dummy opcode allows the call to continue functioning
** after an OOM fault without having to check to see if the return from
** this routine is a valid pointer. But because the dummy.opcode is 0,
** dummy will never be written to. This is verified by code inspection and
** by running with Valgrind.
*/
VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
/* C89 specifies that the constant "dummy" will be initialized to all
** zeros, which is correct. MSVC generates a warning, nevertheless. */
static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
assert( p->magic==VDBE_MAGIC_INIT );
if( addr<0 ){
addr = p->nOp - 1;
}
assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
if( p->db->mallocFailed ){
return (VdbeOp*)&dummy;
}else{
return &p->aOp[addr];
}
}
#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
/*
** Return an integer value for one of the parameters to the opcode pOp
** determined by character c.
*/
static int translateP(char c, const Op *pOp){
if( c=='1' ) return pOp->p1;
if( c=='2' ) return pOp->p2;
if( c=='3' ) return pOp->p3;
if( c=='4' ) return pOp->p4.i;
return pOp->p5;
}
/*
** Compute a string for the "comment" field of a VDBE opcode listing.
**
** The Synopsis: field in comments in the vdbe.c source file gets converted
** to an extra string that is appended to the sqlite3OpcodeName(). In the
** absence of other comments, this synopsis becomes the comment on the opcode.
** Some translation occurs:
**
** "PX" -> "r[X]"
** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
*/
static int displayComment(
const Op *pOp, /* The opcode to be commented */
const char *zP4, /* Previously obtained value for P4 */
char *zTemp, /* Write result here */
int nTemp /* Space available in zTemp[] */
){
const char *zOpName;
const char *zSynopsis;
int nOpName;
int ii, jj;
char zAlt[50];
zOpName = sqlite3OpcodeName(pOp->opcode);
nOpName = sqlite3Strlen30(zOpName);
if( zOpName[nOpName+1] ){
int seenCom = 0;
char c;
zSynopsis = zOpName += nOpName + 1;
if( strncmp(zSynopsis,"IF ",3)==0 ){
if( pOp->p5 & SQLITE_STOREP2 ){
sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
}else{
sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
}
zSynopsis = zAlt;
}
for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
if( c=='P' ){
c = zSynopsis[++ii];
if( c=='4' ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
}else if( c=='X' ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
seenCom = 1;
}else{
int v1 = translateP(c, pOp);
int v2;
sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
ii += 3;
jj += sqlite3Strlen30(zTemp+jj);
v2 = translateP(zSynopsis[ii], pOp);
if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
ii += 2;
v2++;
}
if( v2>1 ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
}
}else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
ii += 4;
}
}
jj += sqlite3Strlen30(zTemp+jj);
}else{
zTemp[jj++] = c;
}
}
if( !seenCom && jj<nTemp-5 && pOp->zComment ){
sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
jj += sqlite3Strlen30(zTemp+jj);
}
if( jj<nTemp ) zTemp[jj] = 0;
}else if( pOp->zComment ){
sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
jj = sqlite3Strlen30(zTemp);
}else{
zTemp[0] = 0;
jj = 0;
}
return jj;
}
#endif /* SQLITE_DEBUG */
#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
/*
** Translate the P4.pExpr value for an OP_CursorHint opcode into text
** that can be displayed in the P4 column of EXPLAIN output.
*/
static void displayP4Expr(StrAccum *p, Expr *pExpr){
const char *zOp = 0;
switch( pExpr->op ){
case TK_STRING:
sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
break;
case TK_INTEGER:
sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
break;
case TK_NULL:
sqlite3_str_appendf(p, "NULL");
break;
case TK_REGISTER: {
sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
break;
}
case TK_COLUMN: {
if( pExpr->iColumn<0 ){
sqlite3_str_appendf(p, "rowid");
}else{
sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
}
break;
}
case TK_LT: zOp = "LT"; break;
case TK_LE: zOp = "LE"; break;
case TK_GT: zOp = "GT"; break;
case TK_GE: zOp = "GE"; break;
case TK_NE: zOp = "NE"; break;
case TK_EQ: zOp = "EQ"; break;
case TK_IS: zOp = "IS"; break;
case TK_ISNOT: zOp = "ISNOT"; break;
case TK_AND: zOp = "AND"; break;
case TK_OR: zOp = "OR"; break;
case TK_PLUS: zOp = "ADD"; break;
case TK_STAR: zOp = "MUL"; break;
case TK_MINUS: zOp = "SUB"; break;
case TK_REM: zOp = "REM"; break;
case TK_BITAND: zOp = "BITAND"; break;
case TK_BITOR: zOp = "BITOR"; break;
case TK_SLASH: zOp = "DIV"; break;
case TK_LSHIFT: zOp = "LSHIFT"; break;
case TK_RSHIFT: zOp = "RSHIFT"; break;
case TK_CONCAT: zOp = "CONCAT"; break;
case TK_UMINUS: zOp = "MINUS"; break;
case TK_UPLUS: zOp = "PLUS"; break;
case TK_BITNOT: zOp = "BITNOT"; break;
case TK_NOT: zOp = "NOT"; break;
case TK_ISNULL: zOp = "ISNULL"; break;
case TK_NOTNULL: zOp = "NOTNULL"; break;
default:
sqlite3_str_appendf(p, "%s", "expr");
break;
}
if( zOp ){
sqlite3_str_appendf(p, "%s(", zOp);
displayP4Expr(p, pExpr->pLeft);
if( pExpr->pRight ){
sqlite3_str_append(p, ",", 1);
displayP4Expr(p, pExpr->pRight);
}
sqlite3_str_append(p, ")", 1);
}
}
#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
#if VDBE_DISPLAY_P4
/*
** Compute a string that describes the P4 parameter for an opcode.
** Use zTemp for any required temporary buffer space.
*/
static char *displayP4(Op *pOp, char *zTemp, int nTemp){
char *zP4 = zTemp;
StrAccum x;
assert( nTemp>=20 );
sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
switch( pOp->p4type ){
case P4_KEYINFO: {
int j;
KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
assert( pKeyInfo->aSortFlags!=0 );
sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
for(j=0; j<pKeyInfo->nKeyField; j++){
CollSeq *pColl = pKeyInfo->aColl[j];
const char *zColl = pColl ? pColl->zName : "";
if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
sqlite3_str_appendf(&x, ",%s%s%s",
(pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
(pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
zColl);
}
sqlite3_str_append(&x, ")", 1);
break;
}
#ifdef SQLITE_ENABLE_CURSOR_HINTS
case P4_EXPR: {
displayP4Expr(&x, pOp->p4.pExpr);
break;
}
#endif
case P4_COLLSEQ: {
CollSeq *pColl = pOp->p4.pColl;
sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
break;
}
case P4_FUNCDEF: {
FuncDef *pDef = pOp->p4.pFunc;
sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
break;
}
case P4_FUNCCTX: {
FuncDef *pDef = pOp->p4.pCtx->pFunc;
sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
break;
}
case P4_INT64: {
sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
break;
}
case P4_INT32: {
sqlite3_str_appendf(&x, "%d", pOp->p4.i);
break;
}
case P4_REAL: {
sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
break;
}
case P4_MEM: {
Mem *pMem = pOp->p4.pMem;
if( pMem->flags & MEM_Str ){
zP4 = pMem->z;
}else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
sqlite3_str_appendf(&x, "%lld", pMem->u.i);
}else if( pMem->flags & MEM_Real ){
sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
}else if( pMem->flags & MEM_Null ){
zP4 = "NULL";
}else{
assert( pMem->flags & MEM_Blob );
zP4 = "(blob)";
}
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case P4_VTAB: {
sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
sqlite3_str_appendf(&x, "vtab:%p", pVtab);
break;
}
#endif
case P4_INTARRAY: {
int i;
int *ai = pOp->p4.ai;
int n = ai[0]; /* The first element of an INTARRAY is always the
** count of the number of elements to follow */
for(i=1; i<=n; i++){
sqlite3_str_appendf(&x, ",%d", ai[i]);
}
zTemp[0] = '[';
sqlite3_str_append(&x, "]", 1);
break;
}
case P4_SUBPROGRAM: {
sqlite3_str_appendf(&x, "program");
break;
}
case P4_DYNBLOB:
case P4_ADVANCE: {
zTemp[0] = 0;
break;
}
case P4_TABLE: {
sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
break;
}
default: {
zP4 = pOp->p4.z;
if( zP4==0 ){
zP4 = zTemp;
zTemp[0] = 0;
}
}
}
sqlite3StrAccumFinish(&x);
assert( zP4!=0 );
return zP4;
}
#endif /* VDBE_DISPLAY_P4 */
/*
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
**
** The prepared statements need to know in advance the complete set of
** attached databases that will be use. A mask of these databases
** is maintained in p->btreeMask. The p->lockMask value is the subset of
** p->btreeMask of databases that will require a lock.
*/
void sqlite3VdbeUsesBtree(Vdbe *p, int i){
assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
assert( i<(int)sizeof(p->btreeMask)*8 );
DbMaskSet(p->btreeMask, i);
if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
DbMaskSet(p->lockMask, i);
}
}
#if !defined(SQLITE_OMIT_SHARED_CACHE)
/*
** If SQLite is compiled to support shared-cache mode and to be threadsafe,
** this routine obtains the mutex associated with each BtShared structure
** that may be accessed by the VM passed as an argument. In doing so it also
** sets the BtShared.db member of each of the BtShared structures, ensuring
** that the correct busy-handler callback is invoked if required.
**
** If SQLite is not threadsafe but does support shared-cache mode, then
** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
** of all of BtShared structures accessible via the database handle
** associated with the VM.
**
** If SQLite is not threadsafe and does not support shared-cache mode, this
** function is a no-op.
**
** The p->btreeMask field is a bitmask of all btrees that the prepared
** statement p will ever use. Let N be the number of bits in p->btreeMask
** corresponding to btrees that use shared cache. Then the runtime of
** this routine is N*N. But as N is rarely more than 1, this should not
** be a problem.
*/
void sqlite3VdbeEnter(Vdbe *p){
int i;
sqlite3 *db;
Db *aDb;
int nDb;
if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
db = p->db;
aDb = db->aDb;
nDb = db->nDb;
for(i=0; i<nDb; i++){
if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
sqlite3BtreeEnter(aDb[i].pBt);
}
}
}
#endif
#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
/*
** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
*/
static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
int i;
sqlite3 *db;
Db *aDb;
int nDb;
db = p->db;
aDb = db->aDb;
nDb = db->nDb;
for(i=0; i<nDb; i++){
if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
sqlite3BtreeLeave(aDb[i].pBt);
}
}
}
void sqlite3VdbeLeave(Vdbe *p){
if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
vdbeLeave(p);
}
#endif
#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Print a single opcode. This routine is used for debugging only.
*/
void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
char *zP4;
char zPtr[50];
char zCom[100];
static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
if( pOut==0 ) pOut = stdout;
zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
displayComment(pOp, zP4, zCom, sizeof(zCom));
#else
zCom[0] = 0;
#endif
/* NB: The sqlite3OpcodeName() function is implemented by code created
** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
** information from the vdbe.c source text */
fprintf(pOut, zFormat1, pc,
sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
zCom
);
fflush(pOut);
}
#endif
/*
** Initialize an array of N Mem element.
*/
static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
while( (N--)>0 ){
p->db = db;
p->flags = flags;
p->szMalloc = 0;
#ifdef SQLITE_DEBUG
p->pScopyFrom = 0;
#endif
p++;
}
}
/*
** Release an array of N Mem elements
*/
static void releaseMemArray(Mem *p, int N){
if( p && N ){
Mem *pEnd = &p[N];
sqlite3 *db = p->db;
if( db->pnBytesFreed ){
do{
if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
}while( (++p)<pEnd );
return;
}
do{
assert( (&p[1])==pEnd || p[0].db==p[1].db );
assert( sqlite3VdbeCheckMemInvariants(p) );
/* This block is really an inlined version of sqlite3VdbeMemRelease()
** that takes advantage of the fact that the memory cell value is
** being set to NULL after releasing any dynamic resources.
**
** The justification for duplicating code is that according to
** callgrind, this causes a certain test case to hit the CPU 4.7
** percent less (x86 linux, gcc version 4.1.2, -O6) than if
** sqlite3MemRelease() were called from here. With -O2, this jumps
** to 6.6 percent. The test case is inserting 1000 rows into a table
** with no indexes using a single prepared INSERT statement, bind()
** and reset(). Inserts are grouped into a transaction.
*/
testcase( p->flags & MEM_Agg );
testcase( p->flags & MEM_Dyn );
testcase( p->xDel==sqlite3VdbeFrameMemDel );
if( p->flags&(MEM_Agg|MEM_Dyn) ){
sqlite3VdbeMemRelease(p);
}else if( p->szMalloc ){
sqlite3DbFreeNN(db, p->zMalloc);
p->szMalloc = 0;
}
p->flags = MEM_Undefined;
}while( (++p)<pEnd );
}
}
#ifdef SQLITE_DEBUG
/*
** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
** and false if something is wrong.
**
** This routine is intended for use inside of assert() statements only.
*/
int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
return 1;
}
#endif
/*
** This is a destructor on a Mem object (which is really an sqlite3_value)
** that deletes the Frame object that is attached to it as a blob.
**
** This routine does not delete the Frame right away. It merely adds the
** frame to a list of frames to be deleted when the Vdbe halts.
*/
void sqlite3VdbeFrameMemDel(void *pArg){
VdbeFrame *pFrame = (VdbeFrame*)pArg;
assert( sqlite3VdbeFrameIsValid(pFrame) );
pFrame->pParent = pFrame->v->pDelFrame;
pFrame->v->pDelFrame = pFrame;
}
/*
** Delete a VdbeFrame object and its contents. VdbeFrame objects are
** allocated by the OP_Program opcode in sqlite3VdbeExec().
*/
void sqlite3VdbeFrameDelete(VdbeFrame *p){
int i;
Mem *aMem = VdbeFrameMem(p);
VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
assert( sqlite3VdbeFrameIsValid(p) );
for(i=0; i<p->nChildCsr; i++){
sqlite3VdbeFreeCursor(p->v, apCsr[i]);
}
releaseMemArray(aMem, p->nChildMem);
sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
sqlite3DbFree(p->v->db, p);
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Give a listing of the program in the virtual machine.
**
** The interface is the same as sqlite3VdbeExec(). But instead of
** running the code, it invokes the callback once for each instruction.
** This feature is used to implement "EXPLAIN".
**
** When p->explain==1, each instruction is listed. When
** p->explain==2, only OP_Explain instructions are listed and these
** are shown in a different format. p->explain==2 is used to implement
** EXPLAIN QUERY PLAN.
** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
** are also shown, so that the boundaries between the main program and
** each trigger are clear.
**
** When p->explain==1, first the main program is listed, then each of
** the trigger subprograms are listed one by one.
*/
int sqlite3VdbeList(
Vdbe *p /* The VDBE */
){
int nRow; /* Stop when row count reaches this */
int nSub = 0; /* Number of sub-vdbes seen so far */
SubProgram **apSub = 0; /* Array of sub-vdbes */
Mem *pSub = 0; /* Memory cell hold array of subprogs */
sqlite3 *db = p->db; /* The database connection */
int i; /* Loop counter */
int rc = SQLITE_OK; /* Return code */
Mem *pMem = &p->aMem[1]; /* First Mem of result set */
int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
Op *pOp = 0;
assert( p->explain );
assert( p->magic==VDBE_MAGIC_RUN );
assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
/* Even though this opcode does not use dynamic strings for
** the result, result columns may become dynamic if the user calls
** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
*/
releaseMemArray(pMem, 8);
p->pResultSet = 0;
if( p->rc==SQLITE_NOMEM ){
/* This happens if a malloc() inside a call to sqlite3_column_text() or
** sqlite3_column_text16() failed. */
sqlite3OomFault(db);
return SQLITE_ERROR;
}
/* When the number of output rows reaches nRow, that means the
** listing has finished and sqlite3_step() should return SQLITE_DONE.
** nRow is the sum of the number of rows in the main program, plus
** the sum of the number of rows in all trigger subprograms encountered
** so far. The nRow value will increase as new trigger subprograms are
** encountered, but p->pc will eventually catch up to nRow.
*/
nRow = p->nOp;
if( bListSubprogs ){
/* The first 8 memory cells are used for the result set. So we will
** commandeer the 9th cell to use as storage for an array of pointers
** to trigger subprograms. The VDBE is guaranteed to have at least 9
** cells. */
assert( p->nMem>9 );
pSub = &p->aMem[9];
if( pSub->flags&MEM_Blob ){
/* On the first call to sqlite3_step(), pSub will hold a NULL. It is
** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
nSub = pSub->n/sizeof(Vdbe*);
apSub = (SubProgram **)pSub->z;
}
for(i=0; i<nSub; i++){
nRow += apSub[i]->nOp;
}
}
while(1){ /* Loop exits via break */
i = p->pc++;
if( i>=nRow ){
p->rc = SQLITE_OK;
rc = SQLITE_DONE;
break;
}
if( i<p->nOp ){
/* The output line number is small enough that we are still in the
** main program. */
pOp = &p->aOp[i];
}else{
/* We are currently listing subprograms. Figure out which one and
** pick up the appropriate opcode. */
int j;
i -= p->nOp;
assert( apSub!=0 );
assert( nSub>0 );
for(j=0; i>=apSub[j]->nOp; j++){
i -= apSub[j]->nOp;
assert( i<apSub[j]->nOp || j+1<nSub );
}
pOp = &apSub[j]->aOp[i];
}
/* When an OP_Program opcode is encounter (the only opcode that has
** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
** kept in p->aMem[9].z to hold the new program - assuming this subprogram
** has not already been seen.
*/
if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
int nByte = (nSub+1)*sizeof(SubProgram*);
int j;
for(j=0; j<nSub; j++){
if( apSub[j]==pOp->p4.pProgram ) break;
}
if( j==nSub ){
p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
if( p->rc!=SQLITE_OK ){
rc = SQLITE_ERROR;
break;
}
apSub = (SubProgram **)pSub->z;
apSub[nSub++] = pOp->p4.pProgram;
pSub->flags |= MEM_Blob;
pSub->n = nSub*sizeof(SubProgram*);
nRow += pOp->p4.pProgram->nOp;
}
}
if( p->explain<2 ) break;
if( pOp->opcode==OP_Explain ) break;
if( pOp->opcode==OP_Init && p->pc>1 ) break;
}
if( rc==SQLITE_OK ){
if( db->u1.isInterrupted ){
p->rc = SQLITE_INTERRUPT;
rc = SQLITE_ERROR;
sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
}else{
char *zP4;
if( p->explain==1 ){
pMem->flags = MEM_Int;
pMem->u.i = i; /* Program counter */
pMem++;
pMem->flags = MEM_Static|MEM_Str|MEM_Term;
pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
assert( pMem->z!=0 );
pMem->n = sqlite3Strlen30(pMem->z);
pMem->enc = SQLITE_UTF8;
pMem++;
}
pMem->flags = MEM_Int;
pMem->u.i = pOp->p1; /* P1 */
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p2; /* P2 */
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p3; /* P3 */
pMem++;
if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
if( zP4!=pMem->z ){
pMem->n = 0;
sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
}else{
assert( pMem->z!=0 );
pMem->n = sqlite3Strlen30(pMem->z);
pMem->enc = SQLITE_UTF8;
}
pMem++;
if( p->explain==1 ){
if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
pMem->n = 2;
sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
pMem->enc = SQLITE_UTF8;
pMem++;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
pMem->n = displayComment(pOp, zP4, pMem->z, 500);
pMem->enc = SQLITE_UTF8;
#else
pMem->flags = MEM_Null; /* Comment */
#endif
}
p->nResColumn = 8 - 4*(p->explain-1);
p->pResultSet = &p->aMem[1];
p->rc = SQLITE_OK;
rc = SQLITE_ROW;
}
}
return rc;
}
#endif /* SQLITE_OMIT_EXPLAIN */
#ifdef SQLITE_DEBUG
/*
** Print the SQL that was used to generate a VDBE program.
*/
void sqlite3VdbePrintSql(Vdbe *p){
const char *z = 0;
if( p->zSql ){
z = p->zSql;
}else if( p->nOp>=1 ){
const VdbeOp *pOp = &p->aOp[0];
if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
z = pOp->p4.z;
while( sqlite3Isspace(*z) ) z++;
}
}
if( z ) printf("SQL: [%s]\n", z);
}
#endif
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** Print an IOTRACE message showing SQL content.
*/
void sqlite3VdbeIOTraceSql(Vdbe *p){
int nOp = p->nOp;
VdbeOp *pOp;
if( sqlite3IoTrace==0 ) return;
if( nOp<1 ) return;
pOp = &p->aOp[0];
if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
int i, j;
char z[1000];
sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
for(i=0; sqlite3Isspace(z[i]); i++){}
for(j=0; z[i]; i++){
if( sqlite3Isspace(z[i]) ){
if( z[i-1]!=' ' ){
z[j++] = ' ';
}
}else{
z[j++] = z[i];
}
}
z[j] = 0;
sqlite3IoTrace("SQL %s\n", z);
}
}
#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
/* An instance of this object describes bulk memory available for use
** by subcomponents of a prepared statement. Space is allocated out
** of a ReusableSpace object by the allocSpace() routine below.
*/
struct ReusableSpace {
u8 *pSpace; /* Available memory */
sqlite3_int64 nFree; /* Bytes of available memory */
sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
};
/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
** from the ReusableSpace object. Return a pointer to the allocated
** memory on success. If insufficient memory is available in the
** ReusableSpace object, increase the ReusableSpace.nNeeded
** value by the amount needed and return NULL.
**
** If pBuf is not initially NULL, that means that the memory has already
** been allocated by a prior call to this routine, so just return a copy
** of pBuf and leave ReusableSpace unchanged.
**
** This allocator is employed to repurpose unused slots at the end of the
** opcode array of prepared state for other memory needs of the prepared
** statement.
*/
static void *allocSpace(
struct ReusableSpace *p, /* Bulk memory available for allocation */
void *pBuf, /* Pointer to a prior allocation */
sqlite3_int64 nByte /* Bytes of memory needed */
){
assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
if( pBuf==0 ){
nByte = ROUND8(nByte);
if( nByte <= p->nFree ){
p->nFree -= nByte;
pBuf = &p->pSpace[p->nFree];
}else{
p->nNeeded += nByte;
}
}
assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
return pBuf;
}
/*
** Rewind the VDBE back to the beginning in preparation for
** running it.
*/
void sqlite3VdbeRewind(Vdbe *p){
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
int i;
#endif
assert( p!=0 );
assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
/* There should be at least one opcode.
*/
assert( p->nOp>0 );
/* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
p->magic = VDBE_MAGIC_RUN;
#ifdef SQLITE_DEBUG
for(i=0; i<p->nMem; i++){
assert( p->aMem[i].db==p->db );
}
#endif
p->pc = -1;
p->rc = SQLITE_OK;
p->errorAction = OE_Abort;
p->nChange = 0;
p->cacheCtr = 1;
p->minWriteFileFormat = 255;
p->iStatement = 0;
p->nFkConstraint = 0;
#ifdef VDBE_PROFILE
for(i=0; i<p->nOp; i++){
p->aOp[i].cnt = 0;
p->aOp[i].cycles = 0;
}
#endif
}
/*
** Prepare a virtual machine for execution for the first time after
** creating the virtual machine. This involves things such
** as allocating registers and initializing the program counter.
** After the VDBE has be prepped, it can be executed by one or more
** calls to sqlite3VdbeExec().
**
** This function may be called exactly once on each virtual machine.
** After this routine is called the VM has been "packaged" and is ready
** to run. After this routine is called, further calls to
** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
** the Vdbe from the Parse object that helped generate it so that the
** the Vdbe becomes an independent entity and the Parse object can be
** destroyed.
**
** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
** to its initial state after it has been run.
*/
void sqlite3VdbeMakeReady(
Vdbe *p, /* The VDBE */
Parse *pParse /* Parsing context */
){
sqlite3 *db; /* The database connection */
int nVar; /* Number of parameters */
int nMem; /* Number of VM memory registers */
int nCursor; /* Number of cursors required */
int nArg; /* Number of arguments in subprograms */
int n; /* Loop counter */
struct ReusableSpace x; /* Reusable bulk memory */
assert( p!=0 );
assert( p->nOp>0 );
assert( pParse!=0 );
assert( p->magic==VDBE_MAGIC_INIT );
assert( pParse==p->pParse );
db = p->db;
assert( db->mallocFailed==0 );
nVar = pParse->nVar;
nMem = pParse->nMem;
nCursor = pParse->nTab;
nArg = pParse->nMaxArg;
/* Each cursor uses a memory cell. The first cursor (cursor 0) can
** use aMem[0] which is not otherwise used by the VDBE program. Allocate
** space at the end of aMem[] for cursors 1 and greater.
** See also: allocateCursor().
*/
nMem += nCursor;
if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
/* Figure out how much reusable memory is available at the end of the
** opcode array. This extra memory will be reallocated for other elements
** of the prepared statement.
*/
n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
assert( x.nFree>=0 );
assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
resolveP2Values(p, &nArg);
p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
if( pParse->explain ){
static const char * const azColName[] = {
"addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
"id", "parent", "notused", "detail"
};
int iFirst, mx, i;
if( nMem<10 ) nMem = 10;
if( pParse->explain==2 ){
sqlite3VdbeSetNumCols(p, 4);
iFirst = 8;
mx = 12;
}else{
sqlite3VdbeSetNumCols(p, 8);
iFirst = 0;
mx = 8;
}
for(i=iFirst; i<mx; i++){
sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
azColName[i], SQLITE_STATIC);
}
}
p->expired = 0;
/* Memory for registers, parameters, cursor, etc, is allocated in one or two
** passes. On the first pass, we try to reuse unused memory at the
** end of the opcode array. If we are unable to satisfy all memory
** requirements by reusing the opcode array tail, then the second
** pass will fill in the remainder using a fresh memory allocation.
**
** This two-pass approach that reuses as much memory as possible from
** the leftover memory at the end of the opcode array. This can significantly
** reduce the amount of memory held by a prepared statement.
*/
x.nNeeded = 0;
p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
#endif
if( x.nNeeded ){
x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
x.nFree = x.nNeeded;
if( !db->mallocFailed ){
p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
#endif
}
}
p->pVList = pParse->pVList;
pParse->pVList = 0;
p->explain = pParse->explain;
if( db->mallocFailed ){
p->nVar = 0;
p->nCursor = 0;
p->nMem = 0;
}else{
p->nCursor = nCursor;
p->nVar = (ynVar)nVar;
initMemArray(p->aVar, nVar, db, MEM_Null);
p->nMem = nMem;
initMemArray(p->aMem, nMem, db, MEM_Undefined);
memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
memset(p->anExec, 0, p->nOp*sizeof(i64));
#endif
}
sqlite3VdbeRewind(p);
}
/*
** Close a VDBE cursor and release all the resources that cursor
** happens to hold.
*/
void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
if( pCx==0 ){
return;
}
assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
switch( pCx->eCurType ){
case CURTYPE_SORTER: {
sqlite3VdbeSorterClose(p->db, pCx);
break;
}
case CURTYPE_BTREE: {
if( pCx->isEphemeral ){
if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
/* The pCx->pCursor will be close automatically, if it exists, by
** the call above. */
}else{
assert( pCx->uc.pCursor!=0 );
sqlite3BtreeCloseCursor(pCx->uc.pCursor);
}
break;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
case CURTYPE_VTAB: {
sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
const sqlite3_module *pModule = pVCur->pVtab->pModule;
assert( pVCur->pVtab->nRef>0 );
pVCur->pVtab->nRef--;
pModule->xClose(pVCur);
break;
}
#endif
}
}
/*
** Close all cursors in the current frame.
*/
static void closeCursorsInFrame(Vdbe *p){
if( p->apCsr ){
int i;
for(i=0; i<p->nCursor; i++){
VdbeCursor *pC = p->apCsr[i];
if( pC ){
sqlite3VdbeFreeCursor(p, pC);
p->apCsr[i] = 0;
}
}
}
}
/*
** Copy the values stored in the VdbeFrame structure to its Vdbe. This
** is used, for example, when a trigger sub-program is halted to restore
** control to the main program.
*/
int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
Vdbe *v = pFrame->v;
closeCursorsInFrame(v);
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
v->anExec = pFrame->anExec;
#endif
v->aOp = pFrame->aOp;
v->nOp = pFrame->nOp;
v->aMem = pFrame->aMem;
v->nMem = pFrame->nMem;
v->apCsr = pFrame->apCsr;
v->nCursor = pFrame->nCursor;
v->db->lastRowid = pFrame->lastRowid;
v->nChange = pFrame->nChange;
v->db->nChange = pFrame->nDbChange;
sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
v->pAuxData = pFrame->pAuxData;
pFrame->pAuxData = 0;
return pFrame->pc;
}
/*
** Close all cursors.
**
** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
** cell array. This is necessary as the memory cell array may contain
** pointers to VdbeFrame objects, which may in turn contain pointers to
** open cursors.
*/
static void closeAllCursors(Vdbe *p){
if( p->pFrame ){
VdbeFrame *pFrame;
for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
sqlite3VdbeFrameRestore(pFrame);
p->pFrame = 0;
p->nFrame = 0;
}
assert( p->nFrame==0 );
closeCursorsInFrame(p);
if( p->aMem ){
releaseMemArray(p->aMem, p->nMem);
}
while( p->pDelFrame ){
VdbeFrame *pDel = p->pDelFrame;
p->pDelFrame = pDel->pParent;
sqlite3VdbeFrameDelete(pDel);
}
/* Delete any auxdata allocations made by the VM */
if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
assert( p->pAuxData==0 );
}
/*
** Set the number of result columns that will be returned by this SQL
** statement. This is now set at compile time, rather than during
** execution of the vdbe program so that sqlite3_column_count() can
** be called on an SQL statement before sqlite3_step().
*/
void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
int n;
sqlite3 *db = p->db;
if( p->nResColumn ){
releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
sqlite3DbFree(db, p->aColName);
}
n = nResColumn*COLNAME_N;
p->nResColumn = (u16)nResColumn;
p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
if( p->aColName==0 ) return;
initMemArray(p->aColName, n, db, MEM_Null);
}
/*
** Set the name of the idx'th column to be returned by the SQL statement.
** zName must be a pointer to a nul terminated string.
**
** This call must be made after a call to sqlite3VdbeSetNumCols().
**
** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
*/
int sqlite3VdbeSetColName(
Vdbe *p, /* Vdbe being configured */
int idx, /* Index of column zName applies to */
int var, /* One of the COLNAME_* constants */
const char *zName, /* Pointer to buffer containing name */
void (*xDel)(void*) /* Memory management strategy for zName */
){
int rc;
Mem *pColName;
assert( idx<p->nResColumn );
assert( var<COLNAME_N );
if( p->db->mallocFailed ){
assert( !zName || xDel!=SQLITE_DYNAMIC );
return SQLITE_NOMEM_BKPT;
}
assert( p->aColName!=0 );
pColName = &(p->aColName[idx+var*p->nResColumn]);
rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
return rc;
}
/*
** A read or write transaction may or may not be active on database handle
** db. If a transaction is active, commit it. If there is a
** write-transaction spanning more than one database file, this routine
** takes care of the master journal trickery.
*/
static int vdbeCommit(sqlite3 *db, Vdbe *p){
int i;
int nTrans = 0; /* Number of databases with an active write-transaction
** that are candidates for a two-phase commit using a
** master-journal */
int rc = SQLITE_OK;
int needXcommit = 0;
#ifdef SQLITE_OMIT_VIRTUALTABLE
/* With this option, sqlite3VtabSync() is defined to be simply
** SQLITE_OK so p is not used.
*/
UNUSED_PARAMETER(p);
#endif
/* Before doing anything else, call the xSync() callback for any
** virtual module tables written in this transaction. This has to
** be done before determining whether a master journal file is
** required, as an xSync() callback may add an attached database
** to the transaction.
*/
rc = sqlite3VtabSync(db, p);
/* This loop determines (a) if the commit hook should be invoked and
** (b) how many database files have open write transactions, not
** including the temp database. (b) is important because if more than
** one database file has an open write transaction, a master journal
** file is required for an atomic commit.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( sqlite3BtreeIsInTrans(pBt) ){
/* Whether or not a database might need a master journal depends upon
** its journal mode (among other things). This matrix determines which
** journal modes use a master journal and which do not */
static const u8 aMJNeeded[] = {
/* DELETE */ 1,
/* PERSIST */ 1,
/* OFF */ 0,
/* TRUNCATE */ 1,
/* MEMORY */ 0,
/* WAL */ 0
};
Pager *pPager; /* Pager associated with pBt */
needXcommit = 1;
sqlite3BtreeEnter(pBt);
pPager = sqlite3BtreePager(pBt);
if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
&& aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
&& sqlite3PagerIsMemdb(pPager)==0
){
assert( i!=1 );
nTrans++;
}
rc = sqlite3PagerExclusiveLock(pPager);
sqlite3BtreeLeave(pBt);
}
}
if( rc!=SQLITE_OK ){
return rc;
}
/* If there are any write-transactions at all, invoke the commit hook */
if( needXcommit && db->xCommitCallback ){
rc = db->xCommitCallback(db->pCommitArg);
if( rc ){
return SQLITE_CONSTRAINT_COMMITHOOK;
}
}
/* The simple case - no more than one database file (not counting the
** TEMP database) has a transaction active. There is no need for the
** master-journal.
**
** If the return value of sqlite3BtreeGetFilename() is a zero length
** string, it means the main database is :memory: or a temp file. In
** that case we do not support atomic multi-file commits, so use the
** simple case then too.
*/
if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
|| nTrans<=1
){
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
}
}
/* Do the commit only if all databases successfully complete phase 1.
** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
** IO error while deleting or truncating a journal file. It is unlikely,
** but could happen. In this case abandon processing and return the error.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
}
}
if( rc==SQLITE_OK ){
sqlite3VtabCommit(db);
}
}
/* The complex case - There is a multi-file write-transaction active.
** This requires a master journal file to ensure the transaction is
** committed atomically.
*/
#ifndef SQLITE_OMIT_DISKIO
else{
sqlite3_vfs *pVfs = db->pVfs;
char *zMaster = 0; /* File-name for the master journal */
char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
sqlite3_file *pMaster = 0;
i64 offset = 0;
int res;
int retryCount = 0;
int nMainFile;
/* Select a master journal file name */
nMainFile = sqlite3Strlen30(zMainFile);
zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz%c%c", zMainFile, 0, 0);
if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
do {
u32 iRandom;
if( retryCount ){
if( retryCount>100 ){
sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
break;
}else if( retryCount==1 ){
sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
}
}
retryCount++;
sqlite3_randomness(sizeof(iRandom), &iRandom);
sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
(iRandom>>8)&0xffffff, iRandom&0xff);
/* The antipenultimate character of the master journal name must
** be "9" to avoid name collisions when using 8+3 filenames. */
assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
sqlite3FileSuffix3(zMainFile, zMaster);
rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
}while( rc==SQLITE_OK && res );
if( rc==SQLITE_OK ){
/* Open the master journal. */
rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
);
}
if( rc!=SQLITE_OK ){
sqlite3DbFree(db, zMaster);
return rc;
}
/* Write the name of each database file in the transaction into the new
** master journal file. If an error occurs at this point close
** and delete the master journal file. All the individual journal files
** still have 'null' as the master journal pointer, so they will roll
** back independently if a failure occurs.
*/
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( sqlite3BtreeIsInTrans(pBt) ){
char const *zFile = sqlite3BtreeGetJournalname(pBt);
if( zFile==0 ){
continue; /* Ignore TEMP and :memory: databases */
}
assert( zFile[0]!=0 );
rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
offset += sqlite3Strlen30(zFile)+1;
if( rc!=SQLITE_OK ){
sqlite3OsCloseFree(pMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
sqlite3DbFree(db, zMaster);
return rc;
}
}
}
/* Sync the master journal file. If the IOCAP_SEQUENTIAL device
** flag is set this is not required.
*/
if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
&& SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
){
sqlite3OsCloseFree(pMaster);
sqlite3OsDelete(pVfs, zMaster, 0);
sqlite3DbFree(db, zMaster);
return rc;
}
/* Sync all the db files involved in the transaction. The same call
** sets the master journal pointer in each individual journal. If
** an error occurs here, do not delete the master journal file.
**
** If the error occurs during the first call to
** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
** master journal file will be orphaned. But we cannot delete it,
** in case the master journal file name was written into the journal
** file before the failure occurred.
*/
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
}
}
sqlite3OsCloseFree(pMaster);
assert( rc!=SQLITE_BUSY );
if( rc!=SQLITE_OK ){
sqlite3DbFree(db, zMaster);
return rc;
}
/* Delete the master journal file. This commits the transaction. After
** doing this the directory is synced again before any individual
** transaction files are deleted.
*/
rc = sqlite3OsDelete(pVfs, zMaster, 1);
sqlite3DbFree(db, zMaster);
zMaster = 0;
if( rc ){
return rc;
}
/* All files and directories have already been synced, so the following
** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
** deleting or truncating journals. If something goes wrong while
** this is happening we don't really care. The integrity of the
** transaction is already guaranteed, but some stray 'cold' journals
** may be lying around. Returning an error code won't help matters.
*/
disable_simulated_io_errors();
sqlite3BeginBenignMalloc();
for(i=0; i<db->nDb; i++){
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
sqlite3BtreeCommitPhaseTwo(pBt, 1);
}
}
sqlite3EndBenignMalloc();
enable_simulated_io_errors();
sqlite3VtabCommit(db);
}
#endif
return rc;
}
/*
** This routine checks that the sqlite3.nVdbeActive count variable
** matches the number of vdbe's in the list sqlite3.pVdbe that are
** currently active. An assertion fails if the two counts do not match.
** This is an internal self-check only - it is not an essential processing
** step.
**
** This is a no-op if NDEBUG is defined.
*/
#ifndef NDEBUG
static void checkActiveVdbeCnt(sqlite3 *db){
Vdbe *p;
int cnt = 0;
int nWrite = 0;
int nRead = 0;
p = db->pVdbe;
while( p ){
if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
cnt++;
if( p->readOnly==0 ) nWrite++;
if( p->bIsReader ) nRead++;
}
p = p->pNext;
}
assert( cnt==db->nVdbeActive );
assert( nWrite==db->nVdbeWrite );
assert( nRead==db->nVdbeRead );
}
#else
#define checkActiveVdbeCnt(x)
#endif
/*
** If the Vdbe passed as the first argument opened a statement-transaction,
** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
** statement transaction is committed.
**
** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
** Otherwise SQLITE_OK.
*/
static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
sqlite3 *const db = p->db;
int rc = SQLITE_OK;
int i;
const int iSavepoint = p->iStatement-1;
assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
assert( db->nStatement>0 );
assert( p->iStatement==(db->nStatement+db->nSavepoint) );
for(i=0; i<db->nDb; i++){
int rc2 = SQLITE_OK;
Btree *pBt = db->aDb[i].pBt;
if( pBt ){
if( eOp==SAVEPOINT_ROLLBACK ){
rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
}
if( rc2==SQLITE_OK ){
rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
}
if( rc==SQLITE_OK ){
rc = rc2;
}
}
}
db->nStatement--;
p->iStatement = 0;
if( rc==SQLITE_OK ){
if( eOp==SAVEPOINT_ROLLBACK ){
rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
}
if( rc==SQLITE_OK ){
rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
}
}
/* If the statement transaction is being rolled back, also restore the
** database handles deferred constraint counter to the value it had when
** the statement transaction was opened. */
if( eOp==SAVEPOINT_ROLLBACK ){
db->nDeferredCons = p->nStmtDefCons;
db->nDeferredImmCons = p->nStmtDefImmCons;
}
return rc;
}
int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
if( p->db->nStatement && p->iStatement ){
return vdbeCloseStatement(p, eOp);
}
return SQLITE_OK;
}
/*
** This function is called when a transaction opened by the database
** handle associated with the VM passed as an argument is about to be
** committed. If there are outstanding deferred foreign key constraint
** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
**
** If there are outstanding FK violations and this function returns
** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
** and write an error message to it. Then return SQLITE_ERROR.
*/
#ifndef SQLITE_OMIT_FOREIGN_KEY
int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
sqlite3 *db = p->db;
if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
|| (!deferred && p->nFkConstraint>0)
){
p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
p->errorAction = OE_Abort;
sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
return SQLITE_ERROR;
}
return SQLITE_OK;
}
#endif
/*
** This routine is called the when a VDBE tries to halt. If the VDBE
** has made changes and is in autocommit mode, then commit those
** changes. If a rollback is needed, then do the rollback.
**
** This routine is the only way to move the state of a VM from
** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
** call this on a VM that is in the SQLITE_MAGIC_HALT state.
**
** Return an error code. If the commit could not complete because of
** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
** means the close did not happen and needs to be repeated.
*/
int sqlite3VdbeHalt(Vdbe *p){
int rc; /* Used to store transient return codes */
sqlite3 *db = p->db;
/* This function contains the logic that determines if a statement or
** transaction will be committed or rolled back as a result of the
** execution of this virtual machine.
**
** If any of the following errors occur:
**
** SQLITE_NOMEM
** SQLITE_IOERR
** SQLITE_FULL
** SQLITE_INTERRUPT
**
** Then the internal cache might have been left in an inconsistent
** state. We need to rollback the statement transaction, if there is
** one, or the complete transaction if there is no statement transaction.
*/
if( p->magic!=VDBE_MAGIC_RUN ){
return SQLITE_OK;
}
if( db->mallocFailed ){
p->rc = SQLITE_NOMEM_BKPT;
}
closeAllCursors(p);
checkActiveVdbeCnt(db);
/* No commit or rollback needed if the program never started or if the
** SQL statement does not read or write a database file. */
if( p->pc>=0 && p->bIsReader ){
int mrc; /* Primary error code from p->rc */
int eStatementOp = 0;
int isSpecialError; /* Set to true if a 'special' error */
/* Lock all btrees used by the statement */
sqlite3VdbeEnter(p);
/* Check for one of the special errors */
mrc = p->rc & 0xff;
isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
|| mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
if( isSpecialError ){
/* If the query was read-only and the error code is SQLITE_INTERRUPT,
** no rollback is necessary. Otherwise, at least a savepoint
** transaction must be rolled back to restore the database to a
** consistent state.
**
** Even if the statement is read-only, it is important to perform
** a statement or transaction rollback operation. If the error
** occurred while writing to the journal, sub-journal or database
** file as part of an effort to free up cache space (see function
** pagerStress() in pager.c), the rollback is required to restore
** the pager to a consistent state.
*/
if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
eStatementOp = SAVEPOINT_ROLLBACK;
}else{
/* We are forced to roll back the active transaction. Before doing
** so, abort any other statements this handle currently has active.
*/
sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
sqlite3CloseSavepoints(db);
db->autoCommit = 1;
p->nChange = 0;
}
}
}
/* Check for immediate foreign key violations. */
if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
sqlite3VdbeCheckFk(p, 0);
}
/* If the auto-commit flag is set and this is the only active writer
** VM, then we do either a commit or rollback of the current transaction.
**
** Note: This block also runs if one of the special errors handled
** above has occurred.
*/
if( !sqlite3VtabInSync(db)
&& db->autoCommit
&& db->nVdbeWrite==(p->readOnly==0)
){
if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
rc = sqlite3VdbeCheckFk(p, 1);
if( rc!=SQLITE_OK ){
if( NEVER(p->readOnly) ){
sqlite3VdbeLeave(p);
return SQLITE_ERROR;
}
rc = SQLITE_CONSTRAINT_FOREIGNKEY;
}else{
/* The auto-commit flag is true, the vdbe program was successful
** or hit an 'OR FAIL' constraint and there are no deferred foreign
** key constraints to hold up the transaction. This means a commit
** is required. */
rc = vdbeCommit(db, p);
}
if( rc==SQLITE_BUSY && p->readOnly ){
sqlite3VdbeLeave(p);
return SQLITE_BUSY;
}else if( rc!=SQLITE_OK ){
p->rc = rc;
sqlite3RollbackAll(db, SQLITE_OK);
p->nChange = 0;
}else{
db->nDeferredCons = 0;
db->nDeferredImmCons = 0;
db->flags &= ~(u64)SQLITE_DeferFKs;
sqlite3CommitInternalChanges(db);
}
}else{
sqlite3RollbackAll(db, SQLITE_OK);
p->nChange = 0;
}
db->nStatement = 0;
}else if( eStatementOp==0 ){
if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
eStatementOp = SAVEPOINT_RELEASE;
}else if( p->errorAction==OE_Abort ){
eStatementOp = SAVEPOINT_ROLLBACK;
}else{
sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
sqlite3CloseSavepoints(db);
db->autoCommit = 1;
p->nChange = 0;
}
}
/* If eStatementOp is non-zero, then a statement transaction needs to
** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
** do so. If this operation returns an error, and the current statement
** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
** current statement error code.
*/
if( eStatementOp ){
rc = sqlite3VdbeCloseStatement(p, eStatementOp);
if( rc ){
if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
p->rc = rc;
sqlite3DbFree(db, p->zErrMsg);
p->zErrMsg = 0;
}
sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
sqlite3CloseSavepoints(db);
db->autoCommit = 1;
p->nChange = 0;
}
}
/* If this was an INSERT, UPDATE or DELETE and no statement transaction
** has been rolled back, update the database connection change-counter.
*/
if( p->changeCntOn ){
if( eStatementOp!=SAVEPOINT_ROLLBACK ){
sqlite3VdbeSetChanges(db, p->nChange);
}else{
sqlite3VdbeSetChanges(db, 0);
}
p->nChange = 0;
}
/* Release the locks */
sqlite3VdbeLeave(p);
}
/* We have successfully halted and closed the VM. Record this fact. */
if( p->pc>=0 ){
db->nVdbeActive--;
if( !p->readOnly ) db->nVdbeWrite--;
if( p->bIsReader ) db->nVdbeRead--;
assert( db->nVdbeActive>=db->nVdbeRead );
assert( db->nVdbeRead>=db->nVdbeWrite );
assert( db->nVdbeWrite>=0 );
}
p->magic = VDBE_MAGIC_HALT;
checkActiveVdbeCnt(db);
if( db->mallocFailed ){
p->rc = SQLITE_NOMEM_BKPT;
}
/* If the auto-commit flag is set to true, then any locks that were held
** by connection db have now been released. Call sqlite3ConnectionUnlocked()
** to invoke any required unlock-notify callbacks.
*/
if( db->autoCommit ){
sqlite3ConnectionUnlocked(db);
}
assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
}
/*
** Each VDBE holds the result of the most recent sqlite3_step() call
** in p->rc. This routine sets that result back to SQLITE_OK.
*/
void sqlite3VdbeResetStepResult(Vdbe *p){
p->rc = SQLITE_OK;
}
/*
** Copy the error code and error message belonging to the VDBE passed
** as the first argument to its database handle (so that they will be
** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
**
** This function does not clear the VDBE error code or message, just
** copies them to the database handle.
*/
int sqlite3VdbeTransferError(Vdbe *p){
sqlite3 *db = p->db;
int rc = p->rc;
if( p->zErrMsg ){
db->bBenignMalloc++;
sqlite3BeginBenignMalloc();
if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
sqlite3EndBenignMalloc();
db->bBenignMalloc--;
}else if( db->pErr ){
sqlite3ValueSetNull(db->pErr);
}
db->errCode = rc;
return rc;
}
#ifdef SQLITE_ENABLE_SQLLOG
/*
** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
** invoke it.
*/
static void vdbeInvokeSqllog(Vdbe *v){
if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
assert( v->db->init.busy==0 );
if( zExpanded ){
sqlite3GlobalConfig.xSqllog(
sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
);
sqlite3DbFree(v->db, zExpanded);
}
}
}
#else
# define vdbeInvokeSqllog(x)
#endif
/*
** Clean up a VDBE after execution but do not delete the VDBE just yet.
** Write any error messages into *pzErrMsg. Return the result code.
**
** After this routine is run, the VDBE should be ready to be executed
** again.
**
** To look at it another way, this routine resets the state of the
** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
** VDBE_MAGIC_INIT.
*/
int sqlite3VdbeReset(Vdbe *p){
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
int i;
#endif
sqlite3 *db;
db = p->db;
/* If the VM did not run to completion or if it encountered an
** error, then it might not have been halted properly. So halt
** it now.
*/
sqlite3VdbeHalt(p);
/* If the VDBE has been run even partially, then transfer the error code
** and error message from the VDBE into the main database structure. But
** if the VDBE has just been set to run but has not actually executed any
** instructions yet, leave the main database error information unchanged.
*/
if( p->pc>=0 ){
vdbeInvokeSqllog(p);
sqlite3VdbeTransferError(p);
if( p->runOnlyOnce ) p->expired = 1;
}else if( p->rc && p->expired ){
/* The expired flag was set on the VDBE before the first call
** to sqlite3_step(). For consistency (since sqlite3_step() was
** called), set the database error in this case as well.
*/
sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
}
/* Reset register contents and reclaim error message memory.
*/
#ifdef SQLITE_DEBUG
/* Execute assert() statements to ensure that the Vdbe.apCsr[] and
** Vdbe.aMem[] arrays have already been cleaned up. */
if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
if( p->aMem ){
for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
}
#endif
sqlite3DbFree(db, p->zErrMsg);
p->zErrMsg = 0;
p->pResultSet = 0;
#ifdef SQLITE_DEBUG
p->nWrite = 0;
#endif
/* Save profiling information from this VDBE run.
*/
#ifdef VDBE_PROFILE
{
FILE *out = fopen("vdbe_profile.out", "a");
if( out ){
fprintf(out, "---- ");
for(i=0; i<p->nOp; i++){
fprintf(out, "%02x", p->aOp[i].opcode);
}
fprintf(out, "\n");
if( p->zSql ){
char c, pc = 0;
fprintf(out, "-- ");
for(i=0; (c = p->zSql[i])!=0; i++){
if( pc=='\n' ) fprintf(out, "-- ");
putc(c, out);
pc = c;
}
if( pc!='\n' ) fprintf(out, "\n");
}
for(i=0; i<p->nOp; i++){
char zHdr[100];
sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
p->aOp[i].cnt,
p->aOp[i].cycles,
p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
);
fprintf(out, "%s", zHdr);
sqlite3VdbePrintOp(out, i, &p->aOp[i]);
}
fclose(out);
}
}
#endif
p->magic = VDBE_MAGIC_RESET;
return p->rc & db->errMask;
}
/*
** Clean up and delete a VDBE after execution. Return an integer which is
** the result code. Write any error message text into *pzErrMsg.
*/
int sqlite3VdbeFinalize(Vdbe *p){
int rc = SQLITE_OK;
if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
rc = sqlite3VdbeReset(p);
assert( (rc & p->db->errMask)==rc );
}
sqlite3VdbeDelete(p);
return rc;
}
/*
** If parameter iOp is less than zero, then invoke the destructor for
** all auxiliary data pointers currently cached by the VM passed as
** the first argument.
**
** Or, if iOp is greater than or equal to zero, then the destructor is
** only invoked for those auxiliary data pointers created by the user
** function invoked by the OP_Function opcode at instruction iOp of
** VM pVdbe, and only then if:
**
** * the associated function parameter is the 32nd or later (counting
** from left to right), or
**
** * the corresponding bit in argument mask is clear (where the first
** function parameter corresponds to bit 0 etc.).
*/
void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
while( *pp ){
AuxData *pAux = *pp;
if( (iOp<0)
|| (pAux->iAuxOp==iOp
&& pAux->iAuxArg>=0
&& (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
){
testcase( pAux->iAuxArg==31 );
if( pAux->xDeleteAux ){
pAux->xDeleteAux(pAux->pAux);
}
*pp = pAux->pNextAux;
sqlite3DbFree(db, pAux);
}else{
pp= &pAux->pNextAux;
}
}
}
/*
** Free all memory associated with the Vdbe passed as the second argument,
** except for object itself, which is preserved.
**
** The difference between this function and sqlite3VdbeDelete() is that
** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
** the database connection and frees the object itself.
*/
void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
SubProgram *pSub, *pNext;
assert( p->db==0 || p->db==db );
releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
for(pSub=p->pProgram; pSub; pSub=pNext){
pNext = pSub->pNext;
vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
sqlite3DbFree(db, pSub);
}
if( p->magic!=VDBE_MAGIC_INIT ){
releaseMemArray(p->aVar, p->nVar);
sqlite3DbFree(db, p->pVList);
sqlite3DbFree(db, p->pFree);
}
vdbeFreeOpArray(db, p->aOp, p->nOp);
sqlite3DbFree(db, p->aColName);
sqlite3DbFree(db, p->zSql);
#ifdef SQLITE_ENABLE_NORMALIZE
sqlite3DbFree(db, p->zNormSql);
{
DblquoteStr *pThis, *pNext;
for(pThis=p->pDblStr; pThis; pThis=pNext){
pNext = pThis->pNextStr;
sqlite3DbFree(db, pThis);
}
}
#endif
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
{
int i;
for(i=0; i<p->nScan; i++){
sqlite3DbFree(db, p->aScan[i].zName);
}
sqlite3DbFree(db, p->aScan);
}
#endif
}
/*
** Delete an entire VDBE.
*/
void sqlite3VdbeDelete(Vdbe *p){
sqlite3 *db;
assert( p!=0 );
db = p->db;
assert( sqlite3_mutex_held(db->mutex) );
sqlite3VdbeClearObject(db, p);
if( p->pPrev ){
p->pPrev->pNext = p->pNext;
}else{
assert( db->pVdbe==p );
db->pVdbe = p->pNext;
}
if( p->pNext ){
p->pNext->pPrev = p->pPrev;
}
p->magic = VDBE_MAGIC_DEAD;
p->db = 0;
sqlite3DbFreeNN(db, p);
}
/*
** The cursor "p" has a pending seek operation that has not yet been
** carried out. Seek the cursor now. If an error occurs, return
** the appropriate error code.
*/
static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
int res, rc;
#ifdef SQLITE_TEST
extern int sqlite3_search_count;
#endif
assert( p->deferredMoveto );
assert( p->isTable );
assert( p->eCurType==CURTYPE_BTREE );
rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
if( rc ) return rc;
if( res!=0 ) return SQLITE_CORRUPT_BKPT;
#ifdef SQLITE_TEST
sqlite3_search_count++;
#endif
p->deferredMoveto = 0;
p->cacheStatus = CACHE_STALE;
return SQLITE_OK;
}
/*
** Something has moved cursor "p" out of place. Maybe the row it was
** pointed to was deleted out from under it. Or maybe the btree was
** rebalanced. Whatever the cause, try to restore "p" to the place it
** is supposed to be pointing. If the row was deleted out from under the
** cursor, set the cursor to point to a NULL row.
*/
static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
int isDifferentRow, rc;
assert( p->eCurType==CURTYPE_BTREE );
assert( p->uc.pCursor!=0 );
assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
p->cacheStatus = CACHE_STALE;
if( isDifferentRow ) p->nullRow = 1;
return rc;
}
/*
** Check to ensure that the cursor is valid. Restore the cursor
** if need be. Return any I/O error from the restore operation.
*/
int sqlite3VdbeCursorRestore(VdbeCursor *p){
assert( p->eCurType==CURTYPE_BTREE );
if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
return handleMovedCursor(p);
}
return SQLITE_OK;
}
/*
** Make sure the cursor p is ready to read or write the row to which it
** was last positioned. Return an error code if an OOM fault or I/O error
** prevents us from positioning the cursor to its correct position.
**
** If a MoveTo operation is pending on the given cursor, then do that
** MoveTo now. If no move is pending, check to see if the row has been
** deleted out from under the cursor and if it has, mark the row as
** a NULL row.
**
** If the cursor is already pointing to the correct row and that row has
** not been deleted out from under the cursor, then this routine is a no-op.
*/
int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
VdbeCursor *p = *pp;
assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
if( p->deferredMoveto ){
int iMap;
if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
*pp = p->pAltCursor;
*piCol = iMap - 1;
return SQLITE_OK;
}
return handleDeferredMoveto(p);
}
if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
return handleMovedCursor(p);
}
return SQLITE_OK;
}
/*
** The following functions:
**
** sqlite3VdbeSerialType()
** sqlite3VdbeSerialTypeLen()
** sqlite3VdbeSerialLen()
** sqlite3VdbeSerialPut()
** sqlite3VdbeSerialGet()
**
** encapsulate the code that serializes values for storage in SQLite
** data and index records. Each serialized value consists of a
** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
** integer, stored as a varint.
**
** In an SQLite index record, the serial type is stored directly before
** the blob of data that it corresponds to. In a table record, all serial
** types are stored at the start of the record, and the blobs of data at
** the end. Hence these functions allow the caller to handle the
** serial-type and data blob separately.
**
** The following table describes the various storage classes for data:
**
** serial type bytes of data type
** -------------- --------------- ---------------
** 0 0 NULL
** 1 1 signed integer
** 2 2 signed integer
** 3 3 signed integer
** 4 4 signed integer
** 5 6 signed integer
** 6 8 signed integer
** 7 8 IEEE float
** 8 0 Integer constant 0
** 9 0 Integer constant 1
** 10,11 reserved for expansion
** N>=12 and even (N-12)/2 BLOB
** N>=13 and odd (N-13)/2 text
**
** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
** of SQLite will not understand those serial types.
*/
#if 0 /* Inlined into the OP_MakeRecord opcode */
/*
** Return the serial-type for the value stored in pMem.
**
** This routine might convert a large MEM_IntReal value into MEM_Real.
**
** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
** opcode in the byte-code engine. But by moving this routine in-line, we
** can omit some redundant tests and make that opcode a lot faster. So
** this routine is now only used by the STAT3 logic and STAT3 support has
** ended. The code is kept here for historical reference only.
*/
u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
int flags = pMem->flags;
u32 n;
assert( pLen!=0 );
if( flags&MEM_Null ){
*pLen = 0;
return 0;
}
if( flags&(MEM_Int|MEM_IntReal) ){
/* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
i64 i = pMem->u.i;
u64 u;
testcase( flags & MEM_Int );
testcase( flags & MEM_IntReal );
if( i<0 ){
u = ~i;
}else{
u = i;
}
if( u<=127 ){
if( (i&1)==i && file_format>=4 ){
*pLen = 0;
return 8+(u32)u;
}else{
*pLen = 1;
return 1;
}
}
if( u<=32767 ){ *pLen = 2; return 2; }
if( u<=8388607 ){ *pLen = 3; return 3; }
if( u<=2147483647 ){ *pLen = 4; return 4; }
if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
*pLen = 8;
if( flags&MEM_IntReal ){
/* If the value is IntReal and is going to take up 8 bytes to store
** as an integer, then we might as well make it an 8-byte floating
** point value */
pMem->u.r = (double)pMem->u.i;
pMem->flags &= ~MEM_IntReal;
pMem->flags |= MEM_Real;
return 7;
}
return 6;
}
if( flags&MEM_Real ){
*pLen = 8;
return 7;
}
assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
assert( pMem->n>=0 );
n = (u32)pMem->n;
if( flags & MEM_Zero ){
n += pMem->u.nZero;
}
*pLen = n;
return ((n*2) + 12 + ((flags&MEM_Str)!=0));
}
#endif /* inlined into OP_MakeRecord */
/*
** The sizes for serial types less than 128
*/
static const u8 sqlite3SmallTypeSizes[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
/* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
/* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
/* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
/* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
/* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
/* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
/* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
/* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
/* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
/* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
/* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
/* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
};
/*
** Return the length of the data corresponding to the supplied serial-type.
*/
u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
if( serial_type>=128 ){
return (serial_type-12)/2;
}else{
assert( serial_type<12
|| sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
return sqlite3SmallTypeSizes[serial_type];
}
}
u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
assert( serial_type<128 );
return sqlite3SmallTypeSizes[serial_type];
}
/*
** If we are on an architecture with mixed-endian floating
** points (ex: ARM7) then swap the lower 4 bytes with the
** upper 4 bytes. Return the result.
**
** For most architectures, this is a no-op.
**
** (later): It is reported to me that the mixed-endian problem
** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
** that early versions of GCC stored the two words of a 64-bit
** float in the wrong order. And that error has been propagated
** ever since. The blame is not necessarily with GCC, though.
** GCC might have just copying the problem from a prior compiler.
** I am also told that newer versions of GCC that follow a different
** ABI get the byte order right.
**
** Developers using SQLite on an ARM7 should compile and run their
** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
** enabled, some asserts below will ensure that the byte order of
** floating point values is correct.
**
** (2007-08-30) Frank van Vugt has studied this problem closely
** and has send his findings to the SQLite developers. Frank
** writes that some Linux kernels offer floating point hardware
** emulation that uses only 32-bit mantissas instead of a full
** 48-bits as required by the IEEE standard. (This is the
** CONFIG_FPE_FASTFPE option.) On such systems, floating point
** byte swapping becomes very complicated. To avoid problems,
** the necessary byte swapping is carried out using a 64-bit integer
** rather than a 64-bit float. Frank assures us that the code here
** works for him. We, the developers, have no way to independently
** verify this, but Frank seems to know what he is talking about
** so we trust him.
*/
#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
static u64 floatSwap(u64 in){
union {
u64 r;
u32 i[2];
} u;
u32 t;
u.r = in;
t = u.i[0];
u.i[0] = u.i[1];
u.i[1] = t;
return u.r;
}
# define swapMixedEndianFloat(X) X = floatSwap(X)
#else
# define swapMixedEndianFloat(X)
#endif
/*
** Write the serialized data blob for the value stored in pMem into
** buf. It is assumed that the caller has allocated sufficient space.
** Return the number of bytes written.
**
** nBuf is the amount of space left in buf[]. The caller is responsible
** for allocating enough space to buf[] to hold the entire field, exclusive
** of the pMem->u.nZero bytes for a MEM_Zero value.
**
** Return the number of bytes actually written into buf[]. The number
** of bytes in the zero-filled tail is included in the return value only
** if those bytes were zeroed in buf[].
*/
u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
u32 len;
/* Integer and Real */
if( serial_type<=7 && serial_type>0 ){
u64 v;
u32 i;
if( serial_type==7 ){
assert( sizeof(v)==sizeof(pMem->u.r) );
memcpy(&v, &pMem->u.r, sizeof(v));
swapMixedEndianFloat(v);
}else{
v = pMem->u.i;
}
len = i = sqlite3SmallTypeSizes[serial_type];
assert( i>0 );
do{
buf[--i] = (u8)(v&0xFF);
v >>= 8;
}while( i );
return len;
}
/* String or blob */
if( serial_type>=12 ){
assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
== (int)sqlite3VdbeSerialTypeLen(serial_type) );
len = pMem->n;
if( len>0 ) memcpy(buf, pMem->z, len);
return len;
}
/* NULL or constants 0 or 1 */
return 0;
}
/* Input "x" is a sequence of unsigned characters that represent a
** big-endian integer. Return the equivalent native integer
*/
#define ONE_BYTE_INT(x) ((i8)(x)[0])
#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
/*
** Deserialize the data blob pointed to by buf as serial type serial_type
** and store the result in pMem. Return the number of bytes read.
**
** This function is implemented as two separate routines for performance.
** The few cases that require local variables are broken out into a separate
** routine so that in most cases the overhead of moving the stack pointer
** is avoided.
*/
static u32 serialGet(
const unsigned char *buf, /* Buffer to deserialize from */
u32 serial_type, /* Serial type to deserialize */
Mem *pMem /* Memory cell to write value into */
){
u64 x = FOUR_BYTE_UINT(buf);
u32 y = FOUR_BYTE_UINT(buf+4);
x = (x<<32) + y;
if( serial_type==6 ){
/* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
** twos-complement integer. */
pMem->u.i = *(i64*)&x;
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
}else{
/* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
** floating point number. */
#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
/* Verify that integers and floating point values use the same
** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
** defined that 64-bit floating point values really are mixed
** endian.
*/
static const u64 t1 = ((u64)0x3ff00000)<<32;
static const double r1 = 1.0;
u64 t2 = t1;
swapMixedEndianFloat(t2);
assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
#endif
assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
swapMixedEndianFloat(x);
memcpy(&pMem->u.r, &x, sizeof(x));
pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
}
return 8;
}
u32 sqlite3VdbeSerialGet(
const unsigned char *buf, /* Buffer to deserialize from */
u32 serial_type, /* Serial type to deserialize */
Mem *pMem /* Memory cell to write value into */
){
switch( serial_type ){
case 10: { /* Internal use only: NULL with virtual table
** UPDATE no-change flag set */
pMem->flags = MEM_Null|MEM_Zero;
pMem->n = 0;
pMem->u.nZero = 0;
break;
}
case 11: /* Reserved for future use */
case 0: { /* Null */
/* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
pMem->flags = MEM_Null;
break;
}
case 1: {
/* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
** integer. */
pMem->u.i = ONE_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 1;
}
case 2: { /* 2-byte signed integer */
/* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
** twos-complement integer. */
pMem->u.i = TWO_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 2;
}
case 3: { /* 3-byte signed integer */
/* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
** twos-complement integer. */
pMem->u.i = THREE_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 3;
}
case 4: { /* 4-byte signed integer */
/* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
** twos-complement integer. */
pMem->u.i = FOUR_BYTE_INT(buf);
#ifdef __HP_cc
/* Work around a sign-extension bug in the HP compiler for HP/UX */
if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
#endif
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 4;
}
case 5: { /* 6-byte signed integer */
/* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
** twos-complement integer. */
pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
pMem->flags = MEM_Int;
testcase( pMem->u.i<0 );
return 6;
}
case 6: /* 8-byte signed integer */
case 7: { /* IEEE floating point */
/* These use local variables, so do them in a separate routine
** to avoid having to move the frame pointer in the common case */
return serialGet(buf,serial_type,pMem);
}
case 8: /* Integer 0 */
case 9: { /* Integer 1 */
/* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
/* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
pMem->u.i = serial_type-8;
pMem->flags = MEM_Int;
return 0;
}
default: {
/* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
** length.
** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
** (N-13)/2 bytes in length. */
static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
pMem->z = (char *)buf;
pMem->n = (serial_type-12)/2;
pMem->flags = aFlag[serial_type&1];
return pMem->n;
}
}
return 0;
}
/*
** This routine is used to allocate sufficient space for an UnpackedRecord
** structure large enough to be used with sqlite3VdbeRecordUnpack() if
** the first argument is a pointer to KeyInfo structure pKeyInfo.
**
** The space is either allocated using sqlite3DbMallocRaw() or from within
** the unaligned buffer passed via the second and third arguments (presumably
** stack space). If the former, then *ppFree is set to a pointer that should
** be eventually freed by the caller using sqlite3DbFree(). Or, if the
** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
** before returning.
**
** If an OOM error occurs, NULL is returned.
*/
UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
KeyInfo *pKeyInfo /* Description of the record */
){
UnpackedRecord *p; /* Unpacked record to return */
int nByte; /* Number of bytes required for *p */
nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
if( !p ) return 0;
p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
assert( pKeyInfo->aSortFlags!=0 );
p->pKeyInfo = pKeyInfo;
p->nField = pKeyInfo->nKeyField + 1;
return p;
}
/*
** Given the nKey-byte encoding of a record in pKey[], populate the
** UnpackedRecord structure indicated by the fourth argument with the
** contents of the decoded record.
*/
void sqlite3VdbeRecordUnpack(
KeyInfo *pKeyInfo, /* Information about the record format */
int nKey, /* Size of the binary record */
const void *pKey, /* The binary record */
UnpackedRecord *p /* Populate this structure before returning. */
){
const unsigned char *aKey = (const unsigned char *)pKey;
u32 d;
u32 idx; /* Offset in aKey[] to read from */
u16 u; /* Unsigned loop counter */
u32 szHdr;
Mem *pMem = p->aMem;
p->default_rc = 0;
assert( EIGHT_BYTE_ALIGNMENT(pMem) );
idx = getVarint32(aKey, szHdr);
d = szHdr;
u = 0;
while( idx<szHdr && d<=(u32)nKey ){
u32 serial_type;
idx += getVarint32(&aKey[idx], serial_type);
pMem->enc = pKeyInfo->enc;
pMem->db = pKeyInfo->db;
/* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
pMem->szMalloc = 0;
pMem->z = 0;
d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
pMem++;
if( (++u)>=p->nField ) break;
}
if( d>(u32)nKey && u ){
assert( CORRUPT_DB );
/* In a corrupt record entry, the last pMem might have been set up using
** uninitialized memory. Overwrite its value with NULL, to prevent
** warnings from MSAN. */
sqlite3VdbeMemSetNull(pMem-1);
}
assert( u<=pKeyInfo->nKeyField + 1 );
p->nField = u;
}
#ifdef SQLITE_DEBUG
/*
** This function compares two index or table record keys in the same way
** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
** this function deserializes and compares values using the
** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
** in assert() statements to ensure that the optimized code in
** sqlite3VdbeRecordCompare() returns results with these two primitives.
**
** Return true if the result of comparison is equivalent to desiredResult.
** Return false if there is a disagreement.
*/
static int vdbeRecordCompareDebug(
int nKey1, const void *pKey1, /* Left key */
const UnpackedRecord *pPKey2, /* Right key */
int desiredResult /* Correct answer */
){
u32 d1; /* Offset into aKey[] of next data element */
u32 idx1; /* Offset into aKey[] of next header element */
u32 szHdr1; /* Number of bytes in header */
int i = 0;
int rc = 0;
const unsigned char *aKey1 = (const unsigned char *)pKey1;
KeyInfo *pKeyInfo;
Mem mem1;
pKeyInfo = pPKey2->pKeyInfo;
if( pKeyInfo->db==0 ) return 1;
mem1.enc = pKeyInfo->enc;
mem1.db = pKeyInfo->db;
/* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
/* Compilers may complain that mem1.u.i is potentially uninitialized.
** We could initialize it, as shown here, to silence those complaints.
** But in fact, mem1.u.i will never actually be used uninitialized, and doing
** the unnecessary initialization has a measurable negative performance
** impact, since this routine is a very high runner. And so, we choose
** to ignore the compiler warnings and leave this variable uninitialized.
*/
/* mem1.u.i = 0; // not needed, here to silence compiler warning */
idx1 = getVarint32(aKey1, szHdr1);
if( szHdr1>98307 ) return SQLITE_CORRUPT;
d1 = szHdr1;
assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
assert( pKeyInfo->aSortFlags!=0 );
assert( pKeyInfo->nKeyField>0 );
assert( idx1<=szHdr1 || CORRUPT_DB );
do{
u32 serial_type1;
/* Read the serial types for the next element in each key. */
idx1 += getVarint32( aKey1+idx1, serial_type1 );
/* Verify that there is enough key space remaining to avoid
** a buffer overread. The "d1+serial_type1+2" subexpression will
** always be greater than or equal to the amount of required key space.
** Use that approximation to avoid the more expensive call to
** sqlite3VdbeSerialTypeLen() in the common case.
*/
if( d1+(u64)serial_type1+2>(u64)nKey1
&& d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
){
break;
}
/* Extract the values to be compared.
*/
d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
/* Do the comparison
*/
rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
if( rc!=0 ){
assert( mem1.szMalloc==0 ); /* See comment below */
if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
&& ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
){
rc = -rc;
}
if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
rc = -rc; /* Invert the result for DESC sort order. */
}
goto debugCompareEnd;
}
i++;
}while( idx1<szHdr1 && i<pPKey2->nField );
/* No memory allocation is ever used on mem1. Prove this using
** the following assert(). If the assert() fails, it indicates a
** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
*/
assert( mem1.szMalloc==0 );
/* rc==0 here means that one of the keys ran out of fields and
** all the fields up to that point were equal. Return the default_rc
** value. */
rc = pPKey2->default_rc;
debugCompareEnd:
if( desiredResult==0 && rc==0 ) return 1;
if( desiredResult<0 && rc<0 ) return 1;
if( desiredResult>0 && rc>0 ) return 1;
if( CORRUPT_DB ) return 1;
if( pKeyInfo->db->mallocFailed ) return 1;
return 0;
}
#endif
#ifdef SQLITE_DEBUG
/*
** Count the number of fields (a.k.a. columns) in the record given by
** pKey,nKey. The verify that this count is less than or equal to the
** limit given by pKeyInfo->nAllField.
**
** If this constraint is not satisfied, it means that the high-speed
** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
** not work correctly. If this assert() ever fires, it probably means
** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
** incorrectly.
*/
static void vdbeAssertFieldCountWithinLimits(
int nKey, const void *pKey, /* The record to verify */
const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
){
int nField = 0;
u32 szHdr;
u32 idx;
u32 notUsed;
const unsigned char *aKey = (const unsigned char*)pKey;
if( CORRUPT_DB ) return;
idx = getVarint32(aKey, szHdr);
assert( nKey>=0 );
assert( szHdr<=(u32)nKey );
while( idx<szHdr ){
idx += getVarint32(aKey+idx, notUsed);
nField++;
}
assert( nField <= pKeyInfo->nAllField );
}
#else
# define vdbeAssertFieldCountWithinLimits(A,B,C)
#endif
/*
** Both *pMem1 and *pMem2 contain string values. Compare the two values
** using the collation sequence pColl. As usual, return a negative , zero
** or positive value if *pMem1 is less than, equal to or greater than
** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
*/
static int vdbeCompareMemString(
const Mem *pMem1,
const Mem *pMem2,
const CollSeq *pColl,
u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
){
if( pMem1->enc==pColl->enc ){
/* The strings are already in the correct encoding. Call the
** comparison function directly */
return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
}else{
int rc;
const void *v1, *v2;
Mem c1;
Mem c2;
sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
if( (v1==0 || v2==0) ){
if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
rc = 0;
}else{
rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
}
sqlite3VdbeMemRelease(&c1);
sqlite3VdbeMemRelease(&c2);
return rc;
}
}
/*
** The input pBlob is guaranteed to be a Blob that is not marked
** with MEM_Zero. Return true if it could be a zero-blob.
*/
static int isAllZero(const char *z, int n){
int i;
for(i=0; i<n; i++){
if( z[i] ) return 0;
}
return 1;
}
/*
** Compare two blobs. Return negative, zero, or positive if the first
** is less than, equal to, or greater than the second, respectively.
** If one blob is a prefix of the other, then the shorter is the lessor.
*/
SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
int c;
int n1 = pB1->n;
int n2 = pB2->n;
/* It is possible to have a Blob value that has some non-zero content
** followed by zero content. But that only comes up for Blobs formed
** by the OP_MakeRecord opcode, and such Blobs never get passed into
** sqlite3MemCompare(). */
assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
if( (pB1->flags|pB2->flags) & MEM_Zero ){
if( pB1->flags & pB2->flags & MEM_Zero ){
return pB1->u.nZero - pB2->u.nZero;
}else if( pB1->flags & MEM_Zero ){
if( !isAllZero(pB2->z, pB2->n) ) return -1;
return pB1->u.nZero - n2;
}else{
if( !isAllZero(pB1->z, pB1->n) ) return +1;
return n1 - pB2->u.nZero;
}
}
c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
if( c ) return c;
return n1 - n2;
}
/*
** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
** number. Return negative, zero, or positive if the first (i64) is less than,
** equal to, or greater than the second (double).
*/
static int sqlite3IntFloatCompare(i64 i, double r){
if( sizeof(LONGDOUBLE_TYPE)>8 ){
LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
if( x<r ) return -1;
if( x>r ) return +1;
return 0;
}else{
i64 y;
double s;
if( r<-9223372036854775808.0 ) return +1;
if( r>=9223372036854775808.0 ) return -1;
y = (i64)r;
if( i<y ) return -1;
if( i>y ) return +1;
s = (double)i;
if( s<r ) return -1;
if( s>r ) return +1;
return 0;
}
}
/*
** Compare the values contained by the two memory cells, returning
** negative, zero or positive if pMem1 is less than, equal to, or greater
** than pMem2. Sorting order is NULL's first, followed by numbers (integers
** and reals) sorted numerically, followed by text ordered by the collating
** sequence pColl and finally blob's ordered by memcmp().
**
** Two NULL values are considered equal by this function.
*/
int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
int f1, f2;
int combined_flags;
f1 = pMem1->flags;
f2 = pMem2->flags;
combined_flags = f1|f2;
assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
/* If one value is NULL, it is less than the other. If both values
** are NULL, return 0.
*/
if( combined_flags&MEM_Null ){
return (f2&MEM_Null) - (f1&MEM_Null);
}
/* At least one of the two values is a number
*/
if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
testcase( combined_flags & MEM_Int );
testcase( combined_flags & MEM_Real );
testcase( combined_flags & MEM_IntReal );
if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
testcase( f1 & f2 & MEM_Int );
testcase( f1 & f2 & MEM_IntReal );
if( pMem1->u.i < pMem2->u.i ) return -1;
if( pMem1->u.i > pMem2->u.i ) return +1;
return 0;
}
if( (f1 & f2 & MEM_Real)!=0 ){
if( pMem1->u.r < pMem2->u.r ) return -1;
if( pMem1->u.r > pMem2->u.r ) return +1;
return 0;
}
if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
testcase( f1 & MEM_Int );
testcase( f1 & MEM_IntReal );
if( (f2&MEM_Real)!=0 ){
return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
}else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
if( pMem1->u.i < pMem2->u.i ) return -1;
if( pMem1->u.i > pMem2->u.i ) return +1;
return 0;
}else{
return -1;
}
}
if( (f1&MEM_Real)!=0 ){
if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
testcase( f2 & MEM_Int );
testcase( f2 & MEM_IntReal );
return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
}else{
return -1;
}
}
return +1;
}
/* If one value is a string and the other is a blob, the string is less.
** If both are strings, compare using the collating functions.
*/
if( combined_flags&MEM_Str ){
if( (f1 & MEM_Str)==0 ){
return 1;
}
if( (f2 & MEM_Str)==0 ){
return -1;
}
assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
assert( pMem1->enc==SQLITE_UTF8 ||
pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
/* The collation sequence must be defined at this point, even if
** the user deletes the collation sequence after the vdbe program is
** compiled (this was not always the case).
*/
assert( !pColl || pColl->xCmp );
if( pColl ){
return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
}
/* If a NULL pointer was passed as the collate function, fall through
** to the blob case and use memcmp(). */
}
/* Both values must be blobs. Compare using memcmp(). */
return sqlite3BlobCompare(pMem1, pMem2);
}
/*
** The first argument passed to this function is a serial-type that
** corresponds to an integer - all values between 1 and 9 inclusive
** except 7. The second points to a buffer containing an integer value
** serialized according to serial_type. This function deserializes
** and returns the value.
*/
static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
u32 y;
assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
switch( serial_type ){
case 0:
case 1:
testcase( aKey[0]&0x80 );
return ONE_BYTE_INT(aKey);
case 2:
testcase( aKey[0]&0x80 );
return TWO_BYTE_INT(aKey);
case 3:
testcase( aKey[0]&0x80 );
return THREE_BYTE_INT(aKey);
case 4: {
testcase( aKey[0]&0x80 );
y = FOUR_BYTE_UINT(aKey);
return (i64)*(int*)&y;
}
case 5: {
testcase( aKey[0]&0x80 );
return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
}
case 6: {
u64 x = FOUR_BYTE_UINT(aKey);
testcase( aKey[0]&0x80 );
x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
return (i64)*(i64*)&x;
}
}
return (serial_type - 8);
}
/*
** This function compares the two table rows or index records
** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
** or positive integer if key1 is less than, equal to or
** greater than key2. The {nKey1, pKey1} key must be a blob
** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
** key must be a parsed key such as obtained from
** sqlite3VdbeParseRecord.
**
** If argument bSkip is non-zero, it is assumed that the caller has already
** determined that the first fields of the keys are equal.
**
** Key1 and Key2 do not have to contain the same number of fields. If all
** fields that appear in both keys are equal, then pPKey2->default_rc is
** returned.
**
** If database corruption is discovered, set pPKey2->errCode to
** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
*/
int sqlite3VdbeRecordCompareWithSkip(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2, /* Right key */
int bSkip /* If true, skip the first field */
){
u32 d1; /* Offset into aKey[] of next data element */
int i; /* Index of next field to compare */
u32 szHdr1; /* Size of record header in bytes */
u32 idx1; /* Offset of first type in header */
int rc = 0; /* Return value */
Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
KeyInfo *pKeyInfo;
const unsigned char *aKey1 = (const unsigned char *)pKey1;
Mem mem1;
/* If bSkip is true, then the caller has already determined that the first
** two elements in the keys are equal. Fix the various stack variables so
** that this routine begins comparing at the second field. */
if( bSkip ){
u32 s1;
idx1 = 1 + getVarint32(&aKey1[1], s1);
szHdr1 = aKey1[0];
d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
i = 1;
pRhs++;
}else{
idx1 = getVarint32(aKey1, szHdr1);
d1 = szHdr1;
i = 0;
}
if( d1>(unsigned)nKey1 ){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}
VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
|| CORRUPT_DB );
assert( pPKey2->pKeyInfo->aSortFlags!=0 );
assert( pPKey2->pKeyInfo->nKeyField>0 );
assert( idx1<=szHdr1 || CORRUPT_DB );
do{
u32 serial_type;
/* RHS is an integer */
if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
testcase( pRhs->flags & MEM_Int );
testcase( pRhs->flags & MEM_IntReal );
serial_type = aKey1[idx1];
testcase( serial_type==12 );
if( serial_type>=10 ){
rc = +1;
}else if( serial_type==0 ){
rc = -1;
}else if( serial_type==7 ){
sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
}else{
i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
i64 rhs = pRhs->u.i;
if( lhs<rhs ){
rc = -1;
}else if( lhs>rhs ){
rc = +1;
}
}
}
/* RHS is real */
else if( pRhs->flags & MEM_Real ){
serial_type = aKey1[idx1];
if( serial_type>=10 ){
/* Serial types 12 or greater are strings and blobs (greater than
** numbers). Types 10 and 11 are currently "reserved for future
** use", so it doesn't really matter what the results of comparing
** them to numberic values are. */
rc = +1;
}else if( serial_type==0 ){
rc = -1;
}else{
sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
if( serial_type==7 ){
if( mem1.u.r<pRhs->u.r ){
rc = -1;
}else if( mem1.u.r>pRhs->u.r ){
rc = +1;
}
}else{
rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
}
}
}
/* RHS is a string */
else if( pRhs->flags & MEM_Str ){
getVarint32(&aKey1[idx1], serial_type);
testcase( serial_type==12 );
if( serial_type<12 ){
rc = -1;
}else if( !(serial_type & 0x01) ){
rc = +1;
}else{
mem1.n = (serial_type - 12) / 2;
testcase( (d1+mem1.n)==(unsigned)nKey1 );
testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
if( (d1+mem1.n) > (unsigned)nKey1
|| (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}else if( pKeyInfo->aColl[i] ){
mem1.enc = pKeyInfo->enc;
mem1.db = pKeyInfo->db;
mem1.flags = MEM_Str;
mem1.z = (char*)&aKey1[d1];
rc = vdbeCompareMemString(
&mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
);
}else{
int nCmp = MIN(mem1.n, pRhs->n);
rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
if( rc==0 ) rc = mem1.n - pRhs->n;
}
}
}
/* RHS is a blob */
else if( pRhs->flags & MEM_Blob ){
assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
getVarint32(&aKey1[idx1], serial_type);
testcase( serial_type==12 );
if( serial_type<12 || (serial_type & 0x01) ){
rc = -1;
}else{
int nStr = (serial_type - 12) / 2;
testcase( (d1+nStr)==(unsigned)nKey1 );
testcase( (d1+nStr+1)==(unsigned)nKey1 );
if( (d1+nStr) > (unsigned)nKey1 ){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}else if( pRhs->flags & MEM_Zero ){
if( !isAllZero((const char*)&aKey1[d1],nStr) ){
rc = 1;
}else{
rc = nStr - pRhs->u.nZero;
}
}else{
int nCmp = MIN(nStr, pRhs->n);
rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
if( rc==0 ) rc = nStr - pRhs->n;
}
}
}
/* RHS is null */
else{
serial_type = aKey1[idx1];
rc = (serial_type!=0);
}
if( rc!=0 ){
int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
if( sortFlags ){
if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
|| ((sortFlags & KEYINFO_ORDER_DESC)
!=(serial_type==0 || (pRhs->flags&MEM_Null)))
){
rc = -rc;
}
}
assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
assert( mem1.szMalloc==0 ); /* See comment below */
return rc;
}
i++;
if( i==pPKey2->nField ) break;
pRhs++;
d1 += sqlite3VdbeSerialTypeLen(serial_type);
idx1 += sqlite3VarintLen(serial_type);
}while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
/* No memory allocation is ever used on mem1. Prove this using
** the following assert(). If the assert() fails, it indicates a
** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
assert( mem1.szMalloc==0 );
/* rc==0 here means that one or both of the keys ran out of fields and
** all the fields up to that point were equal. Return the default_rc
** value. */
assert( CORRUPT_DB
|| vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
|| pPKey2->pKeyInfo->db->mallocFailed
);
pPKey2->eqSeen = 1;
return pPKey2->default_rc;
}
int sqlite3VdbeRecordCompare(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2 /* Right key */
){
return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
}
/*
** This function is an optimized version of sqlite3VdbeRecordCompare()
** that (a) the first field of pPKey2 is an integer, and (b) the
** size-of-header varint at the start of (pKey1/nKey1) fits in a single
** byte (i.e. is less than 128).
**
** To avoid concerns about buffer overreads, this routine is only used
** on schemas where the maximum valid header size is 63 bytes or less.
*/
static int vdbeRecordCompareInt(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2 /* Right key */
){
const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
int serial_type = ((const u8*)pKey1)[1];
int res;
u32 y;
u64 x;
i64 v;
i64 lhs;
vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
switch( serial_type ){
case 1: { /* 1-byte signed integer */
lhs = ONE_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 2: { /* 2-byte signed integer */
lhs = TWO_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 3: { /* 3-byte signed integer */
lhs = THREE_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 4: { /* 4-byte signed integer */
y = FOUR_BYTE_UINT(aKey);
lhs = (i64)*(int*)&y;
testcase( lhs<0 );
break;
}
case 5: { /* 6-byte signed integer */
lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
testcase( lhs<0 );
break;
}
case 6: { /* 8-byte signed integer */
x = FOUR_BYTE_UINT(aKey);
x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
lhs = *(i64*)&x;
testcase( lhs<0 );
break;
}
case 8:
lhs = 0;
break;
case 9:
lhs = 1;
break;
/* This case could be removed without changing the results of running
** this code. Including it causes gcc to generate a faster switch
** statement (since the range of switch targets now starts at zero and
** is contiguous) but does not cause any duplicate code to be generated
** (as gcc is clever enough to combine the two like cases). Other
** compilers might be similar. */
case 0: case 7:
return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
default:
return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
}
v = pPKey2->aMem[0].u.i;
if( v>lhs ){
res = pPKey2->r1;
}else if( v<lhs ){
res = pPKey2->r2;
}else if( pPKey2->nField>1 ){
/* The first fields of the two keys are equal. Compare the trailing
** fields. */
res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
}else{
/* The first fields of the two keys are equal and there are no trailing
** fields. Return pPKey2->default_rc in this case. */
res = pPKey2->default_rc;
pPKey2->eqSeen = 1;
}
assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
return res;
}
/*
** This function is an optimized version of sqlite3VdbeRecordCompare()
** that (a) the first field of pPKey2 is a string, that (b) the first field
** uses the collation sequence BINARY and (c) that the size-of-header varint
** at the start of (pKey1/nKey1) fits in a single byte.
*/
static int vdbeRecordCompareString(
int nKey1, const void *pKey1, /* Left key */
UnpackedRecord *pPKey2 /* Right key */
){
const u8 *aKey1 = (const u8*)pKey1;
int serial_type;
int res;
assert( pPKey2->aMem[0].flags & MEM_Str );
vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
getVarint32(&aKey1[1], serial_type);
if( serial_type<12 ){
res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
}else if( !(serial_type & 0x01) ){
res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
}else{
int nCmp;
int nStr;
int szHdr = aKey1[0];
nStr = (serial_type-12) / 2;
if( (szHdr + nStr) > nKey1 ){
pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
return 0; /* Corruption */
}
nCmp = MIN( pPKey2->aMem[0].n, nStr );
res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
if( res>0 ){
res = pPKey2->r2;
}else if( res<0 ){
res = pPKey2->r1;
}else{
res = nStr - pPKey2->aMem[0].n;
if( res==0 ){
if( pPKey2->nField>1 ){
res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
}else{
res = pPKey2->default_rc;
pPKey2->eqSeen = 1;
}
}else if( res>0 ){
res = pPKey2->r2;
}else{
res = pPKey2->r1;
}
}
}
assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
|| CORRUPT_DB
|| pPKey2->pKeyInfo->db->mallocFailed
);
return res;
}
/*
** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
** suitable for comparing serialized records to the unpacked record passed
** as the only argument.
*/
RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
/* varintRecordCompareInt() and varintRecordCompareString() both assume
** that the size-of-header varint that occurs at the start of each record
** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
** also assumes that it is safe to overread a buffer by at least the
** maximum possible legal header size plus 8 bytes. Because there is
** guaranteed to be at least 74 (but not 136) bytes of padding following each
** buffer passed to varintRecordCompareInt() this makes it convenient to
** limit the size of the header to 64 bytes in cases where the first field
** is an integer.
**
** The easiest way to enforce this limit is to consider only records with
** 13 fields or less. If the first field is an integer, the maximum legal
** header size is (12*5 + 1 + 1) bytes. */
if( p->pKeyInfo->nAllField<=13 ){
int flags = p->aMem[0].flags;
if( p->pKeyInfo->aSortFlags[0] ){
if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
return sqlite3VdbeRecordCompare;
}
p->r1 = 1;
p->r2 = -1;
}else{
p->r1 = -1;
p->r2 = 1;
}
if( (flags & MEM_Int) ){
return vdbeRecordCompareInt;
}
testcase( flags & MEM_Real );
testcase( flags & MEM_Null );
testcase( flags & MEM_Blob );
if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
&& p->pKeyInfo->aColl[0]==0
){
assert( flags & MEM_Str );
return vdbeRecordCompareString;
}
}
return sqlite3VdbeRecordCompare;
}
/*
** pCur points at an index entry created using the OP_MakeRecord opcode.
** Read the rowid (the last field in the record) and store it in *rowid.
** Return SQLITE_OK if everything works, or an error code otherwise.
**
** pCur might be pointing to text obtained from a corrupt database file.
** So the content cannot be trusted. Do appropriate checks on the content.
*/
int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
i64 nCellKey = 0;
int rc;
u32 szHdr; /* Size of the header */
u32 typeRowid; /* Serial type of the rowid */
u32 lenRowid; /* Size of the rowid */
Mem m, v;
/* Get the size of the index entry. Only indices entries of less
** than 2GiB are support - anything large must be database corruption.
** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
** this code can safely assume that nCellKey is 32-bits
*/
assert( sqlite3BtreeCursorIsValid(pCur) );
nCellKey = sqlite3BtreePayloadSize(pCur);
assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
/* Read in the complete content of the index entry */
sqlite3VdbeMemInit(&m, db, 0);
rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
if( rc ){
return rc;
}
/* The index entry must begin with a header size */
(void)getVarint32((u8*)m.z, szHdr);
testcase( szHdr==3 );
testcase( szHdr==m.n );
testcase( szHdr>0x7fffffff );
assert( m.n>=0 );
if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
goto idx_rowid_corruption;
}
/* The last field of the index should be an integer - the ROWID.
** Verify that the last entry really is an integer. */
(void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
testcase( typeRowid==1 );
testcase( typeRowid==2 );
testcase( typeRowid==3 );
testcase( typeRowid==4 );
testcase( typeRowid==5 );
testcase( typeRowid==6 );
testcase( typeRowid==8 );
testcase( typeRowid==9 );
if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
goto idx_rowid_corruption;
}
lenRowid = sqlite3SmallTypeSizes[typeRowid];
testcase( (u32)m.n==szHdr+lenRowid );
if( unlikely((u32)m.n<szHdr+lenRowid) ){
goto idx_rowid_corruption;
}
/* Fetch the integer off the end of the index record */
sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
*rowid = v.u.i;
sqlite3VdbeMemRelease(&m);
return SQLITE_OK;
/* Jump here if database corruption is detected after m has been
** allocated. Free the m object and return SQLITE_CORRUPT. */
idx_rowid_corruption:
testcase( m.szMalloc!=0 );
sqlite3VdbeMemRelease(&m);
return SQLITE_CORRUPT_BKPT;
}
/*
** Compare the key of the index entry that cursor pC is pointing to against
** the key string in pUnpacked. Write into *pRes a number
** that is negative, zero, or positive if pC is less than, equal to,
** or greater than pUnpacked. Return SQLITE_OK on success.
**
** pUnpacked is either created without a rowid or is truncated so that it
** omits the rowid at the end. The rowid at the end of the index entry
** is ignored as well. Hence, this routine only compares the prefixes
** of the keys prior to the final rowid, not the entire key.
*/
int sqlite3VdbeIdxKeyCompare(
sqlite3 *db, /* Database connection */
VdbeCursor *pC, /* The cursor to compare against */
UnpackedRecord *pUnpacked, /* Unpacked version of key */
int *res /* Write the comparison result here */
){
i64 nCellKey = 0;
int rc;
BtCursor *pCur;
Mem m;
assert( pC->eCurType==CURTYPE_BTREE );
pCur = pC->uc.pCursor;
assert( sqlite3BtreeCursorIsValid(pCur) );
nCellKey = sqlite3BtreePayloadSize(pCur);
/* nCellKey will always be between 0 and 0xffffffff because of the way
** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
if( nCellKey<=0 || nCellKey>0x7fffffff ){
*res = 0;
return SQLITE_CORRUPT_BKPT;
}
sqlite3VdbeMemInit(&m, db, 0);
rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
if( rc ){
return rc;
}
*res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
sqlite3VdbeMemRelease(&m);
return SQLITE_OK;
}
/*
** This routine sets the value to be returned by subsequent calls to
** sqlite3_changes() on the database handle 'db'.
*/
void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
assert( sqlite3_mutex_held(db->mutex) );
db->nChange = nChange;
db->nTotalChange += nChange;
}
/*
** Set a flag in the vdbe to update the change counter when it is finalised
** or reset.
*/
void sqlite3VdbeCountChanges(Vdbe *v){
v->changeCntOn = 1;
}
/*
** Mark every prepared statement associated with a database connection
** as expired.
**
** An expired statement means that recompilation of the statement is
** recommend. Statements expire when things happen that make their
** programs obsolete. Removing user-defined functions or collating
** sequences, or changing an authorization function are the types of
** things that make prepared statements obsolete.
**
** If iCode is 1, then expiration is advisory. The statement should
** be reprepared before being restarted, but if it is already running
** it is allowed to run to completion.
**
** Internally, this function just sets the Vdbe.expired flag on all
** prepared statements. The flag is set to 1 for an immediate expiration
** and set to 2 for an advisory expiration.
*/
void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
Vdbe *p;
for(p = db->pVdbe; p; p=p->pNext){
p->expired = iCode+1;
}
}
/*
** Return the database associated with the Vdbe.
*/
sqlite3 *sqlite3VdbeDb(Vdbe *v){
return v->db;
}
/*
** Return the SQLITE_PREPARE flags for a Vdbe.
*/
u8 sqlite3VdbePrepareFlags(Vdbe *v){
return v->prepFlags;
}
/*
** Return a pointer to an sqlite3_value structure containing the value bound
** parameter iVar of VM v. Except, if the value is an SQL NULL, return
** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
** constants) to the value before returning it.
**
** The returned value must be freed by the caller using sqlite3ValueFree().
*/
sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
assert( iVar>0 );
if( v ){
Mem *pMem = &v->aVar[iVar-1];
assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
if( 0==(pMem->flags & MEM_Null) ){
sqlite3_value *pRet = sqlite3ValueNew(v->db);
if( pRet ){
sqlite3VdbeMemCopy((Mem *)pRet, pMem);
sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
}
return pRet;
}
}
return 0;
}
/*
** Configure SQL variable iVar so that binding a new value to it signals
** to sqlite3_reoptimize() that re-preparing the statement may result
** in a better query plan.
*/
void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
assert( iVar>0 );
assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
if( iVar>=32 ){
v->expmask |= 0x80000000;
}else{
v->expmask |= ((u32)1 << (iVar-1));
}
}
/*
** Cause a function to throw an error if it was call from OP_PureFunc
** rather than OP_Function.
**
** OP_PureFunc means that the function must be deterministic, and should
** throw an error if it is given inputs that would make it non-deterministic.
** This routine is invoked by date/time functions that use non-deterministic
** features such as 'now'.
*/
int sqlite3NotPureFunc(sqlite3_context *pCtx){
const VdbeOp *pOp;
#ifdef SQLITE_ENABLE_STAT4
if( pCtx->pVdbe==0 ) return 1;
#endif
pOp = pCtx->pVdbe->aOp + pCtx->iOp;
if( pOp->opcode==OP_PureFunc ){
const char *zContext;
char *zMsg;
if( pOp->p5 & NC_IsCheck ){
zContext = "a CHECK constraint";
}else if( pOp->p5 & NC_GenCol ){
zContext = "a generated column";
}else{
zContext = "an index";
}
zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
pCtx->pFunc->zName, zContext);
sqlite3_result_error(pCtx, zMsg, -1);
sqlite3_free(zMsg);
return 0;
}
return 1;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
** in memory obtained from sqlite3DbMalloc).
*/
void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
if( pVtab->zErrMsg ){
sqlite3 *db = p->db;
sqlite3DbFree(db, p->zErrMsg);
p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
sqlite3_free(pVtab->zErrMsg);
pVtab->zErrMsg = 0;
}
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** If the second argument is not NULL, release any allocations associated
** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
** structure itself, using sqlite3DbFree().
**
** This function is used to free UnpackedRecord structures allocated by
** the vdbeUnpackRecord() function found in vdbeapi.c.
*/
static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
if( p ){
int i;
for(i=0; i<nField; i++){
Mem *pMem = &p->aMem[i];
if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
}
sqlite3DbFreeNN(db, p);
}
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
/*
** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
** then cursor passed as the second argument should point to the row about
** to be update or deleted. If the application calls sqlite3_preupdate_old(),
** the required value will be read from the row the cursor points to.
*/
void sqlite3VdbePreUpdateHook(
Vdbe *v, /* Vdbe pre-update hook is invoked by */
VdbeCursor *pCsr, /* Cursor to grab old.* values from */
int op, /* SQLITE_INSERT, UPDATE or DELETE */
const char *zDb, /* Database name */
Table *pTab, /* Modified table */
i64 iKey1, /* Initial key value */
int iReg /* Register for new.* record */
){
sqlite3 *db = v->db;
i64 iKey2;
PreUpdate preupdate;
const char *zTbl = pTab->zName;
static const u8 fakeSortOrder = 0;
assert( db->pPreUpdate==0 );
memset(&preupdate, 0, sizeof(PreUpdate));
if( HasRowid(pTab)==0 ){
iKey1 = iKey2 = 0;
preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
}else{
if( op==SQLITE_UPDATE ){
iKey2 = v->aMem[iReg].u.i;
}else{
iKey2 = iKey1;
}
}
assert( pCsr->nField==pTab->nCol
|| (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
);
preupdate.v = v;
preupdate.pCsr = pCsr;
preupdate.op = op;
preupdate.iNewReg = iReg;
preupdate.keyinfo.db = db;
preupdate.keyinfo.enc = ENC(db);
preupdate.keyinfo.nKeyField = pTab->nCol;
preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
preupdate.iKey1 = iKey1;
preupdate.iKey2 = iKey2;
preupdate.pTab = pTab;
db->pPreUpdate = &preupdate;
db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
db->pPreUpdate = 0;
sqlite3DbFree(db, preupdate.aRecord);
vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
if( preupdate.aNew ){
int i;
for(i=0; i<pCsr->nField; i++){
sqlite3VdbeMemRelease(&preupdate.aNew[i]);
}
sqlite3DbFreeNN(db, preupdate.aNew);
}
}
#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_1325_3 |
crossvul-cpp_data_bad_2582_0 | /******************************************************************************
*
* Module Name: nsutils - Utilities for accessing ACPI namespace, accessing
* parents and siblings and Scope manipulation
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2017, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "amlcode.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nsutils")
/* Local prototypes */
#ifdef ACPI_OBSOLETE_FUNCTIONS
acpi_name acpi_ns_find_parent_name(struct acpi_namespace_node *node_to_search);
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ns_print_node_pathname
*
* PARAMETERS: node - Object
* message - Prefix message
*
* DESCRIPTION: Print an object's full namespace pathname
* Manages allocation/freeing of a pathname buffer
*
******************************************************************************/
void
acpi_ns_print_node_pathname(struct acpi_namespace_node *node,
const char *message)
{
struct acpi_buffer buffer;
acpi_status status;
if (!node) {
acpi_os_printf("[NULL NAME]");
return;
}
/* Convert handle to full pathname and print it (with supplied message) */
buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER;
status = acpi_ns_handle_to_pathname(node, &buffer, TRUE);
if (ACPI_SUCCESS(status)) {
if (message) {
acpi_os_printf("%s ", message);
}
acpi_os_printf("[%s] (Node %p)", (char *)buffer.pointer, node);
ACPI_FREE(buffer.pointer);
}
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_type
*
* PARAMETERS: node - Parent Node to be examined
*
* RETURN: Type field from Node whose handle is passed
*
* DESCRIPTION: Return the type of a Namespace node
*
******************************************************************************/
acpi_object_type acpi_ns_get_type(struct acpi_namespace_node * node)
{
ACPI_FUNCTION_TRACE(ns_get_type);
if (!node) {
ACPI_WARNING((AE_INFO, "Null Node parameter"));
return_UINT8(ACPI_TYPE_ANY);
}
return_UINT8(node->type);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_local
*
* PARAMETERS: type - A namespace object type
*
* RETURN: LOCAL if names must be found locally in objects of the
* passed type, 0 if enclosing scopes should be searched
*
* DESCRIPTION: Returns scope rule for the given object type.
*
******************************************************************************/
u32 acpi_ns_local(acpi_object_type type)
{
ACPI_FUNCTION_TRACE(ns_local);
if (!acpi_ut_valid_object_type(type)) {
/* Type code out of range */
ACPI_WARNING((AE_INFO, "Invalid Object Type 0x%X", type));
return_UINT32(ACPI_NS_NORMAL);
}
return_UINT32(acpi_gbl_ns_properties[type] & ACPI_NS_LOCAL);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_internal_name_length
*
* PARAMETERS: info - Info struct initialized with the
* external name pointer.
*
* RETURN: None
*
* DESCRIPTION: Calculate the length of the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
void acpi_ns_get_internal_name_length(struct acpi_namestring_info *info)
{
const char *next_external_char;
u32 i;
ACPI_FUNCTION_ENTRY();
next_external_char = info->external_name;
info->num_carats = 0;
info->num_segments = 0;
info->fully_qualified = FALSE;
/*
* For the internal name, the required length is 4 bytes per segment,
* plus 1 each for root_prefix, multi_name_prefix_op, segment count,
* trailing null (which is not really needed, but no there's harm in
* putting it there)
*
* strlen() + 1 covers the first name_seg, which has no path separator
*/
if (ACPI_IS_ROOT_PREFIX(*next_external_char)) {
info->fully_qualified = TRUE;
next_external_char++;
/* Skip redundant root_prefix, like \\_SB.PCI0.SBRG.EC0 */
while (ACPI_IS_ROOT_PREFIX(*next_external_char)) {
next_external_char++;
}
} else {
/* Handle Carat prefixes */
while (ACPI_IS_PARENT_PREFIX(*next_external_char)) {
info->num_carats++;
next_external_char++;
}
}
/*
* Determine the number of ACPI name "segments" by counting the number of
* path separators within the string. Start with one segment since the
* segment count is [(# separators) + 1], and zero separators is ok.
*/
if (*next_external_char) {
info->num_segments = 1;
for (i = 0; next_external_char[i]; i++) {
if (ACPI_IS_PATH_SEPARATOR(next_external_char[i])) {
info->num_segments++;
}
}
}
info->length = (ACPI_NAME_SIZE * info->num_segments) +
4 + info->num_carats;
info->next_external_char = next_external_char;
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_build_internal_name
*
* PARAMETERS: info - Info struct fully initialized
*
* RETURN: Status
*
* DESCRIPTION: Construct the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
acpi_status acpi_ns_build_internal_name(struct acpi_namestring_info *info)
{
u32 num_segments = info->num_segments;
char *internal_name = info->internal_name;
const char *external_name = info->next_external_char;
char *result = NULL;
u32 i;
ACPI_FUNCTION_TRACE(ns_build_internal_name);
/* Setup the correct prefixes, counts, and pointers */
if (info->fully_qualified) {
internal_name[0] = AML_ROOT_PREFIX;
if (num_segments <= 1) {
result = &internal_name[1];
} else if (num_segments == 2) {
internal_name[1] = AML_DUAL_NAME_PREFIX;
result = &internal_name[2];
} else {
internal_name[1] = AML_MULTI_NAME_PREFIX_OP;
internal_name[2] = (char)num_segments;
result = &internal_name[3];
}
} else {
/*
* Not fully qualified.
* Handle Carats first, then append the name segments
*/
i = 0;
if (info->num_carats) {
for (i = 0; i < info->num_carats; i++) {
internal_name[i] = AML_PARENT_PREFIX;
}
}
if (num_segments <= 1) {
result = &internal_name[i];
} else if (num_segments == 2) {
internal_name[i] = AML_DUAL_NAME_PREFIX;
result = &internal_name[(acpi_size)i + 1];
} else {
internal_name[i] = AML_MULTI_NAME_PREFIX_OP;
internal_name[(acpi_size)i + 1] = (char)num_segments;
result = &internal_name[(acpi_size)i + 2];
}
}
/* Build the name (minus path separators) */
for (; num_segments; num_segments--) {
for (i = 0; i < ACPI_NAME_SIZE; i++) {
if (ACPI_IS_PATH_SEPARATOR(*external_name) ||
(*external_name == 0)) {
/* Pad the segment with underscore(s) if segment is short */
result[i] = '_';
} else {
/* Convert the character to uppercase and save it */
result[i] = (char)toupper((int)*external_name);
external_name++;
}
}
/* Now we must have a path separator, or the pathname is bad */
if (!ACPI_IS_PATH_SEPARATOR(*external_name) &&
(*external_name != 0)) {
return_ACPI_STATUS(AE_BAD_PATHNAME);
}
/* Move on the next segment */
external_name++;
result += ACPI_NAME_SIZE;
}
/* Terminate the string */
*result = 0;
if (info->fully_qualified) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Returning [%p] (abs) \"\\%s\"\n",
internal_name, internal_name));
} else {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Returning [%p] (rel) \"%s\"\n",
internal_name, internal_name));
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_internalize_name
*
* PARAMETERS: *external_name - External representation of name
* **Converted name - Where to return the resulting
* internal represention of the name
*
* RETURN: Status
*
* DESCRIPTION: Convert an external representation (e.g. "\_PR_.CPU0")
* to internal form (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
*
*******************************************************************************/
acpi_status
acpi_ns_internalize_name(const char *external_name, char **converted_name)
{
char *internal_name;
struct acpi_namestring_info info;
acpi_status status;
ACPI_FUNCTION_TRACE(ns_internalize_name);
if ((!external_name) || (*external_name == 0) || (!converted_name)) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Get the length of the new internal name */
info.external_name = external_name;
acpi_ns_get_internal_name_length(&info);
/* We need a segment to store the internal name */
internal_name = ACPI_ALLOCATE_ZEROED(info.length);
if (!internal_name) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Build the name */
info.internal_name = internal_name;
status = acpi_ns_build_internal_name(&info);
if (ACPI_FAILURE(status)) {
ACPI_FREE(internal_name);
return_ACPI_STATUS(status);
}
*converted_name = internal_name;
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_externalize_name
*
* PARAMETERS: internal_name_length - Lenth of the internal name below
* internal_name - Internal representation of name
* converted_name_length - Where the length is returned
* converted_name - Where the resulting external name
* is returned
*
* RETURN: Status
*
* DESCRIPTION: Convert internal name (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
* to its external (printable) form (e.g. "\_PR_.CPU0")
*
******************************************************************************/
acpi_status
acpi_ns_externalize_name(u32 internal_name_length,
const char *internal_name,
u32 * converted_name_length, char **converted_name)
{
u32 names_index = 0;
u32 num_segments = 0;
u32 required_length;
u32 prefix_length = 0;
u32 i = 0;
u32 j = 0;
ACPI_FUNCTION_TRACE(ns_externalize_name);
if (!internal_name_length || !internal_name || !converted_name) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Check for a prefix (one '\' | one or more '^') */
switch (internal_name[0]) {
case AML_ROOT_PREFIX:
prefix_length = 1;
break;
case AML_PARENT_PREFIX:
for (i = 0; i < internal_name_length; i++) {
if (ACPI_IS_PARENT_PREFIX(internal_name[i])) {
prefix_length = i + 1;
} else {
break;
}
}
if (i == internal_name_length) {
prefix_length = i;
}
break;
default:
break;
}
/*
* Check for object names. Note that there could be 0-255 of these
* 4-byte elements.
*/
if (prefix_length < internal_name_length) {
switch (internal_name[prefix_length]) {
case AML_MULTI_NAME_PREFIX_OP:
/* <count> 4-byte names */
names_index = prefix_length + 2;
num_segments = (u8)
internal_name[(acpi_size)prefix_length + 1];
break;
case AML_DUAL_NAME_PREFIX:
/* Two 4-byte names */
names_index = prefix_length + 1;
num_segments = 2;
break;
case 0:
/* null_name */
names_index = 0;
num_segments = 0;
break;
default:
/* one 4-byte name */
names_index = prefix_length;
num_segments = 1;
break;
}
}
/*
* Calculate the length of converted_name, which equals the length
* of the prefix, length of all object names, length of any required
* punctuation ('.') between object names, plus the NULL terminator.
*/
required_length = prefix_length + (4 * num_segments) +
((num_segments > 0) ? (num_segments - 1) : 0) + 1;
/*
* Check to see if we're still in bounds. If not, there's a problem
* with internal_name (invalid format).
*/
if (required_length > internal_name_length) {
ACPI_ERROR((AE_INFO, "Invalid internal name"));
return_ACPI_STATUS(AE_BAD_PATHNAME);
}
/* Build the converted_name */
*converted_name = ACPI_ALLOCATE_ZEROED(required_length);
if (!(*converted_name)) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
j = 0;
for (i = 0; i < prefix_length; i++) {
(*converted_name)[j++] = internal_name[i];
}
if (num_segments > 0) {
for (i = 0; i < num_segments; i++) {
if (i > 0) {
(*converted_name)[j++] = '.';
}
/* Copy and validate the 4-char name segment */
ACPI_MOVE_NAME(&(*converted_name)[j],
&internal_name[names_index]);
acpi_ut_repair_name(&(*converted_name)[j]);
j += ACPI_NAME_SIZE;
names_index += ACPI_NAME_SIZE;
}
}
if (converted_name_length) {
*converted_name_length = (u32) required_length;
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_validate_handle
*
* PARAMETERS: handle - Handle to be validated and typecast to a
* namespace node.
*
* RETURN: A pointer to a namespace node
*
* DESCRIPTION: Convert a namespace handle to a namespace node. Handles special
* cases for the root node.
*
* NOTE: Real integer handles would allow for more verification
* and keep all pointers within this subsystem - however this introduces
* more overhead and has not been necessary to this point. Drivers
* holding handles are typically notified before a node becomes invalid
* due to a table unload.
*
******************************************************************************/
struct acpi_namespace_node *acpi_ns_validate_handle(acpi_handle handle)
{
ACPI_FUNCTION_ENTRY();
/* Parameter validation */
if ((!handle) || (handle == ACPI_ROOT_OBJECT)) {
return (acpi_gbl_root_node);
}
/* We can at least attempt to verify the handle */
if (ACPI_GET_DESCRIPTOR_TYPE(handle) != ACPI_DESC_TYPE_NAMED) {
return (NULL);
}
return (ACPI_CAST_PTR(struct acpi_namespace_node, handle));
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_terminate
*
* PARAMETERS: none
*
* RETURN: none
*
* DESCRIPTION: free memory allocated for namespace and ACPI table storage.
*
******************************************************************************/
void acpi_ns_terminate(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ns_terminate);
#ifdef ACPI_EXEC_APP
{
union acpi_operand_object *prev;
union acpi_operand_object *next;
/* Delete any module-level code blocks */
next = acpi_gbl_module_code_list;
while (next) {
prev = next;
next = next->method.mutex;
prev->method.mutex = NULL; /* Clear the Mutex (cheated) field */
acpi_ut_remove_reference(prev);
}
}
#endif
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
acpi_ns_delete_namespace_subtree(acpi_gbl_root_node);
/* Delete any objects attached to the root node */
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_VOID;
}
acpi_ns_delete_node(acpi_gbl_root_node);
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_opens_scope
*
* PARAMETERS: type - A valid namespace type
*
* RETURN: NEWSCOPE if the passed type "opens a name scope" according
* to the ACPI specification, else 0
*
******************************************************************************/
u32 acpi_ns_opens_scope(acpi_object_type type)
{
ACPI_FUNCTION_ENTRY();
if (type > ACPI_TYPE_LOCAL_MAX) {
/* type code out of range */
ACPI_WARNING((AE_INFO, "Invalid Object Type 0x%X", type));
return (ACPI_NS_NORMAL);
}
return (((u32)acpi_gbl_ns_properties[type]) & ACPI_NS_NEWSCOPE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_node_unlocked
*
* PARAMETERS: *pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* prefix_node - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first s8 is '\'), the passed value
* of Scope will not be accessed.
* flags - Used to indicate whether to perform upsearch or
* not.
* return_node - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Doesn't locks namespace
*
******************************************************************************/
acpi_status
acpi_ns_get_node_unlocked(struct acpi_namespace_node *prefix_node,
const char *pathname,
u32 flags, struct acpi_namespace_node **return_node)
{
union acpi_generic_state scope_info;
acpi_status status;
char *internal_path;
ACPI_FUNCTION_TRACE_PTR(ns_get_node_unlocked,
ACPI_CAST_PTR(char, pathname));
/* Simplest case is a null pathname */
if (!pathname) {
*return_node = prefix_node;
if (!prefix_node) {
*return_node = acpi_gbl_root_node;
}
return_ACPI_STATUS(AE_OK);
}
/* Quick check for a reference to the root */
if (ACPI_IS_ROOT_PREFIX(pathname[0]) && (!pathname[1])) {
*return_node = acpi_gbl_root_node;
return_ACPI_STATUS(AE_OK);
}
/* Convert path to internal representation */
status = acpi_ns_internalize_name(pathname, &internal_path);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Setup lookup scope (search starting point) */
scope_info.scope.node = prefix_node;
/* Lookup the name in the namespace */
status = acpi_ns_lookup(&scope_info, internal_path, ACPI_TYPE_ANY,
ACPI_IMODE_EXECUTE,
(flags | ACPI_NS_DONT_OPEN_SCOPE), NULL,
return_node);
if (ACPI_FAILURE(status)) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "%s, %s\n",
pathname, acpi_format_exception(status)));
}
ACPI_FREE(internal_path);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_node
*
* PARAMETERS: *pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* prefix_node - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first s8 is '\'), the passed value
* of Scope will not be accessed.
* flags - Used to indicate whether to perform upsearch or
* not.
* return_node - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Locks namespace
*
******************************************************************************/
acpi_status
acpi_ns_get_node(struct acpi_namespace_node *prefix_node,
const char *pathname,
u32 flags, struct acpi_namespace_node **return_node)
{
acpi_status status;
ACPI_FUNCTION_TRACE_PTR(ns_get_node, ACPI_CAST_PTR(char, pathname));
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
status = acpi_ns_get_node_unlocked(prefix_node, pathname,
flags, return_node);
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
return_ACPI_STATUS(status);
}
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_2582_0 |
crossvul-cpp_data_bad_2581_0 | /******************************************************************************
*
* Module Name: nsutils - Utilities for accessing ACPI namespace, accessing
* parents and siblings and Scope manipulation
*
*****************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2017, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#include "acpi.h"
#include "accommon.h"
#include "acnamesp.h"
#include "amlcode.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME ("nsutils")
/* Local prototypes */
#ifdef ACPI_OBSOLETE_FUNCTIONS
ACPI_NAME
AcpiNsFindParentName (
ACPI_NAMESPACE_NODE *NodeToSearch);
#endif
/*******************************************************************************
*
* FUNCTION: AcpiNsPrintNodePathname
*
* PARAMETERS: Node - Object
* Message - Prefix message
*
* DESCRIPTION: Print an object's full namespace pathname
* Manages allocation/freeing of a pathname buffer
*
******************************************************************************/
void
AcpiNsPrintNodePathname (
ACPI_NAMESPACE_NODE *Node,
const char *Message)
{
ACPI_BUFFER Buffer;
ACPI_STATUS Status;
if (!Node)
{
AcpiOsPrintf ("[NULL NAME]");
return;
}
/* Convert handle to full pathname and print it (with supplied message) */
Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
Status = AcpiNsHandleToPathname (Node, &Buffer, TRUE);
if (ACPI_SUCCESS (Status))
{
if (Message)
{
AcpiOsPrintf ("%s ", Message);
}
AcpiOsPrintf ("[%s] (Node %p)", (char *) Buffer.Pointer, Node);
ACPI_FREE (Buffer.Pointer);
}
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetType
*
* PARAMETERS: Node - Parent Node to be examined
*
* RETURN: Type field from Node whose handle is passed
*
* DESCRIPTION: Return the type of a Namespace node
*
******************************************************************************/
ACPI_OBJECT_TYPE
AcpiNsGetType (
ACPI_NAMESPACE_NODE *Node)
{
ACPI_FUNCTION_TRACE (NsGetType);
if (!Node)
{
ACPI_WARNING ((AE_INFO, "Null Node parameter"));
return_UINT8 (ACPI_TYPE_ANY);
}
return_UINT8 (Node->Type);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsLocal
*
* PARAMETERS: Type - A namespace object type
*
* RETURN: LOCAL if names must be found locally in objects of the
* passed type, 0 if enclosing scopes should be searched
*
* DESCRIPTION: Returns scope rule for the given object type.
*
******************************************************************************/
UINT32
AcpiNsLocal (
ACPI_OBJECT_TYPE Type)
{
ACPI_FUNCTION_TRACE (NsLocal);
if (!AcpiUtValidObjectType (Type))
{
/* Type code out of range */
ACPI_WARNING ((AE_INFO, "Invalid Object Type 0x%X", Type));
return_UINT32 (ACPI_NS_NORMAL);
}
return_UINT32 (AcpiGbl_NsProperties[Type] & ACPI_NS_LOCAL);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetInternalNameLength
*
* PARAMETERS: Info - Info struct initialized with the
* external name pointer.
*
* RETURN: None
*
* DESCRIPTION: Calculate the length of the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
void
AcpiNsGetInternalNameLength (
ACPI_NAMESTRING_INFO *Info)
{
const char *NextExternalChar;
UINT32 i;
ACPI_FUNCTION_ENTRY ();
NextExternalChar = Info->ExternalName;
Info->NumCarats = 0;
Info->NumSegments = 0;
Info->FullyQualified = FALSE;
/*
* For the internal name, the required length is 4 bytes per segment,
* plus 1 each for RootPrefix, MultiNamePrefixOp, segment count,
* trailing null (which is not really needed, but no there's harm in
* putting it there)
*
* strlen() + 1 covers the first NameSeg, which has no path separator
*/
if (ACPI_IS_ROOT_PREFIX (*NextExternalChar))
{
Info->FullyQualified = TRUE;
NextExternalChar++;
/* Skip redundant RootPrefix, like \\_SB.PCI0.SBRG.EC0 */
while (ACPI_IS_ROOT_PREFIX (*NextExternalChar))
{
NextExternalChar++;
}
}
else
{
/* Handle Carat prefixes */
while (ACPI_IS_PARENT_PREFIX (*NextExternalChar))
{
Info->NumCarats++;
NextExternalChar++;
}
}
/*
* Determine the number of ACPI name "segments" by counting the number of
* path separators within the string. Start with one segment since the
* segment count is [(# separators) + 1], and zero separators is ok.
*/
if (*NextExternalChar)
{
Info->NumSegments = 1;
for (i = 0; NextExternalChar[i]; i++)
{
if (ACPI_IS_PATH_SEPARATOR (NextExternalChar[i]))
{
Info->NumSegments++;
}
}
}
Info->Length = (ACPI_NAME_SIZE * Info->NumSegments) +
4 + Info->NumCarats;
Info->NextExternalChar = NextExternalChar;
}
/*******************************************************************************
*
* FUNCTION: AcpiNsBuildInternalName
*
* PARAMETERS: Info - Info struct fully initialized
*
* RETURN: Status
*
* DESCRIPTION: Construct the internal (AML) namestring
* corresponding to the external (ASL) namestring.
*
******************************************************************************/
ACPI_STATUS
AcpiNsBuildInternalName (
ACPI_NAMESTRING_INFO *Info)
{
UINT32 NumSegments = Info->NumSegments;
char *InternalName = Info->InternalName;
const char *ExternalName = Info->NextExternalChar;
char *Result = NULL;
UINT32 i;
ACPI_FUNCTION_TRACE (NsBuildInternalName);
/* Setup the correct prefixes, counts, and pointers */
if (Info->FullyQualified)
{
InternalName[0] = AML_ROOT_PREFIX;
if (NumSegments <= 1)
{
Result = &InternalName[1];
}
else if (NumSegments == 2)
{
InternalName[1] = AML_DUAL_NAME_PREFIX;
Result = &InternalName[2];
}
else
{
InternalName[1] = AML_MULTI_NAME_PREFIX_OP;
InternalName[2] = (char) NumSegments;
Result = &InternalName[3];
}
}
else
{
/*
* Not fully qualified.
* Handle Carats first, then append the name segments
*/
i = 0;
if (Info->NumCarats)
{
for (i = 0; i < Info->NumCarats; i++)
{
InternalName[i] = AML_PARENT_PREFIX;
}
}
if (NumSegments <= 1)
{
Result = &InternalName[i];
}
else if (NumSegments == 2)
{
InternalName[i] = AML_DUAL_NAME_PREFIX;
Result = &InternalName[(ACPI_SIZE) i+1];
}
else
{
InternalName[i] = AML_MULTI_NAME_PREFIX_OP;
InternalName[(ACPI_SIZE) i+1] = (char) NumSegments;
Result = &InternalName[(ACPI_SIZE) i+2];
}
}
/* Build the name (minus path separators) */
for (; NumSegments; NumSegments--)
{
for (i = 0; i < ACPI_NAME_SIZE; i++)
{
if (ACPI_IS_PATH_SEPARATOR (*ExternalName) ||
(*ExternalName == 0))
{
/* Pad the segment with underscore(s) if segment is short */
Result[i] = '_';
}
else
{
/* Convert the character to uppercase and save it */
Result[i] = (char) toupper ((int) *ExternalName);
ExternalName++;
}
}
/* Now we must have a path separator, or the pathname is bad */
if (!ACPI_IS_PATH_SEPARATOR (*ExternalName) &&
(*ExternalName != 0))
{
return_ACPI_STATUS (AE_BAD_PATHNAME);
}
/* Move on the next segment */
ExternalName++;
Result += ACPI_NAME_SIZE;
}
/* Terminate the string */
*Result = 0;
if (Info->FullyQualified)
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Returning [%p] (abs) \"\\%s\"\n",
InternalName, InternalName));
}
else
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Returning [%p] (rel) \"%s\"\n",
InternalName, InternalName));
}
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsInternalizeName
*
* PARAMETERS: *ExternalName - External representation of name
* **Converted Name - Where to return the resulting
* internal represention of the name
*
* RETURN: Status
*
* DESCRIPTION: Convert an external representation (e.g. "\_PR_.CPU0")
* to internal form (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
*
*******************************************************************************/
ACPI_STATUS
AcpiNsInternalizeName (
const char *ExternalName,
char **ConvertedName)
{
char *InternalName;
ACPI_NAMESTRING_INFO Info;
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsInternalizeName);
if ((!ExternalName) ||
(*ExternalName == 0) ||
(!ConvertedName))
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
/* Get the length of the new internal name */
Info.ExternalName = ExternalName;
AcpiNsGetInternalNameLength (&Info);
/* We need a segment to store the internal name */
InternalName = ACPI_ALLOCATE_ZEROED (Info.Length);
if (!InternalName)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Build the name */
Info.InternalName = InternalName;
Status = AcpiNsBuildInternalName (&Info);
if (ACPI_FAILURE (Status))
{
ACPI_FREE (InternalName);
return_ACPI_STATUS (Status);
}
*ConvertedName = InternalName;
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsExternalizeName
*
* PARAMETERS: InternalNameLength - Lenth of the internal name below
* InternalName - Internal representation of name
* ConvertedNameLength - Where the length is returned
* ConvertedName - Where the resulting external name
* is returned
*
* RETURN: Status
*
* DESCRIPTION: Convert internal name (e.g. 5c 2f 02 5f 50 52 5f 43 50 55 30)
* to its external (printable) form (e.g. "\_PR_.CPU0")
*
******************************************************************************/
ACPI_STATUS
AcpiNsExternalizeName (
UINT32 InternalNameLength,
const char *InternalName,
UINT32 *ConvertedNameLength,
char **ConvertedName)
{
UINT32 NamesIndex = 0;
UINT32 NumSegments = 0;
UINT32 RequiredLength;
UINT32 PrefixLength = 0;
UINT32 i = 0;
UINT32 j = 0;
ACPI_FUNCTION_TRACE (NsExternalizeName);
if (!InternalNameLength ||
!InternalName ||
!ConvertedName)
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
/* Check for a prefix (one '\' | one or more '^') */
switch (InternalName[0])
{
case AML_ROOT_PREFIX:
PrefixLength = 1;
break;
case AML_PARENT_PREFIX:
for (i = 0; i < InternalNameLength; i++)
{
if (ACPI_IS_PARENT_PREFIX (InternalName[i]))
{
PrefixLength = i + 1;
}
else
{
break;
}
}
if (i == InternalNameLength)
{
PrefixLength = i;
}
break;
default:
break;
}
/*
* Check for object names. Note that there could be 0-255 of these
* 4-byte elements.
*/
if (PrefixLength < InternalNameLength)
{
switch (InternalName[PrefixLength])
{
case AML_MULTI_NAME_PREFIX_OP:
/* <count> 4-byte names */
NamesIndex = PrefixLength + 2;
NumSegments = (UINT8)
InternalName[(ACPI_SIZE) PrefixLength + 1];
break;
case AML_DUAL_NAME_PREFIX:
/* Two 4-byte names */
NamesIndex = PrefixLength + 1;
NumSegments = 2;
break;
case 0:
/* NullName */
NamesIndex = 0;
NumSegments = 0;
break;
default:
/* one 4-byte name */
NamesIndex = PrefixLength;
NumSegments = 1;
break;
}
}
/*
* Calculate the length of ConvertedName, which equals the length
* of the prefix, length of all object names, length of any required
* punctuation ('.') between object names, plus the NULL terminator.
*/
RequiredLength = PrefixLength + (4 * NumSegments) +
((NumSegments > 0) ? (NumSegments - 1) : 0) + 1;
/*
* Check to see if we're still in bounds. If not, there's a problem
* with InternalName (invalid format).
*/
if (RequiredLength > InternalNameLength)
{
ACPI_ERROR ((AE_INFO, "Invalid internal name"));
return_ACPI_STATUS (AE_BAD_PATHNAME);
}
/* Build the ConvertedName */
*ConvertedName = ACPI_ALLOCATE_ZEROED (RequiredLength);
if (!(*ConvertedName))
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
j = 0;
for (i = 0; i < PrefixLength; i++)
{
(*ConvertedName)[j++] = InternalName[i];
}
if (NumSegments > 0)
{
for (i = 0; i < NumSegments; i++)
{
if (i > 0)
{
(*ConvertedName)[j++] = '.';
}
/* Copy and validate the 4-char name segment */
ACPI_MOVE_NAME (&(*ConvertedName)[j],
&InternalName[NamesIndex]);
AcpiUtRepairName (&(*ConvertedName)[j]);
j += ACPI_NAME_SIZE;
NamesIndex += ACPI_NAME_SIZE;
}
}
if (ConvertedNameLength)
{
*ConvertedNameLength = (UINT32) RequiredLength;
}
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsValidateHandle
*
* PARAMETERS: Handle - Handle to be validated and typecast to a
* namespace node.
*
* RETURN: A pointer to a namespace node
*
* DESCRIPTION: Convert a namespace handle to a namespace node. Handles special
* cases for the root node.
*
* NOTE: Real integer handles would allow for more verification
* and keep all pointers within this subsystem - however this introduces
* more overhead and has not been necessary to this point. Drivers
* holding handles are typically notified before a node becomes invalid
* due to a table unload.
*
******************************************************************************/
ACPI_NAMESPACE_NODE *
AcpiNsValidateHandle (
ACPI_HANDLE Handle)
{
ACPI_FUNCTION_ENTRY ();
/* Parameter validation */
if ((!Handle) || (Handle == ACPI_ROOT_OBJECT))
{
return (AcpiGbl_RootNode);
}
/* We can at least attempt to verify the handle */
if (ACPI_GET_DESCRIPTOR_TYPE (Handle) != ACPI_DESC_TYPE_NAMED)
{
return (NULL);
}
return (ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, Handle));
}
/*******************************************************************************
*
* FUNCTION: AcpiNsTerminate
*
* PARAMETERS: none
*
* RETURN: none
*
* DESCRIPTION: free memory allocated for namespace and ACPI table storage.
*
******************************************************************************/
void
AcpiNsTerminate (
void)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsTerminate);
#ifdef ACPI_EXEC_APP
{
ACPI_OPERAND_OBJECT *Prev;
ACPI_OPERAND_OBJECT *Next;
/* Delete any module-level code blocks */
Next = AcpiGbl_ModuleCodeList;
while (Next)
{
Prev = Next;
Next = Next->Method.Mutex;
Prev->Method.Mutex = NULL; /* Clear the Mutex (cheated) field */
AcpiUtRemoveReference (Prev);
}
}
#endif
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode);
/* Delete any objects attached to the root node */
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_VOID;
}
AcpiNsDeleteNode (AcpiGbl_RootNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: AcpiNsOpensScope
*
* PARAMETERS: Type - A valid namespace type
*
* RETURN: NEWSCOPE if the passed type "opens a name scope" according
* to the ACPI specification, else 0
*
******************************************************************************/
UINT32
AcpiNsOpensScope (
ACPI_OBJECT_TYPE Type)
{
ACPI_FUNCTION_ENTRY ();
if (Type > ACPI_TYPE_LOCAL_MAX)
{
/* type code out of range */
ACPI_WARNING ((AE_INFO, "Invalid Object Type 0x%X", Type));
return (ACPI_NS_NORMAL);
}
return (((UINT32) AcpiGbl_NsProperties[Type]) & ACPI_NS_NEWSCOPE);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetNodeUnlocked
*
* PARAMETERS: *Pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* PrefixNode - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first INT8 is '\'), the passed value
* of Scope will not be accessed.
* Flags - Used to indicate whether to perform upsearch or
* not.
* ReturnNode - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Doesn't locks namespace
*
******************************************************************************/
ACPI_STATUS
AcpiNsGetNodeUnlocked (
ACPI_NAMESPACE_NODE *PrefixNode,
const char *Pathname,
UINT32 Flags,
ACPI_NAMESPACE_NODE **ReturnNode)
{
ACPI_GENERIC_STATE ScopeInfo;
ACPI_STATUS Status;
char *InternalPath;
ACPI_FUNCTION_TRACE_PTR (NsGetNodeUnlocked, ACPI_CAST_PTR (char, Pathname));
/* Simplest case is a null pathname */
if (!Pathname)
{
*ReturnNode = PrefixNode;
if (!PrefixNode)
{
*ReturnNode = AcpiGbl_RootNode;
}
return_ACPI_STATUS (AE_OK);
}
/* Quick check for a reference to the root */
if (ACPI_IS_ROOT_PREFIX (Pathname[0]) && (!Pathname[1]))
{
*ReturnNode = AcpiGbl_RootNode;
return_ACPI_STATUS (AE_OK);
}
/* Convert path to internal representation */
Status = AcpiNsInternalizeName (Pathname, &InternalPath);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
/* Setup lookup scope (search starting point) */
ScopeInfo.Scope.Node = PrefixNode;
/* Lookup the name in the namespace */
Status = AcpiNsLookup (&ScopeInfo, InternalPath, ACPI_TYPE_ANY,
ACPI_IMODE_EXECUTE, (Flags | ACPI_NS_DONT_OPEN_SCOPE),
NULL, ReturnNode);
if (ACPI_FAILURE (Status))
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "%s, %s\n",
Pathname, AcpiFormatException (Status)));
}
ACPI_FREE (InternalPath);
return_ACPI_STATUS (Status);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetNode
*
* PARAMETERS: *Pathname - Name to be found, in external (ASL) format. The
* \ (backslash) and ^ (carat) prefixes, and the
* . (period) to separate segments are supported.
* PrefixNode - Root of subtree to be searched, or NS_ALL for the
* root of the name space. If Name is fully
* qualified (first INT8 is '\'), the passed value
* of Scope will not be accessed.
* Flags - Used to indicate whether to perform upsearch or
* not.
* ReturnNode - Where the Node is returned
*
* DESCRIPTION: Look up a name relative to a given scope and return the
* corresponding Node. NOTE: Scope can be null.
*
* MUTEX: Locks namespace
*
******************************************************************************/
ACPI_STATUS
AcpiNsGetNode (
ACPI_NAMESPACE_NODE *PrefixNode,
const char *Pathname,
UINT32 Flags,
ACPI_NAMESPACE_NODE **ReturnNode)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE_PTR (NsGetNode, ACPI_CAST_PTR (char, Pathname));
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
Status = AcpiNsGetNodeUnlocked (PrefixNode, Pathname,
Flags, ReturnNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
return_ACPI_STATUS (Status);
}
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_2581_0 |
crossvul-cpp_data_good_1325_4 | /*
** 2018 May 08
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
*/
#include "sqliteInt.h"
#ifndef SQLITE_OMIT_WINDOWFUNC
/*
** SELECT REWRITING
**
** Any SELECT statement that contains one or more window functions in
** either the select list or ORDER BY clause (the only two places window
** functions may be used) is transformed by function sqlite3WindowRewrite()
** in order to support window function processing. For example, with the
** schema:
**
** CREATE TABLE t1(a, b, c, d, e, f, g);
**
** the statement:
**
** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
**
** is transformed to:
**
** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
** ) ORDER BY e;
**
** The flattening optimization is disabled when processing this transformed
** SELECT statement. This allows the implementation of the window function
** (in this case max()) to process rows sorted in order of (c, d), which
** makes things easier for obvious reasons. More generally:
**
** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
** the sub-query.
**
** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
**
** * Terminals from each of the expression trees that make up the
** select-list and ORDER BY expressions in the parent query are
** selected by the sub-query. For the purposes of the transformation,
** terminals are column references and aggregate functions.
**
** If there is more than one window function in the SELECT that uses
** the same window declaration (the OVER bit), then a single scan may
** be used to process more than one window function. For example:
**
** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
** min(e) OVER (PARTITION BY c ORDER BY d)
** FROM t1;
**
** is transformed in the same way as the example above. However:
**
** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
** min(e) OVER (PARTITION BY a ORDER BY b)
** FROM t1;
**
** Must be transformed to:
**
** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
** ) ORDER BY c, d
** ) ORDER BY e;
**
** so that both min() and max() may process rows in the order defined by
** their respective window declarations.
**
** INTERFACE WITH SELECT.C
**
** When processing the rewritten SELECT statement, code in select.c calls
** sqlite3WhereBegin() to begin iterating through the results of the
** sub-query, which is always implemented as a co-routine. It then calls
** sqlite3WindowCodeStep() to process rows and finish the scan by calling
** sqlite3WhereEnd().
**
** sqlite3WindowCodeStep() generates VM code so that, for each row returned
** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
** When the sub-routine is invoked:
**
** * The results of all window-functions for the row are stored
** in the associated Window.regResult registers.
**
** * The required terminal values are stored in the current row of
** temp table Window.iEphCsr.
**
** In some cases, depending on the window frame and the specific window
** functions invoked, sqlite3WindowCodeStep() caches each entire partition
** in a temp table before returning any rows. In other cases it does not.
** This detail is encapsulated within this file, the code generated by
** select.c is the same in either case.
**
** BUILT-IN WINDOW FUNCTIONS
**
** This implementation features the following built-in window functions:
**
** row_number()
** rank()
** dense_rank()
** percent_rank()
** cume_dist()
** ntile(N)
** lead(expr [, offset [, default]])
** lag(expr [, offset [, default]])
** first_value(expr)
** last_value(expr)
** nth_value(expr, N)
**
** These are the same built-in window functions supported by Postgres.
** Although the behaviour of aggregate window functions (functions that
** can be used as either aggregates or window funtions) allows them to
** be implemented using an API, built-in window functions are much more
** esoteric. Additionally, some window functions (e.g. nth_value())
** may only be implemented by caching the entire partition in memory.
** As such, some built-in window functions use the same API as aggregate
** window functions and some are implemented directly using VDBE
** instructions. Additionally, for those functions that use the API, the
** window frame is sometimes modified before the SELECT statement is
** rewritten. For example, regardless of the specified window frame, the
** row_number() function always uses:
**
** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
**
** See sqlite3WindowUpdate() for details.
**
** As well as some of the built-in window functions, aggregate window
** functions min() and max() are implemented using VDBE instructions if
** the start of the window frame is declared as anything other than
** UNBOUNDED PRECEDING.
*/
/*
** Implementation of built-in window function row_number(). Assumes that the
** window frame has been coerced to:
**
** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
*/
static void row_numberStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ) (*p)++;
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void row_numberValueFunc(sqlite3_context *pCtx){
i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
sqlite3_result_int64(pCtx, (p ? *p : 0));
}
/*
** Context object type used by rank(), dense_rank(), percent_rank() and
** cume_dist().
*/
struct CallCount {
i64 nValue;
i64 nStep;
i64 nTotal;
};
/*
** Implementation of built-in window function dense_rank(). Assumes that
** the window frame has been set to:
**
** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
*/
static void dense_rankStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ) p->nStep = 1;
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void dense_rankValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
if( p->nStep ){
p->nValue++;
p->nStep = 0;
}
sqlite3_result_int64(pCtx, p->nValue);
}
}
/*
** Implementation of built-in window function nth_value(). This
** implementation is used in "slow mode" only - when the EXCLUDE clause
** is not set to the default value "NO OTHERS".
*/
struct NthValueCtx {
i64 nStep;
sqlite3_value *pValue;
};
static void nth_valueStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
i64 iVal;
switch( sqlite3_value_numeric_type(apArg[1]) ){
case SQLITE_INTEGER:
iVal = sqlite3_value_int64(apArg[1]);
break;
case SQLITE_FLOAT: {
double fVal = sqlite3_value_double(apArg[1]);
if( ((i64)fVal)!=fVal ) goto error_out;
iVal = (i64)fVal;
break;
}
default:
goto error_out;
}
if( iVal<=0 ) goto error_out;
p->nStep++;
if( iVal==p->nStep ){
p->pValue = sqlite3_value_dup(apArg[0]);
if( !p->pValue ){
sqlite3_result_error_nomem(pCtx);
}
}
}
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
return;
error_out:
sqlite3_result_error(
pCtx, "second argument to nth_value must be a positive integer", -1
);
}
static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
if( p && p->pValue ){
sqlite3_result_value(pCtx, p->pValue);
sqlite3_value_free(p->pValue);
p->pValue = 0;
}
}
#define nth_valueInvFunc noopStepFunc
#define nth_valueValueFunc noopValueFunc
static void first_valueStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->pValue==0 ){
p->pValue = sqlite3_value_dup(apArg[0]);
if( !p->pValue ){
sqlite3_result_error_nomem(pCtx);
}
}
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void first_valueFinalizeFunc(sqlite3_context *pCtx){
struct NthValueCtx *p;
p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->pValue ){
sqlite3_result_value(pCtx, p->pValue);
sqlite3_value_free(p->pValue);
p->pValue = 0;
}
}
#define first_valueInvFunc noopStepFunc
#define first_valueValueFunc noopValueFunc
/*
** Implementation of built-in window function rank(). Assumes that
** the window frame has been set to:
**
** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
*/
static void rankStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nStep++;
if( p->nValue==0 ){
p->nValue = p->nStep;
}
}
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
}
static void rankValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
sqlite3_result_int64(pCtx, p->nValue);
p->nValue = 0;
}
}
/*
** Implementation of built-in window function percent_rank(). Assumes that
** the window frame has been set to:
**
** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
*/
static void percent_rankStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nTotal++;
}
}
static void percent_rankInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
p->nStep++;
}
static void percent_rankValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nValue = p->nStep;
if( p->nTotal>1 ){
double r = (double)p->nValue / (double)(p->nTotal-1);
sqlite3_result_double(pCtx, r);
}else{
sqlite3_result_double(pCtx, 0.0);
}
}
}
#define percent_rankFinalizeFunc percent_rankValueFunc
/*
** Implementation of built-in window function cume_dist(). Assumes that
** the window frame has been set to:
**
** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
*/
static void cume_distStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
p->nTotal++;
}
}
static void cume_distInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct CallCount *p;
UNUSED_PARAMETER(nArg); assert( nArg==0 );
UNUSED_PARAMETER(apArg);
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
p->nStep++;
}
static void cume_distValueFunc(sqlite3_context *pCtx){
struct CallCount *p;
p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
if( p ){
double r = (double)(p->nStep) / (double)(p->nTotal);
sqlite3_result_double(pCtx, r);
}
}
#define cume_distFinalizeFunc cume_distValueFunc
/*
** Context object for ntile() window function.
*/
struct NtileCtx {
i64 nTotal; /* Total rows in partition */
i64 nParam; /* Parameter passed to ntile(N) */
i64 iRow; /* Current row */
};
/*
** Implementation of ntile(). This assumes that the window frame has
** been coerced to:
**
** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
*/
static void ntileStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NtileCtx *p;
assert( nArg==1 ); UNUSED_PARAMETER(nArg);
p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
if( p->nTotal==0 ){
p->nParam = sqlite3_value_int64(apArg[0]);
if( p->nParam<=0 ){
sqlite3_result_error(
pCtx, "argument of ntile must be a positive integer", -1
);
}
}
p->nTotal++;
}
}
static void ntileInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct NtileCtx *p;
assert( nArg==1 ); UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
p->iRow++;
}
static void ntileValueFunc(sqlite3_context *pCtx){
struct NtileCtx *p;
p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->nParam>0 ){
int nSize = (p->nTotal / p->nParam);
if( nSize==0 ){
sqlite3_result_int64(pCtx, p->iRow+1);
}else{
i64 nLarge = p->nTotal - p->nParam*nSize;
i64 iSmall = nLarge*(nSize+1);
i64 iRow = p->iRow;
assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
if( iRow<iSmall ){
sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
}else{
sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
}
}
}
}
#define ntileFinalizeFunc ntileValueFunc
/*
** Context object for last_value() window function.
*/
struct LastValueCtx {
sqlite3_value *pVal;
int nVal;
};
/*
** Implementation of last_value().
*/
static void last_valueStepFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct LastValueCtx *p;
UNUSED_PARAMETER(nArg);
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p ){
sqlite3_value_free(p->pVal);
p->pVal = sqlite3_value_dup(apArg[0]);
if( p->pVal==0 ){
sqlite3_result_error_nomem(pCtx);
}else{
p->nVal++;
}
}
}
static void last_valueInvFunc(
sqlite3_context *pCtx,
int nArg,
sqlite3_value **apArg
){
struct LastValueCtx *p;
UNUSED_PARAMETER(nArg);
UNUSED_PARAMETER(apArg);
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( ALWAYS(p) ){
p->nVal--;
if( p->nVal==0 ){
sqlite3_value_free(p->pVal);
p->pVal = 0;
}
}
}
static void last_valueValueFunc(sqlite3_context *pCtx){
struct LastValueCtx *p;
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
if( p && p->pVal ){
sqlite3_result_value(pCtx, p->pVal);
}
}
static void last_valueFinalizeFunc(sqlite3_context *pCtx){
struct LastValueCtx *p;
p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
if( p && p->pVal ){
sqlite3_result_value(pCtx, p->pVal);
sqlite3_value_free(p->pVal);
p->pVal = 0;
}
}
/*
** Static names for the built-in window function names. These static
** names are used, rather than string literals, so that FuncDef objects
** can be associated with a particular window function by direct
** comparison of the zName pointer. Example:
**
** if( pFuncDef->zName==row_valueName ){ ... }
*/
static const char row_numberName[] = "row_number";
static const char dense_rankName[] = "dense_rank";
static const char rankName[] = "rank";
static const char percent_rankName[] = "percent_rank";
static const char cume_distName[] = "cume_dist";
static const char ntileName[] = "ntile";
static const char last_valueName[] = "last_value";
static const char nth_valueName[] = "nth_value";
static const char first_valueName[] = "first_value";
static const char leadName[] = "lead";
static const char lagName[] = "lag";
/*
** No-op implementations of xStep() and xFinalize(). Used as place-holders
** for built-in window functions that never call those interfaces.
**
** The noopValueFunc() is called but is expected to do nothing. The
** noopStepFunc() is never called, and so it is marked with NO_TEST to
** let the test coverage routine know not to expect this function to be
** invoked.
*/
static void noopStepFunc( /*NO_TEST*/
sqlite3_context *p, /*NO_TEST*/
int n, /*NO_TEST*/
sqlite3_value **a /*NO_TEST*/
){ /*NO_TEST*/
UNUSED_PARAMETER(p); /*NO_TEST*/
UNUSED_PARAMETER(n); /*NO_TEST*/
UNUSED_PARAMETER(a); /*NO_TEST*/
assert(0); /*NO_TEST*/
} /*NO_TEST*/
static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
/* Window functions that use all window interfaces: xStep, xFinal,
** xValue, and xInverse */
#define WINDOWFUNCALL(name,nArg,extra) { \
nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
name ## InvFunc, name ## Name, {0} \
}
/* Window functions that are implemented using bytecode and thus have
** no-op routines for their methods */
#define WINDOWFUNCNOOP(name,nArg,extra) { \
nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
noopStepFunc, noopValueFunc, noopValueFunc, \
noopStepFunc, name ## Name, {0} \
}
/* Window functions that use all window interfaces: xStep, the
** same routine for xFinalize and xValue and which never call
** xInverse. */
#define WINDOWFUNCX(name,nArg,extra) { \
nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
noopStepFunc, name ## Name, {0} \
}
/*
** Register those built-in window functions that are not also aggregates.
*/
void sqlite3WindowFunctions(void){
static FuncDef aWindowFuncs[] = {
WINDOWFUNCX(row_number, 0, 0),
WINDOWFUNCX(dense_rank, 0, 0),
WINDOWFUNCX(rank, 0, 0),
WINDOWFUNCALL(percent_rank, 0, 0),
WINDOWFUNCALL(cume_dist, 0, 0),
WINDOWFUNCALL(ntile, 1, 0),
WINDOWFUNCALL(last_value, 1, 0),
WINDOWFUNCALL(nth_value, 2, 0),
WINDOWFUNCALL(first_value, 1, 0),
WINDOWFUNCNOOP(lead, 1, 0),
WINDOWFUNCNOOP(lead, 2, 0),
WINDOWFUNCNOOP(lead, 3, 0),
WINDOWFUNCNOOP(lag, 1, 0),
WINDOWFUNCNOOP(lag, 2, 0),
WINDOWFUNCNOOP(lag, 3, 0),
};
sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
}
static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
Window *p;
for(p=pList; p; p=p->pNextWin){
if( sqlite3StrICmp(p->zName, zName)==0 ) break;
}
if( p==0 ){
sqlite3ErrorMsg(pParse, "no such window: %s", zName);
}
return p;
}
/*
** This function is called immediately after resolving the function name
** for a window function within a SELECT statement. Argument pList is a
** linked list of WINDOW definitions for the current SELECT statement.
** Argument pFunc is the function definition just resolved and pWin
** is the Window object representing the associated OVER clause. This
** function updates the contents of pWin as follows:
**
** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
** search list pList for a matching WINDOW definition, and update pWin
** accordingly. If no such WINDOW clause can be found, leave an error
** in pParse.
**
** * If the function is a built-in window function that requires the
** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
** of this file), pWin is updated here.
*/
void sqlite3WindowUpdate(
Parse *pParse,
Window *pList, /* List of named windows for this SELECT */
Window *pWin, /* Window frame to update */
FuncDef *pFunc /* Window function definition */
){
if( pWin->zName && pWin->eFrmType==0 ){
Window *p = windowFind(pParse, pList, pWin->zName);
if( p==0 ) return;
pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
pWin->eStart = p->eStart;
pWin->eEnd = p->eEnd;
pWin->eFrmType = p->eFrmType;
pWin->eExclude = p->eExclude;
}else{
sqlite3WindowChain(pParse, pWin, pList);
}
if( (pWin->eFrmType==TK_RANGE)
&& (pWin->pStart || pWin->pEnd)
&& (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
){
sqlite3ErrorMsg(pParse,
"RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
);
}else
if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
sqlite3 *db = pParse->db;
if( pWin->pFilter ){
sqlite3ErrorMsg(pParse,
"FILTER clause may only be used with aggregate window functions"
);
}else{
struct WindowUpdate {
const char *zFunc;
int eFrmType;
int eStart;
int eEnd;
} aUp[] = {
{ row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
{ dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
{ rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
{ percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
{ cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
{ ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
{ leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
{ lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
};
int i;
for(i=0; i<ArraySize(aUp); i++){
if( pFunc->zName==aUp[i].zFunc ){
sqlite3ExprDelete(db, pWin->pStart);
sqlite3ExprDelete(db, pWin->pEnd);
pWin->pEnd = pWin->pStart = 0;
pWin->eFrmType = aUp[i].eFrmType;
pWin->eStart = aUp[i].eStart;
pWin->eEnd = aUp[i].eEnd;
pWin->eExclude = 0;
if( pWin->eStart==TK_FOLLOWING ){
pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
}
break;
}
}
}
}
pWin->pFunc = pFunc;
}
/*
** Context object passed through sqlite3WalkExprList() to
** selectWindowRewriteExprCb() by selectWindowRewriteEList().
*/
typedef struct WindowRewrite WindowRewrite;
struct WindowRewrite {
Window *pWin;
SrcList *pSrc;
ExprList *pSub;
Table *pTab;
Select *pSubSelect; /* Current sub-select, if any */
};
/*
** Callback function used by selectWindowRewriteEList(). If necessary,
** this function appends to the output expression-list and updates
** expression (*ppExpr) in place.
*/
static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
struct WindowRewrite *p = pWalker->u.pRewrite;
Parse *pParse = pWalker->pParse;
assert( p!=0 );
assert( p->pWin!=0 );
/* If this function is being called from within a scalar sub-select
** that used by the SELECT statement being processed, only process
** TK_COLUMN expressions that refer to it (the outer SELECT). Do
** not process aggregates or window functions at all, as they belong
** to the scalar sub-select. */
if( p->pSubSelect ){
if( pExpr->op!=TK_COLUMN ){
return WRC_Continue;
}else{
int nSrc = p->pSrc->nSrc;
int i;
for(i=0; i<nSrc; i++){
if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
}
if( i==nSrc ) return WRC_Continue;
}
}
switch( pExpr->op ){
case TK_FUNCTION:
if( !ExprHasProperty(pExpr, EP_WinFunc) ){
break;
}else{
Window *pWin;
for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
if( pExpr->y.pWin==pWin ){
assert( pWin->pOwner==pExpr );
return WRC_Prune;
}
}
}
/* Fall through. */
case TK_AGG_FUNCTION:
case TK_COLUMN: {
int iCol = -1;
if( p->pSub ){
int i;
for(i=0; i<p->pSub->nExpr; i++){
if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
iCol = i;
break;
}
}
}
if( iCol<0 ){
Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
}
if( p->pSub ){
assert( ExprHasProperty(pExpr, EP_Static)==0 );
ExprSetProperty(pExpr, EP_Static);
sqlite3ExprDelete(pParse->db, pExpr);
ExprClearProperty(pExpr, EP_Static);
memset(pExpr, 0, sizeof(Expr));
pExpr->op = TK_COLUMN;
pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
pExpr->iTable = p->pWin->iEphCsr;
pExpr->y.pTab = p->pTab;
}
if( pParse->db->mallocFailed ) return WRC_Abort;
break;
}
default: /* no-op */
break;
}
return WRC_Continue;
}
static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
struct WindowRewrite *p = pWalker->u.pRewrite;
Select *pSave = p->pSubSelect;
if( pSave==pSelect ){
return WRC_Continue;
}else{
p->pSubSelect = pSelect;
sqlite3WalkSelect(pWalker, pSelect);
p->pSubSelect = pSave;
}
return WRC_Prune;
}
/*
** Iterate through each expression in expression-list pEList. For each:
**
** * TK_COLUMN,
** * aggregate function, or
** * window function with a Window object that is not a member of the
** Window list passed as the second argument (pWin).
**
** Append the node to output expression-list (*ppSub). And replace it
** with a TK_COLUMN that reads the (N-1)th element of table
** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
** appending the new one.
*/
static void selectWindowRewriteEList(
Parse *pParse,
Window *pWin,
SrcList *pSrc,
ExprList *pEList, /* Rewrite expressions in this list */
Table *pTab,
ExprList **ppSub /* IN/OUT: Sub-select expression-list */
){
Walker sWalker;
WindowRewrite sRewrite;
assert( pWin!=0 );
memset(&sWalker, 0, sizeof(Walker));
memset(&sRewrite, 0, sizeof(WindowRewrite));
sRewrite.pSub = *ppSub;
sRewrite.pWin = pWin;
sRewrite.pSrc = pSrc;
sRewrite.pTab = pTab;
sWalker.pParse = pParse;
sWalker.xExprCallback = selectWindowRewriteExprCb;
sWalker.xSelectCallback = selectWindowRewriteSelectCb;
sWalker.u.pRewrite = &sRewrite;
(void)sqlite3WalkExprList(&sWalker, pEList);
*ppSub = sRewrite.pSub;
}
/*
** Append a copy of each expression in expression-list pAppend to
** expression list pList. Return a pointer to the result list.
*/
static ExprList *exprListAppendList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
ExprList *pAppend, /* List of values to append. Might be NULL */
int bIntToNull
){
if( pAppend ){
int i;
int nInit = pList ? pList->nExpr : 0;
for(i=0; i<pAppend->nExpr; i++){
Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
pDup->op = TK_NULL;
pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
pDup->u.zToken = 0;
}
pList = sqlite3ExprListAppend(pParse, pList, pDup);
if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
}
}
return pList;
}
/*
** If the SELECT statement passed as the second argument does not invoke
** any SQL window functions, this function is a no-op. Otherwise, it
** rewrites the SELECT statement so that window function xStep functions
** are invoked in the correct order as described under "SELECT REWRITING"
** at the top of this file.
*/
int sqlite3WindowRewrite(Parse *pParse, Select *p){
int rc = SQLITE_OK;
if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
Vdbe *v = sqlite3GetVdbe(pParse);
sqlite3 *db = pParse->db;
Select *pSub = 0; /* The subquery */
SrcList *pSrc = p->pSrc;
Expr *pWhere = p->pWhere;
ExprList *pGroupBy = p->pGroupBy;
Expr *pHaving = p->pHaving;
ExprList *pSort = 0;
ExprList *pSublist = 0; /* Expression list for sub-query */
Window *pMWin = p->pWin; /* Master window object */
Window *pWin; /* Window object iterator */
Table *pTab;
pTab = sqlite3DbMallocZero(db, sizeof(Table));
if( pTab==0 ){
return sqlite3ErrorToParser(db, SQLITE_NOMEM);
}
p->pSrc = 0;
p->pWhere = 0;
p->pGroupBy = 0;
p->pHaving = 0;
p->selFlags &= ~SF_Aggregate;
p->selFlags |= SF_WinRewrite;
/* Create the ORDER BY clause for the sub-select. This is the concatenation
** of the window PARTITION and ORDER BY clauses. Then, if this makes it
** redundant, remove the ORDER BY from the parent SELECT. */
pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
int nSave = pSort->nExpr;
pSort->nExpr = p->pOrderBy->nExpr;
if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
sqlite3ExprListDelete(db, p->pOrderBy);
p->pOrderBy = 0;
}
pSort->nExpr = nSave;
}
/* Assign a cursor number for the ephemeral table used to buffer rows.
** The OpenEphemeral instruction is coded later, after it is known how
** many columns the table will have. */
pMWin->iEphCsr = pParse->nTab++;
pParse->nTab += 3;
selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
/* Append the PARTITION BY and ORDER BY expressions to the to the
** sub-select expression list. They are required to figure out where
** boundaries for partitions and sets of peer rows lie. */
pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
/* Append the arguments passed to each window function to the
** sub-select expression list. Also allocate two registers for each
** window function - one for the accumulator, another for interim
** results. */
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
ExprList *pArgs = pWin->pOwner->x.pList;
if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
pWin->bExprArgs = 1;
}else{
pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
}
if( pWin->pFilter ){
Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
}
pWin->regAccum = ++pParse->nMem;
pWin->regResult = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
}
/* If there is no ORDER BY or PARTITION BY clause, and the window
** function accepts zero arguments, and there are no other columns
** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
** that pSublist is still NULL here. Add a constant expression here to
** keep everything legal in this case.
*/
if( pSublist==0 ){
pSublist = sqlite3ExprListAppend(pParse, 0,
sqlite3Expr(db, TK_INTEGER, "0")
);
}
pSub = sqlite3SelectNew(
pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
);
p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( p->pSrc ){
Table *pTab2;
p->pSrc->a[0].pSelect = pSub;
sqlite3SrcListAssignCursors(pParse, p->pSrc);
pSub->selFlags |= SF_Expanded;
pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
if( pTab2==0 ){
rc = SQLITE_NOMEM;
}else{
memcpy(pTab, pTab2, sizeof(Table));
pTab->tabFlags |= TF_Ephemeral;
p->pSrc->a[0].pTab = pTab;
pTab = pTab2;
}
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
}else{
sqlite3SelectDelete(db, pSub);
}
if( db->mallocFailed ) rc = SQLITE_NOMEM;
sqlite3DbFree(db, pTab);
}
if( rc && pParse->nErr==0 ){
assert( pParse->db->mallocFailed );
return sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
}
return rc;
}
/*
** Unlink the Window object from the Select to which it is attached,
** if it is attached.
*/
void sqlite3WindowUnlinkFromSelect(Window *p){
if( p->ppThis ){
*p->ppThis = p->pNextWin;
if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
p->ppThis = 0;
}
}
/*
** Free the Window object passed as the second argument.
*/
void sqlite3WindowDelete(sqlite3 *db, Window *p){
if( p ){
sqlite3WindowUnlinkFromSelect(p);
sqlite3ExprDelete(db, p->pFilter);
sqlite3ExprListDelete(db, p->pPartition);
sqlite3ExprListDelete(db, p->pOrderBy);
sqlite3ExprDelete(db, p->pEnd);
sqlite3ExprDelete(db, p->pStart);
sqlite3DbFree(db, p->zName);
sqlite3DbFree(db, p->zBase);
sqlite3DbFree(db, p);
}
}
/*
** Free the linked list of Window objects starting at the second argument.
*/
void sqlite3WindowListDelete(sqlite3 *db, Window *p){
while( p ){
Window *pNext = p->pNextWin;
sqlite3WindowDelete(db, p);
p = pNext;
}
}
/*
** The argument expression is an PRECEDING or FOLLOWING offset. The
** value should be a non-negative integer. If the value is not a
** constant, change it to NULL. The fact that it is then a non-negative
** integer will be caught later. But it is important not to leave
** variable values in the expression tree.
*/
static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
if( 0==sqlite3ExprIsConstant(pExpr) ){
if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
sqlite3ExprDelete(pParse->db, pExpr);
pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
}
return pExpr;
}
/*
** Allocate and return a new Window object describing a Window Definition.
*/
Window *sqlite3WindowAlloc(
Parse *pParse, /* Parsing context */
int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
u8 eExclude /* EXCLUDE clause */
){
Window *pWin = 0;
int bImplicitFrame = 0;
/* Parser assures the following: */
assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
|| eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
|| eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
if( eType==0 ){
bImplicitFrame = 1;
eType = TK_RANGE;
}
/* Additionally, the
** starting boundary type may not occur earlier in the following list than
** the ending boundary type:
**
** UNBOUNDED PRECEDING
** <expr> PRECEDING
** CURRENT ROW
** <expr> FOLLOWING
** UNBOUNDED FOLLOWING
**
** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
** frame boundary.
*/
if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
|| (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
){
sqlite3ErrorMsg(pParse, "unsupported frame specification");
goto windowAllocErr;
}
pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
if( pWin==0 ) goto windowAllocErr;
pWin->eFrmType = eType;
pWin->eStart = eStart;
pWin->eEnd = eEnd;
if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
eExclude = TK_NO;
}
pWin->eExclude = eExclude;
pWin->bImplicitFrame = bImplicitFrame;
pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
return pWin;
windowAllocErr:
sqlite3ExprDelete(pParse->db, pEnd);
sqlite3ExprDelete(pParse->db, pStart);
return 0;
}
/*
** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
** equivalent nul-terminated string.
*/
Window *sqlite3WindowAssemble(
Parse *pParse,
Window *pWin,
ExprList *pPartition,
ExprList *pOrderBy,
Token *pBase
){
if( pWin ){
pWin->pPartition = pPartition;
pWin->pOrderBy = pOrderBy;
if( pBase ){
pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
}
}else{
sqlite3ExprListDelete(pParse->db, pPartition);
sqlite3ExprListDelete(pParse->db, pOrderBy);
}
return pWin;
}
/*
** Window *pWin has just been created from a WINDOW clause. Tokne pBase
** is the base window. Earlier windows from the same WINDOW clause are
** stored in the linked list starting at pWin->pNextWin. This function
** either updates *pWin according to the base specification, or else
** leaves an error in pParse.
*/
void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
if( pWin->zBase ){
sqlite3 *db = pParse->db;
Window *pExist = windowFind(pParse, pList, pWin->zBase);
if( pExist ){
const char *zErr = 0;
/* Check for errors */
if( pWin->pPartition ){
zErr = "PARTITION clause";
}else if( pExist->pOrderBy && pWin->pOrderBy ){
zErr = "ORDER BY clause";
}else if( pExist->bImplicitFrame==0 ){
zErr = "frame specification";
}
if( zErr ){
sqlite3ErrorMsg(pParse,
"cannot override %s of window: %s", zErr, pWin->zBase
);
}else{
pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
if( pExist->pOrderBy ){
assert( pWin->pOrderBy==0 );
pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
}
sqlite3DbFree(db, pWin->zBase);
pWin->zBase = 0;
}
}
}
}
/*
** Attach window object pWin to expression p.
*/
void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
if( p ){
assert( p->op==TK_FUNCTION );
assert( pWin );
p->y.pWin = pWin;
ExprSetProperty(p, EP_WinFunc);
pWin->pOwner = p;
if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
sqlite3ErrorMsg(pParse,
"DISTINCT is not supported for window functions"
);
}
}else{
sqlite3WindowDelete(pParse->db, pWin);
}
}
/*
** Possibly link window pWin into the list at pSel->pWin (window functions
** to be processed as part of SELECT statement pSel). The window is linked
** in if either (a) there are no other windows already linked to this
** SELECT, or (b) the windows already linked use a compatible window frame.
*/
void sqlite3WindowLink(Select *pSel, Window *pWin){
if( pSel!=0
&& (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
){
pWin->pNextWin = pSel->pWin;
if( pSel->pWin ){
pSel->pWin->ppThis = &pWin->pNextWin;
}
pSel->pWin = pWin;
pWin->ppThis = &pSel->pWin;
}
}
/*
** Return 0 if the two window objects are identical, or non-zero otherwise.
** Identical window objects can be processed in a single scan.
*/
int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
if( p1->eFrmType!=p2->eFrmType ) return 1;
if( p1->eStart!=p2->eStart ) return 1;
if( p1->eEnd!=p2->eEnd ) return 1;
if( p1->eExclude!=p2->eExclude ) return 1;
if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
if( bFilter ){
if( sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1) ) return 1;
}
return 0;
}
/*
** This is called by code in select.c before it calls sqlite3WhereBegin()
** to begin iterating through the sub-query results. It is used to allocate
** and initialize registers and cursors used by sqlite3WindowCodeStep().
*/
void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
Window *pWin;
Vdbe *v = sqlite3GetVdbe(pParse);
/* Allocate registers to use for PARTITION BY values, if any. Initialize
** said registers to NULL. */
if( pMWin->pPartition ){
int nExpr = pMWin->pPartition->nExpr;
pMWin->regPart = pParse->nMem+1;
pParse->nMem += nExpr;
sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
}
pMWin->regOne = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
if( pMWin->eExclude ){
pMWin->regStartRowid = ++pParse->nMem;
pMWin->regEndRowid = ++pParse->nMem;
pMWin->csrApp = pParse->nTab++;
sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
return;
}
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *p = pWin->pFunc;
if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
/* The inline versions of min() and max() require a single ephemeral
** table and 3 registers. The registers are used as follows:
**
** regApp+0: slot to copy min()/max() argument to for MakeRecord
** regApp+1: integer value used to ensure keys are unique
** regApp+2: output of MakeRecord
*/
ExprList *pList = pWin->pOwner->x.pList;
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
pWin->csrApp = pParse->nTab++;
pWin->regApp = pParse->nMem+1;
pParse->nMem += 3;
if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
assert( pKeyInfo->aSortFlags[0]==0 );
pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
}
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
}
else if( p->zName==nth_valueName || p->zName==first_valueName ){
/* Allocate two registers at pWin->regApp. These will be used to
** store the start and end index of the current frame. */
pWin->regApp = pParse->nMem+1;
pWin->csrApp = pParse->nTab++;
pParse->nMem += 2;
sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
}
else if( p->zName==leadName || p->zName==lagName ){
pWin->csrApp = pParse->nTab++;
sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
}
}
}
#define WINDOW_STARTING_INT 0
#define WINDOW_ENDING_INT 1
#define WINDOW_NTH_VALUE_INT 2
#define WINDOW_STARTING_NUM 3
#define WINDOW_ENDING_NUM 4
/*
** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
** value of the second argument to nth_value() (eCond==2) has just been
** evaluated and the result left in register reg. This function generates VM
** code to check that the value is a non-negative integer and throws an
** exception if it is not.
*/
static void windowCheckValue(Parse *pParse, int reg, int eCond){
static const char *azErr[] = {
"frame starting offset must be a non-negative integer",
"frame ending offset must be a non-negative integer",
"second argument to nth_value must be a positive integer",
"frame starting offset must be a non-negative number",
"frame ending offset must be a non-negative number",
};
static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
Vdbe *v = sqlite3GetVdbe(pParse);
int regZero = sqlite3GetTempReg(pParse);
assert( eCond>=0 && eCond<ArraySize(azErr) );
sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
if( eCond>=WINDOW_STARTING_NUM ){
int regString = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
VdbeCoverage(v);
assert( eCond==3 || eCond==4 );
VdbeCoverageIf(v, eCond==3);
VdbeCoverageIf(v, eCond==4);
}else{
sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
VdbeCoverage(v);
assert( eCond==0 || eCond==1 || eCond==2 );
VdbeCoverageIf(v, eCond==0);
VdbeCoverageIf(v, eCond==1);
VdbeCoverageIf(v, eCond==2);
}
sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
VdbeCoverageNeverNullIf(v, eCond==2);
VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
sqlite3MayAbort(pParse);
sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
sqlite3ReleaseTempReg(pParse, regZero);
}
/*
** Return the number of arguments passed to the window-function associated
** with the object passed as the only argument to this function.
*/
static int windowArgCount(Window *pWin){
ExprList *pList = pWin->pOwner->x.pList;
return (pList ? pList->nExpr : 0);
}
typedef struct WindowCodeArg WindowCodeArg;
typedef struct WindowCsrAndReg WindowCsrAndReg;
/*
** See comments above struct WindowCodeArg.
*/
struct WindowCsrAndReg {
int csr; /* Cursor number */
int reg; /* First in array of peer values */
};
/*
** A single instance of this structure is allocated on the stack by
** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
** routines. This is to reduce the number of arguments required by each
** helper function.
**
** regArg:
** Each window function requires an accumulator register (just as an
** ordinary aggregate function does). This variable is set to the first
** in an array of accumulator registers - one for each window function
** in the WindowCodeArg.pMWin list.
**
** eDelete:
** The window functions implementation sometimes caches the input rows
** that it processes in a temporary table. If it is not zero, this
** variable indicates when rows may be removed from the temp table (in
** order to reduce memory requirements - it would always be safe just
** to leave them there). Possible values for eDelete are:
**
** WINDOW_RETURN_ROW:
** An input row can be discarded after it is returned to the caller.
**
** WINDOW_AGGINVERSE:
** An input row can be discarded after the window functions xInverse()
** callbacks have been invoked in it.
**
** WINDOW_AGGSTEP:
** An input row can be discarded after the window functions xStep()
** callbacks have been invoked in it.
**
** start,current,end
** Consider a window-frame similar to the following:
**
** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
**
** The windows functions implmentation caches the input rows in a temp
** table, sorted by "a, b" (it actually populates the cache lazily, and
** aggressively removes rows once they are no longer required, but that's
** a mere detail). It keeps three cursors open on the temp table. One
** (current) that points to the next row to return to the query engine
** once its window function values have been calculated. Another (end)
** points to the next row to call the xStep() method of each window function
** on (so that it is 2 groups ahead of current). And a third (start) that
** points to the next row to call the xInverse() method of each window
** function on.
**
** Each cursor (start, current and end) consists of a VDBE cursor
** (WindowCsrAndReg.csr) and an array of registers (starting at
** WindowCodeArg.reg) that always contains a copy of the peer values
** read from the corresponding cursor.
**
** Depending on the window-frame in question, all three cursors may not
** be required. In this case both WindowCodeArg.csr and reg are set to
** 0.
*/
struct WindowCodeArg {
Parse *pParse; /* Parse context */
Window *pMWin; /* First in list of functions being processed */
Vdbe *pVdbe; /* VDBE object */
int addrGosub; /* OP_Gosub to this address to return one row */
int regGosub; /* Register used with OP_Gosub(addrGosub) */
int regArg; /* First in array of accumulator registers */
int eDelete; /* See above */
WindowCsrAndReg start;
WindowCsrAndReg current;
WindowCsrAndReg end;
};
/*
** Generate VM code to read the window frames peer values from cursor csr into
** an array of registers starting at reg.
*/
static void windowReadPeerValues(
WindowCodeArg *p,
int csr,
int reg
){
Window *pMWin = p->pMWin;
ExprList *pOrderBy = pMWin->pOrderBy;
if( pOrderBy ){
Vdbe *v = sqlite3GetVdbe(p->pParse);
ExprList *pPart = pMWin->pPartition;
int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
int i;
for(i=0; i<pOrderBy->nExpr; i++){
sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
}
}
}
/*
** Generate VM code to invoke either xStep() (if bInverse is 0) or
** xInverse (if bInverse is non-zero) for each window function in the
** linked list starting at pMWin. Or, for built-in window functions
** that do not use the standard function API, generate the required
** inline VM code.
**
** If argument csr is greater than or equal to 0, then argument reg is
** the first register in an array of registers guaranteed to be large
** enough to hold the array of arguments for each function. In this case
** the arguments are extracted from the current row of csr into the
** array of registers before invoking OP_AggStep or OP_AggInverse
**
** Or, if csr is less than zero, then the array of registers at reg is
** already populated with all columns from the current row of the sub-query.
**
** If argument regPartSize is non-zero, then it is a register containing the
** number of rows in the current partition.
*/
static void windowAggStep(
WindowCodeArg *p,
Window *pMWin, /* Linked list of window functions */
int csr, /* Read arguments from this cursor */
int bInverse, /* True to invoke xInverse instead of xStep */
int reg /* Array of registers */
){
Parse *pParse = p->pParse;
Vdbe *v = sqlite3GetVdbe(pParse);
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
int regArg;
int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
int i;
assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
/* All OVER clauses in the same window function aggregate step must
** be the same. */
assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)==0 );
for(i=0; i<nArg; i++){
if( i!=1 || pFunc->zName!=nth_valueName ){
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
}else{
sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
}
}
regArg = reg;
if( pMWin->regStartRowid==0
&& (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
&& (pWin->eStart!=TK_UNBOUNDED)
){
int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
VdbeCoverage(v);
if( bInverse==0 ){
sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
}else{
sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
VdbeCoverageNeverTaken(v);
sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
}
sqlite3VdbeJumpHere(v, addrIsNull);
}else if( pWin->regApp ){
assert( pFunc->zName==nth_valueName
|| pFunc->zName==first_valueName
);
assert( bInverse==0 || bInverse==1 );
sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
}else if( pFunc->xSFunc!=noopStepFunc ){
int addrIf = 0;
if( pWin->pFilter ){
int regTmp;
assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
regTmp = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, regTmp);
}
if( pWin->bExprArgs ){
int iStart = sqlite3VdbeCurrentAddr(v);
VdbeOp *pOp, *pEnd;
nArg = pWin->pOwner->x.pList->nExpr;
regArg = sqlite3GetTempRange(pParse, nArg);
sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
pEnd = sqlite3VdbeGetOp(v, -1);
for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
pOp->p1 = csr;
}
}
}
if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
CollSeq *pColl;
assert( nArg>0 );
pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
}
sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
bInverse, regArg, pWin->regAccum);
sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
sqlite3VdbeChangeP5(v, (u8)nArg);
if( pWin->bExprArgs ){
sqlite3ReleaseTempRange(pParse, regArg, nArg);
}
if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
}
}
}
/*
** Values that may be passed as the second argument to windowCodeOp().
*/
#define WINDOW_RETURN_ROW 1
#define WINDOW_AGGINVERSE 2
#define WINDOW_AGGSTEP 3
/*
** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
** (bFin==1) for each window function in the linked list starting at
** pMWin. Or, for built-in window-functions that do not use the standard
** API, generate the equivalent VM code.
*/
static void windowAggFinal(WindowCodeArg *p, int bFin){
Parse *pParse = p->pParse;
Window *pMWin = p->pMWin;
Vdbe *v = sqlite3GetVdbe(pParse);
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
if( pMWin->regStartRowid==0
&& (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
&& (pWin->eStart!=TK_UNBOUNDED)
){
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
}else if( pWin->regApp ){
assert( pMWin->regStartRowid==0 );
}else{
int nArg = windowArgCount(pWin);
if( bFin ){
sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
}else{
sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
}
}
}
}
/*
** Generate code to calculate the current values of all window functions in the
** p->pMWin list by doing a full scan of the current window frame. Store the
** results in the Window.regResult registers, ready to return the upper
** layer.
*/
static void windowFullScan(WindowCodeArg *p){
Window *pWin;
Parse *pParse = p->pParse;
Window *pMWin = p->pMWin;
Vdbe *v = p->pVdbe;
int regCRowid = 0; /* Current rowid value */
int regCPeer = 0; /* Current peer values */
int regRowid = 0; /* AggStep rowid value */
int regPeer = 0; /* AggStep peer values */
int nPeer;
int lblNext;
int lblBrk;
int addrNext;
int csr;
VdbeModuleComment((v, "windowFullScan begin"));
assert( pMWin!=0 );
csr = pMWin->csrApp;
nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
lblNext = sqlite3VdbeMakeLabel(pParse);
lblBrk = sqlite3VdbeMakeLabel(pParse);
regCRowid = sqlite3GetTempReg(pParse);
regRowid = sqlite3GetTempReg(pParse);
if( nPeer ){
regCPeer = sqlite3GetTempRange(pParse, nPeer);
regPeer = sqlite3GetTempRange(pParse, nPeer);
}
sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
}
sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
VdbeCoverage(v);
addrNext = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
VdbeCoverageNeverNull(v);
if( pMWin->eExclude==TK_CURRENT ){
sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
VdbeCoverageNeverNull(v);
}else if( pMWin->eExclude!=TK_NO ){
int addr;
int addrEq = 0;
KeyInfo *pKeyInfo = 0;
if( pMWin->pOrderBy ){
pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
}
if( pMWin->eExclude==TK_TIES ){
addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
VdbeCoverageNeverNull(v);
}
if( pKeyInfo ){
windowReadPeerValues(p, csr, regPeer);
sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
addr = sqlite3VdbeCurrentAddr(v)+1;
sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
VdbeCoverageEqNe(v);
}else{
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
}
if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
}
windowAggStep(p, pMWin, csr, 0, p->regArg);
sqlite3VdbeResolveLabel(v, lblNext);
sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addrNext-1);
sqlite3VdbeJumpHere(v, addrNext+1);
sqlite3ReleaseTempReg(pParse, regRowid);
sqlite3ReleaseTempReg(pParse, regCRowid);
if( nPeer ){
sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
}
windowAggFinal(p, 1);
VdbeModuleComment((v, "windowFullScan end"));
}
/*
** Invoke the sub-routine at regGosub (generated by code in select.c) to
** return the current row of Window.iEphCsr. If all window functions are
** aggregate window functions that use the standard API, a single
** OP_Gosub instruction is all that this routine generates. Extra VM code
** for per-row processing is only generated for the following built-in window
** functions:
**
** nth_value()
** first_value()
** lag()
** lead()
*/
static void windowReturnOneRow(WindowCodeArg *p){
Window *pMWin = p->pMWin;
Vdbe *v = p->pVdbe;
if( pMWin->regStartRowid ){
windowFullScan(p);
}else{
Parse *pParse = p->pParse;
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
if( pFunc->zName==nth_valueName
|| pFunc->zName==first_valueName
){
int csr = pWin->csrApp;
int lbl = sqlite3VdbeMakeLabel(pParse);
int tmpReg = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
if( pFunc->zName==nth_valueName ){
sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
windowCheckValue(pParse, tmpReg, 2);
}else{
sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
}
sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
VdbeCoverageNeverNull(v);
sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
VdbeCoverageNeverTaken(v);
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
sqlite3VdbeResolveLabel(v, lbl);
sqlite3ReleaseTempReg(pParse, tmpReg);
}
else if( pFunc->zName==leadName || pFunc->zName==lagName ){
int nArg = pWin->pOwner->x.pList->nExpr;
int csr = pWin->csrApp;
int lbl = sqlite3VdbeMakeLabel(pParse);
int tmpReg = sqlite3GetTempReg(pParse);
int iEph = pMWin->iEphCsr;
if( nArg<3 ){
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
}else{
sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
}
sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
if( nArg<2 ){
int val = (pFunc->zName==leadName ? 1 : -1);
sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
}else{
int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
int tmpReg2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
sqlite3ReleaseTempReg(pParse, tmpReg2);
}
sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
sqlite3VdbeResolveLabel(v, lbl);
sqlite3ReleaseTempReg(pParse, tmpReg);
}
}
}
sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
}
/*
** Generate code to set the accumulator register for each window function
** in the linked list passed as the second argument to NULL. And perform
** any equivalent initialization required by any built-in window functions
** in the list.
*/
static int windowInitAccum(Parse *pParse, Window *pMWin){
Vdbe *v = sqlite3GetVdbe(pParse);
int regArg;
int nArg = 0;
Window *pWin;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
nArg = MAX(nArg, windowArgCount(pWin));
if( pMWin->regStartRowid==0 ){
if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
}
if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
assert( pWin->eStart!=TK_UNBOUNDED );
sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
}
}
}
regArg = pParse->nMem+1;
pParse->nMem += nArg;
return regArg;
}
/*
** Return true if the current frame should be cached in the ephemeral table,
** even if there are no xInverse() calls required.
*/
static int windowCacheFrame(Window *pMWin){
Window *pWin;
if( pMWin->regStartRowid ) return 1;
for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
FuncDef *pFunc = pWin->pFunc;
if( (pFunc->zName==nth_valueName)
|| (pFunc->zName==first_valueName)
|| (pFunc->zName==leadName)
|| (pFunc->zName==lagName)
){
return 1;
}
}
return 0;
}
/*
** regOld and regNew are each the first register in an array of size
** pOrderBy->nExpr. This function generates code to compare the two
** arrays of registers using the collation sequences and other comparison
** parameters specified by pOrderBy.
**
** If the two arrays are not equal, the contents of regNew is copied to
** regOld and control falls through. Otherwise, if the contents of the arrays
** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
*/
static void windowIfNewPeer(
Parse *pParse,
ExprList *pOrderBy,
int regNew, /* First in array of new values */
int regOld, /* First in array of old values */
int addr /* Jump here */
){
Vdbe *v = sqlite3GetVdbe(pParse);
if( pOrderBy ){
int nVal = pOrderBy->nExpr;
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump,
sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
);
VdbeCoverageEqNe(v);
sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
}else{
sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
}
}
/*
** This function is called as part of generating VM programs for RANGE
** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
** code equivalent to:
**
** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
**
** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
**
** If the sort-order for the ORDER BY term in the window is DESC, then the
** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
** is OP_Ge, the generated code is equivalent to:
**
** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
**
** A special type of arithmetic is used such that if csr1.peerVal is not
** a numeric type (real or integer), then the result of the addition addition
** or subtraction is a a copy of csr1.peerVal.
*/
static void windowCodeRangeTest(
WindowCodeArg *p,
int op, /* OP_Ge, OP_Gt, or OP_Le */
int csr1, /* Cursor number for cursor 1 */
int regVal, /* Register containing non-negative number */
int csr2, /* Cursor number for cursor 2 */
int lbl /* Jump destination if condition is true */
){
Parse *pParse = p->pParse;
Vdbe *v = sqlite3GetVdbe(pParse);
ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
int regString = ++pParse->nMem; /* Reg. for constant value '' */
int arith = OP_Add; /* OP_Add or OP_Subtract */
int addrGe; /* Jump destination */
assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
assert( pOrderBy && pOrderBy->nExpr==1 );
if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
switch( op ){
case OP_Ge: op = OP_Le; break;
case OP_Gt: op = OP_Lt; break;
default: assert( op==OP_Le ); op = OP_Ge; break;
}
arith = OP_Subtract;
}
/* Read the peer-value from each cursor into a register */
windowReadPeerValues(p, csr1, reg1);
windowReadPeerValues(p, csr2, reg2);
VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
reg1, (arith==OP_Add ? "+" : "-"), regVal,
((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
));
/* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
** This block adds (or subtracts for DESC) the numeric value in regVal
** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
** then leave reg1 as it is. In pseudo-code, this is implemented as:
**
** if( reg1>='' ) goto addrGe;
** reg1 = reg1 +/- regVal
** addrGe:
**
** Since all strings and blobs are greater-than-or-equal-to an empty string,
** the add/subtract is skipped for these, as required. If reg1 is a NULL,
** then the arithmetic is performed, but since adding or subtracting from
** NULL is always NULL anyway, this case is handled as required too. */
sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
sqlite3VdbeJumpHere(v, addrGe);
/* If the BIGNULL flag is set for the ORDER BY, then it is required to
** consider NULL values to be larger than all other values, instead of
** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
** (and adding that capability causes a performance regression), so
** instead if the BIGNULL flag is set then cases where either reg1 or
** reg2 are NULL are handled separately in the following block. The code
** generated is equivalent to:
**
** if( reg1 IS NULL ){
** if( op==OP_Ge ) goto lbl;
** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
** if( op==OP_Le && reg2 IS NULL ) goto lbl;
** }else if( reg2 IS NULL ){
** if( op==OP_Le ) goto lbl;
** }
**
** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
** not taken, control jumps over the comparison operator coded below this
** block. */
if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
/* This block runs if reg1 contains a NULL. */
int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
switch( op ){
case OP_Ge:
sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
break;
case OP_Gt:
sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
VdbeCoverage(v);
break;
case OP_Le:
sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
VdbeCoverage(v);
break;
default: assert( op==OP_Lt ); /* no-op */ break;
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
/* This block runs if reg1 is not NULL, but reg2 is. */
sqlite3VdbeJumpHere(v, addr);
sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
if( op==OP_Gt || op==OP_Ge ){
sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
}
}
/* Compare registers reg2 and reg1, taking the jump if required. Note that
** control skips over this test if the BIGNULL flag is set and either
** reg1 or reg2 contain a NULL value. */
sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
sqlite3ReleaseTempReg(pParse, reg1);
sqlite3ReleaseTempReg(pParse, reg2);
VdbeModuleComment((v, "CodeRangeTest: end"));
}
/*
** Helper function for sqlite3WindowCodeStep(). Each call to this function
** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
** operation. Refer to the header comment for sqlite3WindowCodeStep() for
** details.
*/
static int windowCodeOp(
WindowCodeArg *p, /* Context object */
int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
int regCountdown, /* Register for OP_IfPos countdown */
int jumpOnEof /* Jump here if stepped cursor reaches EOF */
){
int csr, reg;
Parse *pParse = p->pParse;
Window *pMWin = p->pMWin;
int ret = 0;
Vdbe *v = p->pVdbe;
int addrContinue = 0;
int bPeer = (pMWin->eFrmType!=TK_ROWS);
int lblDone = sqlite3VdbeMakeLabel(pParse);
int addrNextRange = 0;
/* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
** starts with UNBOUNDED PRECEDING. */
if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
assert( regCountdown==0 && jumpOnEof==0 );
return 0;
}
if( regCountdown>0 ){
if( pMWin->eFrmType==TK_RANGE ){
addrNextRange = sqlite3VdbeCurrentAddr(v);
assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
if( op==WINDOW_AGGINVERSE ){
if( pMWin->eStart==TK_FOLLOWING ){
windowCodeRangeTest(
p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
);
}else{
windowCodeRangeTest(
p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
);
}
}else{
windowCodeRangeTest(
p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
);
}
}else{
sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
VdbeCoverage(v);
}
}
if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
windowAggFinal(p, 0);
}
addrContinue = sqlite3VdbeCurrentAddr(v);
/* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
** start cursor does not advance past the end cursor within the
** temporary table. It otherwise might, if (a>b). */
if( pMWin->eStart==pMWin->eEnd && regCountdown
&& pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
){
int regRowid1 = sqlite3GetTempReg(pParse);
int regRowid2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, regRowid1);
sqlite3ReleaseTempReg(pParse, regRowid2);
assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
}
switch( op ){
case WINDOW_RETURN_ROW:
csr = p->current.csr;
reg = p->current.reg;
windowReturnOneRow(p);
break;
case WINDOW_AGGINVERSE:
csr = p->start.csr;
reg = p->start.reg;
if( pMWin->regStartRowid ){
assert( pMWin->regEndRowid );
sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
}else{
windowAggStep(p, pMWin, csr, 1, p->regArg);
}
break;
default:
assert( op==WINDOW_AGGSTEP );
csr = p->end.csr;
reg = p->end.reg;
if( pMWin->regStartRowid ){
assert( pMWin->regEndRowid );
sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
}else{
windowAggStep(p, pMWin, csr, 0, p->regArg);
}
break;
}
if( op==p->eDelete ){
sqlite3VdbeAddOp1(v, OP_Delete, csr);
sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
}
if( jumpOnEof ){
sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
VdbeCoverage(v);
ret = sqlite3VdbeAddOp0(v, OP_Goto);
}else{
sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
VdbeCoverage(v);
if( bPeer ){
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
}
}
if( bPeer ){
int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
windowReadPeerValues(p, csr, regTmp);
windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
sqlite3ReleaseTempRange(pParse, regTmp, nReg);
}
if( addrNextRange ){
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
}
sqlite3VdbeResolveLabel(v, lblDone);
return ret;
}
/*
** Allocate and return a duplicate of the Window object indicated by the
** third argument. Set the Window.pOwner field of the new object to
** pOwner.
*/
Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
Window *pNew = 0;
if( ALWAYS(p) ){
pNew = sqlite3DbMallocZero(db, sizeof(Window));
if( pNew ){
pNew->zName = sqlite3DbStrDup(db, p->zName);
pNew->zBase = sqlite3DbStrDup(db, p->zBase);
pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
pNew->pFunc = p->pFunc;
pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
pNew->eFrmType = p->eFrmType;
pNew->eEnd = p->eEnd;
pNew->eStart = p->eStart;
pNew->eExclude = p->eExclude;
pNew->regResult = p->regResult;
pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
pNew->pOwner = pOwner;
pNew->bImplicitFrame = p->bImplicitFrame;
}
}
return pNew;
}
/*
** Return a copy of the linked list of Window objects passed as the
** second argument.
*/
Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
Window *pWin;
Window *pRet = 0;
Window **pp = &pRet;
for(pWin=p; pWin; pWin=pWin->pNextWin){
*pp = sqlite3WindowDup(db, 0, pWin);
if( *pp==0 ) break;
pp = &((*pp)->pNextWin);
}
return pRet;
}
/*
** Return true if it can be determined at compile time that expression
** pExpr evaluates to a value that, when cast to an integer, is greater
** than zero. False otherwise.
**
** If an OOM error occurs, this function sets the Parse.db.mallocFailed
** flag and returns zero.
*/
static int windowExprGtZero(Parse *pParse, Expr *pExpr){
int ret = 0;
sqlite3 *db = pParse->db;
sqlite3_value *pVal = 0;
sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
if( pVal && sqlite3_value_int(pVal)>0 ){
ret = 1;
}
sqlite3ValueFree(pVal);
return ret;
}
/*
** sqlite3WhereBegin() has already been called for the SELECT statement
** passed as the second argument when this function is invoked. It generates
** code to populate the Window.regResult register for each window function
** and invoke the sub-routine at instruction addrGosub once for each row.
** sqlite3WhereEnd() is always called before returning.
**
** This function handles several different types of window frames, which
** require slightly different processing. The following pseudo code is
** used to implement window frames of the form:
**
** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
**
** Other window frame types use variants of the following:
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
**
** if( first row of partition ){
** // Rewind three cursors, all open on the eph table.
** Rewind(csrEnd);
** Rewind(csrStart);
** Rewind(csrCurrent);
**
** regEnd = <expr2> // FOLLOWING expression
** regStart = <expr1> // PRECEDING expression
** }else{
** // First time this branch is taken, the eph table contains two
** // rows. The first row in the partition, which all three cursors
** // currently point to, and the following row.
** AGGSTEP
** if( (regEnd--)<=0 ){
** RETURN_ROW
** if( (regStart--)<=0 ){
** AGGINVERSE
** }
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** RETURN ROW
** if( csrCurrent is EOF ) break;
** if( (regStart--)<=0 ){
** AggInverse(csrStart)
** Next(csrStart)
** }
** }
**
** The pseudo-code above uses the following shorthand:
**
** AGGSTEP: invoke the aggregate xStep() function for each window function
** with arguments read from the current row of cursor csrEnd, then
** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
**
** RETURN_ROW: return a row to the caller based on the contents of the
** current row of csrCurrent and the current state of all
** aggregates. Then step cursor csrCurrent forward one row.
**
** AGGINVERSE: invoke the aggregate xInverse() function for each window
** functions with arguments read from the current row of cursor
** csrStart. Then step csrStart forward one row.
**
** There are two other ROWS window frames that are handled significantly
** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
** cases because they change the order in which the three cursors (csrStart,
** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
** three.
**
** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** if( (regEnd--)<=0 ){
** AGGSTEP
** }
** RETURN_ROW
** if( (regStart--)<=0 ){
** AGGINVERSE
** }
** }
** }
** flush:
** if( (regEnd--)<=0 ){
** AGGSTEP
** }
** RETURN_ROW
**
**
** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = regEnd - <expr1>
** }else{
** AGGSTEP
** if( (regEnd--)<=0 ){
** RETURN_ROW
** }
** if( (regStart--)<=0 ){
** AGGINVERSE
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** if( (regEnd--)<=0 ){
** RETURN_ROW
** if( eof ) break;
** }
** if( (regStart--)<=0 ){
** AGGINVERSE
** if( eof ) break
** }
** }
** while( !eof csrCurrent ){
** RETURN_ROW
** }
**
** For the most part, the patterns above are adapted to support UNBOUNDED by
** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
** This is optimized of course - branches that will never be taken and
** conditions that are always true are omitted from the VM code. The only
** exceptional case is:
**
** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regStart = <expr1>
** }else{
** AGGSTEP
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** if( (regStart--)<=0 ){
** AGGINVERSE
** if( eof ) break
** }
** RETURN_ROW
** }
** while( !eof csrCurrent ){
** RETURN_ROW
** }
**
** Also requiring special handling are the cases:
**
** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
**
** when (expr1 < expr2). This is detected at runtime, not by this function.
** To handle this case, the pseudo-code programs depicted above are modified
** slightly to be:
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** if( regEnd < regStart ){
** RETURN_ROW
** delete eph table contents
** continue
** }
** ...
**
** The new "continue" statement in the above jumps to the next iteration
** of the outer loop - the one started by sqlite3WhereBegin().
**
** The various GROUPS cases are implemented using the same patterns as
** ROWS. The VM code is modified slightly so that:
**
** 1. The else branch in the main loop is only taken if the row just
** added to the ephemeral table is the start of a new group. In
** other words, it becomes:
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else if( new group ){
** ...
** }
** }
**
** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
** AGGINVERSE step processes the current row of the relevant cursor and
** all subsequent rows belonging to the same group.
**
** RANGE window frames are a little different again. As for GROUPS, the
** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
** deal in groups instead of rows. As for ROWS and GROUPS, there are three
** basic cases:
**
** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** AGGSTEP
** while( (csrCurrent.key + regEnd) < csrEnd.key ){
** RETURN_ROW
** while( csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** RETURN ROW
** if( csrCurrent is EOF ) break;
** while( csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** }
** }
**
** In the above notation, "csr.key" means the current value of the ORDER BY
** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
** or <expr PRECEDING) read from cursor csr.
**
** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
** AGGSTEP
** }
** while( (csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** RETURN_ROW
** }
** }
** flush:
** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
** AGGSTEP
** }
** while( (csrStart.key + regStart) < csrCurrent.key ){
** AGGINVERSE
** }
** RETURN_ROW
**
** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
**
** ... loop started by sqlite3WhereBegin() ...
** if( new partition ){
** Gosub flush
** }
** Insert new row into eph table.
** if( first row of partition ){
** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
** regEnd = <expr2>
** regStart = <expr1>
** }else{
** AGGSTEP
** while( (csrCurrent.key + regEnd) < csrEnd.key ){
** while( (csrCurrent.key + regStart) > csrStart.key ){
** AGGINVERSE
** }
** RETURN_ROW
** }
** }
** }
** flush:
** AGGSTEP
** while( 1 ){
** while( (csrCurrent.key + regStart) > csrStart.key ){
** AGGINVERSE
** if( eof ) break "while( 1 )" loop.
** }
** RETURN_ROW
** }
** while( !eof csrCurrent ){
** RETURN_ROW
** }
**
** The text above leaves out many details. Refer to the code and comments
** below for a more complete picture.
*/
void sqlite3WindowCodeStep(
Parse *pParse, /* Parse context */
Select *p, /* Rewritten SELECT statement */
WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
int regGosub, /* Register for OP_Gosub */
int addrGosub /* OP_Gosub here to return each row */
){
Window *pMWin = p->pWin;
ExprList *pOrderBy = pMWin->pOrderBy;
Vdbe *v = sqlite3GetVdbe(pParse);
int csrWrite; /* Cursor used to write to eph. table */
int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
int iInput; /* To iterate through sub cols */
int addrNe; /* Address of OP_Ne */
int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
int addrInteger = 0; /* Address of OP_Integer */
int addrEmpty; /* Address of OP_Rewind in flush: */
int regNew; /* Array of registers holding new input row */
int regRecord; /* regNew array in record form */
int regRowid; /* Rowid for regRecord in eph table */
int regNewPeer = 0; /* Peer values for new row (part of regNew) */
int regPeer = 0; /* Peer values for current row */
int regFlushPart = 0; /* Register for "Gosub flush_partition" */
WindowCodeArg s; /* Context object for sub-routines */
int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
int regStart = 0; /* Value of <expr> PRECEDING */
int regEnd = 0; /* Value of <expr> FOLLOWING */
assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
|| pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
);
assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
|| pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
);
assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
|| pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
|| pMWin->eExclude==TK_NO
);
lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
/* Fill in the context object */
memset(&s, 0, sizeof(WindowCodeArg));
s.pParse = pParse;
s.pMWin = pMWin;
s.pVdbe = v;
s.regGosub = regGosub;
s.addrGosub = addrGosub;
s.current.csr = pMWin->iEphCsr;
csrWrite = s.current.csr+1;
s.start.csr = s.current.csr+2;
s.end.csr = s.current.csr+3;
/* Figure out when rows may be deleted from the ephemeral table. There
** are four options - they may never be deleted (eDelete==0), they may
** be deleted as soon as they are no longer part of the window frame
** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
** has been returned to the caller (WINDOW_RETURN_ROW), or they may
** be deleted after they enter the frame (WINDOW_AGGSTEP). */
switch( pMWin->eStart ){
case TK_FOLLOWING:
if( pMWin->eFrmType!=TK_RANGE
&& windowExprGtZero(pParse, pMWin->pStart)
){
s.eDelete = WINDOW_RETURN_ROW;
}
break;
case TK_UNBOUNDED:
if( windowCacheFrame(pMWin)==0 ){
if( pMWin->eEnd==TK_PRECEDING ){
if( pMWin->eFrmType!=TK_RANGE
&& windowExprGtZero(pParse, pMWin->pEnd)
){
s.eDelete = WINDOW_AGGSTEP;
}
}else{
s.eDelete = WINDOW_RETURN_ROW;
}
}
break;
default:
s.eDelete = WINDOW_AGGINVERSE;
break;
}
/* Allocate registers for the array of values from the sub-query, the
** samve values in record form, and the rowid used to insert said record
** into the ephemeral table. */
regNew = pParse->nMem+1;
pParse->nMem += nInput;
regRecord = ++pParse->nMem;
regRowid = ++pParse->nMem;
/* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
** clause, allocate registers to store the results of evaluating each
** <expr>. */
if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
regStart = ++pParse->nMem;
}
if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
regEnd = ++pParse->nMem;
}
/* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
** registers to store copies of the ORDER BY expressions (peer values)
** for the main loop, and for each cursor (start, current and end). */
if( pMWin->eFrmType!=TK_ROWS ){
int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
regNewPeer = regNew + pMWin->nBufferCol;
if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
regPeer = pParse->nMem+1; pParse->nMem += nPeer;
s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
}
/* Load the column values for the row returned by the sub-select
** into an array of registers starting at regNew. Assemble them into
** a record in register regRecord. */
for(iInput=0; iInput<nInput; iInput++){
sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
/* An input row has just been read into an array of registers starting
** at regNew. If the window has a PARTITION clause, this block generates
** VM code to check if the input row is the start of a new partition.
** If so, it does an OP_Gosub to an address to be filled in later. The
** address of the OP_Gosub is stored in local variable addrGosubFlush. */
if( pMWin->pPartition ){
int addr;
ExprList *pPart = pMWin->pPartition;
int nPart = pPart->nExpr;
int regNewPart = regNew + pMWin->nBufferCol;
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
regFlushPart = ++pParse->nMem;
addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
VdbeCoverageEqNe(v);
addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
VdbeComment((v, "call flush_partition"));
sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
}
/* Insert the new row into the ephemeral table */
sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
VdbeCoverageNeverNull(v);
/* This block is run for the first row of each partition */
s.regArg = windowInitAccum(pParse, pMWin);
if( regStart ){
sqlite3ExprCode(pParse, pMWin->pStart, regStart);
windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
}
if( regEnd ){
sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
}
if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
windowAggFinal(&s, 0);
sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
VdbeCoverageNeverTaken(v);
windowReturnOneRow(&s);
sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
sqlite3VdbeJumpHere(v, addrGe);
}
if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
assert( pMWin->eEnd==TK_FOLLOWING );
sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
}
if( pMWin->eStart!=TK_UNBOUNDED ){
sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
VdbeCoverageNeverTaken(v);
}
sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
VdbeCoverageNeverTaken(v);
sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
VdbeCoverageNeverTaken(v);
if( regPeer && pOrderBy ){
sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
sqlite3VdbeJumpHere(v, addrNe);
/* Beginning of the block executed for the second and subsequent rows. */
if( regPeer ){
windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
}
if( pMWin->eStart==TK_FOLLOWING ){
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
if( pMWin->eEnd!=TK_UNBOUNDED ){
if( pMWin->eFrmType==TK_RANGE ){
int lbl = sqlite3VdbeMakeLabel(pParse);
int addrNext = sqlite3VdbeCurrentAddr(v);
windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
sqlite3VdbeResolveLabel(v, lbl);
}else{
windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
}
}
}else
if( pMWin->eEnd==TK_PRECEDING ){
int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
}else{
int addr = 0;
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
if( pMWin->eEnd!=TK_UNBOUNDED ){
if( pMWin->eFrmType==TK_RANGE ){
int lbl = 0;
addr = sqlite3VdbeCurrentAddr(v);
if( regEnd ){
lbl = sqlite3VdbeMakeLabel(pParse);
windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
}
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
if( regEnd ){
sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
sqlite3VdbeResolveLabel(v, lbl);
}
}else{
if( regEnd ){
addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
VdbeCoverage(v);
}
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
if( regEnd ) sqlite3VdbeJumpHere(v, addr);
}
}
}
/* End of the main input loop */
sqlite3VdbeResolveLabel(v, lblWhereEnd);
sqlite3WhereEnd(pWInfo);
/* Fall through */
if( pMWin->pPartition ){
addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
sqlite3VdbeJumpHere(v, addrGosubFlush);
}
addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
VdbeCoverage(v);
if( pMWin->eEnd==TK_PRECEDING ){
int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
}else if( pMWin->eStart==TK_FOLLOWING ){
int addrStart;
int addrBreak1;
int addrBreak2;
int addrBreak3;
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
if( pMWin->eFrmType==TK_RANGE ){
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
}else
if( pMWin->eEnd==TK_UNBOUNDED ){
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
}else{
assert( pMWin->eEnd==TK_FOLLOWING );
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
}
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
sqlite3VdbeJumpHere(v, addrBreak2);
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
sqlite3VdbeJumpHere(v, addrBreak1);
sqlite3VdbeJumpHere(v, addrBreak3);
}else{
int addrBreak;
int addrStart;
windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
addrStart = sqlite3VdbeCurrentAddr(v);
addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
sqlite3VdbeJumpHere(v, addrBreak);
}
sqlite3VdbeJumpHere(v, addrEmpty);
sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
if( pMWin->pPartition ){
if( pMWin->regStartRowid ){
sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
}
sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
}
}
#endif /* SQLITE_OMIT_WINDOWFUNC */
| ./CrossVul/dataset_final_sorted/CWE-755/c/good_1325_4 |
crossvul-cpp_data_bad_1352_2 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle SELECT statements in SQLite.
*/
#include "sqliteInt.h"
/*
** Trace output macros
*/
#if SELECTTRACE_ENABLED
/***/ int sqlite3SelectTrace = 0;
# define SELECTTRACE(K,P,S,X) \
if(sqlite3SelectTrace&(K)) \
sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
sqlite3DebugPrintf X
#else
# define SELECTTRACE(K,P,S,X)
#endif
/*
** An instance of the following object is used to record information about
** how to process the DISTINCT keyword, to simplify passing that information
** into the selectInnerLoop() routine.
*/
typedef struct DistinctCtx DistinctCtx;
struct DistinctCtx {
u8 isTnct; /* True if the DISTINCT keyword is present */
u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
int tabTnct; /* Ephemeral table used for DISTINCT processing */
int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
};
/*
** An instance of the following object is used to record information about
** the ORDER BY (or GROUP BY) clause of query is being coded.
**
** The aDefer[] array is used by the sorter-references optimization. For
** example, assuming there is no index that can be used for the ORDER BY,
** for the query:
**
** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
**
** it may be more efficient to add just the "a" values to the sorter, and
** retrieve the associated "bigblob" values directly from table t1 as the
** 10 smallest "a" values are extracted from the sorter.
**
** When the sorter-reference optimization is used, there is one entry in the
** aDefer[] array for each database table that may be read as values are
** extracted from the sorter.
*/
typedef struct SortCtx SortCtx;
struct SortCtx {
ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
int nOBSat; /* Number of ORDER BY terms satisfied by indices */
int iECursor; /* Cursor number for the sorter */
int regReturn; /* Register holding block-output return address */
int labelBkOut; /* Start label for the block-output subroutine */
int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
int labelDone; /* Jump here when done, ex: LIMIT reached */
int labelOBLopt; /* Jump here when sorter is full */
u8 sortFlags; /* Zero or more SORTFLAG_* bits */
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
u8 nDefer; /* Number of valid entries in aDefer[] */
struct DeferredCsr {
Table *pTab; /* Table definition */
int iCsr; /* Cursor number for table */
int nKey; /* Number of PK columns for table pTab (>=1) */
} aDefer[4];
#endif
struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
};
#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
/*
** Delete all the content of a Select structure. Deallocate the structure
** itself depending on the value of bFree
**
** If bFree==1, call sqlite3DbFree() on the p object.
** If bFree==0, Leave the first Select object unfreed
*/
static void clearSelect(sqlite3 *db, Select *p, int bFree){
while( p ){
Select *pPrior = p->pPrior;
sqlite3ExprListDelete(db, p->pEList);
sqlite3SrcListDelete(db, p->pSrc);
sqlite3ExprDelete(db, p->pWhere);
sqlite3ExprListDelete(db, p->pGroupBy);
sqlite3ExprDelete(db, p->pHaving);
sqlite3ExprListDelete(db, p->pOrderBy);
sqlite3ExprDelete(db, p->pLimit);
#ifndef SQLITE_OMIT_WINDOWFUNC
if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
sqlite3WindowListDelete(db, p->pWinDefn);
}
assert( p->pWin==0 );
#endif
if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
if( bFree ) sqlite3DbFreeNN(db, p);
p = pPrior;
bFree = 1;
}
}
/*
** Initialize a SelectDest structure.
*/
void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
pDest->eDest = (u8)eDest;
pDest->iSDParm = iParm;
pDest->zAffSdst = 0;
pDest->iSdst = 0;
pDest->nSdst = 0;
}
/*
** Allocate a new Select structure and return a pointer to that
** structure.
*/
Select *sqlite3SelectNew(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* which columns to include in the result */
SrcList *pSrc, /* the FROM clause -- which tables to scan */
Expr *pWhere, /* the WHERE clause */
ExprList *pGroupBy, /* the GROUP BY clause */
Expr *pHaving, /* the HAVING clause */
ExprList *pOrderBy, /* the ORDER BY clause */
u32 selFlags, /* Flag parameters, such as SF_Distinct */
Expr *pLimit /* LIMIT value. NULL means not used */
){
Select *pNew;
Select standin;
pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
if( pNew==0 ){
assert( pParse->db->mallocFailed );
pNew = &standin;
}
if( pEList==0 ){
pEList = sqlite3ExprListAppend(pParse, 0,
sqlite3Expr(pParse->db,TK_ASTERISK,0));
}
pNew->pEList = pEList;
pNew->op = TK_SELECT;
pNew->selFlags = selFlags;
pNew->iLimit = 0;
pNew->iOffset = 0;
pNew->selId = ++pParse->nSelect;
pNew->addrOpenEphm[0] = -1;
pNew->addrOpenEphm[1] = -1;
pNew->nSelectRow = 0;
if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
pNew->pSrc = pSrc;
pNew->pWhere = pWhere;
pNew->pGroupBy = pGroupBy;
pNew->pHaving = pHaving;
pNew->pOrderBy = pOrderBy;
pNew->pPrior = 0;
pNew->pNext = 0;
pNew->pLimit = pLimit;
pNew->pWith = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
pNew->pWin = 0;
pNew->pWinDefn = 0;
#endif
if( pParse->db->mallocFailed ) {
clearSelect(pParse->db, pNew, pNew!=&standin);
pNew = 0;
}else{
assert( pNew->pSrc!=0 || pParse->nErr>0 );
}
assert( pNew!=&standin );
return pNew;
}
/*
** Delete the given Select structure and all of its substructures.
*/
void sqlite3SelectDelete(sqlite3 *db, Select *p){
if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
}
/*
** Delete all the substructure for p, but keep p allocated. Redefine
** p to be a single SELECT where every column of the result set has a
** value of NULL.
*/
void sqlite3SelectReset(Parse *pParse, Select *p){
if( ALWAYS(p) ){
clearSelect(pParse->db, p, 0);
memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit));
p->pEList = sqlite3ExprListAppend(pParse, 0,
sqlite3ExprAlloc(pParse->db,TK_NULL,0,0));
}
}
/*
** Return a pointer to the right-most SELECT statement in a compound.
*/
static Select *findRightmost(Select *p){
while( p->pNext ) p = p->pNext;
return p;
}
/*
** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
** type of join. Return an integer constant that expresses that type
** in terms of the following bit values:
**
** JT_INNER
** JT_CROSS
** JT_OUTER
** JT_NATURAL
** JT_LEFT
** JT_RIGHT
**
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
**
** If an illegal or unsupported join type is seen, then still return
** a join type, but put an error in the pParse structure.
*/
int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
int jointype = 0;
Token *apAll[3];
Token *p;
/* 0123456789 123456789 123456789 123 */
static const char zKeyText[] = "naturaleftouterightfullinnercross";
static const struct {
u8 i; /* Beginning of keyword text in zKeyText[] */
u8 nChar; /* Length of the keyword in characters */
u8 code; /* Join type mask */
} aKeyword[] = {
/* natural */ { 0, 7, JT_NATURAL },
/* left */ { 6, 4, JT_LEFT|JT_OUTER },
/* outer */ { 10, 5, JT_OUTER },
/* right */ { 14, 5, JT_RIGHT|JT_OUTER },
/* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
/* inner */ { 23, 5, JT_INNER },
/* cross */ { 28, 5, JT_INNER|JT_CROSS },
};
int i, j;
apAll[0] = pA;
apAll[1] = pB;
apAll[2] = pC;
for(i=0; i<3 && apAll[i]; i++){
p = apAll[i];
for(j=0; j<ArraySize(aKeyword); j++){
if( p->n==aKeyword[j].nChar
&& sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
jointype |= aKeyword[j].code;
break;
}
}
testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
if( j>=ArraySize(aKeyword) ){
jointype |= JT_ERROR;
break;
}
}
if(
(jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
(jointype & JT_ERROR)!=0
){
const char *zSp = " ";
assert( pB!=0 );
if( pC==0 ){ zSp++; }
sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
"%T %T%s%T", pA, pB, zSp, pC);
jointype = JT_INNER;
}else if( (jointype & JT_OUTER)!=0
&& (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
sqlite3ErrorMsg(pParse,
"RIGHT and FULL OUTER JOINs are not currently supported");
jointype = JT_INNER;
}
return jointype;
}
/*
** Return the index of a column in a table. Return -1 if the column
** is not contained in the table.
*/
static int columnIndex(Table *pTab, const char *zCol){
int i;
for(i=0; i<pTab->nCol; i++){
if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
}
return -1;
}
/*
** Search the first N tables in pSrc, from left to right, looking for a
** table that has a column named zCol.
**
** When found, set *piTab and *piCol to the table index and column index
** of the matching column and return TRUE.
**
** If not found, return FALSE.
*/
static int tableAndColumnIndex(
SrcList *pSrc, /* Array of tables to search */
int N, /* Number of tables in pSrc->a[] to search */
const char *zCol, /* Name of the column we are looking for */
int *piTab, /* Write index of pSrc->a[] here */
int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
){
int i; /* For looping over tables in pSrc */
int iCol; /* Index of column matching zCol */
assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
for(i=0; i<N; i++){
iCol = columnIndex(pSrc->a[i].pTab, zCol);
if( iCol>=0 ){
if( piTab ){
*piTab = i;
*piCol = iCol;
}
return 1;
}
}
return 0;
}
/*
** This function is used to add terms implied by JOIN syntax to the
** WHERE clause expression of a SELECT statement. The new term, which
** is ANDed with the existing WHERE clause, is of the form:
**
** (tab1.col1 = tab2.col2)
**
** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
** column iColRight of tab2.
*/
static void addWhereTerm(
Parse *pParse, /* Parsing context */
SrcList *pSrc, /* List of tables in FROM clause */
int iLeft, /* Index of first table to join in pSrc */
int iColLeft, /* Index of column in first table */
int iRight, /* Index of second table in pSrc */
int iColRight, /* Index of column in second table */
int isOuterJoin, /* True if this is an OUTER join */
Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
){
sqlite3 *db = pParse->db;
Expr *pE1;
Expr *pE2;
Expr *pEq;
assert( iLeft<iRight );
assert( pSrc->nSrc>iRight );
assert( pSrc->a[iLeft].pTab );
assert( pSrc->a[iRight].pTab );
pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
if( pEq && isOuterJoin ){
ExprSetProperty(pEq, EP_FromJoin);
assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(pEq, EP_NoReduce);
pEq->iRightJoinTable = (i16)pE2->iTable;
}
*ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
}
/*
** Set the EP_FromJoin property on all terms of the given expression.
** And set the Expr.iRightJoinTable to iTable for every term in the
** expression.
**
** The EP_FromJoin property is used on terms of an expression to tell
** the LEFT OUTER JOIN processing logic that this term is part of the
** join restriction specified in the ON or USING clause and not a part
** of the more general WHERE clause. These terms are moved over to the
** WHERE clause during join processing but we need to remember that they
** originated in the ON or USING clause.
**
** The Expr.iRightJoinTable tells the WHERE clause processing that the
** expression depends on table iRightJoinTable even if that table is not
** explicitly mentioned in the expression. That information is needed
** for cases like this:
**
** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
**
** The where clause needs to defer the handling of the t1.x=5
** term until after the t2 loop of the join. In that way, a
** NULL t2 row will be inserted whenever t1.x!=5. If we do not
** defer the handling of t1.x=5, it will be processed immediately
** after the t1 loop and rows with t1.x!=5 will never appear in
** the output, which is incorrect.
*/
void sqlite3SetJoinExpr(Expr *p, int iTable){
while( p ){
ExprSetProperty(p, EP_FromJoin);
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
ExprSetVVAProperty(p, EP_NoReduce);
p->iRightJoinTable = (i16)iTable;
if( p->op==TK_FUNCTION && p->x.pList ){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
}
}
sqlite3SetJoinExpr(p->pLeft, iTable);
p = p->pRight;
}
}
/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
** an ordinary term that omits the EP_FromJoin mark.
**
** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
*/
static void unsetJoinExpr(Expr *p, int iTable){
while( p ){
if( ExprHasProperty(p, EP_FromJoin)
&& (iTable<0 || p->iRightJoinTable==iTable) ){
ExprClearProperty(p, EP_FromJoin);
}
if( p->op==TK_FUNCTION && p->x.pList ){
int i;
for(i=0; i<p->x.pList->nExpr; i++){
unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
}
}
unsetJoinExpr(p->pLeft, iTable);
p = p->pRight;
}
}
/*
** This routine processes the join information for a SELECT statement.
** ON and USING clauses are converted into extra terms of the WHERE clause.
** NATURAL joins also create extra WHERE clause terms.
**
** The terms of a FROM clause are contained in the Select.pSrc structure.
** The left most table is the first entry in Select.pSrc. The right-most
** table is the last entry. The join operator is held in the entry to
** the left. Thus entry 0 contains the join operator for the join between
** entries 0 and 1. Any ON or USING clauses associated with the join are
** also attached to the left entry.
**
** This routine returns the number of errors encountered.
*/
static int sqliteProcessJoin(Parse *pParse, Select *p){
SrcList *pSrc; /* All tables in the FROM clause */
int i, j; /* Loop counters */
struct SrcList_item *pLeft; /* Left table being joined */
struct SrcList_item *pRight; /* Right table being joined */
pSrc = p->pSrc;
pLeft = &pSrc->a[0];
pRight = &pLeft[1];
for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
Table *pRightTab = pRight->pTab;
int isOuter;
if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
/* When the NATURAL keyword is present, add WHERE clause terms for
** every column that the two tables have in common.
*/
if( pRight->fg.jointype & JT_NATURAL ){
if( pRight->pOn || pRight->pUsing ){
sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
"an ON or USING clause", 0);
return 1;
}
for(j=0; j<pRightTab->nCol; j++){
char *zName; /* Name of column in the right table */
int iLeft; /* Matching left table */
int iLeftCol; /* Matching column in the left table */
zName = pRightTab->aCol[j].zName;
if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
isOuter, &p->pWhere);
}
}
}
/* Disallow both ON and USING clauses in the same join
*/
if( pRight->pOn && pRight->pUsing ){
sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
"clauses in the same join");
return 1;
}
/* Add the ON clause to the end of the WHERE clause, connected by
** an AND operator.
*/
if( pRight->pOn ){
if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);
p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
pRight->pOn = 0;
}
/* Create extra terms on the WHERE clause for each column named
** in the USING clause. Example: If the two tables to be joined are
** A and B and the USING clause names X, Y, and Z, then add this
** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
** Report an error if any column mentioned in the USING clause is
** not contained in both tables to be joined.
*/
if( pRight->pUsing ){
IdList *pList = pRight->pUsing;
for(j=0; j<pList->nId; j++){
char *zName; /* Name of the term in the USING clause */
int iLeft; /* Table on the left with matching column name */
int iLeftCol; /* Column number of matching column on the left */
int iRightCol; /* Column number of matching column on the right */
zName = pList->a[j].zName;
iRightCol = columnIndex(pRightTab, zName);
if( iRightCol<0
|| !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
){
sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
"not present in both tables", zName);
return 1;
}
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
isOuter, &p->pWhere);
}
}
}
return 0;
}
/*
** An instance of this object holds information (beyond pParse and pSelect)
** needed to load the next result row that is to be added to the sorter.
*/
typedef struct RowLoadInfo RowLoadInfo;
struct RowLoadInfo {
int regResult; /* Store results in array of registers here */
u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
ExprList *pExtra; /* Extra columns needed by sorter refs */
int regExtraResult; /* Where to load the extra columns */
#endif
};
/*
** This routine does the work of loading query data into an array of
** registers so that it can be added to the sorter.
*/
static void innerLoopLoadRow(
Parse *pParse, /* Statement under construction */
Select *pSelect, /* The query being coded */
RowLoadInfo *pInfo /* Info needed to complete the row load */
){
sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
0, pInfo->ecelFlags);
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pInfo->pExtra ){
sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
}
#endif
}
/*
** Code the OP_MakeRecord instruction that generates the entry to be
** added into the sorter.
**
** Return the register in which the result is stored.
*/
static int makeSorterRecord(
Parse *pParse,
SortCtx *pSort,
Select *pSelect,
int regBase,
int nBase
){
int nOBSat = pSort->nOBSat;
Vdbe *v = pParse->pVdbe;
int regOut = ++pParse->nMem;
if( pSort->pDeferredRowLoad ){
innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
return regOut;
}
/*
** Generate code that will push the record in registers regData
** through regData+nData-1 onto the sorter.
*/
static void pushOntoSorter(
Parse *pParse, /* Parser context */
SortCtx *pSort, /* Information about the ORDER BY clause */
Select *pSelect, /* The whole SELECT statement */
int regData, /* First register holding data to be sorted */
int regOrigData, /* First register holding data before packing */
int nData, /* Number of elements in the regData data array */
int nPrefixReg /* No. of reg prior to regData available for use */
){
Vdbe *v = pParse->pVdbe; /* Stmt under construction */
int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
int regBase; /* Regs for sorter record */
int regRecord = 0; /* Assembled sorter record */
int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
int op; /* Opcode to add sorter record to sorter */
int iLimit; /* LIMIT counter */
int iSkip = 0; /* End of the sorter insert loop */
assert( bSeq==0 || bSeq==1 );
/* Three cases:
** (1) The data to be sorted has already been packed into a Record
** by a prior OP_MakeRecord. In this case nData==1 and regData
** will be completely unrelated to regOrigData.
** (2) All output columns are included in the sort record. In that
** case regData==regOrigData.
** (3) Some output columns are omitted from the sort record due to
** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
** SQLITE_ECEL_OMITREF optimization, or due to the
** SortCtx.pDeferredRowLoad optimiation. In any of these cases
** regOrigData is 0 to prevent this routine from trying to copy
** values that might not yet exist.
*/
assert( nData==1 || regData==regOrigData || regOrigData==0 );
if( nPrefixReg ){
assert( nPrefixReg==nExpr+bSeq );
regBase = regData - nPrefixReg;
}else{
regBase = pParse->nMem + 1;
pParse->nMem += nBase;
}
assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
if( bSeq ){
sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
}
if( nPrefixReg==0 && nData>0 ){
sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
}
if( nOBSat>0 ){
int regPrevKey; /* The first nOBSat columns of the previous row */
int addrFirst; /* Address of the OP_IfNot opcode */
int addrJmp; /* Address of the OP_Jump opcode */
VdbeOp *pOp; /* Opcode that opens the sorter */
int nKey; /* Number of sorting key columns, including OP_Sequence */
KeyInfo *pKI; /* Original KeyInfo on the sorter table */
regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
regPrevKey = pParse->nMem+1;
pParse->nMem += pSort->nOBSat;
nKey = nExpr - pSort->nOBSat + bSeq;
if( bSeq ){
addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
}else{
addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
}
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
if( pParse->db->mallocFailed ) return;
pOp->p2 = nKey + nData;
pKI = pOp->p4.pKeyInfo;
memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
testcase( pKI->nAllField > pKI->nKeyField+2 );
pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
pKI->nAllField-pKI->nKeyField-1);
pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
addrJmp = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
pSort->regReturn = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
if( iLimit ){
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
VdbeCoverage(v);
}
sqlite3VdbeJumpHere(v, addrFirst);
sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
sqlite3VdbeJumpHere(v, addrJmp);
}
if( iLimit ){
/* At this point the values for the new sorter entry are stored
** in an array of registers. They need to be composed into a record
** and inserted into the sorter if either (a) there are currently
** less than LIMIT+OFFSET items or (b) the new record is smaller than
** the largest record currently in the sorter. If (b) is true and there
** are already LIMIT+OFFSET items in the sorter, delete the largest
** entry before inserting the new one. This way there are never more
** than LIMIT+OFFSET items in the sorter.
**
** If the new record does not need to be inserted into the sorter,
** jump to the next iteration of the loop. If the pSort->labelOBLopt
** value is not zero, then it is a label of where to jump. Otherwise,
** just bypass the row insert logic. See the header comment on the
** sqlite3WhereOrderByLimitOptLabel() function for additional info.
*/
int iCsr = pSort->iECursor;
sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
VdbeCoverage(v);
sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
VdbeCoverage(v);
sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
}
if( regRecord==0 ){
regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
}
if( pSort->sortFlags & SORTFLAG_UseSorter ){
op = OP_SorterInsert;
}else{
op = OP_IdxInsert;
}
sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
regBase+nOBSat, nBase-nOBSat);
if( iSkip ){
sqlite3VdbeChangeP2(v, iSkip,
pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
}
}
/*
** Add code to implement the OFFSET
*/
static void codeOffset(
Vdbe *v, /* Generate code into this VM */
int iOffset, /* Register holding the offset counter */
int iContinue /* Jump here to skip the current record */
){
if( iOffset>0 ){
sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
VdbeComment((v, "OFFSET"));
}
}
/*
** Add code that will check to make sure the N registers starting at iMem
** form a distinct entry. iTab is a sorting index that holds previously
** seen combinations of the N values. A new entry is made in iTab
** if the current N values are new.
**
** A jump to addrRepeat is made and the N+1 values are popped from the
** stack if the top N elements are not distinct.
*/
static void codeDistinct(
Parse *pParse, /* Parsing and code generating context */
int iTab, /* A sorting index used to test for distinctness */
int addrRepeat, /* Jump to here if not distinct */
int N, /* Number of elements */
int iMem /* First element */
){
Vdbe *v;
int r1;
v = pParse->pVdbe;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
sqlite3ReleaseTempReg(pParse, r1);
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
/*
** This function is called as part of inner-loop generation for a SELECT
** statement with an ORDER BY that is not optimized by an index. It
** determines the expressions, if any, that the sorter-reference
** optimization should be used for. The sorter-reference optimization
** is used for SELECT queries like:
**
** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
**
** If the optimization is used for expression "bigblob", then instead of
** storing values read from that column in the sorter records, the PK of
** the row from table t1 is stored instead. Then, as records are extracted from
** the sorter to return to the user, the required value of bigblob is
** retrieved directly from table t1. If the values are very large, this
** can be more efficient than storing them directly in the sorter records.
**
** The ExprList_item.bSorterRef flag is set for each expression in pEList
** for which the sorter-reference optimization should be enabled.
** Additionally, the pSort->aDefer[] array is populated with entries
** for all cursors required to evaluate all selected expressions. Finally.
** output variable (*ppExtra) is set to an expression list containing
** expressions for all extra PK values that should be stored in the
** sorter records.
*/
static void selectExprDefer(
Parse *pParse, /* Leave any error here */
SortCtx *pSort, /* Sorter context */
ExprList *pEList, /* Expressions destined for sorter */
ExprList **ppExtra /* Expressions to append to sorter record */
){
int i;
int nDefer = 0;
ExprList *pExtra = 0;
for(i=0; i<pEList->nExpr; i++){
struct ExprList_item *pItem = &pEList->a[i];
if( pItem->u.x.iOrderByCol==0 ){
Expr *pExpr = pItem->pExpr;
Table *pTab = pExpr->y.pTab;
if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
&& (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
){
int j;
for(j=0; j<nDefer; j++){
if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
}
if( j==nDefer ){
if( nDefer==ArraySize(pSort->aDefer) ){
continue;
}else{
int nKey = 1;
int k;
Index *pPk = 0;
if( !HasRowid(pTab) ){
pPk = sqlite3PrimaryKeyIndex(pTab);
nKey = pPk->nKeyCol;
}
for(k=0; k<nKey; k++){
Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
if( pNew ){
pNew->iTable = pExpr->iTable;
pNew->y.pTab = pExpr->y.pTab;
pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
}
}
pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
pSort->aDefer[nDefer].iCsr = pExpr->iTable;
pSort->aDefer[nDefer].nKey = nKey;
nDefer++;
}
}
pItem->bSorterRef = 1;
}
}
}
pSort->nDefer = (u8)nDefer;
*ppExtra = pExtra;
}
#endif
/*
** This routine generates the code for the inside of the inner loop
** of a SELECT.
**
** If srcTab is negative, then the p->pEList expressions
** are evaluated in order to get the data for this row. If srcTab is
** zero or more, then data is pulled from srcTab and p->pEList is used only
** to get the number of columns and the collation sequence for each column.
*/
static void selectInnerLoop(
Parse *pParse, /* The parser context */
Select *p, /* The complete select statement being coded */
int srcTab, /* Pull data from this table if non-negative */
SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
SelectDest *pDest, /* How to dispose of the results */
int iContinue, /* Jump here to continue with next row */
int iBreak /* Jump here to break out of the inner loop */
){
Vdbe *v = pParse->pVdbe;
int i;
int hasDistinct; /* True if the DISTINCT keyword is present */
int eDest = pDest->eDest; /* How to dispose of results */
int iParm = pDest->iSDParm; /* First argument to disposal method */
int nResultCol; /* Number of result columns */
int nPrefixReg = 0; /* Number of extra registers before regResult */
RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
/* Usually, regResult is the first cell in an array of memory cells
** containing the current result row. In this case regOrig is set to the
** same value. However, if the results are being sent to the sorter, the
** values for any expressions that are also part of the sort-key are omitted
** from this array. In this case regOrig is set to zero. */
int regResult; /* Start of memory holding current results */
int regOrig; /* Start of memory holding full result (or 0) */
assert( v );
assert( p->pEList!=0 );
hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
if( pSort && pSort->pOrderBy==0 ) pSort = 0;
if( pSort==0 && !hasDistinct ){
assert( iContinue!=0 );
codeOffset(v, p->iOffset, iContinue);
}
/* Pull the requested columns.
*/
nResultCol = p->pEList->nExpr;
if( pDest->iSdst==0 ){
if( pSort ){
nPrefixReg = pSort->pOrderBy->nExpr;
if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
pParse->nMem += nPrefixReg;
}
pDest->iSdst = pParse->nMem+1;
pParse->nMem += nResultCol;
}else if( pDest->iSdst+nResultCol > pParse->nMem ){
/* This is an error condition that can result, for example, when a SELECT
** on the right-hand side of an INSERT contains more result columns than
** there are columns in the table on the left. The error will be caught
** and reported later. But we need to make sure enough memory is allocated
** to avoid other spurious errors in the meantime. */
pParse->nMem += nResultCol;
}
pDest->nSdst = nResultCol;
regOrig = regResult = pDest->iSdst;
if( srcTab>=0 ){
for(i=0; i<nResultCol; i++){
sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
VdbeComment((v, "%s", p->pEList->a[i].zName));
}
}else if( eDest!=SRT_Exists ){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
ExprList *pExtra = 0;
#endif
/* If the destination is an EXISTS(...) expression, the actual
** values returned by the SELECT are not required.
*/
u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
ExprList *pEList;
if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
ecelFlags = SQLITE_ECEL_DUP;
}else{
ecelFlags = 0;
}
if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
/* For each expression in p->pEList that is a copy of an expression in
** the ORDER BY clause (pSort->pOrderBy), set the associated
** iOrderByCol value to one more than the index of the ORDER BY
** expression within the sort-key that pushOntoSorter() will generate.
** This allows the p->pEList field to be omitted from the sorted record,
** saving space and CPU cycles. */
ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
int j;
if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
}
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
selectExprDefer(pParse, pSort, p->pEList, &pExtra);
if( pExtra && pParse->db->mallocFailed==0 ){
/* If there are any extra PK columns to add to the sorter records,
** allocate extra memory cells and adjust the OpenEphemeral
** instruction to account for the larger records. This is only
** required if there are one or more WITHOUT ROWID tables with
** composite primary keys in the SortCtx.aDefer[] array. */
VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
pOp->p2 += (pExtra->nExpr - pSort->nDefer);
pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
pParse->nMem += pExtra->nExpr;
}
#endif
/* Adjust nResultCol to account for columns that are omitted
** from the sorter by the optimizations in this branch */
pEList = p->pEList;
for(i=0; i<pEList->nExpr; i++){
if( pEList->a[i].u.x.iOrderByCol>0
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
|| pEList->a[i].bSorterRef
#endif
){
nResultCol--;
regOrig = 0;
}
}
testcase( regOrig );
testcase( eDest==SRT_Set );
testcase( eDest==SRT_Mem );
testcase( eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
assert( eDest==SRT_Set || eDest==SRT_Mem
|| eDest==SRT_Coroutine || eDest==SRT_Output );
}
sRowLoadInfo.regResult = regResult;
sRowLoadInfo.ecelFlags = ecelFlags;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
sRowLoadInfo.pExtra = pExtra;
sRowLoadInfo.regExtraResult = regResult + nResultCol;
if( pExtra ) nResultCol += pExtra->nExpr;
#endif
if( p->iLimit
&& (ecelFlags & SQLITE_ECEL_OMITREF)!=0
&& nPrefixReg>0
){
assert( pSort!=0 );
assert( hasDistinct==0 );
pSort->pDeferredRowLoad = &sRowLoadInfo;
regOrig = 0;
}else{
innerLoopLoadRow(pParse, p, &sRowLoadInfo);
}
}
/* If the DISTINCT keyword was present on the SELECT statement
** and this row has been seen before, then do not make this row
** part of the result.
*/
if( hasDistinct ){
switch( pDistinct->eTnctType ){
case WHERE_DISTINCT_ORDERED: {
VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
int iJump; /* Jump destination */
int regPrev; /* Previous row content */
/* Allocate space for the previous row */
regPrev = pParse->nMem+1;
pParse->nMem += nResultCol;
/* Change the OP_OpenEphemeral coded earlier to an OP_Null
** sets the MEM_Cleared bit on the first register of the
** previous value. This will cause the OP_Ne below to always
** fail on the first iteration of the loop even if the first
** row is all NULLs.
*/
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
pOp->opcode = OP_Null;
pOp->p1 = 1;
pOp->p2 = regPrev;
pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */
iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
for(i=0; i<nResultCol; i++){
CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
if( i<nResultCol-1 ){
sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
VdbeCoverage(v);
}else{
sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
VdbeCoverage(v);
}
sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
}
assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
break;
}
case WHERE_DISTINCT_UNIQUE: {
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
break;
}
default: {
assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
regResult);
break;
}
}
if( pSort==0 ){
codeOffset(v, p->iOffset, iContinue);
}
}
switch( eDest ){
/* In this mode, write each query result to the key of the temporary
** table iParm.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
case SRT_Union: {
int r1;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
/* Construct a record from the query result, but instead of
** saving that record, use it as a key to delete elements from
** the temporary table iParm.
*/
case SRT_Except: {
sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
break;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
/* Store the result as data using a unique key.
*/
case SRT_Fifo:
case SRT_DistFifo:
case SRT_Table:
case SRT_EphemTab: {
int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
testcase( eDest==SRT_Table );
testcase( eDest==SRT_EphemTab );
testcase( eDest==SRT_Fifo );
testcase( eDest==SRT_DistFifo );
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
#ifndef SQLITE_OMIT_CTE
if( eDest==SRT_DistFifo ){
/* If the destination is DistFifo, then cursor (iParm+1) is open
** on an ephemeral index. If the current row is already present
** in the index, do not write it to the output. If not, add the
** current row to the index and proceed with writing it to the
** output table as well. */
int addr = sqlite3VdbeCurrentAddr(v) + 4;
sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
VdbeCoverage(v);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
assert( pSort==0 );
}
#endif
if( pSort ){
assert( regResult==regOrig );
pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
}else{
int r2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3ReleaseTempReg(pParse, r2);
}
sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
/* If we are creating a set for an "expr IN (SELECT ...)" construct,
** then there should be a single item on the stack. Write this
** item into the set table with bogus data.
*/
case SRT_Set: {
if( pSort ){
/* At first glance you would think we could optimize out the
** ORDER BY in this case since the order of entries in the set
** does not matter. But there might be a LIMIT clause, in which
** case the order does matter */
pushOntoSorter(
pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
}else{
int r1 = sqlite3GetTempReg(pParse);
assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
r1, pDest->zAffSdst, nResultCol);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
sqlite3ReleaseTempReg(pParse, r1);
}
break;
}
/* If any row exist in the result set, record that fact and abort.
*/
case SRT_Exists: {
sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
/* The LIMIT clause will terminate the loop for us */
break;
}
/* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell or array of
** memory cells and break out of the scan loop.
*/
case SRT_Mem: {
if( pSort ){
assert( nResultCol<=pDest->nSdst );
pushOntoSorter(
pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
}else{
assert( nResultCol==pDest->nSdst );
assert( regResult==iParm );
/* The LIMIT clause will jump out of the loop for us */
}
break;
}
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
case SRT_Coroutine: /* Send data to a co-routine */
case SRT_Output: { /* Return the results */
testcase( eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
if( pSort ){
pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
nPrefixReg);
}else if( eDest==SRT_Coroutine ){
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
}else{
sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
}
break;
}
#ifndef SQLITE_OMIT_CTE
/* Write the results into a priority queue that is order according to
** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
** index with pSO->nExpr+2 columns. Build a key using pSO for the first
** pSO->nExpr columns, then make sure all keys are unique by adding a
** final OP_Sequence column. The last column is the record as a blob.
*/
case SRT_DistQueue:
case SRT_Queue: {
int nKey;
int r1, r2, r3;
int addrTest = 0;
ExprList *pSO;
pSO = pDest->pOrderBy;
assert( pSO );
nKey = pSO->nExpr;
r1 = sqlite3GetTempReg(pParse);
r2 = sqlite3GetTempRange(pParse, nKey+2);
r3 = r2+nKey+1;
if( eDest==SRT_DistQueue ){
/* If the destination is DistQueue, then cursor (iParm+1) is open
** on a second ephemeral index that holds all values every previously
** added to the queue. */
addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
regResult, nResultCol);
VdbeCoverage(v);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
if( eDest==SRT_DistQueue ){
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
}
for(i=0; i<nKey; i++){
sqlite3VdbeAddOp2(v, OP_SCopy,
regResult + pSO->a[i].u.x.iOrderByCol - 1,
r2+i);
}
sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
sqlite3ReleaseTempReg(pParse, r1);
sqlite3ReleaseTempRange(pParse, r2, nKey+2);
break;
}
#endif /* SQLITE_OMIT_CTE */
#if !defined(SQLITE_OMIT_TRIGGER)
/* Discard the results. This is used for SELECT statements inside
** the body of a TRIGGER. The purpose of such selects is to call
** user-defined functions that have side effects. We do not care
** about the actual results of the select.
*/
default: {
assert( eDest==SRT_Discard );
break;
}
#endif
}
/* Jump to the end of the loop if the LIMIT is reached. Except, if
** there is a sorter, in which case the sorter has already limited
** the output for us.
*/
if( pSort==0 && p->iLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
}
}
/*
** Allocate a KeyInfo object sufficient for an index of N key columns and
** X extra columns.
*/
KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
if( p ){
p->aSortFlags = (u8*)&p->aColl[N+X];
p->nKeyField = (u16)N;
p->nAllField = (u16)(N+X);
p->enc = ENC(db);
p->db = db;
p->nRef = 1;
memset(&p[1], 0, nExtra);
}else{
sqlite3OomFault(db);
}
return p;
}
/*
** Deallocate a KeyInfo object
*/
void sqlite3KeyInfoUnref(KeyInfo *p){
if( p ){
assert( p->nRef>0 );
p->nRef--;
if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
}
}
/*
** Make a new pointer to a KeyInfo object
*/
KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
if( p ){
assert( p->nRef>0 );
p->nRef++;
}
return p;
}
#ifdef SQLITE_DEBUG
/*
** Return TRUE if a KeyInfo object can be change. The KeyInfo object
** can only be changed if this is just a single reference to the object.
**
** This routine is used only inside of assert() statements.
*/
int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
#endif /* SQLITE_DEBUG */
/*
** Given an expression list, generate a KeyInfo structure that records
** the collating sequence for each expression in that expression list.
**
** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
** KeyInfo structure is appropriate for initializing a virtual index to
** implement that clause. If the ExprList is the result set of a SELECT
** then the KeyInfo structure is appropriate for initializing a virtual
** index to implement a DISTINCT test.
**
** Space to hold the KeyInfo structure is obtained from malloc. The calling
** function is responsible for seeing that this structure is eventually
** freed.
*/
KeyInfo *sqlite3KeyInfoFromExprList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* Form the KeyInfo object from this ExprList */
int iStart, /* Begin with this column of pList */
int nExtra /* Add this many extra columns to the end */
){
int nExpr;
KeyInfo *pInfo;
struct ExprList_item *pItem;
sqlite3 *db = pParse->db;
int i;
nExpr = pList->nExpr;
pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
if( pInfo ){
assert( sqlite3KeyInfoIsWriteable(pInfo) );
for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
pInfo->aSortFlags[i-iStart] = pItem->sortFlags;
}
}
return pInfo;
}
/*
** Name of the connection operator, used for error messages.
*/
static const char *selectOpName(int id){
char *z;
switch( id ){
case TK_ALL: z = "UNION ALL"; break;
case TK_INTERSECT: z = "INTERSECT"; break;
case TK_EXCEPT: z = "EXCEPT"; break;
default: z = "UNION"; break;
}
return z;
}
#ifndef SQLITE_OMIT_EXPLAIN
/*
** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
** is a no-op. Otherwise, it adds a single row of output to the EQP result,
** where the caption is of the form:
**
** "USE TEMP B-TREE FOR xxx"
**
** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
** is determined by the zUsage argument.
*/
static void explainTempTable(Parse *pParse, const char *zUsage){
ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
}
/*
** Assign expression b to lvalue a. A second, no-op, version of this macro
** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
** in sqlite3Select() to assign values to structure member variables that
** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
** code with #ifndef directives.
*/
# define explainSetInteger(a, b) a = b
#else
/* No-op versions of the explainXXX() functions and macros. */
# define explainTempTable(y,z)
# define explainSetInteger(y,z)
#endif
/*
** If the inner loop was generated using a non-null pOrderBy argument,
** then the results were placed in a sorter. After the loop is terminated
** we need to run the sorter and output the results. The following
** routine generates the code needed to do that.
*/
static void generateSortTail(
Parse *pParse, /* Parsing context */
Select *p, /* The SELECT statement */
SortCtx *pSort, /* Information on the ORDER BY clause */
int nColumn, /* Number of columns of data */
SelectDest *pDest /* Write the sorted results here */
){
Vdbe *v = pParse->pVdbe; /* The prepared statement */
int addrBreak = pSort->labelDone; /* Jump here to exit loop */
int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
int addr; /* Top of output loop. Jump for Next. */
int addrOnce = 0;
int iTab;
ExprList *pOrderBy = pSort->pOrderBy;
int eDest = pDest->eDest;
int iParm = pDest->iSDParm;
int regRow;
int regRowid;
int iCol;
int nKey; /* Number of key columns in sorter record */
int iSortTab; /* Sorter cursor to read from */
int i;
int bSeq; /* True if sorter record includes seq. no. */
int nRefKey = 0;
struct ExprList_item *aOutEx = p->pEList->a;
assert( addrBreak<0 );
if( pSort->labelBkOut ){
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
sqlite3VdbeGoto(v, addrBreak);
sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
/* Open any cursors needed for sorter-reference expressions */
for(i=0; i<pSort->nDefer; i++){
Table *pTab = pSort->aDefer[i].pTab;
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
}
#endif
iTab = pSort->iECursor;
if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
regRowid = 0;
regRow = pDest->iSdst;
}else{
regRowid = sqlite3GetTempReg(pParse);
if( eDest==SRT_EphemTab || eDest==SRT_Table ){
regRow = sqlite3GetTempReg(pParse);
nColumn = 0;
}else{
regRow = sqlite3GetTempRange(pParse, nColumn);
}
}
nKey = pOrderBy->nExpr - pSort->nOBSat;
if( pSort->sortFlags & SORTFLAG_UseSorter ){
int regSortOut = ++pParse->nMem;
iSortTab = pParse->nTab++;
if( pSort->labelBkOut ){
addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
}
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
nKey+1+nColumn+nRefKey);
if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
VdbeCoverage(v);
codeOffset(v, p->iOffset, addrContinue);
sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
bSeq = 0;
}else{
addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
codeOffset(v, p->iOffset, addrContinue);
iSortTab = iTab;
bSeq = 1;
}
for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( aOutEx[i].bSorterRef ) continue;
#endif
if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( pSort->nDefer ){
int iKey = iCol+1;
int regKey = sqlite3GetTempRange(pParse, nRefKey);
for(i=0; i<pSort->nDefer; i++){
int iCsr = pSort->aDefer[i].iCsr;
Table *pTab = pSort->aDefer[i].pTab;
int nKey = pSort->aDefer[i].nKey;
sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
if( HasRowid(pTab) ){
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
sqlite3VdbeCurrentAddr(v)+1, regKey);
}else{
int k;
int iJmp;
assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
for(k=0; k<nKey; k++){
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
}
iJmp = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
}
}
sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
}
#endif
for(i=nColumn-1; i>=0; i--){
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( aOutEx[i].bSorterRef ){
sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
}else
#endif
{
int iRead;
if( aOutEx[i].u.x.iOrderByCol ){
iRead = aOutEx[i].u.x.iOrderByCol-1;
}else{
iRead = iCol--;
}
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
}
}
switch( eDest ){
case SRT_Table:
case SRT_EphemTab: {
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case SRT_Set: {
assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
pDest->zAffSdst, nColumn);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
break;
}
case SRT_Mem: {
/* The LIMIT clause will terminate the loop for us */
break;
}
#endif
default: {
assert( eDest==SRT_Output || eDest==SRT_Coroutine );
testcase( eDest==SRT_Output );
testcase( eDest==SRT_Coroutine );
if( eDest==SRT_Output ){
sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
}else{
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
}
break;
}
}
if( regRowid ){
if( eDest==SRT_Set ){
sqlite3ReleaseTempRange(pParse, regRow, nColumn);
}else{
sqlite3ReleaseTempReg(pParse, regRow);
}
sqlite3ReleaseTempReg(pParse, regRowid);
}
/* The bottom of the loop
*/
sqlite3VdbeResolveLabel(v, addrContinue);
if( pSort->sortFlags & SORTFLAG_UseSorter ){
sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
}else{
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
}
if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
sqlite3VdbeResolveLabel(v, addrBreak);
}
/*
** Return a pointer to a string containing the 'declaration type' of the
** expression pExpr. The string may be treated as static by the caller.
**
** Also try to estimate the size of the returned value and return that
** result in *pEstWidth.
**
** The declaration type is the exact datatype definition extracted from the
** original CREATE TABLE statement if the expression is a column. The
** declaration type for a ROWID field is INTEGER. Exactly when an expression
** is considered a column can be complex in the presence of subqueries. The
** result-set expression in all of the following SELECT statements is
** considered a column by this function.
**
** SELECT col FROM tbl;
** SELECT (SELECT col FROM tbl;
** SELECT (SELECT col FROM tbl);
** SELECT abc FROM (SELECT col AS abc FROM tbl);
**
** The declaration type for any expression other than a column is NULL.
**
** This routine has either 3 or 6 parameters depending on whether or not
** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
*/
#ifdef SQLITE_ENABLE_COLUMN_METADATA
# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
# define columnType(A,B,C,D,E) columnTypeImpl(A,B)
#endif
static const char *columnTypeImpl(
NameContext *pNC,
#ifndef SQLITE_ENABLE_COLUMN_METADATA
Expr *pExpr
#else
Expr *pExpr,
const char **pzOrigDb,
const char **pzOrigTab,
const char **pzOrigCol
#endif
){
char const *zType = 0;
int j;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
char const *zOrigDb = 0;
char const *zOrigTab = 0;
char const *zOrigCol = 0;
#endif
assert( pExpr!=0 );
assert( pNC->pSrcList!=0 );
switch( pExpr->op ){
case TK_COLUMN: {
/* The expression is a column. Locate the table the column is being
** extracted from in NameContext.pSrcList. This table may be real
** database table or a subquery.
*/
Table *pTab = 0; /* Table structure column is extracted from */
Select *pS = 0; /* Select the column is extracted from */
int iCol = pExpr->iColumn; /* Index of column in pTab */
while( pNC && !pTab ){
SrcList *pTabList = pNC->pSrcList;
for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
if( j<pTabList->nSrc ){
pTab = pTabList->a[j].pTab;
pS = pTabList->a[j].pSelect;
}else{
pNC = pNC->pNext;
}
}
if( pTab==0 ){
/* At one time, code such as "SELECT new.x" within a trigger would
** cause this condition to run. Since then, we have restructured how
** trigger code is generated and so this condition is no longer
** possible. However, it can still be true for statements like
** the following:
**
** CREATE TABLE t1(col INTEGER);
** SELECT (SELECT t1.col) FROM FROM t1;
**
** when columnType() is called on the expression "t1.col" in the
** sub-select. In this case, set the column type to NULL, even
** though it should really be "INTEGER".
**
** This is not a problem, as the column type of "t1.col" is never
** used. When columnType() is called on the expression
** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
** branch below. */
break;
}
assert( pTab && pExpr->y.pTab==pTab );
if( pS ){
/* The "table" is actually a sub-select or a view in the FROM clause
** of the SELECT statement. Return the declaration type and origin
** data for the result-set column of the sub-select.
*/
if( iCol>=0 && iCol<pS->pEList->nExpr ){
/* If iCol is less than zero, then the expression requests the
** rowid of the sub-select or view. This expression is legal (see
** test case misc2.2.2) - it always evaluates to NULL.
*/
NameContext sNC;
Expr *p = pS->pEList->a[iCol].pExpr;
sNC.pSrcList = pS->pSrc;
sNC.pNext = pNC;
sNC.pParse = pNC->pParse;
zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
}
}else{
/* A real table or a CTE table */
assert( !pS );
#ifdef SQLITE_ENABLE_COLUMN_METADATA
if( iCol<0 ) iCol = pTab->iPKey;
assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zType = "INTEGER";
zOrigCol = "rowid";
}else{
zOrigCol = pTab->aCol[iCol].zName;
zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
}
zOrigTab = pTab->zName;
if( pNC->pParse && pTab->pSchema ){
int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
}
#else
assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zType = "INTEGER";
}else{
zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
}
#endif
}
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
case TK_SELECT: {
/* The expression is a sub-select. Return the declaration type and
** origin info for the single column in the result set of the SELECT
** statement.
*/
NameContext sNC;
Select *pS = pExpr->x.pSelect;
Expr *p = pS->pEList->a[0].pExpr;
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
sNC.pSrcList = pS->pSrc;
sNC.pNext = pNC;
sNC.pParse = pNC->pParse;
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
break;
}
#endif
}
#ifdef SQLITE_ENABLE_COLUMN_METADATA
if( pzOrigDb ){
assert( pzOrigTab && pzOrigCol );
*pzOrigDb = zOrigDb;
*pzOrigTab = zOrigTab;
*pzOrigCol = zOrigCol;
}
#endif
return zType;
}
/*
** Generate code that will tell the VDBE the declaration types of columns
** in the result set.
*/
static void generateColumnTypes(
Parse *pParse, /* Parser context */
SrcList *pTabList, /* List of tables */
ExprList *pEList /* Expressions defining the result set */
){
#ifndef SQLITE_OMIT_DECLTYPE
Vdbe *v = pParse->pVdbe;
int i;
NameContext sNC;
sNC.pSrcList = pTabList;
sNC.pParse = pParse;
sNC.pNext = 0;
for(i=0; i<pEList->nExpr; i++){
Expr *p = pEList->a[i].pExpr;
const char *zType;
#ifdef SQLITE_ENABLE_COLUMN_METADATA
const char *zOrigDb = 0;
const char *zOrigTab = 0;
const char *zOrigCol = 0;
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
/* The vdbe must make its own copy of the column-type and other
** column specific strings, in case the schema is reset before this
** virtual machine is deleted.
*/
sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
#else
zType = columnType(&sNC, p, 0, 0, 0);
#endif
sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
}
#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
}
/*
** Compute the column names for a SELECT statement.
**
** The only guarantee that SQLite makes about column names is that if the
** column has an AS clause assigning it a name, that will be the name used.
** That is the only documented guarantee. However, countless applications
** developed over the years have made baseless assumptions about column names
** and will break if those assumptions changes. Hence, use extreme caution
** when modifying this routine to avoid breaking legacy.
**
** See Also: sqlite3ColumnsFromExprList()
**
** The PRAGMA short_column_names and PRAGMA full_column_names settings are
** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
** applications should operate this way. Nevertheless, we need to support the
** other modes for legacy:
**
** short=OFF, full=OFF: Column name is the text of the expression has it
** originally appears in the SELECT statement. In
** other words, the zSpan of the result expression.
**
** short=ON, full=OFF: (This is the default setting). If the result
** refers directly to a table column, then the
** result column name is just the table column
** name: COLUMN. Otherwise use zSpan.
**
** full=ON, short=ANY: If the result refers directly to a table column,
** then the result column name with the table name
** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
*/
static void generateColumnNames(
Parse *pParse, /* Parser context */
Select *pSelect /* Generate column names for this SELECT statement */
){
Vdbe *v = pParse->pVdbe;
int i;
Table *pTab;
SrcList *pTabList;
ExprList *pEList;
sqlite3 *db = pParse->db;
int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
#ifndef SQLITE_OMIT_EXPLAIN
/* If this is an EXPLAIN, skip this step */
if( pParse->explain ){
return;
}
#endif
if( pParse->colNamesSet ) return;
/* Column names are determined by the left-most term of a compound select */
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
pTabList = pSelect->pSrc;
pEList = pSelect->pEList;
assert( v!=0 );
assert( pTabList!=0 );
pParse->colNamesSet = 1;
fullName = (db->flags & SQLITE_FullColNames)!=0;
srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
sqlite3VdbeSetNumCols(v, pEList->nExpr);
for(i=0; i<pEList->nExpr; i++){
Expr *p = pEList->a[i].pExpr;
assert( p!=0 );
assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
if( pEList->a[i].zName ){
/* An AS clause always takes first priority */
char *zName = pEList->a[i].zName;
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
}else if( srcName && p->op==TK_COLUMN ){
char *zCol;
int iCol = p->iColumn;
pTab = p->y.pTab;
assert( pTab!=0 );
if( iCol<0 ) iCol = pTab->iPKey;
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
if( iCol<0 ){
zCol = "rowid";
}else{
zCol = pTab->aCol[iCol].zName;
}
if( fullName ){
char *zName = 0;
zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
}else{
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
}
}else{
const char *z = pEList->a[i].zSpan;
z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
}
}
generateColumnTypes(pParse, pTabList, pEList);
}
/*
** Given an expression list (which is really the list of expressions
** that form the result set of a SELECT statement) compute appropriate
** column names for a table that would hold the expression list.
**
** All column names will be unique.
**
** Only the column names are computed. Column.zType, Column.zColl,
** and other fields of Column are zeroed.
**
** Return SQLITE_OK on success. If a memory allocation error occurs,
** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
**
** The only guarantee that SQLite makes about column names is that if the
** column has an AS clause assigning it a name, that will be the name used.
** That is the only documented guarantee. However, countless applications
** developed over the years have made baseless assumptions about column names
** and will break if those assumptions changes. Hence, use extreme caution
** when modifying this routine to avoid breaking legacy.
**
** See Also: generateColumnNames()
*/
int sqlite3ColumnsFromExprList(
Parse *pParse, /* Parsing context */
ExprList *pEList, /* Expr list from which to derive column names */
i16 *pnCol, /* Write the number of columns here */
Column **paCol /* Write the new column list here */
){
sqlite3 *db = pParse->db; /* Database connection */
int i, j; /* Loop counters */
u32 cnt; /* Index added to make the name unique */
Column *aCol, *pCol; /* For looping over result columns */
int nCol; /* Number of columns in the result set */
char *zName; /* Column name */
int nName; /* Size of name in zName[] */
Hash ht; /* Hash table of column names */
sqlite3HashInit(&ht);
if( pEList ){
nCol = pEList->nExpr;
aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
testcase( aCol==0 );
if( nCol>32767 ) nCol = 32767;
}else{
nCol = 0;
aCol = 0;
}
assert( nCol==(i16)nCol );
*pnCol = nCol;
*paCol = aCol;
for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
/* Get an appropriate name for the column
*/
if( (zName = pEList->a[i].zName)!=0 ){
/* If the column contains an "AS <name>" phrase, use <name> as the name */
}else{
Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);
while( pColExpr->op==TK_DOT ){
pColExpr = pColExpr->pRight;
assert( pColExpr!=0 );
}
if( pColExpr->op==TK_COLUMN ){
/* For columns use the column name name */
int iCol = pColExpr->iColumn;
Table *pTab = pColExpr->y.pTab;
assert( pTab!=0 );
if( iCol<0 ) iCol = pTab->iPKey;
zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
}else if( pColExpr->op==TK_ID ){
assert( !ExprHasProperty(pColExpr, EP_IntValue) );
zName = pColExpr->u.zToken;
}else{
/* Use the original text of the column expression as its name */
zName = pEList->a[i].zSpan;
}
}
if( zName ){
zName = sqlite3DbStrDup(db, zName);
}else{
zName = sqlite3MPrintf(db,"column%d",i+1);
}
/* Make sure the column name is unique. If the name is not unique,
** append an integer to the name so that it becomes unique.
*/
cnt = 0;
while( zName && sqlite3HashFind(&ht, zName)!=0 ){
nName = sqlite3Strlen30(zName);
if( nName>0 ){
for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
if( zName[j]==':' ) nName = j;
}
zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
}
pCol->zName = zName;
sqlite3ColumnPropertiesFromName(0, pCol);
if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
sqlite3OomFault(db);
}
}
sqlite3HashClear(&ht);
if( db->mallocFailed ){
for(j=0; j<i; j++){
sqlite3DbFree(db, aCol[j].zName);
}
sqlite3DbFree(db, aCol);
*paCol = 0;
*pnCol = 0;
return SQLITE_NOMEM_BKPT;
}
return SQLITE_OK;
}
/*
** Add type and collation information to a column list based on
** a SELECT statement.
**
** The column list presumably came from selectColumnNamesFromExprList().
** The column list has only names, not types or collations. This
** routine goes through and adds the types and collations.
**
** This routine requires that all identifiers in the SELECT
** statement be resolved.
*/
void sqlite3SelectAddColumnTypeAndCollation(
Parse *pParse, /* Parsing contexts */
Table *pTab, /* Add column type information to this table */
Select *pSelect, /* SELECT used to determine types and collations */
char aff /* Default affinity for columns */
){
sqlite3 *db = pParse->db;
NameContext sNC;
Column *pCol;
CollSeq *pColl;
int i;
Expr *p;
struct ExprList_item *a;
assert( pSelect!=0 );
assert( (pSelect->selFlags & SF_Resolved)!=0 );
assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
if( db->mallocFailed ) return;
memset(&sNC, 0, sizeof(sNC));
sNC.pSrcList = pSelect->pSrc;
a = pSelect->pEList->a;
for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
const char *zType;
int n, m;
p = a[i].pExpr;
zType = columnType(&sNC, p, 0, 0, 0);
/* pCol->szEst = ... // Column size est for SELECT tables never used */
pCol->affinity = sqlite3ExprAffinity(p);
if( zType ){
m = sqlite3Strlen30(zType);
n = sqlite3Strlen30(pCol->zName);
pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
if( pCol->zName ){
memcpy(&pCol->zName[n+1], zType, m+1);
pCol->colFlags |= COLFLAG_HASTYPE;
}
}
if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
pColl = sqlite3ExprCollSeq(pParse, p);
if( pColl && pCol->zColl==0 ){
pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
}
}
pTab->szTabRow = 1; /* Any non-zero value works */
}
/*
** Given a SELECT statement, generate a Table structure that describes
** the result set of that SELECT.
*/
Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
Table *pTab;
sqlite3 *db = pParse->db;
u64 savedFlags;
savedFlags = db->flags;
db->flags &= ~(u64)SQLITE_FullColNames;
db->flags |= SQLITE_ShortColNames;
sqlite3SelectPrep(pParse, pSelect, 0);
db->flags = savedFlags;
if( pParse->nErr ) return 0;
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
pTab = sqlite3DbMallocZero(db, sizeof(Table) );
if( pTab==0 ){
return 0;
}
pTab->nTabRef = 1;
pTab->zName = 0;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);
pTab->iPKey = -1;
if( db->mallocFailed ){
sqlite3DeleteTable(db, pTab);
return 0;
}
return pTab;
}
/*
** Get a VDBE for the given parser context. Create a new one if necessary.
** If an error occurs, return NULL and leave a message in pParse.
*/
Vdbe *sqlite3GetVdbe(Parse *pParse){
if( pParse->pVdbe ){
return pParse->pVdbe;
}
if( pParse->pToplevel==0
&& OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
){
pParse->okConstFactor = 1;
}
return sqlite3VdbeCreate(pParse);
}
/*
** Compute the iLimit and iOffset fields of the SELECT based on the
** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
** that appear in the original SQL statement after the LIMIT and OFFSET
** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
** are the integer memory register numbers for counters used to compute
** the limit and offset. If there is no limit and/or offset, then
** iLimit and iOffset are negative.
**
** This routine changes the values of iLimit and iOffset only if
** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
** and iOffset should have been preset to appropriate default values (zero)
** prior to calling this routine.
**
** The iOffset register (if it exists) is initialized to the value
** of the OFFSET. The iLimit register is initialized to LIMIT. Register
** iOffset+1 is initialized to LIMIT+OFFSET.
**
** Only if pLimit->pLeft!=0 do the limit registers get
** redefined. The UNION ALL operator uses this property to force
** the reuse of the same limit and offset registers across multiple
** SELECT statements.
*/
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
Vdbe *v = 0;
int iLimit = 0;
int iOffset;
int n;
Expr *pLimit = p->pLimit;
if( p->iLimit ) return;
/*
** "LIMIT -1" always shows all rows. There is some
** controversy about what the correct behavior should be.
** The current implementation interprets "LIMIT 0" to mean
** no rows.
*/
if( pLimit ){
assert( pLimit->op==TK_LIMIT );
assert( pLimit->pLeft!=0 );
p->iLimit = iLimit = ++pParse->nMem;
v = sqlite3GetVdbe(pParse);
assert( v!=0 );
if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
VdbeComment((v, "LIMIT counter"));
if( n==0 ){
sqlite3VdbeGoto(v, iBreak);
}else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
p->nSelectRow = sqlite3LogEst((u64)n);
p->selFlags |= SF_FixedLimit;
}
}else{
sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
VdbeComment((v, "LIMIT counter"));
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
}
if( pLimit->pRight ){
p->iOffset = iOffset = ++pParse->nMem;
pParse->nMem++; /* Allocate an extra register for limit+offset */
sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
VdbeComment((v, "OFFSET counter"));
sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
VdbeComment((v, "LIMIT+OFFSET"));
}
}
}
#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** Return the appropriate collating sequence for the iCol-th column of
** the result set for the compound-select statement "p". Return NULL if
** the column has no default collating sequence.
**
** The collating sequence for the compound select is taken from the
** left-most term of the select that has a collating sequence.
*/
static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
CollSeq *pRet;
if( p->pPrior ){
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
}else{
pRet = 0;
}
assert( iCol>=0 );
/* iCol must be less than p->pEList->nExpr. Otherwise an error would
** have been thrown during name resolution and we would not have gotten
** this far */
if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
}
return pRet;
}
/*
** The select statement passed as the second parameter is a compound SELECT
** with an ORDER BY clause. This function allocates and returns a KeyInfo
** structure suitable for implementing the ORDER BY.
**
** Space to hold the KeyInfo structure is obtained from malloc. The calling
** function is responsible for ensuring that this structure is eventually
** freed.
*/
static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
ExprList *pOrderBy = p->pOrderBy;
int nOrderBy = p->pOrderBy->nExpr;
sqlite3 *db = pParse->db;
KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
if( pRet ){
int i;
for(i=0; i<nOrderBy; i++){
struct ExprList_item *pItem = &pOrderBy->a[i];
Expr *pTerm = pItem->pExpr;
CollSeq *pColl;
if( pTerm->flags & EP_Collate ){
pColl = sqlite3ExprCollSeq(pParse, pTerm);
}else{
pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
if( pColl==0 ) pColl = db->pDfltColl;
pOrderBy->a[i].pExpr =
sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
}
assert( sqlite3KeyInfoIsWriteable(pRet) );
pRet->aColl[i] = pColl;
pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags;
}
}
return pRet;
}
#ifndef SQLITE_OMIT_CTE
/*
** This routine generates VDBE code to compute the content of a WITH RECURSIVE
** query of the form:
**
** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
** \___________/ \_______________/
** p->pPrior p
**
**
** There is exactly one reference to the recursive-table in the FROM clause
** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
**
** The setup-query runs once to generate an initial set of rows that go
** into a Queue table. Rows are extracted from the Queue table one by
** one. Each row extracted from Queue is output to pDest. Then the single
** extracted row (now in the iCurrent table) becomes the content of the
** recursive-table for a recursive-query run. The output of the recursive-query
** is added back into the Queue table. Then another row is extracted from Queue
** and the iteration continues until the Queue table is empty.
**
** If the compound query operator is UNION then no duplicate rows are ever
** inserted into the Queue table. The iDistinct table keeps a copy of all rows
** that have ever been inserted into Queue and causes duplicates to be
** discarded. If the operator is UNION ALL, then duplicates are allowed.
**
** If the query has an ORDER BY, then entries in the Queue table are kept in
** ORDER BY order and the first entry is extracted for each cycle. Without
** an ORDER BY, the Queue table is just a FIFO.
**
** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
** have been output to pDest. A LIMIT of zero means to output no rows and a
** negative LIMIT means to output all rows. If there is also an OFFSET clause
** with a positive value, then the first OFFSET outputs are discarded rather
** than being sent to pDest. The LIMIT count does not begin until after OFFSET
** rows have been skipped.
*/
static void generateWithRecursiveQuery(
Parse *pParse, /* Parsing context */
Select *p, /* The recursive SELECT to be coded */
SelectDest *pDest /* What to do with query results */
){
SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
Select *pSetup = p->pPrior; /* The setup query */
int addrTop; /* Top of the loop */
int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
int iCurrent = 0; /* The Current table */
int regCurrent; /* Register holding Current table */
int iQueue; /* The Queue table */
int iDistinct = 0; /* To ensure unique results if UNION */
int eDest = SRT_Fifo; /* How to write to Queue */
SelectDest destQueue; /* SelectDest targetting the Queue table */
int i; /* Loop counter */
int rc; /* Result code */
ExprList *pOrderBy; /* The ORDER BY clause */
Expr *pLimit; /* Saved LIMIT and OFFSET */
int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin ){
sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
return;
}
#endif
/* Obtain authorization to do a recursive query */
if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
/* Process the LIMIT and OFFSET clauses, if they exist */
addrBreak = sqlite3VdbeMakeLabel(pParse);
p->nSelectRow = 320; /* 4 billion rows */
computeLimitRegisters(pParse, p, addrBreak);
pLimit = p->pLimit;
regLimit = p->iLimit;
regOffset = p->iOffset;
p->pLimit = 0;
p->iLimit = p->iOffset = 0;
pOrderBy = p->pOrderBy;
/* Locate the cursor number of the Current table */
for(i=0; ALWAYS(i<pSrc->nSrc); i++){
if( pSrc->a[i].fg.isRecursive ){
iCurrent = pSrc->a[i].iCursor;
break;
}
}
/* Allocate cursors numbers for Queue and Distinct. The cursor number for
** the Distinct table must be exactly one greater than Queue in order
** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
iQueue = pParse->nTab++;
if( p->op==TK_UNION ){
eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
iDistinct = pParse->nTab++;
}else{
eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
}
sqlite3SelectDestInit(&destQueue, eDest, iQueue);
/* Allocate cursors for Current, Queue, and Distinct. */
regCurrent = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
if( pOrderBy ){
KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
(char*)pKeyInfo, P4_KEYINFO);
destQueue.pOrderBy = pOrderBy;
}else{
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
}
VdbeComment((v, "Queue table"));
if( iDistinct ){
p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
p->selFlags |= SF_UsesEphemeral;
}
/* Detach the ORDER BY clause from the compound SELECT */
p->pOrderBy = 0;
/* Store the results of the setup-query in Queue. */
pSetup->pNext = 0;
ExplainQueryPlan((pParse, 1, "SETUP"));
rc = sqlite3Select(pParse, pSetup, &destQueue);
pSetup->pNext = p;
if( rc ) goto end_of_recursive_query;
/* Find the next row in the Queue and output that row */
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
/* Transfer the next row in Queue over to Current */
sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
if( pOrderBy ){
sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
}else{
sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
}
sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
/* Output the single row in Current */
addrCont = sqlite3VdbeMakeLabel(pParse);
codeOffset(v, regOffset, addrCont);
selectInnerLoop(pParse, p, iCurrent,
0, 0, pDest, addrCont, addrBreak);
if( regLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
VdbeCoverage(v);
}
sqlite3VdbeResolveLabel(v, addrCont);
/* Execute the recursive SELECT taking the single row in Current as
** the value for the recursive-table. Store the results in the Queue.
*/
if( p->selFlags & SF_Aggregate ){
sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
}else{
p->pPrior = 0;
ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
sqlite3Select(pParse, p, &destQueue);
assert( p->pPrior==0 );
p->pPrior = pSetup;
}
/* Keep running the loop until the Queue is empty */
sqlite3VdbeGoto(v, addrTop);
sqlite3VdbeResolveLabel(v, addrBreak);
end_of_recursive_query:
sqlite3ExprListDelete(pParse->db, p->pOrderBy);
p->pOrderBy = pOrderBy;
p->pLimit = pLimit;
return;
}
#endif /* SQLITE_OMIT_CTE */
/* Forward references */
static int multiSelectOrderBy(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
);
/*
** Handle the special case of a compound-select that originates from a
** VALUES clause. By handling this as a special case, we avoid deep
** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
** on a VALUES clause.
**
** Because the Select object originates from a VALUES clause:
** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
** (2) All terms are UNION ALL
** (3) There is no ORDER BY clause
**
** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
*/
static int multiSelectValues(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int nRow = 1;
int rc = 0;
int bShowAll = p->pLimit==0;
assert( p->selFlags & SF_MultiValue );
do{
assert( p->selFlags & SF_Values );
assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
if( p->pWin ) return -1;
if( p->pPrior==0 ) break;
assert( p->pPrior->pNext==p );
p = p->pPrior;
nRow += bShowAll;
}while(1);
ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
nRow==1 ? "" : "S"));
while( p ){
selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
if( !bShowAll ) break;
p->nSelectRow = nRow;
p = p->pNext;
}
return rc;
}
/*
** This routine is called to process a compound query form from
** two or more separate queries using UNION, UNION ALL, EXCEPT, or
** INTERSECT
**
** "p" points to the right-most of the two queries. the query on the
** left is p->pPrior. The left query could also be a compound query
** in which case this routine will be called recursively.
**
** The results of the total query are to be written into a destination
** of type eDest with parameter iParm.
**
** Example 1: Consider a three-way compound SQL statement.
**
** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
**
** This statement is parsed up as follows:
**
** SELECT c FROM t3
** |
** `-----> SELECT b FROM t2
** |
** `------> SELECT a FROM t1
**
** The arrows in the diagram above represent the Select.pPrior pointer.
** So if this routine is called with p equal to the t3 query, then
** pPrior will be the t2 query. p->op will be TK_UNION in this case.
**
** Notice that because of the way SQLite parses compound SELECTs, the
** individual selects always group from left to right.
*/
static int multiSelect(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int rc = SQLITE_OK; /* Success code from a subroutine */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest dest; /* Alternative data destination */
Select *pDelete = 0; /* Chain of simple selects to delete */
sqlite3 *db; /* Database connection */
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
*/
assert( p && p->pPrior ); /* Calling function guarantees this much */
assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
assert( p->selFlags & SF_Compound );
db = pParse->db;
pPrior = p->pPrior;
dest = *pDest;
if( pPrior->pOrderBy || pPrior->pLimit ){
sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
rc = 1;
goto multi_select_end;
}
v = sqlite3GetVdbe(pParse);
assert( v!=0 ); /* The VDBE already created by calling function */
/* Create the destination temporary table if necessary
*/
if( dest.eDest==SRT_EphemTab ){
assert( p->pEList );
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
dest.eDest = SRT_Table;
}
/* Special handling for a compound-select that originates as a VALUES clause.
*/
if( p->selFlags & SF_MultiValue ){
rc = multiSelectValues(pParse, p, &dest);
if( rc>=0 ) goto multi_select_end;
rc = SQLITE_OK;
}
/* Make sure all SELECTs in the statement have the same number of elements
** in their result sets.
*/
assert( p->pEList && pPrior->pEList );
assert( p->pEList->nExpr==pPrior->pEList->nExpr );
#ifndef SQLITE_OMIT_CTE
if( p->selFlags & SF_Recursive ){
generateWithRecursiveQuery(pParse, p, &dest);
}else
#endif
/* Compound SELECTs that have an ORDER BY clause are handled separately.
*/
if( p->pOrderBy ){
return multiSelectOrderBy(pParse, p, pDest);
}else{
#ifndef SQLITE_OMIT_EXPLAIN
if( pPrior->pPrior==0 ){
ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
}
#endif
/* Generate code for the left and right SELECT statements.
*/
switch( p->op ){
case TK_ALL: {
int addr = 0;
int nLimit;
assert( !pPrior->pLimit );
pPrior->iLimit = p->iLimit;
pPrior->iOffset = p->iOffset;
pPrior->pLimit = p->pLimit;
rc = sqlite3Select(pParse, pPrior, &dest);
p->pLimit = 0;
if( rc ){
goto multi_select_end;
}
p->pPrior = 0;
p->iLimit = pPrior->iLimit;
p->iOffset = pPrior->iOffset;
if( p->iLimit ){
addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
VdbeComment((v, "Jump ahead if LIMIT reached"));
if( p->iOffset ){
sqlite3VdbeAddOp3(v, OP_OffsetLimit,
p->iLimit, p->iOffset+1, p->iOffset);
}
}
ExplainQueryPlan((pParse, 1, "UNION ALL"));
rc = sqlite3Select(pParse, p, &dest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
if( pPrior->pLimit
&& sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
&& nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
){
p->nSelectRow = sqlite3LogEst((u64)nLimit);
}
if( addr ){
sqlite3VdbeJumpHere(v, addr);
}
break;
}
case TK_EXCEPT:
case TK_UNION: {
int unionTab; /* Cursor number of the temp table holding result */
u8 op = 0; /* One of the SRT_ operations to apply to self */
int priorOp; /* The SRT_ operation to apply to prior selects */
Expr *pLimit; /* Saved values of p->nLimit */
int addr;
SelectDest uniondest;
testcase( p->op==TK_EXCEPT );
testcase( p->op==TK_UNION );
priorOp = SRT_Union;
if( dest.eDest==priorOp ){
/* We can reuse a temporary table generated by a SELECT to our
** right.
*/
assert( p->pLimit==0 ); /* Not allowed on leftward elements */
unionTab = dest.iSDParm;
}else{
/* We will need to create our own temporary table to hold the
** intermediate results.
*/
unionTab = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
}
/* Code the SELECT statements to our left
*/
assert( !pPrior->pOrderBy );
sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
rc = sqlite3Select(pParse, pPrior, &uniondest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT statement
*/
if( p->op==TK_EXCEPT ){
op = SRT_Except;
}else{
assert( p->op==TK_UNION );
op = SRT_Union;
}
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
uniondest.eDest = op;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &uniondest);
testcase( rc!=SQLITE_OK );
/* Query flattening in sqlite3Select() might refill p->pOrderBy.
** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
sqlite3ExprListDelete(db, p->pOrderBy);
pDelete = p->pPrior;
p->pPrior = pPrior;
p->pOrderBy = 0;
if( p->op==TK_UNION ){
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
p->iLimit = 0;
p->iOffset = 0;
/* Convert the data in the temporary table into whatever form
** it is that we currently need.
*/
assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
assert( p->pEList || db->mallocFailed );
if( dest.eDest!=priorOp && db->mallocFailed==0 ){
int iCont, iBreak, iStart;
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
iStart = sqlite3VdbeCurrentAddr(v);
selectInnerLoop(pParse, p, unionTab,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
}
break;
}
default: assert( p->op==TK_INTERSECT ); {
int tab1, tab2;
int iCont, iBreak, iStart;
Expr *pLimit;
int addr;
SelectDest intersectdest;
int r1;
/* INTERSECT is different from the others since it requires
** two temporary tables. Hence it has its own case. Begin
** by allocating the tables we will need.
*/
tab1 = pParse->nTab++;
tab2 = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
/* Code the SELECTs to our left into temporary table "tab1".
*/
sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
rc = sqlite3Select(pParse, pPrior, &intersectdest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT into temporary table "tab2"
*/
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
assert( p->addrOpenEphm[1] == -1 );
p->addrOpenEphm[1] = addr;
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
intersectdest.iSDParm = tab2;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &intersectdest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
if( p->nSelectRow>pPrior->nSelectRow ){
p->nSelectRow = pPrior->nSelectRow;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
/* Generate code to take the intersection of the two temporary
** tables.
*/
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
r1 = sqlite3GetTempReg(pParse);
iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r1);
selectInnerLoop(pParse, p, tab1,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
break;
}
}
#ifndef SQLITE_OMIT_EXPLAIN
if( p->pNext==0 ){
ExplainQueryPlanPop(pParse);
}
#endif
}
if( pParse->nErr ) goto multi_select_end;
/* Compute collating sequences used by
** temporary tables needed to implement the compound select.
** Attach the KeyInfo structure to all temporary tables.
**
** This section is run by the right-most SELECT statement only.
** SELECT statements to the left always skip this part. The right-most
** SELECT might also skip this part if it has no ORDER BY clause and
** no temp tables are required.
*/
if( p->selFlags & SF_UsesEphemeral ){
int i; /* Loop counter */
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
Select *pLoop; /* For looping through SELECT statements */
CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
int nCol; /* Number of columns in result set */
assert( p->pNext==0 );
nCol = p->pEList->nExpr;
pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
if( !pKeyInfo ){
rc = SQLITE_NOMEM_BKPT;
goto multi_select_end;
}
for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
*apColl = multiSelectCollSeq(pParse, p, i);
if( 0==*apColl ){
*apColl = db->pDfltColl;
}
}
for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
for(i=0; i<2; i++){
int addr = pLoop->addrOpenEphm[i];
if( addr<0 ){
/* If [0] is unused then [1] is also unused. So we can
** always safely abort as soon as the first unused slot is found */
assert( pLoop->addrOpenEphm[1]<0 );
break;
}
sqlite3VdbeChangeP2(v, addr, nCol);
sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
P4_KEYINFO);
pLoop->addrOpenEphm[i] = -1;
}
}
sqlite3KeyInfoUnref(pKeyInfo);
}
multi_select_end:
pDest->iSdst = dest.iSdst;
pDest->nSdst = dest.nSdst;
sqlite3SelectDelete(db, pDelete);
return rc;
}
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
/*
** Error message for when two or more terms of a compound select have different
** size result sets.
*/
void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
if( p->selFlags & SF_Values ){
sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
}else{
sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
" do not have the same number of result columns", selectOpName(p->op));
}
}
/*
** Code an output subroutine for a coroutine implementation of a
** SELECT statment.
**
** The data to be output is contained in pIn->iSdst. There are
** pIn->nSdst columns to be output. pDest is where the output should
** be sent.
**
** regReturn is the number of the register holding the subroutine
** return address.
**
** If regPrev>0 then it is the first register in a vector that
** records the previous output. mem[regPrev] is a flag that is false
** if there has been no previous output. If regPrev>0 then code is
** generated to suppress duplicates. pKeyInfo is used for comparing
** keys.
**
** If the LIMIT found in p->iLimit is reached, jump immediately to
** iBreak.
*/
static int generateOutputSubroutine(
Parse *pParse, /* Parsing context */
Select *p, /* The SELECT statement */
SelectDest *pIn, /* Coroutine supplying data */
SelectDest *pDest, /* Where to send the data */
int regReturn, /* The return address register */
int regPrev, /* Previous result register. No uniqueness if 0 */
KeyInfo *pKeyInfo, /* For comparing with previous entry */
int iBreak /* Jump here if we hit the LIMIT */
){
Vdbe *v = pParse->pVdbe;
int iContinue;
int addr;
addr = sqlite3VdbeCurrentAddr(v);
iContinue = sqlite3VdbeMakeLabel(pParse);
/* Suppress duplicates for UNION, EXCEPT, and INTERSECT
*/
if( regPrev ){
int addr1, addr2;
addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
}
if( pParse->db->mallocFailed ) return 0;
/* Suppress the first OFFSET entries if there is an OFFSET clause
*/
codeOffset(v, p->iOffset, iContinue);
assert( pDest->eDest!=SRT_Exists );
assert( pDest->eDest!=SRT_Table );
switch( pDest->eDest ){
/* Store the result as data using a unique key.
*/
case SRT_EphemTab: {
int r1 = sqlite3GetTempReg(pParse);
int r2 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3ReleaseTempReg(pParse, r2);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
#ifndef SQLITE_OMIT_SUBQUERY
/* If we are creating a set for an "expr IN (SELECT ...)".
*/
case SRT_Set: {
int r1;
testcase( pIn->nSdst>1 );
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
r1, pDest->zAffSdst, pIn->nSdst);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
pIn->iSdst, pIn->nSdst);
sqlite3ReleaseTempReg(pParse, r1);
break;
}
/* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell and break out
** of the scan loop. Note that the select might return multiple columns
** if it is the RHS of a row-value IN operator.
*/
case SRT_Mem: {
if( pParse->nErr==0 ){
testcase( pIn->nSdst>1 );
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
}
/* The LIMIT clause will jump out of the loop for us */
break;
}
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
/* The results are stored in a sequence of registers
** starting at pDest->iSdst. Then the co-routine yields.
*/
case SRT_Coroutine: {
if( pDest->iSdst==0 ){
pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
pDest->nSdst = pIn->nSdst;
}
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
break;
}
/* If none of the above, then the result destination must be
** SRT_Output. This routine is never called with any other
** destination other than the ones handled above or SRT_Output.
**
** For SRT_Output, results are stored in a sequence of registers.
** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
** return the next row of result.
*/
default: {
assert( pDest->eDest==SRT_Output );
sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
break;
}
}
/* Jump to the end of the loop if the LIMIT is reached.
*/
if( p->iLimit ){
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
}
/* Generate the subroutine return
*/
sqlite3VdbeResolveLabel(v, iContinue);
sqlite3VdbeAddOp1(v, OP_Return, regReturn);
return addr;
}
/*
** Alternative compound select code generator for cases when there
** is an ORDER BY clause.
**
** We assume a query of the following form:
**
** <selectA> <operator> <selectB> ORDER BY <orderbylist>
**
** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
** is to code both <selectA> and <selectB> with the ORDER BY clause as
** co-routines. Then run the co-routines in parallel and merge the results
** into the output. In addition to the two coroutines (called selectA and
** selectB) there are 7 subroutines:
**
** outA: Move the output of the selectA coroutine into the output
** of the compound query.
**
** outB: Move the output of the selectB coroutine into the output
** of the compound query. (Only generated for UNION and
** UNION ALL. EXCEPT and INSERTSECT never output a row that
** appears only in B.)
**
** AltB: Called when there is data from both coroutines and A<B.
**
** AeqB: Called when there is data from both coroutines and A==B.
**
** AgtB: Called when there is data from both coroutines and A>B.
**
** EofA: Called when data is exhausted from selectA.
**
** EofB: Called when data is exhausted from selectB.
**
** The implementation of the latter five subroutines depend on which
** <operator> is used:
**
**
** UNION ALL UNION EXCEPT INTERSECT
** ------------- ----------------- -------------- -----------------
** AltB: outA, nextA outA, nextA outA, nextA nextA
**
** AeqB: outA, nextA nextA nextA outA, nextA
**
** AgtB: outB, nextB outB, nextB nextB nextB
**
** EofA: outB, nextB outB, nextB halt halt
**
** EofB: outA, nextA outA, nextA outA, nextA halt
**
** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
** causes an immediate jump to EofA and an EOF on B following nextB causes
** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
** following nextX causes a jump to the end of the select processing.
**
** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
** within the output subroutine. The regPrev register set holds the previously
** output value. A comparison is made against this value and the output
** is skipped if the next results would be the same as the previous.
**
** The implementation plan is to implement the two coroutines and seven
** subroutines first, then put the control logic at the bottom. Like this:
**
** goto Init
** coA: coroutine for left query (A)
** coB: coroutine for right query (B)
** outA: output one row of A
** outB: output one row of B (UNION and UNION ALL only)
** EofA: ...
** EofB: ...
** AltB: ...
** AeqB: ...
** AgtB: ...
** Init: initialize coroutine registers
** yield coA
** if eof(A) goto EofA
** yield coB
** if eof(B) goto EofB
** Cmpr: Compare A, B
** Jump AltB, AeqB, AgtB
** End: ...
**
** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
** actually called using Gosub and they do not Return. EofA and EofB loop
** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
** and AgtB jump to either L2 or to one of EofA or EofB.
*/
#ifndef SQLITE_OMIT_COMPOUND_SELECT
static int multiSelectOrderBy(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int i, j; /* Loop counters */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest destA; /* Destination for coroutine A */
SelectDest destB; /* Destination for coroutine B */
int regAddrA; /* Address register for select-A coroutine */
int regAddrB; /* Address register for select-B coroutine */
int addrSelectA; /* Address of the select-A coroutine */
int addrSelectB; /* Address of the select-B coroutine */
int regOutA; /* Address register for the output-A subroutine */
int regOutB; /* Address register for the output-B subroutine */
int addrOutA; /* Address of the output-A subroutine */
int addrOutB = 0; /* Address of the output-B subroutine */
int addrEofA; /* Address of the select-A-exhausted subroutine */
int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
int addrEofB; /* Address of the select-B-exhausted subroutine */
int addrAltB; /* Address of the A<B subroutine */
int addrAeqB; /* Address of the A==B subroutine */
int addrAgtB; /* Address of the A>B subroutine */
int regLimitA; /* Limit register for select-A */
int regLimitB; /* Limit register for select-A */
int regPrev; /* A range of registers to hold previous output */
int savedLimit; /* Saved value of p->iLimit */
int savedOffset; /* Saved value of p->iOffset */
int labelCmpr; /* Label for the start of the merge algorithm */
int labelEnd; /* Label for the end of the overall SELECT stmt */
int addr1; /* Jump instructions that get retargetted */
int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
KeyInfo *pKeyMerge; /* Comparison information for merging rows */
sqlite3 *db; /* Database connection */
ExprList *pOrderBy; /* The ORDER BY clause */
int nOrderBy; /* Number of terms in the ORDER BY clause */
int *aPermute; /* Mapping from ORDER BY terms to result set columns */
assert( p->pOrderBy!=0 );
assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
db = pParse->db;
v = pParse->pVdbe;
assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
labelEnd = sqlite3VdbeMakeLabel(pParse);
labelCmpr = sqlite3VdbeMakeLabel(pParse);
/* Patch up the ORDER BY clause
*/
op = p->op;
pPrior = p->pPrior;
assert( pPrior->pOrderBy==0 );
pOrderBy = p->pOrderBy;
assert( pOrderBy );
nOrderBy = pOrderBy->nExpr;
/* For operators other than UNION ALL we have to make sure that
** the ORDER BY clause covers every term of the result set. Add
** terms to the ORDER BY clause as necessary.
*/
if( op!=TK_ALL ){
for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
struct ExprList_item *pItem;
for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
assert( pItem->u.x.iOrderByCol>0 );
if( pItem->u.x.iOrderByCol==i ) break;
}
if( j==nOrderBy ){
Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
if( pNew==0 ) return SQLITE_NOMEM_BKPT;
pNew->flags |= EP_IntValue;
pNew->u.iValue = i;
p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
}
}
}
/* Compute the comparison permutation and keyinfo that is used with
** the permutation used to determine if the next
** row of results comes from selectA or selectB. Also add explicit
** collations to the ORDER BY clause terms so that when the subqueries
** to the right and the left are evaluated, they use the correct
** collation.
*/
aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
if( aPermute ){
struct ExprList_item *pItem;
aPermute[0] = nOrderBy;
for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
assert( pItem->u.x.iOrderByCol>0 );
assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
aPermute[i] = pItem->u.x.iOrderByCol - 1;
}
pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
}else{
pKeyMerge = 0;
}
/* Reattach the ORDER BY clause to the query.
*/
p->pOrderBy = pOrderBy;
pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
/* Allocate a range of temporary registers and the KeyInfo needed
** for the logic that removes duplicate result rows when the
** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
*/
if( op==TK_ALL ){
regPrev = 0;
}else{
int nExpr = p->pEList->nExpr;
assert( nOrderBy>=nExpr || db->mallocFailed );
regPrev = pParse->nMem+1;
pParse->nMem += nExpr+1;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
if( pKeyDup ){
assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
for(i=0; i<nExpr; i++){
pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
pKeyDup->aSortFlags[i] = 0;
}
}
}
/* Separate the left and the right query from one another
*/
p->pPrior = 0;
pPrior->pNext = 0;
sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
if( pPrior->pPrior==0 ){
sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
}
/* Compute the limit registers */
computeLimitRegisters(pParse, p, labelEnd);
if( p->iLimit && op==TK_ALL ){
regLimitA = ++pParse->nMem;
regLimitB = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
regLimitA);
sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
}else{
regLimitA = regLimitB = 0;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = 0;
regAddrA = ++pParse->nMem;
regAddrB = ++pParse->nMem;
regOutA = ++pParse->nMem;
regOutB = ++pParse->nMem;
sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
/* Generate a coroutine to evaluate the SELECT statement to the
** left of the compound operator - the "A" select.
*/
addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
VdbeComment((v, "left SELECT"));
pPrior->iLimit = regLimitA;
ExplainQueryPlan((pParse, 1, "LEFT"));
sqlite3Select(pParse, pPrior, &destA);
sqlite3VdbeEndCoroutine(v, regAddrA);
sqlite3VdbeJumpHere(v, addr1);
/* Generate a coroutine to evaluate the SELECT statement on
** the right - the "B" select
*/
addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
VdbeComment((v, "right SELECT"));
savedLimit = p->iLimit;
savedOffset = p->iOffset;
p->iLimit = regLimitB;
p->iOffset = 0;
ExplainQueryPlan((pParse, 1, "RIGHT"));
sqlite3Select(pParse, p, &destB);
p->iLimit = savedLimit;
p->iOffset = savedOffset;
sqlite3VdbeEndCoroutine(v, regAddrB);
/* Generate a subroutine that outputs the current row of the A
** select as the next output row of the compound select.
*/
VdbeNoopComment((v, "Output routine for A"));
addrOutA = generateOutputSubroutine(pParse,
p, &destA, pDest, regOutA,
regPrev, pKeyDup, labelEnd);
/* Generate a subroutine that outputs the current row of the B
** select as the next output row of the compound select.
*/
if( op==TK_ALL || op==TK_UNION ){
VdbeNoopComment((v, "Output routine for B"));
addrOutB = generateOutputSubroutine(pParse,
p, &destB, pDest, regOutB,
regPrev, pKeyDup, labelEnd);
}
sqlite3KeyInfoUnref(pKeyDup);
/* Generate a subroutine to run when the results from select A
** are exhausted and only data in select B remains.
*/
if( op==TK_EXCEPT || op==TK_INTERSECT ){
addrEofA_noB = addrEofA = labelEnd;
}else{
VdbeNoopComment((v, "eof-A subroutine"));
addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
VdbeCoverage(v);
sqlite3VdbeGoto(v, addrEofA);
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
/* Generate a subroutine to run when the results from select B
** are exhausted and only data in select A remains.
*/
if( op==TK_INTERSECT ){
addrEofB = addrEofA;
if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
}else{
VdbeNoopComment((v, "eof-B subroutine"));
addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
sqlite3VdbeGoto(v, addrEofB);
}
/* Generate code to handle the case of A<B
*/
VdbeNoopComment((v, "A-lt-B subroutine"));
addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
/* Generate code to handle the case of A==B
*/
if( op==TK_ALL ){
addrAeqB = addrAltB;
}else if( op==TK_INTERSECT ){
addrAeqB = addrAltB;
addrAltB++;
}else{
VdbeNoopComment((v, "A-eq-B subroutine"));
addrAeqB =
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
}
/* Generate code to handle the case of A>B
*/
VdbeNoopComment((v, "A-gt-B subroutine"));
addrAgtB = sqlite3VdbeCurrentAddr(v);
if( op==TK_ALL || op==TK_UNION ){
sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
}
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
sqlite3VdbeGoto(v, labelCmpr);
/* This code runs once to initialize everything.
*/
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
/* Implement the main merge loop
*/
sqlite3VdbeResolveLabel(v, labelCmpr);
sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
(char*)pKeyMerge, P4_KEYINFO);
sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
/* Jump to the this point in order to terminate the query.
*/
sqlite3VdbeResolveLabel(v, labelEnd);
/* Reassembly the compound query so that it will be freed correctly
** by the calling function */
if( p->pPrior ){
sqlite3SelectDelete(db, p->pPrior);
}
p->pPrior = pPrior;
pPrior->pNext = p;
/*** TBD: Insert subroutine calls to close cursors on incomplete
**** subqueries ****/
ExplainQueryPlanPop(pParse);
return pParse->nErr!=0;
}
#endif
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* An instance of the SubstContext object describes an substitution edit
** to be performed on a parse tree.
**
** All references to columns in table iTable are to be replaced by corresponding
** expressions in pEList.
*/
typedef struct SubstContext {
Parse *pParse; /* The parsing context */
int iTable; /* Replace references to this table */
int iNewTable; /* New table number */
int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
ExprList *pEList; /* Replacement expressions */
} SubstContext;
/* Forward Declarations */
static void substExprList(SubstContext*, ExprList*);
static void substSelect(SubstContext*, Select*, int);
/*
** Scan through the expression pExpr. Replace every reference to
** a column in table number iTable with a copy of the iColumn-th
** entry in pEList. (But leave references to the ROWID column
** unchanged.)
**
** This routine is part of the flattening procedure. A subquery
** whose result set is defined by pEList appears as entry in the
** FROM clause of a SELECT such that the VDBE cursor assigned to that
** FORM clause entry is iTable. This routine makes the necessary
** changes to pExpr so that it refers directly to the source table
** of the subquery rather the result set of the subquery.
*/
static Expr *substExpr(
SubstContext *pSubst, /* Description of the substitution */
Expr *pExpr /* Expr in which substitution occurs */
){
if( pExpr==0 ) return 0;
if( ExprHasProperty(pExpr, EP_FromJoin)
&& pExpr->iRightJoinTable==pSubst->iTable
){
pExpr->iRightJoinTable = pSubst->iNewTable;
}
if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
if( pExpr->iColumn<0 ){
pExpr->op = TK_NULL;
}else{
Expr *pNew;
Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
Expr ifNullRow;
assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
assert( pExpr->pRight==0 );
if( sqlite3ExprIsVector(pCopy) ){
sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
}else{
sqlite3 *db = pSubst->pParse->db;
if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
memset(&ifNullRow, 0, sizeof(ifNullRow));
ifNullRow.op = TK_IF_NULL_ROW;
ifNullRow.pLeft = pCopy;
ifNullRow.iTable = pSubst->iNewTable;
pCopy = &ifNullRow;
}
testcase( ExprHasProperty(pCopy, EP_Subquery) );
pNew = sqlite3ExprDup(db, pCopy, 0);
if( pNew && pSubst->isLeftJoin ){
ExprSetProperty(pNew, EP_CanBeNull);
}
if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
pNew->iRightJoinTable = pExpr->iRightJoinTable;
ExprSetProperty(pNew, EP_FromJoin);
}
sqlite3ExprDelete(db, pExpr);
pExpr = pNew;
/* Ensure that the expression now has an implicit collation sequence,
** just as it did when it was a column of a view or sub-query. */
if( pExpr ){
if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
(pColl ? pColl->zName : "BINARY")
);
}
ExprClearProperty(pExpr, EP_Collate);
}
}
}
}else{
if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
pExpr->iTable = pSubst->iNewTable;
}
pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
pExpr->pRight = substExpr(pSubst, pExpr->pRight);
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
substSelect(pSubst, pExpr->x.pSelect, 1);
}else{
substExprList(pSubst, pExpr->x.pList);
}
#ifndef SQLITE_OMIT_WINDOWFUNC
if( ExprHasProperty(pExpr, EP_WinFunc) ){
Window *pWin = pExpr->y.pWin;
pWin->pFilter = substExpr(pSubst, pWin->pFilter);
substExprList(pSubst, pWin->pPartition);
substExprList(pSubst, pWin->pOrderBy);
}
#endif
}
return pExpr;
}
static void substExprList(
SubstContext *pSubst, /* Description of the substitution */
ExprList *pList /* List to scan and in which to make substitutes */
){
int i;
if( pList==0 ) return;
for(i=0; i<pList->nExpr; i++){
pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
}
}
static void substSelect(
SubstContext *pSubst, /* Description of the substitution */
Select *p, /* SELECT statement in which to make substitutions */
int doPrior /* Do substitutes on p->pPrior too */
){
SrcList *pSrc;
struct SrcList_item *pItem;
int i;
if( !p ) return;
do{
substExprList(pSubst, p->pEList);
substExprList(pSubst, p->pGroupBy);
substExprList(pSubst, p->pOrderBy);
p->pHaving = substExpr(pSubst, p->pHaving);
p->pWhere = substExpr(pSubst, p->pWhere);
pSrc = p->pSrc;
assert( pSrc!=0 );
for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
substSelect(pSubst, pItem->pSelect, 1);
if( pItem->fg.isTabFunc ){
substExprList(pSubst, pItem->u1.pFuncArg);
}
}
}while( doPrior && (p = p->pPrior)!=0 );
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** This routine attempts to flatten subqueries as a performance optimization.
** This routine returns 1 if it makes changes and 0 if no flattening occurs.
**
** To understand the concept of flattening, consider the following
** query:
**
** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
**
** The default way of implementing this query is to execute the
** subquery first and store the results in a temporary table, then
** run the outer query on that temporary table. This requires two
** passes over the data. Furthermore, because the temporary table
** has no indices, the WHERE clause on the outer query cannot be
** optimized.
**
** This routine attempts to rewrite queries such as the above into
** a single flat select, like this:
**
** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
**
** The code generated for this simplification gives the same result
** but only has to scan the data once. And because indices might
** exist on the table t1, a complete scan of the data might be
** avoided.
**
** Flattening is subject to the following constraints:
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** The subquery and the outer query cannot both be aggregates.
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** (2) If the subquery is an aggregate then
** (2a) the outer query must not be a join and
** (2b) the outer query must not use subqueries
** other than the one FROM-clause subquery that is a candidate
** for flattening. (This is due to ticket [2f7170d73bf9abf80]
** from 2015-02-09.)
**
** (3) If the subquery is the right operand of a LEFT JOIN then
** (3a) the subquery may not be a join and
** (3b) the FROM clause of the subquery may not contain a virtual
** table and
** (3c) the outer query may not be an aggregate.
** (3d) the outer query may not be DISTINCT.
**
** (4) The subquery can not be DISTINCT.
**
** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
** sub-queries that were excluded from this optimization. Restriction
** (4) has since been expanded to exclude all DISTINCT subqueries.
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** If the subquery is aggregate, the outer query may not be DISTINCT.
**
** (7) The subquery must have a FROM clause. TODO: For subqueries without
** A FROM clause, consider adding a FROM clause with the special
** table sqlite_once that consists of a single row containing a
** single NULL.
**
** (8) If the subquery uses LIMIT then the outer query may not be a join.
**
** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
**
** (**) Restriction (10) was removed from the code on 2005-02-05 but we
** accidently carried the comment forward until 2014-09-15. Original
** constraint: "If the subquery is aggregate then the outer query
** may not use LIMIT."
**
** (11) The subquery and the outer query may not both have ORDER BY clauses.
**
** (**) Not implemented. Subsumed into restriction (3). Was previously
** a separate restriction deriving from ticket #350.
**
** (13) The subquery and outer query may not both use LIMIT.
**
** (14) The subquery may not use OFFSET.
**
** (15) If the outer query is part of a compound select, then the
** subquery may not use LIMIT.
** (See ticket #2339 and ticket [02a8e81d44]).
**
** (16) If the outer query is aggregate, then the subquery may not
** use ORDER BY. (Ticket #2942) This used to not matter
** until we introduced the group_concat() function.
**
** (17) If the subquery is a compound select, then
** (17a) all compound operators must be a UNION ALL, and
** (17b) no terms within the subquery compound may be aggregate
** or DISTINCT, and
** (17c) every term within the subquery compound must have a FROM clause
** (17d) the outer query may not be
** (17d1) aggregate, or
** (17d2) DISTINCT, or
** (17d3) a join.
**
** The parent and sub-query may contain WHERE clauses. Subject to
** rules (11), (13) and (14), they may also contain ORDER BY,
** LIMIT and OFFSET clauses. The subquery cannot use any compound
** operator other than UNION ALL because all the other compound
** operators have an implied DISTINCT which is disallowed by
** restriction (4).
**
** Also, each component of the sub-query must return the same number
** of result columns. This is actually a requirement for any compound
** SELECT statement, but all the code here does is make sure that no
** such (illegal) sub-query is flattened. The caller will detect the
** syntax error and return a detailed message.
**
** (18) If the sub-query is a compound select, then all terms of the
** ORDER BY clause of the parent must be simple references to
** columns of the sub-query.
**
** (19) If the subquery uses LIMIT then the outer query may not
** have a WHERE clause.
**
** (20) If the sub-query is a compound select, then it must not use
** an ORDER BY clause. Ticket #3773. We could relax this constraint
** somewhat by saying that the terms of the ORDER BY clause must
** appear as unmodified result columns in the outer query. But we
** have other optimizations in mind to deal with that case.
**
** (21) If the subquery uses LIMIT then the outer query may not be
** DISTINCT. (See ticket [752e1646fc]).
**
** (22) The subquery may not be a recursive CTE.
**
** (**) Subsumed into restriction (17d3). Was: If the outer query is
** a recursive CTE, then the sub-query may not be a compound query.
** This restriction is because transforming the
** parent to a compound query confuses the code that handles
** recursive queries in multiSelect().
**
** (**) We no longer attempt to flatten aggregate subqueries. Was:
** The subquery may not be an aggregate that uses the built-in min() or
** or max() functions. (Without this restriction, a query like:
** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
** return the value X for which Y was maximal.)
**
** (25) If either the subquery or the parent query contains a window
** function in the select list or ORDER BY clause, flattening
** is not attempted.
**
**
** In this routine, the "p" parameter is a pointer to the outer query.
** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
** uses aggregates.
**
** If flattening is not attempted, this routine is a no-op and returns 0.
** If flattening is attempted this routine returns 1.
**
** All of the expression analysis must occur on both the outer query and
** the subquery before this routine runs.
*/
static int flattenSubquery(
Parse *pParse, /* Parsing context */
Select *p, /* The parent or outer SELECT statement */
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
int isAgg /* True if outer SELECT uses aggregate functions */
){
const char *zSavedAuthContext = pParse->zAuthContext;
Select *pParent; /* Current UNION ALL term of the other query */
Select *pSub; /* The inner query or "subquery" */
Select *pSub1; /* Pointer to the rightmost select in sub-query */
SrcList *pSrc; /* The FROM clause of the outer query */
SrcList *pSubSrc; /* The FROM clause of the subquery */
int iParent; /* VDBE cursor number of the pSub result set temp table */
int iNewParent = -1;/* Replacement table for iParent */
int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
int i; /* Loop counter */
Expr *pWhere; /* The WHERE clause */
struct SrcList_item *pSubitem; /* The subquery */
sqlite3 *db = pParse->db;
/* Check to see if flattening is permitted. Return 0 if not.
*/
assert( p!=0 );
assert( p->pPrior==0 );
if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
pSrc = p->pSrc;
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
pSubitem = &pSrc->a[iFrom];
iParent = pSubitem->iCursor;
pSub = pSubitem->pSelect;
assert( pSub!=0 );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
#endif
pSubSrc = pSub->pSrc;
assert( pSubSrc );
/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
** because they could be computed at compile-time. But when LIMIT and OFFSET
** became arbitrary expressions, we were forced to add restrictions (13)
** and (14). */
if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
return 0; /* Restriction (15) */
}
if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
return 0; /* Restrictions (8)(9) */
}
if( p->pOrderBy && pSub->pOrderBy ){
return 0; /* Restriction (11) */
}
if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
return 0; /* Restriction (21) */
}
if( pSub->selFlags & (SF_Recursive) ){
return 0; /* Restrictions (22) */
}
/*
** If the subquery is the right operand of a LEFT JOIN, then the
** subquery may not be a join itself (3a). Example of why this is not
** allowed:
**
** t1 LEFT OUTER JOIN (t2 JOIN t3)
**
** If we flatten the above, we would get
**
** (t1 LEFT OUTER JOIN t2) JOIN t3
**
** which is not at all the same thing.
**
** If the subquery is the right operand of a LEFT JOIN, then the outer
** query cannot be an aggregate. (3c) This is an artifact of the way
** aggregates are processed - there is no mechanism to determine if
** the LEFT JOIN table should be all-NULL.
**
** See also tickets #306, #350, and #3300.
*/
if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
isLeftJoin = 1;
if( pSubSrc->nSrc>1 /* (3a) */
|| isAgg /* (3b) */
|| IsVirtual(pSubSrc->a[0].pTab) /* (3c) */
|| (p->selFlags & SF_Distinct)!=0 /* (3d) */
){
return 0;
}
}
#ifdef SQLITE_EXTRA_IFNULLROW
else if( iFrom>0 && !isAgg ){
/* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
** every reference to any result column from subquery in a join, even
** though they are not necessary. This will stress-test the OP_IfNullRow
** opcode. */
isLeftJoin = -1;
}
#endif
/* Restriction (17): If the sub-query is a compound SELECT, then it must
** use only the UNION ALL operator. And none of the simple select queries
** that make up the compound SELECT are allowed to be aggregate or distinct
** queries.
*/
if( pSub->pPrior ){
if( pSub->pOrderBy ){
return 0; /* Restriction (20) */
}
if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
return 0; /* (17d1), (17d2), or (17d3) */
}
for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
assert( pSub->pSrc!=0 );
assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
|| (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
|| pSub1->pSrc->nSrc<1 /* (17c) */
){
return 0;
}
testcase( pSub1->pSrc->nSrc>1 );
}
/* Restriction (18). */
if( p->pOrderBy ){
int ii;
for(ii=0; ii<p->pOrderBy->nExpr; ii++){
if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
}
}
}
/* Ex-restriction (23):
** The only way that the recursive part of a CTE can contain a compound
** subquery is for the subquery to be one term of a join. But if the
** subquery is a join, then the flattening has already been stopped by
** restriction (17d3)
*/
assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
/***** If we reach this point, flattening is permitted. *****/
SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
pSub->selId, pSub, iFrom));
/* Authorize the subquery */
pParse->zAuthContext = pSubitem->zName;
TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
testcase( i==SQLITE_DENY );
pParse->zAuthContext = zSavedAuthContext;
/* If the sub-query is a compound SELECT statement, then (by restrictions
** 17 and 18 above) it must be a UNION ALL and the parent query must
** be of the form:
**
** SELECT <expr-list> FROM (<sub-query>) <where-clause>
**
** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
** OFFSET clauses and joins them to the left-hand-side of the original
** using UNION ALL operators. In this case N is the number of simple
** select statements in the compound sub-query.
**
** Example:
**
** SELECT a+1 FROM (
** SELECT x FROM tab
** UNION ALL
** SELECT y FROM tab
** UNION ALL
** SELECT abs(z*2) FROM tab2
** ) WHERE a!=5 ORDER BY 1
**
** Transformed into:
**
** SELECT x+1 FROM tab WHERE x+1!=5
** UNION ALL
** SELECT y+1 FROM tab WHERE y+1!=5
** UNION ALL
** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
** ORDER BY 1
**
** We call this the "compound-subquery flattening".
*/
for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
Select *pNew;
ExprList *pOrderBy = p->pOrderBy;
Expr *pLimit = p->pLimit;
Select *pPrior = p->pPrior;
p->pOrderBy = 0;
p->pSrc = 0;
p->pPrior = 0;
p->pLimit = 0;
pNew = sqlite3SelectDup(db, p, 0);
p->pLimit = pLimit;
p->pOrderBy = pOrderBy;
p->pSrc = pSrc;
p->op = TK_ALL;
if( pNew==0 ){
p->pPrior = pPrior;
}else{
pNew->pPrior = pPrior;
if( pPrior ) pPrior->pNext = pNew;
pNew->pNext = p;
p->pPrior = pNew;
SELECTTRACE(2,pParse,p,("compound-subquery flattener"
" creates %u as peer\n",pNew->selId));
}
if( db->mallocFailed ) return 1;
}
/* Begin flattening the iFrom-th entry of the FROM clause
** in the outer query.
*/
pSub = pSub1 = pSubitem->pSelect;
/* Delete the transient table structure associated with the
** subquery
*/
sqlite3DbFree(db, pSubitem->zDatabase);
sqlite3DbFree(db, pSubitem->zName);
sqlite3DbFree(db, pSubitem->zAlias);
pSubitem->zDatabase = 0;
pSubitem->zName = 0;
pSubitem->zAlias = 0;
pSubitem->pSelect = 0;
/* Defer deleting the Table object associated with the
** subquery until code generation is
** complete, since there may still exist Expr.pTab entries that
** refer to the subquery even after flattening. Ticket #3346.
**
** pSubitem->pTab is always non-NULL by test restrictions and tests above.
*/
if( ALWAYS(pSubitem->pTab!=0) ){
Table *pTabToDel = pSubitem->pTab;
if( pTabToDel->nTabRef==1 ){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pTabToDel->pNextZombie = pToplevel->pZombieTab;
pToplevel->pZombieTab = pTabToDel;
}else{
pTabToDel->nTabRef--;
}
pSubitem->pTab = 0;
}
/* The following loop runs once for each term in a compound-subquery
** flattening (as described above). If we are doing a different kind
** of flattening - a flattening other than a compound-subquery flattening -
** then this loop only runs once.
**
** This loop moves all of the FROM elements of the subquery into the
** the FROM clause of the outer query. Before doing this, remember
** the cursor number for the original outer query FROM element in
** iParent. The iParent cursor will never be used. Subsequent code
** will scan expressions looking for iParent references and replace
** those references with expressions that resolve to the subquery FROM
** elements we are now copying in.
*/
for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
int nSubSrc;
u8 jointype = 0;
assert( pSub!=0 );
pSubSrc = pSub->pSrc; /* FROM clause of subquery */
nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
pSrc = pParent->pSrc; /* FROM clause of the outer query */
if( pSrc ){
assert( pParent==p ); /* First time through the loop */
jointype = pSubitem->fg.jointype;
}else{
assert( pParent!=p ); /* 2nd and subsequent times through the loop */
pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* The subquery uses a single slot of the FROM clause of the outer
** query. If the subquery has more than one element in its FROM clause,
** then expand the outer query to make space for it to hold all elements
** of the subquery.
**
** Example:
**
** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
**
** The outer query has 3 slots in its FROM clause. One slot of the
** outer query (the middle slot) is used by the subquery. The next
** block of code will expand the outer query FROM clause to 4 slots.
** The middle slot is expanded to two slots in order to make space
** for the two elements in the FROM clause of the subquery.
*/
if( nSubSrc>1 ){
pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* Transfer the FROM clause terms from the subquery into the
** outer query.
*/
for(i=0; i<nSubSrc; i++){
sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
pSrc->a[i+iFrom] = pSubSrc->a[i];
iNewParent = pSubSrc->a[i].iCursor;
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
}
pSrc->a[iFrom].fg.jointype = jointype;
/* Now begin substituting subquery result set expressions for
** references to the iParent in the outer query.
**
** Example:
**
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
** \ \_____________ subquery __________/ /
** \_____________________ outer query ______________________________/
**
** We look at every expression in the outer query and every place we see
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
*/
if( pSub->pOrderBy ){
/* At this point, any non-zero iOrderByCol values indicate that the
** ORDER BY column expression is identical to the iOrderByCol'th
** expression returned by SELECT statement pSub. Since these values
** do not necessarily correspond to columns in SELECT statement pParent,
** zero them before transfering the ORDER BY clause.
**
** Not doing this may cause an error if a subsequent call to this
** function attempts to flatten a compound sub-query into pParent
** (the only way this can happen is if the compound sub-query is
** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
ExprList *pOrderBy = pSub->pOrderBy;
for(i=0; i<pOrderBy->nExpr; i++){
pOrderBy->a[i].u.x.iOrderByCol = 0;
}
assert( pParent->pOrderBy==0 );
pParent->pOrderBy = pOrderBy;
pSub->pOrderBy = 0;
}
pWhere = pSub->pWhere;
pSub->pWhere = 0;
if( isLeftJoin>0 ){
sqlite3SetJoinExpr(pWhere, iNewParent);
}
pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
if( db->mallocFailed==0 ){
SubstContext x;
x.pParse = pParse;
x.iTable = iParent;
x.iNewTable = iNewParent;
x.isLeftJoin = isLeftJoin;
x.pEList = pSub->pEList;
substSelect(&x, pParent, 0);
}
/* The flattened query is a compound if either the inner or the
** outer query is a compound. */
pParent->selFlags |= pSub->selFlags & SF_Compound;
assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
/*
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
**
** One is tempted to try to add a and b to combine the limits. But this
** does not work if either limit is negative.
*/
if( pSub->pLimit ){
pParent->pLimit = pSub->pLimit;
pSub->pLimit = 0;
}
}
/* Finially, delete what is left of the subquery and return
** success.
*/
sqlite3SelectDelete(db, pSub1);
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
/*
** A structure to keep track of all of the column values that are fixed to
** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
*/
typedef struct WhereConst WhereConst;
struct WhereConst {
Parse *pParse; /* Parsing context */
int nConst; /* Number for COLUMN=CONSTANT terms */
int nChng; /* Number of times a constant is propagated */
Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
};
/*
** Add a new entry to the pConst object. Except, do not add duplicate
** pColumn entires.
*/
static void constInsert(
WhereConst *pConst, /* The WhereConst into which we are inserting */
Expr *pColumn, /* The COLUMN part of the constraint */
Expr *pValue /* The VALUE part of the constraint */
){
int i;
assert( pColumn->op==TK_COLUMN );
/* 2018-10-25 ticket [cf5ed20f]
** Make sure the same pColumn is not inserted more than once */
for(i=0; i<pConst->nConst; i++){
const Expr *pExpr = pConst->apExpr[i*2];
assert( pExpr->op==TK_COLUMN );
if( pExpr->iTable==pColumn->iTable
&& pExpr->iColumn==pColumn->iColumn
){
return; /* Already present. Return without doing anything. */
}
}
pConst->nConst++;
pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
pConst->nConst*2*sizeof(Expr*));
if( pConst->apExpr==0 ){
pConst->nConst = 0;
}else{
if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
pConst->apExpr[pConst->nConst*2-2] = pColumn;
pConst->apExpr[pConst->nConst*2-1] = pValue;
}
}
/*
** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
** is a constant expression and where the term must be true because it
** is part of the AND-connected terms of the expression. For each term
** found, add it to the pConst structure.
*/
static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
Expr *pRight, *pLeft;
if( pExpr==0 ) return;
if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
if( pExpr->op==TK_AND ){
findConstInWhere(pConst, pExpr->pRight);
findConstInWhere(pConst, pExpr->pLeft);
return;
}
if( pExpr->op!=TK_EQ ) return;
pRight = pExpr->pRight;
pLeft = pExpr->pLeft;
assert( pRight!=0 );
assert( pLeft!=0 );
if( pRight->op==TK_COLUMN
&& !ExprHasProperty(pRight, EP_FixedCol)
&& sqlite3ExprIsConstant(pLeft)
&& sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr))
){
constInsert(pConst, pRight, pLeft);
}else
if( pLeft->op==TK_COLUMN
&& !ExprHasProperty(pLeft, EP_FixedCol)
&& sqlite3ExprIsConstant(pRight)
&& sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr))
){
constInsert(pConst, pLeft, pRight);
}
}
/*
** This is a Walker expression callback. pExpr is a candidate expression
** to be replaced by a value. If pExpr is equivalent to one of the
** columns named in pWalker->u.pConst, then overwrite it with its
** corresponding value.
*/
static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
int i;
WhereConst *pConst;
if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
pConst = pWalker->u.pConst;
for(i=0; i<pConst->nConst; i++){
Expr *pColumn = pConst->apExpr[i*2];
if( pColumn==pExpr ) continue;
if( pColumn->iTable!=pExpr->iTable ) continue;
if( pColumn->iColumn!=pExpr->iColumn ) continue;
/* A match is found. Add the EP_FixedCol property */
pConst->nChng++;
ExprClearProperty(pExpr, EP_Leaf);
ExprSetProperty(pExpr, EP_FixedCol);
assert( pExpr->pLeft==0 );
pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
break;
}
return WRC_Prune;
}
/*
** The WHERE-clause constant propagation optimization.
**
** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
** then throughout the query replace all other occurrences of COLUMN
** with CONSTANT within the WHERE clause.
**
** For example, the query:
**
** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
**
** Is transformed into
**
** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
**
** Return true if any transformations where made and false if not.
**
** Implementation note: Constant propagation is tricky due to affinity
** and collating sequence interactions. Consider this example:
**
** CREATE TABLE t1(a INT,b TEXT);
** INSERT INTO t1 VALUES(123,'0123');
** SELECT * FROM t1 WHERE a=123 AND b=a;
** SELECT * FROM t1 WHERE a=123 AND b=123;
**
** The two SELECT statements above should return different answers. b=a
** is alway true because the comparison uses numeric affinity, but b=123
** is false because it uses text affinity and '0123' is not the same as '123'.
** To work around this, the expression tree is not actually changed from
** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
** and the "123" value is hung off of the pLeft pointer. Code generator
** routines know to generate the constant "123" instead of looking up the
** column value. Also, to avoid collation problems, this optimization is
** only attempted if the "a=123" term uses the default BINARY collation.
*/
static int propagateConstants(
Parse *pParse, /* The parsing context */
Select *p /* The query in which to propagate constants */
){
WhereConst x;
Walker w;
int nChng = 0;
x.pParse = pParse;
do{
x.nConst = 0;
x.nChng = 0;
x.apExpr = 0;
findConstInWhere(&x, p->pWhere);
if( x.nConst ){
memset(&w, 0, sizeof(w));
w.pParse = pParse;
w.xExprCallback = propagateConstantExprRewrite;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.xSelectCallback2 = 0;
w.walkerDepth = 0;
w.u.pConst = &x;
sqlite3WalkExpr(&w, p->pWhere);
sqlite3DbFree(x.pParse->db, x.apExpr);
nChng += x.nChng;
}
}while( x.nChng );
return nChng;
}
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/*
** Make copies of relevant WHERE clause terms of the outer query into
** the WHERE clause of subquery. Example:
**
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
**
** Transformed into:
**
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
** WHERE x=5 AND y=10;
**
** The hope is that the terms added to the inner query will make it more
** efficient.
**
** Do not attempt this optimization if:
**
** (1) (** This restriction was removed on 2017-09-29. We used to
** disallow this optimization for aggregate subqueries, but now
** it is allowed by putting the extra terms on the HAVING clause.
** The added HAVING clause is pointless if the subquery lacks
** a GROUP BY clause. But such a HAVING clause is also harmless
** so there does not appear to be any reason to add extra logic
** to suppress it. **)
**
** (2) The inner query is the recursive part of a common table expression.
**
** (3) The inner query has a LIMIT clause (since the changes to the WHERE
** clause would change the meaning of the LIMIT).
**
** (4) The inner query is the right operand of a LEFT JOIN and the
** expression to be pushed down does not come from the ON clause
** on that LEFT JOIN.
**
** (5) The WHERE clause expression originates in the ON or USING clause
** of a LEFT JOIN where iCursor is not the right-hand table of that
** left join. An example:
**
** SELECT *
** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
**
** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
** But if the (b2=2) term were to be pushed down into the bb subquery,
** then the (1,1,NULL) row would be suppressed.
**
** (6) The inner query features one or more window-functions (since
** changes to the WHERE clause of the inner query could change the
** window over which window functions are calculated).
**
** Return 0 if no changes are made and non-zero if one or more WHERE clause
** terms are duplicated into the subquery.
*/
static int pushDownWhereTerms(
Parse *pParse, /* Parse context (for malloc() and error reporting) */
Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
Expr *pWhere, /* The WHERE clause of the outer query */
int iCursor, /* Cursor number of the subquery */
int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
){
Expr *pNew;
int nChng = 0;
if( pWhere==0 ) return 0;
if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pSubq->pWin ) return 0; /* restriction (6) */
#endif
#ifdef SQLITE_DEBUG
/* Only the first term of a compound can have a WITH clause. But make
** sure no other terms are marked SF_Recursive in case something changes
** in the future.
*/
{
Select *pX;
for(pX=pSubq; pX; pX=pX->pPrior){
assert( (pX->selFlags & (SF_Recursive))==0 );
}
}
#endif
if( pSubq->pLimit!=0 ){
return 0; /* restriction (3) */
}
while( pWhere->op==TK_AND ){
nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
iCursor, isLeftJoin);
pWhere = pWhere->pLeft;
}
if( isLeftJoin
&& (ExprHasProperty(pWhere,EP_FromJoin)==0
|| pWhere->iRightJoinTable!=iCursor)
){
return 0; /* restriction (4) */
}
if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
return 0; /* restriction (5) */
}
if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
nChng++;
while( pSubq ){
SubstContext x;
pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
unsetJoinExpr(pNew, -1);
x.pParse = pParse;
x.iTable = iCursor;
x.iNewTable = iCursor;
x.isLeftJoin = 0;
x.pEList = pSubq->pEList;
pNew = substExpr(&x, pNew);
if( pSubq->selFlags & SF_Aggregate ){
pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
}else{
pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
}
pSubq = pSubq->pPrior;
}
}
return nChng;
}
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
/*
** The pFunc is the only aggregate function in the query. Check to see
** if the query is a candidate for the min/max optimization.
**
** If the query is a candidate for the min/max optimization, then set
** *ppMinMax to be an ORDER BY clause to be used for the optimization
** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
** whether pFunc is a min() or max() function.
**
** If the query is not a candidate for the min/max optimization, return
** WHERE_ORDERBY_NORMAL (which must be zero).
**
** This routine must be called after aggregate functions have been
** located but before their arguments have been subjected to aggregate
** analysis.
*/
static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
const char *zFunc; /* Name of aggregate function pFunc */
ExprList *pOrderBy;
u8 sortFlags;
assert( *ppMinMax==0 );
assert( pFunc->op==TK_AGG_FUNCTION );
assert( !IsWindowFunc(pFunc) );
if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){
return eRet;
}
zFunc = pFunc->u.zToken;
if( sqlite3StrICmp(zFunc, "min")==0 ){
eRet = WHERE_ORDERBY_MIN;
sortFlags = KEYINFO_ORDER_BIGNULL;
}else if( sqlite3StrICmp(zFunc, "max")==0 ){
eRet = WHERE_ORDERBY_MAX;
sortFlags = KEYINFO_ORDER_DESC;
}else{
return eRet;
}
*ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
assert( pOrderBy!=0 || db->mallocFailed );
if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;
return eRet;
}
/*
** The select statement passed as the first argument is an aggregate query.
** The second argument is the associated aggregate-info object. This
** function tests if the SELECT is of the form:
**
** SELECT count(*) FROM <tbl>
**
** where table is a database table, not a sub-select or view. If the query
** does match this pattern, then a pointer to the Table object representing
** <tbl> is returned. Otherwise, 0 is returned.
*/
static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
Table *pTab;
Expr *pExpr;
assert( !p->pGroupBy );
if( p->pWhere || p->pEList->nExpr!=1
|| p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
){
return 0;
}
pTab = p->pSrc->a[0].pTab;
pExpr = p->pEList->a[0].pExpr;
assert( pTab && !pTab->pSelect && pExpr );
if( IsVirtual(pTab) ) return 0;
if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
if( NEVER(pAggInfo->nFunc==0) ) return 0;
if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
return pTab;
}
/*
** If the source-list item passed as an argument was augmented with an
** INDEXED BY clause, then try to locate the specified index. If there
** was such a clause and the named index cannot be found, return
** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
** pFrom->pIndex and return SQLITE_OK.
*/
int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
if( pFrom->pTab && pFrom->fg.isIndexedBy ){
Table *pTab = pFrom->pTab;
char *zIndexedBy = pFrom->u1.zIndexedBy;
Index *pIdx;
for(pIdx=pTab->pIndex;
pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
pIdx=pIdx->pNext
);
if( !pIdx ){
sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
pParse->checkSchema = 1;
return SQLITE_ERROR;
}
pFrom->pIBIndex = pIdx;
}
return SQLITE_OK;
}
/*
** Detect compound SELECT statements that use an ORDER BY clause with
** an alternative collating sequence.
**
** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
**
** These are rewritten as a subquery:
**
** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
** ORDER BY ... COLLATE ...
**
** This transformation is necessary because the multiSelectOrderBy() routine
** above that generates the code for a compound SELECT with an ORDER BY clause
** uses a merge algorithm that requires the same collating sequence on the
** result columns as on the ORDER BY clause. See ticket
** http://www.sqlite.org/src/info/6709574d2a
**
** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
** The UNION ALL operator works fine with multiSelectOrderBy() even when
** there are COLLATE terms in the ORDER BY.
*/
static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
int i;
Select *pNew;
Select *pX;
sqlite3 *db;
struct ExprList_item *a;
SrcList *pNewSrc;
Parse *pParse;
Token dummy;
if( p->pPrior==0 ) return WRC_Continue;
if( p->pOrderBy==0 ) return WRC_Continue;
for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
if( pX==0 ) return WRC_Continue;
a = p->pOrderBy->a;
for(i=p->pOrderBy->nExpr-1; i>=0; i--){
if( a[i].pExpr->flags & EP_Collate ) break;
}
if( i<0 ) return WRC_Continue;
/* If we reach this point, that means the transformation is required. */
pParse = pWalker->pParse;
db = pParse->db;
pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
if( pNew==0 ) return WRC_Abort;
memset(&dummy, 0, sizeof(dummy));
pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
if( pNewSrc==0 ) return WRC_Abort;
*pNew = *p;
p->pSrc = pNewSrc;
p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
p->op = TK_SELECT;
p->pWhere = 0;
pNew->pGroupBy = 0;
pNew->pHaving = 0;
pNew->pOrderBy = 0;
p->pPrior = 0;
p->pNext = 0;
p->pWith = 0;
#ifndef SQLITE_OMIT_WINDOWFUNC
p->pWinDefn = 0;
#endif
p->selFlags &= ~SF_Compound;
assert( (p->selFlags & SF_Converted)==0 );
p->selFlags |= SF_Converted;
assert( pNew->pPrior!=0 );
pNew->pPrior->pNext = pNew;
pNew->pLimit = 0;
return WRC_Continue;
}
/*
** Check to see if the FROM clause term pFrom has table-valued function
** arguments. If it does, leave an error message in pParse and return
** non-zero, since pFrom is not allowed to be a table-valued function.
*/
static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
if( pFrom->fg.isTabFunc ){
sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
return 1;
}
return 0;
}
#ifndef SQLITE_OMIT_CTE
/*
** Argument pWith (which may be NULL) points to a linked list of nested
** WITH contexts, from inner to outermost. If the table identified by
** FROM clause element pItem is really a common-table-expression (CTE)
** then return a pointer to the CTE definition for that table. Otherwise
** return NULL.
**
** If a non-NULL value is returned, set *ppContext to point to the With
** object that the returned CTE belongs to.
*/
static struct Cte *searchWith(
With *pWith, /* Current innermost WITH clause */
struct SrcList_item *pItem, /* FROM clause element to resolve */
With **ppContext /* OUT: WITH clause return value belongs to */
){
const char *zName;
if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
With *p;
for(p=pWith; p; p=p->pOuter){
int i;
for(i=0; i<p->nCte; i++){
if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
*ppContext = p;
return &p->a[i];
}
}
}
}
return 0;
}
/* The code generator maintains a stack of active WITH clauses
** with the inner-most WITH clause being at the top of the stack.
**
** This routine pushes the WITH clause passed as the second argument
** onto the top of the stack. If argument bFree is true, then this
** WITH clause will never be popped from the stack. In this case it
** should be freed along with the Parse object. In other cases, when
** bFree==0, the With object will be freed along with the SELECT
** statement with which it is associated.
*/
void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
if( pWith ){
assert( pParse->pWith!=pWith );
pWith->pOuter = pParse->pWith;
pParse->pWith = pWith;
if( bFree ) pParse->pWithToFree = pWith;
}
}
/*
** This function checks if argument pFrom refers to a CTE declared by
** a WITH clause on the stack currently maintained by the parser. And,
** if currently processing a CTE expression, if it is a recursive
** reference to the current CTE.
**
** If pFrom falls into either of the two categories above, pFrom->pTab
** and other fields are populated accordingly. The caller should check
** (pFrom->pTab!=0) to determine whether or not a successful match
** was found.
**
** Whether or not a match is found, SQLITE_OK is returned if no error
** occurs. If an error does occur, an error message is stored in the
** parser and some error code other than SQLITE_OK returned.
*/
static int withExpand(
Walker *pWalker,
struct SrcList_item *pFrom
){
Parse *pParse = pWalker->pParse;
sqlite3 *db = pParse->db;
struct Cte *pCte; /* Matched CTE (or NULL if no match) */
With *pWith; /* WITH clause that pCte belongs to */
assert( pFrom->pTab==0 );
if( pParse->nErr ){
return SQLITE_ERROR;
}
pCte = searchWith(pParse->pWith, pFrom, &pWith);
if( pCte ){
Table *pTab;
ExprList *pEList;
Select *pSel;
Select *pLeft; /* Left-most SELECT statement */
int bMayRecursive; /* True if compound joined by UNION [ALL] */
With *pSavedWith; /* Initial value of pParse->pWith */
/* If pCte->zCteErr is non-NULL at this point, then this is an illegal
** recursive reference to CTE pCte. Leave an error in pParse and return
** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
** In this case, proceed. */
if( pCte->zCteErr ){
sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
return SQLITE_ERROR;
}
if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
assert( pFrom->pTab==0 );
pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
if( pTab==0 ) return WRC_Abort;
pTab->nTabRef = 1;
pTab->zName = sqlite3DbStrDup(db, pCte->zName);
pTab->iPKey = -1;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
assert( pFrom->pSelect );
/* Check if this is a recursive CTE. */
pSel = pFrom->pSelect;
bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
if( bMayRecursive ){
int i;
SrcList *pSrc = pFrom->pSelect->pSrc;
for(i=0; i<pSrc->nSrc; i++){
struct SrcList_item *pItem = &pSrc->a[i];
if( pItem->zDatabase==0
&& pItem->zName!=0
&& 0==sqlite3StrICmp(pItem->zName, pCte->zName)
){
pItem->pTab = pTab;
pItem->fg.isRecursive = 1;
pTab->nTabRef++;
pSel->selFlags |= SF_Recursive;
}
}
}
/* Only one recursive reference is permitted. */
if( pTab->nTabRef>2 ){
sqlite3ErrorMsg(
pParse, "multiple references to recursive table: %s", pCte->zName
);
return SQLITE_ERROR;
}
assert( pTab->nTabRef==1 ||
((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
pCte->zCteErr = "circular reference: %s";
pSavedWith = pParse->pWith;
pParse->pWith = pWith;
if( bMayRecursive ){
Select *pPrior = pSel->pPrior;
assert( pPrior->pWith==0 );
pPrior->pWith = pSel->pWith;
sqlite3WalkSelect(pWalker, pPrior);
pPrior->pWith = 0;
}else{
sqlite3WalkSelect(pWalker, pSel);
}
pParse->pWith = pWith;
for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
pEList = pLeft->pEList;
if( pCte->pCols ){
if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
pCte->zName, pEList->nExpr, pCte->pCols->nExpr
);
pParse->pWith = pSavedWith;
return SQLITE_ERROR;
}
pEList = pCte->pCols;
}
sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
if( bMayRecursive ){
if( pSel->selFlags & SF_Recursive ){
pCte->zCteErr = "multiple recursive references: %s";
}else{
pCte->zCteErr = "recursive reference in a subquery: %s";
}
sqlite3WalkSelect(pWalker, pSel);
}
pCte->zCteErr = 0;
pParse->pWith = pSavedWith;
}
return SQLITE_OK;
}
#endif
#ifndef SQLITE_OMIT_CTE
/*
** If the SELECT passed as the second argument has an associated WITH
** clause, pop it from the stack stored as part of the Parse object.
**
** This function is used as the xSelectCallback2() callback by
** sqlite3SelectExpand() when walking a SELECT tree to resolve table
** names and other FROM clause elements.
*/
static void selectPopWith(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
With *pWith = findRightmost(p)->pWith;
if( pWith!=0 ){
assert( pParse->pWith==pWith );
pParse->pWith = pWith->pOuter;
}
}
}
#else
#define selectPopWith 0
#endif
/*
** The SrcList_item structure passed as the second argument represents a
** sub-query in the FROM clause of a SELECT statement. This function
** allocates and populates the SrcList_item.pTab object. If successful,
** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
** SQLITE_NOMEM.
*/
int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
Select *pSel = pFrom->pSelect;
Table *pTab;
assert( pSel );
pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
if( pTab==0 ) return SQLITE_NOMEM;
pTab->nTabRef = 1;
if( pFrom->zAlias ){
pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
}else{
pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
}
while( pSel->pPrior ){ pSel = pSel->pPrior; }
sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
pTab->iPKey = -1;
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
pTab->tabFlags |= TF_Ephemeral;
return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
}
/*
** This routine is a Walker callback for "expanding" a SELECT statement.
** "Expanding" means to do the following:
**
** (1) Make sure VDBE cursor numbers have been assigned to every
** element of the FROM clause.
**
** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
** defines FROM clause. When views appear in the FROM clause,
** fill pTabList->a[].pSelect with a copy of the SELECT statement
** that implements the view. A copy is made of the view's SELECT
** statement so that we can freely modify or delete that statement
** without worrying about messing up the persistent representation
** of the view.
**
** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
** on joins and the ON and USING clause of joins.
**
** (4) Scan the list of columns in the result set (pEList) looking
** for instances of the "*" operator or the TABLE.* operator.
** If found, expand each "*" to be every column in every table
** and TABLE.* to be every column in TABLE.
**
*/
static int selectExpander(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
int i, j, k;
SrcList *pTabList;
ExprList *pEList;
struct SrcList_item *pFrom;
sqlite3 *db = pParse->db;
Expr *pE, *pRight, *pExpr;
u16 selFlags = p->selFlags;
u32 elistFlags = 0;
p->selFlags |= SF_Expanded;
if( db->mallocFailed ){
return WRC_Abort;
}
assert( p->pSrc!=0 );
if( (selFlags & SF_Expanded)!=0 ){
return WRC_Prune;
}
if( pWalker->eCode ){
/* Renumber selId because it has been copied from a view */
p->selId = ++pParse->nSelect;
}
pTabList = p->pSrc;
pEList = p->pEList;
sqlite3WithPush(pParse, p->pWith, 0);
/* Make sure cursor numbers have been assigned to all entries in
** the FROM clause of the SELECT statement.
*/
sqlite3SrcListAssignCursors(pParse, pTabList);
/* Look up every table named in the FROM clause of the select. If
** an entry of the FROM clause is a subquery instead of a table or view,
** then create a transient table structure to describe the subquery.
*/
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab;
assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
if( pFrom->fg.isRecursive ) continue;
assert( pFrom->pTab==0 );
#ifndef SQLITE_OMIT_CTE
if( withExpand(pWalker, pFrom) ) return WRC_Abort;
if( pFrom->pTab ) {} else
#endif
if( pFrom->zName==0 ){
#ifndef SQLITE_OMIT_SUBQUERY
Select *pSel = pFrom->pSelect;
/* A sub-query in the FROM clause of a SELECT */
assert( pSel!=0 );
assert( pFrom->pTab==0 );
if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
#endif
}else{
/* An ordinary table or view name in the FROM clause */
assert( pFrom->pTab==0 );
pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
if( pTab==0 ) return WRC_Abort;
if( pTab->nTabRef>=0xffff ){
sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
pTab->zName);
pFrom->pTab = 0;
return WRC_Abort;
}
pTab->nTabRef++;
if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
return WRC_Abort;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
if( IsVirtual(pTab) || pTab->pSelect ){
i16 nCol;
u8 eCodeOrig = pWalker->eCode;
if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
assert( pFrom->pSelect==0 );
if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
pTab->zName);
}
pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
nCol = pTab->nCol;
pTab->nCol = -1;
pWalker->eCode = 1; /* Turn on Select.selId renumbering */
sqlite3WalkSelect(pWalker, pFrom->pSelect);
pWalker->eCode = eCodeOrig;
pTab->nCol = nCol;
}
#endif
}
/* Locate the index named by the INDEXED BY clause, if any. */
if( sqlite3IndexedByLookup(pParse, pFrom) ){
return WRC_Abort;
}
}
/* Process NATURAL keywords, and ON and USING clauses of joins.
*/
if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
return WRC_Abort;
}
/* For every "*" that occurs in the column list, insert the names of
** all columns in all tables. And for every TABLE.* insert the names
** of all columns in TABLE. The parser inserted a special expression
** with the TK_ASTERISK operator for each "*" that it found in the column
** list. The following code just has to locate the TK_ASTERISK
** expressions and expand each one to the list of all columns in
** all tables.
**
** The first loop just checks to see if there are any "*" operators
** that need expanding.
*/
for(k=0; k<pEList->nExpr; k++){
pE = pEList->a[k].pExpr;
if( pE->op==TK_ASTERISK ) break;
assert( pE->op!=TK_DOT || pE->pRight!=0 );
assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
elistFlags |= pE->flags;
}
if( k<pEList->nExpr ){
/*
** If we get here it means the result set contains one or more "*"
** operators that need to be expanded. Loop through each expression
** in the result set and expand them one by one.
*/
struct ExprList_item *a = pEList->a;
ExprList *pNew = 0;
int flags = pParse->db->flags;
int longNames = (flags & SQLITE_FullColNames)!=0
&& (flags & SQLITE_ShortColNames)==0;
for(k=0; k<pEList->nExpr; k++){
pE = a[k].pExpr;
elistFlags |= pE->flags;
pRight = pE->pRight;
assert( pE->op!=TK_DOT || pRight!=0 );
if( pE->op!=TK_ASTERISK
&& (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
){
/* This particular expression does not need to be expanded.
*/
pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
if( pNew ){
pNew->a[pNew->nExpr-1].zName = a[k].zName;
pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
a[k].zName = 0;
a[k].zSpan = 0;
}
a[k].pExpr = 0;
}else{
/* This expression is a "*" or a "TABLE.*" and needs to be
** expanded. */
int tableSeen = 0; /* Set to 1 when TABLE matches */
char *zTName = 0; /* text of name of TABLE */
if( pE->op==TK_DOT ){
assert( pE->pLeft!=0 );
assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
zTName = pE->pLeft->u.zToken;
}
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab = pFrom->pTab;
Select *pSub = pFrom->pSelect;
char *zTabName = pFrom->zAlias;
const char *zSchemaName = 0;
int iDb;
if( zTabName==0 ){
zTabName = pTab->zName;
}
if( db->mallocFailed ) break;
if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
pSub = 0;
if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
continue;
}
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
}
for(j=0; j<pTab->nCol; j++){
char *zName = pTab->aCol[j].zName;
char *zColname; /* The computed column name */
char *zToFree; /* Malloced string that needs to be freed */
Token sColname; /* Computed column name as a token */
assert( zName );
if( zTName && pSub
&& sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
){
continue;
}
/* If a column is marked as 'hidden', omit it from the expanded
** result-set list unless the SELECT has the SF_IncludeHidden
** bit set.
*/
if( (p->selFlags & SF_IncludeHidden)==0
&& IsHiddenColumn(&pTab->aCol[j])
){
continue;
}
tableSeen = 1;
if( i>0 && zTName==0 ){
if( (pFrom->fg.jointype & JT_NATURAL)!=0
&& tableAndColumnIndex(pTabList, i, zName, 0, 0)
){
/* In a NATURAL join, omit the join columns from the
** table to the right of the join */
continue;
}
if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
/* In a join with a USING clause, omit columns in the
** using clause from the table on the right. */
continue;
}
}
pRight = sqlite3Expr(db, TK_ID, zName);
zColname = zName;
zToFree = 0;
if( longNames || pTabList->nSrc>1 ){
Expr *pLeft;
pLeft = sqlite3Expr(db, TK_ID, zTabName);
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
if( zSchemaName ){
pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
}
if( longNames ){
zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
zToFree = zColname;
}
}else{
pExpr = pRight;
}
pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
sqlite3TokenInit(&sColname, zColname);
sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
if( pSub ){
pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
testcase( pX->zSpan==0 );
}else{
pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
zSchemaName, zTabName, zColname);
testcase( pX->zSpan==0 );
}
pX->bSpanIsTab = 1;
}
sqlite3DbFree(db, zToFree);
}
}
if( !tableSeen ){
if( zTName ){
sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
}else{
sqlite3ErrorMsg(pParse, "no tables specified");
}
}
}
}
sqlite3ExprListDelete(db, pEList);
p->pEList = pNew;
}
if( p->pEList ){
if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many columns in result set");
return WRC_Abort;
}
if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
p->selFlags |= SF_ComplexResult;
}
}
return WRC_Continue;
}
/*
** No-op routine for the parse-tree walker.
**
** When this routine is the Walker.xExprCallback then expression trees
** are walked without any actions being taken at each node. Presumably,
** when this routine is used for Walker.xExprCallback then
** Walker.xSelectCallback is set to do something useful for every
** subquery in the parser tree.
*/
int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
return WRC_Continue;
}
/*
** No-op routine for the parse-tree walker for SELECT statements.
** subquery in the parser tree.
*/
int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
return WRC_Continue;
}
#if SQLITE_DEBUG
/*
** Always assert. This xSelectCallback2 implementation proves that the
** xSelectCallback2 is never invoked.
*/
void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
assert( 0 );
}
#endif
/*
** This routine "expands" a SELECT statement and all of its subqueries.
** For additional information on what it means to "expand" a SELECT
** statement, see the comment on the selectExpand worker callback above.
**
** Expanding a SELECT statement is the first step in processing a
** SELECT statement. The SELECT statement must be expanded before
** name resolution is performed.
**
** If anything goes wrong, an error message is written into pParse.
** The calling function can detect the problem by looking at pParse->nErr
** and/or pParse->db->mallocFailed.
*/
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
Walker w;
w.xExprCallback = sqlite3ExprWalkNoop;
w.pParse = pParse;
if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
w.xSelectCallback = convertCompoundSelectToSubquery;
w.xSelectCallback2 = 0;
sqlite3WalkSelect(&w, pSelect);
}
w.xSelectCallback = selectExpander;
w.xSelectCallback2 = selectPopWith;
w.eCode = 0;
sqlite3WalkSelect(&w, pSelect);
}
#ifndef SQLITE_OMIT_SUBQUERY
/*
** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
** interface.
**
** For each FROM-clause subquery, add Column.zType and Column.zColl
** information to the Table structure that represents the result set
** of that subquery.
**
** The Table structure that represents the result set was constructed
** by selectExpander() but the type and collation information was omitted
** at that point because identifiers had not yet been resolved. This
** routine is called after identifier resolution.
*/
static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
Parse *pParse;
int i;
SrcList *pTabList;
struct SrcList_item *pFrom;
assert( p->selFlags & SF_Resolved );
if( p->selFlags & SF_HasTypeInfo ) return;
p->selFlags |= SF_HasTypeInfo;
pParse = pWalker->pParse;
pTabList = p->pSrc;
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
Table *pTab = pFrom->pTab;
assert( pTab!=0 );
if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
/* A sub-query in the FROM clause of a SELECT */
Select *pSel = pFrom->pSelect;
if( pSel ){
while( pSel->pPrior ) pSel = pSel->pPrior;
sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
SQLITE_AFF_NONE);
}
}
}
}
#endif
/*
** This routine adds datatype and collating sequence information to
** the Table structures of all FROM-clause subqueries in a
** SELECT statement.
**
** Use this routine after name resolution.
*/
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
#ifndef SQLITE_OMIT_SUBQUERY
Walker w;
w.xSelectCallback = sqlite3SelectWalkNoop;
w.xSelectCallback2 = selectAddSubqueryTypeInfo;
w.xExprCallback = sqlite3ExprWalkNoop;
w.pParse = pParse;
sqlite3WalkSelect(&w, pSelect);
#endif
}
/*
** This routine sets up a SELECT statement for processing. The
** following is accomplished:
**
** * VDBE Cursor numbers are assigned to all FROM-clause terms.
** * Ephemeral Table objects are created for all FROM-clause subqueries.
** * ON and USING clauses are shifted into WHERE statements
** * Wildcards "*" and "TABLE.*" in result sets are expanded.
** * Identifiers in expression are matched to tables.
**
** This routine acts recursively on all subqueries within the SELECT.
*/
void sqlite3SelectPrep(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
NameContext *pOuterNC /* Name context for container */
){
assert( p!=0 || pParse->db->mallocFailed );
if( pParse->db->mallocFailed ) return;
if( p->selFlags & SF_HasTypeInfo ) return;
sqlite3SelectExpand(pParse, p);
if( pParse->nErr || pParse->db->mallocFailed ) return;
sqlite3ResolveSelectNames(pParse, p, pOuterNC);
if( pParse->nErr || pParse->db->mallocFailed ) return;
sqlite3SelectAddTypeInfo(pParse, p);
}
/*
** Reset the aggregate accumulator.
**
** The aggregate accumulator is a set of memory cells that hold
** intermediate results while calculating an aggregate. This
** routine generates code that stores NULLs in all of those memory
** cells.
*/
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
struct AggInfo_func *pFunc;
int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
if( nReg==0 ) return;
#ifdef SQLITE_DEBUG
/* Verify that all AggInfo registers are within the range specified by
** AggInfo.mnReg..AggInfo.mxReg */
assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
for(i=0; i<pAggInfo->nColumn; i++){
assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
&& pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
}
for(i=0; i<pAggInfo->nFunc; i++){
assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
&& pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
}
#endif
sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
if( pFunc->iDistinct>=0 ){
Expr *pE = pFunc->pExpr;
assert( !ExprHasProperty(pE, EP_xIsSelect) );
if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
"argument");
pFunc->iDistinct = -1;
}else{
KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
(char*)pKeyInfo, P4_KEYINFO);
}
}
}
}
/*
** Invoke the OP_AggFinalize opcode for every aggregate function
** in the AggInfo structure.
*/
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
struct AggInfo_func *pF;
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
ExprList *pList = pF->pExpr->x.pList;
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
}
}
/*
** Update the accumulator memory cells for an aggregate based on
** the current cursor position.
**
** If regAcc is non-zero and there are no min() or max() aggregates
** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
** registers if register regAcc contains 0. The caller will take care
** of setting and clearing regAcc.
*/
static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
Vdbe *v = pParse->pVdbe;
int i;
int regHit = 0;
int addrHitTest = 0;
struct AggInfo_func *pF;
struct AggInfo_col *pC;
pAggInfo->directMode = 1;
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
int nArg;
int addrNext = 0;
int regAgg;
ExprList *pList = pF->pExpr->x.pList;
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
assert( !IsWindowFunc(pF->pExpr) );
if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){
Expr *pFilter = pF->pExpr->y.pWin->pFilter;
if( pAggInfo->nAccumulator
&& (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
){
if( regHit==0 ) regHit = ++pParse->nMem;
/* If this is the first row of the group (regAcc==0), clear the
** "magnet" register regHit so that the accumulator registers
** are populated if the FILTER clause jumps over the the
** invocation of min() or max() altogether. Or, if this is not
** the first row (regAcc==1), set the magnet register so that the
** accumulators are not populated unless the min()/max() is invoked and
** indicates that they should be. */
sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
}
addrNext = sqlite3VdbeMakeLabel(pParse);
sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
}
if( pList ){
nArg = pList->nExpr;
regAgg = sqlite3GetTempRange(pParse, nArg);
sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
}else{
nArg = 0;
regAgg = 0;
}
if( pF->iDistinct>=0 ){
if( addrNext==0 ){
addrNext = sqlite3VdbeMakeLabel(pParse);
}
testcase( nArg==0 ); /* Error condition */
testcase( nArg>1 ); /* Also an error */
codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
}
if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
CollSeq *pColl = 0;
struct ExprList_item *pItem;
int j;
assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
}
if( !pColl ){
pColl = pParse->db->pDfltColl;
}
if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
}
sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
sqlite3VdbeChangeP5(v, (u8)nArg);
sqlite3ReleaseTempRange(pParse, regAgg, nArg);
if( addrNext ){
sqlite3VdbeResolveLabel(v, addrNext);
}
}
if( regHit==0 && pAggInfo->nAccumulator ){
regHit = regAcc;
}
if( regHit ){
addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
}
for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
}
pAggInfo->directMode = 0;
if( addrHitTest ){
sqlite3VdbeJumpHere(v, addrHitTest);
}
}
/*
** Add a single OP_Explain instruction to the VDBE to explain a simple
** count(*) query ("SELECT count(*) FROM pTab").
*/
#ifndef SQLITE_OMIT_EXPLAIN
static void explainSimpleCount(
Parse *pParse, /* Parse context */
Table *pTab, /* Table being queried */
Index *pIdx /* Index used to optimize scan, or NULL */
){
if( pParse->explain==2 ){
int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
pTab->zName,
bCover ? " USING COVERING INDEX " : "",
bCover ? pIdx->zName : ""
);
}
}
#else
# define explainSimpleCount(a,b,c)
#endif
/*
** sqlite3WalkExpr() callback used by havingToWhere().
**
** If the node passed to the callback is a TK_AND node, return
** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
**
** Otherwise, return WRC_Prune. In this case, also check if the
** sub-expression matches the criteria for being moved to the WHERE
** clause. If so, add it to the WHERE clause and replace the sub-expression
** within the HAVING expression with a constant "1".
*/
static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
if( pExpr->op!=TK_AND ){
Select *pS = pWalker->u.pSelect;
if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
sqlite3 *db = pWalker->pParse->db;
Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
if( pNew ){
Expr *pWhere = pS->pWhere;
SWAP(Expr, *pNew, *pExpr);
pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
pS->pWhere = pNew;
pWalker->eCode = 1;
}
}
return WRC_Prune;
}
return WRC_Continue;
}
/*
** Transfer eligible terms from the HAVING clause of a query, which is
** processed after grouping, to the WHERE clause, which is processed before
** grouping. For example, the query:
**
** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
**
** can be rewritten as:
**
** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
**
** A term of the HAVING expression is eligible for transfer if it consists
** entirely of constants and expressions that are also GROUP BY terms that
** use the "BINARY" collation sequence.
*/
static void havingToWhere(Parse *pParse, Select *p){
Walker sWalker;
memset(&sWalker, 0, sizeof(sWalker));
sWalker.pParse = pParse;
sWalker.xExprCallback = havingToWhereExprCb;
sWalker.u.pSelect = p;
sqlite3WalkExpr(&sWalker, p->pHaving);
#if SELECTTRACE_ENABLED
if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}
/*
** Check to see if the pThis entry of pTabList is a self-join of a prior view.
** If it is, then return the SrcList_item for the prior view. If it is not,
** then return 0.
*/
static struct SrcList_item *isSelfJoinView(
SrcList *pTabList, /* Search for self-joins in this FROM clause */
struct SrcList_item *pThis /* Search for prior reference to this subquery */
){
struct SrcList_item *pItem;
for(pItem = pTabList->a; pItem<pThis; pItem++){
Select *pS1;
if( pItem->pSelect==0 ) continue;
if( pItem->fg.viaCoroutine ) continue;
if( pItem->zName==0 ) continue;
assert( pItem->pTab!=0 );
assert( pThis->pTab!=0 );
if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
pS1 = pItem->pSelect;
if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
/* The query flattener left two different CTE tables with identical
** names in the same FROM clause. */
continue;
}
if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
|| sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
){
/* The view was modified by some other optimization such as
** pushDownWhereTerms() */
continue;
}
return pItem;
}
return 0;
}
#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
/*
** Attempt to transform a query of the form
**
** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
**
** Into this:
**
** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
**
** The transformation only works if all of the following are true:
**
** * The subquery is a UNION ALL of two or more terms
** * The subquery does not have a LIMIT clause
** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
** * The outer query is a simple count(*) with no WHERE clause or other
** extraneous syntax.
**
** Return TRUE if the optimization is undertaken.
*/
static int countOfViewOptimization(Parse *pParse, Select *p){
Select *pSub, *pPrior;
Expr *pExpr;
Expr *pCount;
sqlite3 *db;
if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
if( p->pWhere ) return 0;
if( p->pGroupBy ) return 0;
pExpr = p->pEList->a[0].pExpr;
if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
pSub = p->pSrc->a[0].pSelect;
if( pSub==0 ) return 0; /* The FROM is a subquery */
if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
do{
if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
if( pSub->pWhere ) return 0; /* No WHERE clause */
if( pSub->pLimit ) return 0; /* No LIMIT clause */
if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
pSub = pSub->pPrior; /* Repeat over compound */
}while( pSub );
/* If we reach this point then it is OK to perform the transformation */
db = pParse->db;
pCount = pExpr;
pExpr = 0;
pSub = p->pSrc->a[0].pSelect;
p->pSrc->a[0].pSelect = 0;
sqlite3SrcListDelete(db, p->pSrc);
p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
while( pSub ){
Expr *pTerm;
pPrior = pSub->pPrior;
pSub->pPrior = 0;
pSub->pNext = 0;
pSub->selFlags |= SF_Aggregate;
pSub->selFlags &= ~SF_Compound;
pSub->nSelectRow = 0;
sqlite3ExprListDelete(db, pSub->pEList);
pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
sqlite3PExprAddSelect(pParse, pTerm, pSub);
if( pExpr==0 ){
pExpr = pTerm;
}else{
pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
}
pSub = pPrior;
}
p->pEList->a[0].pExpr = pExpr;
p->selFlags &= ~SF_Aggregate;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
}
#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
/*
** Generate code for the SELECT statement given in the p argument.
**
** The results are returned according to the SelectDest structure.
** See comments in sqliteInt.h for further information.
**
** This routine returns the number of errors. If any errors are
** encountered, then an appropriate error message is left in
** pParse->zErrMsg.
**
** This routine does NOT free the Select structure passed in. The
** calling function needs to do that.
*/
int sqlite3Select(
Parse *pParse, /* The parser context */
Select *p, /* The SELECT statement being coded. */
SelectDest *pDest /* What to do with the query results */
){
int i, j; /* Loop counters */
WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
Vdbe *v; /* The virtual machine under construction */
int isAgg; /* True for select lists like "count(*)" */
ExprList *pEList = 0; /* List of columns to extract. */
SrcList *pTabList; /* List of tables to select from */
Expr *pWhere; /* The WHERE clause. May be NULL */
ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
Expr *pHaving; /* The HAVING clause. May be NULL */
int rc = 1; /* Value to return from this function */
DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
SortCtx sSort; /* Info on how to code the ORDER BY clause */
AggInfo sAggInfo; /* Information used by aggregate queries */
int iEnd; /* Address of the end of the query */
sqlite3 *db; /* The database connection */
ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
u8 minMaxFlag; /* Flag for min/max queries */
db = pParse->db;
v = sqlite3GetVdbe(pParse);
if( p==0 || db->mallocFailed || pParse->nErr ){
return 1;
}
if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
memset(&sAggInfo, 0, sizeof(sAggInfo));
#if SELECTTRACE_ENABLED
SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
if( sqlite3SelectTrace & 0x100 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
if( IgnorableOrderby(pDest) ){
assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
/* If ORDER BY makes no difference in the output then neither does
** DISTINCT so it can be removed too. */
sqlite3ExprListDelete(db, p->pOrderBy);
p->pOrderBy = 0;
p->selFlags &= ~SF_Distinct;
}
sqlite3SelectPrep(pParse, p, 0);
if( pParse->nErr || db->mallocFailed ){
goto select_end;
}
assert( p->pEList!=0 );
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x104 ){
SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
if( pDest->eDest==SRT_Output ){
generateColumnNames(pParse, p);
}
#ifndef SQLITE_OMIT_WINDOWFUNC
rc = sqlite3WindowRewrite(pParse, p);
if( rc ){
assert( db->mallocFailed || pParse->nErr>0 );
goto select_end;
}
#if SELECTTRACE_ENABLED
if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){
SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
#endif /* SQLITE_OMIT_WINDOWFUNC */
pTabList = p->pSrc;
isAgg = (p->selFlags & SF_Aggregate)!=0;
memset(&sSort, 0, sizeof(sSort));
sSort.pOrderBy = p->pOrderBy;
/* Try to various optimizations (flattening subqueries, and strength
** reduction of join operators) in the FROM clause up into the main query
*/
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
struct SrcList_item *pItem = &pTabList->a[i];
Select *pSub = pItem->pSelect;
Table *pTab = pItem->pTab;
/* Convert LEFT JOIN into JOIN if there are terms of the right table
** of the LEFT JOIN used in the WHERE clause.
*/
if( (pItem->fg.jointype & JT_LEFT)!=0
&& sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
&& OptimizationEnabled(db, SQLITE_SimplifyJoin)
){
SELECTTRACE(0x100,pParse,p,
("LEFT-JOIN simplifies to JOIN on term %d\n",i));
pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
unsetJoinExpr(p->pWhere, pItem->iCursor);
}
/* No futher action if this term of the FROM clause is no a subquery */
if( pSub==0 ) continue;
/* Catch mismatch in the declared columns of a view and the number of
** columns in the SELECT on the RHS */
if( pTab->nCol!=pSub->pEList->nExpr ){
sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
pTab->nCol, pTab->zName, pSub->pEList->nExpr);
goto select_end;
}
/* Do not try to flatten an aggregate subquery.
**
** Flattening an aggregate subquery is only possible if the outer query
** is not a join. But if the outer query is not a join, then the subquery
** will be implemented as a co-routine and there is no advantage to
** flattening in that case.
*/
if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
assert( pSub->pGroupBy==0 );
/* If the outer query contains a "complex" result set (that is,
** if the result set of the outer query uses functions or subqueries)
** and if the subquery contains an ORDER BY clause and if
** it will be implemented as a co-routine, then do not flatten. This
** restriction allows SQL constructs like this:
**
** SELECT expensive_function(x)
** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
**
** The expensive_function() is only computed on the 10 rows that
** are output, rather than every row of the table.
**
** The requirement that the outer query have a complex result set
** means that flattening does occur on simpler SQL constraints without
** the expensive_function() like:
**
** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
*/
if( pSub->pOrderBy!=0
&& i==0
&& (p->selFlags & SF_ComplexResult)!=0
&& (pTabList->nSrc==1
|| (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
){
continue;
}
if( flattenSubquery(pParse, p, i, isAgg) ){
if( pParse->nErr ) goto select_end;
/* This subquery can be absorbed into its parent. */
i = -1;
}
pTabList = p->pSrc;
if( db->mallocFailed ) goto select_end;
if( !IgnorableOrderby(pDest) ){
sSort.pOrderBy = p->pOrderBy;
}
}
#endif
#ifndef SQLITE_OMIT_COMPOUND_SELECT
/* Handle compound SELECT statements using the separate multiSelect()
** procedure.
*/
if( p->pPrior ){
rc = multiSelect(pParse, p, pDest);
#if SELECTTRACE_ENABLED
SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
return rc;
}
#endif
/* Do the WHERE-clause constant propagation optimization if this is
** a join. No need to speed time on this operation for non-join queries
** as the equivalent optimization will be handled by query planner in
** sqlite3WhereBegin().
*/
if( pTabList->nSrc>1
&& OptimizationEnabled(db, SQLITE_PropagateConst)
&& propagateConstants(pParse, p)
){
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}else{
SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
}
#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
&& countOfViewOptimization(pParse, p)
){
if( db->mallocFailed ) goto select_end;
pEList = p->pEList;
pTabList = p->pSrc;
}
#endif
/* For each term in the FROM clause, do two things:
** (1) Authorized unreferenced tables
** (2) Generate code for all sub-queries
*/
for(i=0; i<pTabList->nSrc; i++){
struct SrcList_item *pItem = &pTabList->a[i];
SelectDest dest;
Select *pSub;
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
const char *zSavedAuthContext;
#endif
/* Issue SQLITE_READ authorizations with a fake column name for any
** tables that are referenced but from which no values are extracted.
** Examples of where these kinds of null SQLITE_READ authorizations
** would occur:
**
** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
**
** The fake column name is an empty string. It is possible for a table to
** have a column named by the empty string, in which case there is no way to
** distinguish between an unreferenced table and an actual reference to the
** "" column. The original design was for the fake column name to be a NULL,
** which would be unambiguous. But legacy authorization callbacks might
** assume the column name is non-NULL and segfault. The use of an empty
** string for the fake column name seems safer.
*/
if( pItem->colUsed==0 && pItem->zName!=0 ){
sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
}
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
/* Generate code for all sub-queries in the FROM clause
*/
pSub = pItem->pSelect;
if( pSub==0 ) continue;
/* The code for a subquery should only be generated once, though it is
** technically harmless for it to be generated multiple times. The
** following assert() will detect if something changes to cause
** the same subquery to be coded multiple times, as a signal to the
** developers to try to optimize the situation.
**
** Update 2019-07-24:
** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.
** The dbsqlfuzz fuzzer found a case where the same subquery gets
** coded twice. So this assert() now becomes a testcase(). It should
** be very rare, though.
*/
testcase( pItem->addrFillSub!=0 );
/* Increment Parse.nHeight by the height of the largest expression
** tree referred to by this, the parent select. The child select
** may contain expression trees of at most
** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
** more conservative than necessary, but much easier than enforcing
** an exact limit.
*/
pParse->nHeight += sqlite3SelectExprHeight(p);
/* Make copies of constant WHERE-clause terms in the outer query down
** inside the subquery. This can help the subquery to run more efficiently.
*/
if( OptimizationEnabled(db, SQLITE_PushDown)
&& pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
(pItem->fg.jointype & JT_OUTER)!=0)
){
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,
("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}else{
SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
}
zSavedAuthContext = pParse->zAuthContext;
pParse->zAuthContext = pItem->zName;
/* Generate code to implement the subquery
**
** The subquery is implemented as a co-routine if the subquery is
** guaranteed to be the outer loop (so that it does not need to be
** computed more than once)
**
** TODO: Are there other reasons beside (1) to use a co-routine
** implementation?
*/
if( i==0
&& (pTabList->nSrc==1
|| (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
){
/* Implement a co-routine that will return a single row of the result
** set on each invocation.
*/
int addrTop = sqlite3VdbeCurrentAddr(v)+1;
pItem->regReturn = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
VdbeComment((v, "%s", pItem->pTab->zName));
pItem->addrFillSub = addrTop;
sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
sqlite3Select(pParse, pSub, &dest);
pItem->pTab->nRowLogEst = pSub->nSelectRow;
pItem->fg.viaCoroutine = 1;
pItem->regResult = dest.iSdst;
sqlite3VdbeEndCoroutine(v, pItem->regReturn);
sqlite3VdbeJumpHere(v, addrTop-1);
sqlite3ClearTempRegCache(pParse);
}else{
/* Generate a subroutine that will fill an ephemeral table with
** the content of this subquery. pItem->addrFillSub will point
** to the address of the generated subroutine. pItem->regReturn
** is a register allocated to hold the subroutine return address
*/
int topAddr;
int onceAddr = 0;
int retAddr;
struct SrcList_item *pPrior;
testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
pItem->regReturn = ++pParse->nMem;
topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
pItem->addrFillSub = topAddr+1;
if( pItem->fg.isCorrelated==0 ){
/* If the subquery is not correlated and if we are not inside of
** a trigger, then we only need to compute the value of the subquery
** once. */
onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
}else{
VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
}
pPrior = isSelfJoinView(pTabList, pItem);
if( pPrior ){
sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
assert( pPrior->pSelect!=0 );
pSub->nSelectRow = pPrior->pSelect->nSelectRow;
}else{
sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
sqlite3Select(pParse, pSub, &dest);
}
pItem->pTab->nRowLogEst = pSub->nSelectRow;
if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
VdbeComment((v, "end %s", pItem->pTab->zName));
sqlite3VdbeChangeP1(v, topAddr, retAddr);
sqlite3ClearTempRegCache(pParse);
}
if( db->mallocFailed ) goto select_end;
pParse->nHeight -= sqlite3SelectExprHeight(p);
pParse->zAuthContext = zSavedAuthContext;
#endif
}
/* Various elements of the SELECT copied into local variables for
** convenience */
pEList = p->pEList;
pWhere = p->pWhere;
pGroupBy = p->pGroupBy;
pHaving = p->pHaving;
sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
/* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
** if the select-list is the same as the ORDER BY list, then this query
** can be rewritten as a GROUP BY. In other words, this:
**
** SELECT DISTINCT xyz FROM ... ORDER BY xyz
**
** is transformed to:
**
** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
**
** The second form is preferred as a single index (or temp-table) may be
** used for both the ORDER BY and DISTINCT processing. As originally
** written the query must use a temp-table for at least one of the ORDER
** BY and DISTINCT, and an index or separate temp-table for the other.
*/
if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
&& sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
&& p->pWin==0
){
p->selFlags &= ~SF_Distinct;
pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
/* Notice that even thought SF_Distinct has been cleared from p->selFlags,
** the sDistinct.isTnct is still set. Hence, isTnct represents the
** original setting of the SF_Distinct flag, not the current setting */
assert( sDistinct.isTnct );
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
}
/* If there is an ORDER BY clause, then create an ephemeral index to
** do the sorting. But this sorting ephemeral index might end up
** being unused if the data can be extracted in pre-sorted order.
** If that is the case, then the OP_OpenEphemeral instruction will be
** changed to an OP_Noop once we figure out that the sorting index is
** not needed. The sSort.addrSortIndex variable is used to facilitate
** that change.
*/
if( sSort.pOrderBy ){
KeyInfo *pKeyInfo;
pKeyInfo = sqlite3KeyInfoFromExprList(
pParse, sSort.pOrderBy, 0, pEList->nExpr);
sSort.iECursor = pParse->nTab++;
sSort.addrSortIndex =
sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
(char*)pKeyInfo, P4_KEYINFO
);
}else{
sSort.addrSortIndex = -1;
}
/* If the output is destined for a temporary table, open that table.
*/
if( pDest->eDest==SRT_EphemTab ){
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
}
/* Set the limiter.
*/
iEnd = sqlite3VdbeMakeLabel(pParse);
if( (p->selFlags & SF_FixedLimit)==0 ){
p->nSelectRow = 320; /* 4 billion rows */
}
computeLimitRegisters(pParse, p, iEnd);
if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
sSort.sortFlags |= SORTFLAG_UseSorter;
}
/* Open an ephemeral index to use for the distinct set.
*/
if( p->selFlags & SF_Distinct ){
sDistinct.tabTnct = pParse->nTab++;
sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
sDistinct.tabTnct, 0, 0,
(char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
P4_KEYINFO);
sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
}else{
sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
}
if( !isAgg && pGroupBy==0 ){
/* No aggregate functions and no GROUP BY clause */
u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
| (p->selFlags & SF_FixedLimit);
#ifndef SQLITE_OMIT_WINDOWFUNC
Window *pWin = p->pWin; /* Master window object (or NULL) */
if( pWin ){
sqlite3WindowCodeInit(pParse, pWin);
}
#endif
assert( WHERE_USE_LIMIT==SF_FixedLimit );
/* Begin the database scan. */
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
p->pEList, wctrlFlags, p->nSelectRow);
if( pWInfo==0 ) goto select_end;
if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
}
if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
}
if( sSort.pOrderBy ){
sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
sSort.pOrderBy = 0;
}
}
/* If sorting index that was created by a prior OP_OpenEphemeral
** instruction ended up not being needed, then change the OP_OpenEphemeral
** into an OP_Noop.
*/
if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
}
assert( p->pEList==pEList );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( pWin ){
int addrGosub = sqlite3VdbeMakeLabel(pParse);
int iCont = sqlite3VdbeMakeLabel(pParse);
int iBreak = sqlite3VdbeMakeLabel(pParse);
int regGosub = ++pParse->nMem;
sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
sqlite3VdbeResolveLabel(v, addrGosub);
VdbeNoopComment((v, "inner-loop subroutine"));
sSort.labelOBLopt = 0;
selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp1(v, OP_Return, regGosub);
VdbeComment((v, "end inner-loop subroutine"));
sqlite3VdbeResolveLabel(v, iBreak);
}else
#endif /* SQLITE_OMIT_WINDOWFUNC */
{
/* Use the standard inner loop. */
selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
sqlite3WhereContinueLabel(pWInfo),
sqlite3WhereBreakLabel(pWInfo));
/* End the database scan loop.
*/
sqlite3WhereEnd(pWInfo);
}
}else{
/* This case when there exist aggregate functions or a GROUP BY clause
** or both */
NameContext sNC; /* Name context for processing aggregate information */
int iAMem; /* First Mem address for storing current GROUP BY */
int iBMem; /* First Mem address for previous GROUP BY */
int iUseFlag; /* Mem address holding flag indicating that at least
** one row of the input to the aggregator has been
** processed */
int iAbortFlag; /* Mem address which causes query abort if positive */
int groupBySort; /* Rows come from source in GROUP BY order */
int addrEnd; /* End of processing for this SELECT */
int sortPTab = 0; /* Pseudotable used to decode sorting results */
int sortOut = 0; /* Output register from the sorter */
int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
/* Remove any and all aliases between the result set and the
** GROUP BY clause.
*/
if( pGroupBy ){
int k; /* Loop counter */
struct ExprList_item *pItem; /* For looping over expression in a list */
for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
pItem->u.x.iAlias = 0;
}
for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
pItem->u.x.iAlias = 0;
}
assert( 66==sqlite3LogEst(100) );
if( p->nSelectRow>66 ) p->nSelectRow = 66;
/* If there is both a GROUP BY and an ORDER BY clause and they are
** identical, then it may be possible to disable the ORDER BY clause
** on the grounds that the GROUP BY will cause elements to come out
** in the correct order. It also may not - the GROUP BY might use a
** database index that causes rows to be grouped together as required
** but not actually sorted. Either way, record the fact that the
** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
** variable. */
if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
int ii;
/* The GROUP BY processing doesn't care whether rows are delivered in
** ASC or DESC order - only that each group is returned contiguously.
** So set the ASC/DESC flags in the GROUP BY to match those in the
** ORDER BY to maximize the chances of rows being delivered in an
** order that makes the ORDER BY redundant. */
for(ii=0; ii<pGroupBy->nExpr; ii++){
u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
pGroupBy->a[ii].sortFlags = sortFlags;
}
if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
orderByGrp = 1;
}
}
}else{
assert( 0==sqlite3LogEst(1) );
p->nSelectRow = 0;
}
/* Create a label to jump to when we want to abort the query */
addrEnd = sqlite3VdbeMakeLabel(pParse);
/* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
** SELECT statement.
*/
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
sNC.uNC.pAggInfo = &sAggInfo;
VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
sAggInfo.mnReg = pParse->nMem+1;
sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
sAggInfo.pGroupBy = pGroupBy;
sqlite3ExprAnalyzeAggList(&sNC, pEList);
sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
if( pHaving ){
if( pGroupBy ){
assert( pWhere==p->pWhere );
assert( pHaving==p->pHaving );
assert( pGroupBy==p->pGroupBy );
havingToWhere(pParse, p);
pWhere = p->pWhere;
}
sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
}
sAggInfo.nAccumulator = sAggInfo.nColumn;
if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
}else{
minMaxFlag = WHERE_ORDERBY_NORMAL;
}
for(i=0; i<sAggInfo.nFunc; i++){
Expr *pExpr = sAggInfo.aFunc[i].pExpr;
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
sNC.ncFlags |= NC_InAggFunc;
sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
#ifndef SQLITE_OMIT_WINDOWFUNC
assert( !IsWindowFunc(pExpr) );
if( ExprHasProperty(pExpr, EP_WinFunc) ){
sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
}
#endif
sNC.ncFlags &= ~NC_InAggFunc;
}
sAggInfo.mxReg = pParse->nMem;
if( db->mallocFailed ) goto select_end;
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x400 ){
int ii;
SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
sqlite3TreeViewSelect(0, p, 0);
for(ii=0; ii<sAggInfo.nColumn; ii++){
sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
ii, sAggInfo.aCol[ii].iMem);
sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
}
for(ii=0; ii<sAggInfo.nFunc; ii++){
sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
ii, sAggInfo.aFunc[ii].iMem);
sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
}
}
#endif
/* Processing for aggregates with GROUP BY is very different and
** much more complex than aggregates without a GROUP BY.
*/
if( pGroupBy ){
KeyInfo *pKeyInfo; /* Keying information for the group by clause */
int addr1; /* A-vs-B comparision jump */
int addrOutputRow; /* Start of subroutine that outputs a result row */
int regOutputRow; /* Return address register for output subroutine */
int addrSetAbort; /* Set the abort flag and return */
int addrTopOfLoop; /* Top of the input loop */
int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
int addrReset; /* Subroutine for resetting the accumulator */
int regReset; /* Return address register for reset subroutine */
/* If there is a GROUP BY clause we might need a sorting index to
** implement it. Allocate that sorting index now. If it turns out
** that we do not need it after all, the OP_SorterOpen instruction
** will be converted into a Noop.
*/
sAggInfo.sortingIdx = pParse->nTab++;
pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
0, (char*)pKeyInfo, P4_KEYINFO);
/* Initialize memory locations used by GROUP BY aggregate processing
*/
iUseFlag = ++pParse->nMem;
iAbortFlag = ++pParse->nMem;
regOutputRow = ++pParse->nMem;
addrOutputRow = sqlite3VdbeMakeLabel(pParse);
regReset = ++pParse->nMem;
addrReset = sqlite3VdbeMakeLabel(pParse);
iAMem = pParse->nMem + 1;
pParse->nMem += pGroupBy->nExpr;
iBMem = pParse->nMem + 1;
pParse->nMem += pGroupBy->nExpr;
sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
VdbeComment((v, "clear abort flag"));
sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
/* Begin a loop that will extract all source rows in GROUP BY order.
** This might involve two separate loops with an OP_Sort in between, or
** it might be a single loop that uses an index to extract information
** in the right order to begin with.
*/
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
);
if( pWInfo==0 ) goto select_end;
if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
/* The optimizer is able to deliver rows in group by order so
** we do not have to sort. The OP_OpenEphemeral table will be
** cancelled later because we still need to use the pKeyInfo
*/
groupBySort = 0;
}else{
/* Rows are coming out in undetermined order. We have to push
** each row into a sorting index, terminate the first loop,
** then loop over the sorting index in order to get the output
** in sorted order
*/
int regBase;
int regRecord;
int nCol;
int nGroupBy;
explainTempTable(pParse,
(sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
"DISTINCT" : "GROUP BY");
groupBySort = 1;
nGroupBy = pGroupBy->nExpr;
nCol = nGroupBy;
j = nGroupBy;
for(i=0; i<sAggInfo.nColumn; i++){
if( sAggInfo.aCol[i].iSorterColumn>=j ){
nCol++;
j++;
}
}
regBase = sqlite3GetTempRange(pParse, nCol);
sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
j = nGroupBy;
for(i=0; i<sAggInfo.nColumn; i++){
struct AggInfo_col *pCol = &sAggInfo.aCol[i];
if( pCol->iSorterColumn>=j ){
int r1 = j + regBase;
sqlite3ExprCodeGetColumnOfTable(v,
pCol->pTab, pCol->iTable, pCol->iColumn, r1);
j++;
}
}
regRecord = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
sqlite3ReleaseTempReg(pParse, regRecord);
sqlite3ReleaseTempRange(pParse, regBase, nCol);
sqlite3WhereEnd(pWInfo);
sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
sortOut = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
sAggInfo.useSortingIdx = 1;
}
/* If the index or temporary table used by the GROUP BY sort
** will naturally deliver rows in the order required by the ORDER BY
** clause, cancel the ephemeral table open coded earlier.
**
** This is an optimization - the correct answer should result regardless.
** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
** disable this optimization for testing purposes. */
if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
&& (groupBySort || sqlite3WhereIsSorted(pWInfo))
){
sSort.pOrderBy = 0;
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
}
/* Evaluate the current GROUP BY terms and store in b0, b1, b2...
** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
** Then compare the current GROUP BY terms against the GROUP BY terms
** from the previous row currently stored in a0, a1, a2...
*/
addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
if( groupBySort ){
sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
sortOut, sortPTab);
}
for(j=0; j<pGroupBy->nExpr; j++){
if( groupBySort ){
sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
}else{
sAggInfo.directMode = 1;
sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
}
}
sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
addr1 = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
/* Generate code that runs whenever the GROUP BY changes.
** Changes in the GROUP BY are detected by the previous code
** block. If there were no changes, this block is skipped.
**
** This code copies current group by terms in b0,b1,b2,...
** over to a0,a1,a2. It then calls the output subroutine
** and resets the aggregate accumulator registers in preparation
** for the next GROUP BY batch.
*/
sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
VdbeComment((v, "output one row"));
sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
VdbeComment((v, "check abort flag"));
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
VdbeComment((v, "reset accumulator"));
/* Update the aggregate accumulators based on the content of
** the current row
*/
sqlite3VdbeJumpHere(v, addr1);
updateAccumulator(pParse, iUseFlag, &sAggInfo);
sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
VdbeComment((v, "indicate data in accumulator"));
/* End of the loop
*/
if( groupBySort ){
sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
VdbeCoverage(v);
}else{
sqlite3WhereEnd(pWInfo);
sqlite3VdbeChangeToNoop(v, addrSortingIdx);
}
/* Output the final row of result
*/
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
VdbeComment((v, "output final row"));
/* Jump over the subroutines
*/
sqlite3VdbeGoto(v, addrEnd);
/* Generate a subroutine that outputs a single row of the result
** set. This subroutine first looks at the iUseFlag. If iUseFlag
** is less than or equal to zero, the subroutine is a no-op. If
** the processing calls for the query to abort, this subroutine
** increments the iAbortFlag memory location before returning in
** order to signal the caller to abort.
*/
addrSetAbort = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
VdbeComment((v, "set abort flag"));
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
sqlite3VdbeResolveLabel(v, addrOutputRow);
addrOutputRow = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
VdbeCoverage(v);
VdbeComment((v, "Groupby result generator entry point"));
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
finalizeAggFunctions(pParse, &sAggInfo);
sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
selectInnerLoop(pParse, p, -1, &sSort,
&sDistinct, pDest,
addrOutputRow+1, addrSetAbort);
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
VdbeComment((v, "end groupby result generator"));
/* Generate a subroutine that will reset the group-by accumulator
*/
sqlite3VdbeResolveLabel(v, addrReset);
resetAccumulator(pParse, &sAggInfo);
sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
VdbeComment((v, "indicate accumulator empty"));
sqlite3VdbeAddOp1(v, OP_Return, regReset);
} /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
else {
#ifndef SQLITE_OMIT_BTREECOUNT
Table *pTab;
if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
/* If isSimpleCount() returns a pointer to a Table structure, then
** the SQL statement is of the form:
**
** SELECT count(*) FROM <tbl>
**
** where the Table structure returned represents table <tbl>.
**
** This statement is so common that it is optimized specially. The
** OP_Count instruction is executed either on the intkey table that
** contains the data for table <tbl> or on one of its indexes. It
** is better to execute the op on an index, as indexes are almost
** always spread across less pages than their corresponding tables.
*/
const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
Index *pIdx; /* Iterator variable */
KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
Index *pBest = 0; /* Best index found so far */
int iRoot = pTab->tnum; /* Root page of scanned b-tree */
sqlite3CodeVerifySchema(pParse, iDb);
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
/* Search for the index that has the lowest scan cost.
**
** (2011-04-15) Do not do a full scan of an unordered index.
**
** (2013-10-03) Do not count the entries in a partial index.
**
** In practice the KeyInfo structure will not be used. It is only
** passed to keep OP_OpenRead happy.
*/
if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
if( pIdx->bUnordered==0
&& pIdx->szIdxRow<pTab->szTabRow
&& pIdx->pPartIdxWhere==0
&& (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
){
pBest = pIdx;
}
}
if( pBest ){
iRoot = pBest->tnum;
pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
}
/* Open a read-only cursor, execute the OP_Count, close the cursor. */
sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
if( pKeyInfo ){
sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
}
sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
sqlite3VdbeAddOp1(v, OP_Close, iCsr);
explainSimpleCount(pParse, pTab, pBest);
}else
#endif /* SQLITE_OMIT_BTREECOUNT */
{
int regAcc = 0; /* "populate accumulators" flag */
/* If there are accumulator registers but no min() or max() functions
** without FILTER clauses, allocate register regAcc. Register regAcc
** will contain 0 the first time the inner loop runs, and 1 thereafter.
** The code generated by updateAccumulator() uses this to ensure
** that the accumulator registers are (a) updated only once if
** there are no min() or max functions or (b) always updated for the
** first row visited by the aggregate, so that they are updated at
** least once even if the FILTER clause means the min() or max()
** function visits zero rows. */
if( sAggInfo.nAccumulator ){
for(i=0; i<sAggInfo.nFunc; i++){
if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue;
if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
}
if( i==sAggInfo.nFunc ){
regAcc = ++pParse->nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
}
}
/* This case runs if the aggregate has no GROUP BY clause. The
** processing is much simpler since there is only a single row
** of output.
*/
assert( p->pGroupBy==0 );
resetAccumulator(pParse, &sAggInfo);
/* If this query is a candidate for the min/max optimization, then
** minMaxFlag will have been previously set to either
** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
** be an appropriate ORDER BY expression for the optimization.
*/
assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
SELECTTRACE(1,pParse,p,("WhereBegin\n"));
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
0, minMaxFlag, 0);
if( pWInfo==0 ){
goto select_end;
}
updateAccumulator(pParse, regAcc, &sAggInfo);
if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
if( sqlite3WhereIsOrdered(pWInfo)>0 ){
sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
VdbeComment((v, "%s() by index",
(minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
}
sqlite3WhereEnd(pWInfo);
finalizeAggFunctions(pParse, &sAggInfo);
}
sSort.pOrderBy = 0;
sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
selectInnerLoop(pParse, p, -1, 0, 0,
pDest, addrEnd, addrEnd);
}
sqlite3VdbeResolveLabel(v, addrEnd);
} /* endif aggregate query */
if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
explainTempTable(pParse, "DISTINCT");
}
/* If there is an ORDER BY clause, then we need to sort the results
** and send them to the callback one by one.
*/
if( sSort.pOrderBy ){
explainTempTable(pParse,
sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
assert( p->pEList==pEList );
generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
}
/* Jump here to skip this query
*/
sqlite3VdbeResolveLabel(v, iEnd);
/* The SELECT has been coded. If there is an error in the Parse structure,
** set the return code to 1. Otherwise 0. */
rc = (pParse->nErr>0);
/* Control jumps to here if an error is encountered above, or upon
** successful coding of the SELECT.
*/
select_end:
sqlite3ExprListDelete(db, pMinMaxOrderBy);
sqlite3DbFree(db, sAggInfo.aCol);
sqlite3DbFree(db, sAggInfo.aFunc);
#if SELECTTRACE_ENABLED
SELECTTRACE(0x1,pParse,p,("end processing\n"));
if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
sqlite3TreeViewSelect(0, p, 0);
}
#endif
ExplainQueryPlanPop(pParse);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-755/c/bad_1352_2 |
crossvul-cpp_data_bad_4766_0 | /* $OpenBSD: authfile.c,v 1.121 2016/04/09 12:39:30 djm Exp $ */
/*
* Copyright (c) 2000, 2013 Markus Friedl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include "cipher.h"
#include "ssh.h"
#include "log.h"
#include "authfile.h"
#include "rsa.h"
#include "misc.h"
#include "atomicio.h"
#include "sshkey.h"
#include "sshbuf.h"
#include "ssherr.h"
#include "krl.h"
#define MAX_KEY_FILE_SIZE (1024 * 1024)
/* Save a key blob to a file */
static int
sshkey_save_private_blob(struct sshbuf *keybuf, const char *filename)
{
int fd, oerrno;
if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0)
return SSH_ERR_SYSTEM_ERROR;
if (atomicio(vwrite, fd, (u_char *)sshbuf_ptr(keybuf),
sshbuf_len(keybuf)) != sshbuf_len(keybuf)) {
oerrno = errno;
close(fd);
unlink(filename);
errno = oerrno;
return SSH_ERR_SYSTEM_ERROR;
}
close(fd);
return 0;
}
int
sshkey_save_private(struct sshkey *key, const char *filename,
const char *passphrase, const char *comment,
int force_new_format, const char *new_format_cipher, int new_format_rounds)
{
struct sshbuf *keyblob = NULL;
int r;
if ((keyblob = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_private_to_fileblob(key, keyblob, passphrase, comment,
force_new_format, new_format_cipher, new_format_rounds)) != 0)
goto out;
if ((r = sshkey_save_private_blob(keyblob, filename)) != 0)
goto out;
r = 0;
out:
sshbuf_free(keyblob);
return r;
}
/* Load a key from a fd into a buffer */
int
sshkey_load_file(int fd, struct sshbuf *blob)
{
u_char buf[1024];
size_t len;
struct stat st;
int r;
if (fstat(fd, &st) < 0)
return SSH_ERR_SYSTEM_ERROR;
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size > MAX_KEY_FILE_SIZE)
return SSH_ERR_INVALID_FORMAT;
for (;;) {
if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
if (errno == EPIPE)
break;
r = SSH_ERR_SYSTEM_ERROR;
goto out;
}
if ((r = sshbuf_put(blob, buf, len)) != 0)
goto out;
if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
}
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size != (off_t)sshbuf_len(blob)) {
r = SSH_ERR_FILE_CHANGED;
goto out;
}
r = 0;
out:
explicit_bzero(buf, sizeof(buf));
if (r != 0)
sshbuf_reset(blob);
return r;
}
#ifdef WITH_SSH1
/*
* Loads the public part of the ssh v1 key file. Returns NULL if an error was
* encountered (the file does not exist or is not readable), and the key
* otherwise.
*/
static int
sshkey_load_public_rsa1(int fd, struct sshkey **keyp, char **commentp)
{
struct sshbuf *b = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_load_file(fd, b)) != 0)
goto out;
if ((r = sshkey_parse_public_rsa1_fileblob(b, keyp, commentp)) != 0)
goto out;
r = 0;
out:
sshbuf_free(b);
return r;
}
#endif /* WITH_SSH1 */
/* XXX remove error() calls from here? */
int
sshkey_perm_ok(int fd, const char *filename)
{
struct stat st;
if (fstat(fd, &st) < 0)
return SSH_ERR_SYSTEM_ERROR;
/*
* if a key owned by the user is accessed, then we check the
* permissions of the file. if the key owned by a different user,
* then we don't care.
*/
if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
error("Permissions 0%3.3o for '%s' are too open.",
(u_int)st.st_mode & 0777, filename);
error("It is required that your private key files are NOT accessible by others.");
error("This private key will be ignored.");
return SSH_ERR_KEY_BAD_PERMISSIONS;
}
return 0;
}
/* XXX kill perm_ok now that we have SSH_ERR_KEY_BAD_PERMISSIONS? */
int
sshkey_load_private_type(int type, const char *filename, const char *passphrase,
struct sshkey **keyp, char **commentp, int *perm_ok)
{
int fd, r;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
if ((fd = open(filename, O_RDONLY)) < 0) {
if (perm_ok != NULL)
*perm_ok = 0;
return SSH_ERR_SYSTEM_ERROR;
}
if (sshkey_perm_ok(fd, filename) != 0) {
if (perm_ok != NULL)
*perm_ok = 0;
r = SSH_ERR_KEY_BAD_PERMISSIONS;
goto out;
}
if (perm_ok != NULL)
*perm_ok = 1;
r = sshkey_load_private_type_fd(fd, type, passphrase, keyp, commentp);
out:
close(fd);
return r;
}
int
sshkey_load_private_type_fd(int fd, int type, const char *passphrase,
struct sshkey **keyp, char **commentp)
{
struct sshbuf *buffer = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
if ((buffer = sshbuf_new()) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_load_file(fd, buffer)) != 0 ||
(r = sshkey_parse_private_fileblob_type(buffer, type,
passphrase, keyp, commentp)) != 0)
goto out;
/* success */
r = 0;
out:
sshbuf_free(buffer);
return r;
}
/* XXX this is almost identical to sshkey_load_private_type() */
int
sshkey_load_private(const char *filename, const char *passphrase,
struct sshkey **keyp, char **commentp)
{
struct sshbuf *buffer = NULL;
int r, fd;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
if ((fd = open(filename, O_RDONLY)) < 0)
return SSH_ERR_SYSTEM_ERROR;
if (sshkey_perm_ok(fd, filename) != 0) {
r = SSH_ERR_KEY_BAD_PERMISSIONS;
goto out;
}
if ((buffer = sshbuf_new()) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_load_file(fd, buffer)) != 0 ||
(r = sshkey_parse_private_fileblob(buffer, passphrase, keyp,
commentp)) != 0)
goto out;
r = 0;
out:
close(fd);
sshbuf_free(buffer);
return r;
}
static int
sshkey_try_load_public(struct sshkey *k, const char *filename, char **commentp)
{
FILE *f;
char line[SSH_MAX_PUBKEY_BYTES];
char *cp;
u_long linenum = 0;
int r;
if (commentp != NULL)
*commentp = NULL;
if ((f = fopen(filename, "r")) == NULL)
return SSH_ERR_SYSTEM_ERROR;
while (read_keyfile_line(f, filename, line, sizeof(line),
&linenum) != -1) {
cp = line;
switch (*cp) {
case '#':
case '\n':
case '\0':
continue;
}
/* Abort loading if this looks like a private key */
if (strncmp(cp, "-----BEGIN", 10) == 0 ||
strcmp(cp, "SSH PRIVATE KEY FILE") == 0)
break;
/* Skip leading whitespace. */
for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
;
if (*cp) {
if ((r = sshkey_read(k, &cp)) == 0) {
cp[strcspn(cp, "\r\n")] = '\0';
if (commentp) {
*commentp = strdup(*cp ?
cp : filename);
if (*commentp == NULL)
r = SSH_ERR_ALLOC_FAIL;
}
fclose(f);
return r;
}
}
}
fclose(f);
return SSH_ERR_INVALID_FORMAT;
}
/* load public key from ssh v1 private or any pubkey file */
int
sshkey_load_public(const char *filename, struct sshkey **keyp, char **commentp)
{
struct sshkey *pub = NULL;
char file[PATH_MAX];
int r, fd;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
/* XXX should load file once and attempt to parse each format */
if ((fd = open(filename, O_RDONLY)) < 0)
goto skip;
#ifdef WITH_SSH1
/* try rsa1 private key */
r = sshkey_load_public_rsa1(fd, keyp, commentp);
close(fd);
switch (r) {
case SSH_ERR_INTERNAL_ERROR:
case SSH_ERR_ALLOC_FAIL:
case SSH_ERR_INVALID_ARGUMENT:
case SSH_ERR_SYSTEM_ERROR:
case 0:
return r;
}
#else /* WITH_SSH1 */
close(fd);
#endif /* WITH_SSH1 */
/* try ssh2 public key */
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_try_load_public(pub, filename, commentp)) == 0) {
if (keyp != NULL)
*keyp = pub;
return 0;
}
sshkey_free(pub);
#ifdef WITH_SSH1
/* try rsa1 public key */
if ((pub = sshkey_new(KEY_RSA1)) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_try_load_public(pub, filename, commentp)) == 0) {
if (keyp != NULL)
*keyp = pub;
return 0;
}
sshkey_free(pub);
#endif /* WITH_SSH1 */
skip:
/* try .pub suffix */
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL)
return SSH_ERR_ALLOC_FAIL;
r = SSH_ERR_ALLOC_FAIL; /* in case strlcpy or strlcat fail */
if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
(strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
(r = sshkey_try_load_public(pub, file, commentp)) == 0) {
if (keyp != NULL)
*keyp = pub;
return 0;
}
sshkey_free(pub);
return r;
}
/* Load the certificate associated with the named private key */
int
sshkey_load_cert(const char *filename, struct sshkey **keyp)
{
struct sshkey *pub = NULL;
char *file = NULL;
int r = SSH_ERR_INTERNAL_ERROR;
if (keyp != NULL)
*keyp = NULL;
if (asprintf(&file, "%s-cert.pub", filename) == -1)
return SSH_ERR_ALLOC_FAIL;
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
goto out;
}
if ((r = sshkey_try_load_public(pub, file, NULL)) != 0)
goto out;
/* success */
if (keyp != NULL) {
*keyp = pub;
pub = NULL;
}
r = 0;
out:
free(file);
sshkey_free(pub);
return r;
}
/* Load private key and certificate */
int
sshkey_load_private_cert(int type, const char *filename, const char *passphrase,
struct sshkey **keyp, int *perm_ok)
{
struct sshkey *key = NULL, *cert = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
switch (type) {
#ifdef WITH_OPENSSL
case KEY_RSA:
case KEY_DSA:
case KEY_ECDSA:
#endif /* WITH_OPENSSL */
case KEY_ED25519:
case KEY_UNSPEC:
break;
default:
return SSH_ERR_KEY_TYPE_UNKNOWN;
}
if ((r = sshkey_load_private_type(type, filename,
passphrase, &key, NULL, perm_ok)) != 0 ||
(r = sshkey_load_cert(filename, &cert)) != 0)
goto out;
/* Make sure the private key matches the certificate */
if (sshkey_equal_public(key, cert) == 0) {
r = SSH_ERR_KEY_CERT_MISMATCH;
goto out;
}
if ((r = sshkey_to_certified(key)) != 0 ||
(r = sshkey_cert_copy(cert, key)) != 0)
goto out;
r = 0;
if (keyp != NULL) {
*keyp = key;
key = NULL;
}
out:
sshkey_free(key);
sshkey_free(cert);
return r;
}
/*
* Returns success if the specified "key" is listed in the file "filename",
* SSH_ERR_KEY_NOT_FOUND: if the key is not listed or another error.
* If "strict_type" is set then the key type must match exactly,
* otherwise a comparison that ignores certficiate data is performed.
* If "check_ca" is set and "key" is a certificate, then its CA key is
* also checked and sshkey_in_file() will return success if either is found.
*/
int
sshkey_in_file(struct sshkey *key, const char *filename, int strict_type,
int check_ca)
{
FILE *f;
char line[SSH_MAX_PUBKEY_BYTES];
char *cp;
u_long linenum = 0;
int r = 0;
struct sshkey *pub = NULL;
int (*sshkey_compare)(const struct sshkey *, const struct sshkey *) =
strict_type ? sshkey_equal : sshkey_equal_public;
if ((f = fopen(filename, "r")) == NULL)
return SSH_ERR_SYSTEM_ERROR;
while (read_keyfile_line(f, filename, line, sizeof(line),
&linenum) != -1) {
cp = line;
/* Skip leading whitespace. */
for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
;
/* Skip comments and empty lines */
switch (*cp) {
case '#':
case '\n':
case '\0':
continue;
}
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_read(pub, &cp)) != 0)
goto out;
if (sshkey_compare(key, pub) ||
(check_ca && sshkey_is_cert(key) &&
sshkey_compare(key->cert->signature_key, pub))) {
r = 0;
goto out;
}
sshkey_free(pub);
pub = NULL;
}
r = SSH_ERR_KEY_NOT_FOUND;
out:
sshkey_free(pub);
fclose(f);
return r;
}
/*
* Checks whether the specified key is revoked, returning 0 if not,
* SSH_ERR_KEY_REVOKED if it is or another error code if something
* unexpected happened.
* This will check both the key and, if it is a certificate, its CA key too.
* "revoked_keys_file" may be a KRL or a one-per-line list of public keys.
*/
int
sshkey_check_revoked(struct sshkey *key, const char *revoked_keys_file)
{
int r;
r = ssh_krl_file_contains_key(revoked_keys_file, key);
/* If this was not a KRL to begin with then continue below */
if (r != SSH_ERR_KRL_BAD_MAGIC)
return r;
/*
* If the file is not a KRL or we can't handle KRLs then attempt to
* parse the file as a flat list of keys.
*/
switch ((r = sshkey_in_file(key, revoked_keys_file, 0, 1))) {
case 0:
/* Key found => revoked */
return SSH_ERR_KEY_REVOKED;
case SSH_ERR_KEY_NOT_FOUND:
/* Key not found => not revoked */
return 0;
default:
/* Some other error occurred */
return r;
}
}
| ./CrossVul/dataset_final_sorted/CWE-320/c/bad_4766_0 |
crossvul-cpp_data_good_4766_0 | /* $OpenBSD: authfile.c,v 1.122 2016/11/25 23:24:45 djm Exp $ */
/*
* Copyright (c) 2000, 2013 Markus Friedl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include "cipher.h"
#include "ssh.h"
#include "log.h"
#include "authfile.h"
#include "rsa.h"
#include "misc.h"
#include "atomicio.h"
#include "sshkey.h"
#include "sshbuf.h"
#include "ssherr.h"
#include "krl.h"
#define MAX_KEY_FILE_SIZE (1024 * 1024)
/* Save a key blob to a file */
static int
sshkey_save_private_blob(struct sshbuf *keybuf, const char *filename)
{
int fd, oerrno;
if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0)
return SSH_ERR_SYSTEM_ERROR;
if (atomicio(vwrite, fd, (u_char *)sshbuf_ptr(keybuf),
sshbuf_len(keybuf)) != sshbuf_len(keybuf)) {
oerrno = errno;
close(fd);
unlink(filename);
errno = oerrno;
return SSH_ERR_SYSTEM_ERROR;
}
close(fd);
return 0;
}
int
sshkey_save_private(struct sshkey *key, const char *filename,
const char *passphrase, const char *comment,
int force_new_format, const char *new_format_cipher, int new_format_rounds)
{
struct sshbuf *keyblob = NULL;
int r;
if ((keyblob = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_private_to_fileblob(key, keyblob, passphrase, comment,
force_new_format, new_format_cipher, new_format_rounds)) != 0)
goto out;
if ((r = sshkey_save_private_blob(keyblob, filename)) != 0)
goto out;
r = 0;
out:
sshbuf_free(keyblob);
return r;
}
/* Load a key from a fd into a buffer */
int
sshkey_load_file(int fd, struct sshbuf *blob)
{
u_char buf[1024];
size_t len;
struct stat st;
int r, dontmax = 0;
if (fstat(fd, &st) < 0)
return SSH_ERR_SYSTEM_ERROR;
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size > MAX_KEY_FILE_SIZE)
return SSH_ERR_INVALID_FORMAT;
/*
* Pre-allocate the buffer used for the key contents and clamp its
* maximum size. This ensures that key contents are never leaked via
* implicit realloc() in the sshbuf code.
*/
if ((st.st_mode & S_IFREG) == 0 || st.st_size <= 0) {
st.st_size = 64*1024; /* 64k should be enough for anyone :) */
dontmax = 1;
}
if ((r = sshbuf_allocate(blob, st.st_size)) != 0 ||
(dontmax && (r = sshbuf_set_max_size(blob, st.st_size)) != 0))
return r;
for (;;) {
if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
if (errno == EPIPE)
break;
r = SSH_ERR_SYSTEM_ERROR;
goto out;
}
if ((r = sshbuf_put(blob, buf, len)) != 0)
goto out;
if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
}
if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
st.st_size != (off_t)sshbuf_len(blob)) {
r = SSH_ERR_FILE_CHANGED;
goto out;
}
r = 0;
out:
explicit_bzero(buf, sizeof(buf));
if (r != 0)
sshbuf_reset(blob);
return r;
}
#ifdef WITH_SSH1
/*
* Loads the public part of the ssh v1 key file. Returns NULL if an error was
* encountered (the file does not exist or is not readable), and the key
* otherwise.
*/
static int
sshkey_load_public_rsa1(int fd, struct sshkey **keyp, char **commentp)
{
struct sshbuf *b = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_load_file(fd, b)) != 0)
goto out;
if ((r = sshkey_parse_public_rsa1_fileblob(b, keyp, commentp)) != 0)
goto out;
r = 0;
out:
sshbuf_free(b);
return r;
}
#endif /* WITH_SSH1 */
/* XXX remove error() calls from here? */
int
sshkey_perm_ok(int fd, const char *filename)
{
struct stat st;
if (fstat(fd, &st) < 0)
return SSH_ERR_SYSTEM_ERROR;
/*
* if a key owned by the user is accessed, then we check the
* permissions of the file. if the key owned by a different user,
* then we don't care.
*/
if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
error("Permissions 0%3.3o for '%s' are too open.",
(u_int)st.st_mode & 0777, filename);
error("It is required that your private key files are NOT accessible by others.");
error("This private key will be ignored.");
return SSH_ERR_KEY_BAD_PERMISSIONS;
}
return 0;
}
/* XXX kill perm_ok now that we have SSH_ERR_KEY_BAD_PERMISSIONS? */
int
sshkey_load_private_type(int type, const char *filename, const char *passphrase,
struct sshkey **keyp, char **commentp, int *perm_ok)
{
int fd, r;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
if ((fd = open(filename, O_RDONLY)) < 0) {
if (perm_ok != NULL)
*perm_ok = 0;
return SSH_ERR_SYSTEM_ERROR;
}
if (sshkey_perm_ok(fd, filename) != 0) {
if (perm_ok != NULL)
*perm_ok = 0;
r = SSH_ERR_KEY_BAD_PERMISSIONS;
goto out;
}
if (perm_ok != NULL)
*perm_ok = 1;
r = sshkey_load_private_type_fd(fd, type, passphrase, keyp, commentp);
out:
close(fd);
return r;
}
int
sshkey_load_private_type_fd(int fd, int type, const char *passphrase,
struct sshkey **keyp, char **commentp)
{
struct sshbuf *buffer = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
if ((buffer = sshbuf_new()) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_load_file(fd, buffer)) != 0 ||
(r = sshkey_parse_private_fileblob_type(buffer, type,
passphrase, keyp, commentp)) != 0)
goto out;
/* success */
r = 0;
out:
sshbuf_free(buffer);
return r;
}
/* XXX this is almost identical to sshkey_load_private_type() */
int
sshkey_load_private(const char *filename, const char *passphrase,
struct sshkey **keyp, char **commentp)
{
struct sshbuf *buffer = NULL;
int r, fd;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
if ((fd = open(filename, O_RDONLY)) < 0)
return SSH_ERR_SYSTEM_ERROR;
if (sshkey_perm_ok(fd, filename) != 0) {
r = SSH_ERR_KEY_BAD_PERMISSIONS;
goto out;
}
if ((buffer = sshbuf_new()) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_load_file(fd, buffer)) != 0 ||
(r = sshkey_parse_private_fileblob(buffer, passphrase, keyp,
commentp)) != 0)
goto out;
r = 0;
out:
close(fd);
sshbuf_free(buffer);
return r;
}
static int
sshkey_try_load_public(struct sshkey *k, const char *filename, char **commentp)
{
FILE *f;
char line[SSH_MAX_PUBKEY_BYTES];
char *cp;
u_long linenum = 0;
int r;
if (commentp != NULL)
*commentp = NULL;
if ((f = fopen(filename, "r")) == NULL)
return SSH_ERR_SYSTEM_ERROR;
while (read_keyfile_line(f, filename, line, sizeof(line),
&linenum) != -1) {
cp = line;
switch (*cp) {
case '#':
case '\n':
case '\0':
continue;
}
/* Abort loading if this looks like a private key */
if (strncmp(cp, "-----BEGIN", 10) == 0 ||
strcmp(cp, "SSH PRIVATE KEY FILE") == 0)
break;
/* Skip leading whitespace. */
for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
;
if (*cp) {
if ((r = sshkey_read(k, &cp)) == 0) {
cp[strcspn(cp, "\r\n")] = '\0';
if (commentp) {
*commentp = strdup(*cp ?
cp : filename);
if (*commentp == NULL)
r = SSH_ERR_ALLOC_FAIL;
}
fclose(f);
return r;
}
}
}
fclose(f);
return SSH_ERR_INVALID_FORMAT;
}
/* load public key from ssh v1 private or any pubkey file */
int
sshkey_load_public(const char *filename, struct sshkey **keyp, char **commentp)
{
struct sshkey *pub = NULL;
char file[PATH_MAX];
int r, fd;
if (keyp != NULL)
*keyp = NULL;
if (commentp != NULL)
*commentp = NULL;
/* XXX should load file once and attempt to parse each format */
if ((fd = open(filename, O_RDONLY)) < 0)
goto skip;
#ifdef WITH_SSH1
/* try rsa1 private key */
r = sshkey_load_public_rsa1(fd, keyp, commentp);
close(fd);
switch (r) {
case SSH_ERR_INTERNAL_ERROR:
case SSH_ERR_ALLOC_FAIL:
case SSH_ERR_INVALID_ARGUMENT:
case SSH_ERR_SYSTEM_ERROR:
case 0:
return r;
}
#else /* WITH_SSH1 */
close(fd);
#endif /* WITH_SSH1 */
/* try ssh2 public key */
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_try_load_public(pub, filename, commentp)) == 0) {
if (keyp != NULL)
*keyp = pub;
return 0;
}
sshkey_free(pub);
#ifdef WITH_SSH1
/* try rsa1 public key */
if ((pub = sshkey_new(KEY_RSA1)) == NULL)
return SSH_ERR_ALLOC_FAIL;
if ((r = sshkey_try_load_public(pub, filename, commentp)) == 0) {
if (keyp != NULL)
*keyp = pub;
return 0;
}
sshkey_free(pub);
#endif /* WITH_SSH1 */
skip:
/* try .pub suffix */
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL)
return SSH_ERR_ALLOC_FAIL;
r = SSH_ERR_ALLOC_FAIL; /* in case strlcpy or strlcat fail */
if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
(strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
(r = sshkey_try_load_public(pub, file, commentp)) == 0) {
if (keyp != NULL)
*keyp = pub;
return 0;
}
sshkey_free(pub);
return r;
}
/* Load the certificate associated with the named private key */
int
sshkey_load_cert(const char *filename, struct sshkey **keyp)
{
struct sshkey *pub = NULL;
char *file = NULL;
int r = SSH_ERR_INTERNAL_ERROR;
if (keyp != NULL)
*keyp = NULL;
if (asprintf(&file, "%s-cert.pub", filename) == -1)
return SSH_ERR_ALLOC_FAIL;
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
goto out;
}
if ((r = sshkey_try_load_public(pub, file, NULL)) != 0)
goto out;
/* success */
if (keyp != NULL) {
*keyp = pub;
pub = NULL;
}
r = 0;
out:
free(file);
sshkey_free(pub);
return r;
}
/* Load private key and certificate */
int
sshkey_load_private_cert(int type, const char *filename, const char *passphrase,
struct sshkey **keyp, int *perm_ok)
{
struct sshkey *key = NULL, *cert = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
switch (type) {
#ifdef WITH_OPENSSL
case KEY_RSA:
case KEY_DSA:
case KEY_ECDSA:
#endif /* WITH_OPENSSL */
case KEY_ED25519:
case KEY_UNSPEC:
break;
default:
return SSH_ERR_KEY_TYPE_UNKNOWN;
}
if ((r = sshkey_load_private_type(type, filename,
passphrase, &key, NULL, perm_ok)) != 0 ||
(r = sshkey_load_cert(filename, &cert)) != 0)
goto out;
/* Make sure the private key matches the certificate */
if (sshkey_equal_public(key, cert) == 0) {
r = SSH_ERR_KEY_CERT_MISMATCH;
goto out;
}
if ((r = sshkey_to_certified(key)) != 0 ||
(r = sshkey_cert_copy(cert, key)) != 0)
goto out;
r = 0;
if (keyp != NULL) {
*keyp = key;
key = NULL;
}
out:
sshkey_free(key);
sshkey_free(cert);
return r;
}
/*
* Returns success if the specified "key" is listed in the file "filename",
* SSH_ERR_KEY_NOT_FOUND: if the key is not listed or another error.
* If "strict_type" is set then the key type must match exactly,
* otherwise a comparison that ignores certficiate data is performed.
* If "check_ca" is set and "key" is a certificate, then its CA key is
* also checked and sshkey_in_file() will return success if either is found.
*/
int
sshkey_in_file(struct sshkey *key, const char *filename, int strict_type,
int check_ca)
{
FILE *f;
char line[SSH_MAX_PUBKEY_BYTES];
char *cp;
u_long linenum = 0;
int r = 0;
struct sshkey *pub = NULL;
int (*sshkey_compare)(const struct sshkey *, const struct sshkey *) =
strict_type ? sshkey_equal : sshkey_equal_public;
if ((f = fopen(filename, "r")) == NULL)
return SSH_ERR_SYSTEM_ERROR;
while (read_keyfile_line(f, filename, line, sizeof(line),
&linenum) != -1) {
cp = line;
/* Skip leading whitespace. */
for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
;
/* Skip comments and empty lines */
switch (*cp) {
case '#':
case '\n':
case '\0':
continue;
}
if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_read(pub, &cp)) != 0)
goto out;
if (sshkey_compare(key, pub) ||
(check_ca && sshkey_is_cert(key) &&
sshkey_compare(key->cert->signature_key, pub))) {
r = 0;
goto out;
}
sshkey_free(pub);
pub = NULL;
}
r = SSH_ERR_KEY_NOT_FOUND;
out:
sshkey_free(pub);
fclose(f);
return r;
}
/*
* Checks whether the specified key is revoked, returning 0 if not,
* SSH_ERR_KEY_REVOKED if it is or another error code if something
* unexpected happened.
* This will check both the key and, if it is a certificate, its CA key too.
* "revoked_keys_file" may be a KRL or a one-per-line list of public keys.
*/
int
sshkey_check_revoked(struct sshkey *key, const char *revoked_keys_file)
{
int r;
r = ssh_krl_file_contains_key(revoked_keys_file, key);
/* If this was not a KRL to begin with then continue below */
if (r != SSH_ERR_KRL_BAD_MAGIC)
return r;
/*
* If the file is not a KRL or we can't handle KRLs then attempt to
* parse the file as a flat list of keys.
*/
switch ((r = sshkey_in_file(key, revoked_keys_file, 0, 1))) {
case 0:
/* Key found => revoked */
return SSH_ERR_KEY_REVOKED;
case SSH_ERR_KEY_NOT_FOUND:
/* Key not found => not revoked */
return 0;
default:
/* Some other error occurred */
return r;
}
}
| ./CrossVul/dataset_final_sorted/CWE-320/c/good_4766_0 |
crossvul-cpp_data_good_857_0 | /*
* Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Portions Copyright (c) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "krb5_locl.h"
#ifndef WIN32
#include <heim-ipc.h>
#endif /* WIN32 */
typedef struct krb5_get_init_creds_ctx {
KDCOptions flags;
krb5_creds cred;
krb5_addresses *addrs;
krb5_enctype *etypes;
krb5_preauthtype *pre_auth_types;
char *in_tkt_service;
unsigned nonce;
unsigned pk_nonce;
krb5_data req_buffer;
AS_REQ as_req;
int pa_counter;
/* password and keytab_data is freed on completion */
char *password;
krb5_keytab_key_proc_args *keytab_data;
krb5_pointer *keyseed;
krb5_s2k_proc keyproc;
krb5_get_init_creds_tristate req_pac;
krb5_pk_init_ctx pk_init_ctx;
int ic_flags;
struct {
unsigned change_password:1;
} runflags;
int used_pa_types;
#define USED_PKINIT 1
#define USED_PKINIT_W2K 2
#define USED_ENC_TS_GUESS 4
#define USED_ENC_TS_INFO 8
METHOD_DATA md;
KRB_ERROR error;
AS_REP as_rep;
EncKDCRepPart enc_part;
krb5_prompter_fct prompter;
void *prompter_data;
struct pa_info_data *ppaid;
struct fast_state {
enum PA_FX_FAST_REQUEST_enum type;
unsigned int flags;
#define KRB5_FAST_REPLY_KEY_USE_TO_ENCRYPT_THE_REPLY 1
#define KRB5_FAST_REPLY_KEY_USE_IN_TRANSACTION 2
#define KRB5_FAST_KDC_REPLY_KEY_REPLACED 4
#define KRB5_FAST_REPLY_REPLY_VERIFED 8
#define KRB5_FAST_STRONG 16
#define KRB5_FAST_EXPECTED 32 /* in exchange with KDC, fast was discovered */
#define KRB5_FAST_REQUIRED 64 /* fast required by action of caller */
#define KRB5_FAST_DISABLED 128
#define KRB5_FAST_AP_ARMOR_SERVICE 256
krb5_keyblock *reply_key;
krb5_ccache armor_ccache;
krb5_principal armor_service;
krb5_crypto armor_crypto;
krb5_keyblock armor_key;
krb5_keyblock *strengthen_key;
} fast_state;
} krb5_get_init_creds_ctx;
struct pa_info_data {
krb5_enctype etype;
krb5_salt salt;
krb5_data *s2kparams;
};
static void
free_paid(krb5_context context, struct pa_info_data *ppaid)
{
krb5_free_salt(context, ppaid->salt);
if (ppaid->s2kparams)
krb5_free_data(context, ppaid->s2kparams);
}
static krb5_error_code KRB5_CALLCONV
default_s2k_func(krb5_context context, krb5_enctype type,
krb5_const_pointer keyseed,
krb5_salt salt, krb5_data *s2kparms,
krb5_keyblock **key)
{
krb5_error_code ret;
krb5_data password;
krb5_data opaque;
_krb5_debug(context, 5, "krb5_get_init_creds: using default_s2k_func");
password.data = rk_UNCONST(keyseed);
password.length = strlen(keyseed);
if (s2kparms)
opaque = *s2kparms;
else
krb5_data_zero(&opaque);
*key = malloc(sizeof(**key));
if (*key == NULL)
return ENOMEM;
ret = krb5_string_to_key_data_salt_opaque(context, type, password,
salt, opaque, *key);
if (ret) {
free(*key);
*key = NULL;
}
return ret;
}
static void
free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx)
{
if (ctx->etypes)
free(ctx->etypes);
if (ctx->pre_auth_types)
free (ctx->pre_auth_types);
if (ctx->in_tkt_service)
free(ctx->in_tkt_service);
if (ctx->keytab_data)
free(ctx->keytab_data);
if (ctx->password) {
memset(ctx->password, 0, strlen(ctx->password));
free(ctx->password);
}
/*
* FAST state (we don't close the armor_ccache because we might have
* to destroy it, and how would we know? also, the caller should
* take care of cleaning up the armor_ccache).
*/
if (ctx->fast_state.armor_service)
krb5_free_principal(context, ctx->fast_state.armor_service);
if (ctx->fast_state.armor_crypto)
krb5_crypto_destroy(context, ctx->fast_state.armor_crypto);
if (ctx->fast_state.strengthen_key)
krb5_free_keyblock(context, ctx->fast_state.strengthen_key);
krb5_free_keyblock_contents(context, &ctx->fast_state.armor_key);
krb5_data_free(&ctx->req_buffer);
krb5_free_cred_contents(context, &ctx->cred);
free_METHOD_DATA(&ctx->md);
free_AS_REP(&ctx->as_rep);
free_EncKDCRepPart(&ctx->enc_part);
free_KRB_ERROR(&ctx->error);
free_AS_REQ(&ctx->as_req);
if (ctx->ppaid) {
free_paid(context, ctx->ppaid);
free(ctx->ppaid);
}
memset(ctx, 0, sizeof(*ctx));
}
static int
get_config_time (krb5_context context,
const char *realm,
const char *name,
int def)
{
int ret;
ret = krb5_config_get_time (context, NULL,
"realms",
realm,
name,
NULL);
if (ret >= 0)
return ret;
ret = krb5_config_get_time (context, NULL,
"libdefaults",
name,
NULL);
if (ret >= 0)
return ret;
return def;
}
static krb5_error_code
init_cred (krb5_context context,
krb5_creds *cred,
krb5_principal client,
krb5_deltat start_time,
krb5_get_init_creds_opt *options)
{
krb5_error_code ret;
int tmp;
krb5_timestamp now;
krb5_timeofday (context, &now);
memset (cred, 0, sizeof(*cred));
if (client)
ret = krb5_copy_principal(context, client, &cred->client);
else
ret = krb5_get_default_principal(context, &cred->client);
if (ret)
goto out;
if (start_time)
cred->times.starttime = now + start_time;
if (options->flags & KRB5_GET_INIT_CREDS_OPT_TKT_LIFE)
tmp = options->tkt_life;
else
tmp = KRB5_TKT_LIFETIME_DEFAULT;
cred->times.endtime = now + tmp;
if ((options->flags & KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE)) {
if (options->renew_life > 0)
tmp = options->renew_life;
else
tmp = KRB5_TKT_RENEW_LIFETIME_DEFAULT;
cred->times.renew_till = now + tmp;
}
return 0;
out:
krb5_free_cred_contents (context, cred);
return ret;
}
/*
* Print a message (str) to the user about the expiration in `lr'
*/
static void
report_expiration (krb5_context context,
krb5_prompter_fct prompter,
krb5_data *data,
const char *str,
time_t now)
{
char *p = NULL;
if (asprintf(&p, "%s%s", str, ctime(&now)) < 0 || p == NULL)
return;
(*prompter)(context, data, NULL, p, 0, NULL);
free(p);
}
/*
* Check the context, and in the case there is a expiration warning,
* use the prompter to print the warning.
*
* @param context A Kerberos 5 context.
* @param options An GIC options structure
* @param ctx The krb5_init_creds_context check for expiration.
*/
krb5_error_code
krb5_process_last_request(krb5_context context,
krb5_get_init_creds_opt *options,
krb5_init_creds_context ctx)
{
krb5_const_realm realm;
LastReq *lr;
krb5_boolean reported = FALSE;
krb5_timestamp sec;
time_t t;
size_t i;
/*
* First check if there is a API consumer.
*/
realm = krb5_principal_get_realm (context, ctx->cred.client);
lr = &ctx->enc_part.last_req;
if (options && options->opt_private && options->opt_private->lr.func) {
krb5_last_req_entry **lre;
lre = calloc(lr->len + 1, sizeof(*lre));
if (lre == NULL)
return krb5_enomem(context);
for (i = 0; i < lr->len; i++) {
lre[i] = calloc(1, sizeof(*lre[i]));
if (lre[i] == NULL)
break;
lre[i]->lr_type = lr->val[i].lr_type;
lre[i]->value = lr->val[i].lr_value;
}
(*options->opt_private->lr.func)(context, lre,
options->opt_private->lr.ctx);
for (i = 0; i < lr->len; i++)
free(lre[i]);
free(lre);
}
/*
* Now check if we should prompt the user
*/
if (ctx->prompter == NULL)
return 0;
krb5_timeofday (context, &sec);
t = sec + get_config_time (context,
realm,
"warn_pwexpire",
7 * 24 * 60 * 60);
for (i = 0; i < lr->len; ++i) {
if (lr->val[i].lr_value <= t) {
switch (lr->val[i].lr_type) {
case LR_PW_EXPTIME :
report_expiration(context, ctx->prompter,
ctx->prompter_data,
"Your password will expire at ",
lr->val[i].lr_value);
reported = TRUE;
break;
case LR_ACCT_EXPTIME :
report_expiration(context, ctx->prompter,
ctx->prompter_data,
"Your account will expire at ",
lr->val[i].lr_value);
reported = TRUE;
break;
default:
break;
}
}
}
if (!reported
&& ctx->enc_part.key_expiration
&& *ctx->enc_part.key_expiration <= t) {
report_expiration(context, ctx->prompter,
ctx->prompter_data,
"Your password/account will expire at ",
*ctx->enc_part.key_expiration);
}
return 0;
}
static krb5_addresses no_addrs = { 0, NULL };
static krb5_error_code
get_init_creds_common(krb5_context context,
krb5_principal client,
krb5_deltat start_time,
krb5_get_init_creds_opt *options,
krb5_init_creds_context ctx)
{
krb5_get_init_creds_opt *default_opt = NULL;
krb5_error_code ret;
krb5_enctype *etypes;
krb5_preauthtype *pre_auth_types;
memset(ctx, 0, sizeof(*ctx));
if (options == NULL) {
const char *realm = krb5_principal_get_realm(context, client);
krb5_get_init_creds_opt_alloc (context, &default_opt);
options = default_opt;
krb5_get_init_creds_opt_set_default_flags(context, NULL, realm, options);
}
if (options->opt_private) {
if (options->opt_private->password) {
ret = krb5_init_creds_set_password(context, ctx,
options->opt_private->password);
if (ret)
goto out;
}
ctx->keyproc = options->opt_private->key_proc;
ctx->req_pac = options->opt_private->req_pac;
ctx->pk_init_ctx = options->opt_private->pk_init_ctx;
ctx->ic_flags = options->opt_private->flags;
} else
ctx->req_pac = KRB5_INIT_CREDS_TRISTATE_UNSET;
if (ctx->keyproc == NULL)
ctx->keyproc = default_s2k_func;
/* Enterprise name implicitly turns on canonicalize */
if ((ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE) ||
krb5_principal_get_type(context, client) == KRB5_NT_ENTERPRISE_PRINCIPAL)
ctx->flags.canonicalize = 1;
ctx->pre_auth_types = NULL;
ctx->addrs = NULL;
ctx->etypes = NULL;
ctx->pre_auth_types = NULL;
ret = init_cred(context, &ctx->cred, client, start_time, options);
if (ret) {
if (default_opt)
krb5_get_init_creds_opt_free(context, default_opt);
return ret;
}
ret = krb5_init_creds_set_service(context, ctx, NULL);
if (ret)
goto out;
if (options->flags & KRB5_GET_INIT_CREDS_OPT_FORWARDABLE)
ctx->flags.forwardable = options->forwardable;
if (options->flags & KRB5_GET_INIT_CREDS_OPT_PROXIABLE)
ctx->flags.proxiable = options->proxiable;
if (start_time)
ctx->flags.postdated = 1;
if (ctx->cred.times.renew_till)
ctx->flags.renewable = 1;
if (options->flags & KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST) {
ctx->addrs = options->address_list;
} else if (options->opt_private) {
switch (options->opt_private->addressless) {
case KRB5_INIT_CREDS_TRISTATE_UNSET:
#if KRB5_ADDRESSLESS_DEFAULT == TRUE
ctx->addrs = &no_addrs;
#else
ctx->addrs = NULL;
#endif
break;
case KRB5_INIT_CREDS_TRISTATE_FALSE:
ctx->addrs = NULL;
break;
case KRB5_INIT_CREDS_TRISTATE_TRUE:
ctx->addrs = &no_addrs;
break;
}
}
if (options->flags & KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST) {
if (ctx->etypes)
free(ctx->etypes);
etypes = malloc((options->etype_list_length + 1)
* sizeof(krb5_enctype));
if (etypes == NULL) {
ret = krb5_enomem(context);
goto out;
}
memcpy (etypes, options->etype_list,
options->etype_list_length * sizeof(krb5_enctype));
etypes[options->etype_list_length] = ETYPE_NULL;
ctx->etypes = etypes;
}
if (options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST) {
pre_auth_types = malloc((options->preauth_list_length + 1)
* sizeof(krb5_preauthtype));
if (pre_auth_types == NULL) {
ret = krb5_enomem(context);
goto out;
}
memcpy (pre_auth_types, options->preauth_list,
options->preauth_list_length * sizeof(krb5_preauthtype));
pre_auth_types[options->preauth_list_length] = KRB5_PADATA_NONE;
ctx->pre_auth_types = pre_auth_types;
}
if (options->flags & KRB5_GET_INIT_CREDS_OPT_ANONYMOUS)
ctx->flags.request_anonymous = options->anonymous;
if (default_opt)
krb5_get_init_creds_opt_free(context, default_opt);
return 0;
out:
if (default_opt)
krb5_get_init_creds_opt_free(context, default_opt);
return ret;
}
static krb5_error_code
change_password (krb5_context context,
krb5_principal client,
const char *password,
char *newpw,
size_t newpw_sz,
krb5_prompter_fct prompter,
void *data,
krb5_get_init_creds_opt *old_options)
{
krb5_prompt prompts[2];
krb5_error_code ret;
krb5_creds cpw_cred;
char buf1[BUFSIZ], buf2[BUFSIZ];
krb5_data password_data[2];
int result_code;
krb5_data result_code_string;
krb5_data result_string;
char *p;
krb5_get_init_creds_opt *options;
heim_assert(prompter != NULL, "unexpected NULL prompter");
memset (&cpw_cred, 0, sizeof(cpw_cred));
ret = krb5_get_init_creds_opt_alloc(context, &options);
if (ret)
return ret;
krb5_get_init_creds_opt_set_tkt_life (options, 60);
krb5_get_init_creds_opt_set_forwardable (options, FALSE);
krb5_get_init_creds_opt_set_proxiable (options, FALSE);
if (old_options &&
(old_options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST))
krb5_get_init_creds_opt_set_preauth_list(options,
old_options->preauth_list,
old_options->preauth_list_length);
if (old_options &&
(old_options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT))
krb5_get_init_creds_opt_set_change_password_prompt(options,
old_options->change_password_prompt);
krb5_data_zero (&result_code_string);
krb5_data_zero (&result_string);
ret = krb5_get_init_creds_password (context,
&cpw_cred,
client,
password,
prompter,
data,
0,
"kadmin/changepw",
options);
krb5_get_init_creds_opt_free(context, options);
if (ret)
goto out;
for(;;) {
password_data[0].data = buf1;
password_data[0].length = sizeof(buf1);
prompts[0].hidden = 1;
prompts[0].prompt = "New password: ";
prompts[0].reply = &password_data[0];
prompts[0].type = KRB5_PROMPT_TYPE_NEW_PASSWORD;
password_data[1].data = buf2;
password_data[1].length = sizeof(buf2);
prompts[1].hidden = 1;
prompts[1].prompt = "Repeat new password: ";
prompts[1].reply = &password_data[1];
prompts[1].type = KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN;
ret = (*prompter) (context, data, NULL, "Changing password",
2, prompts);
if (ret) {
memset (buf1, 0, sizeof(buf1));
memset (buf2, 0, sizeof(buf2));
goto out;
}
if (strcmp (buf1, buf2) == 0)
break;
memset (buf1, 0, sizeof(buf1));
memset (buf2, 0, sizeof(buf2));
}
ret = krb5_set_password (context,
&cpw_cred,
buf1,
client,
&result_code,
&result_code_string,
&result_string);
if (ret)
goto out;
if (asprintf(&p, "%s: %.*s\n",
result_code ? "Error" : "Success",
(int)result_string.length,
result_string.length > 0 ? (char*)result_string.data : "") < 0)
{
ret = ENOMEM;
goto out;
}
/* return the result */
(*prompter) (context, data, NULL, p, 0, NULL);
free (p);
if (result_code == 0) {
strlcpy (newpw, buf1, newpw_sz);
ret = 0;
} else {
ret = ENOTTY;
krb5_set_error_message(context, ret,
N_("failed changing password", ""));
}
out:
memset (buf1, 0, sizeof(buf1));
memset (buf2, 0, sizeof(buf2));
krb5_data_free (&result_string);
krb5_data_free (&result_code_string);
krb5_free_cred_contents (context, &cpw_cred);
return ret;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_keyblock_key_proc (krb5_context context,
krb5_keytype type,
krb5_data *salt,
krb5_const_pointer keyseed,
krb5_keyblock **key)
{
return krb5_copy_keyblock (context, keyseed, key);
}
/*
*
*/
static krb5_error_code
init_as_req (krb5_context context,
KDCOptions opts,
const krb5_creds *creds,
const krb5_addresses *addrs,
const krb5_enctype *etypes,
AS_REQ *a)
{
krb5_error_code ret;
memset(a, 0, sizeof(*a));
a->pvno = 5;
a->msg_type = krb_as_req;
a->req_body.kdc_options = opts;
a->req_body.cname = malloc(sizeof(*a->req_body.cname));
if (a->req_body.cname == NULL) {
ret = krb5_enomem(context);
goto fail;
}
a->req_body.sname = malloc(sizeof(*a->req_body.sname));
if (a->req_body.sname == NULL) {
ret = krb5_enomem(context);
goto fail;
}
ret = _krb5_principal2principalname (a->req_body.cname, creds->client);
if (ret)
goto fail;
ret = copy_Realm(&creds->client->realm, &a->req_body.realm);
if (ret)
goto fail;
ret = _krb5_principal2principalname (a->req_body.sname, creds->server);
if (ret)
goto fail;
if(creds->times.starttime) {
a->req_body.from = malloc(sizeof(*a->req_body.from));
if (a->req_body.from == NULL) {
ret = krb5_enomem(context);
goto fail;
}
*a->req_body.from = creds->times.starttime;
}
if(creds->times.endtime){
if ((ALLOC(a->req_body.till, 1)) != NULL)
*a->req_body.till = creds->times.endtime;
else {
ret = krb5_enomem(context);
goto fail;
}
}
if(creds->times.renew_till){
a->req_body.rtime = malloc(sizeof(*a->req_body.rtime));
if (a->req_body.rtime == NULL) {
ret = krb5_enomem(context);
goto fail;
}
*a->req_body.rtime = creds->times.renew_till;
}
a->req_body.nonce = 0;
ret = _krb5_init_etype(context,
KRB5_PDU_AS_REQUEST,
&a->req_body.etype.len,
&a->req_body.etype.val,
etypes);
if (ret)
goto fail;
/*
* This means no addresses
*/
if (addrs && addrs->len == 0) {
a->req_body.addresses = NULL;
} else {
a->req_body.addresses = malloc(sizeof(*a->req_body.addresses));
if (a->req_body.addresses == NULL) {
ret = krb5_enomem(context);
goto fail;
}
if (addrs)
ret = krb5_copy_addresses(context, addrs, a->req_body.addresses);
else {
ret = krb5_get_all_client_addrs (context, a->req_body.addresses);
if(ret == 0 && a->req_body.addresses->len == 0) {
free(a->req_body.addresses);
a->req_body.addresses = NULL;
}
}
if (ret)
goto fail;
}
a->req_body.enc_authorization_data = NULL;
a->req_body.additional_tickets = NULL;
a->padata = NULL;
return 0;
fail:
free_AS_REQ(a);
memset(a, 0, sizeof(*a));
return ret;
}
static krb5_error_code
set_paid(struct pa_info_data *paid, krb5_context context,
krb5_enctype etype,
krb5_salttype salttype, void *salt_string, size_t salt_len,
krb5_data *s2kparams)
{
paid->etype = etype;
paid->salt.salttype = salttype;
paid->salt.saltvalue.data = malloc(salt_len + 1);
if (paid->salt.saltvalue.data == NULL) {
krb5_clear_error_message(context);
return ENOMEM;
}
memcpy(paid->salt.saltvalue.data, salt_string, salt_len);
((char *)paid->salt.saltvalue.data)[salt_len] = '\0';
paid->salt.saltvalue.length = salt_len;
if (s2kparams) {
krb5_error_code ret;
ret = krb5_copy_data(context, s2kparams, &paid->s2kparams);
if (ret) {
krb5_clear_error_message(context);
krb5_free_salt(context, paid->salt);
return ret;
}
} else
paid->s2kparams = NULL;
return 0;
}
static struct pa_info_data *
pa_etype_info2(krb5_context context,
const krb5_principal client,
const AS_REQ *asreq,
struct pa_info_data *paid,
heim_octet_string *data)
{
krb5_error_code ret;
ETYPE_INFO2 e;
size_t sz;
size_t i, j;
memset(&e, 0, sizeof(e));
ret = decode_ETYPE_INFO2(data->data, data->length, &e, &sz);
if (ret)
goto out;
if (e.len == 0)
goto out;
for (j = 0; j < asreq->req_body.etype.len; j++) {
for (i = 0; i < e.len; i++) {
if (asreq->req_body.etype.val[j] == e.val[i].etype) {
krb5_salt salt;
if (e.val[i].salt == NULL)
ret = krb5_get_pw_salt(context, client, &salt);
else {
salt.saltvalue.data = *e.val[i].salt;
salt.saltvalue.length = strlen(*e.val[i].salt);
ret = 0;
}
if (ret == 0)
ret = set_paid(paid, context, e.val[i].etype,
KRB5_PW_SALT,
salt.saltvalue.data,
salt.saltvalue.length,
e.val[i].s2kparams);
if (e.val[i].salt == NULL)
krb5_free_salt(context, salt);
if (ret == 0) {
free_ETYPE_INFO2(&e);
return paid;
}
}
}
}
out:
free_ETYPE_INFO2(&e);
return NULL;
}
static struct pa_info_data *
pa_etype_info(krb5_context context,
const krb5_principal client,
const AS_REQ *asreq,
struct pa_info_data *paid,
heim_octet_string *data)
{
krb5_error_code ret;
ETYPE_INFO e;
size_t sz;
size_t i, j;
memset(&e, 0, sizeof(e));
ret = decode_ETYPE_INFO(data->data, data->length, &e, &sz);
if (ret)
goto out;
if (e.len == 0)
goto out;
for (j = 0; j < asreq->req_body.etype.len; j++) {
for (i = 0; i < e.len; i++) {
if (asreq->req_body.etype.val[j] == e.val[i].etype) {
krb5_salt salt;
salt.salttype = KRB5_PW_SALT;
if (e.val[i].salt == NULL)
ret = krb5_get_pw_salt(context, client, &salt);
else {
salt.saltvalue = *e.val[i].salt;
ret = 0;
}
if (e.val[i].salttype)
salt.salttype = *e.val[i].salttype;
if (ret == 0) {
ret = set_paid(paid, context, e.val[i].etype,
salt.salttype,
salt.saltvalue.data,
salt.saltvalue.length,
NULL);
if (e.val[i].salt == NULL)
krb5_free_salt(context, salt);
}
if (ret == 0) {
free_ETYPE_INFO(&e);
return paid;
}
}
}
}
out:
free_ETYPE_INFO(&e);
return NULL;
}
static struct pa_info_data *
pa_pw_or_afs3_salt(krb5_context context,
const krb5_principal client,
const AS_REQ *asreq,
struct pa_info_data *paid,
heim_octet_string *data)
{
krb5_error_code ret;
if (paid->etype == KRB5_ENCTYPE_NULL)
return NULL;
ret = set_paid(paid, context,
paid->etype,
paid->salt.salttype,
data->data,
data->length,
NULL);
if (ret)
return NULL;
return paid;
}
struct pa_info {
krb5_preauthtype type;
struct pa_info_data *(*salt_info)(krb5_context,
const krb5_principal,
const AS_REQ *,
struct pa_info_data *,
heim_octet_string *);
};
static struct pa_info pa_prefs[] = {
{ KRB5_PADATA_ETYPE_INFO2, pa_etype_info2 },
{ KRB5_PADATA_ETYPE_INFO, pa_etype_info },
{ KRB5_PADATA_PW_SALT, pa_pw_or_afs3_salt },
{ KRB5_PADATA_AFS3_SALT, pa_pw_or_afs3_salt }
};
static PA_DATA *
find_pa_data(const METHOD_DATA *md, unsigned type)
{
size_t i;
if (md == NULL)
return NULL;
for (i = 0; i < md->len; i++)
if (md->val[i].padata_type == type)
return &md->val[i];
return NULL;
}
static struct pa_info_data *
process_pa_info(krb5_context context,
const krb5_principal client,
const AS_REQ *asreq,
struct pa_info_data *paid,
METHOD_DATA *md)
{
struct pa_info_data *p = NULL;
size_t i;
for (i = 0; p == NULL && i < sizeof(pa_prefs)/sizeof(pa_prefs[0]); i++) {
PA_DATA *pa = find_pa_data(md, pa_prefs[i].type);
if (pa == NULL)
continue;
paid->salt.salttype = (krb5_salttype)pa_prefs[i].type;
p = (*pa_prefs[i].salt_info)(context, client, asreq,
paid, &pa->padata_value);
}
return p;
}
static krb5_error_code
make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md,
krb5_enctype etype, krb5_keyblock *key)
{
PA_ENC_TS_ENC p;
unsigned char *buf;
size_t buf_size;
size_t len = 0;
EncryptedData encdata;
krb5_error_code ret;
int32_t usec;
int usec2;
krb5_crypto crypto;
krb5_us_timeofday (context, &p.patimestamp, &usec);
usec2 = usec;
p.pausec = &usec2;
ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret);
if (ret)
return ret;
if(buf_size != len)
krb5_abortx(context, "internal error in ASN.1 encoder");
ret = krb5_crypto_init(context, key, 0, &crypto);
if (ret) {
free(buf);
return ret;
}
ret = krb5_encrypt_EncryptedData(context,
crypto,
KRB5_KU_PA_ENC_TIMESTAMP,
buf,
len,
0,
&encdata);
free(buf);
krb5_crypto_destroy(context, crypto);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
free_EncryptedData(&encdata);
if (ret)
return ret;
if(buf_size != len)
krb5_abortx(context, "internal error in ASN.1 encoder");
ret = krb5_padata_add(context, md, KRB5_PADATA_ENC_TIMESTAMP, buf, len);
if (ret)
free(buf);
return ret;
}
static krb5_error_code
add_enc_ts_padata(krb5_context context,
METHOD_DATA *md,
krb5_principal client,
krb5_s2k_proc keyproc,
krb5_const_pointer keyseed,
krb5_enctype *enctypes,
unsigned netypes,
krb5_salt *salt,
krb5_data *s2kparams)
{
krb5_error_code ret;
krb5_salt salt2;
krb5_enctype *ep;
size_t i;
if(salt == NULL) {
/* default to standard salt */
ret = krb5_get_pw_salt (context, client, &salt2);
if (ret)
return ret;
salt = &salt2;
}
if (!enctypes) {
enctypes = context->etypes;
netypes = 0;
for (ep = enctypes; *ep != (krb5_enctype)ETYPE_NULL; ep++)
netypes++;
}
for (i = 0; i < netypes; ++i) {
krb5_keyblock *key;
_krb5_debug(context, 5, "krb5_get_init_creds: using ENC-TS with enctype %d", enctypes[i]);
ret = (*keyproc)(context, enctypes[i], keyseed,
*salt, s2kparams, &key);
if (ret)
continue;
ret = make_pa_enc_timestamp (context, md, enctypes[i], key);
krb5_free_keyblock (context, key);
if (ret)
return ret;
}
if(salt == &salt2)
krb5_free_salt(context, salt2);
return 0;
}
static krb5_error_code
pa_data_to_md_ts_enc(krb5_context context,
const AS_REQ *a,
const krb5_principal client,
krb5_get_init_creds_ctx *ctx,
struct pa_info_data *ppaid,
METHOD_DATA *md)
{
if (ctx->keyproc == NULL || ctx->keyseed == NULL)
return 0;
if (ppaid) {
add_enc_ts_padata(context, md, client,
ctx->keyproc, ctx->keyseed,
&ppaid->etype, 1,
&ppaid->salt, ppaid->s2kparams);
} else {
krb5_salt salt;
_krb5_debug(context, 5, "krb5_get_init_creds: pa-info not found, guessing salt");
/* make a v5 salted pa-data */
add_enc_ts_padata(context, md, client,
ctx->keyproc, ctx->keyseed,
a->req_body.etype.val, a->req_body.etype.len,
NULL, NULL);
/* make a v4 salted pa-data */
salt.salttype = KRB5_PW_SALT;
krb5_data_zero(&salt.saltvalue);
add_enc_ts_padata(context, md, client,
ctx->keyproc, ctx->keyseed,
a->req_body.etype.val, a->req_body.etype.len,
&salt, NULL);
}
return 0;
}
static krb5_error_code
pa_data_to_key_plain(krb5_context context,
const krb5_principal client,
krb5_get_init_creds_ctx *ctx,
krb5_salt salt,
krb5_data *s2kparams,
krb5_enctype etype,
krb5_keyblock **key)
{
krb5_error_code ret;
ret = (*ctx->keyproc)(context, etype, ctx->keyseed,
salt, s2kparams, key);
return ret;
}
static krb5_error_code
pa_data_to_md_pkinit(krb5_context context,
const AS_REQ *a,
const krb5_principal client,
int win2k,
krb5_get_init_creds_ctx *ctx,
METHOD_DATA *md)
{
if (ctx->pk_init_ctx == NULL)
return 0;
#ifdef PKINIT
return _krb5_pk_mk_padata(context,
ctx->pk_init_ctx,
ctx->ic_flags,
win2k,
&a->req_body,
ctx->pk_nonce,
md);
#else
krb5_set_error_message(context, EINVAL,
N_("no support for PKINIT compiled in", ""));
return EINVAL;
#endif
}
static krb5_error_code
pa_data_add_pac_request(krb5_context context,
krb5_get_init_creds_ctx *ctx,
METHOD_DATA *md)
{
size_t len = 0, length;
krb5_error_code ret;
PA_PAC_REQUEST req;
void *buf;
switch (ctx->req_pac) {
case KRB5_INIT_CREDS_TRISTATE_UNSET:
return 0; /* don't bother */
case KRB5_INIT_CREDS_TRISTATE_TRUE:
req.include_pac = 1;
break;
case KRB5_INIT_CREDS_TRISTATE_FALSE:
req.include_pac = 0;
}
ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length,
&req, &len, ret);
if (ret)
return ret;
if(len != length)
krb5_abortx(context, "internal error in ASN.1 encoder");
ret = krb5_padata_add(context, md, KRB5_PADATA_PA_PAC_REQUEST, buf, len);
if (ret)
free(buf);
return 0;
}
/*
* Assumes caller always will free `out_md', even on error.
*/
static krb5_error_code
process_pa_data_to_md(krb5_context context,
const krb5_creds *creds,
const AS_REQ *a,
krb5_get_init_creds_ctx *ctx,
METHOD_DATA *in_md,
METHOD_DATA **out_md,
krb5_prompter_fct prompter,
void *prompter_data)
{
krb5_error_code ret;
ALLOC(*out_md, 1);
if (*out_md == NULL)
return krb5_enomem(context);
(*out_md)->len = 0;
(*out_md)->val = NULL;
if (_krb5_have_debug(context, 5)) {
unsigned i;
_krb5_debug(context, 5, "KDC send %d patypes", in_md->len);
for (i = 0; i < in_md->len; i++)
_krb5_debug(context, 5, "KDC send PA-DATA type: %d", in_md->val[i].padata_type);
}
/*
* Make sure we don't sent both ENC-TS and PK-INIT pa data, no
* need to expose our password protecting our PKCS12 key.
*/
if (ctx->pk_init_ctx) {
_krb5_debug(context, 5, "krb5_get_init_creds: "
"prepareing PKINIT padata (%s)",
(ctx->used_pa_types & USED_PKINIT_W2K) ? "win2k" : "ietf");
if (ctx->used_pa_types & USED_PKINIT_W2K) {
krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
"Already tried pkinit, looping");
return KRB5_GET_IN_TKT_LOOP;
}
ret = pa_data_to_md_pkinit(context, a, creds->client,
(ctx->used_pa_types & USED_PKINIT),
ctx, *out_md);
if (ret)
return ret;
if (ctx->used_pa_types & USED_PKINIT)
ctx->used_pa_types |= USED_PKINIT_W2K;
else
ctx->used_pa_types |= USED_PKINIT;
} else if (in_md->len != 0) {
struct pa_info_data *paid, *ppaid;
unsigned flag;
paid = calloc(1, sizeof(*paid));
if (paid == NULL)
return krb5_enomem(context);
paid->etype = KRB5_ENCTYPE_NULL;
ppaid = process_pa_info(context, creds->client, a, paid, in_md);
if (ppaid)
flag = USED_ENC_TS_INFO;
else
flag = USED_ENC_TS_GUESS;
if (ctx->used_pa_types & flag) {
if (ppaid)
free_paid(context, ppaid);
free(paid);
krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
"Already tried ENC-TS-%s, looping",
flag == USED_ENC_TS_INFO ? "info" : "guess");
return KRB5_GET_IN_TKT_LOOP;
}
pa_data_to_md_ts_enc(context, a, creds->client, ctx, ppaid, *out_md);
ctx->used_pa_types |= flag;
if (ppaid) {
if (ctx->ppaid) {
free_paid(context, ctx->ppaid);
free(ctx->ppaid);
}
ctx->ppaid = ppaid;
} else
free(paid);
}
pa_data_add_pac_request(context, ctx, *out_md);
if ((ctx->fast_state.flags & KRB5_FAST_DISABLED) == 0) {
ret = krb5_padata_add(context, *out_md, KRB5_PADATA_REQ_ENC_PA_REP, NULL, 0);
if (ret)
return ret;
}
if ((*out_md)->len == 0) {
free(*out_md);
*out_md = NULL;
}
return 0;
}
static krb5_error_code
process_pa_data_to_key(krb5_context context,
krb5_get_init_creds_ctx *ctx,
krb5_creds *creds,
AS_REQ *a,
AS_REP *rep,
const krb5_krbhst_info *hi,
krb5_keyblock **key)
{
struct pa_info_data paid, *ppaid = NULL;
krb5_error_code ret;
krb5_enctype etype;
PA_DATA *pa;
memset(&paid, 0, sizeof(paid));
etype = rep->enc_part.etype;
if (rep->padata) {
paid.etype = etype;
ppaid = process_pa_info(context, creds->client, a, &paid,
rep->padata);
}
if (ppaid == NULL)
ppaid = ctx->ppaid;
if (ppaid == NULL) {
ret = krb5_get_pw_salt (context, creds->client, &paid.salt);
if (ret)
return ret;
paid.etype = etype;
paid.s2kparams = NULL;
ppaid = &paid;
}
pa = NULL;
if (rep->padata) {
int idx = 0;
pa = krb5_find_padata(rep->padata->val,
rep->padata->len,
KRB5_PADATA_PK_AS_REP,
&idx);
if (pa == NULL) {
idx = 0;
pa = krb5_find_padata(rep->padata->val,
rep->padata->len,
KRB5_PADATA_PK_AS_REP_19,
&idx);
}
}
if (pa && ctx->pk_init_ctx) {
#ifdef PKINIT
_krb5_debug(context, 5, "krb5_get_init_creds: using PKINIT");
ret = _krb5_pk_rd_pa_reply(context,
a->req_body.realm,
ctx->pk_init_ctx,
etype,
hi,
ctx->pk_nonce,
&ctx->req_buffer,
pa,
key);
#else
ret = EINVAL;
krb5_set_error_message(context, ret, N_("no support for PKINIT compiled in", ""));
#endif
} else if (ctx->keyseed) {
_krb5_debug(context, 5, "krb5_get_init_creds: using keyproc");
ret = pa_data_to_key_plain(context, creds->client, ctx,
ppaid->salt, ppaid->s2kparams, etype, key);
} else {
ret = EINVAL;
krb5_set_error_message(context, ret, N_("No usable pa data type", ""));
}
free_paid(context, &paid);
return ret;
}
/**
* Start a new context to get a new initial credential.
*
* @param context A Kerberos 5 context.
* @param client The Kerberos principal to get the credential for, if
* NULL is given, the default principal is used as determined by
* krb5_get_default_principal().
* @param prompter
* @param prompter_data
* @param start_time the time the ticket should start to be valid or 0 for now.
* @param options a options structure, can be NULL for default options.
* @param rctx A new allocated free with krb5_init_creds_free().
*
* @return 0 for success or an Kerberos 5 error code, see krb5_get_error_message().
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_init(krb5_context context,
krb5_principal client,
krb5_prompter_fct prompter,
void *prompter_data,
krb5_deltat start_time,
krb5_get_init_creds_opt *options,
krb5_init_creds_context *rctx)
{
krb5_init_creds_context ctx;
krb5_error_code ret;
*rctx = NULL;
ctx = calloc(1, sizeof(*ctx));
if (ctx == NULL)
return krb5_enomem(context);
ret = get_init_creds_common(context, client, start_time, options, ctx);
if (ret) {
free(ctx);
return ret;
}
/* Set a new nonce. */
krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce));
ctx->nonce &= 0x7fffffff;
/* XXX these just needs to be the same when using Windows PK-INIT */
ctx->pk_nonce = ctx->nonce;
ctx->prompter = prompter;
ctx->prompter_data = prompter_data;
*rctx = ctx;
return ret;
}
/**
* Sets the service that the is requested. This call is only neede for
* special initial tickets, by default the a krbtgt is fetched in the default realm.
*
* @param context a Kerberos 5 context.
* @param ctx a krb5_init_creds_context context.
* @param service the service given as a string, for example
* "kadmind/admin". If NULL, the default krbtgt in the clients
* realm is set.
*
* @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_set_service(krb5_context context,
krb5_init_creds_context ctx,
const char *service)
{
krb5_const_realm client_realm;
krb5_principal principal;
krb5_error_code ret;
client_realm = krb5_principal_get_realm (context, ctx->cred.client);
if (service) {
ret = krb5_parse_name (context, service, &principal);
if (ret)
return ret;
krb5_principal_set_realm (context, principal, client_realm);
} else {
ret = krb5_make_principal(context, &principal,
client_realm, KRB5_TGS_NAME, client_realm,
NULL);
if (ret)
return ret;
}
/*
* This is for Windows RODC that are picky about what name type
* the server principal have, and the really strange part is that
* they are picky about the AS-REQ name type and not the TGS-REQ
* later. Oh well.
*/
if (krb5_principal_is_krbtgt(context, principal))
krb5_principal_set_type(context, principal, KRB5_NT_SRV_INST);
krb5_free_principal(context, ctx->cred.server);
ctx->cred.server = principal;
return 0;
}
/**
* Sets the password that will use for the request.
*
* @param context a Kerberos 5 context.
* @param ctx ctx krb5_init_creds_context context.
* @param password the password to use.
*
* @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_set_password(krb5_context context,
krb5_init_creds_context ctx,
const char *password)
{
if (ctx->password) {
memset(ctx->password, 0, strlen(ctx->password));
free(ctx->password);
}
if (password) {
ctx->password = strdup(password);
if (ctx->password == NULL)
return krb5_enomem(context);
ctx->keyseed = (void *) ctx->password;
} else {
ctx->keyseed = NULL;
ctx->password = NULL;
}
return 0;
}
static krb5_error_code KRB5_CALLCONV
keytab_key_proc(krb5_context context, krb5_enctype enctype,
krb5_const_pointer keyseed,
krb5_salt salt, krb5_data *s2kparms,
krb5_keyblock **key)
{
krb5_keytab_key_proc_args *args = rk_UNCONST(keyseed);
krb5_keytab keytab = args->keytab;
krb5_principal principal = args->principal;
krb5_error_code ret;
krb5_keytab real_keytab;
krb5_keytab_entry entry;
if(keytab == NULL)
krb5_kt_default(context, &real_keytab);
else
real_keytab = keytab;
ret = krb5_kt_get_entry (context, real_keytab, principal,
0, enctype, &entry);
if (keytab == NULL)
krb5_kt_close (context, real_keytab);
if (ret)
return ret;
ret = krb5_copy_keyblock (context, &entry.keyblock, key);
krb5_kt_free_entry(context, &entry);
return ret;
}
/**
* Set the keytab to use for authentication.
*
* @param context a Kerberos 5 context.
* @param ctx ctx krb5_init_creds_context context.
* @param keytab the keytab to read the key from.
*
* @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message().
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_set_keytab(krb5_context context,
krb5_init_creds_context ctx,
krb5_keytab keytab)
{
krb5_keytab_key_proc_args *a;
krb5_keytab_entry entry;
krb5_kt_cursor cursor;
krb5_enctype *etypes = NULL;
krb5_error_code ret;
size_t netypes = 0;
int kvno = 0, found = 0;
a = malloc(sizeof(*a));
if (a == NULL)
return krb5_enomem(context);
a->principal = ctx->cred.client;
a->keytab = keytab;
ctx->keytab_data = a;
ctx->keyseed = (void *)a;
ctx->keyproc = keytab_key_proc;
/*
* We need to the KDC what enctypes we support for this keytab,
* esp if the keytab is really a password based entry, then the
* KDC might have more enctypes in the database then what we have
* in the keytab.
*/
ret = krb5_kt_start_seq_get(context, keytab, &cursor);
if(ret)
goto out;
while(krb5_kt_next_entry(context, keytab, &entry, &cursor) == 0){
void *ptr;
if (!krb5_principal_compare(context, entry.principal, ctx->cred.client))
goto next;
found = 1;
/* check if we ahve this kvno already */
if (entry.vno > kvno) {
/* remove old list of etype */
if (etypes)
free(etypes);
etypes = NULL;
netypes = 0;
kvno = entry.vno;
} else if (entry.vno != kvno)
goto next;
/* check if enctype is supported */
if (krb5_enctype_valid(context, entry.keyblock.keytype) != 0)
goto next;
/* add enctype to supported list */
ptr = realloc(etypes, sizeof(etypes[0]) * (netypes + 2));
if (ptr == NULL) {
free(etypes);
ret = krb5_enomem(context);
goto out;
}
etypes = ptr;
etypes[netypes] = entry.keyblock.keytype;
etypes[netypes + 1] = ETYPE_NULL;
netypes++;
next:
krb5_kt_free_entry(context, &entry);
}
krb5_kt_end_seq_get(context, keytab, &cursor);
if (etypes) {
if (ctx->etypes)
free(ctx->etypes);
ctx->etypes = etypes;
}
out:
if (!found) {
if (ret == 0)
ret = KRB5_KT_NOTFOUND;
_krb5_kt_principal_not_found(context, ret, keytab, ctx->cred.client, 0, 0);
}
return ret;
}
static krb5_error_code KRB5_CALLCONV
keyblock_key_proc(krb5_context context, krb5_enctype enctype,
krb5_const_pointer keyseed,
krb5_salt salt, krb5_data *s2kparms,
krb5_keyblock **key)
{
return krb5_copy_keyblock (context, keyseed, key);
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_set_keyblock(krb5_context context,
krb5_init_creds_context ctx,
krb5_keyblock *keyblock)
{
ctx->keyseed = (void *)keyblock;
ctx->keyproc = keyblock_key_proc;
return 0;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_set_fast_ccache(krb5_context context,
krb5_init_creds_context ctx,
krb5_ccache fast_ccache)
{
ctx->fast_state.armor_ccache = fast_ccache;
ctx->fast_state.flags |= KRB5_FAST_REQUIRED;
return 0;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_set_fast_ap_armor_service(krb5_context context,
krb5_init_creds_context ctx,
krb5_const_principal armor_service)
{
krb5_error_code ret;
if (ctx->fast_state.armor_service)
krb5_free_principal(context, ctx->fast_state.armor_service);
if (armor_service) {
ret = krb5_copy_principal(context, armor_service, &ctx->fast_state.armor_service);
if (ret)
return ret;
} else {
ctx->fast_state.armor_service = NULL;
}
ctx->fast_state.flags |= KRB5_FAST_REQUIRED | KRB5_FAST_AP_ARMOR_SERVICE;
return 0;
}
/*
* FAST
*/
static krb5_error_code
check_fast(krb5_context context, struct fast_state *state)
{
if (state->flags & KRB5_FAST_EXPECTED) {
krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
"Expected FAST, but no FAST "
"was in the response from the KDC");
return KRB5KRB_AP_ERR_MODIFIED;
}
return 0;
}
static krb5_error_code
fast_unwrap_as_rep(krb5_context context, int32_t nonce,
krb5_data *chksumdata,
struct fast_state *state, AS_REP *rep)
{
PA_FX_FAST_REPLY fxfastrep;
KrbFastResponse fastrep;
krb5_error_code ret;
PA_DATA *pa = NULL;
int idx = 0;
if (state->armor_crypto == NULL || rep->padata == NULL)
return check_fast(context, state);
/* find PA_FX_FAST_REPLY */
pa = krb5_find_padata(rep->padata->val, rep->padata->len,
KRB5_PADATA_FX_FAST, &idx);
if (pa == NULL)
return check_fast(context, state);
memset(&fxfastrep, 0, sizeof(fxfastrep));
memset(&fastrep, 0, sizeof(fastrep));
ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data, pa->padata_value.length, &fxfastrep, NULL);
if (ret)
return ret;
if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) {
krb5_data data;
ret = krb5_decrypt_EncryptedData(context,
state->armor_crypto,
KRB5_KU_FAST_REP,
&fxfastrep.u.armored_data.enc_fast_rep,
&data);
if (ret)
goto out;
ret = decode_KrbFastResponse(data.data, data.length, &fastrep, NULL);
krb5_data_free(&data);
if (ret)
goto out;
} else {
ret = KRB5KDC_ERR_PREAUTH_FAILED;
goto out;
}
free_METHOD_DATA(rep->padata);
ret = copy_METHOD_DATA(&fastrep.padata, rep->padata);
if (ret)
goto out;
if (fastrep.strengthen_key) {
if (state->strengthen_key)
krb5_free_keyblock(context, state->strengthen_key);
ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key);
if (ret)
goto out;
}
if (nonce != fastrep.nonce) {
ret = KRB5KDC_ERR_PREAUTH_FAILED;
goto out;
}
if (fastrep.finished) {
PrincipalName cname;
krb5_realm crealm = NULL;
if (chksumdata == NULL) {
ret = KRB5KDC_ERR_PREAUTH_FAILED;
goto out;
}
ret = krb5_verify_checksum(context, state->armor_crypto,
KRB5_KU_FAST_FINISHED,
chksumdata->data, chksumdata->length,
&fastrep.finished->ticket_checksum);
if (ret)
goto out;
/* update */
ret = copy_Realm(&fastrep.finished->crealm, &crealm);
if (ret)
goto out;
free_Realm(&rep->crealm);
rep->crealm = crealm;
ret = copy_PrincipalName(&fastrep.finished->cname, &cname);
if (ret)
goto out;
free_PrincipalName(&rep->cname);
rep->cname = cname;
#if 0 /* store authenticated checksum as kdc-offset */
fastrep->finished.timestamp;
fastrep->finished.usec = 0;
#endif
} else if (chksumdata) {
/* expected fastrep.finish but didn't get it */
ret = KRB5KDC_ERR_PREAUTH_FAILED;
}
out:
free_PA_FX_FAST_REPLY(&fxfastrep);
return ret;
}
static krb5_error_code
fast_unwrap_error(krb5_context context, struct fast_state *state, KRB_ERROR *error)
{
if (state->armor_crypto == NULL)
return check_fast(context, state);
return 0;
}
krb5_error_code
_krb5_make_fast_ap_fxarmor(krb5_context context,
krb5_ccache armor_ccache,
krb5_data *armor_value,
krb5_keyblock *armor_key,
krb5_crypto *armor_crypto)
{
krb5_auth_context auth_context = NULL;
krb5_creds cred, *credp = NULL;
krb5_error_code ret;
krb5_data empty;
krb5_data_zero(&empty);
memset(&cred, 0, sizeof(cred));
ret = krb5_auth_con_init (context, &auth_context);
if (ret)
goto out;
ret = krb5_cc_get_principal(context, armor_ccache, &cred.client);
if (ret)
goto out;
ret = krb5_make_principal(context, &cred.server,
cred.client->realm,
KRB5_TGS_NAME,
cred.client->realm,
NULL);
if (ret) {
krb5_free_principal(context, cred.client);
goto out;
}
ret = krb5_get_credentials(context, 0, armor_ccache, &cred, &credp);
krb5_free_principal(context, cred.server);
krb5_free_principal(context, cred.client);
if (ret)
goto out;
ret = krb5_auth_con_add_AuthorizationData(context, auth_context, KRB5_PADATA_FX_FAST_ARMOR, &empty);
if (ret)
goto out;
ret = krb5_mk_req_extended(context,
&auth_context,
AP_OPTS_USE_SUBKEY,
NULL,
credp,
armor_value);
krb5_free_creds(context, credp);
if (ret)
goto out;
ret = _krb5_fast_armor_key(context,
auth_context->local_subkey,
auth_context->keyblock,
armor_key,
armor_crypto);
if (ret)
goto out;
out:
krb5_auth_con_free(context, auth_context);
return ret;
}
#ifndef WIN32
static heim_base_once_t armor_service_once = HEIM_BASE_ONCE_INIT;
static heim_ipc armor_service = NULL;
static void
fast_armor_init_ipc(void *ctx)
{
heim_ipc *ipc = ctx;
heim_ipc_init_context("ANY:org.h5l.armor-service", ipc);
}
#endif /* WIN32 */
static krb5_error_code
make_fast_ap_fxarmor(krb5_context context,
struct fast_state *state,
const char *realm,
KrbFastArmor **armor)
{
KrbFastArmor *fxarmor = NULL;
krb5_error_code ret;
if (state->armor_crypto)
krb5_crypto_destroy(context, state->armor_crypto);
krb5_free_keyblock_contents(context, &state->armor_key);
ALLOC(fxarmor, 1);
if (fxarmor == NULL)
return krb5_enomem(context);
if (state->flags & KRB5_FAST_AP_ARMOR_SERVICE) {
#ifdef WIN32
krb5_set_error_message(context, ENOTSUP, "Fast armor IPC service not supportted yet on Windows");
ret = ENOTSUP;
goto out;
#else /* WIN32 */
KERB_ARMOR_SERVICE_REPLY msg;
krb5_data request, reply;
heim_base_once_f(&armor_service_once, &armor_service, fast_armor_init_ipc);
if (armor_service == NULL) {
krb5_set_error_message(context, ENOENT, "Failed to open fast armor service");
ret = ENOENT;
goto out;
}
krb5_data_zero(&reply);
request.data = rk_UNCONST(realm);
request.length = strlen(realm);
ret = heim_ipc_call(armor_service, &request, &reply, NULL);
heim_release(send);
if (ret) {
krb5_set_error_message(context, ret, "Failed to get armor service credential");
goto out;
}
ret = decode_KERB_ARMOR_SERVICE_REPLY(reply.data, reply.length, &msg, NULL);
krb5_data_free(&reply);
if (ret)
goto out;
ret = copy_KrbFastArmor(fxarmor, &msg.armor);
if (ret) {
free_KERB_ARMOR_SERVICE_REPLY(&msg);
goto out;
}
ret = krb5_copy_keyblock_contents(context, &msg.armor_key, &state->armor_key);
free_KERB_ARMOR_SERVICE_REPLY(&msg);
if (ret)
goto out;
ret = krb5_crypto_init(context, &state->armor_key, 0, &state->armor_crypto);
if (ret)
goto out;
#endif /* WIN32 */
} else {
fxarmor->armor_type = 1;
ret = _krb5_make_fast_ap_fxarmor(context,
state->armor_ccache,
&fxarmor->armor_value,
&state->armor_key,
&state->armor_crypto);
if (ret)
goto out;
}
*armor = fxarmor;
fxarmor = NULL;
out:
if (fxarmor) {
free_KrbFastArmor(fxarmor);
free(fxarmor);
}
return ret;
}
static krb5_error_code
fast_wrap_req(krb5_context context, struct fast_state *state, KDC_REQ *req)
{
KrbFastArmor *fxarmor = NULL;
PA_FX_FAST_REQUEST fxreq;
krb5_error_code ret;
KrbFastReq fastreq;
krb5_data data;
size_t size;
if (state->flags & KRB5_FAST_DISABLED) {
_krb5_debug(context, 10, "fast disabled, not doing any fast wrapping");
return 0;
}
memset(&fxreq, 0, sizeof(fxreq));
memset(&fastreq, 0, sizeof(fastreq));
krb5_data_zero(&data);
if (state->armor_crypto == NULL) {
if (state->armor_ccache) {
/*
* Instead of keeping state in FX_COOKIE in the KDC, we
* rebuild a new armor key for every request, because this
* is what the MIT KDC expect and RFC6113 is vage about
* what the behavior should be.
*/
state->type = choice_PA_FX_FAST_REQUEST_armored_data;
} else {
return check_fast(context, state);
}
}
state->flags |= KRB5_FAST_EXPECTED;
fastreq.fast_options.hide_client_names = 1;
ret = copy_KDC_REQ_BODY(&req->req_body, &fastreq.req_body);
free_KDC_REQ_BODY(&req->req_body);
req->req_body.realm = strdup(KRB5_ANON_REALM);
if ((ALLOC(req->req_body.cname, 1)) != NULL) {
req->req_body.cname->name_type = KRB5_NT_WELLKNOWN;
if ((ALLOC(req->req_body.cname->name_string.val, 2)) != NULL) {
req->req_body.cname->name_string.len = 2;
req->req_body.cname->name_string.val[0] = strdup(KRB5_WELLKNOWN_NAME);
req->req_body.cname->name_string.val[1] = strdup(KRB5_ANON_NAME);
if (req->req_body.cname->name_string.val[0] == NULL ||
req->req_body.cname->name_string.val[1] == NULL)
ret = krb5_enomem(context);
} else
ret = krb5_enomem(context);
} else
ret = krb5_enomem(context);
if ((ALLOC(req->req_body.till, 1)) != NULL)
*req->req_body.till = 0;
else
ret = krb5_enomem(context);
if (ret)
goto out;
if (req->padata) {
ret = copy_METHOD_DATA(req->padata, &fastreq.padata);
free_METHOD_DATA(req->padata);
} else {
if ((ALLOC(req->padata, 1)) == NULL)
ret = krb5_enomem(context);
}
if (ret)
goto out;
ASN1_MALLOC_ENCODE(KrbFastReq, data.data, data.length, &fastreq, &size, ret);
if (ret)
goto out;
heim_assert(data.length == size, "ASN.1 internal error");
fxreq.element = state->type;
if (state->type == choice_PA_FX_FAST_REQUEST_armored_data) {
size_t len;
void *buf;
ret = make_fast_ap_fxarmor(context, state, fastreq.req_body.realm, &fxreq.u.armored_data.armor);
if (ret)
goto out;
heim_assert(state->armor_crypto != NULL, "FAST armor key missing when FAST started");
ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, len, &req->req_body, &size, ret);
if (ret)
goto out;
heim_assert(len == size, "ASN.1 internal error");
ret = krb5_create_checksum(context, state->armor_crypto,
KRB5_KU_FAST_REQ_CHKSUM, 0,
buf, len,
&fxreq.u.armored_data.req_checksum);
free(buf);
if (ret)
goto out;
ret = krb5_encrypt_EncryptedData(context, state->armor_crypto,
KRB5_KU_FAST_ENC,
data.data,
data.length,
0,
&fxreq.u.armored_data.enc_fast_req);
krb5_data_free(&data);
if (ret)
goto out;
} else {
krb5_data_free(&data);
heim_assert(false, "unknown FAST type, internal error");
}
ASN1_MALLOC_ENCODE(PA_FX_FAST_REQUEST, data.data, data.length, &fxreq, &size, ret);
if (ret)
goto out;
heim_assert(data.length == size, "ASN.1 internal error");
ret = krb5_padata_add(context, req->padata, KRB5_PADATA_FX_FAST, data.data, data.length);
if (ret)
goto out;
krb5_data_zero(&data);
out:
free_PA_FX_FAST_REQUEST(&fxreq);
free_KrbFastReq(&fastreq);
if (fxarmor) {
free_KrbFastArmor(fxarmor);
free(fxarmor);
}
krb5_data_free(&data);
return ret;
}
/**
* The core loop if krb5_get_init_creds() function family. Create the
* packets and have the caller send them off to the KDC.
*
* If the caller want all work been done for them, use
* krb5_init_creds_get() instead.
*
* @param context a Kerberos 5 context.
* @param ctx ctx krb5_init_creds_context context.
* @param in input data from KDC, first round it should be reset by krb5_data_zer().
* @param out reply to KDC.
* @param hostinfo KDC address info, first round it can be NULL.
* @param flags status of the round, if
* KRB5_INIT_CREDS_STEP_FLAG_CONTINUE is set, continue one more round.
*
* @return 0 for success, or an Kerberos 5 error code, see
* krb5_get_error_message().
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_step(krb5_context context,
krb5_init_creds_context ctx,
krb5_data *in,
krb5_data *out,
krb5_krbhst_info *hostinfo,
unsigned int *flags)
{
krb5_error_code ret;
size_t len = 0;
size_t size;
AS_REQ req2;
krb5_data_zero(out);
if (ctx->as_req.req_body.cname == NULL) {
ret = init_as_req(context, ctx->flags, &ctx->cred,
ctx->addrs, ctx->etypes, &ctx->as_req);
if (ret) {
free_init_creds_ctx(context, ctx);
return ret;
}
}
#define MAX_PA_COUNTER 10
if (ctx->pa_counter > MAX_PA_COUNTER) {
krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
N_("Looping %d times while getting "
"initial credentials", ""),
ctx->pa_counter);
return KRB5_GET_IN_TKT_LOOP;
}
ctx->pa_counter++;
_krb5_debug(context, 5, "krb5_get_init_creds: loop %d", ctx->pa_counter);
/* Lets process the input packet */
if (in && in->length) {
krb5_kdc_rep rep;
memset(&rep, 0, sizeof(rep));
_krb5_debug(context, 5, "krb5_get_init_creds: processing input");
ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);
if (ret == 0) {
unsigned eflags = EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC;
krb5_data data;
/*
* Unwrap AS-REP
*/
ASN1_MALLOC_ENCODE(Ticket, data.data, data.length,
&rep.kdc_rep.ticket, &size, ret);
if (ret)
goto out;
heim_assert(data.length == size, "ASN.1 internal error");
ret = fast_unwrap_as_rep(context, ctx->nonce, &data,
&ctx->fast_state, &rep.kdc_rep);
krb5_data_free(&data);
if (ret)
goto out;
/*
* Now check and extract the ticket
*/
if (ctx->flags.canonicalize) {
eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
eflags |= EXTRACT_TICKET_MATCH_REALM;
}
if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)
eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
ret = process_pa_data_to_key(context, ctx, &ctx->cred,
&ctx->as_req, &rep.kdc_rep,
hostinfo, &ctx->fast_state.reply_key);
if (ret) {
free_AS_REP(&rep.kdc_rep);
goto out;
}
_krb5_debug(context, 5, "krb5_get_init_creds: extracting ticket");
ret = _krb5_extract_ticket(context,
&rep,
&ctx->cred,
ctx->fast_state.reply_key,
NULL,
KRB5_KU_AS_REP_ENC_PART,
NULL,
ctx->nonce,
eflags,
&ctx->req_buffer,
NULL,
NULL);
if (ret == 0 && ctx->pk_init_ctx) {
PA_DATA *pa_pkinit_kx;
int idx = 0;
pa_pkinit_kx =
krb5_find_padata(rep.kdc_rep.padata->val,
rep.kdc_rep.padata->len,
KRB5_PADATA_PKINIT_KX,
&idx);
ret = _krb5_pk_kx_confirm(context, ctx->pk_init_ctx,
ctx->fast_state.reply_key,
&ctx->cred.session,
pa_pkinit_kx);
if (ret)
krb5_set_error_message(context, ret,
N_("Failed to confirm PA-PKINIT-KX", ""));
else if (pa_pkinit_kx != NULL)
ctx->ic_flags |= KRB5_INIT_CREDS_PKINIT_KX_VALID;
}
if (ret == 0)
ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);
krb5_free_keyblock(context, ctx->fast_state.reply_key);
ctx->fast_state.reply_key = NULL;
*flags = 0;
free_AS_REP(&rep.kdc_rep);
free_EncASRepPart(&rep.enc_part);
return ret;
} else {
/* let's try to parse it as a KRB-ERROR */
_krb5_debug(context, 5, "krb5_get_init_creds: got an error");
free_KRB_ERROR(&ctx->error);
ret = krb5_rd_error(context, in, &ctx->error);
if(ret && in->length && ((char*)in->data)[0] == 4)
ret = KRB5KRB_AP_ERR_V4_REPLY;
if (ret) {
_krb5_debug(context, 5, "krb5_get_init_creds: failed to read error");
goto out;
}
/*
* Unwrap KRB-ERROR
*/
ret = fast_unwrap_error(context, &ctx->fast_state, &ctx->error);
if (ret)
goto out;
/*
*
*/
ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);
_krb5_debug(context, 5, "krb5_get_init_creds: KRB-ERROR %d", ret);
/*
* If no preauth was set and KDC requires it, give it one
* more try.
*/
if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) {
free_METHOD_DATA(&ctx->md);
memset(&ctx->md, 0, sizeof(ctx->md));
if (ctx->error.e_data) {
ret = decode_METHOD_DATA(ctx->error.e_data->data,
ctx->error.e_data->length,
&ctx->md,
NULL);
if (ret)
krb5_set_error_message(context, ret,
N_("Failed to decode METHOD-DATA", ""));
} else {
krb5_set_error_message(context, ret,
N_("Preauth required but no preauth "
"options send by KDC", ""));
}
} else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) {
/*
* Try adapt to timeskrew when we are using pre-auth, and
* if there was a time skew, try again.
*/
krb5_set_real_time(context, ctx->error.stime, -1);
if (context->kdc_sec_offset)
ret = 0;
_krb5_debug(context, 10, "init_creds: err skew updateing kdc offset to %d",
context->kdc_sec_offset);
ctx->used_pa_types = 0;
} else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) {
/* client referal to a new realm */
if (ctx->error.crealm == NULL) {
krb5_set_error_message(context, ret,
N_("Got a client referral, not but no realm", ""));
goto out;
}
_krb5_debug(context, 5,
"krb5_get_init_creds: got referal to realm %s",
*ctx->error.crealm);
ret = krb5_principal_set_realm(context,
ctx->cred.client,
*ctx->error.crealm);
if (ret)
goto out;
if (krb5_principal_is_krbtgt(context, ctx->cred.server)) {
ret = krb5_init_creds_set_service(context, ctx, NULL);
if (ret)
goto out;
}
free_AS_REQ(&ctx->as_req);
memset(&ctx->as_req, 0, sizeof(ctx->as_req));
ctx->used_pa_types = 0;
} else if (ret == KRB5KDC_ERR_KEY_EXP && ctx->runflags.change_password == 0 && ctx->prompter) {
char buf2[1024];
ctx->runflags.change_password = 1;
ctx->prompter(context, ctx->prompter_data, NULL, N_("Password has expired", ""), 0, NULL);
/* try to avoid recursion */
if (ctx->in_tkt_service != NULL && strcmp(ctx->in_tkt_service, "kadmin/changepw") == 0)
goto out;
/* don't try to change password where then where none */
if (ctx->prompter == NULL)
goto out;
ret = change_password(context,
ctx->cred.client,
ctx->password,
buf2,
sizeof(buf2),
ctx->prompter,
ctx->prompter_data,
NULL);
if (ret)
goto out;
krb5_init_creds_set_password(context, ctx, buf2);
ctx->used_pa_types = 0;
ret = 0;
} else if (ret == KRB5KDC_ERR_PREAUTH_FAILED) {
if (ctx->fast_state.flags & KRB5_FAST_DISABLED)
goto out;
if (ctx->fast_state.flags & (KRB5_FAST_REQUIRED | KRB5_FAST_EXPECTED))
goto out;
_krb5_debug(context, 10, "preauth failed with FAST, "
"and told by KD or user, trying w/o FAST");
ctx->fast_state.flags |= KRB5_FAST_DISABLED;
ctx->used_pa_types = 0;
ret = 0;
}
if (ret)
goto out;
}
}
if (ctx->as_req.req_body.cname == NULL) {
ret = init_as_req(context, ctx->flags, &ctx->cred,
ctx->addrs, ctx->etypes, &ctx->as_req);
if (ret) {
free_init_creds_ctx(context, ctx);
return ret;
}
}
if (ctx->as_req.padata) {
free_METHOD_DATA(ctx->as_req.padata);
free(ctx->as_req.padata);
ctx->as_req.padata = NULL;
}
/* Set a new nonce. */
ctx->as_req.req_body.nonce = ctx->nonce;
/* fill_in_md_data */
ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,
&ctx->md, &ctx->as_req.padata,
ctx->prompter, ctx->prompter_data);
if (ret)
goto out;
/*
* Wrap with FAST
*/
copy_AS_REQ(&ctx->as_req, &req2);
ret = fast_wrap_req(context, &ctx->fast_state, &req2);
if (ret) {
free_AS_REQ(&req2);
goto out;
}
krb5_data_free(&ctx->req_buffer);
ASN1_MALLOC_ENCODE(AS_REQ,
ctx->req_buffer.data, ctx->req_buffer.length,
&req2, &len, ret);
free_AS_REQ(&req2);
if (ret)
goto out;
if(len != ctx->req_buffer.length)
krb5_abortx(context, "internal error in ASN.1 encoder");
out->data = ctx->req_buffer.data;
out->length = ctx->req_buffer.length;
*flags = KRB5_INIT_CREDS_STEP_FLAG_CONTINUE;
return 0;
out:
return ret;
}
/**
* Extract the newly acquired credentials from krb5_init_creds_context
* context.
*
* @param context A Kerberos 5 context.
* @param ctx
* @param cred credentials, free with krb5_free_cred_contents().
*
* @return 0 for sucess or An Kerberos error code, see krb5_get_error_message().
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_get_creds(krb5_context context,
krb5_init_creds_context ctx,
krb5_creds *cred)
{
return krb5_copy_creds_contents(context, &ctx->cred, cred);
}
/**
* Get the last error from the transaction.
*
* @return Returns 0 or an error code
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_get_error(krb5_context context,
krb5_init_creds_context ctx,
KRB_ERROR *error)
{
krb5_error_code ret;
ret = copy_KRB_ERROR(&ctx->error, error);
if (ret)
krb5_enomem(context);
return ret;
}
/**
*
* @ingroup krb5_credential
*/
krb5_error_code
krb5_init_creds_store(krb5_context context,
krb5_init_creds_context ctx,
krb5_ccache id)
{
krb5_error_code ret;
if (ctx->cred.client == NULL) {
ret = KRB5KDC_ERR_PREAUTH_REQUIRED;
krb5_set_error_message(context, ret, "init creds not completed yet");
return ret;
}
ret = krb5_cc_initialize(context, id, ctx->cred.client);
if (ret)
return ret;
ret = krb5_cc_store_cred(context, id, &ctx->cred);
if (ret)
return ret;
if (ctx->cred.flags.b.enc_pa_rep) {
krb5_data data = { 3, rk_UNCONST("yes") };
ret = krb5_cc_set_config(context, id, ctx->cred.server,
"fast_avail", &data);
if (ret)
return ret;
}
return ret;
}
/**
* Free the krb5_init_creds_context allocated by krb5_init_creds_init().
*
* @param context A Kerberos 5 context.
* @param ctx The krb5_init_creds_context to free.
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION void KRB5_LIB_CALL
krb5_init_creds_free(krb5_context context,
krb5_init_creds_context ctx)
{
free_init_creds_ctx(context, ctx);
free(ctx);
}
/**
* Get new credentials as setup by the krb5_init_creds_context.
*
* @param context A Kerberos 5 context.
* @param ctx The krb5_init_creds_context to process.
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx)
{
krb5_sendto_ctx stctx = NULL;
krb5_krbhst_info *hostinfo = NULL;
krb5_error_code ret;
krb5_data in, out;
unsigned int flags = 0;
krb5_data_zero(&in);
krb5_data_zero(&out);
ret = krb5_sendto_ctx_alloc(context, &stctx);
if (ret)
goto out;
krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);
while (1) {
flags = 0;
ret = krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags);
krb5_data_free(&in);
if (ret)
goto out;
if ((flags & 1) == 0)
break;
ret = krb5_sendto_context (context, stctx, &out,
ctx->cred.client->realm, &in);
if (ret)
goto out;
}
out:
if (stctx)
krb5_sendto_ctx_free(context, stctx);
return ret;
}
/**
* Get new credentials using password.
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_get_init_creds_password(krb5_context context,
krb5_creds *creds,
krb5_principal client,
const char *password,
krb5_prompter_fct prompter,
void *data,
krb5_deltat start_time,
const char *in_tkt_service,
krb5_get_init_creds_opt *options)
{
krb5_init_creds_context ctx;
char buf[BUFSIZ], buf2[BUFSIZ];
krb5_error_code ret;
int chpw = 0;
again:
ret = krb5_init_creds_init(context, client, prompter, data, start_time, options, &ctx);
if (ret)
goto out;
ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
if (ret)
goto out;
if (prompter != NULL && ctx->password == NULL && password == NULL) {
krb5_prompt prompt;
krb5_data password_data;
char *p, *q = NULL;
int aret;
ret = krb5_unparse_name(context, client, &p);
if (ret)
goto out;
aret = asprintf(&q, "%s's Password: ", p);
free (p);
if (aret == -1 || q == NULL) {
ret = krb5_enomem(context);
goto out;
}
prompt.prompt = q;
password_data.data = buf;
password_data.length = sizeof(buf);
prompt.hidden = 1;
prompt.reply = &password_data;
prompt.type = KRB5_PROMPT_TYPE_PASSWORD;
ret = (*prompter) (context, data, NULL, NULL, 1, &prompt);
free (q);
if (ret) {
memset (buf, 0, sizeof(buf));
ret = KRB5_LIBOS_PWDINTR;
krb5_clear_error_message (context);
goto out;
}
password = password_data.data;
}
if (password) {
ret = krb5_init_creds_set_password(context, ctx, password);
if (ret)
goto out;
}
ret = krb5_init_creds_get(context, ctx);
if (ret == 0)
krb5_process_last_request(context, options, ctx);
if (ret == KRB5KDC_ERR_KEY_EXPIRED && chpw == 0) {
/* try to avoid recursion */
if (in_tkt_service != NULL && strcmp(in_tkt_service, "kadmin/changepw") == 0)
goto out;
/* don't try to change password where then where none */
if (prompter == NULL)
goto out;
if ((options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT) &&
!options->change_password_prompt)
goto out;
ret = change_password (context,
client,
ctx->password,
buf2,
sizeof(buf2),
prompter,
data,
options);
if (ret)
goto out;
password = buf2;
chpw = 1;
krb5_init_creds_free(context, ctx);
goto again;
}
out:
if (ret == 0)
krb5_init_creds_get_creds(context, ctx, creds);
if (ctx)
krb5_init_creds_free(context, ctx);
memset(buf, 0, sizeof(buf));
memset(buf2, 0, sizeof(buf2));
return ret;
}
/**
* Get new credentials using keyblock.
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_get_init_creds_keyblock(krb5_context context,
krb5_creds *creds,
krb5_principal client,
krb5_keyblock *keyblock,
krb5_deltat start_time,
const char *in_tkt_service,
krb5_get_init_creds_opt *options)
{
krb5_init_creds_context ctx;
krb5_error_code ret;
memset(creds, 0, sizeof(*creds));
ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
if (ret)
goto out;
ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
if (ret)
goto out;
ret = krb5_init_creds_set_keyblock(context, ctx, keyblock);
if (ret)
goto out;
ret = krb5_init_creds_get(context, ctx);
if (ret == 0)
krb5_process_last_request(context, options, ctx);
out:
if (ret == 0)
krb5_init_creds_get_creds(context, ctx, creds);
if (ctx)
krb5_init_creds_free(context, ctx);
return ret;
}
/**
* Get new credentials using keytab.
*
* @ingroup krb5_credential
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_get_init_creds_keytab(krb5_context context,
krb5_creds *creds,
krb5_principal client,
krb5_keytab keytab,
krb5_deltat start_time,
const char *in_tkt_service,
krb5_get_init_creds_opt *options)
{
krb5_init_creds_context ctx;
krb5_keytab_entry ktent;
krb5_error_code ret;
memset(&ktent, 0, sizeof(ktent));
memset(creds, 0, sizeof(*creds));
if (strcmp(client->realm, "") == 0) {
/*
* Referral realm. We have a keytab, so pick a realm by
* matching in the keytab.
*/
ret = krb5_kt_get_entry(context, keytab, client, 0, 0, &ktent);
if (ret == 0)
client = ktent.principal;
}
ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx);
if (ret)
goto out;
ret = krb5_init_creds_set_service(context, ctx, in_tkt_service);
if (ret)
goto out;
ret = krb5_init_creds_set_keytab(context, ctx, keytab);
if (ret)
goto out;
ret = krb5_init_creds_get(context, ctx);
if (ret == 0)
krb5_process_last_request(context, options, ctx);
out:
krb5_kt_free_entry(context, &ktent);
if (ret == 0)
krb5_init_creds_get_creds(context, ctx, creds);
if (ctx)
krb5_init_creds_free(context, ctx);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-320/c/good_857_0 |
crossvul-cpp_data_bad_857_2 | /*
* Copyright (c) 2003 - 2016 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Portions Copyright (c) 2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "krb5_locl.h"
struct krb5_dh_moduli {
char *name;
unsigned long bits;
heim_integer p;
heim_integer g;
heim_integer q;
};
#ifdef PKINIT
#include <cms_asn1.h>
#include <pkcs8_asn1.h>
#include <pkcs9_asn1.h>
#include <pkcs12_asn1.h>
#include <pkinit_asn1.h>
#include <asn1_err.h>
#include <der.h>
struct krb5_pk_cert {
hx509_cert cert;
};
static void
pk_copy_error(krb5_context context,
hx509_context hx509ctx,
int hxret,
const char *fmt,
...)
__attribute__ ((__format__ (__printf__, 4, 5)));
/*
*
*/
KRB5_LIB_FUNCTION void KRB5_LIB_CALL
_krb5_pk_cert_free(struct krb5_pk_cert *cert)
{
if (cert->cert) {
hx509_cert_free(cert->cert);
}
free(cert);
}
static krb5_error_code
BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer)
{
integer->length = BN_num_bytes(bn);
integer->data = malloc(integer->length);
if (integer->data == NULL) {
krb5_clear_error_message(context);
return ENOMEM;
}
BN_bn2bin(bn, integer->data);
integer->negative = BN_is_negative(bn);
return 0;
}
static BIGNUM *
integer_to_BN(krb5_context context, const char *field, const heim_integer *f)
{
BIGNUM *bn;
bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
if (bn == NULL) {
krb5_set_error_message(context, ENOMEM,
N_("PKINIT: parsing BN failed %s", ""), field);
return NULL;
}
BN_set_negative(bn, f->negative);
return bn;
}
static krb5_error_code
select_dh_group(krb5_context context, DH *dh, unsigned long bits,
struct krb5_dh_moduli **moduli)
{
const struct krb5_dh_moduli *m;
if (bits == 0) {
m = moduli[1]; /* XXX */
if (m == NULL)
m = moduli[0]; /* XXX */
} else {
int i;
for (i = 0; moduli[i] != NULL; i++) {
if (bits < moduli[i]->bits)
break;
}
if (moduli[i] == NULL) {
krb5_set_error_message(context, EINVAL,
N_("Did not find a DH group parameter "
"matching requirement of %lu bits", ""),
bits);
return EINVAL;
}
m = moduli[i];
}
dh->p = integer_to_BN(context, "p", &m->p);
if (dh->p == NULL)
return ENOMEM;
dh->g = integer_to_BN(context, "g", &m->g);
if (dh->g == NULL)
return ENOMEM;
dh->q = integer_to_BN(context, "q", &m->q);
if (dh->q == NULL)
return ENOMEM;
return 0;
}
struct certfind {
const char *type;
const heim_oid *oid;
};
/*
* Try searchin the key by to use by first looking for for PK-INIT
* EKU, then the Microsoft smart card EKU and last, no special EKU at all.
*/
static krb5_error_code
find_cert(krb5_context context, struct krb5_pk_identity *id,
hx509_query *q, hx509_cert *cert)
{
struct certfind cf[4] = {
{ "MobileMe EKU", NULL },
{ "PKINIT EKU", NULL },
{ "MS EKU", NULL },
{ "any (or no)", NULL }
};
int ret = HX509_CERT_NOT_FOUND;
size_t i, start = 1;
unsigned oids[] = { 1, 2, 840, 113635, 100, 3, 2, 1 };
const heim_oid mobileMe = { sizeof(oids)/sizeof(oids[0]), oids };
if (id->flags & PKINIT_BTMM)
start = 0;
cf[0].oid = &mobileMe;
cf[1].oid = &asn1_oid_id_pkekuoid;
cf[2].oid = &asn1_oid_id_pkinit_ms_eku;
cf[3].oid = NULL;
for (i = start; i < sizeof(cf)/sizeof(cf[0]); i++) {
ret = hx509_query_match_eku(q, cf[i].oid);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed setting %s OID", cf[i].type);
return ret;
}
ret = hx509_certs_find(context->hx509ctx, id->certs, q, cert);
if (ret == 0)
break;
pk_copy_error(context, context->hx509ctx, ret,
"Failed finding certificate with %s OID", cf[i].type);
}
return ret;
}
static krb5_error_code
create_signature(krb5_context context,
const heim_oid *eContentType,
krb5_data *eContent,
struct krb5_pk_identity *id,
hx509_peer_info peer,
krb5_data *sd_data)
{
int ret, flags = 0;
if (id->cert == NULL)
flags |= HX509_CMS_SIGNATURE_NO_SIGNER;
ret = hx509_cms_create_signed_1(context->hx509ctx,
flags,
eContentType,
eContent->data,
eContent->length,
NULL,
id->cert,
peer,
NULL,
id->certs,
sd_data);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Create CMS signedData");
return ret;
}
return 0;
}
static int
cert2epi(hx509_context context, void *ctx, hx509_cert c)
{
ExternalPrincipalIdentifiers *ids = ctx;
ExternalPrincipalIdentifier id;
hx509_name subject = NULL;
void *p;
int ret;
if (ids->len > 10)
return 0;
memset(&id, 0, sizeof(id));
ret = hx509_cert_get_subject(c, &subject);
if (ret)
return ret;
if (hx509_name_is_null_p(subject) != 0) {
id.subjectName = calloc(1, sizeof(*id.subjectName));
if (id.subjectName == NULL) {
hx509_name_free(&subject);
free_ExternalPrincipalIdentifier(&id);
return ENOMEM;
}
ret = hx509_name_binary(subject, id.subjectName);
if (ret) {
hx509_name_free(&subject);
free_ExternalPrincipalIdentifier(&id);
return ret;
}
}
hx509_name_free(&subject);
id.issuerAndSerialNumber = calloc(1, sizeof(*id.issuerAndSerialNumber));
if (id.issuerAndSerialNumber == NULL) {
free_ExternalPrincipalIdentifier(&id);
return ENOMEM;
}
{
IssuerAndSerialNumber iasn;
hx509_name issuer;
size_t size = 0;
memset(&iasn, 0, sizeof(iasn));
ret = hx509_cert_get_issuer(c, &issuer);
if (ret) {
free_ExternalPrincipalIdentifier(&id);
return ret;
}
ret = hx509_name_to_Name(issuer, &iasn.issuer);
hx509_name_free(&issuer);
if (ret) {
free_ExternalPrincipalIdentifier(&id);
return ret;
}
ret = hx509_cert_get_serialnumber(c, &iasn.serialNumber);
if (ret) {
free_IssuerAndSerialNumber(&iasn);
free_ExternalPrincipalIdentifier(&id);
return ret;
}
ASN1_MALLOC_ENCODE(IssuerAndSerialNumber,
id.issuerAndSerialNumber->data,
id.issuerAndSerialNumber->length,
&iasn, &size, ret);
free_IssuerAndSerialNumber(&iasn);
if (ret) {
free_ExternalPrincipalIdentifier(&id);
return ret;
}
if (id.issuerAndSerialNumber->length != size)
abort();
}
id.subjectKeyIdentifier = NULL;
p = realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1));
if (p == NULL) {
free_ExternalPrincipalIdentifier(&id);
return ENOMEM;
}
ids->val = p;
ids->val[ids->len] = id;
ids->len++;
return 0;
}
static krb5_error_code
build_edi(krb5_context context,
hx509_context hx509ctx,
hx509_certs certs,
ExternalPrincipalIdentifiers *ids)
{
return hx509_certs_iter_f(hx509ctx, certs, cert2epi, ids);
}
static krb5_error_code
build_auth_pack(krb5_context context,
unsigned nonce,
krb5_pk_init_ctx ctx,
const KDC_REQ_BODY *body,
AuthPack *a)
{
size_t buf_size, len = 0;
krb5_error_code ret;
void *buf;
krb5_timestamp sec;
int32_t usec;
Checksum checksum;
krb5_clear_error_message(context);
memset(&checksum, 0, sizeof(checksum));
krb5_us_timeofday(context, &sec, &usec);
a->pkAuthenticator.ctime = sec;
a->pkAuthenticator.nonce = nonce;
ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret);
if (ret)
return ret;
if (buf_size != len)
krb5_abortx(context, "internal error in ASN.1 encoder");
ret = krb5_create_checksum(context,
NULL,
0,
CKSUMTYPE_SHA1,
buf,
len,
&checksum);
free(buf);
if (ret)
return ret;
ALLOC(a->pkAuthenticator.paChecksum, 1);
if (a->pkAuthenticator.paChecksum == NULL) {
return krb5_enomem(context);
}
ret = krb5_data_copy(a->pkAuthenticator.paChecksum,
checksum.checksum.data, checksum.checksum.length);
free_Checksum(&checksum);
if (ret)
return ret;
if (ctx->keyex == USE_DH || ctx->keyex == USE_ECDH) {
const char *moduli_file;
unsigned long dh_min_bits;
krb5_data dhbuf;
size_t size = 0;
krb5_data_zero(&dhbuf);
moduli_file = krb5_config_get_string(context, NULL,
"libdefaults",
"moduli",
NULL);
dh_min_bits =
krb5_config_get_int_default(context, NULL, 0,
"libdefaults",
"pkinit_dh_min_bits",
NULL);
ret = _krb5_parse_moduli(context, moduli_file, &ctx->m);
if (ret)
return ret;
ctx->u.dh = DH_new();
if (ctx->u.dh == NULL)
return krb5_enomem(context);
ret = select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m);
if (ret)
return ret;
if (DH_generate_key(ctx->u.dh) != 1) {
krb5_set_error_message(context, ENOMEM,
N_("pkinit: failed to generate DH key", ""));
return ENOMEM;
}
if (1 /* support_cached_dh */) {
ALLOC(a->clientDHNonce, 1);
if (a->clientDHNonce == NULL) {
krb5_clear_error_message(context);
return ENOMEM;
}
ret = krb5_data_alloc(a->clientDHNonce, 40);
if (a->clientDHNonce == NULL) {
krb5_clear_error_message(context);
return ret;
}
RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length);
ret = krb5_copy_data(context, a->clientDHNonce,
&ctx->clientDHNonce);
if (ret)
return ret;
}
ALLOC(a->clientPublicValue, 1);
if (a->clientPublicValue == NULL)
return ENOMEM;
if (ctx->keyex == USE_DH) {
DH *dh = ctx->u.dh;
DomainParameters dp;
heim_integer dh_pub_key;
ret = der_copy_oid(&asn1_oid_id_dhpublicnumber,
&a->clientPublicValue->algorithm.algorithm);
if (ret)
return ret;
memset(&dp, 0, sizeof(dp));
ret = BN_to_integer(context, dh->p, &dp.p);
if (ret) {
free_DomainParameters(&dp);
return ret;
}
ret = BN_to_integer(context, dh->g, &dp.g);
if (ret) {
free_DomainParameters(&dp);
return ret;
}
dp.q = calloc(1, sizeof(*dp.q));
if (dp.q == NULL) {
free_DomainParameters(&dp);
return ENOMEM;
}
ret = BN_to_integer(context, dh->q, dp.q);
if (ret) {
free_DomainParameters(&dp);
return ret;
}
dp.j = NULL;
dp.validationParms = NULL;
a->clientPublicValue->algorithm.parameters =
malloc(sizeof(*a->clientPublicValue->algorithm.parameters));
if (a->clientPublicValue->algorithm.parameters == NULL) {
free_DomainParameters(&dp);
return ret;
}
ASN1_MALLOC_ENCODE(DomainParameters,
a->clientPublicValue->algorithm.parameters->data,
a->clientPublicValue->algorithm.parameters->length,
&dp, &size, ret);
free_DomainParameters(&dp);
if (ret)
return ret;
if (size != a->clientPublicValue->algorithm.parameters->length)
krb5_abortx(context, "Internal ASN1 encoder error");
ret = BN_to_integer(context, dh->pub_key, &dh_pub_key);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length,
&dh_pub_key, &size, ret);
der_free_heim_integer(&dh_pub_key);
if (ret)
return ret;
if (size != dhbuf.length)
krb5_abortx(context, "asn1 internal error");
a->clientPublicValue->subjectPublicKey.length = dhbuf.length * 8;
a->clientPublicValue->subjectPublicKey.data = dhbuf.data;
} else if (ctx->keyex == USE_ECDH) {
ret = _krb5_build_authpack_subjectPK_EC(context, ctx, a);
if (ret)
return ret;
} else
krb5_abortx(context, "internal error");
}
{
a->supportedCMSTypes = calloc(1, sizeof(*a->supportedCMSTypes));
if (a->supportedCMSTypes == NULL)
return ENOMEM;
ret = hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL,
ctx->id->cert,
&a->supportedCMSTypes->val,
&a->supportedCMSTypes->len);
if (ret)
return ret;
}
return ret;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_pk_mk_ContentInfo(krb5_context context,
const krb5_data *buf,
const heim_oid *oid,
struct ContentInfo *content_info)
{
krb5_error_code ret;
ret = der_copy_oid(oid, &content_info->contentType);
if (ret)
return ret;
ALLOC(content_info->content, 1);
if (content_info->content == NULL)
return ENOMEM;
content_info->content->data = malloc(buf->length);
if (content_info->content->data == NULL)
return ENOMEM;
memcpy(content_info->content->data, buf->data, buf->length);
content_info->content->length = buf->length;
return 0;
}
static krb5_error_code
pk_mk_padata(krb5_context context,
krb5_pk_init_ctx ctx,
const KDC_REQ_BODY *req_body,
unsigned nonce,
METHOD_DATA *md)
{
struct ContentInfo content_info;
krb5_error_code ret;
const heim_oid *oid = NULL;
size_t size = 0;
krb5_data buf, sd_buf;
int pa_type = -1;
krb5_data_zero(&buf);
krb5_data_zero(&sd_buf);
memset(&content_info, 0, sizeof(content_info));
if (ctx->type == PKINIT_WIN2K) {
AuthPack_Win2k ap;
krb5_timestamp sec;
int32_t usec;
memset(&ap, 0, sizeof(ap));
/* fill in PKAuthenticator */
ret = copy_PrincipalName(req_body->sname, &ap.pkAuthenticator.kdcName);
if (ret) {
free_AuthPack_Win2k(&ap);
krb5_clear_error_message(context);
goto out;
}
ret = copy_Realm(&req_body->realm, &ap.pkAuthenticator.kdcRealm);
if (ret) {
free_AuthPack_Win2k(&ap);
krb5_clear_error_message(context);
goto out;
}
krb5_us_timeofday(context, &sec, &usec);
ap.pkAuthenticator.ctime = sec;
ap.pkAuthenticator.cusec = usec;
ap.pkAuthenticator.nonce = nonce;
ASN1_MALLOC_ENCODE(AuthPack_Win2k, buf.data, buf.length,
&ap, &size, ret);
free_AuthPack_Win2k(&ap);
if (ret) {
krb5_set_error_message(context, ret,
N_("Failed encoding AuthPackWin: %d", ""),
(int)ret);
goto out;
}
if (buf.length != size)
krb5_abortx(context, "internal ASN1 encoder error");
oid = &asn1_oid_id_pkcs7_data;
} else if (ctx->type == PKINIT_27) {
AuthPack ap;
memset(&ap, 0, sizeof(ap));
ret = build_auth_pack(context, nonce, ctx, req_body, &ap);
if (ret) {
free_AuthPack(&ap);
goto out;
}
ASN1_MALLOC_ENCODE(AuthPack, buf.data, buf.length, &ap, &size, ret);
free_AuthPack(&ap);
if (ret) {
krb5_set_error_message(context, ret,
N_("Failed encoding AuthPack: %d", ""),
(int)ret);
goto out;
}
if (buf.length != size)
krb5_abortx(context, "internal ASN1 encoder error");
oid = &asn1_oid_id_pkauthdata;
} else
krb5_abortx(context, "internal pkinit error");
ret = create_signature(context, oid, &buf, ctx->id,
ctx->peer, &sd_buf);
krb5_data_free(&buf);
if (ret)
goto out;
ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &sd_buf, &buf);
krb5_data_free(&sd_buf);
if (ret) {
krb5_set_error_message(context, ret,
N_("ContentInfo wrapping of signedData failed",""));
goto out;
}
if (ctx->type == PKINIT_WIN2K) {
PA_PK_AS_REQ_Win2k winreq;
pa_type = KRB5_PADATA_PK_AS_REQ_WIN;
memset(&winreq, 0, sizeof(winreq));
winreq.signed_auth_pack = buf;
ASN1_MALLOC_ENCODE(PA_PK_AS_REQ_Win2k, buf.data, buf.length,
&winreq, &size, ret);
free_PA_PK_AS_REQ_Win2k(&winreq);
} else if (ctx->type == PKINIT_27) {
PA_PK_AS_REQ req;
pa_type = KRB5_PADATA_PK_AS_REQ;
memset(&req, 0, sizeof(req));
req.signedAuthPack = buf;
if (ctx->trustedCertifiers) {
req.trustedCertifiers = calloc(1, sizeof(*req.trustedCertifiers));
if (req.trustedCertifiers == NULL) {
ret = krb5_enomem(context);
free_PA_PK_AS_REQ(&req);
goto out;
}
ret = build_edi(context, context->hx509ctx,
ctx->id->anchors, req.trustedCertifiers);
if (ret) {
krb5_set_error_message(context, ret,
N_("pk-init: failed to build "
"trustedCertifiers", ""));
free_PA_PK_AS_REQ(&req);
goto out;
}
}
req.kdcPkId = NULL;
ASN1_MALLOC_ENCODE(PA_PK_AS_REQ, buf.data, buf.length,
&req, &size, ret);
free_PA_PK_AS_REQ(&req);
} else
krb5_abortx(context, "internal pkinit error");
if (ret) {
krb5_set_error_message(context, ret, "PA-PK-AS-REQ %d", (int)ret);
goto out;
}
if (buf.length != size)
krb5_abortx(context, "Internal ASN1 encoder error");
ret = krb5_padata_add(context, md, pa_type, buf.data, buf.length);
if (ret)
free(buf.data);
if (ret == 0)
krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0);
out:
free_ContentInfo(&content_info);
return ret;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_pk_mk_padata(krb5_context context,
void *c,
int ic_flags,
int win2k,
const KDC_REQ_BODY *req_body,
unsigned nonce,
METHOD_DATA *md)
{
krb5_pk_init_ctx ctx = c;
int win2k_compat;
if (ctx->id->certs == NULL && ctx->anonymous == 0) {
krb5_set_error_message(context, HEIM_PKINIT_NO_PRIVATE_KEY,
N_("PKINIT: No user certificate given", ""));
return HEIM_PKINIT_NO_PRIVATE_KEY;
}
win2k_compat = krb5_config_get_bool_default(context, NULL,
win2k,
"realms",
req_body->realm,
"pkinit_win2k",
NULL);
if (win2k_compat) {
ctx->require_binding =
krb5_config_get_bool_default(context, NULL,
TRUE,
"realms",
req_body->realm,
"pkinit_win2k_require_binding",
NULL);
ctx->type = PKINIT_WIN2K;
} else
ctx->type = PKINIT_27;
ctx->require_eku =
krb5_config_get_bool_default(context, NULL,
TRUE,
"realms",
req_body->realm,
"pkinit_require_eku",
NULL);
if (ic_flags & KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK)
ctx->require_eku = 0;
if (ctx->id->flags & PKINIT_BTMM)
ctx->require_eku = 0;
ctx->require_krbtgt_otherName =
krb5_config_get_bool_default(context, NULL,
TRUE,
"realms",
req_body->realm,
"pkinit_require_krbtgt_otherName",
NULL);
ctx->require_hostname_match =
krb5_config_get_bool_default(context, NULL,
FALSE,
"realms",
req_body->realm,
"pkinit_require_hostname_match",
NULL);
ctx->trustedCertifiers =
krb5_config_get_bool_default(context, NULL,
TRUE,
"realms",
req_body->realm,
"pkinit_trustedCertifiers",
NULL);
return pk_mk_padata(context, ctx, req_body, nonce, md);
}
static krb5_error_code
pk_verify_sign(krb5_context context,
const void *data,
size_t length,
struct krb5_pk_identity *id,
heim_oid *contentType,
krb5_data *content,
struct krb5_pk_cert **signer)
{
hx509_certs signer_certs;
int ret, flags = 0;
/* BTMM is broken in Leo and SnowLeo */
if (id->flags & PKINIT_BTMM) {
flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH;
flags |= HX509_CMS_VS_NO_KU_CHECK;
flags |= HX509_CMS_VS_NO_VALIDATE;
}
*signer = NULL;
ret = hx509_cms_verify_signed(context->hx509ctx,
id->verify_ctx,
flags,
data,
length,
NULL,
id->certpool,
contentType,
content,
&signer_certs);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"CMS verify signed failed");
return ret;
}
*signer = calloc(1, sizeof(**signer));
if (*signer == NULL) {
krb5_clear_error_message(context);
ret = ENOMEM;
goto out;
}
ret = hx509_get_one_cert(context->hx509ctx, signer_certs, &(*signer)->cert);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to get on of the signer certs");
goto out;
}
out:
hx509_certs_free(&signer_certs);
if (ret) {
if (*signer) {
hx509_cert_free((*signer)->cert);
free(*signer);
*signer = NULL;
}
}
return ret;
}
static krb5_error_code
get_reply_key_win(krb5_context context,
const krb5_data *content,
unsigned nonce,
krb5_keyblock **key)
{
ReplyKeyPack_Win2k key_pack;
krb5_error_code ret;
size_t size;
ret = decode_ReplyKeyPack_Win2k(content->data,
content->length,
&key_pack,
&size);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT decoding reply key failed", ""));
free_ReplyKeyPack_Win2k(&key_pack);
return ret;
}
if ((unsigned)key_pack.nonce != nonce) {
krb5_set_error_message(context, ret,
N_("PKINIT enckey nonce is wrong", ""));
free_ReplyKeyPack_Win2k(&key_pack);
return KRB5KRB_AP_ERR_MODIFIED;
}
*key = malloc (sizeof (**key));
if (*key == NULL) {
free_ReplyKeyPack_Win2k(&key_pack);
return krb5_enomem(context);
}
ret = copy_EncryptionKey(&key_pack.replyKey, *key);
free_ReplyKeyPack_Win2k(&key_pack);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT failed copying reply key", ""));
free(*key);
*key = NULL;
}
return ret;
}
static krb5_error_code
get_reply_key(krb5_context context,
const krb5_data *content,
const krb5_data *req_buffer,
krb5_keyblock **key)
{
ReplyKeyPack key_pack;
krb5_error_code ret;
size_t size;
ret = decode_ReplyKeyPack(content->data,
content->length,
&key_pack,
&size);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT decoding reply key failed", ""));
free_ReplyKeyPack(&key_pack);
return ret;
}
{
krb5_crypto crypto;
/*
* XXX Verify kp.replyKey is a allowed enctype in the
* configuration file
*/
ret = krb5_crypto_init(context, &key_pack.replyKey, 0, &crypto);
if (ret) {
free_ReplyKeyPack(&key_pack);
return ret;
}
ret = krb5_verify_checksum(context, crypto, 6,
req_buffer->data, req_buffer->length,
&key_pack.asChecksum);
krb5_crypto_destroy(context, crypto);
if (ret) {
free_ReplyKeyPack(&key_pack);
return ret;
}
}
*key = malloc (sizeof (**key));
if (*key == NULL) {
free_ReplyKeyPack(&key_pack);
return krb5_enomem(context);
}
ret = copy_EncryptionKey(&key_pack.replyKey, *key);
free_ReplyKeyPack(&key_pack);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT failed copying reply key", ""));
free(*key);
*key = NULL;
}
return ret;
}
static krb5_error_code
pk_verify_host(krb5_context context,
const char *realm,
const krb5_krbhst_info *hi,
struct krb5_pk_init_ctx_data *ctx,
struct krb5_pk_cert *host)
{
krb5_error_code ret = 0;
if (ctx->require_eku) {
ret = hx509_cert_check_eku(context->hx509ctx, host->cert,
&asn1_oid_id_pkkdcekuoid, 0);
if (ret) {
krb5_set_error_message(context, ret,
N_("No PK-INIT KDC EKU in kdc certificate", ""));
return ret;
}
}
if (ctx->require_krbtgt_otherName) {
hx509_octet_string_list list;
size_t i;
int matched = 0;
ret = hx509_cert_find_subjectAltName_otherName(context->hx509ctx,
host->cert,
&asn1_oid_id_pkinit_san,
&list);
if (ret) {
krb5_set_error_message(context, ret,
N_("Failed to find the PK-INIT "
"subjectAltName in the KDC "
"certificate", ""));
return ret;
}
/*
* subjectAltNames are multi-valued, and a single KDC may serve
* multiple realms. The SAN validation here must accept
* the KDC's cert if *any* of the SANs match the expected KDC.
* It is OK for *some* of the SANs to not match, provided at least
* one does.
*/
for (i = 0; matched == 0 && i < list.len; i++) {
KRB5PrincipalName r;
ret = decode_KRB5PrincipalName(list.val[i].data,
list.val[i].length,
&r,
NULL);
if (ret) {
krb5_set_error_message(context, ret,
N_("Failed to decode the PK-INIT "
"subjectAltName in the "
"KDC certificate", ""));
break;
}
if (r.principalName.name_string.len == 2 &&
strcmp(r.principalName.name_string.val[0], KRB5_TGS_NAME) == 0
&& strcmp(r.principalName.name_string.val[1], realm) == 0
&& strcmp(r.realm, realm) == 0)
matched = 1;
free_KRB5PrincipalName(&r);
}
hx509_free_octet_string_list(&list);
if (matched == 0) {
ret = KRB5_KDC_ERR_INVALID_CERTIFICATE;
/* XXX: Lost in translation... */
krb5_set_error_message(context, ret,
N_("KDC have wrong realm name in "
"the certificate", ""));
}
}
if (ret)
return ret;
if (hi) {
ret = hx509_verify_hostname(context->hx509ctx, host->cert,
ctx->require_hostname_match,
HX509_HN_HOSTNAME,
hi->hostname,
hi->ai->ai_addr, hi->ai->ai_addrlen);
if (ret)
krb5_set_error_message(context, ret,
N_("Address mismatch in "
"the KDC certificate", ""));
}
return ret;
}
static krb5_error_code
pk_rd_pa_reply_enckey(krb5_context context,
int type,
const heim_octet_string *indata,
const heim_oid *dataType,
const char *realm,
krb5_pk_init_ctx ctx,
krb5_enctype etype,
const krb5_krbhst_info *hi,
unsigned nonce,
const krb5_data *req_buffer,
PA_DATA *pa,
krb5_keyblock **key)
{
krb5_error_code ret;
struct krb5_pk_cert *host = NULL;
krb5_data content;
heim_oid contentType = { 0, NULL };
int flags = HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT;
if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_envelopedData, dataType)) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: Invalid content type", ""));
return EINVAL;
}
if (ctx->type == PKINIT_WIN2K)
flags |= HX509_CMS_UE_ALLOW_WEAK;
ret = hx509_cms_unenvelope(context->hx509ctx,
ctx->id->certs,
flags,
indata->data,
indata->length,
NULL,
0,
&contentType,
&content);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to unenvelope CMS data in PK-INIT reply");
return ret;
}
der_free_oid(&contentType);
/* win2k uses ContentInfo */
if (type == PKINIT_WIN2K) {
heim_oid type2;
heim_octet_string out;
ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL);
if (ret) {
/* windows LH with interesting CMS packets */
size_t ph = 1 + der_length_len(content.length);
unsigned char *ptr = malloc(content.length + ph);
size_t l;
memcpy(ptr + ph, content.data, content.length);
ret = der_put_length_and_tag (ptr + ph - 1, ph, content.length,
ASN1_C_UNIV, CONS, UT_Sequence, &l);
if (ret) {
free(ptr);
return ret;
}
free(content.data);
content.data = ptr;
content.length += ph;
ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL);
if (ret)
goto out;
}
if (der_heim_oid_cmp(&type2, &asn1_oid_id_pkcs7_signedData)) {
ret = EINVAL; /* XXX */
krb5_set_error_message(context, ret,
N_("PKINIT: Invalid content type", ""));
der_free_oid(&type2);
der_free_octet_string(&out);
goto out;
}
der_free_oid(&type2);
krb5_data_free(&content);
ret = krb5_data_copy(&content, out.data, out.length);
der_free_octet_string(&out);
if (ret) {
krb5_set_error_message(context, ret,
N_("malloc: out of memory", ""));
goto out;
}
}
ret = pk_verify_sign(context,
content.data,
content.length,
ctx->id,
&contentType,
&content,
&host);
if (ret)
goto out;
/* make sure that it is the kdc's certificate */
ret = pk_verify_host(context, realm, hi, ctx, host);
if (ret) {
goto out;
}
#if 0
if (type == PKINIT_WIN2K) {
if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) != 0) {
ret = KRB5KRB_AP_ERR_MSG_TYPE;
krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
goto out;
}
} else {
if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkrkeydata) != 0) {
ret = KRB5KRB_AP_ERR_MSG_TYPE;
krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
goto out;
}
}
#endif
switch(type) {
case PKINIT_WIN2K:
ret = get_reply_key(context, &content, req_buffer, key);
if (ret != 0 && ctx->require_binding == 0)
ret = get_reply_key_win(context, &content, nonce, key);
break;
case PKINIT_27:
ret = get_reply_key(context, &content, req_buffer, key);
break;
}
if (ret)
goto out;
/* XXX compare given etype with key->etype */
out:
if (host)
_krb5_pk_cert_free(host);
der_free_oid(&contentType);
krb5_data_free(&content);
return ret;
}
static krb5_error_code
pk_rd_pa_reply_dh(krb5_context context,
const heim_octet_string *indata,
const heim_oid *dataType,
const char *realm,
krb5_pk_init_ctx ctx,
krb5_enctype etype,
const krb5_krbhst_info *hi,
const DHNonce *c_n,
const DHNonce *k_n,
unsigned nonce,
PA_DATA *pa,
krb5_keyblock **key)
{
const unsigned char *p;
unsigned char *dh_gen_key = NULL;
struct krb5_pk_cert *host = NULL;
BIGNUM *kdc_dh_pubkey = NULL;
KDCDHKeyInfo kdc_dh_info;
heim_oid contentType = { 0, NULL };
krb5_data content;
krb5_error_code ret;
int dh_gen_keylen = 0;
size_t size;
krb5_data_zero(&content);
memset(&kdc_dh_info, 0, sizeof(kdc_dh_info));
if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_signedData, dataType)) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: Invalid content type", ""));
return EINVAL;
}
ret = pk_verify_sign(context,
indata->data,
indata->length,
ctx->id,
&contentType,
&content,
&host);
if (ret)
goto out;
/* make sure that it is the kdc's certificate */
ret = pk_verify_host(context, realm, hi, ctx, host);
if (ret)
goto out;
if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkdhkeydata)) {
ret = KRB5KRB_AP_ERR_MSG_TYPE;
krb5_set_error_message(context, ret,
N_("pkinit - dh reply contains wrong oid", ""));
goto out;
}
ret = decode_KDCDHKeyInfo(content.data,
content.length,
&kdc_dh_info,
&size);
if (ret) {
krb5_set_error_message(context, ret,
N_("pkinit - failed to decode "
"KDC DH Key Info", ""));
goto out;
}
if (kdc_dh_info.nonce != nonce) {
ret = KRB5KRB_AP_ERR_MODIFIED;
krb5_set_error_message(context, ret,
N_("PKINIT: DH nonce is wrong", ""));
goto out;
}
if (kdc_dh_info.dhKeyExpiration) {
if (k_n == NULL) {
ret = KRB5KRB_ERR_GENERIC;
krb5_set_error_message(context, ret,
N_("pkinit; got key expiration "
"without server nonce", ""));
goto out;
}
if (c_n == NULL) {
ret = KRB5KRB_ERR_GENERIC;
krb5_set_error_message(context, ret,
N_("pkinit; got DH reuse but no "
"client nonce", ""));
goto out;
}
} else {
if (k_n) {
ret = KRB5KRB_ERR_GENERIC;
krb5_set_error_message(context, ret,
N_("pkinit: got server nonce "
"without key expiration", ""));
goto out;
}
c_n = NULL;
}
p = kdc_dh_info.subjectPublicKey.data;
size = (kdc_dh_info.subjectPublicKey.length + 7) / 8;
if (ctx->keyex == USE_DH) {
DHPublicKey k;
ret = decode_DHPublicKey(p, size, &k, NULL);
if (ret) {
krb5_set_error_message(context, ret,
N_("pkinit: can't decode "
"without key expiration", ""));
goto out;
}
kdc_dh_pubkey = integer_to_BN(context, "DHPublicKey", &k);
free_DHPublicKey(&k);
if (kdc_dh_pubkey == NULL) {
ret = ENOMEM;
goto out;
}
size = DH_size(ctx->u.dh);
dh_gen_key = malloc(size);
if (dh_gen_key == NULL) {
ret = krb5_enomem(context);
goto out;
}
dh_gen_keylen = DH_compute_key(dh_gen_key, kdc_dh_pubkey, ctx->u.dh);
if (dh_gen_keylen == -1) {
ret = KRB5KRB_ERR_GENERIC;
dh_gen_keylen = 0;
krb5_set_error_message(context, ret,
N_("PKINIT: Can't compute Diffie-Hellman key", ""));
goto out;
}
if (dh_gen_keylen < (int)size) {
size -= dh_gen_keylen;
memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen);
memset(dh_gen_key, 0, size);
}
} else {
ret = _krb5_pk_rd_pa_reply_ecdh_compute_key(context, ctx, p,
size, &dh_gen_key,
&dh_gen_keylen);
if (ret)
goto out;
}
if (dh_gen_keylen <= 0) {
ret = EINVAL;
krb5_set_error_message(context, ret,
N_("PKINIT: resulting DH key <= 0", ""));
dh_gen_keylen = 0;
goto out;
}
*key = malloc (sizeof (**key));
if (*key == NULL) {
ret = krb5_enomem(context);
goto out;
}
ret = _krb5_pk_octetstring2key(context,
etype,
dh_gen_key, dh_gen_keylen,
c_n, k_n,
*key);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT: can't create key from DH key", ""));
free(*key);
*key = NULL;
goto out;
}
out:
if (kdc_dh_pubkey)
BN_free(kdc_dh_pubkey);
if (dh_gen_key) {
memset(dh_gen_key, 0, dh_gen_keylen);
free(dh_gen_key);
}
if (host)
_krb5_pk_cert_free(host);
if (content.data)
krb5_data_free(&content);
der_free_oid(&contentType);
free_KDCDHKeyInfo(&kdc_dh_info);
return ret;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_pk_rd_pa_reply(krb5_context context,
const char *realm,
void *c,
krb5_enctype etype,
const krb5_krbhst_info *hi,
unsigned nonce,
const krb5_data *req_buffer,
PA_DATA *pa,
krb5_keyblock **key)
{
krb5_pk_init_ctx ctx = c;
krb5_error_code ret;
size_t size;
/* Check for IETF PK-INIT first */
if (ctx->type == PKINIT_27) {
PA_PK_AS_REP rep;
heim_octet_string os, data;
heim_oid oid;
if (pa->padata_type != KRB5_PADATA_PK_AS_REP) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: wrong padata recv", ""));
return EINVAL;
}
ret = decode_PA_PK_AS_REP(pa->padata_value.data,
pa->padata_value.length,
&rep,
&size);
if (ret) {
krb5_set_error_message(context, ret,
N_("Failed to decode pkinit AS rep", ""));
return ret;
}
switch (rep.element) {
case choice_PA_PK_AS_REP_dhInfo:
_krb5_debug(context, 5, "krb5_get_init_creds: using pkinit dh");
os = rep.u.dhInfo.dhSignedData;
break;
case choice_PA_PK_AS_REP_encKeyPack:
_krb5_debug(context, 5, "krb5_get_init_creds: using kinit enc reply key");
os = rep.u.encKeyPack;
break;
default: {
PA_PK_AS_REP_BTMM btmm;
free_PA_PK_AS_REP(&rep);
memset(&rep, 0, sizeof(rep));
_krb5_debug(context, 5, "krb5_get_init_creds: using BTMM kinit enc reply key");
ret = decode_PA_PK_AS_REP_BTMM(pa->padata_value.data,
pa->padata_value.length,
&btmm,
&size);
if (ret) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: -27 reply "
"invalid content type", ""));
return EINVAL;
}
if (btmm.dhSignedData || btmm.encKeyPack == NULL) {
free_PA_PK_AS_REP_BTMM(&btmm);
ret = EINVAL;
krb5_set_error_message(context, ret,
N_("DH mode not supported for BTMM mode", ""));
return ret;
}
/*
* Transform to IETF style PK-INIT reply so that free works below
*/
rep.element = choice_PA_PK_AS_REP_encKeyPack;
rep.u.encKeyPack.data = btmm.encKeyPack->data;
rep.u.encKeyPack.length = btmm.encKeyPack->length;
btmm.encKeyPack->data = NULL;
btmm.encKeyPack->length = 0;
free_PA_PK_AS_REP_BTMM(&btmm);
os = rep.u.encKeyPack;
}
}
ret = hx509_cms_unwrap_ContentInfo(&os, &oid, &data, NULL);
if (ret) {
free_PA_PK_AS_REP(&rep);
krb5_set_error_message(context, ret,
N_("PKINIT: failed to unwrap CI", ""));
return ret;
}
switch (rep.element) {
case choice_PA_PK_AS_REP_dhInfo:
ret = pk_rd_pa_reply_dh(context, &data, &oid, realm, ctx, etype, hi,
ctx->clientDHNonce,
rep.u.dhInfo.serverDHNonce,
nonce, pa, key);
break;
case choice_PA_PK_AS_REP_encKeyPack:
ret = pk_rd_pa_reply_enckey(context, PKINIT_27, &data, &oid, realm,
ctx, etype, hi, nonce, req_buffer, pa, key);
break;
default:
krb5_abortx(context, "pk-init as-rep case not possible to happen");
}
der_free_octet_string(&data);
der_free_oid(&oid);
free_PA_PK_AS_REP(&rep);
} else if (ctx->type == PKINIT_WIN2K) {
PA_PK_AS_REP_Win2k w2krep;
/* Check for Windows encoding of the AS-REP pa data */
#if 0 /* should this be ? */
if (pa->padata_type != KRB5_PADATA_PK_AS_REP) {
krb5_set_error_message(context, EINVAL,
"PKINIT: wrong padata recv");
return EINVAL;
}
#endif
memset(&w2krep, 0, sizeof(w2krep));
ret = decode_PA_PK_AS_REP_Win2k(pa->padata_value.data,
pa->padata_value.length,
&w2krep,
&size);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT: Failed decoding windows "
"pkinit reply %d", ""), (int)ret);
return ret;
}
krb5_clear_error_message(context);
switch (w2krep.element) {
case choice_PA_PK_AS_REP_Win2k_encKeyPack: {
heim_octet_string data;
heim_oid oid;
ret = hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack,
&oid, &data, NULL);
free_PA_PK_AS_REP_Win2k(&w2krep);
if (ret) {
krb5_set_error_message(context, ret,
N_("PKINIT: failed to unwrap CI", ""));
return ret;
}
ret = pk_rd_pa_reply_enckey(context, PKINIT_WIN2K, &data, &oid, realm,
ctx, etype, hi, nonce, req_buffer, pa, key);
der_free_octet_string(&data);
der_free_oid(&oid);
break;
}
default:
free_PA_PK_AS_REP_Win2k(&w2krep);
ret = EINVAL;
krb5_set_error_message(context, ret,
N_("PKINIT: win2k reply invalid "
"content type", ""));
break;
}
} else {
ret = EINVAL;
krb5_set_error_message(context, ret,
N_("PKINIT: unknown reply type", ""));
}
return ret;
}
struct prompter {
krb5_context context;
krb5_prompter_fct prompter;
void *prompter_data;
};
static int
hx_pass_prompter(void *data, const hx509_prompt *prompter)
{
krb5_error_code ret;
krb5_prompt prompt;
krb5_data password_data;
struct prompter *p = data;
password_data.data = prompter->reply.data;
password_data.length = prompter->reply.length;
prompt.prompt = prompter->prompt;
prompt.hidden = hx509_prompt_hidden(prompter->type);
prompt.reply = &password_data;
switch (prompter->type) {
case HX509_PROMPT_TYPE_INFO:
prompt.type = KRB5_PROMPT_TYPE_INFO;
break;
case HX509_PROMPT_TYPE_PASSWORD:
case HX509_PROMPT_TYPE_QUESTION:
default:
prompt.type = KRB5_PROMPT_TYPE_PASSWORD;
break;
}
ret = (*p->prompter)(p->context, p->prompter_data, NULL, NULL, 1, &prompt);
if (ret) {
memset (prompter->reply.data, 0, prompter->reply.length);
return 1;
}
return 0;
}
static krb5_error_code
_krb5_pk_set_user_id(krb5_context context,
krb5_principal principal,
krb5_pk_init_ctx ctx,
struct hx509_certs_data *certs)
{
hx509_certs c = hx509_certs_ref(certs);
hx509_query *q = NULL;
int ret;
if (ctx->id->certs)
hx509_certs_free(&ctx->id->certs);
if (ctx->id->cert) {
hx509_cert_free(ctx->id->cert);
ctx->id->cert = NULL;
}
ctx->id->certs = c;
ctx->anonymous = 0;
ret = hx509_query_alloc(context->hx509ctx, &q);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Allocate query to find signing certificate");
return ret;
}
hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
if (principal && strncmp("LKDC:SHA1.", krb5_principal_get_realm(context, principal), 9) == 0) {
ctx->id->flags |= PKINIT_BTMM;
}
ret = find_cert(context, ctx->id, q, &ctx->id->cert);
hx509_query_free(context->hx509ctx, q);
if (ret == 0 && _krb5_have_debug(context, 2)) {
hx509_name name;
char *str, *sn;
heim_integer i;
ret = hx509_cert_get_subject(ctx->id->cert, &name);
if (ret)
goto out;
ret = hx509_name_to_string(name, &str);
hx509_name_free(&name);
if (ret)
goto out;
ret = hx509_cert_get_serialnumber(ctx->id->cert, &i);
if (ret) {
free(str);
goto out;
}
ret = der_print_hex_heim_integer(&i, &sn);
der_free_heim_integer(&i);
if (ret) {
free(name);
goto out;
}
_krb5_debug(context, 2, "using cert: subject: %s sn: %s", str, sn);
free(str);
free(sn);
}
out:
return ret;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_pk_load_id(krb5_context context,
struct krb5_pk_identity **ret_id,
const char *user_id,
const char *anchor_id,
char * const *chain_list,
char * const *revoke_list,
krb5_prompter_fct prompter,
void *prompter_data,
char *password)
{
struct krb5_pk_identity *id = NULL;
struct prompter p;
int ret;
*ret_id = NULL;
if (anchor_id == NULL) {
krb5_set_error_message(context, HEIM_PKINIT_NO_VALID_CA,
N_("PKINIT: No anchor given", ""));
return HEIM_PKINIT_NO_VALID_CA;
}
/* load cert */
id = calloc(1, sizeof(*id));
if (id == NULL)
return krb5_enomem(context);
if (user_id) {
hx509_lock lock;
ret = hx509_lock_init(context->hx509ctx, &lock);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret, "Failed init lock");
goto out;
}
if (password && password[0])
hx509_lock_add_password(lock, password);
if (prompter) {
p.context = context;
p.prompter = prompter;
p.prompter_data = prompter_data;
ret = hx509_lock_set_prompter(lock, hx_pass_prompter, &p);
if (ret) {
hx509_lock_free(lock);
goto out;
}
}
ret = hx509_certs_init(context->hx509ctx, user_id, 0, lock, &id->certs);
hx509_lock_free(lock);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to init cert certs");
goto out;
}
} else {
id->certs = NULL;
}
ret = hx509_certs_init(context->hx509ctx, anchor_id, 0, NULL, &id->anchors);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to init anchors");
goto out;
}
ret = hx509_certs_init(context->hx509ctx, "MEMORY:pkinit-cert-chain",
0, NULL, &id->certpool);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to init chain");
goto out;
}
while (chain_list && *chain_list) {
ret = hx509_certs_append(context->hx509ctx, id->certpool,
NULL, *chain_list);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to laod chain %s",
*chain_list);
goto out;
}
chain_list++;
}
if (revoke_list) {
ret = hx509_revoke_init(context->hx509ctx, &id->revokectx);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed init revoke list");
goto out;
}
while (*revoke_list) {
ret = hx509_revoke_add_crl(context->hx509ctx,
id->revokectx,
*revoke_list);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed load revoke list");
goto out;
}
revoke_list++;
}
} else
hx509_context_set_missing_revoke(context->hx509ctx, 1);
ret = hx509_verify_init_ctx(context->hx509ctx, &id->verify_ctx);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed init verify context");
goto out;
}
hx509_verify_attach_anchors(id->verify_ctx, id->anchors);
hx509_verify_attach_revoke(id->verify_ctx, id->revokectx);
out:
if (ret) {
hx509_verify_destroy_ctx(id->verify_ctx);
hx509_certs_free(&id->certs);
hx509_certs_free(&id->anchors);
hx509_certs_free(&id->certpool);
hx509_revoke_free(&id->revokectx);
free(id);
} else
*ret_id = id;
return ret;
}
/*
*
*/
static void
pk_copy_error(krb5_context context,
hx509_context hx509ctx,
int hxret,
const char *fmt,
...)
{
va_list va;
char *s, *f;
int ret;
va_start(va, fmt);
ret = vasprintf(&f, fmt, va);
va_end(va);
if (ret == -1 || f == NULL) {
krb5_clear_error_message(context);
return;
}
s = hx509_get_error_string(hx509ctx, hxret);
if (s == NULL) {
krb5_clear_error_message(context);
free(f);
return;
}
krb5_set_error_message(context, hxret, "%s: %s", f, s);
free(s);
free(f);
}
static int
parse_integer(krb5_context context, char **p, const char *file, int lineno,
const char *name, heim_integer *integer)
{
int ret;
char *p1;
p1 = strsep(p, " \t");
if (p1 == NULL) {
krb5_set_error_message(context, EINVAL,
N_("moduli file %s missing %s on line %d", ""),
file, name, lineno);
return EINVAL;
}
ret = der_parse_hex_heim_integer(p1, integer);
if (ret) {
krb5_set_error_message(context, ret,
N_("moduli file %s failed parsing %s "
"on line %d", ""),
file, name, lineno);
return ret;
}
return 0;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_parse_moduli_line(krb5_context context,
const char *file,
int lineno,
char *p,
struct krb5_dh_moduli **m)
{
struct krb5_dh_moduli *m1;
char *p1;
int ret;
*m = NULL;
m1 = calloc(1, sizeof(*m1));
if (m1 == NULL)
return krb5_enomem(context);
while (isspace((unsigned char)*p))
p++;
if (*p == '#') {
free(m1);
return 0;
}
ret = EINVAL;
p1 = strsep(&p, " \t");
if (p1 == NULL) {
krb5_set_error_message(context, ret,
N_("moduli file %s missing name on line %d", ""),
file, lineno);
goto out;
}
m1->name = strdup(p1);
if (m1->name == NULL) {
ret = krb5_enomem(context);
goto out;
}
p1 = strsep(&p, " \t");
if (p1 == NULL) {
krb5_set_error_message(context, ret,
N_("moduli file %s missing bits on line %d", ""),
file, lineno);
goto out;
}
m1->bits = atoi(p1);
if (m1->bits == 0) {
krb5_set_error_message(context, ret,
N_("moduli file %s have un-parsable "
"bits on line %d", ""), file, lineno);
goto out;
}
ret = parse_integer(context, &p, file, lineno, "p", &m1->p);
if (ret)
goto out;
ret = parse_integer(context, &p, file, lineno, "g", &m1->g);
if (ret)
goto out;
ret = parse_integer(context, &p, file, lineno, "q", &m1->q);
if (ret)
goto out;
*m = m1;
return 0;
out:
free(m1->name);
der_free_heim_integer(&m1->p);
der_free_heim_integer(&m1->g);
der_free_heim_integer(&m1->q);
free(m1);
return ret;
}
KRB5_LIB_FUNCTION void KRB5_LIB_CALL
_krb5_free_moduli(struct krb5_dh_moduli **moduli)
{
int i;
for (i = 0; moduli[i] != NULL; i++) {
free(moduli[i]->name);
der_free_heim_integer(&moduli[i]->p);
der_free_heim_integer(&moduli[i]->g);
der_free_heim_integer(&moduli[i]->q);
free(moduli[i]);
}
free(moduli);
}
static const char *default_moduli_RFC2412_MODP_group2 =
/* name */
"RFC2412-MODP-group2 "
/* bits */
"1024 "
/* p */
"FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1"
"29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD"
"EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245"
"E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED"
"EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381"
"FFFFFFFF" "FFFFFFFF "
/* g */
"02 "
/* q */
"7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68"
"94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E"
"F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122"
"F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6"
"F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F67329C0"
"FFFFFFFF" "FFFFFFFF";
static const char *default_moduli_rfc3526_MODP_group14 =
/* name */
"rfc3526-MODP-group14 "
/* bits */
"1760 "
/* p */
"FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1"
"29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD"
"EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245"
"E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED"
"EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE45B3D"
"C2007CB8" "A163BF05" "98DA4836" "1C55D39A" "69163FA8" "FD24CF5F"
"83655D23" "DCA3AD96" "1C62F356" "208552BB" "9ED52907" "7096966D"
"670C354E" "4ABC9804" "F1746C08" "CA18217C" "32905E46" "2E36CE3B"
"E39E772C" "180E8603" "9B2783A2" "EC07A28F" "B5C55DF0" "6F4C52C9"
"DE2BCBF6" "95581718" "3995497C" "EA956AE5" "15D22618" "98FA0510"
"15728E5A" "8AACAA68" "FFFFFFFF" "FFFFFFFF "
/* g */
"02 "
/* q */
"7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68"
"94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E"
"F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122"
"F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6"
"F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F6722D9E"
"E1003E5C" "50B1DF82" "CC6D241B" "0E2AE9CD" "348B1FD4" "7E9267AF"
"C1B2AE91" "EE51D6CB" "0E3179AB" "1042A95D" "CF6A9483" "B84B4B36"
"B3861AA7" "255E4C02" "78BA3604" "650C10BE" "19482F23" "171B671D"
"F1CF3B96" "0C074301" "CD93C1D1" "7603D147" "DAE2AEF8" "37A62964"
"EF15E5FB" "4AAC0B8C" "1CCAA4BE" "754AB572" "8AE9130C" "4C7D0288"
"0AB9472D" "45565534" "7FFFFFFF" "FFFFFFFF";
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_parse_moduli(krb5_context context, const char *file,
struct krb5_dh_moduli ***moduli)
{
/* name bits P G Q */
krb5_error_code ret;
struct krb5_dh_moduli **m = NULL, **m2;
char buf[4096];
FILE *f;
int lineno = 0, n = 0;
*moduli = NULL;
m = calloc(1, sizeof(m[0]) * 3);
if (m == NULL)
return krb5_enomem(context);
strlcpy(buf, default_moduli_rfc3526_MODP_group14, sizeof(buf));
ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[0]);
if (ret) {
_krb5_free_moduli(m);
return ret;
}
n++;
strlcpy(buf, default_moduli_RFC2412_MODP_group2, sizeof(buf));
ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[1]);
if (ret) {
_krb5_free_moduli(m);
return ret;
}
n++;
if (file == NULL)
file = MODULI_FILE;
#ifdef KRB5_USE_PATH_TOKENS
{
char * exp_file;
if (_krb5_expand_path_tokens(context, file, 1, &exp_file) == 0) {
f = fopen(exp_file, "r");
krb5_xfree(exp_file);
} else {
f = NULL;
}
}
#else
f = fopen(file, "r");
#endif
if (f == NULL) {
*moduli = m;
return 0;
}
rk_cloexec_file(f);
while(fgets(buf, sizeof(buf), f) != NULL) {
struct krb5_dh_moduli *element;
buf[strcspn(buf, "\n")] = '\0';
lineno++;
m2 = realloc(m, (n + 2) * sizeof(m[0]));
if (m2 == NULL) {
_krb5_free_moduli(m);
return krb5_enomem(context);
}
m = m2;
m[n] = NULL;
ret = _krb5_parse_moduli_line(context, file, lineno, buf, &element);
if (ret) {
_krb5_free_moduli(m);
return ret;
}
if (element == NULL)
continue;
m[n] = element;
m[n + 1] = NULL;
n++;
}
*moduli = m;
return 0;
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
_krb5_dh_group_ok(krb5_context context, unsigned long bits,
heim_integer *p, heim_integer *g, heim_integer *q,
struct krb5_dh_moduli **moduli,
char **name)
{
int i;
if (name)
*name = NULL;
for (i = 0; moduli[i] != NULL; i++) {
if (der_heim_integer_cmp(&moduli[i]->g, g) == 0 &&
der_heim_integer_cmp(&moduli[i]->p, p) == 0 &&
(q == NULL || der_heim_integer_cmp(&moduli[i]->q, q) == 0))
{
if (bits && bits > moduli[i]->bits) {
krb5_set_error_message(context,
KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
N_("PKINIT: DH group parameter %s "
"no accepted, not enough bits "
"generated", ""),
moduli[i]->name);
return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
}
if (name)
*name = strdup(moduli[i]->name);
return 0;
}
}
krb5_set_error_message(context,
KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
N_("PKINIT: DH group parameter no ok", ""));
return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
}
#endif /* PKINIT */
KRB5_LIB_FUNCTION void KRB5_LIB_CALL
_krb5_get_init_creds_opt_free_pkinit(krb5_get_init_creds_opt *opt)
{
#ifdef PKINIT
krb5_pk_init_ctx ctx;
if (opt->opt_private == NULL || opt->opt_private->pk_init_ctx == NULL)
return;
ctx = opt->opt_private->pk_init_ctx;
switch (ctx->keyex) {
case USE_DH:
if (ctx->u.dh)
DH_free(ctx->u.dh);
break;
case USE_RSA:
break;
case USE_ECDH:
if (ctx->u.eckey)
_krb5_pk_eckey_free(ctx->u.eckey);
break;
}
if (ctx->id) {
hx509_verify_destroy_ctx(ctx->id->verify_ctx);
hx509_certs_free(&ctx->id->certs);
hx509_cert_free(ctx->id->cert);
hx509_certs_free(&ctx->id->anchors);
hx509_certs_free(&ctx->id->certpool);
if (ctx->clientDHNonce) {
krb5_free_data(NULL, ctx->clientDHNonce);
ctx->clientDHNonce = NULL;
}
if (ctx->m)
_krb5_free_moduli(ctx->m);
free(ctx->id);
ctx->id = NULL;
}
free(opt->opt_private->pk_init_ctx);
opt->opt_private->pk_init_ctx = NULL;
#endif
}
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_get_init_creds_opt_set_pkinit(krb5_context context,
krb5_get_init_creds_opt *opt,
krb5_principal principal,
const char *user_id,
const char *x509_anchors,
char * const * pool,
char * const * pki_revoke,
int flags,
krb5_prompter_fct prompter,
void *prompter_data,
char *password)
{
#ifdef PKINIT
krb5_error_code ret;
char *anchors = NULL;
if (opt->opt_private == NULL) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: on non extendable opt", ""));
return EINVAL;
}
opt->opt_private->pk_init_ctx =
calloc(1, sizeof(*opt->opt_private->pk_init_ctx));
if (opt->opt_private->pk_init_ctx == NULL)
return krb5_enomem(context);
opt->opt_private->pk_init_ctx->require_binding = 0;
opt->opt_private->pk_init_ctx->require_eku = 1;
opt->opt_private->pk_init_ctx->require_krbtgt_otherName = 1;
opt->opt_private->pk_init_ctx->peer = NULL;
/* XXX implement krb5_appdefault_strings */
if (pool == NULL)
pool = krb5_config_get_strings(context, NULL,
"appdefaults",
"pkinit_pool",
NULL);
if (pki_revoke == NULL)
pki_revoke = krb5_config_get_strings(context, NULL,
"appdefaults",
"pkinit_revoke",
NULL);
if (x509_anchors == NULL) {
krb5_appdefault_string(context, "kinit",
krb5_principal_get_realm(context, principal),
"pkinit_anchors", NULL, &anchors);
x509_anchors = anchors;
}
if (flags & KRB5_GIC_OPT_PKINIT_ANONYMOUS)
opt->opt_private->pk_init_ctx->anonymous = 1;
ret = _krb5_pk_load_id(context,
&opt->opt_private->pk_init_ctx->id,
user_id,
x509_anchors,
pool,
pki_revoke,
prompter,
prompter_data,
password);
if (ret) {
free(opt->opt_private->pk_init_ctx);
opt->opt_private->pk_init_ctx = NULL;
return ret;
}
if (opt->opt_private->pk_init_ctx->id->certs) {
_krb5_pk_set_user_id(context,
principal,
opt->opt_private->pk_init_ctx,
opt->opt_private->pk_init_ctx->id->certs);
} else
opt->opt_private->pk_init_ctx->id->cert = NULL;
if ((flags & KRB5_GIC_OPT_PKINIT_USE_ENCKEY) == 0) {
hx509_context hx509ctx = context->hx509ctx;
hx509_cert cert = opt->opt_private->pk_init_ctx->id->cert;
opt->opt_private->pk_init_ctx->keyex = USE_DH;
/*
* If its a ECDSA certs, lets select ECDSA as the keyex algorithm.
*/
if (cert) {
AlgorithmIdentifier alg;
ret = hx509_cert_get_SPKI_AlgorithmIdentifier(hx509ctx, cert, &alg);
if (ret == 0) {
if (der_heim_oid_cmp(&alg.algorithm, &asn1_oid_id_ecPublicKey) == 0)
opt->opt_private->pk_init_ctx->keyex = USE_ECDH;
free_AlgorithmIdentifier(&alg);
}
}
} else {
opt->opt_private->pk_init_ctx->keyex = USE_RSA;
if (opt->opt_private->pk_init_ctx->id->certs == NULL) {
krb5_set_error_message(context, EINVAL,
N_("No anonymous pkinit support in RSA mode", ""));
return EINVAL;
}
}
return 0;
#else
krb5_set_error_message(context, EINVAL,
N_("no support for PKINIT compiled in", ""));
return EINVAL;
#endif
}
krb5_error_code KRB5_LIB_FUNCTION
krb5_get_init_creds_opt_set_pkinit_user_certs(krb5_context context,
krb5_get_init_creds_opt *opt,
struct hx509_certs_data *certs)
{
#ifdef PKINIT
if (opt->opt_private == NULL) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: on non extendable opt", ""));
return EINVAL;
}
if (opt->opt_private->pk_init_ctx == NULL) {
krb5_set_error_message(context, EINVAL,
N_("PKINIT: on pkinit context", ""));
return EINVAL;
}
_krb5_pk_set_user_id(context, NULL, opt->opt_private->pk_init_ctx, certs);
return 0;
#else
krb5_set_error_message(context, EINVAL,
N_("no support for PKINIT compiled in", ""));
return EINVAL;
#endif
}
#ifdef PKINIT
static int
get_ms_san(hx509_context context, hx509_cert cert, char **upn)
{
hx509_octet_string_list list;
int ret;
*upn = NULL;
ret = hx509_cert_find_subjectAltName_otherName(context,
cert,
&asn1_oid_id_pkinit_ms_san,
&list);
if (ret)
return 0;
if (list.len > 0 && list.val[0].length > 0)
ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length,
upn, NULL);
else
ret = 1;
hx509_free_octet_string_list(&list);
return ret;
}
static int
find_ms_san(hx509_context context, hx509_cert cert, void *ctx)
{
char *upn;
int ret;
ret = get_ms_san(context, cert, &upn);
if (ret == 0)
free(upn);
return ret;
}
#endif
/*
* Private since it need to be redesigned using krb5_get_init_creds()
*/
KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
krb5_pk_enterprise_cert(krb5_context context,
const char *user_id,
krb5_const_realm realm,
krb5_principal *principal,
struct hx509_certs_data **res)
{
#ifdef PKINIT
krb5_error_code ret;
hx509_certs certs, result;
hx509_cert cert = NULL;
hx509_query *q;
char *name;
*principal = NULL;
if (res)
*res = NULL;
if (user_id == NULL) {
krb5_set_error_message(context, ENOENT, "no user id");
return ENOENT;
}
ret = hx509_certs_init(context->hx509ctx, user_id, 0, NULL, &certs);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to init cert certs");
goto out;
}
ret = hx509_query_alloc(context->hx509ctx, &q);
if (ret) {
krb5_set_error_message(context, ret, "out of memory");
hx509_certs_free(&certs);
goto out;
}
hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
hx509_query_match_eku(q, &asn1_oid_id_pkinit_ms_eku);
hx509_query_match_cmp_func(q, find_ms_san, NULL);
ret = hx509_certs_filter(context->hx509ctx, certs, q, &result);
hx509_query_free(context->hx509ctx, q);
hx509_certs_free(&certs);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to find PKINIT certificate");
return ret;
}
ret = hx509_get_one_cert(context->hx509ctx, result, &cert);
hx509_certs_free(&result);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to get one cert");
goto out;
}
ret = get_ms_san(context->hx509ctx, cert, &name);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Failed to get MS SAN");
goto out;
}
ret = krb5_make_principal(context, principal, realm, name, NULL);
free(name);
if (ret)
goto out;
krb5_principal_set_type(context, *principal, KRB5_NT_ENTERPRISE_PRINCIPAL);
if (res) {
ret = hx509_certs_init(context->hx509ctx, "MEMORY:", 0, NULL, res);
if (ret)
goto out;
ret = hx509_certs_add(context->hx509ctx, *res, cert);
if (ret) {
hx509_certs_free(res);
goto out;
}
}
out:
hx509_cert_free(cert);
return ret;
#else
krb5_set_error_message(context, EINVAL,
N_("no support for PKINIT compiled in", ""));
return EINVAL;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-320/c/bad_857_2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.